file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
socket.rs
kernel /// let n_sent = socket.send_to(&pkt[..], &kernel_addr, 0).unwrap(); /// assert_eq!(n_sent, pkt.len()); /// // buffer for receiving the response /// let mut buf = vec![0; 4096]; /// loop { /// // receive a datagram /// let (n_received, sender_addr) = socket.recv_from(&mut &mut buf[..], 0).unwrap(); /// assert_eq!(sender_addr, kernel_addr); /// println!("received datagram {:?}", &buf[..n_received]); /// if buf[4] == 2 && buf[5] == 0 { /// println!("the kernel responded with an error"); /// return; /// } /// if buf[4] == 3 && buf[5] == 0 { /// println!("end of dump"); /// return; /// } /// } /// ``` #[derive(Clone, Debug)] pub struct Socket(RawFd); impl AsRawFd for Socket { fn as_raw_fd(&self) -> RawFd { self.0 } } impl FromRawFd for Socket { unsafe fn from_raw_fd(fd: RawFd) -> Self { Socket(fd) } } impl Drop for Socket { fn drop(&mut self) { unsafe { libc::close(self.0) }; } } impl Socket { /// Open a new socket for the given netlink subsystem. `protocol` must be one of the /// [`netlink_sys::protocols`][protos] constants. /// /// [protos]: crate::protocols pub fn new(protocol: isize) -> Result<Self> { let res = unsafe { libc::socket( libc::PF_NETLINK, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, protocol as libc::c_int, ) }; if res < 0 { return Err(Error::last_os_error()); } Ok(Socket(res)) } /// Bind the socket to the given address pub fn bind(&mut self, addr: &SocketAddr) -> Result<()> { let (addr_ptr, addr_len) = addr.as_raw(); let res = unsafe { libc::bind(self.0, addr_ptr, addr_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } /// Bind the socket to an address assigned by the kernel, and return that address. pub fn bind_auto(&mut self) -> Result<SocketAddr> { let mut addr = SocketAddr::new(0, 0); self.bind(&addr)?; self.get_address(&mut addr)?; Ok(addr) } /// Get the socket address pub fn get_address(&self, addr: &mut SocketAddr) -> Result<()> { let (addr_ptr, mut addr_len) = addr.as_raw_mut(); let addr_len_copy = addr_len; let addr_len_ptr = &mut addr_len as *mut libc::socklen_t; let res = unsafe { libc::getsockname(self.0, addr_ptr, addr_len_ptr) }; if res < 0 { return Err(Error::last_os_error()); } assert_eq!(addr_len, addr_len_copy); Ok(()) } // when building with --features smol we don't need this #[allow(dead_code)] /// Make this socket non-blocking pub fn
(&self, non_blocking: bool) -> Result<()> { let mut non_blocking = non_blocking as libc::c_int; let res = unsafe { libc::ioctl(self.0, libc::FIONBIO, &mut non_blocking) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } /// Connect the socket to the given address. Netlink is a connection-less protocol, so a socket can communicate with /// multiple peers with the [`Socket::send_to`] and [`Socket::recv_from`] methods. However, if the socket only needs /// to communicate with one peer, it is convenient not to have to bother with the peer address. This is what /// `connect` is for. After calling `connect`, [`Socket::send`] and [`Socket::recv`] respectively send and receive /// datagrams to and from `remote_addr`. /// /// # Examples /// /// In this example we: /// /// 1. open a socket /// 2. connect it to the kernel with [`Socket::connect`] /// 3. send a request to the kernel with [`Socket::send`] /// 4. read the response (which can span over several messages) [`Socket::recv`] /// /// ```rust /// use netlink_sys::{protocols::NETLINK_ROUTE, Socket, SocketAddr}; /// use std::process; /// /// let mut socket = Socket::new(NETLINK_ROUTE).unwrap(); /// let _ = socket.bind_auto().unwrap(); /// let kernel_addr = SocketAddr::new(0, 0); /// socket.connect(&kernel_addr).unwrap(); /// // This is a valid message for listing the network links on the system /// let msg = vec![ /// 0x14, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, 0x03, 0xfd, 0xfe, 0x38, 0x5c, 0x00, 0x00, 0x00, /// 0x00, 0x00, 0x00, 0x00, 0x00, /// ]; /// let n_sent = socket.send(&msg[..], 0).unwrap(); /// assert_eq!(n_sent, msg.len()); /// // buffer for receiving the response /// let mut buf = vec![0; 4096]; /// loop { /// let mut n_received = socket.recv(&mut &mut buf[..], 0).unwrap(); /// println!("received {:?}", &buf[..n_received]); /// if buf[4] == 2 && buf[5] == 0 { /// println!("the kernel responded with an error"); /// return; /// } /// if buf[4] == 3 && buf[5] == 0 { /// println!("end of dump"); /// return; /// } /// } /// ``` pub fn connect(&self, remote_addr: &SocketAddr) -> Result<()> { // FIXME: // // Event though for SOCK_DGRAM sockets there's no IO, if our socket is non-blocking, // connect() might return EINPROGRESS. In theory, the right way to treat EINPROGRESS would // be to ignore the error, and let the user poll the socket to check when it becomes // writable, indicating that the connection succeeded. The code already exists in mio for // TcpStream: // // > pub fn connect(stream: net::TcpStream, addr: &SocketAddr) -> io::Result<TcpStream> { // > set_non_block(stream.as_raw_fd())?; // > match stream.connect(addr) { // > Ok(..) => {} // > Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {} // > Err(e) => return Err(e), // > } // > Ok(TcpStream { inner: stream }) // > } // // In practice, since the connection does not require any IO for SOCK_DGRAM sockets, it // almost never returns EINPROGRESS and so for now, we just return whatever libc::connect // returns. If it returns EINPROGRESS, the caller will have to handle the error themself // // Refs: // // - https://stackoverflow.com/a/14046386/1836144 // - https://lists.isc.org/pipermail/bind-users/2009-August/077527.html let (addr, addr_len) = remote_addr.as_raw(); let res = unsafe { libc::connect(self.0, addr, addr_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } // Most of the comments in this method come from a discussion on rust users forum. // [thread]: https://users.rust-lang.org/t/help-understanding-libc-call/17308/9 // /// Read a datagram from the socket and return the number of bytes that have been read and the address of the /// sender. The data being read is copied into `buf`. If `buf` is too small, the datagram is truncated. The /// supported flags are the `MSG_*` described in `man 2 recvmsg` /// /// # Warning /// /// In datagram oriented protocols, `recv` and `recvfrom` receive normally only ONE datagram, but this seems not to /// be always true for netlink sockets: with some protocols like `NETLINK_AUDIT`, multiple netlink packets can be /// read with a single call. pub fn recv_from<B>(&self, buf: &mut B, flags: libc::c_int) -> Result<(usize, SocketAddr)> where B: bytes::BufMut, { // Create an empty storage for the address. Note that Rust standard library create a // sockaddr_storage so that it works for any address family, but here, we already know that // we'll have a Netlink address, so we can create the appropriate storage. let mut addr = unsafe { mem::zeroed::<libc::sockaddr_nl>() }; // recvfrom takes a *sockaddr as parameter so that it can accept any kind of address // storage, so we need to create such a pointer for the sockaddr_nl we just initialized. // // Create a raw pointer to Cast our raw pointer to a // our storage. We cannot generic pointer to *sockaddr // pass it to recvfrom yet. that recvfrom can use // ^ ^ // | | // +--------------+---------------+ +---------+--------+ // / \ / \ let addr_ptr = &mut addr as *mut libc::sockaddr_nl as *mut libc::sockaddr; // Why do we need to pass the address length? We're passing a generic *sockaddr to // recvfrom. Somehow recvfrom needs to make sure that the address of the received packet // would fit into the actual type that is behind *sockaddr: it could be a sockaddr_nl but // also a sockaddr_in, a sockaddr_in6, or even the generic sockaddr_storage that can store // any address. let mut addrlen = mem::size_of_val(&addr); // recvfrom does not take the address length by value (see [thread]), so we need to create // a pointer to it. let addrlen_ptr = &mut addrlen as *mut usize as *mut libc::socklen_t; let chunk = buf.chunk_mut(); // Cast the *mut u8 into *mut void. // This is equivalent to casting a *char into *void // See [thread] // ^ // Create a *mut u8 | // ^ | // | | // +------+-------+ +--------+-------+ // / \ / \ let buf_ptr = chunk.as_mut_ptr() as *mut libc::c_void; let buf_len = chunk.len() as libc::size_t; let res = unsafe { libc::recvfrom(self.0, buf_ptr, buf_len, flags, addr_ptr, addrlen_ptr) }; if res < 0 { return Err(Error::last_os_error()); } else { // with `MSG_TRUNC` `res` might exceed `buf_len` let written = std::cmp::min(buf_len, res as usize); unsafe { buf.advance_mut(written); } } Ok((res as usize, SocketAddr(addr))) } /// For a connected socket, `recv` reads a datagram from the socket. The sender is the remote peer the socket is /// connected to (see [`Socket::connect`]). See also [`Socket::recv_from`] pub fn recv<B>(&self, buf: &mut B, flags: libc::c_int) -> Result<usize> where B: bytes::BufMut, { let chunk = buf.chunk_mut(); let buf_ptr = chunk.as_mut_ptr() as *mut libc::c_void; let buf_len = chunk.len() as libc::size_t; let res = unsafe { libc::recv(self.0, buf_ptr, buf_len, flags) }; if res < 0 { return Err(Error::last_os_error()); } else { // with `MSG_TRUNC` `res` might exceed `buf_len` let written = std::cmp::min(buf_len, res as usize); unsafe { buf.advance_mut(written); } } Ok(res as usize) } /// Receive a full message. Unlike [`Socket::recv_from`], which truncates messages that exceed the length of the /// buffer passed as argument, this method always reads a whole message, no matter its size. pub fn recv_from_full(&self) -> Result<(Vec<u8>, SocketAddr)> { // Peek let mut buf: Vec<u8> = Vec::new(); let (peek_len, _) = self.recv_from(&mut buf, libc::MSG_PEEK | libc::MSG_TRUNC)?; // Receive buf.clear(); buf.reserve(peek_len); let (rlen, addr) = self.recv_from(&mut buf, 0)?; assert_eq!(rlen, peek_len); Ok((buf, addr)) } /// Send the given buffer `buf` to the remote peer with address `addr`. The supported flags are the `MSG_*` values /// documented in `man 2 send`. pub fn send_to(&self, buf: &[u8], addr: &SocketAddr, flags: libc::c_int) -> Result<usize> { let (addr_ptr, addr_len) = addr.as_raw(); let buf_ptr = buf.as_ptr() as *const libc::c_void; let buf_len = buf.len() as libc::size_t; let res = unsafe { libc::sendto(self.0, buf_ptr, buf_len, flags, addr_ptr, addr_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(res as usize) } /// For a connected socket, `send` sends the given buffer `buf` to the remote peer the socket is connected to. See /// also [`Socket::connect`] and [`Socket::send_to`]. pub fn send(&self, buf: &[u8], flags: libc::c_int) -> Result<usize> { let buf_ptr = buf.as_ptr() as *const libc::c_void; let buf_len = buf.len() as libc::size_t; let res = unsafe { libc::send(self.0, buf_ptr, buf_len, flags) }; if res < 0 { return Err(Error::last_os_error()); } Ok(res as usize) } pub fn set_pktinfo(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_PKTINFO, value) } pub fn get_pktinfo(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_PKTINFO)?; Ok(res == 1) } pub fn add_membership(&mut self, group: u32) -> Result<()> { setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_ADD_MEMBERSHIP, group, ) } pub fn drop_membership(&mut self, group: u32) -> Result<()> { setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_DROP_MEMBERSHIP, group, ) } // pub fn list_membership(&self) -> Vec<u32> { // unimplemented!(); // // getsockopt won't be enough here, because we may need to perform 2 calls, and because the // // length of the list returned by libc::getsockopt is returned by mutating the length // // argument, which our implementation of getsockopt forbids. // } /// `NETLINK_BROADCAST_ERROR` (since Linux 2.6.30). When not set, `netlink_broadcast()` only /// reports `ESRCH` errors and silently ignore `NOBUFS` errors. pub fn set_broadcast_error(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_BROADCAST_ERROR, value, ) } pub fn get_broadcast_error(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_BROADCAST_ERROR)?; Ok(res == 1) } /// `NETLINK_NO_ENOBUFS` (since Linux 2.6.30). This flag can be used by unicast and broadcast /// listeners to avoid receiving `ENOBUFS` errors. pub fn set_no_enobufs(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_NO_ENOBUFS, value) } pub fn get_no_enobufs(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_NO_ENOBUFS)?; Ok(res == 1) } /// `NETLINK_LISTEN_ALL_NSID` (since Linux 4.2). When set, this socket will receive netlink /// notifications from all network namespaces that have an nsid assigned into the network /// namespace where the socket has been opened. The nsid is sent to user space via an ancillary /// data. pub fn set_listen_all_namespaces(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_LISTEN_ALL_NSID, value, ) } pub fn get_listen_all_namespaces(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_LISTEN_ALL_NSID)?; Ok(res == 1) } /// `NETLINK_CAP_ACK` (since Linux 4.2). The kernel may fail to allocate the necessary room /// for the acknowledgment message back to user space. This option trims off the payload of /// the original netlink message. The netlink message header is still included, so the user can /// guess from the sequence number which message triggered the acknowledgment. pub fn set_cap_ack(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_CAP_ACK, value) } pub fn get_cap_ack(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_CAP_ACK)?; Ok(res == 1) } } /// Wrapper around `getsockopt`: /// /// ```no_rust /// int getsockopt(int socket, int level, int option_name, void *restrict option_value, socklen_t *restrict option_len); /// ``` pub(crate) fn getsockopt<T: Copy>(fd: RawFd, level: libc::c_int, option: libc::c_int) -> Result<T> { // Create storage for the options we're fetching let mut slot: T = unsafe { mem::zeroed() }; // Create a mutable raw pointer to the storage so that getsockopt can fill the value let slot_ptr = &mut slot as *mut T as *mut libc::c_void; // Let getsockopt know how big our storage is let mut slot_len = mem::size_of::<T>() as libc::socklen_t; // getsockopt takes a mutable pointer to the length, because for some options like // NETLINK_LIST_MEMBERSHIP where the option value is a list with arbitrary length, // getsockopt uses this parameter to signal how big the storage needs to be. let slot_len_ptr = &mut slot_len as *mut libc::socklen_t; let res = unsafe { libc::getsockopt(fd, level, option, slot_ptr, slot_len_ptr) }; if res < 0 { return Err(Error::last_os_error()); } // Ignore the options that require the legnth to be set by getsockopt. // We'll deal with them individually. assert_eq!(slot_len as usize, mem::size_of::<T>()); Ok(slot) } // adapted from rust standard library fn setsockopt<T>(fd: RawFd, level: libc::c_int, option: libc::c_int, payload: T) -> Result<()> { let payload = &payload as *const T as *const libc::c_void; let payload_len = mem::size_of::<T>() as libc::socklen_t; let res = unsafe { libc::setsockopt(fd, level, option, payload, payload_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } #[cfg(test)] mod
set_non_blocking
identifier_name
socket.rs
the kernel /// let n_sent = socket.send_to(&pkt[..], &kernel_addr, 0).unwrap(); /// assert_eq!(n_sent, pkt.len()); /// // buffer for receiving the response /// let mut buf = vec![0; 4096]; /// loop { /// // receive a datagram /// let (n_received, sender_addr) = socket.recv_from(&mut &mut buf[..], 0).unwrap(); /// assert_eq!(sender_addr, kernel_addr); /// println!("received datagram {:?}", &buf[..n_received]); /// if buf[4] == 2 && buf[5] == 0 { /// println!("the kernel responded with an error"); /// return; /// } /// if buf[4] == 3 && buf[5] == 0 { /// println!("end of dump"); /// return; /// } /// } /// ``` #[derive(Clone, Debug)] pub struct Socket(RawFd); impl AsRawFd for Socket { fn as_raw_fd(&self) -> RawFd { self.0 } } impl FromRawFd for Socket { unsafe fn from_raw_fd(fd: RawFd) -> Self { Socket(fd) } } impl Drop for Socket { fn drop(&mut self) { unsafe { libc::close(self.0) }; } } impl Socket { /// Open a new socket for the given netlink subsystem. `protocol` must be one of the /// [`netlink_sys::protocols`][protos] constants. /// /// [protos]: crate::protocols pub fn new(protocol: isize) -> Result<Self> { let res = unsafe { libc::socket( libc::PF_NETLINK, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, protocol as libc::c_int, ) }; if res < 0 { return Err(Error::last_os_error()); } Ok(Socket(res)) } /// Bind the socket to the given address pub fn bind(&mut self, addr: &SocketAddr) -> Result<()> { let (addr_ptr, addr_len) = addr.as_raw(); let res = unsafe { libc::bind(self.0, addr_ptr, addr_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } /// Bind the socket to an address assigned by the kernel, and return that address. pub fn bind_auto(&mut self) -> Result<SocketAddr> { let mut addr = SocketAddr::new(0, 0); self.bind(&addr)?; self.get_address(&mut addr)?; Ok(addr) } /// Get the socket address pub fn get_address(&self, addr: &mut SocketAddr) -> Result<()> { let (addr_ptr, mut addr_len) = addr.as_raw_mut(); let addr_len_copy = addr_len; let addr_len_ptr = &mut addr_len as *mut libc::socklen_t; let res = unsafe { libc::getsockname(self.0, addr_ptr, addr_len_ptr) }; if res < 0 { return Err(Error::last_os_error()); } assert_eq!(addr_len, addr_len_copy); Ok(()) } // when building with --features smol we don't need this #[allow(dead_code)] /// Make this socket non-blocking pub fn set_non_blocking(&self, non_blocking: bool) -> Result<()> { let mut non_blocking = non_blocking as libc::c_int; let res = unsafe { libc::ioctl(self.0, libc::FIONBIO, &mut non_blocking) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } /// Connect the socket to the given address. Netlink is a connection-less protocol, so a socket can communicate with /// multiple peers with the [`Socket::send_to`] and [`Socket::recv_from`] methods. However, if the socket only needs /// to communicate with one peer, it is convenient not to have to bother with the peer address. This is what /// `connect` is for. After calling `connect`, [`Socket::send`] and [`Socket::recv`] respectively send and receive /// datagrams to and from `remote_addr`. /// /// # Examples /// /// In this example we: /// /// 1. open a socket /// 2. connect it to the kernel with [`Socket::connect`] /// 3. send a request to the kernel with [`Socket::send`] /// 4. read the response (which can span over several messages) [`Socket::recv`] /// /// ```rust /// use netlink_sys::{protocols::NETLINK_ROUTE, Socket, SocketAddr}; /// use std::process; /// /// let mut socket = Socket::new(NETLINK_ROUTE).unwrap(); /// let _ = socket.bind_auto().unwrap(); /// let kernel_addr = SocketAddr::new(0, 0); /// socket.connect(&kernel_addr).unwrap(); /// // This is a valid message for listing the network links on the system /// let msg = vec![ /// 0x14, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, 0x03, 0xfd, 0xfe, 0x38, 0x5c, 0x00, 0x00, 0x00, /// 0x00, 0x00, 0x00, 0x00, 0x00, /// ]; /// let n_sent = socket.send(&msg[..], 0).unwrap(); /// assert_eq!(n_sent, msg.len()); /// // buffer for receiving the response /// let mut buf = vec![0; 4096]; /// loop { /// let mut n_received = socket.recv(&mut &mut buf[..], 0).unwrap(); /// println!("received {:?}", &buf[..n_received]); /// if buf[4] == 2 && buf[5] == 0 { /// println!("the kernel responded with an error"); /// return; /// } /// if buf[4] == 3 && buf[5] == 0 { /// println!("end of dump"); /// return; /// } /// } /// ``` pub fn connect(&self, remote_addr: &SocketAddr) -> Result<()> { // FIXME: // // Event though for SOCK_DGRAM sockets there's no IO, if our socket is non-blocking, // connect() might return EINPROGRESS. In theory, the right way to treat EINPROGRESS would // be to ignore the error, and let the user poll the socket to check when it becomes // writable, indicating that the connection succeeded. The code already exists in mio for // TcpStream: // // > pub fn connect(stream: net::TcpStream, addr: &SocketAddr) -> io::Result<TcpStream> { // > set_non_block(stream.as_raw_fd())?; // > match stream.connect(addr) { // > Ok(..) => {} // > Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {} // > Err(e) => return Err(e), // > } // > Ok(TcpStream { inner: stream }) // > } // // In practice, since the connection does not require any IO for SOCK_DGRAM sockets, it // almost never returns EINPROGRESS and so for now, we just return whatever libc::connect // returns. If it returns EINPROGRESS, the caller will have to handle the error themself // // Refs: // // - https://stackoverflow.com/a/14046386/1836144 // - https://lists.isc.org/pipermail/bind-users/2009-August/077527.html let (addr, addr_len) = remote_addr.as_raw(); let res = unsafe { libc::connect(self.0, addr, addr_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } // Most of the comments in this method come from a discussion on rust users forum. // [thread]: https://users.rust-lang.org/t/help-understanding-libc-call/17308/9 // /// Read a datagram from the socket and return the number of bytes that have been read and the address of the /// sender. The data being read is copied into `buf`. If `buf` is too small, the datagram is truncated. The /// supported flags are the `MSG_*` described in `man 2 recvmsg` /// /// # Warning /// /// In datagram oriented protocols, `recv` and `recvfrom` receive normally only ONE datagram, but this seems not to /// be always true for netlink sockets: with some protocols like `NETLINK_AUDIT`, multiple netlink packets can be /// read with a single call. pub fn recv_from<B>(&self, buf: &mut B, flags: libc::c_int) -> Result<(usize, SocketAddr)> where B: bytes::BufMut, { // Create an empty storage for the address. Note that Rust standard library create a // sockaddr_storage so that it works for any address family, but here, we already know that // we'll have a Netlink address, so we can create the appropriate storage. let mut addr = unsafe { mem::zeroed::<libc::sockaddr_nl>() }; // recvfrom takes a *sockaddr as parameter so that it can accept any kind of address // storage, so we need to create such a pointer for the sockaddr_nl we just initialized. // // Create a raw pointer to Cast our raw pointer to a // our storage. We cannot generic pointer to *sockaddr // pass it to recvfrom yet. that recvfrom can use // ^ ^ // | | // +--------------+---------------+ +---------+--------+ // / \ / \ let addr_ptr = &mut addr as *mut libc::sockaddr_nl as *mut libc::sockaddr; // Why do we need to pass the address length? We're passing a generic *sockaddr to // recvfrom. Somehow recvfrom needs to make sure that the address of the received packet // would fit into the actual type that is behind *sockaddr: it could be a sockaddr_nl but
// a pointer to it. let addrlen_ptr = &mut addrlen as *mut usize as *mut libc::socklen_t; let chunk = buf.chunk_mut(); // Cast the *mut u8 into *mut void. // This is equivalent to casting a *char into *void // See [thread] // ^ // Create a *mut u8 | // ^ | // | | // +------+-------+ +--------+-------+ // / \ / \ let buf_ptr = chunk.as_mut_ptr() as *mut libc::c_void; let buf_len = chunk.len() as libc::size_t; let res = unsafe { libc::recvfrom(self.0, buf_ptr, buf_len, flags, addr_ptr, addrlen_ptr) }; if res < 0 { return Err(Error::last_os_error()); } else { // with `MSG_TRUNC` `res` might exceed `buf_len` let written = std::cmp::min(buf_len, res as usize); unsafe { buf.advance_mut(written); } } Ok((res as usize, SocketAddr(addr))) } /// For a connected socket, `recv` reads a datagram from the socket. The sender is the remote peer the socket is /// connected to (see [`Socket::connect`]). See also [`Socket::recv_from`] pub fn recv<B>(&self, buf: &mut B, flags: libc::c_int) -> Result<usize> where B: bytes::BufMut, { let chunk = buf.chunk_mut(); let buf_ptr = chunk.as_mut_ptr() as *mut libc::c_void; let buf_len = chunk.len() as libc::size_t; let res = unsafe { libc::recv(self.0, buf_ptr, buf_len, flags) }; if res < 0 { return Err(Error::last_os_error()); } else { // with `MSG_TRUNC` `res` might exceed `buf_len` let written = std::cmp::min(buf_len, res as usize); unsafe { buf.advance_mut(written); } } Ok(res as usize) } /// Receive a full message. Unlike [`Socket::recv_from`], which truncates messages that exceed the length of the /// buffer passed as argument, this method always reads a whole message, no matter its size. pub fn recv_from_full(&self) -> Result<(Vec<u8>, SocketAddr)> { // Peek let mut buf: Vec<u8> = Vec::new(); let (peek_len, _) = self.recv_from(&mut buf, libc::MSG_PEEK | libc::MSG_TRUNC)?; // Receive buf.clear(); buf.reserve(peek_len); let (rlen, addr) = self.recv_from(&mut buf, 0)?; assert_eq!(rlen, peek_len); Ok((buf, addr)) } /// Send the given buffer `buf` to the remote peer with address `addr`. The supported flags are the `MSG_*` values /// documented in `man 2 send`. pub fn send_to(&self, buf: &[u8], addr: &SocketAddr, flags: libc::c_int) -> Result<usize> { let (addr_ptr, addr_len) = addr.as_raw(); let buf_ptr = buf.as_ptr() as *const libc::c_void; let buf_len = buf.len() as libc::size_t; let res = unsafe { libc::sendto(self.0, buf_ptr, buf_len, flags, addr_ptr, addr_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(res as usize) } /// For a connected socket, `send` sends the given buffer `buf` to the remote peer the socket is connected to. See /// also [`Socket::connect`] and [`Socket::send_to`]. pub fn send(&self, buf: &[u8], flags: libc::c_int) -> Result<usize> { let buf_ptr = buf.as_ptr() as *const libc::c_void; let buf_len = buf.len() as libc::size_t; let res = unsafe { libc::send(self.0, buf_ptr, buf_len, flags) }; if res < 0 { return Err(Error::last_os_error()); } Ok(res as usize) } pub fn set_pktinfo(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_PKTINFO, value) } pub fn get_pktinfo(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_PKTINFO)?; Ok(res == 1) } pub fn add_membership(&mut self, group: u32) -> Result<()> { setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_ADD_MEMBERSHIP, group, ) } pub fn drop_membership(&mut self, group: u32) -> Result<()> { setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_DROP_MEMBERSHIP, group, ) } // pub fn list_membership(&self) -> Vec<u32> { // unimplemented!(); // // getsockopt won't be enough here, because we may need to perform 2 calls, and because the // // length of the list returned by libc::getsockopt is returned by mutating the length // // argument, which our implementation of getsockopt forbids. // } /// `NETLINK_BROADCAST_ERROR` (since Linux 2.6.30). When not set, `netlink_broadcast()` only /// reports `ESRCH` errors and silently ignore `NOBUFS` errors. pub fn set_broadcast_error(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_BROADCAST_ERROR, value, ) } pub fn get_broadcast_error(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_BROADCAST_ERROR)?; Ok(res == 1) } /// `NETLINK_NO_ENOBUFS` (since Linux 2.6.30). This flag can be used by unicast and broadcast /// listeners to avoid receiving `ENOBUFS` errors. pub fn set_no_enobufs(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_NO_ENOBUFS, value) } pub fn get_no_enobufs(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_NO_ENOBUFS)?; Ok(res == 1) } /// `NETLINK_LISTEN_ALL_NSID` (since Linux 4.2). When set, this socket will receive netlink /// notifications from all network namespaces that have an nsid assigned into the network /// namespace where the socket has been opened. The nsid is sent to user space via an ancillary /// data. pub fn set_listen_all_namespaces(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_LISTEN_ALL_NSID, value, ) } pub fn get_listen_all_namespaces(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_LISTEN_ALL_NSID)?; Ok(res == 1) } /// `NETLINK_CAP_ACK` (since Linux 4.2). The kernel may fail to allocate the necessary room /// for the acknowledgment message back to user space. This option trims off the payload of /// the original netlink message. The netlink message header is still included, so the user can /// guess from the sequence number which message triggered the acknowledgment. pub fn set_cap_ack(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_CAP_ACK, value) } pub fn get_cap_ack(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_CAP_ACK)?; Ok(res == 1) } } /// Wrapper around `getsockopt`: /// /// ```no_rust /// int getsockopt(int socket, int level, int option_name, void *restrict option_value, socklen_t *restrict option_len); /// ``` pub(crate) fn getsockopt<T: Copy>(fd: RawFd, level: libc::c_int, option: libc::c_int) -> Result<T> { // Create storage for the options we're fetching let mut slot: T = unsafe { mem::zeroed() }; // Create a mutable raw pointer to the storage so that getsockopt can fill the value let slot_ptr = &mut slot as *mut T as *mut libc::c_void; // Let getsockopt know how big our storage is let mut slot_len = mem::size_of::<T>() as libc::socklen_t; // getsockopt takes a mutable pointer to the length, because for some options like // NETLINK_LIST_MEMBERSHIP where the option value is a list with arbitrary length, // getsockopt uses this parameter to signal how big the storage needs to be. let slot_len_ptr = &mut slot_len as *mut libc::socklen_t; let res = unsafe { libc::getsockopt(fd, level, option, slot_ptr, slot_len_ptr) }; if res < 0 { return Err(Error::last_os_error()); } // Ignore the options that require the legnth to be set by getsockopt. // We'll deal with them individually. assert_eq!(slot_len as usize, mem::size_of::<T>()); Ok(slot) } // adapted from rust standard library fn setsockopt<T>(fd: RawFd, level: libc::c_int, option: libc::c_int, payload: T) -> Result<()> { let payload = &payload as *const T as *const libc::c_void; let payload_len = mem::size_of::<T>() as libc::socklen_t; let res = unsafe { libc::setsockopt(fd, level, option, payload, payload_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } #[cfg(test)] mod t
// also a sockaddr_in, a sockaddr_in6, or even the generic sockaddr_storage that can store // any address. let mut addrlen = mem::size_of_val(&addr); // recvfrom does not take the address length by value (see [thread]), so we need to create
random_line_split
socket.rs
kernel /// let n_sent = socket.send_to(&pkt[..], &kernel_addr, 0).unwrap(); /// assert_eq!(n_sent, pkt.len()); /// // buffer for receiving the response /// let mut buf = vec![0; 4096]; /// loop { /// // receive a datagram /// let (n_received, sender_addr) = socket.recv_from(&mut &mut buf[..], 0).unwrap(); /// assert_eq!(sender_addr, kernel_addr); /// println!("received datagram {:?}", &buf[..n_received]); /// if buf[4] == 2 && buf[5] == 0 { /// println!("the kernel responded with an error"); /// return; /// } /// if buf[4] == 3 && buf[5] == 0 { /// println!("end of dump"); /// return; /// } /// } /// ``` #[derive(Clone, Debug)] pub struct Socket(RawFd); impl AsRawFd for Socket { fn as_raw_fd(&self) -> RawFd { self.0 } } impl FromRawFd for Socket { unsafe fn from_raw_fd(fd: RawFd) -> Self { Socket(fd) } } impl Drop for Socket { fn drop(&mut self) { unsafe { libc::close(self.0) }; } } impl Socket { /// Open a new socket for the given netlink subsystem. `protocol` must be one of the /// [`netlink_sys::protocols`][protos] constants. /// /// [protos]: crate::protocols pub fn new(protocol: isize) -> Result<Self> { let res = unsafe { libc::socket( libc::PF_NETLINK, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, protocol as libc::c_int, ) }; if res < 0 { return Err(Error::last_os_error()); } Ok(Socket(res)) } /// Bind the socket to the given address pub fn bind(&mut self, addr: &SocketAddr) -> Result<()> { let (addr_ptr, addr_len) = addr.as_raw(); let res = unsafe { libc::bind(self.0, addr_ptr, addr_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } /// Bind the socket to an address assigned by the kernel, and return that address. pub fn bind_auto(&mut self) -> Result<SocketAddr> { let mut addr = SocketAddr::new(0, 0); self.bind(&addr)?; self.get_address(&mut addr)?; Ok(addr) } /// Get the socket address pub fn get_address(&self, addr: &mut SocketAddr) -> Result<()> { let (addr_ptr, mut addr_len) = addr.as_raw_mut(); let addr_len_copy = addr_len; let addr_len_ptr = &mut addr_len as *mut libc::socklen_t; let res = unsafe { libc::getsockname(self.0, addr_ptr, addr_len_ptr) }; if res < 0 { return Err(Error::last_os_error()); } assert_eq!(addr_len, addr_len_copy); Ok(()) } // when building with --features smol we don't need this #[allow(dead_code)] /// Make this socket non-blocking pub fn set_non_blocking(&self, non_blocking: bool) -> Result<()> { let mut non_blocking = non_blocking as libc::c_int; let res = unsafe { libc::ioctl(self.0, libc::FIONBIO, &mut non_blocking) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } /// Connect the socket to the given address. Netlink is a connection-less protocol, so a socket can communicate with /// multiple peers with the [`Socket::send_to`] and [`Socket::recv_from`] methods. However, if the socket only needs /// to communicate with one peer, it is convenient not to have to bother with the peer address. This is what /// `connect` is for. After calling `connect`, [`Socket::send`] and [`Socket::recv`] respectively send and receive /// datagrams to and from `remote_addr`. /// /// # Examples /// /// In this example we: /// /// 1. open a socket /// 2. connect it to the kernel with [`Socket::connect`] /// 3. send a request to the kernel with [`Socket::send`] /// 4. read the response (which can span over several messages) [`Socket::recv`] /// /// ```rust /// use netlink_sys::{protocols::NETLINK_ROUTE, Socket, SocketAddr}; /// use std::process; /// /// let mut socket = Socket::new(NETLINK_ROUTE).unwrap(); /// let _ = socket.bind_auto().unwrap(); /// let kernel_addr = SocketAddr::new(0, 0); /// socket.connect(&kernel_addr).unwrap(); /// // This is a valid message for listing the network links on the system /// let msg = vec![ /// 0x14, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, 0x03, 0xfd, 0xfe, 0x38, 0x5c, 0x00, 0x00, 0x00, /// 0x00, 0x00, 0x00, 0x00, 0x00, /// ]; /// let n_sent = socket.send(&msg[..], 0).unwrap(); /// assert_eq!(n_sent, msg.len()); /// // buffer for receiving the response /// let mut buf = vec![0; 4096]; /// loop { /// let mut n_received = socket.recv(&mut &mut buf[..], 0).unwrap(); /// println!("received {:?}", &buf[..n_received]); /// if buf[4] == 2 && buf[5] == 0 { /// println!("the kernel responded with an error"); /// return; /// } /// if buf[4] == 3 && buf[5] == 0 { /// println!("end of dump"); /// return; /// } /// } /// ``` pub fn connect(&self, remote_addr: &SocketAddr) -> Result<()>
// almost never returns EINPROGRESS and so for now, we just return whatever libc::connect // returns. If it returns EINPROGRESS, the caller will have to handle the error themself // // Refs: // // - https://stackoverflow.com/a/14046386/1836144 // - https://lists.isc.org/pipermail/bind-users/2009-August/077527.html let (addr, addr_len) = remote_addr.as_raw(); let res = unsafe { libc::connect(self.0, addr, addr_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } // Most of the comments in this method come from a discussion on rust users forum. // [thread]: https://users.rust-lang.org/t/help-understanding-libc-call/17308/9 // /// Read a datagram from the socket and return the number of bytes that have been read and the address of the /// sender. The data being read is copied into `buf`. If `buf` is too small, the datagram is truncated. The /// supported flags are the `MSG_*` described in `man 2 recvmsg` /// /// # Warning /// /// In datagram oriented protocols, `recv` and `recvfrom` receive normally only ONE datagram, but this seems not to /// be always true for netlink sockets: with some protocols like `NETLINK_AUDIT`, multiple netlink packets can be /// read with a single call. pub fn recv_from<B>(&self, buf: &mut B, flags: libc::c_int) -> Result<(usize, SocketAddr)> where B: bytes::BufMut, { // Create an empty storage for the address. Note that Rust standard library create a // sockaddr_storage so that it works for any address family, but here, we already know that // we'll have a Netlink address, so we can create the appropriate storage. let mut addr = unsafe { mem::zeroed::<libc::sockaddr_nl>() }; // recvfrom takes a *sockaddr as parameter so that it can accept any kind of address // storage, so we need to create such a pointer for the sockaddr_nl we just initialized. // // Create a raw pointer to Cast our raw pointer to a // our storage. We cannot generic pointer to *sockaddr // pass it to recvfrom yet. that recvfrom can use // ^ ^ // | | // +--------------+---------------+ +---------+--------+ // / \ / \ let addr_ptr = &mut addr as *mut libc::sockaddr_nl as *mut libc::sockaddr; // Why do we need to pass the address length? We're passing a generic *sockaddr to // recvfrom. Somehow recvfrom needs to make sure that the address of the received packet // would fit into the actual type that is behind *sockaddr: it could be a sockaddr_nl but // also a sockaddr_in, a sockaddr_in6, or even the generic sockaddr_storage that can store // any address. let mut addrlen = mem::size_of_val(&addr); // recvfrom does not take the address length by value (see [thread]), so we need to create // a pointer to it. let addrlen_ptr = &mut addrlen as *mut usize as *mut libc::socklen_t; let chunk = buf.chunk_mut(); // Cast the *mut u8 into *mut void. // This is equivalent to casting a *char into *void // See [thread] // ^ // Create a *mut u8 | // ^ | // | | // +------+-------+ +--------+-------+ // / \ / \ let buf_ptr = chunk.as_mut_ptr() as *mut libc::c_void; let buf_len = chunk.len() as libc::size_t; let res = unsafe { libc::recvfrom(self.0, buf_ptr, buf_len, flags, addr_ptr, addrlen_ptr) }; if res < 0 { return Err(Error::last_os_error()); } else { // with `MSG_TRUNC` `res` might exceed `buf_len` let written = std::cmp::min(buf_len, res as usize); unsafe { buf.advance_mut(written); } } Ok((res as usize, SocketAddr(addr))) } /// For a connected socket, `recv` reads a datagram from the socket. The sender is the remote peer the socket is /// connected to (see [`Socket::connect`]). See also [`Socket::recv_from`] pub fn recv<B>(&self, buf: &mut B, flags: libc::c_int) -> Result<usize> where B: bytes::BufMut, { let chunk = buf.chunk_mut(); let buf_ptr = chunk.as_mut_ptr() as *mut libc::c_void; let buf_len = chunk.len() as libc::size_t; let res = unsafe { libc::recv(self.0, buf_ptr, buf_len, flags) }; if res < 0 { return Err(Error::last_os_error()); } else { // with `MSG_TRUNC` `res` might exceed `buf_len` let written = std::cmp::min(buf_len, res as usize); unsafe { buf.advance_mut(written); } } Ok(res as usize) } /// Receive a full message. Unlike [`Socket::recv_from`], which truncates messages that exceed the length of the /// buffer passed as argument, this method always reads a whole message, no matter its size. pub fn recv_from_full(&self) -> Result<(Vec<u8>, SocketAddr)> { // Peek let mut buf: Vec<u8> = Vec::new(); let (peek_len, _) = self.recv_from(&mut buf, libc::MSG_PEEK | libc::MSG_TRUNC)?; // Receive buf.clear(); buf.reserve(peek_len); let (rlen, addr) = self.recv_from(&mut buf, 0)?; assert_eq!(rlen, peek_len); Ok((buf, addr)) } /// Send the given buffer `buf` to the remote peer with address `addr`. The supported flags are the `MSG_*` values /// documented in `man 2 send`. pub fn send_to(&self, buf: &[u8], addr: &SocketAddr, flags: libc::c_int) -> Result<usize> { let (addr_ptr, addr_len) = addr.as_raw(); let buf_ptr = buf.as_ptr() as *const libc::c_void; let buf_len = buf.len() as libc::size_t; let res = unsafe { libc::sendto(self.0, buf_ptr, buf_len, flags, addr_ptr, addr_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(res as usize) } /// For a connected socket, `send` sends the given buffer `buf` to the remote peer the socket is connected to. See /// also [`Socket::connect`] and [`Socket::send_to`]. pub fn send(&self, buf: &[u8], flags: libc::c_int) -> Result<usize> { let buf_ptr = buf.as_ptr() as *const libc::c_void; let buf_len = buf.len() as libc::size_t; let res = unsafe { libc::send(self.0, buf_ptr, buf_len, flags) }; if res < 0 { return Err(Error::last_os_error()); } Ok(res as usize) } pub fn set_pktinfo(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_PKTINFO, value) } pub fn get_pktinfo(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_PKTINFO)?; Ok(res == 1) } pub fn add_membership(&mut self, group: u32) -> Result<()> { setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_ADD_MEMBERSHIP, group, ) } pub fn drop_membership(&mut self, group: u32) -> Result<()> { setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_DROP_MEMBERSHIP, group, ) } // pub fn list_membership(&self) -> Vec<u32> { // unimplemented!(); // // getsockopt won't be enough here, because we may need to perform 2 calls, and because the // // length of the list returned by libc::getsockopt is returned by mutating the length // // argument, which our implementation of getsockopt forbids. // } /// `NETLINK_BROADCAST_ERROR` (since Linux 2.6.30). When not set, `netlink_broadcast()` only /// reports `ESRCH` errors and silently ignore `NOBUFS` errors. pub fn set_broadcast_error(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_BROADCAST_ERROR, value, ) } pub fn get_broadcast_error(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_BROADCAST_ERROR)?; Ok(res == 1) } /// `NETLINK_NO_ENOBUFS` (since Linux 2.6.30). This flag can be used by unicast and broadcast /// listeners to avoid receiving `ENOBUFS` errors. pub fn set_no_enobufs(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_NO_ENOBUFS, value) } pub fn get_no_enobufs(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_NO_ENOBUFS)?; Ok(res == 1) } /// `NETLINK_LISTEN_ALL_NSID` (since Linux 4.2). When set, this socket will receive netlink /// notifications from all network namespaces that have an nsid assigned into the network /// namespace where the socket has been opened. The nsid is sent to user space via an ancillary /// data. pub fn set_listen_all_namespaces(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_LISTEN_ALL_NSID, value, ) } pub fn get_listen_all_namespaces(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_LISTEN_ALL_NSID)?; Ok(res == 1) } /// `NETLINK_CAP_ACK` (since Linux 4.2). The kernel may fail to allocate the necessary room /// for the acknowledgment message back to user space. This option trims off the payload of /// the original netlink message. The netlink message header is still included, so the user can /// guess from the sequence number which message triggered the acknowledgment. pub fn set_cap_ack(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_CAP_ACK, value) } pub fn get_cap_ack(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_CAP_ACK)?; Ok(res == 1) } } /// Wrapper around `getsockopt`: /// /// ```no_rust /// int getsockopt(int socket, int level, int option_name, void *restrict option_value, socklen_t *restrict option_len); /// ``` pub(crate) fn getsockopt<T: Copy>(fd: RawFd, level: libc::c_int, option: libc::c_int) -> Result<T> { // Create storage for the options we're fetching let mut slot: T = unsafe { mem::zeroed() }; // Create a mutable raw pointer to the storage so that getsockopt can fill the value let slot_ptr = &mut slot as *mut T as *mut libc::c_void; // Let getsockopt know how big our storage is let mut slot_len = mem::size_of::<T>() as libc::socklen_t; // getsockopt takes a mutable pointer to the length, because for some options like // NETLINK_LIST_MEMBERSHIP where the option value is a list with arbitrary length, // getsockopt uses this parameter to signal how big the storage needs to be. let slot_len_ptr = &mut slot_len as *mut libc::socklen_t; let res = unsafe { libc::getsockopt(fd, level, option, slot_ptr, slot_len_ptr) }; if res < 0 { return Err(Error::last_os_error()); } // Ignore the options that require the legnth to be set by getsockopt. // We'll deal with them individually. assert_eq!(slot_len as usize, mem::size_of::<T>()); Ok(slot) } // adapted from rust standard library fn setsockopt<T>(fd: RawFd, level: libc::c_int, option: libc::c_int, payload: T) -> Result<()> { let payload = &payload as *const T as *const libc::c_void; let payload_len = mem::size_of::<T>() as libc::socklen_t; let res = unsafe { libc::setsockopt(fd, level, option, payload, payload_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } #[cfg(test)] mod
{ // FIXME: // // Event though for SOCK_DGRAM sockets there's no IO, if our socket is non-blocking, // connect() might return EINPROGRESS. In theory, the right way to treat EINPROGRESS would // be to ignore the error, and let the user poll the socket to check when it becomes // writable, indicating that the connection succeeded. The code already exists in mio for // TcpStream: // // > pub fn connect(stream: net::TcpStream, addr: &SocketAddr) -> io::Result<TcpStream> { // > set_non_block(stream.as_raw_fd())?; // > match stream.connect(addr) { // > Ok(..) => {} // > Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {} // > Err(e) => return Err(e), // > } // > Ok(TcpStream { inner: stream }) // > } // // In practice, since the connection does not require any IO for SOCK_DGRAM sockets, it
identifier_body
socket.rs
kernel /// let n_sent = socket.send_to(&pkt[..], &kernel_addr, 0).unwrap(); /// assert_eq!(n_sent, pkt.len()); /// // buffer for receiving the response /// let mut buf = vec![0; 4096]; /// loop { /// // receive a datagram /// let (n_received, sender_addr) = socket.recv_from(&mut &mut buf[..], 0).unwrap(); /// assert_eq!(sender_addr, kernel_addr); /// println!("received datagram {:?}", &buf[..n_received]); /// if buf[4] == 2 && buf[5] == 0 { /// println!("the kernel responded with an error"); /// return; /// } /// if buf[4] == 3 && buf[5] == 0 { /// println!("end of dump"); /// return; /// } /// } /// ``` #[derive(Clone, Debug)] pub struct Socket(RawFd); impl AsRawFd for Socket { fn as_raw_fd(&self) -> RawFd { self.0 } } impl FromRawFd for Socket { unsafe fn from_raw_fd(fd: RawFd) -> Self { Socket(fd) } } impl Drop for Socket { fn drop(&mut self) { unsafe { libc::close(self.0) }; } } impl Socket { /// Open a new socket for the given netlink subsystem. `protocol` must be one of the /// [`netlink_sys::protocols`][protos] constants. /// /// [protos]: crate::protocols pub fn new(protocol: isize) -> Result<Self> { let res = unsafe { libc::socket( libc::PF_NETLINK, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, protocol as libc::c_int, ) }; if res < 0 { return Err(Error::last_os_error()); } Ok(Socket(res)) } /// Bind the socket to the given address pub fn bind(&mut self, addr: &SocketAddr) -> Result<()> { let (addr_ptr, addr_len) = addr.as_raw(); let res = unsafe { libc::bind(self.0, addr_ptr, addr_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } /// Bind the socket to an address assigned by the kernel, and return that address. pub fn bind_auto(&mut self) -> Result<SocketAddr> { let mut addr = SocketAddr::new(0, 0); self.bind(&addr)?; self.get_address(&mut addr)?; Ok(addr) } /// Get the socket address pub fn get_address(&self, addr: &mut SocketAddr) -> Result<()> { let (addr_ptr, mut addr_len) = addr.as_raw_mut(); let addr_len_copy = addr_len; let addr_len_ptr = &mut addr_len as *mut libc::socklen_t; let res = unsafe { libc::getsockname(self.0, addr_ptr, addr_len_ptr) }; if res < 0 { return Err(Error::last_os_error()); } assert_eq!(addr_len, addr_len_copy); Ok(()) } // when building with --features smol we don't need this #[allow(dead_code)] /// Make this socket non-blocking pub fn set_non_blocking(&self, non_blocking: bool) -> Result<()> { let mut non_blocking = non_blocking as libc::c_int; let res = unsafe { libc::ioctl(self.0, libc::FIONBIO, &mut non_blocking) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } /// Connect the socket to the given address. Netlink is a connection-less protocol, so a socket can communicate with /// multiple peers with the [`Socket::send_to`] and [`Socket::recv_from`] methods. However, if the socket only needs /// to communicate with one peer, it is convenient not to have to bother with the peer address. This is what /// `connect` is for. After calling `connect`, [`Socket::send`] and [`Socket::recv`] respectively send and receive /// datagrams to and from `remote_addr`. /// /// # Examples /// /// In this example we: /// /// 1. open a socket /// 2. connect it to the kernel with [`Socket::connect`] /// 3. send a request to the kernel with [`Socket::send`] /// 4. read the response (which can span over several messages) [`Socket::recv`] /// /// ```rust /// use netlink_sys::{protocols::NETLINK_ROUTE, Socket, SocketAddr}; /// use std::process; /// /// let mut socket = Socket::new(NETLINK_ROUTE).unwrap(); /// let _ = socket.bind_auto().unwrap(); /// let kernel_addr = SocketAddr::new(0, 0); /// socket.connect(&kernel_addr).unwrap(); /// // This is a valid message for listing the network links on the system /// let msg = vec![ /// 0x14, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, 0x03, 0xfd, 0xfe, 0x38, 0x5c, 0x00, 0x00, 0x00, /// 0x00, 0x00, 0x00, 0x00, 0x00, /// ]; /// let n_sent = socket.send(&msg[..], 0).unwrap(); /// assert_eq!(n_sent, msg.len()); /// // buffer for receiving the response /// let mut buf = vec![0; 4096]; /// loop { /// let mut n_received = socket.recv(&mut &mut buf[..], 0).unwrap(); /// println!("received {:?}", &buf[..n_received]); /// if buf[4] == 2 && buf[5] == 0 { /// println!("the kernel responded with an error"); /// return; /// } /// if buf[4] == 3 && buf[5] == 0 { /// println!("end of dump"); /// return; /// } /// } /// ``` pub fn connect(&self, remote_addr: &SocketAddr) -> Result<()> { // FIXME: // // Event though for SOCK_DGRAM sockets there's no IO, if our socket is non-blocking, // connect() might return EINPROGRESS. In theory, the right way to treat EINPROGRESS would // be to ignore the error, and let the user poll the socket to check when it becomes // writable, indicating that the connection succeeded. The code already exists in mio for // TcpStream: // // > pub fn connect(stream: net::TcpStream, addr: &SocketAddr) -> io::Result<TcpStream> { // > set_non_block(stream.as_raw_fd())?; // > match stream.connect(addr) { // > Ok(..) => {} // > Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {} // > Err(e) => return Err(e), // > } // > Ok(TcpStream { inner: stream }) // > } // // In practice, since the connection does not require any IO for SOCK_DGRAM sockets, it // almost never returns EINPROGRESS and so for now, we just return whatever libc::connect // returns. If it returns EINPROGRESS, the caller will have to handle the error themself // // Refs: // // - https://stackoverflow.com/a/14046386/1836144 // - https://lists.isc.org/pipermail/bind-users/2009-August/077527.html let (addr, addr_len) = remote_addr.as_raw(); let res = unsafe { libc::connect(self.0, addr, addr_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } // Most of the comments in this method come from a discussion on rust users forum. // [thread]: https://users.rust-lang.org/t/help-understanding-libc-call/17308/9 // /// Read a datagram from the socket and return the number of bytes that have been read and the address of the /// sender. The data being read is copied into `buf`. If `buf` is too small, the datagram is truncated. The /// supported flags are the `MSG_*` described in `man 2 recvmsg` /// /// # Warning /// /// In datagram oriented protocols, `recv` and `recvfrom` receive normally only ONE datagram, but this seems not to /// be always true for netlink sockets: with some protocols like `NETLINK_AUDIT`, multiple netlink packets can be /// read with a single call. pub fn recv_from<B>(&self, buf: &mut B, flags: libc::c_int) -> Result<(usize, SocketAddr)> where B: bytes::BufMut, { // Create an empty storage for the address. Note that Rust standard library create a // sockaddr_storage so that it works for any address family, but here, we already know that // we'll have a Netlink address, so we can create the appropriate storage. let mut addr = unsafe { mem::zeroed::<libc::sockaddr_nl>() }; // recvfrom takes a *sockaddr as parameter so that it can accept any kind of address // storage, so we need to create such a pointer for the sockaddr_nl we just initialized. // // Create a raw pointer to Cast our raw pointer to a // our storage. We cannot generic pointer to *sockaddr // pass it to recvfrom yet. that recvfrom can use // ^ ^ // | | // +--------------+---------------+ +---------+--------+ // / \ / \ let addr_ptr = &mut addr as *mut libc::sockaddr_nl as *mut libc::sockaddr; // Why do we need to pass the address length? We're passing a generic *sockaddr to // recvfrom. Somehow recvfrom needs to make sure that the address of the received packet // would fit into the actual type that is behind *sockaddr: it could be a sockaddr_nl but // also a sockaddr_in, a sockaddr_in6, or even the generic sockaddr_storage that can store // any address. let mut addrlen = mem::size_of_val(&addr); // recvfrom does not take the address length by value (see [thread]), so we need to create // a pointer to it. let addrlen_ptr = &mut addrlen as *mut usize as *mut libc::socklen_t; let chunk = buf.chunk_mut(); // Cast the *mut u8 into *mut void. // This is equivalent to casting a *char into *void // See [thread] // ^ // Create a *mut u8 | // ^ | // | | // +------+-------+ +--------+-------+ // / \ / \ let buf_ptr = chunk.as_mut_ptr() as *mut libc::c_void; let buf_len = chunk.len() as libc::size_t; let res = unsafe { libc::recvfrom(self.0, buf_ptr, buf_len, flags, addr_ptr, addrlen_ptr) }; if res < 0 { return Err(Error::last_os_error()); } else { // with `MSG_TRUNC` `res` might exceed `buf_len` let written = std::cmp::min(buf_len, res as usize); unsafe { buf.advance_mut(written); } } Ok((res as usize, SocketAddr(addr))) } /// For a connected socket, `recv` reads a datagram from the socket. The sender is the remote peer the socket is /// connected to (see [`Socket::connect`]). See also [`Socket::recv_from`] pub fn recv<B>(&self, buf: &mut B, flags: libc::c_int) -> Result<usize> where B: bytes::BufMut, { let chunk = buf.chunk_mut(); let buf_ptr = chunk.as_mut_ptr() as *mut libc::c_void; let buf_len = chunk.len() as libc::size_t; let res = unsafe { libc::recv(self.0, buf_ptr, buf_len, flags) }; if res < 0 { return Err(Error::last_os_error()); } else { // with `MSG_TRUNC` `res` might exceed `buf_len` let written = std::cmp::min(buf_len, res as usize); unsafe { buf.advance_mut(written); } } Ok(res as usize) } /// Receive a full message. Unlike [`Socket::recv_from`], which truncates messages that exceed the length of the /// buffer passed as argument, this method always reads a whole message, no matter its size. pub fn recv_from_full(&self) -> Result<(Vec<u8>, SocketAddr)> { // Peek let mut buf: Vec<u8> = Vec::new(); let (peek_len, _) = self.recv_from(&mut buf, libc::MSG_PEEK | libc::MSG_TRUNC)?; // Receive buf.clear(); buf.reserve(peek_len); let (rlen, addr) = self.recv_from(&mut buf, 0)?; assert_eq!(rlen, peek_len); Ok((buf, addr)) } /// Send the given buffer `buf` to the remote peer with address `addr`. The supported flags are the `MSG_*` values /// documented in `man 2 send`. pub fn send_to(&self, buf: &[u8], addr: &SocketAddr, flags: libc::c_int) -> Result<usize> { let (addr_ptr, addr_len) = addr.as_raw(); let buf_ptr = buf.as_ptr() as *const libc::c_void; let buf_len = buf.len() as libc::size_t; let res = unsafe { libc::sendto(self.0, buf_ptr, buf_len, flags, addr_ptr, addr_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(res as usize) } /// For a connected socket, `send` sends the given buffer `buf` to the remote peer the socket is connected to. See /// also [`Socket::connect`] and [`Socket::send_to`]. pub fn send(&self, buf: &[u8], flags: libc::c_int) -> Result<usize> { let buf_ptr = buf.as_ptr() as *const libc::c_void; let buf_len = buf.len() as libc::size_t; let res = unsafe { libc::send(self.0, buf_ptr, buf_len, flags) }; if res < 0 { return Err(Error::last_os_error()); } Ok(res as usize) } pub fn set_pktinfo(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_PKTINFO, value) } pub fn get_pktinfo(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_PKTINFO)?; Ok(res == 1) } pub fn add_membership(&mut self, group: u32) -> Result<()> { setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_ADD_MEMBERSHIP, group, ) } pub fn drop_membership(&mut self, group: u32) -> Result<()> { setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_DROP_MEMBERSHIP, group, ) } // pub fn list_membership(&self) -> Vec<u32> { // unimplemented!(); // // getsockopt won't be enough here, because we may need to perform 2 calls, and because the // // length of the list returned by libc::getsockopt is returned by mutating the length // // argument, which our implementation of getsockopt forbids. // } /// `NETLINK_BROADCAST_ERROR` (since Linux 2.6.30). When not set, `netlink_broadcast()` only /// reports `ESRCH` errors and silently ignore `NOBUFS` errors. pub fn set_broadcast_error(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_BROADCAST_ERROR, value, ) } pub fn get_broadcast_error(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_BROADCAST_ERROR)?; Ok(res == 1) } /// `NETLINK_NO_ENOBUFS` (since Linux 2.6.30). This flag can be used by unicast and broadcast /// listeners to avoid receiving `ENOBUFS` errors. pub fn set_no_enobufs(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value
else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_NO_ENOBUFS, value) } pub fn get_no_enobufs(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_NO_ENOBUFS)?; Ok(res == 1) } /// `NETLINK_LISTEN_ALL_NSID` (since Linux 4.2). When set, this socket will receive netlink /// notifications from all network namespaces that have an nsid assigned into the network /// namespace where the socket has been opened. The nsid is sent to user space via an ancillary /// data. pub fn set_listen_all_namespaces(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt( self.0, libc::SOL_NETLINK, libc::NETLINK_LISTEN_ALL_NSID, value, ) } pub fn get_listen_all_namespaces(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_LISTEN_ALL_NSID)?; Ok(res == 1) } /// `NETLINK_CAP_ACK` (since Linux 4.2). The kernel may fail to allocate the necessary room /// for the acknowledgment message back to user space. This option trims off the payload of /// the original netlink message. The netlink message header is still included, so the user can /// guess from the sequence number which message triggered the acknowledgment. pub fn set_cap_ack(&mut self, value: bool) -> Result<()> { let value: libc::c_int = if value { 1 } else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_CAP_ACK, value) } pub fn get_cap_ack(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_CAP_ACK)?; Ok(res == 1) } } /// Wrapper around `getsockopt`: /// /// ```no_rust /// int getsockopt(int socket, int level, int option_name, void *restrict option_value, socklen_t *restrict option_len); /// ``` pub(crate) fn getsockopt<T: Copy>(fd: RawFd, level: libc::c_int, option: libc::c_int) -> Result<T> { // Create storage for the options we're fetching let mut slot: T = unsafe { mem::zeroed() }; // Create a mutable raw pointer to the storage so that getsockopt can fill the value let slot_ptr = &mut slot as *mut T as *mut libc::c_void; // Let getsockopt know how big our storage is let mut slot_len = mem::size_of::<T>() as libc::socklen_t; // getsockopt takes a mutable pointer to the length, because for some options like // NETLINK_LIST_MEMBERSHIP where the option value is a list with arbitrary length, // getsockopt uses this parameter to signal how big the storage needs to be. let slot_len_ptr = &mut slot_len as *mut libc::socklen_t; let res = unsafe { libc::getsockopt(fd, level, option, slot_ptr, slot_len_ptr) }; if res < 0 { return Err(Error::last_os_error()); } // Ignore the options that require the legnth to be set by getsockopt. // We'll deal with them individually. assert_eq!(slot_len as usize, mem::size_of::<T>()); Ok(slot) } // adapted from rust standard library fn setsockopt<T>(fd: RawFd, level: libc::c_int, option: libc::c_int, payload: T) -> Result<()> { let payload = &payload as *const T as *const libc::c_void; let payload_len = mem::size_of::<T>() as libc::socklen_t; let res = unsafe { libc::setsockopt(fd, level, option, payload, payload_len) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } #[cfg(test)] mod
{ 1 }
conditional_block
printer.rs
format_options: FormatOptions, } impl Printer { pub fn new( pretty: Pretty, theme: Option<Theme>, stream: bool, buffer: Buffer, format_options: FormatOptions, ) -> Self { let theme = theme.unwrap_or(Theme::Auto); Printer { indent_json: pretty.format(), sort_headers: pretty.format(), color: pretty.color(), stream, theme, buffer, format_options, } } fn get_highlighter(&mut self, syntax: &'static str) -> Highlighter<'_> { Highlighter::new(syntax, self.theme, &mut self.buffer) } fn print_colorized_text(&mut self, text: &str, syntax: &'static str) -> io::Result<()> { self.get_highlighter(syntax).highlight(text) } fn print_syntax_text(&mut self, text: &str, syntax: &'static str) -> io::Result<()> { if self.color { self.print_colorized_text(text, syntax) } else { self.buffer.print(text) } } fn print_json_text(&mut self, text: &str, check_valid: bool) -> io::Result<()> { if!self.indent_json { // We don't have to do anything specialized, so fall back to the generic version return self.print_syntax_text(text, "json"); } if check_valid &&!valid_json(text) { // JSONXF may mess up the text, e.g. by removing whitespace // This is somewhat common as application/json is the default // content type for requests return self.print_syntax_text(text, "json"); } let mut formatter = get_json_formatter(&self.format_options); if self.color { let mut buf = Vec::new(); formatter.format_buf(text.as_bytes(), &mut buf)?; // in principle, buf should already be valid UTF-8, // because JSONXF doesn't mangle it let text = String::from_utf8_lossy(&buf); self.print_colorized_text(&text, "json") } else { formatter.format_buf(text.as_bytes(), &mut self.buffer) } } fn print_body_text(&mut self, content_type: ContentType, body: &str) -> io::Result<()> { match content_type { ContentType::Json => self.print_json_text(body, true), ContentType::Xml => self.print_syntax_text(body, "xml"), ContentType::Html => self.print_syntax_text(body, "html"), ContentType::Css => self.print_syntax_text(body, "css"), // In HTTPie part of this behavior is gated behind the --json flag // But it does JSON formatting even without that flag, so doing // this check unconditionally is fine ContentType::Text | ContentType::JavaScript if valid_json(body) => { self.print_json_text(body, false) } ContentType::JavaScript => self.print_syntax_text(body, "js"), _ => self.buffer.print(body), } } fn print_stream(&mut self, reader: &mut impl Read) -> io::Result<()> { if!self.buffer.is_terminal() { return copy_largebuf(reader, &mut self.buffer, true); } let mut guard = BinaryGuard::new(reader, true); while let Some(lines) = guard.read_lines()? { self.buffer.write_all(lines)?; self.buffer.flush()?; } Ok(()) } fn print_colorized_stream( &mut self, stream: &mut impl Read, syntax: &'static str, ) -> io::Result<()> { let mut guard = BinaryGuard::new(stream, self.buffer.is_terminal()); let mut highlighter = self.get_highlighter(syntax); while let Some(lines) = guard.read_lines()? { for line in lines.split_inclusive(|&b| b == b'\n') { highlighter.highlight_bytes(line)?; } highlighter.flush()?; } Ok(()) } fn print_syntax_stream( &mut self, stream: &mut impl Read, syntax: &'static str, ) -> io::Result<()> { if self.color { self.print_colorized_stream(stream, syntax) } else { self.print_stream(stream) } } fn print_json_stream(&mut self, stream: &mut impl Read) -> io::Result<()> { if!self.indent_json { // We don't have to do anything specialized, so fall back to the generic version self.print_syntax_stream(stream, "json") } else if self.color { let mut guard = BinaryGuard::new(stream, self.buffer.is_terminal()); let mut formatter = get_json_formatter(&self.format_options); let mut highlighter = self.get_highlighter("json"); let mut buf = Vec::new(); while let Some(lines) = guard.read_lines()? { formatter.format_buf(lines, &mut buf)?; for line in buf.split_inclusive(|&b| b == b'\n') { highlighter.highlight_bytes(line)?; } highlighter.flush()?; buf.clear(); } Ok(()) } else { let mut formatter = get_json_formatter(&self.format_options); if!self.buffer.is_terminal() { let mut buf = vec![0; BUFFER_SIZE]; loop { match stream.read(&mut buf) { Ok(0) => return Ok(()), Ok(n) => { formatter.format_buf(&buf[0..n], &mut self.buffer)?; self.buffer.flush()?; } Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => return Err(e), } } } let mut guard = BinaryGuard::new(stream, true); while let Some(lines) = guard.read_lines()? { formatter.format_buf(lines, &mut self.buffer)?; self.buffer.flush()?; } Ok(()) } } fn print_body_stream( &mut self, content_type: ContentType, body: &mut impl Read, ) -> io::Result<()> { match content_type { ContentType::Json => self.print_json_stream(body), ContentType::Xml => self.print_syntax_stream(body, "xml"), ContentType::Html => self.print_syntax_stream(body, "html"), ContentType::Css => self.print_syntax_stream(body, "css"), // print_body_text() has fancy JSON detection, but we can't do that here ContentType::JavaScript => self.print_syntax_stream(body, "js"), _ => self.print_stream(body), } } fn print_headers(&mut self, text: &str) -> io::Result<()> { if self.color { self.print_colorized_text(text, "http") } else { self.buffer.print(text) } } fn headers_to_string(&self, headers: &HeaderMap, version: Version) -> String { let as_titlecase = match version { Version::HTTP_09 | Version::HTTP_10 | Version::HTTP_11 => true, Version::HTTP_2 | Version::HTTP_3 => false, _ => false, }; let mut headers: Vec<(&HeaderName, &HeaderValue)> = headers.iter().collect(); if self.sort_headers { headers.sort_by_key(|(name, _)| name.as_str()); } let mut header_string = String::new(); for (key, value) in headers { if as_titlecase { // Ought to be equivalent to how hyper does it // https://github.com/hyperium/hyper/blob/f46b175bf71b202fbb907c4970b5743881b891e1/src/proto/h1/role.rs#L1332 // Header names are ASCII so it's ok to operate on char instead of u8 let mut prev = '-'; for mut c in key.as_str().chars() { if prev == '-' { c.make_ascii_uppercase(); } header_string.push(c); prev = c; } } else { header_string.push_str(key.as_str()); } header_string.push_str(": "); match value.to_str() { Ok(value) => header_string.push_str(value), #[allow(clippy::format_push_string)] Err(_) => header_string.push_str(&format!("{:?}", value)), } header_string.push('\n'); } header_string.pop(); header_string } pub fn print_separator(&mut self) -> io::Result<()> { self.buffer.print("\n")?; self.buffer.flush()?; Ok(()) } pub fn print_request_headers<T>(&mut self, request: &Request, cookie_jar: &T) -> io::Result<()> where T: CookieStore, { let method = request.method(); let url = request.url(); let query_string = url.query().map_or(String::from(""), |q| ["?", q].concat()); let version = request.version(); let mut headers = request.headers().clone(); headers .entry(ACCEPT) .or_insert_with(|| HeaderValue::from_static("*/*")); if let Some(cookie) = cookie_jar.cookies(url) { headers.insert(COOKIE, cookie); } // See https://github.com/seanmonstar/reqwest/issues/1030 // reqwest and hyper add certain headers, but only in the process of // sending the request, which we haven't done yet if let Some(body) = request.body().and_then(Body::as_bytes) { // Added at https://github.com/seanmonstar/reqwest/blob/e56bd160ba/src/blocking/request.rs#L132 headers .entry(CONTENT_LENGTH) .or_insert_with(|| body.len().into()); } if let Some(host) = request.url().host_str() { // This is incorrect in case of HTTP/2, but we're already assuming // HTTP/1.1 anyway headers.entry(HOST).or_insert_with(|| { // Added at https://github.com/hyperium/hyper/blob/dfa1bb291d/src/client/client.rs#L237 if test_mode() { HeaderValue::from_str("http.mock") } else if let Some(port) = request.url().port() { HeaderValue::from_str(&format!("{}:{}", host, port)) } else { HeaderValue::from_str(host) } .expect("hostname should already be validated/parsed") }); } let request_line = format!("{} {}{} {:?}\n", method, url.path(), query_string, version); let headers = self.headers_to_string(&headers, version); self.print_headers(&(request_line + &headers))?; self.buffer.print("\n\n")?; self.buffer.flush()?; Ok(()) } pub fn print_response_headers(&mut self, response: &Response) -> io::Result<()> { let version = response.version(); let status = response.status(); let headers = response.headers(); let status_line = format!("{:?} {}\n", version, status); let headers = self.headers_to_string(headers, version); self.print_headers(&(status_line + &headers))?; self.buffer.print("\n\n")?; self.buffer.flush()?; Ok(()) } pub fn print_request_body(&mut self, request: &mut Request) -> anyhow::Result<()>
pub fn print_response_body( &mut self, response: &mut Response, encoding: Option<&'static Encoding>, mime: Option<&str>, ) -> anyhow::Result<()> { let starting_time = Instant::now(); let url = response.url().clone(); let content_type = mime.map_or_else(|| get_content_type(response.headers()), ContentType::from); let encoding = encoding.or_else(|| get_charset(response)); let compression_type = get_compression_type(response.headers()); let mut body = decompress(response, compression_type); if!self.buffer.is_terminal() { if (self.color || self.indent_json) && content_type.is_text() { // The user explicitly asked for formatting even though this is // going into a file, and the response is at least supposed to be // text, so decode it // TODO: HTTPie re-encodes output in the original encoding, we don't // encoding_rs::Encoder::encode_from_utf8_to_vec_without_replacement() // and guess_encoding() may help, but it'll require refactoring // The current design is a bit unfortunate because there's no way to // force UTF-8 output without coloring or formatting // Unconditionally decoding is not an option because the body // might not be text at all if self.stream { self.print_body_stream( content_type, &mut decode_stream(&mut body, encoding, &url)?, )?; } else { let mut buf = Vec::new(); body.read_to_end(&mut buf)?; let text = decode_blob_unconditional(&buf, encoding, &url); self.print_body_text(content_type, &text)?; } } else if self.stream { copy_largebuf(&mut body, &mut self.buffer, true)?; } else { let mut buf = Vec::new(); body.read_to_end(&mut buf)?; self.buffer.print(&buf)?; } } else if self.stream { match self .print_body_stream(content_type, &mut decode_stream(&mut body, encoding, &url)?) { Ok(_) => { self.buffer.print("\n")?; } Err(err) if err.kind() == io::ErrorKind::InvalidData => { self.buffer.print(BINARY_SUPPRESSOR)?; } Err(err) => return Err(err.into()), } } else { let mut buf = Vec::new(); body.read_to_end(&mut buf)?; match decode_blob(&buf, encoding, &url) { None => { self.buffer.print(BINARY_SUPPRESSOR)?; } Some(text) => { self.print_body_text(content_type, &text)?; self.buffer.print("\n")?; } }; } self.buffer.flush()?; drop(body); // silence the borrow checker response.meta_mut().content_download_duration = Some(starting_time.elapsed()); Ok(()) } pub fn print_response_meta(&mut self, response: &Response) -> anyhow::Result<()> { let meta = response.meta(); let mut total_elapsed_time = meta.request_duration.as_secs_f64(); if let Some(content_download_duration) = meta.content_download_duration { total_elapsed_time += content_download_duration.as_secs_f64(); } self.buffer .print(format!("Elapsed time: {:.5}s", total_elapsed_time))?; self.buffer.print("\n\n")?; Ok(()) } } enum ContentType { Json, Html, Xml, JavaScript, Css, Text, UrlencodedForm, Multipart, Unknown, } impl ContentType { fn is_text(&self) -> bool { !matches!( self, ContentType::Unknown | ContentType::UrlencodedForm | ContentType::Multipart ) } } impl From<&str> for ContentType { fn from(content_type: &str) -> Self { if content_type.contains("json") { ContentType::Json } else if content_type.contains("html") { ContentType::Html } else if content_type.contains("xml") { ContentType::Xml } else if content_type.contains("multipart") { ContentType::Multipart } else if content_type.contains("x-www-form-urlencoded") { ContentType::UrlencodedForm } else if content_type.contains("javascript") { ContentType::JavaScript } else if content_type.contains("css") { ContentType::Css } else if content_type.contains("text") { // We later check if this one's JSON // HTTPie checks for "json", "javascript" and "text" in one place: // https://github.com/httpie/httpie/blob/a32ad344dd/httpie/output/formatters/json.py#L14 // We have it more spread out but it behaves more or less the same ContentType::Text } else {
{ let content_type = get_content_type(request.headers()); if let Some(body) = request.body_mut() { let body = body.buffer()?; if body.contains(&b'\0') { self.buffer.print(BINARY_SUPPRESSOR)?; } else { self.print_body_text(content_type, &String::from_utf8_lossy(body))?; self.buffer.print("\n")?; } // Breathing room between request and response self.buffer.print("\n")?; self.buffer.flush()?; } Ok(()) }
identifier_body
printer.rs
if!self.indent_json { // We don't have to do anything specialized, so fall back to the generic version return self.print_syntax_text(text, "json"); } if check_valid &&!valid_json(text) { // JSONXF may mess up the text, e.g. by removing whitespace // This is somewhat common as application/json is the default // content type for requests return self.print_syntax_text(text, "json"); } let mut formatter = get_json_formatter(&self.format_options); if self.color { let mut buf = Vec::new(); formatter.format_buf(text.as_bytes(), &mut buf)?; // in principle, buf should already be valid UTF-8, // because JSONXF doesn't mangle it let text = String::from_utf8_lossy(&buf); self.print_colorized_text(&text, "json") } else { formatter.format_buf(text.as_bytes(), &mut self.buffer) } } fn print_body_text(&mut self, content_type: ContentType, body: &str) -> io::Result<()> { match content_type { ContentType::Json => self.print_json_text(body, true), ContentType::Xml => self.print_syntax_text(body, "xml"), ContentType::Html => self.print_syntax_text(body, "html"), ContentType::Css => self.print_syntax_text(body, "css"), // In HTTPie part of this behavior is gated behind the --json flag // But it does JSON formatting even without that flag, so doing // this check unconditionally is fine ContentType::Text | ContentType::JavaScript if valid_json(body) => { self.print_json_text(body, false) } ContentType::JavaScript => self.print_syntax_text(body, "js"), _ => self.buffer.print(body), } } fn print_stream(&mut self, reader: &mut impl Read) -> io::Result<()> { if!self.buffer.is_terminal() { return copy_largebuf(reader, &mut self.buffer, true); } let mut guard = BinaryGuard::new(reader, true); while let Some(lines) = guard.read_lines()? { self.buffer.write_all(lines)?; self.buffer.flush()?; } Ok(()) } fn print_colorized_stream( &mut self, stream: &mut impl Read, syntax: &'static str, ) -> io::Result<()> { let mut guard = BinaryGuard::new(stream, self.buffer.is_terminal()); let mut highlighter = self.get_highlighter(syntax); while let Some(lines) = guard.read_lines()? { for line in lines.split_inclusive(|&b| b == b'\n') { highlighter.highlight_bytes(line)?; } highlighter.flush()?; } Ok(()) } fn print_syntax_stream( &mut self, stream: &mut impl Read, syntax: &'static str, ) -> io::Result<()> { if self.color { self.print_colorized_stream(stream, syntax) } else { self.print_stream(stream) } } fn print_json_stream(&mut self, stream: &mut impl Read) -> io::Result<()> { if!self.indent_json { // We don't have to do anything specialized, so fall back to the generic version self.print_syntax_stream(stream, "json") } else if self.color { let mut guard = BinaryGuard::new(stream, self.buffer.is_terminal()); let mut formatter = get_json_formatter(&self.format_options); let mut highlighter = self.get_highlighter("json"); let mut buf = Vec::new(); while let Some(lines) = guard.read_lines()? { formatter.format_buf(lines, &mut buf)?; for line in buf.split_inclusive(|&b| b == b'\n') { highlighter.highlight_bytes(line)?; } highlighter.flush()?; buf.clear(); } Ok(()) } else { let mut formatter = get_json_formatter(&self.format_options); if!self.buffer.is_terminal() { let mut buf = vec![0; BUFFER_SIZE]; loop { match stream.read(&mut buf) { Ok(0) => return Ok(()), Ok(n) => { formatter.format_buf(&buf[0..n], &mut self.buffer)?; self.buffer.flush()?; } Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => return Err(e), } } } let mut guard = BinaryGuard::new(stream, true); while let Some(lines) = guard.read_lines()? { formatter.format_buf(lines, &mut self.buffer)?; self.buffer.flush()?; } Ok(()) } } fn print_body_stream( &mut self, content_type: ContentType, body: &mut impl Read, ) -> io::Result<()> { match content_type { ContentType::Json => self.print_json_stream(body), ContentType::Xml => self.print_syntax_stream(body, "xml"), ContentType::Html => self.print_syntax_stream(body, "html"), ContentType::Css => self.print_syntax_stream(body, "css"), // print_body_text() has fancy JSON detection, but we can't do that here ContentType::JavaScript => self.print_syntax_stream(body, "js"), _ => self.print_stream(body), } } fn print_headers(&mut self, text: &str) -> io::Result<()> { if self.color { self.print_colorized_text(text, "http") } else { self.buffer.print(text) } } fn headers_to_string(&self, headers: &HeaderMap, version: Version) -> String { let as_titlecase = match version { Version::HTTP_09 | Version::HTTP_10 | Version::HTTP_11 => true, Version::HTTP_2 | Version::HTTP_3 => false, _ => false, }; let mut headers: Vec<(&HeaderName, &HeaderValue)> = headers.iter().collect(); if self.sort_headers { headers.sort_by_key(|(name, _)| name.as_str()); } let mut header_string = String::new(); for (key, value) in headers { if as_titlecase { // Ought to be equivalent to how hyper does it // https://github.com/hyperium/hyper/blob/f46b175bf71b202fbb907c4970b5743881b891e1/src/proto/h1/role.rs#L1332 // Header names are ASCII so it's ok to operate on char instead of u8 let mut prev = '-'; for mut c in key.as_str().chars() { if prev == '-' { c.make_ascii_uppercase(); } header_string.push(c); prev = c; } } else { header_string.push_str(key.as_str()); } header_string.push_str(": "); match value.to_str() { Ok(value) => header_string.push_str(value), #[allow(clippy::format_push_string)] Err(_) => header_string.push_str(&format!("{:?}", value)), } header_string.push('\n'); } header_string.pop(); header_string } pub fn print_separator(&mut self) -> io::Result<()> { self.buffer.print("\n")?; self.buffer.flush()?; Ok(()) } pub fn print_request_headers<T>(&mut self, request: &Request, cookie_jar: &T) -> io::Result<()> where T: CookieStore, { let method = request.method(); let url = request.url(); let query_string = url.query().map_or(String::from(""), |q| ["?", q].concat()); let version = request.version(); let mut headers = request.headers().clone(); headers .entry(ACCEPT) .or_insert_with(|| HeaderValue::from_static("*/*")); if let Some(cookie) = cookie_jar.cookies(url) { headers.insert(COOKIE, cookie); } // See https://github.com/seanmonstar/reqwest/issues/1030 // reqwest and hyper add certain headers, but only in the process of // sending the request, which we haven't done yet if let Some(body) = request.body().and_then(Body::as_bytes) { // Added at https://github.com/seanmonstar/reqwest/blob/e56bd160ba/src/blocking/request.rs#L132 headers .entry(CONTENT_LENGTH) .or_insert_with(|| body.len().into()); } if let Some(host) = request.url().host_str() { // This is incorrect in case of HTTP/2, but we're already assuming // HTTP/1.1 anyway headers.entry(HOST).or_insert_with(|| { // Added at https://github.com/hyperium/hyper/blob/dfa1bb291d/src/client/client.rs#L237 if test_mode() { HeaderValue::from_str("http.mock") } else if let Some(port) = request.url().port() { HeaderValue::from_str(&format!("{}:{}", host, port)) } else { HeaderValue::from_str(host) } .expect("hostname should already be validated/parsed") }); } let request_line = format!("{} {}{} {:?}\n", method, url.path(), query_string, version); let headers = self.headers_to_string(&headers, version); self.print_headers(&(request_line + &headers))?; self.buffer.print("\n\n")?; self.buffer.flush()?; Ok(()) } pub fn print_response_headers(&mut self, response: &Response) -> io::Result<()> { let version = response.version(); let status = response.status(); let headers = response.headers(); let status_line = format!("{:?} {}\n", version, status); let headers = self.headers_to_string(headers, version); self.print_headers(&(status_line + &headers))?; self.buffer.print("\n\n")?; self.buffer.flush()?; Ok(()) } pub fn print_request_body(&mut self, request: &mut Request) -> anyhow::Result<()> { let content_type = get_content_type(request.headers()); if let Some(body) = request.body_mut() { let body = body.buffer()?; if body.contains(&b'\0') { self.buffer.print(BINARY_SUPPRESSOR)?; } else { self.print_body_text(content_type, &String::from_utf8_lossy(body))?; self.buffer.print("\n")?; } // Breathing room between request and response self.buffer.print("\n")?; self.buffer.flush()?; } Ok(()) } pub fn print_response_body( &mut self, response: &mut Response, encoding: Option<&'static Encoding>, mime: Option<&str>, ) -> anyhow::Result<()> { let starting_time = Instant::now(); let url = response.url().clone(); let content_type = mime.map_or_else(|| get_content_type(response.headers()), ContentType::from); let encoding = encoding.or_else(|| get_charset(response)); let compression_type = get_compression_type(response.headers()); let mut body = decompress(response, compression_type); if!self.buffer.is_terminal() { if (self.color || self.indent_json) && content_type.is_text() { // The user explicitly asked for formatting even though this is // going into a file, and the response is at least supposed to be // text, so decode it // TODO: HTTPie re-encodes output in the original encoding, we don't // encoding_rs::Encoder::encode_from_utf8_to_vec_without_replacement() // and guess_encoding() may help, but it'll require refactoring // The current design is a bit unfortunate because there's no way to // force UTF-8 output without coloring or formatting // Unconditionally decoding is not an option because the body // might not be text at all if self.stream { self.print_body_stream( content_type, &mut decode_stream(&mut body, encoding, &url)?, )?; } else { let mut buf = Vec::new(); body.read_to_end(&mut buf)?; let text = decode_blob_unconditional(&buf, encoding, &url); self.print_body_text(content_type, &text)?; } } else if self.stream { copy_largebuf(&mut body, &mut self.buffer, true)?; } else { let mut buf = Vec::new(); body.read_to_end(&mut buf)?; self.buffer.print(&buf)?; } } else if self.stream { match self .print_body_stream(content_type, &mut decode_stream(&mut body, encoding, &url)?) { Ok(_) => { self.buffer.print("\n")?; } Err(err) if err.kind() == io::ErrorKind::InvalidData => { self.buffer.print(BINARY_SUPPRESSOR)?; } Err(err) => return Err(err.into()), } } else { let mut buf = Vec::new(); body.read_to_end(&mut buf)?; match decode_blob(&buf, encoding, &url) { None => { self.buffer.print(BINARY_SUPPRESSOR)?; } Some(text) => { self.print_body_text(content_type, &text)?; self.buffer.print("\n")?; } }; } self.buffer.flush()?; drop(body); // silence the borrow checker response.meta_mut().content_download_duration = Some(starting_time.elapsed()); Ok(()) } pub fn print_response_meta(&mut self, response: &Response) -> anyhow::Result<()> { let meta = response.meta(); let mut total_elapsed_time = meta.request_duration.as_secs_f64(); if let Some(content_download_duration) = meta.content_download_duration { total_elapsed_time += content_download_duration.as_secs_f64(); } self.buffer .print(format!("Elapsed time: {:.5}s", total_elapsed_time))?; self.buffer.print("\n\n")?; Ok(()) } } enum ContentType { Json, Html, Xml, JavaScript, Css, Text, UrlencodedForm, Multipart, Unknown, } impl ContentType { fn is_text(&self) -> bool { !matches!( self, ContentType::Unknown | ContentType::UrlencodedForm | ContentType::Multipart ) } } impl From<&str> for ContentType { fn from(content_type: &str) -> Self { if content_type.contains("json") { ContentType::Json } else if content_type.contains("html") { ContentType::Html } else if content_type.contains("xml") { ContentType::Xml } else if content_type.contains("multipart") { ContentType::Multipart } else if content_type.contains("x-www-form-urlencoded") { ContentType::UrlencodedForm } else if content_type.contains("javascript") { ContentType::JavaScript } else if content_type.contains("css") { ContentType::Css } else if content_type.contains("text") { // We later check if this one's JSON // HTTPie checks for "json", "javascript" and "text" in one place: // https://github.com/httpie/httpie/blob/a32ad344dd/httpie/output/formatters/json.py#L14 // We have it more spread out but it behaves more or less the same ContentType::Text } else { ContentType::Unknown } } } fn get_content_type(headers: &HeaderMap) -> ContentType { headers .get(CONTENT_TYPE) .and_then(|value| value.to_str().ok()) .map_or(ContentType::Unknown, ContentType::from) } fn valid_json(text: &str) -> bool { serde_json::from_str::<serde::de::IgnoredAny>(text).is_ok() } /// Decode a response, using BOM sniffing or chardet if the encoding is unknown. /// /// This is different from [`Response::text`], which assumes UTF-8 as a fallback. /// /// Returns `None` if the decoded text would contain null codepoints (i.e., is binary). fn decode_blob<'a>( raw: &'a [u8], encoding: Option<&'static Encoding>, url: &Url, ) -> Option<Cow<'a, str>> { let encoding = encoding.unwrap_or_else(|| detect_encoding(raw, true, url)); // If the encoding is ASCII-compatible then a null byte corresponds to a // null codepoint and vice versa, so we can check for them before decoding. // For a 11MB binary file this saves 100ms, that's worth doing. // UTF-16 is not ASCII-compatible: all ASCII characters are padded with a // null byte, so finding a null byte doesn't mean anything. if encoding.is_ascii_compatible() && raw.contains(&0) { return None; } // Don't allow the BOM to override the encoding. But do remove it if // it matches the encoding. let text = encoding.decode_with_bom_removal(raw).0; if!encoding.is_ascii_compatible() && text.contains('\0')
{ None }
conditional_block
printer.rs
format_options: FormatOptions, } impl Printer { pub fn new( pretty: Pretty, theme: Option<Theme>, stream: bool, buffer: Buffer, format_options: FormatOptions, ) -> Self { let theme = theme.unwrap_or(Theme::Auto); Printer { indent_json: pretty.format(), sort_headers: pretty.format(), color: pretty.color(), stream, theme, buffer, format_options, } } fn get_highlighter(&mut self, syntax: &'static str) -> Highlighter<'_> { Highlighter::new(syntax, self.theme, &mut self.buffer) } fn print_colorized_text(&mut self, text: &str, syntax: &'static str) -> io::Result<()> { self.get_highlighter(syntax).highlight(text) } fn print_syntax_text(&mut self, text: &str, syntax: &'static str) -> io::Result<()> { if self.color { self.print_colorized_text(text, syntax) } else { self.buffer.print(text) } } fn print_json_text(&mut self, text: &str, check_valid: bool) -> io::Result<()> { if!self.indent_json { // We don't have to do anything specialized, so fall back to the generic version return self.print_syntax_text(text, "json"); } if check_valid &&!valid_json(text) { // JSONXF may mess up the text, e.g. by removing whitespace // This is somewhat common as application/json is the default // content type for requests return self.print_syntax_text(text, "json"); } let mut formatter = get_json_formatter(&self.format_options); if self.color { let mut buf = Vec::new(); formatter.format_buf(text.as_bytes(), &mut buf)?; // in principle, buf should already be valid UTF-8, // because JSONXF doesn't mangle it let text = String::from_utf8_lossy(&buf); self.print_colorized_text(&text, "json") } else { formatter.format_buf(text.as_bytes(), &mut self.buffer) } } fn print_body_text(&mut self, content_type: ContentType, body: &str) -> io::Result<()> { match content_type { ContentType::Json => self.print_json_text(body, true), ContentType::Xml => self.print_syntax_text(body, "xml"), ContentType::Html => self.print_syntax_text(body, "html"), ContentType::Css => self.print_syntax_text(body, "css"), // In HTTPie part of this behavior is gated behind the --json flag // But it does JSON formatting even without that flag, so doing // this check unconditionally is fine ContentType::Text | ContentType::JavaScript if valid_json(body) => { self.print_json_text(body, false) } ContentType::JavaScript => self.print_syntax_text(body, "js"), _ => self.buffer.print(body), } } fn print_stream(&mut self, reader: &mut impl Read) -> io::Result<()> { if!self.buffer.is_terminal() { return copy_largebuf(reader, &mut self.buffer, true); } let mut guard = BinaryGuard::new(reader, true); while let Some(lines) = guard.read_lines()? { self.buffer.write_all(lines)?; self.buffer.flush()?; } Ok(()) } fn print_colorized_stream( &mut self, stream: &mut impl Read, syntax: &'static str, ) -> io::Result<()> { let mut guard = BinaryGuard::new(stream, self.buffer.is_terminal()); let mut highlighter = self.get_highlighter(syntax); while let Some(lines) = guard.read_lines()? { for line in lines.split_inclusive(|&b| b == b'\n') { highlighter.highlight_bytes(line)?; } highlighter.flush()?; } Ok(()) } fn print_syntax_stream( &mut self, stream: &mut impl Read, syntax: &'static str, ) -> io::Result<()> { if self.color { self.print_colorized_stream(stream, syntax) } else { self.print_stream(stream) } } fn print_json_stream(&mut self, stream: &mut impl Read) -> io::Result<()> { if!self.indent_json { // We don't have to do anything specialized, so fall back to the generic version self.print_syntax_stream(stream, "json") } else if self.color { let mut guard = BinaryGuard::new(stream, self.buffer.is_terminal()); let mut formatter = get_json_formatter(&self.format_options); let mut highlighter = self.get_highlighter("json"); let mut buf = Vec::new(); while let Some(lines) = guard.read_lines()? { formatter.format_buf(lines, &mut buf)?; for line in buf.split_inclusive(|&b| b == b'\n') { highlighter.highlight_bytes(line)?; } highlighter.flush()?; buf.clear(); } Ok(()) } else { let mut formatter = get_json_formatter(&self.format_options); if!self.buffer.is_terminal() { let mut buf = vec![0; BUFFER_SIZE]; loop { match stream.read(&mut buf) { Ok(0) => return Ok(()), Ok(n) => { formatter.format_buf(&buf[0..n], &mut self.buffer)?; self.buffer.flush()?; } Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => return Err(e), } } } let mut guard = BinaryGuard::new(stream, true); while let Some(lines) = guard.read_lines()? { formatter.format_buf(lines, &mut self.buffer)?; self.buffer.flush()?; } Ok(()) } } fn print_body_stream( &mut self, content_type: ContentType, body: &mut impl Read, ) -> io::Result<()> { match content_type { ContentType::Json => self.print_json_stream(body), ContentType::Xml => self.print_syntax_stream(body, "xml"), ContentType::Html => self.print_syntax_stream(body, "html"), ContentType::Css => self.print_syntax_stream(body, "css"), // print_body_text() has fancy JSON detection, but we can't do that here ContentType::JavaScript => self.print_syntax_stream(body, "js"), _ => self.print_stream(body), } } fn print_headers(&mut self, text: &str) -> io::Result<()> { if self.color { self.print_colorized_text(text, "http") } else { self.buffer.print(text) } } fn
(&self, headers: &HeaderMap, version: Version) -> String { let as_titlecase = match version { Version::HTTP_09 | Version::HTTP_10 | Version::HTTP_11 => true, Version::HTTP_2 | Version::HTTP_3 => false, _ => false, }; let mut headers: Vec<(&HeaderName, &HeaderValue)> = headers.iter().collect(); if self.sort_headers { headers.sort_by_key(|(name, _)| name.as_str()); } let mut header_string = String::new(); for (key, value) in headers { if as_titlecase { // Ought to be equivalent to how hyper does it // https://github.com/hyperium/hyper/blob/f46b175bf71b202fbb907c4970b5743881b891e1/src/proto/h1/role.rs#L1332 // Header names are ASCII so it's ok to operate on char instead of u8 let mut prev = '-'; for mut c in key.as_str().chars() { if prev == '-' { c.make_ascii_uppercase(); } header_string.push(c); prev = c; } } else { header_string.push_str(key.as_str()); } header_string.push_str(": "); match value.to_str() { Ok(value) => header_string.push_str(value), #[allow(clippy::format_push_string)] Err(_) => header_string.push_str(&format!("{:?}", value)), } header_string.push('\n'); } header_string.pop(); header_string } pub fn print_separator(&mut self) -> io::Result<()> { self.buffer.print("\n")?; self.buffer.flush()?; Ok(()) } pub fn print_request_headers<T>(&mut self, request: &Request, cookie_jar: &T) -> io::Result<()> where T: CookieStore, { let method = request.method(); let url = request.url(); let query_string = url.query().map_or(String::from(""), |q| ["?", q].concat()); let version = request.version(); let mut headers = request.headers().clone(); headers .entry(ACCEPT) .or_insert_with(|| HeaderValue::from_static("*/*")); if let Some(cookie) = cookie_jar.cookies(url) { headers.insert(COOKIE, cookie); } // See https://github.com/seanmonstar/reqwest/issues/1030 // reqwest and hyper add certain headers, but only in the process of // sending the request, which we haven't done yet if let Some(body) = request.body().and_then(Body::as_bytes) { // Added at https://github.com/seanmonstar/reqwest/blob/e56bd160ba/src/blocking/request.rs#L132 headers .entry(CONTENT_LENGTH) .or_insert_with(|| body.len().into()); } if let Some(host) = request.url().host_str() { // This is incorrect in case of HTTP/2, but we're already assuming // HTTP/1.1 anyway headers.entry(HOST).or_insert_with(|| { // Added at https://github.com/hyperium/hyper/blob/dfa1bb291d/src/client/client.rs#L237 if test_mode() { HeaderValue::from_str("http.mock") } else if let Some(port) = request.url().port() { HeaderValue::from_str(&format!("{}:{}", host, port)) } else { HeaderValue::from_str(host) } .expect("hostname should already be validated/parsed") }); } let request_line = format!("{} {}{} {:?}\n", method, url.path(), query_string, version); let headers = self.headers_to_string(&headers, version); self.print_headers(&(request_line + &headers))?; self.buffer.print("\n\n")?; self.buffer.flush()?; Ok(()) } pub fn print_response_headers(&mut self, response: &Response) -> io::Result<()> { let version = response.version(); let status = response.status(); let headers = response.headers(); let status_line = format!("{:?} {}\n", version, status); let headers = self.headers_to_string(headers, version); self.print_headers(&(status_line + &headers))?; self.buffer.print("\n\n")?; self.buffer.flush()?; Ok(()) } pub fn print_request_body(&mut self, request: &mut Request) -> anyhow::Result<()> { let content_type = get_content_type(request.headers()); if let Some(body) = request.body_mut() { let body = body.buffer()?; if body.contains(&b'\0') { self.buffer.print(BINARY_SUPPRESSOR)?; } else { self.print_body_text(content_type, &String::from_utf8_lossy(body))?; self.buffer.print("\n")?; } // Breathing room between request and response self.buffer.print("\n")?; self.buffer.flush()?; } Ok(()) } pub fn print_response_body( &mut self, response: &mut Response, encoding: Option<&'static Encoding>, mime: Option<&str>, ) -> anyhow::Result<()> { let starting_time = Instant::now(); let url = response.url().clone(); let content_type = mime.map_or_else(|| get_content_type(response.headers()), ContentType::from); let encoding = encoding.or_else(|| get_charset(response)); let compression_type = get_compression_type(response.headers()); let mut body = decompress(response, compression_type); if!self.buffer.is_terminal() { if (self.color || self.indent_json) && content_type.is_text() { // The user explicitly asked for formatting even though this is // going into a file, and the response is at least supposed to be // text, so decode it // TODO: HTTPie re-encodes output in the original encoding, we don't // encoding_rs::Encoder::encode_from_utf8_to_vec_without_replacement() // and guess_encoding() may help, but it'll require refactoring // The current design is a bit unfortunate because there's no way to // force UTF-8 output without coloring or formatting // Unconditionally decoding is not an option because the body // might not be text at all if self.stream { self.print_body_stream( content_type, &mut decode_stream(&mut body, encoding, &url)?, )?; } else { let mut buf = Vec::new(); body.read_to_end(&mut buf)?; let text = decode_blob_unconditional(&buf, encoding, &url); self.print_body_text(content_type, &text)?; } } else if self.stream { copy_largebuf(&mut body, &mut self.buffer, true)?; } else { let mut buf = Vec::new(); body.read_to_end(&mut buf)?; self.buffer.print(&buf)?; } } else if self.stream { match self .print_body_stream(content_type, &mut decode_stream(&mut body, encoding, &url)?) { Ok(_) => { self.buffer.print("\n")?; } Err(err) if err.kind() == io::ErrorKind::InvalidData => { self.buffer.print(BINARY_SUPPRESSOR)?; } Err(err) => return Err(err.into()), } } else { let mut buf = Vec::new(); body.read_to_end(&mut buf)?; match decode_blob(&buf, encoding, &url) { None => { self.buffer.print(BINARY_SUPPRESSOR)?; } Some(text) => { self.print_body_text(content_type, &text)?; self.buffer.print("\n")?; } }; } self.buffer.flush()?; drop(body); // silence the borrow checker response.meta_mut().content_download_duration = Some(starting_time.elapsed()); Ok(()) } pub fn print_response_meta(&mut self, response: &Response) -> anyhow::Result<()> { let meta = response.meta(); let mut total_elapsed_time = meta.request_duration.as_secs_f64(); if let Some(content_download_duration) = meta.content_download_duration { total_elapsed_time += content_download_duration.as_secs_f64(); } self.buffer .print(format!("Elapsed time: {:.5}s", total_elapsed_time))?; self.buffer.print("\n\n")?; Ok(()) } } enum ContentType { Json, Html, Xml, JavaScript, Css, Text, UrlencodedForm, Multipart, Unknown, } impl ContentType { fn is_text(&self) -> bool { !matches!( self, ContentType::Unknown | ContentType::UrlencodedForm | ContentType::Multipart ) } } impl From<&str> for ContentType { fn from(content_type: &str) -> Self { if content_type.contains("json") { ContentType::Json } else if content_type.contains("html") { ContentType::Html } else if content_type.contains("xml") { ContentType::Xml } else if content_type.contains("multipart") { ContentType::Multipart } else if content_type.contains("x-www-form-urlencoded") { ContentType::UrlencodedForm } else if content_type.contains("javascript") { ContentType::JavaScript } else if content_type.contains("css") { ContentType::Css } else if content_type.contains("text") { // We later check if this one's JSON // HTTPie checks for "json", "javascript" and "text" in one place: // https://github.com/httpie/httpie/blob/a32ad344dd/httpie/output/formatters/json.py#L14 // We have it more spread out but it behaves more or less the same ContentType::Text } else {
headers_to_string
identifier_name
printer.rs
format_options: FormatOptions, } impl Printer { pub fn new( pretty: Pretty, theme: Option<Theme>, stream: bool, buffer: Buffer, format_options: FormatOptions, ) -> Self { let theme = theme.unwrap_or(Theme::Auto); Printer { indent_json: pretty.format(), sort_headers: pretty.format(), color: pretty.color(), stream, theme, buffer, format_options, } } fn get_highlighter(&mut self, syntax: &'static str) -> Highlighter<'_> { Highlighter::new(syntax, self.theme, &mut self.buffer) } fn print_colorized_text(&mut self, text: &str, syntax: &'static str) -> io::Result<()> { self.get_highlighter(syntax).highlight(text) } fn print_syntax_text(&mut self, text: &str, syntax: &'static str) -> io::Result<()> { if self.color { self.print_colorized_text(text, syntax) } else { self.buffer.print(text) } } fn print_json_text(&mut self, text: &str, check_valid: bool) -> io::Result<()> { if!self.indent_json { // We don't have to do anything specialized, so fall back to the generic version return self.print_syntax_text(text, "json"); } if check_valid &&!valid_json(text) { // JSONXF may mess up the text, e.g. by removing whitespace // This is somewhat common as application/json is the default // content type for requests return self.print_syntax_text(text, "json"); } let mut formatter = get_json_formatter(&self.format_options); if self.color { let mut buf = Vec::new(); formatter.format_buf(text.as_bytes(), &mut buf)?; // in principle, buf should already be valid UTF-8, // because JSONXF doesn't mangle it let text = String::from_utf8_lossy(&buf); self.print_colorized_text(&text, "json") } else { formatter.format_buf(text.as_bytes(), &mut self.buffer) } } fn print_body_text(&mut self, content_type: ContentType, body: &str) -> io::Result<()> { match content_type { ContentType::Json => self.print_json_text(body, true), ContentType::Xml => self.print_syntax_text(body, "xml"), ContentType::Html => self.print_syntax_text(body, "html"), ContentType::Css => self.print_syntax_text(body, "css"), // In HTTPie part of this behavior is gated behind the --json flag // But it does JSON formatting even without that flag, so doing // this check unconditionally is fine ContentType::Text | ContentType::JavaScript if valid_json(body) => { self.print_json_text(body, false) } ContentType::JavaScript => self.print_syntax_text(body, "js"), _ => self.buffer.print(body), } } fn print_stream(&mut self, reader: &mut impl Read) -> io::Result<()> { if!self.buffer.is_terminal() { return copy_largebuf(reader, &mut self.buffer, true); } let mut guard = BinaryGuard::new(reader, true); while let Some(lines) = guard.read_lines()? { self.buffer.write_all(lines)?; self.buffer.flush()?; } Ok(()) } fn print_colorized_stream( &mut self, stream: &mut impl Read, syntax: &'static str, ) -> io::Result<()> { let mut guard = BinaryGuard::new(stream, self.buffer.is_terminal()); let mut highlighter = self.get_highlighter(syntax); while let Some(lines) = guard.read_lines()? { for line in lines.split_inclusive(|&b| b == b'\n') { highlighter.highlight_bytes(line)?; } highlighter.flush()?; } Ok(()) } fn print_syntax_stream( &mut self, stream: &mut impl Read, syntax: &'static str, ) -> io::Result<()> { if self.color { self.print_colorized_stream(stream, syntax) } else { self.print_stream(stream) } } fn print_json_stream(&mut self, stream: &mut impl Read) -> io::Result<()> { if!self.indent_json { // We don't have to do anything specialized, so fall back to the generic version self.print_syntax_stream(stream, "json") } else if self.color { let mut guard = BinaryGuard::new(stream, self.buffer.is_terminal()); let mut formatter = get_json_formatter(&self.format_options); let mut highlighter = self.get_highlighter("json"); let mut buf = Vec::new(); while let Some(lines) = guard.read_lines()? { formatter.format_buf(lines, &mut buf)?; for line in buf.split_inclusive(|&b| b == b'\n') { highlighter.highlight_bytes(line)?; } highlighter.flush()?; buf.clear(); } Ok(()) } else { let mut formatter = get_json_formatter(&self.format_options); if!self.buffer.is_terminal() { let mut buf = vec![0; BUFFER_SIZE]; loop { match stream.read(&mut buf) { Ok(0) => return Ok(()), Ok(n) => { formatter.format_buf(&buf[0..n], &mut self.buffer)?; self.buffer.flush()?; } Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => return Err(e), } } } let mut guard = BinaryGuard::new(stream, true); while let Some(lines) = guard.read_lines()? { formatter.format_buf(lines, &mut self.buffer)?; self.buffer.flush()?; } Ok(()) } } fn print_body_stream( &mut self, content_type: ContentType, body: &mut impl Read, ) -> io::Result<()> { match content_type { ContentType::Json => self.print_json_stream(body), ContentType::Xml => self.print_syntax_stream(body, "xml"), ContentType::Html => self.print_syntax_stream(body, "html"), ContentType::Css => self.print_syntax_stream(body, "css"), // print_body_text() has fancy JSON detection, but we can't do that here ContentType::JavaScript => self.print_syntax_stream(body, "js"), _ => self.print_stream(body), } } fn print_headers(&mut self, text: &str) -> io::Result<()> { if self.color { self.print_colorized_text(text, "http") } else { self.buffer.print(text) } } fn headers_to_string(&self, headers: &HeaderMap, version: Version) -> String { let as_titlecase = match version { Version::HTTP_09 | Version::HTTP_10 | Version::HTTP_11 => true, Version::HTTP_2 | Version::HTTP_3 => false, _ => false, }; let mut headers: Vec<(&HeaderName, &HeaderValue)> = headers.iter().collect(); if self.sort_headers { headers.sort_by_key(|(name, _)| name.as_str()); } let mut header_string = String::new(); for (key, value) in headers { if as_titlecase { // Ought to be equivalent to how hyper does it // https://github.com/hyperium/hyper/blob/f46b175bf71b202fbb907c4970b5743881b891e1/src/proto/h1/role.rs#L1332 // Header names are ASCII so it's ok to operate on char instead of u8 let mut prev = '-'; for mut c in key.as_str().chars() { if prev == '-' { c.make_ascii_uppercase(); } header_string.push(c); prev = c; } } else { header_string.push_str(key.as_str()); } header_string.push_str(": "); match value.to_str() { Ok(value) => header_string.push_str(value), #[allow(clippy::format_push_string)] Err(_) => header_string.push_str(&format!("{:?}", value)), } header_string.push('\n'); } header_string.pop(); header_string } pub fn print_separator(&mut self) -> io::Result<()> { self.buffer.print("\n")?; self.buffer.flush()?; Ok(()) } pub fn print_request_headers<T>(&mut self, request: &Request, cookie_jar: &T) -> io::Result<()> where T: CookieStore, { let method = request.method(); let url = request.url(); let query_string = url.query().map_or(String::from(""), |q| ["?", q].concat()); let version = request.version(); let mut headers = request.headers().clone(); headers .entry(ACCEPT) .or_insert_with(|| HeaderValue::from_static("*/*")); if let Some(cookie) = cookie_jar.cookies(url) { headers.insert(COOKIE, cookie); } // See https://github.com/seanmonstar/reqwest/issues/1030 // reqwest and hyper add certain headers, but only in the process of // sending the request, which we haven't done yet if let Some(body) = request.body().and_then(Body::as_bytes) { // Added at https://github.com/seanmonstar/reqwest/blob/e56bd160ba/src/blocking/request.rs#L132 headers .entry(CONTENT_LENGTH) .or_insert_with(|| body.len().into()); } if let Some(host) = request.url().host_str() { // This is incorrect in case of HTTP/2, but we're already assuming // HTTP/1.1 anyway headers.entry(HOST).or_insert_with(|| { // Added at https://github.com/hyperium/hyper/blob/dfa1bb291d/src/client/client.rs#L237 if test_mode() { HeaderValue::from_str("http.mock") } else if let Some(port) = request.url().port() { HeaderValue::from_str(&format!("{}:{}", host, port)) } else { HeaderValue::from_str(host) } .expect("hostname should already be validated/parsed") }); } let request_line = format!("{} {}{} {:?}\n", method, url.path(), query_string, version); let headers = self.headers_to_string(&headers, version); self.print_headers(&(request_line + &headers))?; self.buffer.print("\n\n")?; self.buffer.flush()?; Ok(()) } pub fn print_response_headers(&mut self, response: &Response) -> io::Result<()> { let version = response.version(); let status = response.status(); let headers = response.headers(); let status_line = format!("{:?} {}\n", version, status); let headers = self.headers_to_string(headers, version); self.print_headers(&(status_line + &headers))?; self.buffer.print("\n\n")?; self.buffer.flush()?; Ok(()) } pub fn print_request_body(&mut self, request: &mut Request) -> anyhow::Result<()> { let content_type = get_content_type(request.headers()); if let Some(body) = request.body_mut() { let body = body.buffer()?; if body.contains(&b'\0') { self.buffer.print(BINARY_SUPPRESSOR)?; } else { self.print_body_text(content_type, &String::from_utf8_lossy(body))?; self.buffer.print("\n")?; } // Breathing room between request and response self.buffer.print("\n")?; self.buffer.flush()?; } Ok(()) } pub fn print_response_body( &mut self, response: &mut Response, encoding: Option<&'static Encoding>, mime: Option<&str>, ) -> anyhow::Result<()> { let starting_time = Instant::now(); let url = response.url().clone(); let content_type = mime.map_or_else(|| get_content_type(response.headers()), ContentType::from); let encoding = encoding.or_else(|| get_charset(response)); let compression_type = get_compression_type(response.headers()); let mut body = decompress(response, compression_type); if!self.buffer.is_terminal() { if (self.color || self.indent_json) && content_type.is_text() { // The user explicitly asked for formatting even though this is // going into a file, and the response is at least supposed to be // text, so decode it // TODO: HTTPie re-encodes output in the original encoding, we don't // encoding_rs::Encoder::encode_from_utf8_to_vec_without_replacement() // and guess_encoding() may help, but it'll require refactoring // The current design is a bit unfortunate because there's no way to // force UTF-8 output without coloring or formatting // Unconditionally decoding is not an option because the body // might not be text at all if self.stream { self.print_body_stream( content_type, &mut decode_stream(&mut body, encoding, &url)?, )?; } else { let mut buf = Vec::new(); body.read_to_end(&mut buf)?; let text = decode_blob_unconditional(&buf, encoding, &url); self.print_body_text(content_type, &text)?; } } else if self.stream { copy_largebuf(&mut body, &mut self.buffer, true)?; } else { let mut buf = Vec::new(); body.read_to_end(&mut buf)?; self.buffer.print(&buf)?; } } else if self.stream { match self .print_body_stream(content_type, &mut decode_stream(&mut body, encoding, &url)?) {
self.buffer.print("\n")?; } Err(err) if err.kind() == io::ErrorKind::InvalidData => { self.buffer.print(BINARY_SUPPRESSOR)?; } Err(err) => return Err(err.into()), } } else { let mut buf = Vec::new(); body.read_to_end(&mut buf)?; match decode_blob(&buf, encoding, &url) { None => { self.buffer.print(BINARY_SUPPRESSOR)?; } Some(text) => { self.print_body_text(content_type, &text)?; self.buffer.print("\n")?; } }; } self.buffer.flush()?; drop(body); // silence the borrow checker response.meta_mut().content_download_duration = Some(starting_time.elapsed()); Ok(()) } pub fn print_response_meta(&mut self, response: &Response) -> anyhow::Result<()> { let meta = response.meta(); let mut total_elapsed_time = meta.request_duration.as_secs_f64(); if let Some(content_download_duration) = meta.content_download_duration { total_elapsed_time += content_download_duration.as_secs_f64(); } self.buffer .print(format!("Elapsed time: {:.5}s", total_elapsed_time))?; self.buffer.print("\n\n")?; Ok(()) } } enum ContentType { Json, Html, Xml, JavaScript, Css, Text, UrlencodedForm, Multipart, Unknown, } impl ContentType { fn is_text(&self) -> bool { !matches!( self, ContentType::Unknown | ContentType::UrlencodedForm | ContentType::Multipart ) } } impl From<&str> for ContentType { fn from(content_type: &str) -> Self { if content_type.contains("json") { ContentType::Json } else if content_type.contains("html") { ContentType::Html } else if content_type.contains("xml") { ContentType::Xml } else if content_type.contains("multipart") { ContentType::Multipart } else if content_type.contains("x-www-form-urlencoded") { ContentType::UrlencodedForm } else if content_type.contains("javascript") { ContentType::JavaScript } else if content_type.contains("css") { ContentType::Css } else if content_type.contains("text") { // We later check if this one's JSON // HTTPie checks for "json", "javascript" and "text" in one place: // https://github.com/httpie/httpie/blob/a32ad344dd/httpie/output/formatters/json.py#L14 // We have it more spread out but it behaves more or less the same ContentType::Text } else {
Ok(_) => {
random_line_split
reading.rs
use crate::sector::{ sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap, SectorContentsMapFromBytesError, SectorMetadataChecksummed, }; use parity_scale_codec::Decode; use rayon::prelude::*; use std::mem::ManuallyDrop; use std::simd::Simd; use subspace_core_primitives::crypto::{blake3_hash, Scalar}; use subspace_core_primitives::{ Piece, PieceOffset, Record, RecordCommitment, RecordWitness, SBucket, SectorId, }; use subspace_erasure_coding::ErasureCoding; use subspace_proof_of_space::{Quality, Table, TableGenerator}; use thiserror::Error; use tracing::debug; /// Errors that happen during reading #[derive(Debug, Error)] pub enum ReadingError { /// Wrong sector size #[error("Wrong sector size: expected {expected}, actual {actual}")] WrongSectorSize { /// Expected size in bytes expected: usize, /// Actual size in bytes actual: usize, }, /// Failed to read chunk. /// /// This is an implementation bug, most likely due to mismatch between sector contents map and /// other farming parameters. #[error("Failed to read chunk at location {chunk_location}")] FailedToReadChunk { /// Chunk location chunk_location: usize, }, /// Invalid chunk, possible disk corruption #[error( "Invalid chunk at location {chunk_location} s-bucket {s_bucket} encoded \ {encoded_chunk_used}, possible disk corruption: {error}" )] InvalidChunk { /// S-bucket s_bucket: SBucket, /// Indicates whether chunk was encoded encoded_chunk_used: bool, /// Chunk location chunk_location: usize, /// Lower-level error error: String, }, /// Failed to erasure-decode record #[error("Failed to erasure-decode record at offset {piece_offset}: {error}")] FailedToErasureDecodeRecord { /// Piece offset piece_offset: PieceOffset, /// Lower-level error error: String, }, /// Wrong record size after decoding #[error("Wrong record size after decoding: expected {expected}, actual {actual}")] WrongRecordSizeAfterDecoding { /// Expected size in bytes expected: usize, /// Actual size in bytes actual: usize, }, /// Failed to decode sector contents map #[error("Failed to decode sector contents map: {0}")] FailedToDecodeSectorContentsMap(#[from] SectorContentsMapFromBytesError), /// Checksum mismatch #[error("Checksum mismatch")] ChecksumMismatch, } /// Record contained in the plot #[derive(Debug, Clone)] pub struct PlotRecord { /// Record scalars pub scalars: Box<[Scalar; Record::NUM_CHUNKS]>, /// Record commitment pub commitment: RecordCommitment, /// Record witness pub witness: RecordWitness, } /// Read sector record chunks, only plotted s-buckets are returned (in decoded form) pub fn read_sector_record_chunks<PosTable>( piece_offset: PieceOffset, pieces_in_sector: u16, s_bucket_offsets: &[u32; Record::NUM_S_BUCKETS], sector_contents_map: &SectorContentsMap, pos_table: &PosTable, sector: &[u8], ) -> Result<Box<[Option<Scalar>; Record::NUM_S_BUCKETS]>, ReadingError> where PosTable: Table, { if sector.len()!= sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { expected: sector_size(pieces_in_sector), actual: sector.len(), }); } let mut record_chunks = vec![None; Record::NUM_S_BUCKETS]; record_chunks .par_iter_mut() .zip(sector_contents_map.par_iter_record_chunk_to_plot(piece_offset)) .zip( (u16::from(SBucket::ZERO)..=u16::from(SBucket::MAX)) .into_par_iter() .map(SBucket::from) .zip(s_bucket_offsets.par_iter()), ) .try_for_each( |((maybe_record_chunk, maybe_chunk_details), (s_bucket, &s_bucket_offset))| { let (chunk_offset, encoded_chunk_used) = match maybe_chunk_details { Some(chunk_details) => chunk_details, None => { return Ok(()); } }; let chunk_location = chunk_offset + s_bucket_offset as usize; let mut record_chunk = sector[SectorContentsMap::encoded_size(pieces_in_sector)..] .array_chunks::<{ Scalar::FULL_BYTES }>() .nth(chunk_location) .copied() .ok_or(ReadingError::FailedToReadChunk { chunk_location })?; // Decode chunk if necessary if encoded_chunk_used { let quality = pos_table .find_quality(s_bucket.into()) .expect("encoded_chunk_used implies quality exists for this chunk; qed"); record_chunk = Simd::to_array( Simd::from(record_chunk) ^ Simd::from(quality.create_proof().hash()), ); } maybe_record_chunk.replace(Scalar::try_from(record_chunk).map_err(|error| { ReadingError::InvalidChunk { s_bucket, encoded_chunk_used, chunk_location, error, } })?); Ok::<_, ReadingError>(()) }, )?; let mut record_chunks = ManuallyDrop::new(record_chunks); // SAFETY: Original memory is not dropped, layout is exactly what we need here let record_chunks = unsafe { Box::from_raw(record_chunks.as_mut_ptr() as *mut [Option<Scalar>; Record::NUM_S_BUCKETS]) }; Ok(record_chunks) } /// Given sector record chunks recover extended record chunks (both source and parity) pub fn recover_extended_record_chunks( sector_record_chunks: &[Option<Scalar>; Record::NUM_S_BUCKETS], piece_offset: PieceOffset, erasure_coding: &ErasureCoding, ) -> Result<Box<[Scalar; Record::NUM_S_BUCKETS]>, ReadingError> { // Restore source record scalars let record_chunks = erasure_coding .recover(sector_record_chunks) .map_err(|error| ReadingError::FailedToErasureDecodeRecord { piece_offset, error, })?; // Required for safety invariant below if record_chunks.len()!= Record::NUM_S_BUCKETS { return Err(ReadingError::WrongRecordSizeAfterDecoding { expected: Record::NUM_S_BUCKETS, actual: record_chunks.len(), }); } let mut record_chunks = ManuallyDrop::new(record_chunks); // SAFETY: Original memory is not dropped, size of the data checked above let record_chunks = unsafe { Box::from_raw(record_chunks.as_mut_ptr() as *mut [Scalar; Record::NUM_S_BUCKETS]) }; Ok(record_chunks) } /// Given sector record chunks recover source record chunks in form of an iterator. pub fn recover_source_record_chunks( sector_record_chunks: &[Option<Scalar>; Record::NUM_S_BUCKETS], piece_offset: PieceOffset, erasure_coding: &ErasureCoding, ) -> Result<impl ExactSizeIterator<Item = Scalar>, ReadingError> { // Restore source record scalars let record_chunks = erasure_coding .recover_source(sector_record_chunks) .map_err(|error| ReadingError::FailedToErasureDecodeRecord { piece_offset, error, })?; // Required for safety invariant below if record_chunks.len()!= Record::NUM_CHUNKS
Ok(record_chunks) } /// Read metadata (commitment and witness) for record pub(crate) fn read_record_metadata( piece_offset: PieceOffset, pieces_in_sector: u16, sector: &[u8], ) -> Result<RecordMetadata, ReadingError> { if sector.len()!= sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { expected: sector_size(pieces_in_sector), actual: sector.len(), }); } let sector_metadata_start = SectorContentsMap::encoded_size(pieces_in_sector) + sector_record_chunks_size(pieces_in_sector); // Move to the beginning of the commitment and witness we care about let record_metadata_bytes = &sector[sector_metadata_start..] [RecordMetadata::encoded_size() * usize::from(piece_offset)..]; let record_metadata = RecordMetadata::decode(&mut &*record_metadata_bytes).expect( "Length is correct and checked above, contents doesn't have specific structure to \ it; qed", ); Ok(record_metadata) } /// Read piece from sector pub fn read_piece<PosTable>( piece_offset: PieceOffset, sector_id: &SectorId, sector_metadata: &SectorMetadataChecksummed, sector: &[u8], erasure_coding: &ErasureCoding, table_generator: &mut PosTable::Generator, ) -> Result<Piece, ReadingError> where PosTable: Table, { let pieces_in_sector = sector_metadata.pieces_in_sector; if sector.len()!= sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { expected: sector_size(pieces_in_sector), actual: sector.len(), }); } let sector_contents_map = { SectorContentsMap::from_bytes( &sector[..SectorContentsMap::encoded_size(pieces_in_sector)], pieces_in_sector, )? }; // Restore source record scalars let record_chunks = recover_source_record_chunks( &*read_sector_record_chunks( piece_offset, pieces_in_sector, &sector_metadata.s_bucket_offsets(), &sector_contents_map, &table_generator.generate( &sector_id.derive_evaluation_seed(piece_offset, sector_metadata.history_size), ), sector, )?, piece_offset, erasure_coding, )?; let record_metadata = read_record_metadata(piece_offset, pieces_in_sector, sector)?; let mut piece = Piece::default(); piece .record_mut() .iter_mut() .zip(record_chunks) .for_each(|(output, input)| { *output = input.to_bytes(); }); *piece.commitment_mut() = record_metadata.commitment; *piece.witness_mut() = record_metadata.witness; // Verify checksum let actual_checksum = blake3_hash(piece.as_ref()); if actual_checksum!= record_metadata.piece_checksum { debug!( ?sector_id, %piece_offset, actual_checksum = %hex::encode(actual_checksum), expected_checksum = %hex::encode(record_metadata.piece_checksum), "Hash doesn't match, plotted piece is corrupted" ); return Err(ReadingError::ChecksumMismatch); } Ok(piece) }
{ return Err(ReadingError::WrongRecordSizeAfterDecoding { expected: Record::NUM_CHUNKS, actual: record_chunks.len(), }); }
conditional_block
reading.rs
use crate::sector::{ sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap, SectorContentsMapFromBytesError, SectorMetadataChecksummed, }; use parity_scale_codec::Decode; use rayon::prelude::*; use std::mem::ManuallyDrop; use std::simd::Simd; use subspace_core_primitives::crypto::{blake3_hash, Scalar}; use subspace_core_primitives::{ Piece, PieceOffset, Record, RecordCommitment, RecordWitness, SBucket, SectorId, }; use subspace_erasure_coding::ErasureCoding; use subspace_proof_of_space::{Quality, Table, TableGenerator}; use thiserror::Error; use tracing::debug; /// Errors that happen during reading #[derive(Debug, Error)] pub enum ReadingError { /// Wrong sector size #[error("Wrong sector size: expected {expected}, actual {actual}")] WrongSectorSize { /// Expected size in bytes expected: usize, /// Actual size in bytes actual: usize, }, /// Failed to read chunk. /// /// This is an implementation bug, most likely due to mismatch between sector contents map and /// other farming parameters. #[error("Failed to read chunk at location {chunk_location}")] FailedToReadChunk { /// Chunk location chunk_location: usize, }, /// Invalid chunk, possible disk corruption #[error( "Invalid chunk at location {chunk_location} s-bucket {s_bucket} encoded \ {encoded_chunk_used}, possible disk corruption: {error}" )] InvalidChunk { /// S-bucket s_bucket: SBucket, /// Indicates whether chunk was encoded encoded_chunk_used: bool, /// Chunk location chunk_location: usize, /// Lower-level error error: String, }, /// Failed to erasure-decode record #[error("Failed to erasure-decode record at offset {piece_offset}: {error}")] FailedToErasureDecodeRecord { /// Piece offset piece_offset: PieceOffset, /// Lower-level error error: String, }, /// Wrong record size after decoding #[error("Wrong record size after decoding: expected {expected}, actual {actual}")] WrongRecordSizeAfterDecoding { /// Expected size in bytes expected: usize, /// Actual size in bytes actual: usize, }, /// Failed to decode sector contents map #[error("Failed to decode sector contents map: {0}")] FailedToDecodeSectorContentsMap(#[from] SectorContentsMapFromBytesError), /// Checksum mismatch #[error("Checksum mismatch")] ChecksumMismatch, } /// Record contained in the plot #[derive(Debug, Clone)] pub struct PlotRecord { /// Record scalars pub scalars: Box<[Scalar; Record::NUM_CHUNKS]>, /// Record commitment pub commitment: RecordCommitment, /// Record witness pub witness: RecordWitness, } /// Read sector record chunks, only plotted s-buckets are returned (in decoded form) pub fn read_sector_record_chunks<PosTable>( piece_offset: PieceOffset, pieces_in_sector: u16, s_bucket_offsets: &[u32; Record::NUM_S_BUCKETS], sector_contents_map: &SectorContentsMap, pos_table: &PosTable, sector: &[u8], ) -> Result<Box<[Option<Scalar>; Record::NUM_S_BUCKETS]>, ReadingError> where PosTable: Table, { if sector.len()!= sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { expected: sector_size(pieces_in_sector), actual: sector.len(), }); } let mut record_chunks = vec![None; Record::NUM_S_BUCKETS]; record_chunks .par_iter_mut() .zip(sector_contents_map.par_iter_record_chunk_to_plot(piece_offset)) .zip( (u16::from(SBucket::ZERO)..=u16::from(SBucket::MAX)) .into_par_iter() .map(SBucket::from) .zip(s_bucket_offsets.par_iter()), ) .try_for_each( |((maybe_record_chunk, maybe_chunk_details), (s_bucket, &s_bucket_offset))| { let (chunk_offset, encoded_chunk_used) = match maybe_chunk_details { Some(chunk_details) => chunk_details, None => { return Ok(()); } }; let chunk_location = chunk_offset + s_bucket_offset as usize; let mut record_chunk = sector[SectorContentsMap::encoded_size(pieces_in_sector)..] .array_chunks::<{ Scalar::FULL_BYTES }>() .nth(chunk_location) .copied() .ok_or(ReadingError::FailedToReadChunk { chunk_location })?; // Decode chunk if necessary if encoded_chunk_used { let quality = pos_table .find_quality(s_bucket.into()) .expect("encoded_chunk_used implies quality exists for this chunk; qed"); record_chunk = Simd::to_array( Simd::from(record_chunk) ^ Simd::from(quality.create_proof().hash()),
ReadingError::InvalidChunk { s_bucket, encoded_chunk_used, chunk_location, error, } })?); Ok::<_, ReadingError>(()) }, )?; let mut record_chunks = ManuallyDrop::new(record_chunks); // SAFETY: Original memory is not dropped, layout is exactly what we need here let record_chunks = unsafe { Box::from_raw(record_chunks.as_mut_ptr() as *mut [Option<Scalar>; Record::NUM_S_BUCKETS]) }; Ok(record_chunks) } /// Given sector record chunks recover extended record chunks (both source and parity) pub fn recover_extended_record_chunks( sector_record_chunks: &[Option<Scalar>; Record::NUM_S_BUCKETS], piece_offset: PieceOffset, erasure_coding: &ErasureCoding, ) -> Result<Box<[Scalar; Record::NUM_S_BUCKETS]>, ReadingError> { // Restore source record scalars let record_chunks = erasure_coding .recover(sector_record_chunks) .map_err(|error| ReadingError::FailedToErasureDecodeRecord { piece_offset, error, })?; // Required for safety invariant below if record_chunks.len()!= Record::NUM_S_BUCKETS { return Err(ReadingError::WrongRecordSizeAfterDecoding { expected: Record::NUM_S_BUCKETS, actual: record_chunks.len(), }); } let mut record_chunks = ManuallyDrop::new(record_chunks); // SAFETY: Original memory is not dropped, size of the data checked above let record_chunks = unsafe { Box::from_raw(record_chunks.as_mut_ptr() as *mut [Scalar; Record::NUM_S_BUCKETS]) }; Ok(record_chunks) } /// Given sector record chunks recover source record chunks in form of an iterator. pub fn recover_source_record_chunks( sector_record_chunks: &[Option<Scalar>; Record::NUM_S_BUCKETS], piece_offset: PieceOffset, erasure_coding: &ErasureCoding, ) -> Result<impl ExactSizeIterator<Item = Scalar>, ReadingError> { // Restore source record scalars let record_chunks = erasure_coding .recover_source(sector_record_chunks) .map_err(|error| ReadingError::FailedToErasureDecodeRecord { piece_offset, error, })?; // Required for safety invariant below if record_chunks.len()!= Record::NUM_CHUNKS { return Err(ReadingError::WrongRecordSizeAfterDecoding { expected: Record::NUM_CHUNKS, actual: record_chunks.len(), }); } Ok(record_chunks) } /// Read metadata (commitment and witness) for record pub(crate) fn read_record_metadata( piece_offset: PieceOffset, pieces_in_sector: u16, sector: &[u8], ) -> Result<RecordMetadata, ReadingError> { if sector.len()!= sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { expected: sector_size(pieces_in_sector), actual: sector.len(), }); } let sector_metadata_start = SectorContentsMap::encoded_size(pieces_in_sector) + sector_record_chunks_size(pieces_in_sector); // Move to the beginning of the commitment and witness we care about let record_metadata_bytes = &sector[sector_metadata_start..] [RecordMetadata::encoded_size() * usize::from(piece_offset)..]; let record_metadata = RecordMetadata::decode(&mut &*record_metadata_bytes).expect( "Length is correct and checked above, contents doesn't have specific structure to \ it; qed", ); Ok(record_metadata) } /// Read piece from sector pub fn read_piece<PosTable>( piece_offset: PieceOffset, sector_id: &SectorId, sector_metadata: &SectorMetadataChecksummed, sector: &[u8], erasure_coding: &ErasureCoding, table_generator: &mut PosTable::Generator, ) -> Result<Piece, ReadingError> where PosTable: Table, { let pieces_in_sector = sector_metadata.pieces_in_sector; if sector.len()!= sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { expected: sector_size(pieces_in_sector), actual: sector.len(), }); } let sector_contents_map = { SectorContentsMap::from_bytes( &sector[..SectorContentsMap::encoded_size(pieces_in_sector)], pieces_in_sector, )? }; // Restore source record scalars let record_chunks = recover_source_record_chunks( &*read_sector_record_chunks( piece_offset, pieces_in_sector, &sector_metadata.s_bucket_offsets(), &sector_contents_map, &table_generator.generate( &sector_id.derive_evaluation_seed(piece_offset, sector_metadata.history_size), ), sector, )?, piece_offset, erasure_coding, )?; let record_metadata = read_record_metadata(piece_offset, pieces_in_sector, sector)?; let mut piece = Piece::default(); piece .record_mut() .iter_mut() .zip(record_chunks) .for_each(|(output, input)| { *output = input.to_bytes(); }); *piece.commitment_mut() = record_metadata.commitment; *piece.witness_mut() = record_metadata.witness; // Verify checksum let actual_checksum = blake3_hash(piece.as_ref()); if actual_checksum!= record_metadata.piece_checksum { debug!( ?sector_id, %piece_offset, actual_checksum = %hex::encode(actual_checksum), expected_checksum = %hex::encode(record_metadata.piece_checksum), "Hash doesn't match, plotted piece is corrupted" ); return Err(ReadingError::ChecksumMismatch); } Ok(piece) }
); } maybe_record_chunk.replace(Scalar::try_from(record_chunk).map_err(|error| {
random_line_split
reading.rs
use crate::sector::{ sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap, SectorContentsMapFromBytesError, SectorMetadataChecksummed, }; use parity_scale_codec::Decode; use rayon::prelude::*; use std::mem::ManuallyDrop; use std::simd::Simd; use subspace_core_primitives::crypto::{blake3_hash, Scalar}; use subspace_core_primitives::{ Piece, PieceOffset, Record, RecordCommitment, RecordWitness, SBucket, SectorId, }; use subspace_erasure_coding::ErasureCoding; use subspace_proof_of_space::{Quality, Table, TableGenerator}; use thiserror::Error; use tracing::debug; /// Errors that happen during reading #[derive(Debug, Error)] pub enum ReadingError { /// Wrong sector size #[error("Wrong sector size: expected {expected}, actual {actual}")] WrongSectorSize { /// Expected size in bytes expected: usize, /// Actual size in bytes actual: usize, }, /// Failed to read chunk. /// /// This is an implementation bug, most likely due to mismatch between sector contents map and /// other farming parameters. #[error("Failed to read chunk at location {chunk_location}")] FailedToReadChunk { /// Chunk location chunk_location: usize, }, /// Invalid chunk, possible disk corruption #[error( "Invalid chunk at location {chunk_location} s-bucket {s_bucket} encoded \ {encoded_chunk_used}, possible disk corruption: {error}" )] InvalidChunk { /// S-bucket s_bucket: SBucket, /// Indicates whether chunk was encoded encoded_chunk_used: bool, /// Chunk location chunk_location: usize, /// Lower-level error error: String, }, /// Failed to erasure-decode record #[error("Failed to erasure-decode record at offset {piece_offset}: {error}")] FailedToErasureDecodeRecord { /// Piece offset piece_offset: PieceOffset, /// Lower-level error error: String, }, /// Wrong record size after decoding #[error("Wrong record size after decoding: expected {expected}, actual {actual}")] WrongRecordSizeAfterDecoding { /// Expected size in bytes expected: usize, /// Actual size in bytes actual: usize, }, /// Failed to decode sector contents map #[error("Failed to decode sector contents map: {0}")] FailedToDecodeSectorContentsMap(#[from] SectorContentsMapFromBytesError), /// Checksum mismatch #[error("Checksum mismatch")] ChecksumMismatch, } /// Record contained in the plot #[derive(Debug, Clone)] pub struct PlotRecord { /// Record scalars pub scalars: Box<[Scalar; Record::NUM_CHUNKS]>, /// Record commitment pub commitment: RecordCommitment, /// Record witness pub witness: RecordWitness, } /// Read sector record chunks, only plotted s-buckets are returned (in decoded form) pub fn read_sector_record_chunks<PosTable>( piece_offset: PieceOffset, pieces_in_sector: u16, s_bucket_offsets: &[u32; Record::NUM_S_BUCKETS], sector_contents_map: &SectorContentsMap, pos_table: &PosTable, sector: &[u8], ) -> Result<Box<[Option<Scalar>; Record::NUM_S_BUCKETS]>, ReadingError> where PosTable: Table, { if sector.len()!= sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { expected: sector_size(pieces_in_sector), actual: sector.len(), }); } let mut record_chunks = vec![None; Record::NUM_S_BUCKETS]; record_chunks .par_iter_mut() .zip(sector_contents_map.par_iter_record_chunk_to_plot(piece_offset)) .zip( (u16::from(SBucket::ZERO)..=u16::from(SBucket::MAX)) .into_par_iter() .map(SBucket::from) .zip(s_bucket_offsets.par_iter()), ) .try_for_each( |((maybe_record_chunk, maybe_chunk_details), (s_bucket, &s_bucket_offset))| { let (chunk_offset, encoded_chunk_used) = match maybe_chunk_details { Some(chunk_details) => chunk_details, None => { return Ok(()); } }; let chunk_location = chunk_offset + s_bucket_offset as usize; let mut record_chunk = sector[SectorContentsMap::encoded_size(pieces_in_sector)..] .array_chunks::<{ Scalar::FULL_BYTES }>() .nth(chunk_location) .copied() .ok_or(ReadingError::FailedToReadChunk { chunk_location })?; // Decode chunk if necessary if encoded_chunk_used { let quality = pos_table .find_quality(s_bucket.into()) .expect("encoded_chunk_used implies quality exists for this chunk; qed"); record_chunk = Simd::to_array( Simd::from(record_chunk) ^ Simd::from(quality.create_proof().hash()), ); } maybe_record_chunk.replace(Scalar::try_from(record_chunk).map_err(|error| { ReadingError::InvalidChunk { s_bucket, encoded_chunk_used, chunk_location, error, } })?); Ok::<_, ReadingError>(()) }, )?; let mut record_chunks = ManuallyDrop::new(record_chunks); // SAFETY: Original memory is not dropped, layout is exactly what we need here let record_chunks = unsafe { Box::from_raw(record_chunks.as_mut_ptr() as *mut [Option<Scalar>; Record::NUM_S_BUCKETS]) }; Ok(record_chunks) } /// Given sector record chunks recover extended record chunks (both source and parity) pub fn recover_extended_record_chunks( sector_record_chunks: &[Option<Scalar>; Record::NUM_S_BUCKETS], piece_offset: PieceOffset, erasure_coding: &ErasureCoding, ) -> Result<Box<[Scalar; Record::NUM_S_BUCKETS]>, ReadingError> { // Restore source record scalars let record_chunks = erasure_coding .recover(sector_record_chunks) .map_err(|error| ReadingError::FailedToErasureDecodeRecord { piece_offset, error, })?; // Required for safety invariant below if record_chunks.len()!= Record::NUM_S_BUCKETS { return Err(ReadingError::WrongRecordSizeAfterDecoding { expected: Record::NUM_S_BUCKETS, actual: record_chunks.len(), }); } let mut record_chunks = ManuallyDrop::new(record_chunks); // SAFETY: Original memory is not dropped, size of the data checked above let record_chunks = unsafe { Box::from_raw(record_chunks.as_mut_ptr() as *mut [Scalar; Record::NUM_S_BUCKETS]) }; Ok(record_chunks) } /// Given sector record chunks recover source record chunks in form of an iterator. pub fn recover_source_record_chunks( sector_record_chunks: &[Option<Scalar>; Record::NUM_S_BUCKETS], piece_offset: PieceOffset, erasure_coding: &ErasureCoding, ) -> Result<impl ExactSizeIterator<Item = Scalar>, ReadingError> { // Restore source record scalars let record_chunks = erasure_coding .recover_source(sector_record_chunks) .map_err(|error| ReadingError::FailedToErasureDecodeRecord { piece_offset, error, })?; // Required for safety invariant below if record_chunks.len()!= Record::NUM_CHUNKS { return Err(ReadingError::WrongRecordSizeAfterDecoding { expected: Record::NUM_CHUNKS, actual: record_chunks.len(), }); } Ok(record_chunks) } /// Read metadata (commitment and witness) for record pub(crate) fn read_record_metadata( piece_offset: PieceOffset, pieces_in_sector: u16, sector: &[u8], ) -> Result<RecordMetadata, ReadingError> { if sector.len()!= sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { expected: sector_size(pieces_in_sector), actual: sector.len(), }); } let sector_metadata_start = SectorContentsMap::encoded_size(pieces_in_sector) + sector_record_chunks_size(pieces_in_sector); // Move to the beginning of the commitment and witness we care about let record_metadata_bytes = &sector[sector_metadata_start..] [RecordMetadata::encoded_size() * usize::from(piece_offset)..]; let record_metadata = RecordMetadata::decode(&mut &*record_metadata_bytes).expect( "Length is correct and checked above, contents doesn't have specific structure to \ it; qed", ); Ok(record_metadata) } /// Read piece from sector pub fn
<PosTable>( piece_offset: PieceOffset, sector_id: &SectorId, sector_metadata: &SectorMetadataChecksummed, sector: &[u8], erasure_coding: &ErasureCoding, table_generator: &mut PosTable::Generator, ) -> Result<Piece, ReadingError> where PosTable: Table, { let pieces_in_sector = sector_metadata.pieces_in_sector; if sector.len()!= sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { expected: sector_size(pieces_in_sector), actual: sector.len(), }); } let sector_contents_map = { SectorContentsMap::from_bytes( &sector[..SectorContentsMap::encoded_size(pieces_in_sector)], pieces_in_sector, )? }; // Restore source record scalars let record_chunks = recover_source_record_chunks( &*read_sector_record_chunks( piece_offset, pieces_in_sector, &sector_metadata.s_bucket_offsets(), &sector_contents_map, &table_generator.generate( &sector_id.derive_evaluation_seed(piece_offset, sector_metadata.history_size), ), sector, )?, piece_offset, erasure_coding, )?; let record_metadata = read_record_metadata(piece_offset, pieces_in_sector, sector)?; let mut piece = Piece::default(); piece .record_mut() .iter_mut() .zip(record_chunks) .for_each(|(output, input)| { *output = input.to_bytes(); }); *piece.commitment_mut() = record_metadata.commitment; *piece.witness_mut() = record_metadata.witness; // Verify checksum let actual_checksum = blake3_hash(piece.as_ref()); if actual_checksum!= record_metadata.piece_checksum { debug!( ?sector_id, %piece_offset, actual_checksum = %hex::encode(actual_checksum), expected_checksum = %hex::encode(record_metadata.piece_checksum), "Hash doesn't match, plotted piece is corrupted" ); return Err(ReadingError::ChecksumMismatch); } Ok(piece) }
read_piece
identifier_name
reading.rs
use crate::sector::{ sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap, SectorContentsMapFromBytesError, SectorMetadataChecksummed, }; use parity_scale_codec::Decode; use rayon::prelude::*; use std::mem::ManuallyDrop; use std::simd::Simd; use subspace_core_primitives::crypto::{blake3_hash, Scalar}; use subspace_core_primitives::{ Piece, PieceOffset, Record, RecordCommitment, RecordWitness, SBucket, SectorId, }; use subspace_erasure_coding::ErasureCoding; use subspace_proof_of_space::{Quality, Table, TableGenerator}; use thiserror::Error; use tracing::debug; /// Errors that happen during reading #[derive(Debug, Error)] pub enum ReadingError { /// Wrong sector size #[error("Wrong sector size: expected {expected}, actual {actual}")] WrongSectorSize { /// Expected size in bytes expected: usize, /// Actual size in bytes actual: usize, }, /// Failed to read chunk. /// /// This is an implementation bug, most likely due to mismatch between sector contents map and /// other farming parameters. #[error("Failed to read chunk at location {chunk_location}")] FailedToReadChunk { /// Chunk location chunk_location: usize, }, /// Invalid chunk, possible disk corruption #[error( "Invalid chunk at location {chunk_location} s-bucket {s_bucket} encoded \ {encoded_chunk_used}, possible disk corruption: {error}" )] InvalidChunk { /// S-bucket s_bucket: SBucket, /// Indicates whether chunk was encoded encoded_chunk_used: bool, /// Chunk location chunk_location: usize, /// Lower-level error error: String, }, /// Failed to erasure-decode record #[error("Failed to erasure-decode record at offset {piece_offset}: {error}")] FailedToErasureDecodeRecord { /// Piece offset piece_offset: PieceOffset, /// Lower-level error error: String, }, /// Wrong record size after decoding #[error("Wrong record size after decoding: expected {expected}, actual {actual}")] WrongRecordSizeAfterDecoding { /// Expected size in bytes expected: usize, /// Actual size in bytes actual: usize, }, /// Failed to decode sector contents map #[error("Failed to decode sector contents map: {0}")] FailedToDecodeSectorContentsMap(#[from] SectorContentsMapFromBytesError), /// Checksum mismatch #[error("Checksum mismatch")] ChecksumMismatch, } /// Record contained in the plot #[derive(Debug, Clone)] pub struct PlotRecord { /// Record scalars pub scalars: Box<[Scalar; Record::NUM_CHUNKS]>, /// Record commitment pub commitment: RecordCommitment, /// Record witness pub witness: RecordWitness, } /// Read sector record chunks, only plotted s-buckets are returned (in decoded form) pub fn read_sector_record_chunks<PosTable>( piece_offset: PieceOffset, pieces_in_sector: u16, s_bucket_offsets: &[u32; Record::NUM_S_BUCKETS], sector_contents_map: &SectorContentsMap, pos_table: &PosTable, sector: &[u8], ) -> Result<Box<[Option<Scalar>; Record::NUM_S_BUCKETS]>, ReadingError> where PosTable: Table, { if sector.len()!= sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { expected: sector_size(pieces_in_sector), actual: sector.len(), }); } let mut record_chunks = vec![None; Record::NUM_S_BUCKETS]; record_chunks .par_iter_mut() .zip(sector_contents_map.par_iter_record_chunk_to_plot(piece_offset)) .zip( (u16::from(SBucket::ZERO)..=u16::from(SBucket::MAX)) .into_par_iter() .map(SBucket::from) .zip(s_bucket_offsets.par_iter()), ) .try_for_each( |((maybe_record_chunk, maybe_chunk_details), (s_bucket, &s_bucket_offset))| { let (chunk_offset, encoded_chunk_used) = match maybe_chunk_details { Some(chunk_details) => chunk_details, None => { return Ok(()); } }; let chunk_location = chunk_offset + s_bucket_offset as usize; let mut record_chunk = sector[SectorContentsMap::encoded_size(pieces_in_sector)..] .array_chunks::<{ Scalar::FULL_BYTES }>() .nth(chunk_location) .copied() .ok_or(ReadingError::FailedToReadChunk { chunk_location })?; // Decode chunk if necessary if encoded_chunk_used { let quality = pos_table .find_quality(s_bucket.into()) .expect("encoded_chunk_used implies quality exists for this chunk; qed"); record_chunk = Simd::to_array( Simd::from(record_chunk) ^ Simd::from(quality.create_proof().hash()), ); } maybe_record_chunk.replace(Scalar::try_from(record_chunk).map_err(|error| { ReadingError::InvalidChunk { s_bucket, encoded_chunk_used, chunk_location, error, } })?); Ok::<_, ReadingError>(()) }, )?; let mut record_chunks = ManuallyDrop::new(record_chunks); // SAFETY: Original memory is not dropped, layout is exactly what we need here let record_chunks = unsafe { Box::from_raw(record_chunks.as_mut_ptr() as *mut [Option<Scalar>; Record::NUM_S_BUCKETS]) }; Ok(record_chunks) } /// Given sector record chunks recover extended record chunks (both source and parity) pub fn recover_extended_record_chunks( sector_record_chunks: &[Option<Scalar>; Record::NUM_S_BUCKETS], piece_offset: PieceOffset, erasure_coding: &ErasureCoding, ) -> Result<Box<[Scalar; Record::NUM_S_BUCKETS]>, ReadingError> { // Restore source record scalars let record_chunks = erasure_coding .recover(sector_record_chunks) .map_err(|error| ReadingError::FailedToErasureDecodeRecord { piece_offset, error, })?; // Required for safety invariant below if record_chunks.len()!= Record::NUM_S_BUCKETS { return Err(ReadingError::WrongRecordSizeAfterDecoding { expected: Record::NUM_S_BUCKETS, actual: record_chunks.len(), }); } let mut record_chunks = ManuallyDrop::new(record_chunks); // SAFETY: Original memory is not dropped, size of the data checked above let record_chunks = unsafe { Box::from_raw(record_chunks.as_mut_ptr() as *mut [Scalar; Record::NUM_S_BUCKETS]) }; Ok(record_chunks) } /// Given sector record chunks recover source record chunks in form of an iterator. pub fn recover_source_record_chunks( sector_record_chunks: &[Option<Scalar>; Record::NUM_S_BUCKETS], piece_offset: PieceOffset, erasure_coding: &ErasureCoding, ) -> Result<impl ExactSizeIterator<Item = Scalar>, ReadingError>
/// Read metadata (commitment and witness) for record pub(crate) fn read_record_metadata( piece_offset: PieceOffset, pieces_in_sector: u16, sector: &[u8], ) -> Result<RecordMetadata, ReadingError> { if sector.len()!= sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { expected: sector_size(pieces_in_sector), actual: sector.len(), }); } let sector_metadata_start = SectorContentsMap::encoded_size(pieces_in_sector) + sector_record_chunks_size(pieces_in_sector); // Move to the beginning of the commitment and witness we care about let record_metadata_bytes = &sector[sector_metadata_start..] [RecordMetadata::encoded_size() * usize::from(piece_offset)..]; let record_metadata = RecordMetadata::decode(&mut &*record_metadata_bytes).expect( "Length is correct and checked above, contents doesn't have specific structure to \ it; qed", ); Ok(record_metadata) } /// Read piece from sector pub fn read_piece<PosTable>( piece_offset: PieceOffset, sector_id: &SectorId, sector_metadata: &SectorMetadataChecksummed, sector: &[u8], erasure_coding: &ErasureCoding, table_generator: &mut PosTable::Generator, ) -> Result<Piece, ReadingError> where PosTable: Table, { let pieces_in_sector = sector_metadata.pieces_in_sector; if sector.len()!= sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { expected: sector_size(pieces_in_sector), actual: sector.len(), }); } let sector_contents_map = { SectorContentsMap::from_bytes( &sector[..SectorContentsMap::encoded_size(pieces_in_sector)], pieces_in_sector, )? }; // Restore source record scalars let record_chunks = recover_source_record_chunks( &*read_sector_record_chunks( piece_offset, pieces_in_sector, &sector_metadata.s_bucket_offsets(), &sector_contents_map, &table_generator.generate( &sector_id.derive_evaluation_seed(piece_offset, sector_metadata.history_size), ), sector, )?, piece_offset, erasure_coding, )?; let record_metadata = read_record_metadata(piece_offset, pieces_in_sector, sector)?; let mut piece = Piece::default(); piece .record_mut() .iter_mut() .zip(record_chunks) .for_each(|(output, input)| { *output = input.to_bytes(); }); *piece.commitment_mut() = record_metadata.commitment; *piece.witness_mut() = record_metadata.witness; // Verify checksum let actual_checksum = blake3_hash(piece.as_ref()); if actual_checksum!= record_metadata.piece_checksum { debug!( ?sector_id, %piece_offset, actual_checksum = %hex::encode(actual_checksum), expected_checksum = %hex::encode(record_metadata.piece_checksum), "Hash doesn't match, plotted piece is corrupted" ); return Err(ReadingError::ChecksumMismatch); } Ok(piece) }
{ // Restore source record scalars let record_chunks = erasure_coding .recover_source(sector_record_chunks) .map_err(|error| ReadingError::FailedToErasureDecodeRecord { piece_offset, error, })?; // Required for safety invariant below if record_chunks.len() != Record::NUM_CHUNKS { return Err(ReadingError::WrongRecordSizeAfterDecoding { expected: Record::NUM_CHUNKS, actual: record_chunks.len(), }); } Ok(record_chunks) }
identifier_body
graph.rs
use cairo; use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags, WidgetExt}; use std::cell::RefCell; use gdk::{self, WindowExt}; use std::rc::Rc; use std::time::Instant; use color::Color; use utils::RotateVec; const LEFT_WIDTH: f64 = 31.; pub struct Graph { elapsed: Instant, colors: Vec<Color>, pub data: Vec<RotateVec<f64>>, vertical_layout: gtk::Box, scroll_layout: gtk::ScrolledWindow, horizontal_layout: gtk::Box, pub area: DrawingArea, max: Option<RefCell<f64>>, keep_max: bool, display_labels: RefCell<bool>, initial_diff: Option<i32>, label_callbacks: Option<Box<Fn(f64) -> [String; 4]>>, labels_layout_width: i32, } impl Graph { // If `max` is `None`, the graph will expect values between 0 and 1. // // If `keep_max` is set to `true`, then this value will never go down, meaning that graphs // won't rescale down. It is not taken into account if `max` is `None`. pub fn new(max: Option<f64>, keep_max: bool) -> Graph { let g = Graph { elapsed: Instant::now(), colors: vec!(), data: vec!(), vertical_layout: gtk::Box::new(gtk::Orientation::Vertical, 0), scroll_layout: gtk::ScrolledWindow::new(None, None), horizontal_layout: gtk::Box::new(gtk::Orientation::Horizontal, 0), area: DrawingArea::new(), max: if let Some(max) = max { Some(RefCell::new(max)) } else { None }, keep_max, display_labels: RefCell::new(true), initial_diff: None, label_callbacks: None, labels_layout_width: 80, }; g.scroll_layout.set_min_content_width(g.labels_layout_width); g.scroll_layout.add(&g.vertical_layout); g.horizontal_layout.pack_start(&g.area, true, true, 0); g.horizontal_layout.pack_start(&g.scroll_layout, false, true, 10); g.horizontal_layout.set_margin_left(5); g } /// Changes the size of the layout containing labels (the one on the right). pub fn set_labels_width(&mut self, labels_layout_width: u32) { self.scroll_layout.set_min_content_width(labels_layout_width as i32); self.labels_layout_width = labels_layout_width as i32; } pub fn set_label_callbacks(&mut self, label_callbacks: Option<Box<Fn(f64) -> [String; 4]>>) { self.label_callbacks = label_callbacks; } pub fn set_display_labels(&self, display_labels: bool) { *self.display_labels.borrow_mut() = display_labels; if display_labels == true { self.scroll_layout.show_all(); } else { self.scroll_layout.hide(); } self.invalidate(); } pub fn hide(&self) { self.horizontal_layout.hide(); } pub fn show_all(&self) { self.horizontal_layout.show_all(); if *self.display_labels.borrow() == false { self.scroll_layout.hide(); } } pub fn attach_to(&self, to: &gtk::Box) { to.add(&self.horizontal_layout); } pub fn
(&mut self, d: RotateVec<f64>, s: &str, override_color: Option<usize>) { let c = if let Some(over) = override_color { Color::generate(over) } else { Color::generate(self.data.len() + 11) }; let l = gtk::Label::new(Some(s)); l.override_color(StateFlags::from_bits(0).expect("from_bits failed"), &c.to_gdk()); self.vertical_layout.add(&l); self.colors.push(c); self.data.push(d); } fn draw_labels(&self, c: &cairo::Context, max: f64, height: f64) { if let Some(ref call) = self.label_callbacks { let entries = call(max); let font_size = 8.; c.set_source_rgb(0., 0., 0.); c.set_font_size(font_size); c.move_to(LEFT_WIDTH - 4. - entries[0].len() as f64 * 4., font_size); c.show_text(entries[0].as_str()); c.move_to(LEFT_WIDTH - 4. - entries[1].len() as f64 * 4., height / 2.); c.show_text(entries[1].as_str()); c.move_to(LEFT_WIDTH - 4. - entries[2].len() as f64 * 4., height - 2.); c.show_text(entries[2].as_str()); c.move_to(font_size - 1., height / 2. + 4. * (entries[3].len() >> 1) as f64); c.rotate(-1.5708); c.show_text(entries[3].as_str()); } } pub fn draw(&self, c: &cairo::Context, width: f64, height: f64) { let x_start = if self.label_callbacks.is_some() { LEFT_WIDTH } else { 1.0 }; c.set_source_rgb(0.95, 0.95, 0.95); c.rectangle(x_start, 1.0, width - 1.0, height - 2.0); c.fill(); c.set_source_rgb(0.0, 0.0, 0.0); c.set_line_width(1.0); c.move_to(x_start, 0.0); c.line_to(x_start, height); c.move_to(width, 0.0); c.line_to(width, height); c.move_to(x_start, 0.0); c.line_to(width, 0.0); c.move_to(x_start, height); c.line_to(width, height); // For now it's always 60 seconds. let time = 60.; let elapsed = self.elapsed.elapsed().as_secs() % 5; let x_step = (width - 2.0 - x_start) * 5.0 / (time as f64); let mut current = width - elapsed as f64 * (x_step / 5.0) - 1.0; if x_step < 0.1 { c.stroke(); return; } while current > x_start { c.move_to(current, 0.0); c.line_to(current, height); current -= x_step; } let step = height / 10.0; current = step - 1.0; while current < height - 1. { c.move_to(x_start, current); c.line_to(width - 1.0, current); current += step; } c.stroke(); if let Some(ref self_max) = self.max { let mut max = if self.keep_max { *self_max.borrow() } else { 1. }; let len = self.data[0].len() - 1; for x in 0..len { for entry in &self.data { if entry[x] > max { max = entry[x]; } } } if!self.data.is_empty() &&!self.data[0].is_empty() { let len = self.data[0].len() - 1; let step = (width - 2.0 - x_start) / len as f64; current = x_start + 1.0; let mut index = len; while current > x_start && index > 0 { for (entry, color) in self.data.iter().zip(self.colors.iter()) { c.set_source_rgb(color.r, color.g, color.b); c.move_to(current + step, height - entry[index - 1] / max * (height - 1.0)); c.line_to(current, height - entry[index] / max * (height - 1.0)); c.stroke(); } current += step; index -= 1; } } if max > *self_max.borrow() ||!self.keep_max { *self_max.borrow_mut() = max; } self.draw_labels(c, max, height); } else if!self.data.is_empty() &&!self.data[0].is_empty() { let len = self.data[0].len() - 1; let step = (width - 2.0 - x_start) / (len as f64); current = x_start + 1.0; let mut index = len; while current > x_start && index > 0 { for (entry, color) in self.data.iter().zip(self.colors.iter()) { c.set_source_rgb(color.r, color.g, color.b); c.move_to(current + step, height - entry[index - 1] * (height - 1.0)); c.line_to(current, height - entry[index] * (height - 1.0)); c.stroke(); } current += step; index -= 1; } // To be called in last to avoid having to restore state (rotation). self.draw_labels(c, 100., height); } } pub fn invalidate(&self) { if let Some(t_win) = self.area.get_window() { let (x, y) = self.area.translate_coordinates(&self.area, 0, 0) .expect("translate_coordinates failed"); let rect = gdk::Rectangle { x: x, y: y, width: self.area.get_allocated_width(), height: self.area.get_allocated_height() }; t_win.invalidate_rect(&rect, true); } } pub fn send_size_request(&self, width: Option<i32>) { let mut width = match width { Some(w) => w, None => { if let Some(parent) = self.area.get_parent() { parent.get_allocation().width - parent.get_margin_left() - parent.get_margin_right() } else { eprintln!("<Graph::send_size_request> A parent is required if no width is \ provided..."); return; } } }; // This condition is to avoid having a graph with a bigger width than the window. if let Some(top) = self.area.get_toplevel() { let max_width = top.get_allocation().width; if width > max_width { width = max_width; } } self.area.set_size_request( if *self.display_labels.borrow() == true { width - if width >= self.labels_layout_width { self.labels_layout_width } else { width } } else { width }, 200); } } pub trait Connecter { fn connect_to_window_events(&self); } impl Connecter for Rc<RefCell<Graph>> { fn connect_to_window_events(&self) { let s = self.clone(); if let Some(parent) = self.borrow().horizontal_layout.get_toplevel() { // TODO: ugly way to resize drawing area, I should find a better way parent.connect_configure_event(move |w, _| { let need_diff = s.borrow().initial_diff.is_none(); if need_diff { let mut s = s.borrow_mut(); let parent_width = if let Some(p) = s.area.get_parent() { p.get_allocation().width } else { 0 }; s.initial_diff = Some(w.get_allocation().width - parent_width); } s.borrow().send_size_request(None); false }); } else { eprintln!("This method needs to be called *after* it has been put inside a window"); } } }
push
identifier_name
graph.rs
use cairo; use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags, WidgetExt}; use std::cell::RefCell; use gdk::{self, WindowExt}; use std::rc::Rc; use std::time::Instant; use color::Color; use utils::RotateVec; const LEFT_WIDTH: f64 = 31.; pub struct Graph { elapsed: Instant, colors: Vec<Color>, pub data: Vec<RotateVec<f64>>, vertical_layout: gtk::Box, scroll_layout: gtk::ScrolledWindow, horizontal_layout: gtk::Box, pub area: DrawingArea, max: Option<RefCell<f64>>, keep_max: bool, display_labels: RefCell<bool>, initial_diff: Option<i32>, label_callbacks: Option<Box<Fn(f64) -> [String; 4]>>, labels_layout_width: i32, } impl Graph { // If `max` is `None`, the graph will expect values between 0 and 1. // // If `keep_max` is set to `true`, then this value will never go down, meaning that graphs // won't rescale down. It is not taken into account if `max` is `None`. pub fn new(max: Option<f64>, keep_max: bool) -> Graph { let g = Graph { elapsed: Instant::now(), colors: vec!(), data: vec!(), vertical_layout: gtk::Box::new(gtk::Orientation::Vertical, 0), scroll_layout: gtk::ScrolledWindow::new(None, None), horizontal_layout: gtk::Box::new(gtk::Orientation::Horizontal, 0), area: DrawingArea::new(), max: if let Some(max) = max { Some(RefCell::new(max)) } else { None }, keep_max, display_labels: RefCell::new(true), initial_diff: None, label_callbacks: None, labels_layout_width: 80, }; g.scroll_layout.set_min_content_width(g.labels_layout_width); g.scroll_layout.add(&g.vertical_layout); g.horizontal_layout.pack_start(&g.area, true, true, 0); g.horizontal_layout.pack_start(&g.scroll_layout, false, true, 10); g.horizontal_layout.set_margin_left(5); g } /// Changes the size of the layout containing labels (the one on the right). pub fn set_labels_width(&mut self, labels_layout_width: u32) { self.scroll_layout.set_min_content_width(labels_layout_width as i32); self.labels_layout_width = labels_layout_width as i32; } pub fn set_label_callbacks(&mut self, label_callbacks: Option<Box<Fn(f64) -> [String; 4]>>) { self.label_callbacks = label_callbacks; } pub fn set_display_labels(&self, display_labels: bool) { *self.display_labels.borrow_mut() = display_labels; if display_labels == true { self.scroll_layout.show_all(); } else { self.scroll_layout.hide(); } self.invalidate(); } pub fn hide(&self) { self.horizontal_layout.hide(); } pub fn show_all(&self) { self.horizontal_layout.show_all(); if *self.display_labels.borrow() == false { self.scroll_layout.hide(); } } pub fn attach_to(&self, to: &gtk::Box) { to.add(&self.horizontal_layout); } pub fn push(&mut self, d: RotateVec<f64>, s: &str, override_color: Option<usize>) { let c = if let Some(over) = override_color { Color::generate(over) } else { Color::generate(self.data.len() + 11) }; let l = gtk::Label::new(Some(s)); l.override_color(StateFlags::from_bits(0).expect("from_bits failed"), &c.to_gdk()); self.vertical_layout.add(&l); self.colors.push(c); self.data.push(d); } fn draw_labels(&self, c: &cairo::Context, max: f64, height: f64) { if let Some(ref call) = self.label_callbacks { let entries = call(max); let font_size = 8.; c.set_source_rgb(0., 0., 0.); c.set_font_size(font_size); c.move_to(LEFT_WIDTH - 4. - entries[0].len() as f64 * 4., font_size); c.show_text(entries[0].as_str()); c.move_to(LEFT_WIDTH - 4. - entries[1].len() as f64 * 4., height / 2.); c.show_text(entries[1].as_str()); c.move_to(LEFT_WIDTH - 4. - entries[2].len() as f64 * 4., height - 2.); c.show_text(entries[2].as_str()); c.move_to(font_size - 1., height / 2. + 4. * (entries[3].len() >> 1) as f64); c.rotate(-1.5708); c.show_text(entries[3].as_str()); } } pub fn draw(&self, c: &cairo::Context, width: f64, height: f64) { let x_start = if self.label_callbacks.is_some() { LEFT_WIDTH } else { 1.0 }; c.set_source_rgb(0.95, 0.95, 0.95); c.rectangle(x_start, 1.0, width - 1.0, height - 2.0); c.fill(); c.set_source_rgb(0.0, 0.0, 0.0); c.set_line_width(1.0); c.move_to(x_start, 0.0); c.line_to(x_start, height); c.move_to(width, 0.0); c.line_to(width, height); c.move_to(x_start, 0.0); c.line_to(width, 0.0); c.move_to(x_start, height); c.line_to(width, height); // For now it's always 60 seconds. let time = 60.; let elapsed = self.elapsed.elapsed().as_secs() % 5; let x_step = (width - 2.0 - x_start) * 5.0 / (time as f64); let mut current = width - elapsed as f64 * (x_step / 5.0) - 1.0; if x_step < 0.1 { c.stroke(); return; } while current > x_start { c.move_to(current, 0.0); c.line_to(current, height); current -= x_step; } let step = height / 10.0; current = step - 1.0; while current < height - 1. { c.move_to(x_start, current); c.line_to(width - 1.0, current); current += step; } c.stroke(); if let Some(ref self_max) = self.max { let mut max = if self.keep_max { *self_max.borrow() } else { 1. }; let len = self.data[0].len() - 1; for x in 0..len { for entry in &self.data { if entry[x] > max { max = entry[x]; } } } if!self.data.is_empty() &&!self.data[0].is_empty() { let len = self.data[0].len() - 1; let step = (width - 2.0 - x_start) / len as f64; current = x_start + 1.0; let mut index = len; while current > x_start && index > 0 { for (entry, color) in self.data.iter().zip(self.colors.iter()) { c.set_source_rgb(color.r, color.g, color.b); c.move_to(current + step, height - entry[index - 1] / max * (height - 1.0)); c.line_to(current, height - entry[index] / max * (height - 1.0)); c.stroke(); } current += step; index -= 1; } } if max > *self_max.borrow() ||!self.keep_max { *self_max.borrow_mut() = max; } self.draw_labels(c, max, height); } else if!self.data.is_empty() &&!self.data[0].is_empty() { let len = self.data[0].len() - 1; let step = (width - 2.0 - x_start) / (len as f64); current = x_start + 1.0; let mut index = len; while current > x_start && index > 0 { for (entry, color) in self.data.iter().zip(self.colors.iter()) { c.set_source_rgb(color.r, color.g, color.b); c.move_to(current + step, height - entry[index - 1] * (height - 1.0)); c.line_to(current, height - entry[index] * (height - 1.0)); c.stroke(); } current += step; index -= 1; } // To be called in last to avoid having to restore state (rotation). self.draw_labels(c, 100., height); }
pub fn invalidate(&self) { if let Some(t_win) = self.area.get_window() { let (x, y) = self.area.translate_coordinates(&self.area, 0, 0) .expect("translate_coordinates failed"); let rect = gdk::Rectangle { x: x, y: y, width: self.area.get_allocated_width(), height: self.area.get_allocated_height() }; t_win.invalidate_rect(&rect, true); } } pub fn send_size_request(&self, width: Option<i32>) { let mut width = match width { Some(w) => w, None => { if let Some(parent) = self.area.get_parent() { parent.get_allocation().width - parent.get_margin_left() - parent.get_margin_right() } else { eprintln!("<Graph::send_size_request> A parent is required if no width is \ provided..."); return; } } }; // This condition is to avoid having a graph with a bigger width than the window. if let Some(top) = self.area.get_toplevel() { let max_width = top.get_allocation().width; if width > max_width { width = max_width; } } self.area.set_size_request( if *self.display_labels.borrow() == true { width - if width >= self.labels_layout_width { self.labels_layout_width } else { width } } else { width }, 200); } } pub trait Connecter { fn connect_to_window_events(&self); } impl Connecter for Rc<RefCell<Graph>> { fn connect_to_window_events(&self) { let s = self.clone(); if let Some(parent) = self.borrow().horizontal_layout.get_toplevel() { // TODO: ugly way to resize drawing area, I should find a better way parent.connect_configure_event(move |w, _| { let need_diff = s.borrow().initial_diff.is_none(); if need_diff { let mut s = s.borrow_mut(); let parent_width = if let Some(p) = s.area.get_parent() { p.get_allocation().width } else { 0 }; s.initial_diff = Some(w.get_allocation().width - parent_width); } s.borrow().send_size_request(None); false }); } else { eprintln!("This method needs to be called *after* it has been put inside a window"); } } }
}
random_line_split
graph.rs
use cairo; use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags, WidgetExt}; use std::cell::RefCell; use gdk::{self, WindowExt}; use std::rc::Rc; use std::time::Instant; use color::Color; use utils::RotateVec; const LEFT_WIDTH: f64 = 31.; pub struct Graph { elapsed: Instant, colors: Vec<Color>, pub data: Vec<RotateVec<f64>>, vertical_layout: gtk::Box, scroll_layout: gtk::ScrolledWindow, horizontal_layout: gtk::Box, pub area: DrawingArea, max: Option<RefCell<f64>>, keep_max: bool, display_labels: RefCell<bool>, initial_diff: Option<i32>, label_callbacks: Option<Box<Fn(f64) -> [String; 4]>>, labels_layout_width: i32, } impl Graph { // If `max` is `None`, the graph will expect values between 0 and 1. // // If `keep_max` is set to `true`, then this value will never go down, meaning that graphs // won't rescale down. It is not taken into account if `max` is `None`. pub fn new(max: Option<f64>, keep_max: bool) -> Graph { let g = Graph { elapsed: Instant::now(), colors: vec!(), data: vec!(), vertical_layout: gtk::Box::new(gtk::Orientation::Vertical, 0), scroll_layout: gtk::ScrolledWindow::new(None, None), horizontal_layout: gtk::Box::new(gtk::Orientation::Horizontal, 0), area: DrawingArea::new(), max: if let Some(max) = max { Some(RefCell::new(max)) } else { None }, keep_max, display_labels: RefCell::new(true), initial_diff: None, label_callbacks: None, labels_layout_width: 80, }; g.scroll_layout.set_min_content_width(g.labels_layout_width); g.scroll_layout.add(&g.vertical_layout); g.horizontal_layout.pack_start(&g.area, true, true, 0); g.horizontal_layout.pack_start(&g.scroll_layout, false, true, 10); g.horizontal_layout.set_margin_left(5); g } /// Changes the size of the layout containing labels (the one on the right). pub fn set_labels_width(&mut self, labels_layout_width: u32) { self.scroll_layout.set_min_content_width(labels_layout_width as i32); self.labels_layout_width = labels_layout_width as i32; } pub fn set_label_callbacks(&mut self, label_callbacks: Option<Box<Fn(f64) -> [String; 4]>>) { self.label_callbacks = label_callbacks; } pub fn set_display_labels(&self, display_labels: bool) { *self.display_labels.borrow_mut() = display_labels; if display_labels == true { self.scroll_layout.show_all(); } else { self.scroll_layout.hide(); } self.invalidate(); } pub fn hide(&self) { self.horizontal_layout.hide(); } pub fn show_all(&self) { self.horizontal_layout.show_all(); if *self.display_labels.borrow() == false { self.scroll_layout.hide(); } } pub fn attach_to(&self, to: &gtk::Box) { to.add(&self.horizontal_layout); } pub fn push(&mut self, d: RotateVec<f64>, s: &str, override_color: Option<usize>) { let c = if let Some(over) = override_color { Color::generate(over) } else { Color::generate(self.data.len() + 11) }; let l = gtk::Label::new(Some(s)); l.override_color(StateFlags::from_bits(0).expect("from_bits failed"), &c.to_gdk()); self.vertical_layout.add(&l); self.colors.push(c); self.data.push(d); } fn draw_labels(&self, c: &cairo::Context, max: f64, height: f64) { if let Some(ref call) = self.label_callbacks { let entries = call(max); let font_size = 8.; c.set_source_rgb(0., 0., 0.); c.set_font_size(font_size); c.move_to(LEFT_WIDTH - 4. - entries[0].len() as f64 * 4., font_size); c.show_text(entries[0].as_str()); c.move_to(LEFT_WIDTH - 4. - entries[1].len() as f64 * 4., height / 2.); c.show_text(entries[1].as_str()); c.move_to(LEFT_WIDTH - 4. - entries[2].len() as f64 * 4., height - 2.); c.show_text(entries[2].as_str()); c.move_to(font_size - 1., height / 2. + 4. * (entries[3].len() >> 1) as f64); c.rotate(-1.5708); c.show_text(entries[3].as_str()); } } pub fn draw(&self, c: &cairo::Context, width: f64, height: f64) { let x_start = if self.label_callbacks.is_some() { LEFT_WIDTH } else { 1.0 }; c.set_source_rgb(0.95, 0.95, 0.95); c.rectangle(x_start, 1.0, width - 1.0, height - 2.0); c.fill(); c.set_source_rgb(0.0, 0.0, 0.0); c.set_line_width(1.0); c.move_to(x_start, 0.0); c.line_to(x_start, height); c.move_to(width, 0.0); c.line_to(width, height); c.move_to(x_start, 0.0); c.line_to(width, 0.0); c.move_to(x_start, height); c.line_to(width, height); // For now it's always 60 seconds. let time = 60.; let elapsed = self.elapsed.elapsed().as_secs() % 5; let x_step = (width - 2.0 - x_start) * 5.0 / (time as f64); let mut current = width - elapsed as f64 * (x_step / 5.0) - 1.0; if x_step < 0.1 { c.stroke(); return; } while current > x_start { c.move_to(current, 0.0); c.line_to(current, height); current -= x_step; } let step = height / 10.0; current = step - 1.0; while current < height - 1. { c.move_to(x_start, current); c.line_to(width - 1.0, current); current += step; } c.stroke(); if let Some(ref self_max) = self.max { let mut max = if self.keep_max { *self_max.borrow() } else { 1. }; let len = self.data[0].len() - 1; for x in 0..len { for entry in &self.data { if entry[x] > max { max = entry[x]; } } } if!self.data.is_empty() &&!self.data[0].is_empty() { let len = self.data[0].len() - 1; let step = (width - 2.0 - x_start) / len as f64; current = x_start + 1.0; let mut index = len; while current > x_start && index > 0 { for (entry, color) in self.data.iter().zip(self.colors.iter()) { c.set_source_rgb(color.r, color.g, color.b); c.move_to(current + step, height - entry[index - 1] / max * (height - 1.0)); c.line_to(current, height - entry[index] / max * (height - 1.0)); c.stroke(); } current += step; index -= 1; } } if max > *self_max.borrow() ||!self.keep_max { *self_max.borrow_mut() = max; } self.draw_labels(c, max, height); } else if!self.data.is_empty() &&!self.data[0].is_empty() { let len = self.data[0].len() - 1; let step = (width - 2.0 - x_start) / (len as f64); current = x_start + 1.0; let mut index = len; while current > x_start && index > 0 { for (entry, color) in self.data.iter().zip(self.colors.iter()) { c.set_source_rgb(color.r, color.g, color.b); c.move_to(current + step, height - entry[index - 1] * (height - 1.0)); c.line_to(current, height - entry[index] * (height - 1.0)); c.stroke(); } current += step; index -= 1; } // To be called in last to avoid having to restore state (rotation). self.draw_labels(c, 100., height); } } pub fn invalidate(&self) { if let Some(t_win) = self.area.get_window() { let (x, y) = self.area.translate_coordinates(&self.area, 0, 0) .expect("translate_coordinates failed"); let rect = gdk::Rectangle { x: x, y: y, width: self.area.get_allocated_width(), height: self.area.get_allocated_height() }; t_win.invalidate_rect(&rect, true); } } pub fn send_size_request(&self, width: Option<i32>) { let mut width = match width { Some(w) => w, None => { if let Some(parent) = self.area.get_parent() { parent.get_allocation().width - parent.get_margin_left() - parent.get_margin_right() } else { eprintln!("<Graph::send_size_request> A parent is required if no width is \ provided..."); return; } } }; // This condition is to avoid having a graph with a bigger width than the window. if let Some(top) = self.area.get_toplevel() { let max_width = top.get_allocation().width; if width > max_width { width = max_width; } } self.area.set_size_request( if *self.display_labels.borrow() == true { width - if width >= self.labels_layout_width { self.labels_layout_width } else { width } } else { width }, 200); } } pub trait Connecter { fn connect_to_window_events(&self); } impl Connecter for Rc<RefCell<Graph>> { fn connect_to_window_events(&self)
} } }
{ let s = self.clone(); if let Some(parent) = self.borrow().horizontal_layout.get_toplevel() { // TODO: ugly way to resize drawing area, I should find a better way parent.connect_configure_event(move |w, _| { let need_diff = s.borrow().initial_diff.is_none(); if need_diff { let mut s = s.borrow_mut(); let parent_width = if let Some(p) = s.area.get_parent() { p.get_allocation().width } else { 0 }; s.initial_diff = Some(w.get_allocation().width - parent_width); } s.borrow().send_size_request(None); false }); } else { eprintln!("This method needs to be called *after* it has been put inside a window");
identifier_body
graph.rs
use cairo; use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags, WidgetExt}; use std::cell::RefCell; use gdk::{self, WindowExt}; use std::rc::Rc; use std::time::Instant; use color::Color; use utils::RotateVec; const LEFT_WIDTH: f64 = 31.; pub struct Graph { elapsed: Instant, colors: Vec<Color>, pub data: Vec<RotateVec<f64>>, vertical_layout: gtk::Box, scroll_layout: gtk::ScrolledWindow, horizontal_layout: gtk::Box, pub area: DrawingArea, max: Option<RefCell<f64>>, keep_max: bool, display_labels: RefCell<bool>, initial_diff: Option<i32>, label_callbacks: Option<Box<Fn(f64) -> [String; 4]>>, labels_layout_width: i32, } impl Graph { // If `max` is `None`, the graph will expect values between 0 and 1. // // If `keep_max` is set to `true`, then this value will never go down, meaning that graphs // won't rescale down. It is not taken into account if `max` is `None`. pub fn new(max: Option<f64>, keep_max: bool) -> Graph { let g = Graph { elapsed: Instant::now(), colors: vec!(), data: vec!(), vertical_layout: gtk::Box::new(gtk::Orientation::Vertical, 0), scroll_layout: gtk::ScrolledWindow::new(None, None), horizontal_layout: gtk::Box::new(gtk::Orientation::Horizontal, 0), area: DrawingArea::new(), max: if let Some(max) = max { Some(RefCell::new(max)) } else { None }, keep_max, display_labels: RefCell::new(true), initial_diff: None, label_callbacks: None, labels_layout_width: 80, }; g.scroll_layout.set_min_content_width(g.labels_layout_width); g.scroll_layout.add(&g.vertical_layout); g.horizontal_layout.pack_start(&g.area, true, true, 0); g.horizontal_layout.pack_start(&g.scroll_layout, false, true, 10); g.horizontal_layout.set_margin_left(5); g } /// Changes the size of the layout containing labels (the one on the right). pub fn set_labels_width(&mut self, labels_layout_width: u32) { self.scroll_layout.set_min_content_width(labels_layout_width as i32); self.labels_layout_width = labels_layout_width as i32; } pub fn set_label_callbacks(&mut self, label_callbacks: Option<Box<Fn(f64) -> [String; 4]>>) { self.label_callbacks = label_callbacks; } pub fn set_display_labels(&self, display_labels: bool) { *self.display_labels.borrow_mut() = display_labels; if display_labels == true { self.scroll_layout.show_all(); } else { self.scroll_layout.hide(); } self.invalidate(); } pub fn hide(&self) { self.horizontal_layout.hide(); } pub fn show_all(&self) { self.horizontal_layout.show_all(); if *self.display_labels.borrow() == false { self.scroll_layout.hide(); } } pub fn attach_to(&self, to: &gtk::Box) { to.add(&self.horizontal_layout); } pub fn push(&mut self, d: RotateVec<f64>, s: &str, override_color: Option<usize>) { let c = if let Some(over) = override_color { Color::generate(over) } else { Color::generate(self.data.len() + 11) }; let l = gtk::Label::new(Some(s)); l.override_color(StateFlags::from_bits(0).expect("from_bits failed"), &c.to_gdk()); self.vertical_layout.add(&l); self.colors.push(c); self.data.push(d); } fn draw_labels(&self, c: &cairo::Context, max: f64, height: f64) { if let Some(ref call) = self.label_callbacks { let entries = call(max); let font_size = 8.; c.set_source_rgb(0., 0., 0.); c.set_font_size(font_size); c.move_to(LEFT_WIDTH - 4. - entries[0].len() as f64 * 4., font_size); c.show_text(entries[0].as_str()); c.move_to(LEFT_WIDTH - 4. - entries[1].len() as f64 * 4., height / 2.); c.show_text(entries[1].as_str()); c.move_to(LEFT_WIDTH - 4. - entries[2].len() as f64 * 4., height - 2.); c.show_text(entries[2].as_str()); c.move_to(font_size - 1., height / 2. + 4. * (entries[3].len() >> 1) as f64); c.rotate(-1.5708); c.show_text(entries[3].as_str()); } } pub fn draw(&self, c: &cairo::Context, width: f64, height: f64) { let x_start = if self.label_callbacks.is_some() { LEFT_WIDTH } else { 1.0 }; c.set_source_rgb(0.95, 0.95, 0.95); c.rectangle(x_start, 1.0, width - 1.0, height - 2.0); c.fill(); c.set_source_rgb(0.0, 0.0, 0.0); c.set_line_width(1.0); c.move_to(x_start, 0.0); c.line_to(x_start, height); c.move_to(width, 0.0); c.line_to(width, height); c.move_to(x_start, 0.0); c.line_to(width, 0.0); c.move_to(x_start, height); c.line_to(width, height); // For now it's always 60 seconds. let time = 60.; let elapsed = self.elapsed.elapsed().as_secs() % 5; let x_step = (width - 2.0 - x_start) * 5.0 / (time as f64); let mut current = width - elapsed as f64 * (x_step / 5.0) - 1.0; if x_step < 0.1 { c.stroke(); return; } while current > x_start { c.move_to(current, 0.0); c.line_to(current, height); current -= x_step; } let step = height / 10.0; current = step - 1.0; while current < height - 1. { c.move_to(x_start, current); c.line_to(width - 1.0, current); current += step; } c.stroke(); if let Some(ref self_max) = self.max { let mut max = if self.keep_max { *self_max.borrow() } else { 1. }; let len = self.data[0].len() - 1; for x in 0..len { for entry in &self.data { if entry[x] > max { max = entry[x]; } } } if!self.data.is_empty() &&!self.data[0].is_empty() { let len = self.data[0].len() - 1; let step = (width - 2.0 - x_start) / len as f64; current = x_start + 1.0; let mut index = len; while current > x_start && index > 0 { for (entry, color) in self.data.iter().zip(self.colors.iter()) { c.set_source_rgb(color.r, color.g, color.b); c.move_to(current + step, height - entry[index - 1] / max * (height - 1.0)); c.line_to(current, height - entry[index] / max * (height - 1.0)); c.stroke(); } current += step; index -= 1; } } if max > *self_max.borrow() ||!self.keep_max { *self_max.borrow_mut() = max; } self.draw_labels(c, max, height); } else if!self.data.is_empty() &&!self.data[0].is_empty() { let len = self.data[0].len() - 1; let step = (width - 2.0 - x_start) / (len as f64); current = x_start + 1.0; let mut index = len; while current > x_start && index > 0 { for (entry, color) in self.data.iter().zip(self.colors.iter()) { c.set_source_rgb(color.r, color.g, color.b); c.move_to(current + step, height - entry[index - 1] * (height - 1.0)); c.line_to(current, height - entry[index] * (height - 1.0)); c.stroke(); } current += step; index -= 1; } // To be called in last to avoid having to restore state (rotation). self.draw_labels(c, 100., height); } } pub fn invalidate(&self) { if let Some(t_win) = self.area.get_window() { let (x, y) = self.area.translate_coordinates(&self.area, 0, 0) .expect("translate_coordinates failed"); let rect = gdk::Rectangle { x: x, y: y, width: self.area.get_allocated_width(), height: self.area.get_allocated_height() }; t_win.invalidate_rect(&rect, true); } } pub fn send_size_request(&self, width: Option<i32>) { let mut width = match width { Some(w) => w, None => { if let Some(parent) = self.area.get_parent() { parent.get_allocation().width - parent.get_margin_left() - parent.get_margin_right() } else { eprintln!("<Graph::send_size_request> A parent is required if no width is \ provided..."); return; } } }; // This condition is to avoid having a graph with a bigger width than the window. if let Some(top) = self.area.get_toplevel() { let max_width = top.get_allocation().width; if width > max_width { width = max_width; } } self.area.set_size_request( if *self.display_labels.borrow() == true { width - if width >= self.labels_layout_width { self.labels_layout_width } else { width } } else { width }, 200); } } pub trait Connecter { fn connect_to_window_events(&self); } impl Connecter for Rc<RefCell<Graph>> { fn connect_to_window_events(&self) { let s = self.clone(); if let Some(parent) = self.borrow().horizontal_layout.get_toplevel()
else { eprintln!("This method needs to be called *after* it has been put inside a window"); } } }
{ // TODO: ugly way to resize drawing area, I should find a better way parent.connect_configure_event(move |w, _| { let need_diff = s.borrow().initial_diff.is_none(); if need_diff { let mut s = s.borrow_mut(); let parent_width = if let Some(p) = s.area.get_parent() { p.get_allocation().width } else { 0 }; s.initial_diff = Some(w.get_allocation().width - parent_width); } s.borrow().send_size_request(None); false }); }
conditional_block
windows_aligned_file_reader.rs
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ use std::sync::Arc; use std::time::Duration; use std::{ptr, thread}; use crossbeam::sync::ShardedLock; use hashbrown::HashMap; use once_cell::sync::Lazy; use platform::file_handle::{AccessMode, ShareMode}; use platform::{ file_handle::FileHandle, file_io::{get_queued_completion_status, read_file_to_slice}, io_completion_port::IOCompletionPort, }; use winapi::{ shared::{basetsd::ULONG_PTR, minwindef::DWORD}, um::minwinbase::OVERLAPPED, }; use crate::common::{ANNError, ANNResult}; use crate::model::IOContext; pub const MAX_IO_CONCURRENCY: usize = 128; // To do: explore the optimal value for this. The current value is taken from C++ code. pub const FILE_ATTRIBUTE_READONLY: DWORD = 0x00000001; pub const IO_COMPLETION_TIMEOUT: DWORD = u32::MAX; // Infinite timeout. pub const DISK_IO_ALIGNMENT: usize = 512; pub const ASYNC_IO_COMPLETION_CHECK_INTERVAL: Duration = Duration::from_micros(5); /// Aligned read struct for disk IO, it takes the ownership of the AlignedBoxedSlice and returns the AlignedBoxWithSlice data immutably. pub struct AlignedRead<'a, T> { /// where to read from /// offset needs to be aligned with DISK_IO_ALIGNMENT offset: u64, /// where to read into /// aligned_buf and its len need to be aligned with DISK_IO_ALIGNMENT aligned_buf: &'a mut [T], } impl<'a, T> AlignedRead<'a, T> { pub fn new(offset: u64, aligned_buf: &'a mut [T]) -> ANNResult<Self> { Self::assert_is_aligned(offset as usize)?; Self::assert_is_aligned(std::mem::size_of_val(aligned_buf))?; Ok(Self { offset, aligned_buf, }) } fn assert_is_aligned(val: usize) -> ANNResult<()> { match val % DISK_IO_ALIGNMENT { 0 => Ok(()), _ => Err(ANNError::log_disk_io_request_alignment_error(format!( "The offset or length of AlignedRead request is not {} bytes aligned", DISK_IO_ALIGNMENT ))), } } pub fn aligned_buf(&self) -> &[T] { self.aligned_buf } } pub struct WindowsAlignedFileReader { file_name: String, // ctx_map is the mapping from thread id to io context. It is hashmap behind a sharded lock to allow concurrent access from multiple threads. // ShardedLock: shardedlock provides an implementation of a reader-writer lock that offers concurrent read access to the shared data while allowing exclusive write access. // It achieves better scalability by dividing the shared data into multiple shards, and each with its own internal lock. // Multiple threads can read from different shards simultaneously, reducing contention. // https://docs.rs/crossbeam/0.8.2/crossbeam/sync/struct.ShardedLock.html // Comparing to RwLock, ShardedLock provides higher concurrency for read operations and is suitable for read heavy workloads. // The value of the hashmap is an Arc<IOContext> to allow immutable access to IOContext with automatic reference counting. ctx_map: Lazy<ShardedLock<HashMap<thread::ThreadId, Arc<IOContext>>>>, } impl WindowsAlignedFileReader { pub fn new(fname: &str) -> ANNResult<Self> { let reader: WindowsAlignedFileReader = WindowsAlignedFileReader { file_name: fname.to_string(), ctx_map: Lazy::new(|| ShardedLock::new(HashMap::new())), }; reader.register_thread()?; Ok(reader) } // Register the io context for a thread if it hasn't been registered. pub fn register_thread(&self) -> ANNResult<()> { let mut ctx_map = self.ctx_map.write().map_err(|_| { ANNError::log_lock_poison_error("unable to acquire read lock on ctx_map".to_string()) })?; let id = thread::current().id(); if ctx_map.contains_key(&id) { println!( "Warning:: Duplicate registration for thread_id : {:?}. Directly call get_ctx to get the thread context data.", id); return Ok(()); } let mut ctx = IOContext::new(); match unsafe { FileHandle::new(&self.file_name, AccessMode::Read, ShareMode::Read) } { Ok(file_handle) => ctx.file_handle = file_handle, Err(err) => { return Err(ANNError::log_io_error(err)); } } // Create a io completion port for the file handle, later it will be used to get the completion status. match IOCompletionPort::new(&ctx.file_handle, None, 0, 0) { Ok(io_completion_port) => ctx.io_completion_port = io_completion_port, Err(err) => { return Err(ANNError::log_io_error(err)); } } ctx_map.insert(id, Arc::new(ctx)); Ok(()) } // Get the reference counted io context for the current thread. pub fn get_ctx(&self) -> ANNResult<Arc<IOContext>> { let ctx_map = self.ctx_map.read().map_err(|_| { ANNError::log_lock_poison_error("unable to acquire read lock on ctx_map".to_string()) })?; let id = thread::current().id(); match ctx_map.get(&id) { Some(ctx) => Ok(Arc::clone(ctx)), None => Err(ANNError::log_index_error(format!( "unable to find IOContext for thread_id {:?}", id ))), } } // Read the data from the file by sending concurrent io requests in batches. pub fn read<T>(&self, read_requests: &mut [AlignedRead<T>], ctx: &IOContext) -> ANNResult<()> { let n_requests = read_requests.len(); let n_batches = (n_requests + MAX_IO_CONCURRENCY - 1) / MAX_IO_CONCURRENCY; let mut overlapped_in_out = vec![unsafe { std::mem::zeroed::<OVERLAPPED>() }; MAX_IO_CONCURRENCY]; for batch_idx in 0..n_batches { let batch_start = MAX_IO_CONCURRENCY * batch_idx; let batch_size = std::cmp::min(n_requests - batch_start, MAX_IO_CONCURRENCY); for j in 0..batch_size { let req = &mut read_requests[batch_start + j]; let os = &mut overlapped_in_out[j]; match unsafe { read_file_to_slice(&ctx.file_handle, req.aligned_buf, os, req.offset) } { Ok(_) => {} Err(error) => { return Err(ANNError::IOError { err: (error) }); } } } let mut n_read: DWORD = 0; let mut n_complete: u64 = 0; let mut completion_key: ULONG_PTR = 0; let mut lp_os: *mut OVERLAPPED = ptr::null_mut(); while n_complete < batch_size as u64 { match unsafe { get_queued_completion_status( &ctx.io_completion_port, &mut n_read, &mut completion_key, &mut lp_os, IO_COMPLETION_TIMEOUT, ) } { // An IO request completed. Ok(true) => n_complete += 1, // No IO request completed, continue to wait. Ok(false) => { thread::sleep(ASYNC_IO_COMPLETION_CHECK_INTERVAL); } // An error ocurred. Err(error) => return Err(ANNError::IOError { err: (error) }), } } } Ok(()) } } #[cfg(test)] mod tests { use std::{fs::File, io::BufReader}; use bincode::deserialize_from; use serde::{Deserialize, Serialize}; use crate::{common::AlignedBoxWithSlice, model::SECTOR_LEN}; use super::*; pub const TEST_INDEX_PATH: &str = "./tests/data/disk_index_siftsmall_learn_256pts_R4_L50_A1.2_alligned_reader_test.index"; pub const TRUTH_NODE_DATA_PATH: &str = "./tests/data/disk_index_node_data_aligned_reader_truth.bin"; #[derive(Debug, Serialize, Deserialize)] struct NodeData { num_neighbors: u32, coordinates: Vec<f32>, neighbors: Vec<u32>, } impl PartialEq for NodeData { fn eq(&self, other: &Self) -> bool { self.num_neighbors == other.num_neighbors && self.coordinates == other.coordinates && self.neighbors == other.neighbors } } #[test] fn test_new_aligned_file_reader() { // Replace "test_file_path" with actual file path let result = WindowsAlignedFileReader::new(TEST_INDEX_PATH); assert!(result.is_ok()); let reader = result.unwrap(); assert_eq!(reader.file_name, TEST_INDEX_PATH); } #[test] fn test_read() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let ctx = reader.get_ctx().unwrap(); let read_length = 512; // adjust according to your logic let num_read = 10; let mut aligned_mem = AlignedBoxWithSlice::<u8>::new(read_length * num_read, 512).unwrap(); // create and add AlignedReads to the vector let mut mem_slices = aligned_mem .split_into_nonoverlapping_mut_slices(0..aligned_mem.len(), read_length) .unwrap(); let mut aligned_reads: Vec<AlignedRead<'_, u8>> = mem_slices .iter_mut() .enumerate() .map(|(i, slice)| { let offset = (i * read_length) as u64; AlignedRead::new(offset, slice).unwrap() }) .collect(); let result = reader.read(&mut aligned_reads, &ctx); assert!(result.is_ok()); } #[test] fn test_read_disk_index_by_sector() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let ctx = reader.get_ctx().unwrap(); let read_length = SECTOR_LEN; // adjust according to your logic let num_sector = 10; let mut aligned_mem = AlignedBoxWithSlice::<u8>::new(read_length * num_sector, 512).unwrap(); // Each slice will be used as the buffer for a read request of a sector. let mut mem_slices = aligned_mem .split_into_nonoverlapping_mut_slices(0..aligned_mem.len(), read_length) .unwrap(); let mut aligned_reads: Vec<AlignedRead<'_, u8>> = mem_slices .iter_mut() .enumerate() .map(|(sector_id, slice)| { let offset = (sector_id * read_length) as u64; AlignedRead::new(offset, slice).unwrap() }) .collect(); let result = reader.read(&mut aligned_reads, &ctx); assert!(result.is_ok()); aligned_reads.iter().for_each(|read| { assert_eq!(read.aligned_buf.len(), SECTOR_LEN); }); let disk_layout_meta = reconstruct_disk_meta(aligned_reads[0].aligned_buf); assert!(disk_layout_meta.len() > 9); let dims = disk_layout_meta[1]; let num_pts = disk_layout_meta[0]; let max_node_len = disk_layout_meta[3]; let max_num_nodes_per_sector = disk_layout_meta[4]; assert!(max_node_len * max_num_nodes_per_sector < SECTOR_LEN as u64); let num_nbrs_start = (dims as usize) * std::mem::size_of::<f32>(); let nbrs_buf_start = num_nbrs_start + std::mem::size_of::<u32>(); let mut node_data_array = Vec::with_capacity(max_num_nodes_per_sector as usize * 9); // Only validate the first 9 sectors with graph nodes. (1..9).for_each(|sector_id| { let sector_data = &mem_slices[sector_id]; for node_data in sector_data.chunks_exact(max_node_len as usize) { // Extract coordinates data from the start of the node_data let coordinates_end = (dims as usize) * std::mem::size_of::<f32>(); let coordinates = node_data[0..coordinates_end]
// Extract number of neighbors from the node_data let neighbors_num = u32::from_le_bytes( node_data[num_nbrs_start..nbrs_buf_start] .try_into() .unwrap(), ); let nbors_buf_end = nbrs_buf_start + (neighbors_num as usize) * std::mem::size_of::<u32>(); // Extract neighbors from the node data. let mut neighbors = Vec::new(); for nbors_data in node_data[nbrs_buf_start..nbors_buf_end] .chunks_exact(std::mem::size_of::<u32>()) { let nbors_id = u32::from_le_bytes(nbors_data.try_into().unwrap()); assert!(nbors_id < num_pts as u32); neighbors.push(nbors_id); } // Create NodeData struct and push it to the node_data_array node_data_array.push(NodeData { num_neighbors: neighbors_num, coordinates, neighbors, }); } }); // Compare that each node read from the disk index are expected. let node_data_truth_file = File::open(TRUTH_NODE_DATA_PATH).unwrap(); let reader = BufReader::new(node_data_truth_file); let node_data_vec: Vec<NodeData> = deserialize_from(reader).unwrap(); for (node_from_node_data_file, node_from_disk_index) in node_data_vec.iter().zip(node_data_array.iter()) { // Verify that the NodeData from the file is equal to the NodeData in node_data_array assert_eq!(node_from_node_data_file, node_from_disk_index); } } #[test] fn test_read_fail_invalid_file() { let reader = WindowsAlignedFileReader::new("/invalid_path"); assert!(reader.is_err()); } #[test] fn test_read_no_requests() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let ctx = reader.get_ctx().unwrap(); let mut read_requests = Vec::<AlignedRead<u8>>::new(); let result = reader.read(&mut read_requests, &ctx); assert!(result.is_ok()); } #[test] fn test_get_ctx() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let result = reader.get_ctx(); assert!(result.is_ok()); } #[test] fn test_register_thread() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let result = reader.register_thread(); assert!(result.is_ok()); } fn reconstruct_disk_meta(buffer: &[u8]) -> Vec<u64> { let size_of_u64 = std::mem::size_of::<u64>(); let num_values = buffer.len() / size_of_u64; let mut disk_layout_meta = Vec::with_capacity(num_values); let meta_data = &buffer[8..]; for chunk in meta_data.chunks_exact(size_of_u64) { let value = u64::from_le_bytes(chunk.try_into().unwrap()); disk_layout_meta.push(value); } disk_layout_meta } }
.chunks_exact(std::mem::size_of::<f32>()) .map(|chunk| f32::from_le_bytes(chunk.try_into().unwrap())) .collect();
random_line_split
windows_aligned_file_reader.rs
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ use std::sync::Arc; use std::time::Duration; use std::{ptr, thread}; use crossbeam::sync::ShardedLock; use hashbrown::HashMap; use once_cell::sync::Lazy; use platform::file_handle::{AccessMode, ShareMode}; use platform::{ file_handle::FileHandle, file_io::{get_queued_completion_status, read_file_to_slice}, io_completion_port::IOCompletionPort, }; use winapi::{ shared::{basetsd::ULONG_PTR, minwindef::DWORD}, um::minwinbase::OVERLAPPED, }; use crate::common::{ANNError, ANNResult}; use crate::model::IOContext; pub const MAX_IO_CONCURRENCY: usize = 128; // To do: explore the optimal value for this. The current value is taken from C++ code. pub const FILE_ATTRIBUTE_READONLY: DWORD = 0x00000001; pub const IO_COMPLETION_TIMEOUT: DWORD = u32::MAX; // Infinite timeout. pub const DISK_IO_ALIGNMENT: usize = 512; pub const ASYNC_IO_COMPLETION_CHECK_INTERVAL: Duration = Duration::from_micros(5); /// Aligned read struct for disk IO, it takes the ownership of the AlignedBoxedSlice and returns the AlignedBoxWithSlice data immutably. pub struct AlignedRead<'a, T> { /// where to read from /// offset needs to be aligned with DISK_IO_ALIGNMENT offset: u64, /// where to read into /// aligned_buf and its len need to be aligned with DISK_IO_ALIGNMENT aligned_buf: &'a mut [T], } impl<'a, T> AlignedRead<'a, T> { pub fn new(offset: u64, aligned_buf: &'a mut [T]) -> ANNResult<Self> { Self::assert_is_aligned(offset as usize)?; Self::assert_is_aligned(std::mem::size_of_val(aligned_buf))?; Ok(Self { offset, aligned_buf, }) } fn assert_is_aligned(val: usize) -> ANNResult<()> { match val % DISK_IO_ALIGNMENT { 0 => Ok(()), _ => Err(ANNError::log_disk_io_request_alignment_error(format!( "The offset or length of AlignedRead request is not {} bytes aligned", DISK_IO_ALIGNMENT ))), } } pub fn aligned_buf(&self) -> &[T] { self.aligned_buf } } pub struct WindowsAlignedFileReader { file_name: String, // ctx_map is the mapping from thread id to io context. It is hashmap behind a sharded lock to allow concurrent access from multiple threads. // ShardedLock: shardedlock provides an implementation of a reader-writer lock that offers concurrent read access to the shared data while allowing exclusive write access. // It achieves better scalability by dividing the shared data into multiple shards, and each with its own internal lock. // Multiple threads can read from different shards simultaneously, reducing contention. // https://docs.rs/crossbeam/0.8.2/crossbeam/sync/struct.ShardedLock.html // Comparing to RwLock, ShardedLock provides higher concurrency for read operations and is suitable for read heavy workloads. // The value of the hashmap is an Arc<IOContext> to allow immutable access to IOContext with automatic reference counting. ctx_map: Lazy<ShardedLock<HashMap<thread::ThreadId, Arc<IOContext>>>>, } impl WindowsAlignedFileReader { pub fn new(fname: &str) -> ANNResult<Self> { let reader: WindowsAlignedFileReader = WindowsAlignedFileReader { file_name: fname.to_string(), ctx_map: Lazy::new(|| ShardedLock::new(HashMap::new())), }; reader.register_thread()?; Ok(reader) } // Register the io context for a thread if it hasn't been registered. pub fn register_thread(&self) -> ANNResult<()> { let mut ctx_map = self.ctx_map.write().map_err(|_| { ANNError::log_lock_poison_error("unable to acquire read lock on ctx_map".to_string()) })?; let id = thread::current().id(); if ctx_map.contains_key(&id) { println!( "Warning:: Duplicate registration for thread_id : {:?}. Directly call get_ctx to get the thread context data.", id); return Ok(()); } let mut ctx = IOContext::new(); match unsafe { FileHandle::new(&self.file_name, AccessMode::Read, ShareMode::Read) } { Ok(file_handle) => ctx.file_handle = file_handle, Err(err) => { return Err(ANNError::log_io_error(err)); } } // Create a io completion port for the file handle, later it will be used to get the completion status. match IOCompletionPort::new(&ctx.file_handle, None, 0, 0) { Ok(io_completion_port) => ctx.io_completion_port = io_completion_port, Err(err) => { return Err(ANNError::log_io_error(err)); } } ctx_map.insert(id, Arc::new(ctx)); Ok(()) } // Get the reference counted io context for the current thread. pub fn get_ctx(&self) -> ANNResult<Arc<IOContext>> { let ctx_map = self.ctx_map.read().map_err(|_| { ANNError::log_lock_poison_error("unable to acquire read lock on ctx_map".to_string()) })?; let id = thread::current().id(); match ctx_map.get(&id) { Some(ctx) => Ok(Arc::clone(ctx)), None => Err(ANNError::log_index_error(format!( "unable to find IOContext for thread_id {:?}", id ))), } } // Read the data from the file by sending concurrent io requests in batches. pub fn read<T>(&self, read_requests: &mut [AlignedRead<T>], ctx: &IOContext) -> ANNResult<()> { let n_requests = read_requests.len(); let n_batches = (n_requests + MAX_IO_CONCURRENCY - 1) / MAX_IO_CONCURRENCY; let mut overlapped_in_out = vec![unsafe { std::mem::zeroed::<OVERLAPPED>() }; MAX_IO_CONCURRENCY]; for batch_idx in 0..n_batches { let batch_start = MAX_IO_CONCURRENCY * batch_idx; let batch_size = std::cmp::min(n_requests - batch_start, MAX_IO_CONCURRENCY); for j in 0..batch_size { let req = &mut read_requests[batch_start + j]; let os = &mut overlapped_in_out[j]; match unsafe { read_file_to_slice(&ctx.file_handle, req.aligned_buf, os, req.offset) } { Ok(_) => {} Err(error) => { return Err(ANNError::IOError { err: (error) }); } } } let mut n_read: DWORD = 0; let mut n_complete: u64 = 0; let mut completion_key: ULONG_PTR = 0; let mut lp_os: *mut OVERLAPPED = ptr::null_mut(); while n_complete < batch_size as u64 { match unsafe { get_queued_completion_status( &ctx.io_completion_port, &mut n_read, &mut completion_key, &mut lp_os, IO_COMPLETION_TIMEOUT, ) } { // An IO request completed. Ok(true) => n_complete += 1, // No IO request completed, continue to wait. Ok(false) => { thread::sleep(ASYNC_IO_COMPLETION_CHECK_INTERVAL); } // An error ocurred. Err(error) => return Err(ANNError::IOError { err: (error) }), } } } Ok(()) } } #[cfg(test)] mod tests { use std::{fs::File, io::BufReader}; use bincode::deserialize_from; use serde::{Deserialize, Serialize}; use crate::{common::AlignedBoxWithSlice, model::SECTOR_LEN}; use super::*; pub const TEST_INDEX_PATH: &str = "./tests/data/disk_index_siftsmall_learn_256pts_R4_L50_A1.2_alligned_reader_test.index"; pub const TRUTH_NODE_DATA_PATH: &str = "./tests/data/disk_index_node_data_aligned_reader_truth.bin"; #[derive(Debug, Serialize, Deserialize)] struct NodeData { num_neighbors: u32, coordinates: Vec<f32>, neighbors: Vec<u32>, } impl PartialEq for NodeData { fn eq(&self, other: &Self) -> bool { self.num_neighbors == other.num_neighbors && self.coordinates == other.coordinates && self.neighbors == other.neighbors } } #[test] fn test_new_aligned_file_reader() { // Replace "test_file_path" with actual file path let result = WindowsAlignedFileReader::new(TEST_INDEX_PATH); assert!(result.is_ok()); let reader = result.unwrap(); assert_eq!(reader.file_name, TEST_INDEX_PATH); } #[test] fn test_read() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let ctx = reader.get_ctx().unwrap(); let read_length = 512; // adjust according to your logic let num_read = 10; let mut aligned_mem = AlignedBoxWithSlice::<u8>::new(read_length * num_read, 512).unwrap(); // create and add AlignedReads to the vector let mut mem_slices = aligned_mem .split_into_nonoverlapping_mut_slices(0..aligned_mem.len(), read_length) .unwrap(); let mut aligned_reads: Vec<AlignedRead<'_, u8>> = mem_slices .iter_mut() .enumerate() .map(|(i, slice)| { let offset = (i * read_length) as u64; AlignedRead::new(offset, slice).unwrap() }) .collect(); let result = reader.read(&mut aligned_reads, &ctx); assert!(result.is_ok()); } #[test] fn test_read_disk_index_by_sector() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let ctx = reader.get_ctx().unwrap(); let read_length = SECTOR_LEN; // adjust according to your logic let num_sector = 10; let mut aligned_mem = AlignedBoxWithSlice::<u8>::new(read_length * num_sector, 512).unwrap(); // Each slice will be used as the buffer for a read request of a sector. let mut mem_slices = aligned_mem .split_into_nonoverlapping_mut_slices(0..aligned_mem.len(), read_length) .unwrap(); let mut aligned_reads: Vec<AlignedRead<'_, u8>> = mem_slices .iter_mut() .enumerate() .map(|(sector_id, slice)| { let offset = (sector_id * read_length) as u64; AlignedRead::new(offset, slice).unwrap() }) .collect(); let result = reader.read(&mut aligned_reads, &ctx); assert!(result.is_ok()); aligned_reads.iter().for_each(|read| { assert_eq!(read.aligned_buf.len(), SECTOR_LEN); }); let disk_layout_meta = reconstruct_disk_meta(aligned_reads[0].aligned_buf); assert!(disk_layout_meta.len() > 9); let dims = disk_layout_meta[1]; let num_pts = disk_layout_meta[0]; let max_node_len = disk_layout_meta[3]; let max_num_nodes_per_sector = disk_layout_meta[4]; assert!(max_node_len * max_num_nodes_per_sector < SECTOR_LEN as u64); let num_nbrs_start = (dims as usize) * std::mem::size_of::<f32>(); let nbrs_buf_start = num_nbrs_start + std::mem::size_of::<u32>(); let mut node_data_array = Vec::with_capacity(max_num_nodes_per_sector as usize * 9); // Only validate the first 9 sectors with graph nodes. (1..9).for_each(|sector_id| { let sector_data = &mem_slices[sector_id]; for node_data in sector_data.chunks_exact(max_node_len as usize) { // Extract coordinates data from the start of the node_data let coordinates_end = (dims as usize) * std::mem::size_of::<f32>(); let coordinates = node_data[0..coordinates_end] .chunks_exact(std::mem::size_of::<f32>()) .map(|chunk| f32::from_le_bytes(chunk.try_into().unwrap())) .collect(); // Extract number of neighbors from the node_data let neighbors_num = u32::from_le_bytes( node_data[num_nbrs_start..nbrs_buf_start] .try_into() .unwrap(), ); let nbors_buf_end = nbrs_buf_start + (neighbors_num as usize) * std::mem::size_of::<u32>(); // Extract neighbors from the node data. let mut neighbors = Vec::new(); for nbors_data in node_data[nbrs_buf_start..nbors_buf_end] .chunks_exact(std::mem::size_of::<u32>()) { let nbors_id = u32::from_le_bytes(nbors_data.try_into().unwrap()); assert!(nbors_id < num_pts as u32); neighbors.push(nbors_id); } // Create NodeData struct and push it to the node_data_array node_data_array.push(NodeData { num_neighbors: neighbors_num, coordinates, neighbors, }); } }); // Compare that each node read from the disk index are expected. let node_data_truth_file = File::open(TRUTH_NODE_DATA_PATH).unwrap(); let reader = BufReader::new(node_data_truth_file); let node_data_vec: Vec<NodeData> = deserialize_from(reader).unwrap(); for (node_from_node_data_file, node_from_disk_index) in node_data_vec.iter().zip(node_data_array.iter()) { // Verify that the NodeData from the file is equal to the NodeData in node_data_array assert_eq!(node_from_node_data_file, node_from_disk_index); } } #[test] fn test_read_fail_invalid_file() { let reader = WindowsAlignedFileReader::new("/invalid_path"); assert!(reader.is_err()); } #[test] fn test_read_no_requests() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let ctx = reader.get_ctx().unwrap(); let mut read_requests = Vec::<AlignedRead<u8>>::new(); let result = reader.read(&mut read_requests, &ctx); assert!(result.is_ok()); } #[test] fn
() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let result = reader.get_ctx(); assert!(result.is_ok()); } #[test] fn test_register_thread() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let result = reader.register_thread(); assert!(result.is_ok()); } fn reconstruct_disk_meta(buffer: &[u8]) -> Vec<u64> { let size_of_u64 = std::mem::size_of::<u64>(); let num_values = buffer.len() / size_of_u64; let mut disk_layout_meta = Vec::with_capacity(num_values); let meta_data = &buffer[8..]; for chunk in meta_data.chunks_exact(size_of_u64) { let value = u64::from_le_bytes(chunk.try_into().unwrap()); disk_layout_meta.push(value); } disk_layout_meta } }
test_get_ctx
identifier_name
windows_aligned_file_reader.rs
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ use std::sync::Arc; use std::time::Duration; use std::{ptr, thread}; use crossbeam::sync::ShardedLock; use hashbrown::HashMap; use once_cell::sync::Lazy; use platform::file_handle::{AccessMode, ShareMode}; use platform::{ file_handle::FileHandle, file_io::{get_queued_completion_status, read_file_to_slice}, io_completion_port::IOCompletionPort, }; use winapi::{ shared::{basetsd::ULONG_PTR, minwindef::DWORD}, um::minwinbase::OVERLAPPED, }; use crate::common::{ANNError, ANNResult}; use crate::model::IOContext; pub const MAX_IO_CONCURRENCY: usize = 128; // To do: explore the optimal value for this. The current value is taken from C++ code. pub const FILE_ATTRIBUTE_READONLY: DWORD = 0x00000001; pub const IO_COMPLETION_TIMEOUT: DWORD = u32::MAX; // Infinite timeout. pub const DISK_IO_ALIGNMENT: usize = 512; pub const ASYNC_IO_COMPLETION_CHECK_INTERVAL: Duration = Duration::from_micros(5); /// Aligned read struct for disk IO, it takes the ownership of the AlignedBoxedSlice and returns the AlignedBoxWithSlice data immutably. pub struct AlignedRead<'a, T> { /// where to read from /// offset needs to be aligned with DISK_IO_ALIGNMENT offset: u64, /// where to read into /// aligned_buf and its len need to be aligned with DISK_IO_ALIGNMENT aligned_buf: &'a mut [T], } impl<'a, T> AlignedRead<'a, T> { pub fn new(offset: u64, aligned_buf: &'a mut [T]) -> ANNResult<Self> { Self::assert_is_aligned(offset as usize)?; Self::assert_is_aligned(std::mem::size_of_val(aligned_buf))?; Ok(Self { offset, aligned_buf, }) } fn assert_is_aligned(val: usize) -> ANNResult<()> { match val % DISK_IO_ALIGNMENT { 0 => Ok(()), _ => Err(ANNError::log_disk_io_request_alignment_error(format!( "The offset or length of AlignedRead request is not {} bytes aligned", DISK_IO_ALIGNMENT ))), } } pub fn aligned_buf(&self) -> &[T]
} pub struct WindowsAlignedFileReader { file_name: String, // ctx_map is the mapping from thread id to io context. It is hashmap behind a sharded lock to allow concurrent access from multiple threads. // ShardedLock: shardedlock provides an implementation of a reader-writer lock that offers concurrent read access to the shared data while allowing exclusive write access. // It achieves better scalability by dividing the shared data into multiple shards, and each with its own internal lock. // Multiple threads can read from different shards simultaneously, reducing contention. // https://docs.rs/crossbeam/0.8.2/crossbeam/sync/struct.ShardedLock.html // Comparing to RwLock, ShardedLock provides higher concurrency for read operations and is suitable for read heavy workloads. // The value of the hashmap is an Arc<IOContext> to allow immutable access to IOContext with automatic reference counting. ctx_map: Lazy<ShardedLock<HashMap<thread::ThreadId, Arc<IOContext>>>>, } impl WindowsAlignedFileReader { pub fn new(fname: &str) -> ANNResult<Self> { let reader: WindowsAlignedFileReader = WindowsAlignedFileReader { file_name: fname.to_string(), ctx_map: Lazy::new(|| ShardedLock::new(HashMap::new())), }; reader.register_thread()?; Ok(reader) } // Register the io context for a thread if it hasn't been registered. pub fn register_thread(&self) -> ANNResult<()> { let mut ctx_map = self.ctx_map.write().map_err(|_| { ANNError::log_lock_poison_error("unable to acquire read lock on ctx_map".to_string()) })?; let id = thread::current().id(); if ctx_map.contains_key(&id) { println!( "Warning:: Duplicate registration for thread_id : {:?}. Directly call get_ctx to get the thread context data.", id); return Ok(()); } let mut ctx = IOContext::new(); match unsafe { FileHandle::new(&self.file_name, AccessMode::Read, ShareMode::Read) } { Ok(file_handle) => ctx.file_handle = file_handle, Err(err) => { return Err(ANNError::log_io_error(err)); } } // Create a io completion port for the file handle, later it will be used to get the completion status. match IOCompletionPort::new(&ctx.file_handle, None, 0, 0) { Ok(io_completion_port) => ctx.io_completion_port = io_completion_port, Err(err) => { return Err(ANNError::log_io_error(err)); } } ctx_map.insert(id, Arc::new(ctx)); Ok(()) } // Get the reference counted io context for the current thread. pub fn get_ctx(&self) -> ANNResult<Arc<IOContext>> { let ctx_map = self.ctx_map.read().map_err(|_| { ANNError::log_lock_poison_error("unable to acquire read lock on ctx_map".to_string()) })?; let id = thread::current().id(); match ctx_map.get(&id) { Some(ctx) => Ok(Arc::clone(ctx)), None => Err(ANNError::log_index_error(format!( "unable to find IOContext for thread_id {:?}", id ))), } } // Read the data from the file by sending concurrent io requests in batches. pub fn read<T>(&self, read_requests: &mut [AlignedRead<T>], ctx: &IOContext) -> ANNResult<()> { let n_requests = read_requests.len(); let n_batches = (n_requests + MAX_IO_CONCURRENCY - 1) / MAX_IO_CONCURRENCY; let mut overlapped_in_out = vec![unsafe { std::mem::zeroed::<OVERLAPPED>() }; MAX_IO_CONCURRENCY]; for batch_idx in 0..n_batches { let batch_start = MAX_IO_CONCURRENCY * batch_idx; let batch_size = std::cmp::min(n_requests - batch_start, MAX_IO_CONCURRENCY); for j in 0..batch_size { let req = &mut read_requests[batch_start + j]; let os = &mut overlapped_in_out[j]; match unsafe { read_file_to_slice(&ctx.file_handle, req.aligned_buf, os, req.offset) } { Ok(_) => {} Err(error) => { return Err(ANNError::IOError { err: (error) }); } } } let mut n_read: DWORD = 0; let mut n_complete: u64 = 0; let mut completion_key: ULONG_PTR = 0; let mut lp_os: *mut OVERLAPPED = ptr::null_mut(); while n_complete < batch_size as u64 { match unsafe { get_queued_completion_status( &ctx.io_completion_port, &mut n_read, &mut completion_key, &mut lp_os, IO_COMPLETION_TIMEOUT, ) } { // An IO request completed. Ok(true) => n_complete += 1, // No IO request completed, continue to wait. Ok(false) => { thread::sleep(ASYNC_IO_COMPLETION_CHECK_INTERVAL); } // An error ocurred. Err(error) => return Err(ANNError::IOError { err: (error) }), } } } Ok(()) } } #[cfg(test)] mod tests { use std::{fs::File, io::BufReader}; use bincode::deserialize_from; use serde::{Deserialize, Serialize}; use crate::{common::AlignedBoxWithSlice, model::SECTOR_LEN}; use super::*; pub const TEST_INDEX_PATH: &str = "./tests/data/disk_index_siftsmall_learn_256pts_R4_L50_A1.2_alligned_reader_test.index"; pub const TRUTH_NODE_DATA_PATH: &str = "./tests/data/disk_index_node_data_aligned_reader_truth.bin"; #[derive(Debug, Serialize, Deserialize)] struct NodeData { num_neighbors: u32, coordinates: Vec<f32>, neighbors: Vec<u32>, } impl PartialEq for NodeData { fn eq(&self, other: &Self) -> bool { self.num_neighbors == other.num_neighbors && self.coordinates == other.coordinates && self.neighbors == other.neighbors } } #[test] fn test_new_aligned_file_reader() { // Replace "test_file_path" with actual file path let result = WindowsAlignedFileReader::new(TEST_INDEX_PATH); assert!(result.is_ok()); let reader = result.unwrap(); assert_eq!(reader.file_name, TEST_INDEX_PATH); } #[test] fn test_read() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let ctx = reader.get_ctx().unwrap(); let read_length = 512; // adjust according to your logic let num_read = 10; let mut aligned_mem = AlignedBoxWithSlice::<u8>::new(read_length * num_read, 512).unwrap(); // create and add AlignedReads to the vector let mut mem_slices = aligned_mem .split_into_nonoverlapping_mut_slices(0..aligned_mem.len(), read_length) .unwrap(); let mut aligned_reads: Vec<AlignedRead<'_, u8>> = mem_slices .iter_mut() .enumerate() .map(|(i, slice)| { let offset = (i * read_length) as u64; AlignedRead::new(offset, slice).unwrap() }) .collect(); let result = reader.read(&mut aligned_reads, &ctx); assert!(result.is_ok()); } #[test] fn test_read_disk_index_by_sector() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let ctx = reader.get_ctx().unwrap(); let read_length = SECTOR_LEN; // adjust according to your logic let num_sector = 10; let mut aligned_mem = AlignedBoxWithSlice::<u8>::new(read_length * num_sector, 512).unwrap(); // Each slice will be used as the buffer for a read request of a sector. let mut mem_slices = aligned_mem .split_into_nonoverlapping_mut_slices(0..aligned_mem.len(), read_length) .unwrap(); let mut aligned_reads: Vec<AlignedRead<'_, u8>> = mem_slices .iter_mut() .enumerate() .map(|(sector_id, slice)| { let offset = (sector_id * read_length) as u64; AlignedRead::new(offset, slice).unwrap() }) .collect(); let result = reader.read(&mut aligned_reads, &ctx); assert!(result.is_ok()); aligned_reads.iter().for_each(|read| { assert_eq!(read.aligned_buf.len(), SECTOR_LEN); }); let disk_layout_meta = reconstruct_disk_meta(aligned_reads[0].aligned_buf); assert!(disk_layout_meta.len() > 9); let dims = disk_layout_meta[1]; let num_pts = disk_layout_meta[0]; let max_node_len = disk_layout_meta[3]; let max_num_nodes_per_sector = disk_layout_meta[4]; assert!(max_node_len * max_num_nodes_per_sector < SECTOR_LEN as u64); let num_nbrs_start = (dims as usize) * std::mem::size_of::<f32>(); let nbrs_buf_start = num_nbrs_start + std::mem::size_of::<u32>(); let mut node_data_array = Vec::with_capacity(max_num_nodes_per_sector as usize * 9); // Only validate the first 9 sectors with graph nodes. (1..9).for_each(|sector_id| { let sector_data = &mem_slices[sector_id]; for node_data in sector_data.chunks_exact(max_node_len as usize) { // Extract coordinates data from the start of the node_data let coordinates_end = (dims as usize) * std::mem::size_of::<f32>(); let coordinates = node_data[0..coordinates_end] .chunks_exact(std::mem::size_of::<f32>()) .map(|chunk| f32::from_le_bytes(chunk.try_into().unwrap())) .collect(); // Extract number of neighbors from the node_data let neighbors_num = u32::from_le_bytes( node_data[num_nbrs_start..nbrs_buf_start] .try_into() .unwrap(), ); let nbors_buf_end = nbrs_buf_start + (neighbors_num as usize) * std::mem::size_of::<u32>(); // Extract neighbors from the node data. let mut neighbors = Vec::new(); for nbors_data in node_data[nbrs_buf_start..nbors_buf_end] .chunks_exact(std::mem::size_of::<u32>()) { let nbors_id = u32::from_le_bytes(nbors_data.try_into().unwrap()); assert!(nbors_id < num_pts as u32); neighbors.push(nbors_id); } // Create NodeData struct and push it to the node_data_array node_data_array.push(NodeData { num_neighbors: neighbors_num, coordinates, neighbors, }); } }); // Compare that each node read from the disk index are expected. let node_data_truth_file = File::open(TRUTH_NODE_DATA_PATH).unwrap(); let reader = BufReader::new(node_data_truth_file); let node_data_vec: Vec<NodeData> = deserialize_from(reader).unwrap(); for (node_from_node_data_file, node_from_disk_index) in node_data_vec.iter().zip(node_data_array.iter()) { // Verify that the NodeData from the file is equal to the NodeData in node_data_array assert_eq!(node_from_node_data_file, node_from_disk_index); } } #[test] fn test_read_fail_invalid_file() { let reader = WindowsAlignedFileReader::new("/invalid_path"); assert!(reader.is_err()); } #[test] fn test_read_no_requests() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let ctx = reader.get_ctx().unwrap(); let mut read_requests = Vec::<AlignedRead<u8>>::new(); let result = reader.read(&mut read_requests, &ctx); assert!(result.is_ok()); } #[test] fn test_get_ctx() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let result = reader.get_ctx(); assert!(result.is_ok()); } #[test] fn test_register_thread() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let result = reader.register_thread(); assert!(result.is_ok()); } fn reconstruct_disk_meta(buffer: &[u8]) -> Vec<u64> { let size_of_u64 = std::mem::size_of::<u64>(); let num_values = buffer.len() / size_of_u64; let mut disk_layout_meta = Vec::with_capacity(num_values); let meta_data = &buffer[8..]; for chunk in meta_data.chunks_exact(size_of_u64) { let value = u64::from_le_bytes(chunk.try_into().unwrap()); disk_layout_meta.push(value); } disk_layout_meta } }
{ self.aligned_buf }
identifier_body
columnar.rs
rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0. //! A columnar representation of ((Key, Val), Time, i64) data suitable for in-memory //! reads and persistent storage. use std::mem::size_of; use std::{cmp, fmt}; use arrow2::buffer::Buffer; use arrow2::offset::OffsetsBuffer; use arrow2::types::Index; pub mod arrow; pub mod parquet; /// The maximum allowed amount of total key data (similarly val data) in a /// single ColumnarBatch. /// /// Note that somewhat counter-intuitively, this also includes offsets (counting /// as 4 bytes each) in the definition of "key/val data". /// /// TODO: The limit on the amount of {key,val} data is because we use i32 /// offsets in parquet; this won't change. However, we include the offsets in /// the size because the parquet library we use currently maps each Array 1:1 /// with a parquet "page" (so for a "binary" column this is both the offsets and /// the data). The parquet format internally stores the size of a page in an /// i32, so if this gets too big, our library overflows it and writes bad data. /// There's no reason it needs to map an Array 1:1 to a page (it could instead /// be 1:1 with a "column chunk", which contains 1 or more pages). For now, we /// work around it. // TODO(benesch): find a way to express this without `as`. #[allow(clippy::as_conversions)] pub const KEY_VAL_DATA_MAX_LEN: usize = i32::MAX as usize; const BYTES_PER_KEY_VAL_OFFSET: usize = 4; /// A set of ((Key, Val), Time, Diff) records stored in a columnar /// representation. /// /// Note that the data are unsorted, and unconsolidated (so there may be /// multiple instances of the same ((Key, Val), Time), and some Diffs might be /// zero, or add up to zero). /// /// Both Time and Diff are presented externally to persist users as a type /// parameter that implements [mz_persist_types::Codec64]. Our columnar format /// intentionally stores them both as i64 columns (as opposed to something like /// a fixed width binary column) because this allows us additional compression /// options. /// /// Also note that we intentionally use an i64 over a u64 for Time. Over the /// range `[0, i64::MAX]`, the bytes are the same and we've talked at various /// times about changing Time in mz to an i64. Both millis since unix epoch and /// nanos since unix epoch easily fit into this range (the latter until some /// time after year 2200). Using a i64 might be a pessimization for a /// non-realtime mz source with u64 timestamps in the range `(i64::MAX, /// u64::MAX]`, but realtime sources are overwhelmingly the common case. /// /// The i'th key's data is stored in /// `key_data[key_offsets[i]..key_offsets[i+1]]`. Similarly for val. /// /// Invariants: /// - len < usize::MAX (so len+1 can fit in a usize) /// - key_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + key_data.len() <= KEY_VAL_DATA_MAX_LEN /// - key_offsets.len() == len + 1 /// - key_offsets are non-decreasing /// - Each key_offset is <= key_data.len() /// - key_offsets.first().unwrap() == 0 /// - key_offsets.last().unwrap() == key_data.len() /// - val_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + val_data.len() <= KEY_VAL_DATA_MAX_LEN /// - val_offsets.len() == len + 1 /// - val_offsets are non-decreasing /// - Each val_offset is <= val_data.len() /// - val_offsets.first().unwrap() == 0 /// - val_offsets.last().unwrap() == val_data.len() /// - timestamps.len() == len /// - diffs.len() == len #[derive(Clone, PartialEq)] pub struct ColumnarRecords { len: usize, key_data: Buffer<u8>, key_offsets: OffsetsBuffer<i32>, val_data: Buffer<u8>, val_offsets: OffsetsBuffer<i32>, timestamps: Buffer<i64>, diffs: Buffer<i64>, } impl fmt::Debug for ColumnarRecords { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.borrow(), fmt) } } impl ColumnarRecords { /// The number of (potentially duplicated) ((Key, Val), Time, i64) records /// stored in Self. pub fn len(&self) -> usize { self.len } /// The number of logical bytes in the represented data, excluding offsets /// and lengths. pub fn goodbytes(&self) -> usize { self.key_data.len() + self.val_data.len() + 8 * self.timestamps.len() + 8 * self.diffs.len() } /// Read the record at `idx`, if there is one. /// /// Returns None if `idx >= self.len()`. pub fn get<'a>(&'a self, idx: usize) -> Option<((&'a [u8], &'a [u8]), [u8; 8], [u8; 8])> { self.borrow().get(idx) } /// Borrow Self as a [ColumnarRecordsRef]. fn borrow<'a>(&'a self) -> ColumnarRecordsRef<'a> { // The ColumnarRecords constructor already validates, so don't bother // doing it again. // // TODO: Forcing everything through a `fn new` would make this more // obvious. ColumnarRecordsRef { len: self.len, key_data: self.key_data.as_slice(), key_offsets: self.key_offsets.as_slice(), val_data: self.val_data.as_slice(), val_offsets: self.val_offsets.as_slice(), timestamps: self.timestamps.as_slice(), diffs: self.diffs.as_slice(), } } /// Iterate through the records in Self. pub fn iter<'a>(&'a self) -> ColumnarRecordsIter<'a> { self.borrow().iter() } } /// A reference to a [ColumnarRecords]. #[derive(Clone)] struct ColumnarRecordsRef<'a> { len: usize, key_data: &'a [u8], key_offsets: &'a [i32], val_data: &'a [u8], val_offsets: &'a [i32], timestamps: &'a [i64], diffs: &'a [i64], } impl<'a> fmt::Debug for ColumnarRecordsRef<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_list().entries(self.iter()).finish() } } impl<'a> ColumnarRecordsRef<'a> { fn validate(&self) -> Result<(), String> { let key_data_size = self.key_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + self.key_data.len(); if key_data_size > KEY_VAL_DATA_MAX_LEN { return Err(format!( "expected encoded key offsets and data size to be less than or equal to {} got {}", KEY_VAL_DATA_MAX_LEN, key_data_size )); } if self.key_offsets.len()!= self.len + 1 { return Err(format!( "expected {} key_offsets got {}", self.len + 1, self.key_offsets.len() )); } if let Some(first_key_offset) = self.key_offsets.first() { if first_key_offset.to_usize()!= 0 { return Err(format!( "expected first key offset to be 0 got {}", first_key_offset.to_usize() )); } } if let Some(last_key_offset) = self.key_offsets.last() { if last_key_offset.to_usize()!= self.key_data.len() { return Err(format!( "expected {} bytes of key data got {}", last_key_offset, self.key_data.len() )); } } let val_data_size = self.val_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + self.val_data.len(); if val_data_size > KEY_VAL_DATA_MAX_LEN { return Err(format!( "expected encoded val offsets and data size to be less than or equal to {} got {}", KEY_VAL_DATA_MAX_LEN, val_data_size )); } if self.val_offsets.len()!= self.len + 1 { return Err(format!( "expected {} val_offsets got {}", self.len + 1, self.val_offsets.len() )); } if let Some(first_val_offset) = self.val_offsets.first() { if first_val_offset.to_usize()!= 0 { return Err(format!( "expected first val offset to be 0 got {}", first_val_offset.to_usize() )); } } if let Some(last_val_offset) = self.val_offsets.last() { if last_val_offset.to_usize()!= self.val_data.len() { return Err(format!( "expected {} bytes of val data got {}", last_val_offset, self.val_data.len() )); } } if self.diffs.len()!= self.len { return Err(format!( "expected {} diffs got {}", self.len, self.diffs.len() )); } if self.timestamps.len()!= self.len { return Err(format!( "expected {} timestamps got {}", self.len, self.timestamps.len() )); } // Unlike most of our Validate methods, this one is called in a // production code path: when decoding a columnar batch. Only check the // more expensive assertions in debug. #[cfg(debug_assertions)] { let (mut prev_key, mut prev_val) = (0, 0); for i in 0..=self.len { let (key, val) = (self.key_offsets[i], self.val_offsets[i]); if key < prev_key { return Err(format!( "expected non-decreasing key offsets got {} followed by {}", prev_key, key )); } if val < prev_val { return Err(format!( "expected non-decreasing val offsets got {} followed by {}", prev_val, val )); } prev_key = key; prev_val = val; } } Ok(()) } /// Read the record at `idx`, if there is one. /// /// Returns None if `idx >= self.len()`. fn get(&self, idx: usize) -> Option<((&'a [u8], &'a [u8]), [u8; 8], [u8; 8])> { if idx >= self.len { return None; } // There used to be `debug_assert_eq!(self.validate(), Ok(()))`, but it // resulted in accidentally O(n^2) behavior in debug mode. Instead, we // push that responsibility to the ColumnarRecordsRef constructor. let key_range = self.key_offsets[idx].to_usize()..self.key_offsets[idx + 1].to_usize(); let val_range = self.val_offsets[idx].to_usize()..self.val_offsets[idx + 1].to_usize(); let key = &self.key_data[key_range]; let val = &self.val_data[val_range]; let ts = i64::to_le_bytes(self.timestamps[idx]); let diff = i64::to_le_bytes(self.diffs[idx]); Some(((key, val), ts, diff)) } /// Iterate through the records in Self. fn iter(&self) -> ColumnarRecordsIter<'a> { ColumnarRecordsIter { idx: 0, records: self.clone(), } } } /// An [Iterator] over the records in a [ColumnarRecords]. #[derive(Clone, Debug)] pub struct ColumnarRecordsIter<'a> { idx: usize, records: ColumnarRecordsRef<'a>, } impl<'a> Iterator for ColumnarRecordsIter<'a> { type Item = ((&'a [u8], &'a [u8]), [u8; 8], [u8; 8]); fn size_hint(&self) -> (usize, Option<usize>) { (self.records.len, Some(self.records.len)) } fn next(&mut self) -> Option<Self::Item> { let ret = self.records.get(self.idx); self.idx += 1; ret } } impl<'a> ExactSizeIterator for ColumnarRecordsIter<'a> {} /// An abstraction to incrementally add ((Key, Value), Time, i64) records /// in a columnar representation, and eventually get back a [ColumnarRecords]. pub struct ColumnarRecordsBuilder { len: usize, key_data: Vec<u8>, key_offsets: Vec<i32>, val_data: Vec<u8>, val_offsets: Vec<i32>, timestamps: Vec<i64>, diffs: Vec<i64>, } impl fmt::Debug for ColumnarRecordsBuilder { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.borrow(), fmt) } } impl Default for ColumnarRecordsBuilder { fn default() -> Self { let mut ret = ColumnarRecordsBuilder { len: 0, key_data: Vec::new(), key_offsets: Vec::new(), val_data: Vec::new(), val_offsets: Vec::new(), timestamps: Vec::new(), diffs: Vec::new(), }; // Push initial 0 offsets to maintain our invariants, even as we build. ret.key_offsets.push(0); ret.val_offsets.push(0); debug_assert_eq!(ret.borrow().validate(), Ok(())); ret } } impl ColumnarRecordsBuilder { /// The number of (potentially duplicated) ((Key, Val), Time, i64) records /// stored in Self. pub fn len(&self) -> usize { self.len } /// Borrow Self as a [ColumnarRecordsRef]. fn borrow<'a>(&'a self) -> ColumnarRecordsRef<'a> { let ret = ColumnarRecordsRef { len: self.len, key_data: self.key_data.as_slice(), key_offsets: self.key_offsets.as_slice(), val_data: self.val_data.as_slice(), val_offsets: self.val_offsets.as_slice(), timestamps: self.timestamps.as_slice(), diffs: self.diffs.as_slice(), }; debug_assert_eq!(ret.validate(), Ok(())); ret } /// Reserve space for `additional` more records, based on `key_size_guess` and /// `val_size_guess`. /// /// The guesses for key and val sizes are best effort, and if they end up being /// too small, the underlying buffers will be resized. pub fn reserve(&mut self, additional: usize, key_size_guess: usize, val_size_guess: usize) { self.key_offsets.reserve(additional); self.key_data .reserve(cmp::min(additional * key_size_guess, KEY_VAL_DATA_MAX_LEN)); self.val_offsets.reserve(additional); self.val_data .reserve(cmp::min(additional * val_size_guess, KEY_VAL_DATA_MAX_LEN)); self.timestamps.reserve(additional); self.diffs.reserve(additional); debug_assert_eq!(self.borrow().validate(), Ok(())); } /// Reserve space for `additional` more records, with exact sizes for the key and value data. pub fn reserve_exact(&mut self, additional: usize, key_bytes: usize, val_bytes: usize) { self.key_offsets.reserve(additional); self.key_data .reserve(cmp::min(key_bytes, KEY_VAL_DATA_MAX_LEN)); self.val_offsets.reserve(additional); self.val_data .reserve(cmp::min(val_bytes, KEY_VAL_DATA_MAX_LEN)); self.timestamps.reserve(additional); self.diffs.reserve(additional); debug_assert_eq!(self.borrow().validate(), Ok(())); } /// Returns if the given key_offsets+key_data or val_offsets+val_data fits /// in the limits imposed by ColumnarRecords. /// /// Note that limit is always [KEY_VAL_DATA_MAX_LEN] in production. It's /// only override-able here for testing. pub fn can_fit(&self, key: &[u8], val: &[u8], limit: usize) -> bool { let key_data_size = (self.key_offsets.len() + 1) * BYTES_PER_KEY_VAL_OFFSET + self.key_data.len() + key.len(); let val_data_size = (self.val_offsets.len() + 1) * BYTES_PER_KEY_VAL_OFFSET + self.val_data.len() + val.len(); key_data_size <= limit && val_data_size <= limit } /// Add a record to Self. /// /// Returns whether the record was successfully added. A record will not a /// added if it exceeds the size limitations of ColumnarBatch. This method /// is atomic, if it fails, no partial data will have been added. #[must_use] pub fn push(&mut self, record: ((&[u8], &[u8]), [u8; 8], [u8; 8])) -> bool
true } /// Finalize constructing a [ColumnarRecords]. pub fn finish(self) -> ColumnarRecords { let ret = ColumnarRecords { len: self.len, key_data: Buffer::from(self.key_data), key_offsets: OffsetsBuffer::try_from(self.key_offsets) .expect("constructed valid offsets"), val_data: Buffer::from(self.val_data), val_offsets: OffsetsBuffer::try_from(self.val_offsets) .expect("constructed valid offsets"), timestamps: Buffer::from(self.timestamps), diffs: Buffer::from(self.diffs), }; debug_assert_eq!(ret.borrow().validate(), Ok(())); ret } /// Size of an update record as stored in the columnar representation pub fn columnar_record_size(key_bytes_len: usize, value_bytes_len: usize) -> usize { (key_bytes_len + BYTES_PER_KEY_VAL_OFFSET) + (value_bytes_len + BYTES_PER_KEY_VAL_OFFSET) + (2 * size_of::<u64>()) // T and D } } #[cfg(test)] mod tests { use mz_persist_types::Codec64; use super::*; /// Smoke test some edge cases around empty sets of records and empty keys/vals /// /// Most of this functionality is also well-exercised in other unit tests as well. #[mz_ore::test] fn columnar_records() { let builder = ColumnarRecordsBuilder::default(); // Empty builder. let records = builder.finish(); let reads: Vec<_> = records.iter().collect(); assert_eq!(reads, vec![]); // Empty key and val. let updates: Vec<((Vec<u8>, Vec<u8>), u64, i64)> = vec![ (("".into(), "".into()), 0, 0), (("".into(), "".into()), 1, 1), ]; let mut builder = ColumnarRecordsBuilder::default(); for ((key, val), time, diff) in updates.iter() { assert!(builder.push(((key, val), u64::encode(time), i64::encode(diff)))); } let records = builder.finish(); let reads: Vec<_> = records .iter() .map(|((k, v), t, d)| ((k.to_vec(), v.to_vec()), u64::decode(t), i64::decode(d)))
{ let ((key, val), ts, diff) = record; // Check size invariants ahead of time so we stay atomic when we can't // add the record. if !self.can_fit(key, val, KEY_VAL_DATA_MAX_LEN) { return false; } // NB: We should never hit the following expects because we check them // above. self.key_data.extend_from_slice(key); self.key_offsets .push(i32::try_from(self.key_data.len()).expect("key_data is smaller than 2GB")); self.val_data.extend_from_slice(val); self.val_offsets .push(i32::try_from(self.val_data.len()).expect("val_data is smaller than 2GB")); self.timestamps.push(i64::from_le_bytes(ts)); self.diffs.push(i64::from_le_bytes(diff)); self.len += 1;
identifier_body
columnar.rs
All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0. //! A columnar representation of ((Key, Val), Time, i64) data suitable for in-memory //! reads and persistent storage. use std::mem::size_of; use std::{cmp, fmt}; use arrow2::buffer::Buffer; use arrow2::offset::OffsetsBuffer; use arrow2::types::Index; pub mod arrow; pub mod parquet; /// The maximum allowed amount of total key data (similarly val data) in a /// single ColumnarBatch. /// /// Note that somewhat counter-intuitively, this also includes offsets (counting /// as 4 bytes each) in the definition of "key/val data". /// /// TODO: The limit on the amount of {key,val} data is because we use i32 /// offsets in parquet; this won't change. However, we include the offsets in /// the size because the parquet library we use currently maps each Array 1:1 /// with a parquet "page" (so for a "binary" column this is both the offsets and /// the data). The parquet format internally stores the size of a page in an /// i32, so if this gets too big, our library overflows it and writes bad data. /// There's no reason it needs to map an Array 1:1 to a page (it could instead /// be 1:1 with a "column chunk", which contains 1 or more pages). For now, we /// work around it. // TODO(benesch): find a way to express this without `as`. #[allow(clippy::as_conversions)] pub const KEY_VAL_DATA_MAX_LEN: usize = i32::MAX as usize; const BYTES_PER_KEY_VAL_OFFSET: usize = 4; /// A set of ((Key, Val), Time, Diff) records stored in a columnar /// representation. /// /// Note that the data are unsorted, and unconsolidated (so there may be /// multiple instances of the same ((Key, Val), Time), and some Diffs might be /// zero, or add up to zero). /// /// Both Time and Diff are presented externally to persist users as a type /// parameter that implements [mz_persist_types::Codec64]. Our columnar format /// intentionally stores them both as i64 columns (as opposed to something like /// a fixed width binary column) because this allows us additional compression /// options. /// /// Also note that we intentionally use an i64 over a u64 for Time. Over the /// range `[0, i64::MAX]`, the bytes are the same and we've talked at various /// times about changing Time in mz to an i64. Both millis since unix epoch and /// nanos since unix epoch easily fit into this range (the latter until some /// time after year 2200). Using a i64 might be a pessimization for a /// non-realtime mz source with u64 timestamps in the range `(i64::MAX, /// u64::MAX]`, but realtime sources are overwhelmingly the common case. /// /// The i'th key's data is stored in /// `key_data[key_offsets[i]..key_offsets[i+1]]`. Similarly for val. /// /// Invariants: /// - len < usize::MAX (so len+1 can fit in a usize) /// - key_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + key_data.len() <= KEY_VAL_DATA_MAX_LEN /// - key_offsets.len() == len + 1 /// - key_offsets are non-decreasing /// - Each key_offset is <= key_data.len() /// - key_offsets.first().unwrap() == 0 /// - key_offsets.last().unwrap() == key_data.len() /// - val_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + val_data.len() <= KEY_VAL_DATA_MAX_LEN /// - val_offsets.len() == len + 1 /// - val_offsets are non-decreasing /// - Each val_offset is <= val_data.len() /// - val_offsets.first().unwrap() == 0 /// - val_offsets.last().unwrap() == val_data.len() /// - timestamps.len() == len /// - diffs.len() == len #[derive(Clone, PartialEq)] pub struct ColumnarRecords { len: usize, key_data: Buffer<u8>, key_offsets: OffsetsBuffer<i32>, val_data: Buffer<u8>, val_offsets: OffsetsBuffer<i32>, timestamps: Buffer<i64>, diffs: Buffer<i64>, } impl fmt::Debug for ColumnarRecords { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.borrow(), fmt) } } impl ColumnarRecords { /// The number of (potentially duplicated) ((Key, Val), Time, i64) records /// stored in Self. pub fn len(&self) -> usize { self.len } /// The number of logical bytes in the represented data, excluding offsets /// and lengths. pub fn goodbytes(&self) -> usize { self.key_data.len() + self.val_data.len() + 8 * self.timestamps.len() + 8 * self.diffs.len() } /// Read the record at `idx`, if there is one. /// /// Returns None if `idx >= self.len()`. pub fn get<'a>(&'a self, idx: usize) -> Option<((&'a [u8], &'a [u8]), [u8; 8], [u8; 8])> { self.borrow().get(idx) } /// Borrow Self as a [ColumnarRecordsRef]. fn borrow<'a>(&'a self) -> ColumnarRecordsRef<'a> { // The ColumnarRecords constructor already validates, so don't bother // doing it again. // // TODO: Forcing everything through a `fn new` would make this more // obvious. ColumnarRecordsRef { len: self.len, key_data: self.key_data.as_slice(), key_offsets: self.key_offsets.as_slice(), val_data: self.val_data.as_slice(), val_offsets: self.val_offsets.as_slice(), timestamps: self.timestamps.as_slice(), diffs: self.diffs.as_slice(), } } /// Iterate through the records in Self. pub fn iter<'a>(&'a self) -> ColumnarRecordsIter<'a> { self.borrow().iter() } } /// A reference to a [ColumnarRecords]. #[derive(Clone)] struct ColumnarRecordsRef<'a> { len: usize, key_data: &'a [u8], key_offsets: &'a [i32], val_data: &'a [u8], val_offsets: &'a [i32], timestamps: &'a [i64], diffs: &'a [i64], } impl<'a> fmt::Debug for ColumnarRecordsRef<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_list().entries(self.iter()).finish() } } impl<'a> ColumnarRecordsRef<'a> { fn validate(&self) -> Result<(), String> { let key_data_size = self.key_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + self.key_data.len(); if key_data_size > KEY_VAL_DATA_MAX_LEN { return Err(format!( "expected encoded key offsets and data size to be less than or equal to {} got {}", KEY_VAL_DATA_MAX_LEN, key_data_size )); } if self.key_offsets.len()!= self.len + 1 { return Err(format!( "expected {} key_offsets got {}", self.len + 1, self.key_offsets.len() )); } if let Some(first_key_offset) = self.key_offsets.first() { if first_key_offset.to_usize()!= 0 { return Err(format!( "expected first key offset to be 0 got {}", first_key_offset.to_usize() )); } } if let Some(last_key_offset) = self.key_offsets.last() { if last_key_offset.to_usize()!= self.key_data.len() { return Err(format!( "expected {} bytes of key data got {}", last_key_offset, self.key_data.len() )); } } let val_data_size = self.val_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + self.val_data.len(); if val_data_size > KEY_VAL_DATA_MAX_LEN { return Err(format!( "expected encoded val offsets and data size to be less than or equal to {} got {}", KEY_VAL_DATA_MAX_LEN, val_data_size )); } if self.val_offsets.len()!= self.len + 1 { return Err(format!( "expected {} val_offsets got {}", self.len + 1, self.val_offsets.len() )); } if let Some(first_val_offset) = self.val_offsets.first() { if first_val_offset.to_usize()!= 0 { return Err(format!( "expected first val offset to be 0 got {}", first_val_offset.to_usize() )); } } if let Some(last_val_offset) = self.val_offsets.last() { if last_val_offset.to_usize()!= self.val_data.len() { return Err(format!( "expected {} bytes of val data got {}", last_val_offset, self.val_data.len() )); } } if self.diffs.len()!= self.len { return Err(format!( "expected {} diffs got {}", self.len, self.diffs.len() )); } if self.timestamps.len()!= self.len { return Err(format!( "expected {} timestamps got {}", self.len, self.timestamps.len() )); } // Unlike most of our Validate methods, this one is called in a // production code path: when decoding a columnar batch. Only check the // more expensive assertions in debug. #[cfg(debug_assertions)] { let (mut prev_key, mut prev_val) = (0, 0); for i in 0..=self.len { let (key, val) = (self.key_offsets[i], self.val_offsets[i]); if key < prev_key { return Err(format!( "expected non-decreasing key offsets got {} followed by {}", prev_key, key )); } if val < prev_val { return Err(format!( "expected non-decreasing val offsets got {} followed by {}", prev_val, val )); } prev_key = key; prev_val = val; } } Ok(()) } /// Read the record at `idx`, if there is one. /// /// Returns None if `idx >= self.len()`. fn get(&self, idx: usize) -> Option<((&'a [u8], &'a [u8]), [u8; 8], [u8; 8])> { if idx >= self.len { return None; } // There used to be `debug_assert_eq!(self.validate(), Ok(()))`, but it // resulted in accidentally O(n^2) behavior in debug mode. Instead, we // push that responsibility to the ColumnarRecordsRef constructor. let key_range = self.key_offsets[idx].to_usize()..self.key_offsets[idx + 1].to_usize(); let val_range = self.val_offsets[idx].to_usize()..self.val_offsets[idx + 1].to_usize(); let key = &self.key_data[key_range]; let val = &self.val_data[val_range]; let ts = i64::to_le_bytes(self.timestamps[idx]); let diff = i64::to_le_bytes(self.diffs[idx]); Some(((key, val), ts, diff)) } /// Iterate through the records in Self. fn iter(&self) -> ColumnarRecordsIter<'a> { ColumnarRecordsIter { idx: 0, records: self.clone(), } } } /// An [Iterator] over the records in a [ColumnarRecords]. #[derive(Clone, Debug)] pub struct ColumnarRecordsIter<'a> { idx: usize, records: ColumnarRecordsRef<'a>, } impl<'a> Iterator for ColumnarRecordsIter<'a> { type Item = ((&'a [u8], &'a [u8]), [u8; 8], [u8; 8]); fn size_hint(&self) -> (usize, Option<usize>) { (self.records.len, Some(self.records.len)) } fn next(&mut self) -> Option<Self::Item> { let ret = self.records.get(self.idx); self.idx += 1; ret } } impl<'a> ExactSizeIterator for ColumnarRecordsIter<'a> {} /// An abstraction to incrementally add ((Key, Value), Time, i64) records /// in a columnar representation, and eventually get back a [ColumnarRecords]. pub struct ColumnarRecordsBuilder { len: usize, key_data: Vec<u8>, key_offsets: Vec<i32>, val_data: Vec<u8>, val_offsets: Vec<i32>, timestamps: Vec<i64>, diffs: Vec<i64>, } impl fmt::Debug for ColumnarRecordsBuilder { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.borrow(), fmt) } } impl Default for ColumnarRecordsBuilder { fn default() -> Self { let mut ret = ColumnarRecordsBuilder { len: 0, key_data: Vec::new(), key_offsets: Vec::new(), val_data: Vec::new(), val_offsets: Vec::new(), timestamps: Vec::new(), diffs: Vec::new(), }; // Push initial 0 offsets to maintain our invariants, even as we build. ret.key_offsets.push(0); ret.val_offsets.push(0); debug_assert_eq!(ret.borrow().validate(), Ok(())); ret } } impl ColumnarRecordsBuilder { /// The number of (potentially duplicated) ((Key, Val), Time, i64) records /// stored in Self. pub fn len(&self) -> usize { self.len }
key_data: self.key_data.as_slice(), key_offsets: self.key_offsets.as_slice(), val_data: self.val_data.as_slice(), val_offsets: self.val_offsets.as_slice(), timestamps: self.timestamps.as_slice(), diffs: self.diffs.as_slice(), }; debug_assert_eq!(ret.validate(), Ok(())); ret } /// Reserve space for `additional` more records, based on `key_size_guess` and /// `val_size_guess`. /// /// The guesses for key and val sizes are best effort, and if they end up being /// too small, the underlying buffers will be resized. pub fn reserve(&mut self, additional: usize, key_size_guess: usize, val_size_guess: usize) { self.key_offsets.reserve(additional); self.key_data .reserve(cmp::min(additional * key_size_guess, KEY_VAL_DATA_MAX_LEN)); self.val_offsets.reserve(additional); self.val_data .reserve(cmp::min(additional * val_size_guess, KEY_VAL_DATA_MAX_LEN)); self.timestamps.reserve(additional); self.diffs.reserve(additional); debug_assert_eq!(self.borrow().validate(), Ok(())); } /// Reserve space for `additional` more records, with exact sizes for the key and value data. pub fn reserve_exact(&mut self, additional: usize, key_bytes: usize, val_bytes: usize) { self.key_offsets.reserve(additional); self.key_data .reserve(cmp::min(key_bytes, KEY_VAL_DATA_MAX_LEN)); self.val_offsets.reserve(additional); self.val_data .reserve(cmp::min(val_bytes, KEY_VAL_DATA_MAX_LEN)); self.timestamps.reserve(additional); self.diffs.reserve(additional); debug_assert_eq!(self.borrow().validate(), Ok(())); } /// Returns if the given key_offsets+key_data or val_offsets+val_data fits /// in the limits imposed by ColumnarRecords. /// /// Note that limit is always [KEY_VAL_DATA_MAX_LEN] in production. It's /// only override-able here for testing. pub fn can_fit(&self, key: &[u8], val: &[u8], limit: usize) -> bool { let key_data_size = (self.key_offsets.len() + 1) * BYTES_PER_KEY_VAL_OFFSET + self.key_data.len() + key.len(); let val_data_size = (self.val_offsets.len() + 1) * BYTES_PER_KEY_VAL_OFFSET + self.val_data.len() + val.len(); key_data_size <= limit && val_data_size <= limit } /// Add a record to Self. /// /// Returns whether the record was successfully added. A record will not a /// added if it exceeds the size limitations of ColumnarBatch. This method /// is atomic, if it fails, no partial data will have been added. #[must_use] pub fn push(&mut self, record: ((&[u8], &[u8]), [u8; 8], [u8; 8])) -> bool { let ((key, val), ts, diff) = record; // Check size invariants ahead of time so we stay atomic when we can't // add the record. if!self.can_fit(key, val, KEY_VAL_DATA_MAX_LEN) { return false; } // NB: We should never hit the following expects because we check them // above. self.key_data.extend_from_slice(key); self.key_offsets .push(i32::try_from(self.key_data.len()).expect("key_data is smaller than 2GB")); self.val_data.extend_from_slice(val); self.val_offsets .push(i32::try_from(self.val_data.len()).expect("val_data is smaller than 2GB")); self.timestamps.push(i64::from_le_bytes(ts)); self.diffs.push(i64::from_le_bytes(diff)); self.len += 1; true } /// Finalize constructing a [ColumnarRecords]. pub fn finish(self) -> ColumnarRecords { let ret = ColumnarRecords { len: self.len, key_data: Buffer::from(self.key_data), key_offsets: OffsetsBuffer::try_from(self.key_offsets) .expect("constructed valid offsets"), val_data: Buffer::from(self.val_data), val_offsets: OffsetsBuffer::try_from(self.val_offsets) .expect("constructed valid offsets"), timestamps: Buffer::from(self.timestamps), diffs: Buffer::from(self.diffs), }; debug_assert_eq!(ret.borrow().validate(), Ok(())); ret } /// Size of an update record as stored in the columnar representation pub fn columnar_record_size(key_bytes_len: usize, value_bytes_len: usize) -> usize { (key_bytes_len + BYTES_PER_KEY_VAL_OFFSET) + (value_bytes_len + BYTES_PER_KEY_VAL_OFFSET) + (2 * size_of::<u64>()) // T and D } } #[cfg(test)] mod tests { use mz_persist_types::Codec64; use super::*; /// Smoke test some edge cases around empty sets of records and empty keys/vals /// /// Most of this functionality is also well-exercised in other unit tests as well. #[mz_ore::test] fn columnar_records() { let builder = ColumnarRecordsBuilder::default(); // Empty builder. let records = builder.finish(); let reads: Vec<_> = records.iter().collect(); assert_eq!(reads, vec![]); // Empty key and val. let updates: Vec<((Vec<u8>, Vec<u8>), u64, i64)> = vec![ (("".into(), "".into()), 0, 0), (("".into(), "".into()), 1, 1), ]; let mut builder = ColumnarRecordsBuilder::default(); for ((key, val), time, diff) in updates.iter() { assert!(builder.push(((key, val), u64::encode(time), i64::encode(diff)))); } let records = builder.finish(); let reads: Vec<_> = records .iter() .map(|((k, v), t, d)| ((k.to_vec(), v.to_vec()), u64::decode(t), i64::decode(d))) .
/// Borrow Self as a [ColumnarRecordsRef]. fn borrow<'a>(&'a self) -> ColumnarRecordsRef<'a> { let ret = ColumnarRecordsRef { len: self.len,
random_line_split
columnar.rs
rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0. //! A columnar representation of ((Key, Val), Time, i64) data suitable for in-memory //! reads and persistent storage. use std::mem::size_of; use std::{cmp, fmt}; use arrow2::buffer::Buffer; use arrow2::offset::OffsetsBuffer; use arrow2::types::Index; pub mod arrow; pub mod parquet; /// The maximum allowed amount of total key data (similarly val data) in a /// single ColumnarBatch. /// /// Note that somewhat counter-intuitively, this also includes offsets (counting /// as 4 bytes each) in the definition of "key/val data". /// /// TODO: The limit on the amount of {key,val} data is because we use i32 /// offsets in parquet; this won't change. However, we include the offsets in /// the size because the parquet library we use currently maps each Array 1:1 /// with a parquet "page" (so for a "binary" column this is both the offsets and /// the data). The parquet format internally stores the size of a page in an /// i32, so if this gets too big, our library overflows it and writes bad data. /// There's no reason it needs to map an Array 1:1 to a page (it could instead /// be 1:1 with a "column chunk", which contains 1 or more pages). For now, we /// work around it. // TODO(benesch): find a way to express this without `as`. #[allow(clippy::as_conversions)] pub const KEY_VAL_DATA_MAX_LEN: usize = i32::MAX as usize; const BYTES_PER_KEY_VAL_OFFSET: usize = 4; /// A set of ((Key, Val), Time, Diff) records stored in a columnar /// representation. /// /// Note that the data are unsorted, and unconsolidated (so there may be /// multiple instances of the same ((Key, Val), Time), and some Diffs might be /// zero, or add up to zero). /// /// Both Time and Diff are presented externally to persist users as a type /// parameter that implements [mz_persist_types::Codec64]. Our columnar format /// intentionally stores them both as i64 columns (as opposed to something like /// a fixed width binary column) because this allows us additional compression /// options. /// /// Also note that we intentionally use an i64 over a u64 for Time. Over the /// range `[0, i64::MAX]`, the bytes are the same and we've talked at various /// times about changing Time in mz to an i64. Both millis since unix epoch and /// nanos since unix epoch easily fit into this range (the latter until some /// time after year 2200). Using a i64 might be a pessimization for a /// non-realtime mz source with u64 timestamps in the range `(i64::MAX, /// u64::MAX]`, but realtime sources are overwhelmingly the common case. /// /// The i'th key's data is stored in /// `key_data[key_offsets[i]..key_offsets[i+1]]`. Similarly for val. /// /// Invariants: /// - len < usize::MAX (so len+1 can fit in a usize) /// - key_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + key_data.len() <= KEY_VAL_DATA_MAX_LEN /// - key_offsets.len() == len + 1 /// - key_offsets are non-decreasing /// - Each key_offset is <= key_data.len() /// - key_offsets.first().unwrap() == 0 /// - key_offsets.last().unwrap() == key_data.len() /// - val_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + val_data.len() <= KEY_VAL_DATA_MAX_LEN /// - val_offsets.len() == len + 1 /// - val_offsets are non-decreasing /// - Each val_offset is <= val_data.len() /// - val_offsets.first().unwrap() == 0 /// - val_offsets.last().unwrap() == val_data.len() /// - timestamps.len() == len /// - diffs.len() == len #[derive(Clone, PartialEq)] pub struct ColumnarRecords { len: usize, key_data: Buffer<u8>, key_offsets: OffsetsBuffer<i32>, val_data: Buffer<u8>, val_offsets: OffsetsBuffer<i32>, timestamps: Buffer<i64>, diffs: Buffer<i64>, } impl fmt::Debug for ColumnarRecords { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.borrow(), fmt) } } impl ColumnarRecords { /// The number of (potentially duplicated) ((Key, Val), Time, i64) records /// stored in Self. pub fn len(&self) -> usize { self.len } /// The number of logical bytes in the represented data, excluding offsets /// and lengths. pub fn goodbytes(&self) -> usize { self.key_data.len() + self.val_data.len() + 8 * self.timestamps.len() + 8 * self.diffs.len() } /// Read the record at `idx`, if there is one. /// /// Returns None if `idx >= self.len()`. pub fn get<'a>(&'a self, idx: usize) -> Option<((&'a [u8], &'a [u8]), [u8; 8], [u8; 8])> { self.borrow().get(idx) } /// Borrow Self as a [ColumnarRecordsRef]. fn borrow<'a>(&'a self) -> ColumnarRecordsRef<'a> { // The ColumnarRecords constructor already validates, so don't bother // doing it again. // // TODO: Forcing everything through a `fn new` would make this more // obvious. ColumnarRecordsRef { len: self.len, key_data: self.key_data.as_slice(), key_offsets: self.key_offsets.as_slice(), val_data: self.val_data.as_slice(), val_offsets: self.val_offsets.as_slice(), timestamps: self.timestamps.as_slice(), diffs: self.diffs.as_slice(), } } /// Iterate through the records in Self. pub fn iter<'a>(&'a self) -> ColumnarRecordsIter<'a> { self.borrow().iter() } } /// A reference to a [ColumnarRecords]. #[derive(Clone)] struct ColumnarRecordsRef<'a> { len: usize, key_data: &'a [u8], key_offsets: &'a [i32], val_data: &'a [u8], val_offsets: &'a [i32], timestamps: &'a [i64], diffs: &'a [i64], } impl<'a> fmt::Debug for ColumnarRecordsRef<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_list().entries(self.iter()).finish() } } impl<'a> ColumnarRecordsRef<'a> { fn validate(&self) -> Result<(), String> { let key_data_size = self.key_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + self.key_data.len(); if key_data_size > KEY_VAL_DATA_MAX_LEN { return Err(format!( "expected encoded key offsets and data size to be less than or equal to {} got {}", KEY_VAL_DATA_MAX_LEN, key_data_size )); } if self.key_offsets.len()!= self.len + 1 { return Err(format!( "expected {} key_offsets got {}", self.len + 1, self.key_offsets.len() )); } if let Some(first_key_offset) = self.key_offsets.first() { if first_key_offset.to_usize()!= 0 { return Err(format!( "expected first key offset to be 0 got {}", first_key_offset.to_usize() )); } } if let Some(last_key_offset) = self.key_offsets.last() { if last_key_offset.to_usize()!= self.key_data.len() { return Err(format!( "expected {} bytes of key data got {}", last_key_offset, self.key_data.len() )); } } let val_data_size = self.val_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + self.val_data.len(); if val_data_size > KEY_VAL_DATA_MAX_LEN { return Err(format!( "expected encoded val offsets and data size to be less than or equal to {} got {}", KEY_VAL_DATA_MAX_LEN, val_data_size )); } if self.val_offsets.len()!= self.len + 1 { return Err(format!( "expected {} val_offsets got {}", self.len + 1, self.val_offsets.len() )); } if let Some(first_val_offset) = self.val_offsets.first() { if first_val_offset.to_usize()!= 0 { return Err(format!( "expected first val offset to be 0 got {}", first_val_offset.to_usize() )); } } if let Some(last_val_offset) = self.val_offsets.last() { if last_val_offset.to_usize()!= self.val_data.len() { return Err(format!( "expected {} bytes of val data got {}", last_val_offset, self.val_data.len() )); } } if self.diffs.len()!= self.len { return Err(format!( "expected {} diffs got {}", self.len, self.diffs.len() )); } if self.timestamps.len()!= self.len { return Err(format!( "expected {} timestamps got {}", self.len, self.timestamps.len() )); } // Unlike most of our Validate methods, this one is called in a // production code path: when decoding a columnar batch. Only check the // more expensive assertions in debug. #[cfg(debug_assertions)] { let (mut prev_key, mut prev_val) = (0, 0); for i in 0..=self.len { let (key, val) = (self.key_offsets[i], self.val_offsets[i]); if key < prev_key { return Err(format!( "expected non-decreasing key offsets got {} followed by {}", prev_key, key )); } if val < prev_val { return Err(format!( "expected non-decreasing val offsets got {} followed by {}", prev_val, val )); } prev_key = key; prev_val = val; } } Ok(()) } /// Read the record at `idx`, if there is one. /// /// Returns None if `idx >= self.len()`. fn get(&self, idx: usize) -> Option<((&'a [u8], &'a [u8]), [u8; 8], [u8; 8])> { if idx >= self.len { return None; } // There used to be `debug_assert_eq!(self.validate(), Ok(()))`, but it // resulted in accidentally O(n^2) behavior in debug mode. Instead, we // push that responsibility to the ColumnarRecordsRef constructor. let key_range = self.key_offsets[idx].to_usize()..self.key_offsets[idx + 1].to_usize(); let val_range = self.val_offsets[idx].to_usize()..self.val_offsets[idx + 1].to_usize(); let key = &self.key_data[key_range]; let val = &self.val_data[val_range]; let ts = i64::to_le_bytes(self.timestamps[idx]); let diff = i64::to_le_bytes(self.diffs[idx]); Some(((key, val), ts, diff)) } /// Iterate through the records in Self. fn iter(&self) -> ColumnarRecordsIter<'a> { ColumnarRecordsIter { idx: 0, records: self.clone(), } } } /// An [Iterator] over the records in a [ColumnarRecords]. #[derive(Clone, Debug)] pub struct ColumnarRecordsIter<'a> { idx: usize, records: ColumnarRecordsRef<'a>, } impl<'a> Iterator for ColumnarRecordsIter<'a> { type Item = ((&'a [u8], &'a [u8]), [u8; 8], [u8; 8]); fn size_hint(&self) -> (usize, Option<usize>) { (self.records.len, Some(self.records.len)) } fn next(&mut self) -> Option<Self::Item> { let ret = self.records.get(self.idx); self.idx += 1; ret } } impl<'a> ExactSizeIterator for ColumnarRecordsIter<'a> {} /// An abstraction to incrementally add ((Key, Value), Time, i64) records /// in a columnar representation, and eventually get back a [ColumnarRecords]. pub struct ColumnarRecordsBuilder { len: usize, key_data: Vec<u8>, key_offsets: Vec<i32>, val_data: Vec<u8>, val_offsets: Vec<i32>, timestamps: Vec<i64>, diffs: Vec<i64>, } impl fmt::Debug for ColumnarRecordsBuilder { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.borrow(), fmt) } } impl Default for ColumnarRecordsBuilder { fn default() -> Self { let mut ret = ColumnarRecordsBuilder { len: 0, key_data: Vec::new(), key_offsets: Vec::new(), val_data: Vec::new(), val_offsets: Vec::new(), timestamps: Vec::new(), diffs: Vec::new(), }; // Push initial 0 offsets to maintain our invariants, even as we build. ret.key_offsets.push(0); ret.val_offsets.push(0); debug_assert_eq!(ret.borrow().validate(), Ok(())); ret } } impl ColumnarRecordsBuilder { /// The number of (potentially duplicated) ((Key, Val), Time, i64) records /// stored in Self. pub fn len(&self) -> usize { self.len } /// Borrow Self as a [ColumnarRecordsRef]. fn borrow<'a>(&'a self) -> ColumnarRecordsRef<'a> { let ret = ColumnarRecordsRef { len: self.len, key_data: self.key_data.as_slice(), key_offsets: self.key_offsets.as_slice(), val_data: self.val_data.as_slice(), val_offsets: self.val_offsets.as_slice(), timestamps: self.timestamps.as_slice(), diffs: self.diffs.as_slice(), }; debug_assert_eq!(ret.validate(), Ok(())); ret } /// Reserve space for `additional` more records, based on `key_size_guess` and /// `val_size_guess`. /// /// The guesses for key and val sizes are best effort, and if they end up being /// too small, the underlying buffers will be resized. pub fn reserve(&mut self, additional: usize, key_size_guess: usize, val_size_guess: usize) { self.key_offsets.reserve(additional); self.key_data .reserve(cmp::min(additional * key_size_guess, KEY_VAL_DATA_MAX_LEN)); self.val_offsets.reserve(additional); self.val_data .reserve(cmp::min(additional * val_size_guess, KEY_VAL_DATA_MAX_LEN)); self.timestamps.reserve(additional); self.diffs.reserve(additional); debug_assert_eq!(self.borrow().validate(), Ok(())); } /// Reserve space for `additional` more records, with exact sizes for the key and value data. pub fn reserve_exact(&mut self, additional: usize, key_bytes: usize, val_bytes: usize) { self.key_offsets.reserve(additional); self.key_data .reserve(cmp::min(key_bytes, KEY_VAL_DATA_MAX_LEN)); self.val_offsets.reserve(additional); self.val_data .reserve(cmp::min(val_bytes, KEY_VAL_DATA_MAX_LEN)); self.timestamps.reserve(additional); self.diffs.reserve(additional); debug_assert_eq!(self.borrow().validate(), Ok(())); } /// Returns if the given key_offsets+key_data or val_offsets+val_data fits /// in the limits imposed by ColumnarRecords. /// /// Note that limit is always [KEY_VAL_DATA_MAX_LEN] in production. It's /// only override-able here for testing. pub fn can_fit(&self, key: &[u8], val: &[u8], limit: usize) -> bool { let key_data_size = (self.key_offsets.len() + 1) * BYTES_PER_KEY_VAL_OFFSET + self.key_data.len() + key.len(); let val_data_size = (self.val_offsets.len() + 1) * BYTES_PER_KEY_VAL_OFFSET + self.val_data.len() + val.len(); key_data_size <= limit && val_data_size <= limit } /// Add a record to Self. /// /// Returns whether the record was successfully added. A record will not a /// added if it exceeds the size limitations of ColumnarBatch. This method /// is atomic, if it fails, no partial data will have been added. #[must_use] pub fn push(&mut self, record: ((&[u8], &[u8]), [u8; 8], [u8; 8])) -> bool { let ((key, val), ts, diff) = record; // Check size invariants ahead of time so we stay atomic when we can't // add the record. if!self.can_fit(key, val, KEY_VAL_DATA_MAX_LEN) { return false; } // NB: We should never hit the following expects because we check them // above. self.key_data.extend_from_slice(key); self.key_offsets .push(i32::try_from(self.key_data.len()).expect("key_data is smaller than 2GB")); self.val_data.extend_from_slice(val); self.val_offsets .push(i32::try_from(self.val_data.len()).expect("val_data is smaller than 2GB")); self.timestamps.push(i64::from_le_bytes(ts)); self.diffs.push(i64::from_le_bytes(diff)); self.len += 1; true } /// Finalize constructing a [ColumnarRecords]. pub fn
(self) -> ColumnarRecords { let ret = ColumnarRecords { len: self.len, key_data: Buffer::from(self.key_data), key_offsets: OffsetsBuffer::try_from(self.key_offsets) .expect("constructed valid offsets"), val_data: Buffer::from(self.val_data), val_offsets: OffsetsBuffer::try_from(self.val_offsets) .expect("constructed valid offsets"), timestamps: Buffer::from(self.timestamps), diffs: Buffer::from(self.diffs), }; debug_assert_eq!(ret.borrow().validate(), Ok(())); ret } /// Size of an update record as stored in the columnar representation pub fn columnar_record_size(key_bytes_len: usize, value_bytes_len: usize) -> usize { (key_bytes_len + BYTES_PER_KEY_VAL_OFFSET) + (value_bytes_len + BYTES_PER_KEY_VAL_OFFSET) + (2 * size_of::<u64>()) // T and D } } #[cfg(test)] mod tests { use mz_persist_types::Codec64; use super::*; /// Smoke test some edge cases around empty sets of records and empty keys/vals /// /// Most of this functionality is also well-exercised in other unit tests as well. #[mz_ore::test] fn columnar_records() { let builder = ColumnarRecordsBuilder::default(); // Empty builder. let records = builder.finish(); let reads: Vec<_> = records.iter().collect(); assert_eq!(reads, vec![]); // Empty key and val. let updates: Vec<((Vec<u8>, Vec<u8>), u64, i64)> = vec![ (("".into(), "".into()), 0, 0), (("".into(), "".into()), 1, 1), ]; let mut builder = ColumnarRecordsBuilder::default(); for ((key, val), time, diff) in updates.iter() { assert!(builder.push(((key, val), u64::encode(time), i64::encode(diff)))); } let records = builder.finish(); let reads: Vec<_> = records .iter() .map(|((k, v), t, d)| ((k.to_vec(), v.to_vec()), u64::decode(t), i64::decode(d)))
finish
identifier_name
columnar.rs
rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0. //! A columnar representation of ((Key, Val), Time, i64) data suitable for in-memory //! reads and persistent storage. use std::mem::size_of; use std::{cmp, fmt}; use arrow2::buffer::Buffer; use arrow2::offset::OffsetsBuffer; use arrow2::types::Index; pub mod arrow; pub mod parquet; /// The maximum allowed amount of total key data (similarly val data) in a /// single ColumnarBatch. /// /// Note that somewhat counter-intuitively, this also includes offsets (counting /// as 4 bytes each) in the definition of "key/val data". /// /// TODO: The limit on the amount of {key,val} data is because we use i32 /// offsets in parquet; this won't change. However, we include the offsets in /// the size because the parquet library we use currently maps each Array 1:1 /// with a parquet "page" (so for a "binary" column this is both the offsets and /// the data). The parquet format internally stores the size of a page in an /// i32, so if this gets too big, our library overflows it and writes bad data. /// There's no reason it needs to map an Array 1:1 to a page (it could instead /// be 1:1 with a "column chunk", which contains 1 or more pages). For now, we /// work around it. // TODO(benesch): find a way to express this without `as`. #[allow(clippy::as_conversions)] pub const KEY_VAL_DATA_MAX_LEN: usize = i32::MAX as usize; const BYTES_PER_KEY_VAL_OFFSET: usize = 4; /// A set of ((Key, Val), Time, Diff) records stored in a columnar /// representation. /// /// Note that the data are unsorted, and unconsolidated (so there may be /// multiple instances of the same ((Key, Val), Time), and some Diffs might be /// zero, or add up to zero). /// /// Both Time and Diff are presented externally to persist users as a type /// parameter that implements [mz_persist_types::Codec64]. Our columnar format /// intentionally stores them both as i64 columns (as opposed to something like /// a fixed width binary column) because this allows us additional compression /// options. /// /// Also note that we intentionally use an i64 over a u64 for Time. Over the /// range `[0, i64::MAX]`, the bytes are the same and we've talked at various /// times about changing Time in mz to an i64. Both millis since unix epoch and /// nanos since unix epoch easily fit into this range (the latter until some /// time after year 2200). Using a i64 might be a pessimization for a /// non-realtime mz source with u64 timestamps in the range `(i64::MAX, /// u64::MAX]`, but realtime sources are overwhelmingly the common case. /// /// The i'th key's data is stored in /// `key_data[key_offsets[i]..key_offsets[i+1]]`. Similarly for val. /// /// Invariants: /// - len < usize::MAX (so len+1 can fit in a usize) /// - key_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + key_data.len() <= KEY_VAL_DATA_MAX_LEN /// - key_offsets.len() == len + 1 /// - key_offsets are non-decreasing /// - Each key_offset is <= key_data.len() /// - key_offsets.first().unwrap() == 0 /// - key_offsets.last().unwrap() == key_data.len() /// - val_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + val_data.len() <= KEY_VAL_DATA_MAX_LEN /// - val_offsets.len() == len + 1 /// - val_offsets are non-decreasing /// - Each val_offset is <= val_data.len() /// - val_offsets.first().unwrap() == 0 /// - val_offsets.last().unwrap() == val_data.len() /// - timestamps.len() == len /// - diffs.len() == len #[derive(Clone, PartialEq)] pub struct ColumnarRecords { len: usize, key_data: Buffer<u8>, key_offsets: OffsetsBuffer<i32>, val_data: Buffer<u8>, val_offsets: OffsetsBuffer<i32>, timestamps: Buffer<i64>, diffs: Buffer<i64>, } impl fmt::Debug for ColumnarRecords { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.borrow(), fmt) } } impl ColumnarRecords { /// The number of (potentially duplicated) ((Key, Val), Time, i64) records /// stored in Self. pub fn len(&self) -> usize { self.len } /// The number of logical bytes in the represented data, excluding offsets /// and lengths. pub fn goodbytes(&self) -> usize { self.key_data.len() + self.val_data.len() + 8 * self.timestamps.len() + 8 * self.diffs.len() } /// Read the record at `idx`, if there is one. /// /// Returns None if `idx >= self.len()`. pub fn get<'a>(&'a self, idx: usize) -> Option<((&'a [u8], &'a [u8]), [u8; 8], [u8; 8])> { self.borrow().get(idx) } /// Borrow Self as a [ColumnarRecordsRef]. fn borrow<'a>(&'a self) -> ColumnarRecordsRef<'a> { // The ColumnarRecords constructor already validates, so don't bother // doing it again. // // TODO: Forcing everything through a `fn new` would make this more // obvious. ColumnarRecordsRef { len: self.len, key_data: self.key_data.as_slice(), key_offsets: self.key_offsets.as_slice(), val_data: self.val_data.as_slice(), val_offsets: self.val_offsets.as_slice(), timestamps: self.timestamps.as_slice(), diffs: self.diffs.as_slice(), } } /// Iterate through the records in Self. pub fn iter<'a>(&'a self) -> ColumnarRecordsIter<'a> { self.borrow().iter() } } /// A reference to a [ColumnarRecords]. #[derive(Clone)] struct ColumnarRecordsRef<'a> { len: usize, key_data: &'a [u8], key_offsets: &'a [i32], val_data: &'a [u8], val_offsets: &'a [i32], timestamps: &'a [i64], diffs: &'a [i64], } impl<'a> fmt::Debug for ColumnarRecordsRef<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_list().entries(self.iter()).finish() } } impl<'a> ColumnarRecordsRef<'a> { fn validate(&self) -> Result<(), String> { let key_data_size = self.key_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + self.key_data.len(); if key_data_size > KEY_VAL_DATA_MAX_LEN { return Err(format!( "expected encoded key offsets and data size to be less than or equal to {} got {}", KEY_VAL_DATA_MAX_LEN, key_data_size )); } if self.key_offsets.len()!= self.len + 1 { return Err(format!( "expected {} key_offsets got {}", self.len + 1, self.key_offsets.len() )); } if let Some(first_key_offset) = self.key_offsets.first() { if first_key_offset.to_usize()!= 0 { return Err(format!( "expected first key offset to be 0 got {}", first_key_offset.to_usize() )); } } if let Some(last_key_offset) = self.key_offsets.last() { if last_key_offset.to_usize()!= self.key_data.len() { return Err(format!( "expected {} bytes of key data got {}", last_key_offset, self.key_data.len() )); } } let val_data_size = self.val_offsets.len() * BYTES_PER_KEY_VAL_OFFSET + self.val_data.len(); if val_data_size > KEY_VAL_DATA_MAX_LEN { return Err(format!( "expected encoded val offsets and data size to be less than or equal to {} got {}", KEY_VAL_DATA_MAX_LEN, val_data_size )); } if self.val_offsets.len()!= self.len + 1
if let Some(first_val_offset) = self.val_offsets.first() { if first_val_offset.to_usize()!= 0 { return Err(format!( "expected first val offset to be 0 got {}", first_val_offset.to_usize() )); } } if let Some(last_val_offset) = self.val_offsets.last() { if last_val_offset.to_usize()!= self.val_data.len() { return Err(format!( "expected {} bytes of val data got {}", last_val_offset, self.val_data.len() )); } } if self.diffs.len()!= self.len { return Err(format!( "expected {} diffs got {}", self.len, self.diffs.len() )); } if self.timestamps.len()!= self.len { return Err(format!( "expected {} timestamps got {}", self.len, self.timestamps.len() )); } // Unlike most of our Validate methods, this one is called in a // production code path: when decoding a columnar batch. Only check the // more expensive assertions in debug. #[cfg(debug_assertions)] { let (mut prev_key, mut prev_val) = (0, 0); for i in 0..=self.len { let (key, val) = (self.key_offsets[i], self.val_offsets[i]); if key < prev_key { return Err(format!( "expected non-decreasing key offsets got {} followed by {}", prev_key, key )); } if val < prev_val { return Err(format!( "expected non-decreasing val offsets got {} followed by {}", prev_val, val )); } prev_key = key; prev_val = val; } } Ok(()) } /// Read the record at `idx`, if there is one. /// /// Returns None if `idx >= self.len()`. fn get(&self, idx: usize) -> Option<((&'a [u8], &'a [u8]), [u8; 8], [u8; 8])> { if idx >= self.len { return None; } // There used to be `debug_assert_eq!(self.validate(), Ok(()))`, but it // resulted in accidentally O(n^2) behavior in debug mode. Instead, we // push that responsibility to the ColumnarRecordsRef constructor. let key_range = self.key_offsets[idx].to_usize()..self.key_offsets[idx + 1].to_usize(); let val_range = self.val_offsets[idx].to_usize()..self.val_offsets[idx + 1].to_usize(); let key = &self.key_data[key_range]; let val = &self.val_data[val_range]; let ts = i64::to_le_bytes(self.timestamps[idx]); let diff = i64::to_le_bytes(self.diffs[idx]); Some(((key, val), ts, diff)) } /// Iterate through the records in Self. fn iter(&self) -> ColumnarRecordsIter<'a> { ColumnarRecordsIter { idx: 0, records: self.clone(), } } } /// An [Iterator] over the records in a [ColumnarRecords]. #[derive(Clone, Debug)] pub struct ColumnarRecordsIter<'a> { idx: usize, records: ColumnarRecordsRef<'a>, } impl<'a> Iterator for ColumnarRecordsIter<'a> { type Item = ((&'a [u8], &'a [u8]), [u8; 8], [u8; 8]); fn size_hint(&self) -> (usize, Option<usize>) { (self.records.len, Some(self.records.len)) } fn next(&mut self) -> Option<Self::Item> { let ret = self.records.get(self.idx); self.idx += 1; ret } } impl<'a> ExactSizeIterator for ColumnarRecordsIter<'a> {} /// An abstraction to incrementally add ((Key, Value), Time, i64) records /// in a columnar representation, and eventually get back a [ColumnarRecords]. pub struct ColumnarRecordsBuilder { len: usize, key_data: Vec<u8>, key_offsets: Vec<i32>, val_data: Vec<u8>, val_offsets: Vec<i32>, timestamps: Vec<i64>, diffs: Vec<i64>, } impl fmt::Debug for ColumnarRecordsBuilder { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.borrow(), fmt) } } impl Default for ColumnarRecordsBuilder { fn default() -> Self { let mut ret = ColumnarRecordsBuilder { len: 0, key_data: Vec::new(), key_offsets: Vec::new(), val_data: Vec::new(), val_offsets: Vec::new(), timestamps: Vec::new(), diffs: Vec::new(), }; // Push initial 0 offsets to maintain our invariants, even as we build. ret.key_offsets.push(0); ret.val_offsets.push(0); debug_assert_eq!(ret.borrow().validate(), Ok(())); ret } } impl ColumnarRecordsBuilder { /// The number of (potentially duplicated) ((Key, Val), Time, i64) records /// stored in Self. pub fn len(&self) -> usize { self.len } /// Borrow Self as a [ColumnarRecordsRef]. fn borrow<'a>(&'a self) -> ColumnarRecordsRef<'a> { let ret = ColumnarRecordsRef { len: self.len, key_data: self.key_data.as_slice(), key_offsets: self.key_offsets.as_slice(), val_data: self.val_data.as_slice(), val_offsets: self.val_offsets.as_slice(), timestamps: self.timestamps.as_slice(), diffs: self.diffs.as_slice(), }; debug_assert_eq!(ret.validate(), Ok(())); ret } /// Reserve space for `additional` more records, based on `key_size_guess` and /// `val_size_guess`. /// /// The guesses for key and val sizes are best effort, and if they end up being /// too small, the underlying buffers will be resized. pub fn reserve(&mut self, additional: usize, key_size_guess: usize, val_size_guess: usize) { self.key_offsets.reserve(additional); self.key_data .reserve(cmp::min(additional * key_size_guess, KEY_VAL_DATA_MAX_LEN)); self.val_offsets.reserve(additional); self.val_data .reserve(cmp::min(additional * val_size_guess, KEY_VAL_DATA_MAX_LEN)); self.timestamps.reserve(additional); self.diffs.reserve(additional); debug_assert_eq!(self.borrow().validate(), Ok(())); } /// Reserve space for `additional` more records, with exact sizes for the key and value data. pub fn reserve_exact(&mut self, additional: usize, key_bytes: usize, val_bytes: usize) { self.key_offsets.reserve(additional); self.key_data .reserve(cmp::min(key_bytes, KEY_VAL_DATA_MAX_LEN)); self.val_offsets.reserve(additional); self.val_data .reserve(cmp::min(val_bytes, KEY_VAL_DATA_MAX_LEN)); self.timestamps.reserve(additional); self.diffs.reserve(additional); debug_assert_eq!(self.borrow().validate(), Ok(())); } /// Returns if the given key_offsets+key_data or val_offsets+val_data fits /// in the limits imposed by ColumnarRecords. /// /// Note that limit is always [KEY_VAL_DATA_MAX_LEN] in production. It's /// only override-able here for testing. pub fn can_fit(&self, key: &[u8], val: &[u8], limit: usize) -> bool { let key_data_size = (self.key_offsets.len() + 1) * BYTES_PER_KEY_VAL_OFFSET + self.key_data.len() + key.len(); let val_data_size = (self.val_offsets.len() + 1) * BYTES_PER_KEY_VAL_OFFSET + self.val_data.len() + val.len(); key_data_size <= limit && val_data_size <= limit } /// Add a record to Self. /// /// Returns whether the record was successfully added. A record will not a /// added if it exceeds the size limitations of ColumnarBatch. This method /// is atomic, if it fails, no partial data will have been added. #[must_use] pub fn push(&mut self, record: ((&[u8], &[u8]), [u8; 8], [u8; 8])) -> bool { let ((key, val), ts, diff) = record; // Check size invariants ahead of time so we stay atomic when we can't // add the record. if!self.can_fit(key, val, KEY_VAL_DATA_MAX_LEN) { return false; } // NB: We should never hit the following expects because we check them // above. self.key_data.extend_from_slice(key); self.key_offsets .push(i32::try_from(self.key_data.len()).expect("key_data is smaller than 2GB")); self.val_data.extend_from_slice(val); self.val_offsets .push(i32::try_from(self.val_data.len()).expect("val_data is smaller than 2GB")); self.timestamps.push(i64::from_le_bytes(ts)); self.diffs.push(i64::from_le_bytes(diff)); self.len += 1; true } /// Finalize constructing a [ColumnarRecords]. pub fn finish(self) -> ColumnarRecords { let ret = ColumnarRecords { len: self.len, key_data: Buffer::from(self.key_data), key_offsets: OffsetsBuffer::try_from(self.key_offsets) .expect("constructed valid offsets"), val_data: Buffer::from(self.val_data), val_offsets: OffsetsBuffer::try_from(self.val_offsets) .expect("constructed valid offsets"), timestamps: Buffer::from(self.timestamps), diffs: Buffer::from(self.diffs), }; debug_assert_eq!(ret.borrow().validate(), Ok(())); ret } /// Size of an update record as stored in the columnar representation pub fn columnar_record_size(key_bytes_len: usize, value_bytes_len: usize) -> usize { (key_bytes_len + BYTES_PER_KEY_VAL_OFFSET) + (value_bytes_len + BYTES_PER_KEY_VAL_OFFSET) + (2 * size_of::<u64>()) // T and D } } #[cfg(test)] mod tests { use mz_persist_types::Codec64; use super::*; /// Smoke test some edge cases around empty sets of records and empty keys/vals /// /// Most of this functionality is also well-exercised in other unit tests as well. #[mz_ore::test] fn columnar_records() { let builder = ColumnarRecordsBuilder::default(); // Empty builder. let records = builder.finish(); let reads: Vec<_> = records.iter().collect(); assert_eq!(reads, vec![]); // Empty key and val. let updates: Vec<((Vec<u8>, Vec<u8>), u64, i64)> = vec![ (("".into(), "".into()), 0, 0), (("".into(), "".into()), 1, 1), ]; let mut builder = ColumnarRecordsBuilder::default(); for ((key, val), time, diff) in updates.iter() { assert!(builder.push(((key, val), u64::encode(time), i64::encode(diff)))); } let records = builder.finish(); let reads: Vec<_> = records .iter() .map(|((k, v), t, d)| ((k.to_vec(), v.to_vec()), u64::decode(t), i64::decode(d)))
{ return Err(format!( "expected {} val_offsets got {}", self.len + 1, self.val_offsets.len() )); }
conditional_block
mod.rs
use std::{ alloc::Layout, array::TryFromSliceError, borrow::BorrowMut, cell::{Cell, UnsafeCell}, collections::HashMap, ffi::OsStr, fs, io::{self, Read, Write}, mem, ops::{Deref, DerefMut}, path::Path, sync::{Arc, Mutex, MutexGuard},
use anyhow::{anyhow, Result}; use bevy_ecs::{ ComponentId, DynamicFetch, DynamicFetchResult, DynamicQuery, DynamicSystem, EntityBuilder, QueryAccess, StatefulQuery, TypeAccess, TypeInfo, World, }; use bincode::DefaultOptions; use fs::OpenOptions; use io::IoSlice; use mem::ManuallyDrop; use quill::ecs::TypeLayout; use wasmer::{ import_namespace, imports, Array, FromToNativeWasmType, Function, HostEnvInitError, Instance, LazyInit, Memory, Module, NativeFunc, Store, Type, ValueType, WasmPtr, WasmTypeList, WasmerEnv, JIT, LLVM, }; use wasmer_wasi::WasiState; use serde::{de::DeserializeOwned, Deserialize, Serialize}; #[derive(Default)] struct PluginEnv<S> { memory: LazyInit<Memory>, buffer_reserve: LazyInit<NativeFunc<(WasmPtr<RawBuffer>, u32)>>, rpcs: Arc<Mutex<HashMap<String, Box<dyn Fn(&mut Buffer, &PluginEnv<S>) -> Result<()> + Send>>>>, state: Arc<Mutex<S>>, layouts: Arc<Mutex<Layouts>>, } impl<S: Send + Sync +'static> Clone for PluginEnv<S> { fn clone(&self) -> Self { Self { memory: self.memory.clone(), buffer_reserve: self.buffer_reserve.clone(), rpcs: self.rpcs.clone(), state: self.state.clone(), layouts: Default::default(), } } } impl<S: Send + Sync +'static> WasmerEnv for PluginEnv<S> { fn init_with_instance(&mut self, instance: &Instance) -> Result<(), HostEnvInitError> { let memory = instance.exports.get_memory("memory")?; self.memory.initialize(memory.clone()); self.buffer_reserve.initialize( instance .exports .get_native_function("__quill_buffer_reserve")?, ); Ok(()) } } impl<S: Send + Sync +'static> PluginEnv<S> { fn memory(&self) -> &Memory { // TODO: handle errors. self.memory.get_ref().unwrap() } fn buffer_reserve(&self) -> &NativeFunc<(WasmPtr<RawBuffer>, u32)> { self.buffer_reserve.get_ref().unwrap() } fn buffer(&self, raw: WasmPtr<RawBuffer>) -> Buffer { Buffer { memory: self.memory(), reserve: self.buffer_reserve(), raw, } } fn add_rpc< 'a, Args: Serialize + DeserializeOwned +'static, R: Serialize + DeserializeOwned +'static, >( &mut self, name: &str, callback: fn(&PluginEnv<S>, Args) -> R, ) -> Result<()> { self.rpcs .lock() .map_err(|_| anyhow!("could not lock rpcs"))? .insert( name.to_owned(), Box::new(move |mut buffer: &mut Buffer, env: &PluginEnv<S>| { let (_, args): (String, Args) = bincode::deserialize(buffer.as_slice()).unwrap(); let result = callback(env, args); buffer.clear(); bincode::serialize_into(buffer, &result).unwrap(); Ok(()) }), ); Ok(()) } fn call<Args: Serialize, R: DeserializeOwned>(&self, name: &str, args: Args) -> Result<R> { // TODO: requires access to buffer. todo!() } } pub struct Plugin { instance: Instance, env: PluginEnv<World>, } impl Plugin { pub fn load<P: AsRef<Path>>(path: P) -> Result<Self> { let mut env = PluginEnv::default(); let store = Store::new(&JIT::new(LLVM::default()).engine()); let module = Module::from_file(&store, &path)?; let mut wasi_env = WasiState::new( path.as_ref() .file_name() .and_then(OsStr::to_str) .unwrap_or("unkown"), ) .finalize()?; let mut import_object = wasi_env.import_object(&module)?; import_object.register( "env", import_namespace!({ "__quill_host_call" => Function::new_native_with_env(&store, env.clone(), __quill_host_call), }), ); // env.add_rpc("players_push", |state, player: String| state.push(player))?; // // TODO: Return reference to state? // env.add_rpc("players", |state, ()| state.clone())?; env.add_rpc("world_spawn", |env, entity: quill::ecs::Entity| { let mut world = env.state.lock().unwrap(); let mut layouts = env.layouts.lock().unwrap(); let mut builder = EntityBuilder::new(); for (layout, data) in entity.components { builder.add_dynamic( TypeInfo::of_external( layouts.external_id(&layout), Layout::new::<Vec<u8>>(), |_| (), ), data.as_slice(), ); } world.spawn(builder.build()); })?; env.add_rpc( "world_query", // TODO: world should not be the state but union(world, layouts) |env, access: quill::ecs::QueryAccess| { let world = env.state.lock().unwrap(); let mut layouts = env.layouts.lock().unwrap(); let query = access.query(&mut layouts).unwrap(); let access = Default::default(); let mut query: StatefulQuery<DynamicQuery, DynamicQuery> = StatefulQuery::new(&world, &access, query); for entity in query.iter_mut() { entity.immutable; entity.mutable; } }, )?; let instance = Instance::new(&module, &import_object)?; let start = instance.exports.get_function("_start")?; start.call(&[])?; Ok(Plugin { instance, env }) } } #[derive(Default)] pub struct Layouts { layouts: HashMap<quill::ecs::TypeLayout, u64>, } impl Layouts { pub fn component_id(&mut self, layout: &TypeLayout) -> ComponentId { ComponentId::ExternalId(self.external_id(layout)) } pub fn external_id(&mut self, layout: &TypeLayout) -> u64 { if let Some(component_id) = self.layouts.get(&layout) { *component_id } else { let next = self.layouts.len() as u64; self.layouts.insert(layout.clone(), next); next } } } trait IntoBevyAccess { fn access(&self, layouts: &mut Layouts) -> Result<QueryAccess>; fn component_ids(&self) -> Result<Vec<ComponentId>>; fn query(&self, layouts: &mut Layouts) -> Result<DynamicQuery>; } impl IntoBevyAccess for quill::ecs::QueryAccess { fn access(&self, layouts: &mut Layouts) -> Result<QueryAccess> { use quill::ecs::QueryAccess::*; Ok(match self { None => QueryAccess::None, Read(layout) => QueryAccess::Read(layouts.component_id(layout), "??"), Write(layout) => QueryAccess::Write(layouts.component_id(layout), "??"), Optional(access) => { QueryAccess::optional(IntoBevyAccess::access(access.as_ref(), layouts)?) } With(layout, access) => QueryAccess::With( layouts.component_id(layout), Box::new(IntoBevyAccess::access(access.as_ref(), layouts)?), ), Without(layout, access) => QueryAccess::Without( layouts.component_id(layout), Box::new(IntoBevyAccess::access(access.as_ref(), layouts)?), ), Union(accesses) => QueryAccess::Union( accesses .into_iter() .map(|access| IntoBevyAccess::access(access, layouts)) .collect::<Result<Vec<QueryAccess>>>()?, ), }) } fn component_ids(&self) -> Result<Vec<ComponentId>> { todo!() } fn query(&self, layouts: &mut Layouts) -> Result<DynamicQuery> { let mut query = DynamicQuery::default(); query.access = self.access(layouts)?; // TODO: TypeInfo Ok(query) } } struct Buffer<'a> { memory: &'a Memory, // fn reserve(ptr: WasmPtr<u8, Array>, cap: u32, len: u32, additional: u32) reserve: &'a NativeFunc<(WasmPtr<RawBuffer>, u32)>, raw: WasmPtr<RawBuffer>, } #[repr(C)] #[derive(Debug, Clone, Copy)] struct RawBuffer { ptr: WasmPtr<u8, Array>, cap: u32, len: u32, } unsafe impl ValueType for RawBuffer {} impl<'a> Buffer<'a> { fn reserve(&mut self, additional: u32) { let raw = self.raw.deref(self.memory).unwrap().get(); if raw.cap < raw.len + additional { self.reserve.call(self.raw, additional).unwrap(); } } fn clear(&mut self) { let raw_cell = self.raw.deref(self.memory).unwrap(); raw_cell.set(RawBuffer { len: 0, ..raw_cell.get() }) } fn push(&mut self, byte: u8) { self.extend_from_slice(&[byte]); } fn extend_from_slice(&mut self, other: &[u8]) { self.reserve(other.len() as u32); let raw_cell = self.raw.deref(self.memory).unwrap(); let raw = raw_cell.get(); raw.ptr .deref(self.memory, raw.len, raw.cap) .unwrap() .into_iter() .zip(other.iter()) .for_each(|(cell, value)| cell.set(*value)); raw_cell.set(RawBuffer { len: raw.len + other.len() as u32, ..raw }); } fn as_slice(&self) -> &[u8] { self } } impl<'a> Write for Buffer<'a> { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.extend_from_slice(buf); Ok(buf.len()) } #[inline] fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { let len = bufs.iter().map(|b| b.len() as u32).sum(); self.reserve(len); for buf in bufs { self.extend_from_slice(buf); } Ok(len as usize) } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.extend_from_slice(buf); Ok(()) } #[inline] fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl<'a> Deref for Buffer<'a> { type Target = [u8]; fn deref(&self) -> &Self::Target { let raw = self.raw.deref(self.memory).unwrap().get(); unsafe { mem::transmute(raw.ptr.deref(self.memory, 0, raw.len).unwrap()) } } } impl<'a> AsRef<[u8]> for Buffer<'a> { fn as_ref(&self) -> &[u8] { self } } fn __quill_host_call(env: &PluginEnv<World>, buffer_raw: WasmPtr<RawBuffer>) { let mut buffer = env.buffer(buffer_raw); let name: String = bincode::deserialize_from(buffer.as_slice()).unwrap(); let rpcs = env.rpcs.lock().unwrap(); let rpc = rpcs.get(&name).unwrap(); rpc(&mut buffer, env).unwrap(); }
todo, u32, vec, };
random_line_split
mod.rs
use std::{ alloc::Layout, array::TryFromSliceError, borrow::BorrowMut, cell::{Cell, UnsafeCell}, collections::HashMap, ffi::OsStr, fs, io::{self, Read, Write}, mem, ops::{Deref, DerefMut}, path::Path, sync::{Arc, Mutex, MutexGuard}, todo, u32, vec, }; use anyhow::{anyhow, Result}; use bevy_ecs::{ ComponentId, DynamicFetch, DynamicFetchResult, DynamicQuery, DynamicSystem, EntityBuilder, QueryAccess, StatefulQuery, TypeAccess, TypeInfo, World, }; use bincode::DefaultOptions; use fs::OpenOptions; use io::IoSlice; use mem::ManuallyDrop; use quill::ecs::TypeLayout; use wasmer::{ import_namespace, imports, Array, FromToNativeWasmType, Function, HostEnvInitError, Instance, LazyInit, Memory, Module, NativeFunc, Store, Type, ValueType, WasmPtr, WasmTypeList, WasmerEnv, JIT, LLVM, }; use wasmer_wasi::WasiState; use serde::{de::DeserializeOwned, Deserialize, Serialize}; #[derive(Default)] struct PluginEnv<S> { memory: LazyInit<Memory>, buffer_reserve: LazyInit<NativeFunc<(WasmPtr<RawBuffer>, u32)>>, rpcs: Arc<Mutex<HashMap<String, Box<dyn Fn(&mut Buffer, &PluginEnv<S>) -> Result<()> + Send>>>>, state: Arc<Mutex<S>>, layouts: Arc<Mutex<Layouts>>, } impl<S: Send + Sync +'static> Clone for PluginEnv<S> { fn clone(&self) -> Self { Self { memory: self.memory.clone(), buffer_reserve: self.buffer_reserve.clone(), rpcs: self.rpcs.clone(), state: self.state.clone(), layouts: Default::default(), } } } impl<S: Send + Sync +'static> WasmerEnv for PluginEnv<S> { fn init_with_instance(&mut self, instance: &Instance) -> Result<(), HostEnvInitError> { let memory = instance.exports.get_memory("memory")?; self.memory.initialize(memory.clone()); self.buffer_reserve.initialize( instance .exports .get_native_function("__quill_buffer_reserve")?, ); Ok(()) } } impl<S: Send + Sync +'static> PluginEnv<S> { fn memory(&self) -> &Memory { // TODO: handle errors. self.memory.get_ref().unwrap() } fn buffer_reserve(&self) -> &NativeFunc<(WasmPtr<RawBuffer>, u32)> { self.buffer_reserve.get_ref().unwrap() } fn buffer(&self, raw: WasmPtr<RawBuffer>) -> Buffer { Buffer { memory: self.memory(), reserve: self.buffer_reserve(), raw, } } fn add_rpc< 'a, Args: Serialize + DeserializeOwned +'static, R: Serialize + DeserializeOwned +'static, >( &mut self, name: &str, callback: fn(&PluginEnv<S>, Args) -> R, ) -> Result<()> { self.rpcs .lock() .map_err(|_| anyhow!("could not lock rpcs"))? .insert( name.to_owned(), Box::new(move |mut buffer: &mut Buffer, env: &PluginEnv<S>| { let (_, args): (String, Args) = bincode::deserialize(buffer.as_slice()).unwrap(); let result = callback(env, args); buffer.clear(); bincode::serialize_into(buffer, &result).unwrap(); Ok(()) }), ); Ok(()) } fn call<Args: Serialize, R: DeserializeOwned>(&self, name: &str, args: Args) -> Result<R> { // TODO: requires access to buffer. todo!() } } pub struct Plugin { instance: Instance, env: PluginEnv<World>, } impl Plugin { pub fn load<P: AsRef<Path>>(path: P) -> Result<Self> { let mut env = PluginEnv::default(); let store = Store::new(&JIT::new(LLVM::default()).engine()); let module = Module::from_file(&store, &path)?; let mut wasi_env = WasiState::new( path.as_ref() .file_name() .and_then(OsStr::to_str) .unwrap_or("unkown"), ) .finalize()?; let mut import_object = wasi_env.import_object(&module)?; import_object.register( "env", import_namespace!({ "__quill_host_call" => Function::new_native_with_env(&store, env.clone(), __quill_host_call), }), ); // env.add_rpc("players_push", |state, player: String| state.push(player))?; // // TODO: Return reference to state? // env.add_rpc("players", |state, ()| state.clone())?; env.add_rpc("world_spawn", |env, entity: quill::ecs::Entity| { let mut world = env.state.lock().unwrap(); let mut layouts = env.layouts.lock().unwrap(); let mut builder = EntityBuilder::new(); for (layout, data) in entity.components { builder.add_dynamic( TypeInfo::of_external( layouts.external_id(&layout), Layout::new::<Vec<u8>>(), |_| (), ), data.as_slice(), ); } world.spawn(builder.build()); })?; env.add_rpc( "world_query", // TODO: world should not be the state but union(world, layouts) |env, access: quill::ecs::QueryAccess| { let world = env.state.lock().unwrap(); let mut layouts = env.layouts.lock().unwrap(); let query = access.query(&mut layouts).unwrap(); let access = Default::default(); let mut query: StatefulQuery<DynamicQuery, DynamicQuery> = StatefulQuery::new(&world, &access, query); for entity in query.iter_mut() { entity.immutable; entity.mutable; } }, )?; let instance = Instance::new(&module, &import_object)?; let start = instance.exports.get_function("_start")?; start.call(&[])?; Ok(Plugin { instance, env }) } } #[derive(Default)] pub struct Layouts { layouts: HashMap<quill::ecs::TypeLayout, u64>, } impl Layouts { pub fn component_id(&mut self, layout: &TypeLayout) -> ComponentId { ComponentId::ExternalId(self.external_id(layout)) } pub fn external_id(&mut self, layout: &TypeLayout) -> u64 { if let Some(component_id) = self.layouts.get(&layout) { *component_id } else { let next = self.layouts.len() as u64; self.layouts.insert(layout.clone(), next); next } } } trait IntoBevyAccess { fn access(&self, layouts: &mut Layouts) -> Result<QueryAccess>; fn component_ids(&self) -> Result<Vec<ComponentId>>; fn query(&self, layouts: &mut Layouts) -> Result<DynamicQuery>; } impl IntoBevyAccess for quill::ecs::QueryAccess { fn access(&self, layouts: &mut Layouts) -> Result<QueryAccess> { use quill::ecs::QueryAccess::*; Ok(match self { None => QueryAccess::None, Read(layout) => QueryAccess::Read(layouts.component_id(layout), "??"), Write(layout) => QueryAccess::Write(layouts.component_id(layout), "??"), Optional(access) => { QueryAccess::optional(IntoBevyAccess::access(access.as_ref(), layouts)?) } With(layout, access) => QueryAccess::With( layouts.component_id(layout), Box::new(IntoBevyAccess::access(access.as_ref(), layouts)?), ), Without(layout, access) => QueryAccess::Without( layouts.component_id(layout), Box::new(IntoBevyAccess::access(access.as_ref(), layouts)?), ), Union(accesses) => QueryAccess::Union( accesses .into_iter() .map(|access| IntoBevyAccess::access(access, layouts)) .collect::<Result<Vec<QueryAccess>>>()?, ), }) } fn component_ids(&self) -> Result<Vec<ComponentId>> { todo!() } fn query(&self, layouts: &mut Layouts) -> Result<DynamicQuery> { let mut query = DynamicQuery::default(); query.access = self.access(layouts)?; // TODO: TypeInfo Ok(query) } } struct Buffer<'a> { memory: &'a Memory, // fn reserve(ptr: WasmPtr<u8, Array>, cap: u32, len: u32, additional: u32) reserve: &'a NativeFunc<(WasmPtr<RawBuffer>, u32)>, raw: WasmPtr<RawBuffer>, } #[repr(C)] #[derive(Debug, Clone, Copy)] struct RawBuffer { ptr: WasmPtr<u8, Array>, cap: u32, len: u32, } unsafe impl ValueType for RawBuffer {} impl<'a> Buffer<'a> { fn reserve(&mut self, additional: u32) { let raw = self.raw.deref(self.memory).unwrap().get(); if raw.cap < raw.len + additional { self.reserve.call(self.raw, additional).unwrap(); } } fn clear(&mut self) { let raw_cell = self.raw.deref(self.memory).unwrap(); raw_cell.set(RawBuffer { len: 0, ..raw_cell.get() }) } fn push(&mut self, byte: u8) { self.extend_from_slice(&[byte]); } fn extend_from_slice(&mut self, other: &[u8]) { self.reserve(other.len() as u32); let raw_cell = self.raw.deref(self.memory).unwrap(); let raw = raw_cell.get(); raw.ptr .deref(self.memory, raw.len, raw.cap) .unwrap() .into_iter() .zip(other.iter()) .for_each(|(cell, value)| cell.set(*value)); raw_cell.set(RawBuffer { len: raw.len + other.len() as u32, ..raw }); } fn as_slice(&self) -> &[u8] { self } } impl<'a> Write for Buffer<'a> { #[inline] fn
(&mut self, buf: &[u8]) -> io::Result<usize> { self.extend_from_slice(buf); Ok(buf.len()) } #[inline] fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { let len = bufs.iter().map(|b| b.len() as u32).sum(); self.reserve(len); for buf in bufs { self.extend_from_slice(buf); } Ok(len as usize) } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.extend_from_slice(buf); Ok(()) } #[inline] fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl<'a> Deref for Buffer<'a> { type Target = [u8]; fn deref(&self) -> &Self::Target { let raw = self.raw.deref(self.memory).unwrap().get(); unsafe { mem::transmute(raw.ptr.deref(self.memory, 0, raw.len).unwrap()) } } } impl<'a> AsRef<[u8]> for Buffer<'a> { fn as_ref(&self) -> &[u8] { self } } fn __quill_host_call(env: &PluginEnv<World>, buffer_raw: WasmPtr<RawBuffer>) { let mut buffer = env.buffer(buffer_raw); let name: String = bincode::deserialize_from(buffer.as_slice()).unwrap(); let rpcs = env.rpcs.lock().unwrap(); let rpc = rpcs.get(&name).unwrap(); rpc(&mut buffer, env).unwrap(); }
write
identifier_name
mod.rs
use std::{ alloc::Layout, array::TryFromSliceError, borrow::BorrowMut, cell::{Cell, UnsafeCell}, collections::HashMap, ffi::OsStr, fs, io::{self, Read, Write}, mem, ops::{Deref, DerefMut}, path::Path, sync::{Arc, Mutex, MutexGuard}, todo, u32, vec, }; use anyhow::{anyhow, Result}; use bevy_ecs::{ ComponentId, DynamicFetch, DynamicFetchResult, DynamicQuery, DynamicSystem, EntityBuilder, QueryAccess, StatefulQuery, TypeAccess, TypeInfo, World, }; use bincode::DefaultOptions; use fs::OpenOptions; use io::IoSlice; use mem::ManuallyDrop; use quill::ecs::TypeLayout; use wasmer::{ import_namespace, imports, Array, FromToNativeWasmType, Function, HostEnvInitError, Instance, LazyInit, Memory, Module, NativeFunc, Store, Type, ValueType, WasmPtr, WasmTypeList, WasmerEnv, JIT, LLVM, }; use wasmer_wasi::WasiState; use serde::{de::DeserializeOwned, Deserialize, Serialize}; #[derive(Default)] struct PluginEnv<S> { memory: LazyInit<Memory>, buffer_reserve: LazyInit<NativeFunc<(WasmPtr<RawBuffer>, u32)>>, rpcs: Arc<Mutex<HashMap<String, Box<dyn Fn(&mut Buffer, &PluginEnv<S>) -> Result<()> + Send>>>>, state: Arc<Mutex<S>>, layouts: Arc<Mutex<Layouts>>, } impl<S: Send + Sync +'static> Clone for PluginEnv<S> { fn clone(&self) -> Self { Self { memory: self.memory.clone(), buffer_reserve: self.buffer_reserve.clone(), rpcs: self.rpcs.clone(), state: self.state.clone(), layouts: Default::default(), } } } impl<S: Send + Sync +'static> WasmerEnv for PluginEnv<S> { fn init_with_instance(&mut self, instance: &Instance) -> Result<(), HostEnvInitError> { let memory = instance.exports.get_memory("memory")?; self.memory.initialize(memory.clone()); self.buffer_reserve.initialize( instance .exports .get_native_function("__quill_buffer_reserve")?, ); Ok(()) } } impl<S: Send + Sync +'static> PluginEnv<S> { fn memory(&self) -> &Memory { // TODO: handle errors. self.memory.get_ref().unwrap() } fn buffer_reserve(&self) -> &NativeFunc<(WasmPtr<RawBuffer>, u32)> { self.buffer_reserve.get_ref().unwrap() } fn buffer(&self, raw: WasmPtr<RawBuffer>) -> Buffer { Buffer { memory: self.memory(), reserve: self.buffer_reserve(), raw, } } fn add_rpc< 'a, Args: Serialize + DeserializeOwned +'static, R: Serialize + DeserializeOwned +'static, >( &mut self, name: &str, callback: fn(&PluginEnv<S>, Args) -> R, ) -> Result<()> { self.rpcs .lock() .map_err(|_| anyhow!("could not lock rpcs"))? .insert( name.to_owned(), Box::new(move |mut buffer: &mut Buffer, env: &PluginEnv<S>| { let (_, args): (String, Args) = bincode::deserialize(buffer.as_slice()).unwrap(); let result = callback(env, args); buffer.clear(); bincode::serialize_into(buffer, &result).unwrap(); Ok(()) }), ); Ok(()) } fn call<Args: Serialize, R: DeserializeOwned>(&self, name: &str, args: Args) -> Result<R> { // TODO: requires access to buffer. todo!() } } pub struct Plugin { instance: Instance, env: PluginEnv<World>, } impl Plugin { pub fn load<P: AsRef<Path>>(path: P) -> Result<Self> { let mut env = PluginEnv::default(); let store = Store::new(&JIT::new(LLVM::default()).engine()); let module = Module::from_file(&store, &path)?; let mut wasi_env = WasiState::new( path.as_ref() .file_name() .and_then(OsStr::to_str) .unwrap_or("unkown"), ) .finalize()?; let mut import_object = wasi_env.import_object(&module)?; import_object.register( "env", import_namespace!({ "__quill_host_call" => Function::new_native_with_env(&store, env.clone(), __quill_host_call), }), ); // env.add_rpc("players_push", |state, player: String| state.push(player))?; // // TODO: Return reference to state? // env.add_rpc("players", |state, ()| state.clone())?; env.add_rpc("world_spawn", |env, entity: quill::ecs::Entity| { let mut world = env.state.lock().unwrap(); let mut layouts = env.layouts.lock().unwrap(); let mut builder = EntityBuilder::new(); for (layout, data) in entity.components { builder.add_dynamic( TypeInfo::of_external( layouts.external_id(&layout), Layout::new::<Vec<u8>>(), |_| (), ), data.as_slice(), ); } world.spawn(builder.build()); })?; env.add_rpc( "world_query", // TODO: world should not be the state but union(world, layouts) |env, access: quill::ecs::QueryAccess| { let world = env.state.lock().unwrap(); let mut layouts = env.layouts.lock().unwrap(); let query = access.query(&mut layouts).unwrap(); let access = Default::default(); let mut query: StatefulQuery<DynamicQuery, DynamicQuery> = StatefulQuery::new(&world, &access, query); for entity in query.iter_mut() { entity.immutable; entity.mutable; } }, )?; let instance = Instance::new(&module, &import_object)?; let start = instance.exports.get_function("_start")?; start.call(&[])?; Ok(Plugin { instance, env }) } } #[derive(Default)] pub struct Layouts { layouts: HashMap<quill::ecs::TypeLayout, u64>, } impl Layouts { pub fn component_id(&mut self, layout: &TypeLayout) -> ComponentId { ComponentId::ExternalId(self.external_id(layout)) } pub fn external_id(&mut self, layout: &TypeLayout) -> u64 { if let Some(component_id) = self.layouts.get(&layout) { *component_id } else { let next = self.layouts.len() as u64; self.layouts.insert(layout.clone(), next); next } } } trait IntoBevyAccess { fn access(&self, layouts: &mut Layouts) -> Result<QueryAccess>; fn component_ids(&self) -> Result<Vec<ComponentId>>; fn query(&self, layouts: &mut Layouts) -> Result<DynamicQuery>; } impl IntoBevyAccess for quill::ecs::QueryAccess { fn access(&self, layouts: &mut Layouts) -> Result<QueryAccess> { use quill::ecs::QueryAccess::*; Ok(match self { None => QueryAccess::None, Read(layout) => QueryAccess::Read(layouts.component_id(layout), "??"), Write(layout) => QueryAccess::Write(layouts.component_id(layout), "??"), Optional(access) => { QueryAccess::optional(IntoBevyAccess::access(access.as_ref(), layouts)?) } With(layout, access) => QueryAccess::With( layouts.component_id(layout), Box::new(IntoBevyAccess::access(access.as_ref(), layouts)?), ), Without(layout, access) => QueryAccess::Without( layouts.component_id(layout), Box::new(IntoBevyAccess::access(access.as_ref(), layouts)?), ), Union(accesses) => QueryAccess::Union( accesses .into_iter() .map(|access| IntoBevyAccess::access(access, layouts)) .collect::<Result<Vec<QueryAccess>>>()?, ), }) } fn component_ids(&self) -> Result<Vec<ComponentId>> { todo!() } fn query(&self, layouts: &mut Layouts) -> Result<DynamicQuery>
} struct Buffer<'a> { memory: &'a Memory, // fn reserve(ptr: WasmPtr<u8, Array>, cap: u32, len: u32, additional: u32) reserve: &'a NativeFunc<(WasmPtr<RawBuffer>, u32)>, raw: WasmPtr<RawBuffer>, } #[repr(C)] #[derive(Debug, Clone, Copy)] struct RawBuffer { ptr: WasmPtr<u8, Array>, cap: u32, len: u32, } unsafe impl ValueType for RawBuffer {} impl<'a> Buffer<'a> { fn reserve(&mut self, additional: u32) { let raw = self.raw.deref(self.memory).unwrap().get(); if raw.cap < raw.len + additional { self.reserve.call(self.raw, additional).unwrap(); } } fn clear(&mut self) { let raw_cell = self.raw.deref(self.memory).unwrap(); raw_cell.set(RawBuffer { len: 0, ..raw_cell.get() }) } fn push(&mut self, byte: u8) { self.extend_from_slice(&[byte]); } fn extend_from_slice(&mut self, other: &[u8]) { self.reserve(other.len() as u32); let raw_cell = self.raw.deref(self.memory).unwrap(); let raw = raw_cell.get(); raw.ptr .deref(self.memory, raw.len, raw.cap) .unwrap() .into_iter() .zip(other.iter()) .for_each(|(cell, value)| cell.set(*value)); raw_cell.set(RawBuffer { len: raw.len + other.len() as u32, ..raw }); } fn as_slice(&self) -> &[u8] { self } } impl<'a> Write for Buffer<'a> { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.extend_from_slice(buf); Ok(buf.len()) } #[inline] fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { let len = bufs.iter().map(|b| b.len() as u32).sum(); self.reserve(len); for buf in bufs { self.extend_from_slice(buf); } Ok(len as usize) } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.extend_from_slice(buf); Ok(()) } #[inline] fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl<'a> Deref for Buffer<'a> { type Target = [u8]; fn deref(&self) -> &Self::Target { let raw = self.raw.deref(self.memory).unwrap().get(); unsafe { mem::transmute(raw.ptr.deref(self.memory, 0, raw.len).unwrap()) } } } impl<'a> AsRef<[u8]> for Buffer<'a> { fn as_ref(&self) -> &[u8] { self } } fn __quill_host_call(env: &PluginEnv<World>, buffer_raw: WasmPtr<RawBuffer>) { let mut buffer = env.buffer(buffer_raw); let name: String = bincode::deserialize_from(buffer.as_slice()).unwrap(); let rpcs = env.rpcs.lock().unwrap(); let rpc = rpcs.get(&name).unwrap(); rpc(&mut buffer, env).unwrap(); }
{ let mut query = DynamicQuery::default(); query.access = self.access(layouts)?; // TODO: TypeInfo Ok(query) }
identifier_body
scheduler.rs
extern crate clap; extern crate esvm; extern crate fern; extern crate ethereum_newtypes; extern crate rayon; extern crate regex; extern crate reqwest; extern crate hexdecode; extern crate serde_json; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate chrono; use std::fs::{self, File}; use std::io::{BufWriter, Read, Write}; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, Mutex, }; use std::thread; use std::time::Duration; use esvm::{AttackType, TimeoutAnalysis, AnalysisSuccess}; use serde_json::json; use chrono::prelude::Local; use clap::{App, Arg, ArgMatches}; use ethereum_newtypes::{Address}; use regex::Regex; use reqwest::Client; fn init_logger() -> Result<()> { fern::Dispatch::new() // Perform allocation-free log formatting .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )) }) // Add blanket level filter - .level(log::LevelFilter::Info) // Output to stdout, files, and other Dispatch configurations .chain(std::io::stdout()) .chain(fern::log_file("log/evmse-scheduler.log")?) // Apply globally .apply()?; Ok(()) } #[derive(Debug)] struct Worker { client: Client, url: String, timeout: Duration, } impl Worker { fn new(url: &str, timeout: usize) -> Result<Worker> { let client = reqwest::Client::builder().timeout(None).build()?; let mut url = format!("{}/analyze_address", url); if timeout > 0 { url.push_str("_timeout"); } let timeout = Duration::from_secs((timeout * 60) as u64); Ok(Worker { client, url: url, timeout, }) } fn analyze(&self, address: Address) -> Result<AnalysisSuccess> { info!("Analyzing {:x}", address.0); let mut res = if self.timeout > Duration::from_secs(0) { self .client .post(&self.url) .json(&TimeoutAnalysis { address, timeout: self.timeout}) .send()? } else { self .client .post(&self.url) .json(&address) .send()? }; Ok(res.json()?) } fn check_alive(&self) -> Result<()> { self.client .get(&format!("{}/alive", &self.url)) .send() .map_err(|e| e.into()) .map(|_| ()) } } struct WorkerHandle<'a> { worker: Option<Worker>, scheduler: &'a Scheduler, kill: bool, } impl<'a> WorkerHandle<'a> { // specifically consume the handle to force readding the worker fn analyze(mut self, addr: Address) -> Result<AnalysisSuccess> { let res = self.worker.as_ref().unwrap().analyze(addr); if let Err(ref error) = res { error!("Error analyzing {:x?}, checking worker!", error); if let Err(_) = self.worker.as_ref().unwrap().check_alive() { error!("Worker died analyzing {:x?}, shuting down worker!", error); self.kill = true; } else { return Err(Error::retry()); } } res } } impl<'a> Drop for WorkerHandle<'a> { fn drop(&mut self) { if!self.kill { let worker = self .worker .take() .expect("Worker replaced before adding back"); self.scheduler.add_worker(worker) } else { self.worker .take() .expect("Worker replaced before adding back"); } } } #[derive(Debug)] struct Scheduler { queue: Arc<Mutex<Vec<Worker>>>, } impl Scheduler { fn new() -> Self { let queue = Arc::new(Mutex::new(Vec::new())); Self { queue } } fn with_worker_count(urls: Vec<String>, timeout: usize) -> Self
fn add_worker(&self, worker: Worker) { self.queue.lock().unwrap().push(worker); } fn get_worker(&self) -> WorkerHandle { let worker; loop { if let Some(w) = self.queue.lock().unwrap().pop() { worker = Some(w); break; } } WorkerHandle { worker, scheduler: self, kill: false, } } } type Result<T> = ::std::result::Result<T, Error>; #[derive(Debug)] struct Error { kind: Kind, } impl Error { fn from_str(s: String) -> Self { Self { kind: Kind::Execution(s), } } fn retry() -> Self { Self { kind: Kind::Retry, } } fn kind(&self) -> &Kind { &self.kind } } macro_rules! impl_error_kind { ( $(#[$struct_attr:meta])* enum Kind { $( $enum_variant_name:ident($error_type:path), )+ ; $( $single_variant_name:ident, )+ } ) => { // meta attributes $(#[$struct_attr])* // enum definition enum Kind { $( $enum_variant_name($error_type), )+ $( $single_variant_name, )+ } // impl error conversion for each type $( impl ::std::convert::From<$error_type> for Error { fn from(error: $error_type) -> Self { Self { kind: Kind::$enum_variant_name(error), } } } )+ }; } impl_error_kind!(#[derive(Debug)] enum Kind { Reqwest(reqwest::Error), SerdeJson(serde_json::Error), Log(log::SetLoggerError), IO(std::io::Error), Execution(String), ; Retry, }); fn parse_args<'a>() -> ArgMatches<'a> { App::new("EthAEG scheduler for analyzing a large list of contracts") .arg( Arg::with_name("INPUT") .help("Set the list of accounts to scan") .required(true) .index(1), ) .arg( Arg::with_name("SERVER_LIST") .help("Set the list of backend servers") .required(true) .index(2), ) .arg(Arg::with_name("timeout").long("timeout").takes_value(true).help("Specify a timeout for the analysis, none used by default")) .arg(Arg::with_name("json").long("json").help("Dump the analysis result in json format.")) .get_matches() } fn parse_account_list(path: &str) -> (Arc<Mutex<Vec<(usize, String)>>>, usize) { let mut acc_list = String::new(); File::open(path) .expect("Could not open account list") .read_to_string(&mut acc_list) .expect("Could not read account list"); let acc_vec: Vec<(usize, String)> = acc_list .lines() .filter_map(|line| match ACC_RE.captures(line) { Some(cap) => { let capture = cap.get(0).unwrap().as_str(); Some((0, capture.to_string())) } None => { warn!("Could not process: {}", line); None } }) .collect(); let len = acc_vec.len(); (Arc::new(Mutex::new(acc_vec)), len) } fn parse_server_list(path: &str) -> Vec<String> { let mut server_list = String::new(); File::open(path) .expect("Could not open server list") .read_to_string(&mut server_list) .expect("Could not read server list"); server_list .lines() .map(|line| { let line = line.trim(); if line.starts_with("http") || line.starts_with("https") { line.to_string() } else { format!("http://{}", line) } }) .collect() } lazy_static! { static ref ACC_RE: Regex = Regex::new(r"0x[A-za-z0-9]{40}").unwrap(); } fn execute( work_stack: Arc<Mutex<Vec<(usize, String)>>>, scheduler: Arc<Scheduler>, counter: Arc<AtomicUsize>, acc_len: usize, root_path: Arc<String>, csv: &Mutex<BufWriter<File>>, json: bool, ) -> Result<()> { loop { let (c, acc) = match work_stack.lock().unwrap().pop() { Some(work) => work, None => { info!("Could not fetch new work, exiting loop!"); return Ok(()); } }; if c >= 5 { info!("Account {} seed {} times, discarding!", acc, c); continue; } let a = Address(hexdecode::decode(&acc.as_bytes()).unwrap().as_slice().into()); let worker = scheduler.get_worker(); let res = worker.analyze(a); match res { Ok(r) => { let file_path = if json { format!("{}/{}.json", root_path, acc) } else { format!("{}/{}", root_path, acc) }; let mut f = match File::create(file_path) { Ok(f) => f, Err(e) => { error!("Could not create file for {}: {:?}", acc, e); return Err(Error::from_str(format!( "Could not create file for {}: {:?}", acc, e ))); } }; if json { if let AnalysisSuccess::Success(ref analysis) = r { let mut res = (false, false, false); if let Some(ref attacks) = analysis.attacks { for attack in attacks { if attack.attack_type == AttackType::StealMoney { res.0 = true; } if attack.attack_type == AttackType::DeleteContract { res.1 = true; } if attack.attack_type == AttackType::HijackControlFlow { res.2 = true; } } } csv.lock().unwrap().write_all(format!("{:x}, {}, {}, {}\n", analysis.address, res.0, res.1, res.2).as_bytes()).expect("Could not write to csv file!"); } let _write_res = f.write_all(json!(r).to_string().as_bytes()); } else { let content = match r { AnalysisSuccess::Success(analysis) => { let mut res = (false, false, false); if let Some(ref attacks) = analysis.attacks { for attack in attacks { if attack.attack_type == AttackType::StealMoney { res.0 = true; } if attack.attack_type == AttackType::DeleteContract { res.1 = true; } if attack.attack_type == AttackType::HijackControlFlow { res.2 = true; } } } csv.lock().unwrap().write_all(format!("{:x}, {}, {}, {}\n", analysis.address, res.0, res.1, res.2).as_bytes()).expect("Could not write to csv file!"); format!("{}", analysis) }, AnalysisSuccess::Failure(s) => { warn!("Failure during analysing {}: {}", acc, s); s }, AnalysisSuccess::Timeout => { warn!("Timeout during analysis: {:?}", acc); format!("Timeout analysing {:?}", acc) }, }; let _write_res = f.write_all(content.as_bytes()); } } Err(e) => { if let Kind::Retry = e.kind() { error!("Error analyzing {}, retrying...", acc); work_stack.lock().unwrap().push((c+1, acc)); } else { error!("Error analyzing {}: {:?} worker died!", acc, e); } } }; info!( "Analyzed {} of {} contracts", counter.fetch_add(1, Ordering::Relaxed), acc_len ); } } fn main() { // init logger init_logger().expect("Could not initialize logger"); // parse args let matches = parse_args(); // create root path let root_path = format!( "analysis/{}/", Local::now().format("%Y-%m-%d-%H:%M:%S").to_string() ); fs::create_dir_all(root_path.clone()).expect("Could not create root folder for analysis"); let root_path = Arc::new(root_path); let acc_path = matches.value_of("INPUT").unwrap(); let server_path = matches.value_of("SERVER_LIST").unwrap(); let (work_stack, acc_len) = parse_account_list(acc_path); let server_list = parse_server_list(server_path); let server_len = server_list.len(); let timeout = if let Some(b) = matches.value_of("timeout") { b.parse().expect("Incorrect timeout supplied!") } else { 0 }; let scheduler = Arc::new(Scheduler::with_worker_count(server_list, timeout)); let counter = Arc::new(AtomicUsize::new(1)); let mut f = File::create(format!("{}/analysis.csv", root_path)).expect("Could not create csv file!"); f.write_all("address, steal ether, trigger suicide, hijack control flow\n".as_bytes()).expect("Could not write header to cvs!"); let csv_writer = Arc::new(Mutex::new(BufWriter::new(f))); info!("Starting Analysis"); let mut threads = Vec::new(); for _ in 0..server_len { let work_stack_clone = Arc::clone(&work_stack); let scheduler_clone = Arc::clone(&scheduler); let counter_clone = Arc::clone(&counter); let root_path_clone = Arc::clone(&root_path); let csv_clone = Arc::clone(&csv_writer); let json = matches.is_present("json"); let join_handle = thread::spawn(move || { execute( work_stack_clone, scheduler_clone, counter_clone, acc_len, root_path_clone, &csv_clone, json, ) }); threads.push(join_handle); } csv_writer.lock().unwrap().flush().expect("Could not finally flush writer"); for handle in threads { let _res = handle.join(); } info!("Finished Analysis"); }
{ let s = Scheduler::new(); for url in &urls { s.queue.lock().unwrap().push(Worker::new(url, timeout).unwrap()); // if the workers can not connect initially fail } s }
identifier_body
scheduler.rs
extern crate clap; extern crate esvm; extern crate fern; extern crate ethereum_newtypes; extern crate rayon; extern crate regex; extern crate reqwest; extern crate hexdecode; extern crate serde_json; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate chrono; use std::fs::{self, File}; use std::io::{BufWriter, Read, Write}; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, Mutex, }; use std::thread; use std::time::Duration; use esvm::{AttackType, TimeoutAnalysis, AnalysisSuccess}; use serde_json::json; use chrono::prelude::Local; use clap::{App, Arg, ArgMatches}; use ethereum_newtypes::{Address}; use regex::Regex; use reqwest::Client; fn init_logger() -> Result<()> { fern::Dispatch::new() // Perform allocation-free log formatting .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )) }) // Add blanket level filter - .level(log::LevelFilter::Info) // Output to stdout, files, and other Dispatch configurations .chain(std::io::stdout()) .chain(fern::log_file("log/evmse-scheduler.log")?) // Apply globally .apply()?; Ok(()) } #[derive(Debug)] struct Worker { client: Client, url: String, timeout: Duration, } impl Worker { fn new(url: &str, timeout: usize) -> Result<Worker> { let client = reqwest::Client::builder().timeout(None).build()?; let mut url = format!("{}/analyze_address", url); if timeout > 0 { url.push_str("_timeout"); } let timeout = Duration::from_secs((timeout * 60) as u64); Ok(Worker { client, url: url, timeout, }) } fn analyze(&self, address: Address) -> Result<AnalysisSuccess> { info!("Analyzing {:x}", address.0); let mut res = if self.timeout > Duration::from_secs(0) { self .client .post(&self.url) .json(&TimeoutAnalysis { address, timeout: self.timeout}) .send()? } else { self .client .post(&self.url) .json(&address) .send()? }; Ok(res.json()?) } fn check_alive(&self) -> Result<()> { self.client .get(&format!("{}/alive", &self.url)) .send() .map_err(|e| e.into()) .map(|_| ()) } } struct WorkerHandle<'a> { worker: Option<Worker>, scheduler: &'a Scheduler, kill: bool, } impl<'a> WorkerHandle<'a> { // specifically consume the handle to force readding the worker fn analyze(mut self, addr: Address) -> Result<AnalysisSuccess> { let res = self.worker.as_ref().unwrap().analyze(addr); if let Err(ref error) = res { error!("Error analyzing {:x?}, checking worker!", error); if let Err(_) = self.worker.as_ref().unwrap().check_alive() { error!("Worker died analyzing {:x?}, shuting down worker!", error); self.kill = true; } else { return Err(Error::retry()); } } res } } impl<'a> Drop for WorkerHandle<'a> { fn drop(&mut self) { if!self.kill { let worker = self .worker .take() .expect("Worker replaced before adding back"); self.scheduler.add_worker(worker) } else { self.worker .take() .expect("Worker replaced before adding back"); } } } #[derive(Debug)] struct Scheduler { queue: Arc<Mutex<Vec<Worker>>>, } impl Scheduler { fn new() -> Self { let queue = Arc::new(Mutex::new(Vec::new())); Self { queue } } fn with_worker_count(urls: Vec<String>, timeout: usize) -> Self { let s = Scheduler::new(); for url in &urls { s.queue.lock().unwrap().push(Worker::new(url, timeout).unwrap()); // if the workers can not connect initially fail } s } fn add_worker(&self, worker: Worker) { self.queue.lock().unwrap().push(worker); } fn get_worker(&self) -> WorkerHandle { let worker; loop { if let Some(w) = self.queue.lock().unwrap().pop() { worker = Some(w); break; } } WorkerHandle { worker, scheduler: self, kill: false, } } } type Result<T> = ::std::result::Result<T, Error>; #[derive(Debug)] struct Error { kind: Kind, } impl Error { fn from_str(s: String) -> Self { Self { kind: Kind::Execution(s), } } fn retry() -> Self { Self { kind: Kind::Retry, } } fn kind(&self) -> &Kind { &self.kind } } macro_rules! impl_error_kind { ( $(#[$struct_attr:meta])* enum Kind { $( $enum_variant_name:ident($error_type:path), )+ ; $( $single_variant_name:ident, )+ } ) => { // meta attributes $(#[$struct_attr])* // enum definition enum Kind { $( $enum_variant_name($error_type), )+ $( $single_variant_name, )+ } // impl error conversion for each type $( impl ::std::convert::From<$error_type> for Error { fn from(error: $error_type) -> Self { Self { kind: Kind::$enum_variant_name(error), } } } )+ }; } impl_error_kind!(#[derive(Debug)] enum Kind { Reqwest(reqwest::Error), SerdeJson(serde_json::Error), Log(log::SetLoggerError), IO(std::io::Error), Execution(String), ; Retry, }); fn parse_args<'a>() -> ArgMatches<'a> { App::new("EthAEG scheduler for analyzing a large list of contracts") .arg( Arg::with_name("INPUT") .help("Set the list of accounts to scan") .required(true) .index(1), ) .arg( Arg::with_name("SERVER_LIST") .help("Set the list of backend servers") .required(true) .index(2), ) .arg(Arg::with_name("timeout").long("timeout").takes_value(true).help("Specify a timeout for the analysis, none used by default")) .arg(Arg::with_name("json").long("json").help("Dump the analysis result in json format.")) .get_matches() } fn
(path: &str) -> (Arc<Mutex<Vec<(usize, String)>>>, usize) { let mut acc_list = String::new(); File::open(path) .expect("Could not open account list") .read_to_string(&mut acc_list) .expect("Could not read account list"); let acc_vec: Vec<(usize, String)> = acc_list .lines() .filter_map(|line| match ACC_RE.captures(line) { Some(cap) => { let capture = cap.get(0).unwrap().as_str(); Some((0, capture.to_string())) } None => { warn!("Could not process: {}", line); None } }) .collect(); let len = acc_vec.len(); (Arc::new(Mutex::new(acc_vec)), len) } fn parse_server_list(path: &str) -> Vec<String> { let mut server_list = String::new(); File::open(path) .expect("Could not open server list") .read_to_string(&mut server_list) .expect("Could not read server list"); server_list .lines() .map(|line| { let line = line.trim(); if line.starts_with("http") || line.starts_with("https") { line.to_string() } else { format!("http://{}", line) } }) .collect() } lazy_static! { static ref ACC_RE: Regex = Regex::new(r"0x[A-za-z0-9]{40}").unwrap(); } fn execute( work_stack: Arc<Mutex<Vec<(usize, String)>>>, scheduler: Arc<Scheduler>, counter: Arc<AtomicUsize>, acc_len: usize, root_path: Arc<String>, csv: &Mutex<BufWriter<File>>, json: bool, ) -> Result<()> { loop { let (c, acc) = match work_stack.lock().unwrap().pop() { Some(work) => work, None => { info!("Could not fetch new work, exiting loop!"); return Ok(()); } }; if c >= 5 { info!("Account {} seed {} times, discarding!", acc, c); continue; } let a = Address(hexdecode::decode(&acc.as_bytes()).unwrap().as_slice().into()); let worker = scheduler.get_worker(); let res = worker.analyze(a); match res { Ok(r) => { let file_path = if json { format!("{}/{}.json", root_path, acc) } else { format!("{}/{}", root_path, acc) }; let mut f = match File::create(file_path) { Ok(f) => f, Err(e) => { error!("Could not create file for {}: {:?}", acc, e); return Err(Error::from_str(format!( "Could not create file for {}: {:?}", acc, e ))); } }; if json { if let AnalysisSuccess::Success(ref analysis) = r { let mut res = (false, false, false); if let Some(ref attacks) = analysis.attacks { for attack in attacks { if attack.attack_type == AttackType::StealMoney { res.0 = true; } if attack.attack_type == AttackType::DeleteContract { res.1 = true; } if attack.attack_type == AttackType::HijackControlFlow { res.2 = true; } } } csv.lock().unwrap().write_all(format!("{:x}, {}, {}, {}\n", analysis.address, res.0, res.1, res.2).as_bytes()).expect("Could not write to csv file!"); } let _write_res = f.write_all(json!(r).to_string().as_bytes()); } else { let content = match r { AnalysisSuccess::Success(analysis) => { let mut res = (false, false, false); if let Some(ref attacks) = analysis.attacks { for attack in attacks { if attack.attack_type == AttackType::StealMoney { res.0 = true; } if attack.attack_type == AttackType::DeleteContract { res.1 = true; } if attack.attack_type == AttackType::HijackControlFlow { res.2 = true; } } } csv.lock().unwrap().write_all(format!("{:x}, {}, {}, {}\n", analysis.address, res.0, res.1, res.2).as_bytes()).expect("Could not write to csv file!"); format!("{}", analysis) }, AnalysisSuccess::Failure(s) => { warn!("Failure during analysing {}: {}", acc, s); s }, AnalysisSuccess::Timeout => { warn!("Timeout during analysis: {:?}", acc); format!("Timeout analysing {:?}", acc) }, }; let _write_res = f.write_all(content.as_bytes()); } } Err(e) => { if let Kind::Retry = e.kind() { error!("Error analyzing {}, retrying...", acc); work_stack.lock().unwrap().push((c+1, acc)); } else { error!("Error analyzing {}: {:?} worker died!", acc, e); } } }; info!( "Analyzed {} of {} contracts", counter.fetch_add(1, Ordering::Relaxed), acc_len ); } } fn main() { // init logger init_logger().expect("Could not initialize logger"); // parse args let matches = parse_args(); // create root path let root_path = format!( "analysis/{}/", Local::now().format("%Y-%m-%d-%H:%M:%S").to_string() ); fs::create_dir_all(root_path.clone()).expect("Could not create root folder for analysis"); let root_path = Arc::new(root_path); let acc_path = matches.value_of("INPUT").unwrap(); let server_path = matches.value_of("SERVER_LIST").unwrap(); let (work_stack, acc_len) = parse_account_list(acc_path); let server_list = parse_server_list(server_path); let server_len = server_list.len(); let timeout = if let Some(b) = matches.value_of("timeout") { b.parse().expect("Incorrect timeout supplied!") } else { 0 }; let scheduler = Arc::new(Scheduler::with_worker_count(server_list, timeout)); let counter = Arc::new(AtomicUsize::new(1)); let mut f = File::create(format!("{}/analysis.csv", root_path)).expect("Could not create csv file!"); f.write_all("address, steal ether, trigger suicide, hijack control flow\n".as_bytes()).expect("Could not write header to cvs!"); let csv_writer = Arc::new(Mutex::new(BufWriter::new(f))); info!("Starting Analysis"); let mut threads = Vec::new(); for _ in 0..server_len { let work_stack_clone = Arc::clone(&work_stack); let scheduler_clone = Arc::clone(&scheduler); let counter_clone = Arc::clone(&counter); let root_path_clone = Arc::clone(&root_path); let csv_clone = Arc::clone(&csv_writer); let json = matches.is_present("json"); let join_handle = thread::spawn(move || { execute( work_stack_clone, scheduler_clone, counter_clone, acc_len, root_path_clone, &csv_clone, json, ) }); threads.push(join_handle); } csv_writer.lock().unwrap().flush().expect("Could not finally flush writer"); for handle in threads { let _res = handle.join(); } info!("Finished Analysis"); }
parse_account_list
identifier_name
scheduler.rs
extern crate clap; extern crate esvm; extern crate fern; extern crate ethereum_newtypes; extern crate rayon; extern crate regex; extern crate reqwest; extern crate hexdecode; extern crate serde_json; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate chrono; use std::fs::{self, File}; use std::io::{BufWriter, Read, Write}; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, Mutex, }; use std::thread; use std::time::Duration; use esvm::{AttackType, TimeoutAnalysis, AnalysisSuccess}; use serde_json::json; use chrono::prelude::Local; use clap::{App, Arg, ArgMatches}; use ethereum_newtypes::{Address}; use regex::Regex; use reqwest::Client; fn init_logger() -> Result<()> { fern::Dispatch::new() // Perform allocation-free log formatting .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )) }) // Add blanket level filter - .level(log::LevelFilter::Info) // Output to stdout, files, and other Dispatch configurations .chain(std::io::stdout()) .chain(fern::log_file("log/evmse-scheduler.log")?) // Apply globally .apply()?; Ok(()) } #[derive(Debug)] struct Worker { client: Client, url: String, timeout: Duration, } impl Worker { fn new(url: &str, timeout: usize) -> Result<Worker> { let client = reqwest::Client::builder().timeout(None).build()?; let mut url = format!("{}/analyze_address", url); if timeout > 0 { url.push_str("_timeout"); } let timeout = Duration::from_secs((timeout * 60) as u64); Ok(Worker { client, url: url, timeout, }) } fn analyze(&self, address: Address) -> Result<AnalysisSuccess> { info!("Analyzing {:x}", address.0); let mut res = if self.timeout > Duration::from_secs(0) { self .client .post(&self.url) .json(&TimeoutAnalysis { address, timeout: self.timeout}) .send()? } else { self .client .post(&self.url) .json(&address) .send()? }; Ok(res.json()?) } fn check_alive(&self) -> Result<()> { self.client .get(&format!("{}/alive", &self.url)) .send() .map_err(|e| e.into()) .map(|_| ()) } } struct WorkerHandle<'a> { worker: Option<Worker>, scheduler: &'a Scheduler, kill: bool, } impl<'a> WorkerHandle<'a> { // specifically consume the handle to force readding the worker fn analyze(mut self, addr: Address) -> Result<AnalysisSuccess> { let res = self.worker.as_ref().unwrap().analyze(addr); if let Err(ref error) = res { error!("Error analyzing {:x?}, checking worker!", error); if let Err(_) = self.worker.as_ref().unwrap().check_alive() { error!("Worker died analyzing {:x?}, shuting down worker!", error); self.kill = true; } else { return Err(Error::retry());
} res } } impl<'a> Drop for WorkerHandle<'a> { fn drop(&mut self) { if!self.kill { let worker = self .worker .take() .expect("Worker replaced before adding back"); self.scheduler.add_worker(worker) } else { self.worker .take() .expect("Worker replaced before adding back"); } } } #[derive(Debug)] struct Scheduler { queue: Arc<Mutex<Vec<Worker>>>, } impl Scheduler { fn new() -> Self { let queue = Arc::new(Mutex::new(Vec::new())); Self { queue } } fn with_worker_count(urls: Vec<String>, timeout: usize) -> Self { let s = Scheduler::new(); for url in &urls { s.queue.lock().unwrap().push(Worker::new(url, timeout).unwrap()); // if the workers can not connect initially fail } s } fn add_worker(&self, worker: Worker) { self.queue.lock().unwrap().push(worker); } fn get_worker(&self) -> WorkerHandle { let worker; loop { if let Some(w) = self.queue.lock().unwrap().pop() { worker = Some(w); break; } } WorkerHandle { worker, scheduler: self, kill: false, } } } type Result<T> = ::std::result::Result<T, Error>; #[derive(Debug)] struct Error { kind: Kind, } impl Error { fn from_str(s: String) -> Self { Self { kind: Kind::Execution(s), } } fn retry() -> Self { Self { kind: Kind::Retry, } } fn kind(&self) -> &Kind { &self.kind } } macro_rules! impl_error_kind { ( $(#[$struct_attr:meta])* enum Kind { $( $enum_variant_name:ident($error_type:path), )+ ; $( $single_variant_name:ident, )+ } ) => { // meta attributes $(#[$struct_attr])* // enum definition enum Kind { $( $enum_variant_name($error_type), )+ $( $single_variant_name, )+ } // impl error conversion for each type $( impl ::std::convert::From<$error_type> for Error { fn from(error: $error_type) -> Self { Self { kind: Kind::$enum_variant_name(error), } } } )+ }; } impl_error_kind!(#[derive(Debug)] enum Kind { Reqwest(reqwest::Error), SerdeJson(serde_json::Error), Log(log::SetLoggerError), IO(std::io::Error), Execution(String), ; Retry, }); fn parse_args<'a>() -> ArgMatches<'a> { App::new("EthAEG scheduler for analyzing a large list of contracts") .arg( Arg::with_name("INPUT") .help("Set the list of accounts to scan") .required(true) .index(1), ) .arg( Arg::with_name("SERVER_LIST") .help("Set the list of backend servers") .required(true) .index(2), ) .arg(Arg::with_name("timeout").long("timeout").takes_value(true).help("Specify a timeout for the analysis, none used by default")) .arg(Arg::with_name("json").long("json").help("Dump the analysis result in json format.")) .get_matches() } fn parse_account_list(path: &str) -> (Arc<Mutex<Vec<(usize, String)>>>, usize) { let mut acc_list = String::new(); File::open(path) .expect("Could not open account list") .read_to_string(&mut acc_list) .expect("Could not read account list"); let acc_vec: Vec<(usize, String)> = acc_list .lines() .filter_map(|line| match ACC_RE.captures(line) { Some(cap) => { let capture = cap.get(0).unwrap().as_str(); Some((0, capture.to_string())) } None => { warn!("Could not process: {}", line); None } }) .collect(); let len = acc_vec.len(); (Arc::new(Mutex::new(acc_vec)), len) } fn parse_server_list(path: &str) -> Vec<String> { let mut server_list = String::new(); File::open(path) .expect("Could not open server list") .read_to_string(&mut server_list) .expect("Could not read server list"); server_list .lines() .map(|line| { let line = line.trim(); if line.starts_with("http") || line.starts_with("https") { line.to_string() } else { format!("http://{}", line) } }) .collect() } lazy_static! { static ref ACC_RE: Regex = Regex::new(r"0x[A-za-z0-9]{40}").unwrap(); } fn execute( work_stack: Arc<Mutex<Vec<(usize, String)>>>, scheduler: Arc<Scheduler>, counter: Arc<AtomicUsize>, acc_len: usize, root_path: Arc<String>, csv: &Mutex<BufWriter<File>>, json: bool, ) -> Result<()> { loop { let (c, acc) = match work_stack.lock().unwrap().pop() { Some(work) => work, None => { info!("Could not fetch new work, exiting loop!"); return Ok(()); } }; if c >= 5 { info!("Account {} seed {} times, discarding!", acc, c); continue; } let a = Address(hexdecode::decode(&acc.as_bytes()).unwrap().as_slice().into()); let worker = scheduler.get_worker(); let res = worker.analyze(a); match res { Ok(r) => { let file_path = if json { format!("{}/{}.json", root_path, acc) } else { format!("{}/{}", root_path, acc) }; let mut f = match File::create(file_path) { Ok(f) => f, Err(e) => { error!("Could not create file for {}: {:?}", acc, e); return Err(Error::from_str(format!( "Could not create file for {}: {:?}", acc, e ))); } }; if json { if let AnalysisSuccess::Success(ref analysis) = r { let mut res = (false, false, false); if let Some(ref attacks) = analysis.attacks { for attack in attacks { if attack.attack_type == AttackType::StealMoney { res.0 = true; } if attack.attack_type == AttackType::DeleteContract { res.1 = true; } if attack.attack_type == AttackType::HijackControlFlow { res.2 = true; } } } csv.lock().unwrap().write_all(format!("{:x}, {}, {}, {}\n", analysis.address, res.0, res.1, res.2).as_bytes()).expect("Could not write to csv file!"); } let _write_res = f.write_all(json!(r).to_string().as_bytes()); } else { let content = match r { AnalysisSuccess::Success(analysis) => { let mut res = (false, false, false); if let Some(ref attacks) = analysis.attacks { for attack in attacks { if attack.attack_type == AttackType::StealMoney { res.0 = true; } if attack.attack_type == AttackType::DeleteContract { res.1 = true; } if attack.attack_type == AttackType::HijackControlFlow { res.2 = true; } } } csv.lock().unwrap().write_all(format!("{:x}, {}, {}, {}\n", analysis.address, res.0, res.1, res.2).as_bytes()).expect("Could not write to csv file!"); format!("{}", analysis) }, AnalysisSuccess::Failure(s) => { warn!("Failure during analysing {}: {}", acc, s); s }, AnalysisSuccess::Timeout => { warn!("Timeout during analysis: {:?}", acc); format!("Timeout analysing {:?}", acc) }, }; let _write_res = f.write_all(content.as_bytes()); } } Err(e) => { if let Kind::Retry = e.kind() { error!("Error analyzing {}, retrying...", acc); work_stack.lock().unwrap().push((c+1, acc)); } else { error!("Error analyzing {}: {:?} worker died!", acc, e); } } }; info!( "Analyzed {} of {} contracts", counter.fetch_add(1, Ordering::Relaxed), acc_len ); } } fn main() { // init logger init_logger().expect("Could not initialize logger"); // parse args let matches = parse_args(); // create root path let root_path = format!( "analysis/{}/", Local::now().format("%Y-%m-%d-%H:%M:%S").to_string() ); fs::create_dir_all(root_path.clone()).expect("Could not create root folder for analysis"); let root_path = Arc::new(root_path); let acc_path = matches.value_of("INPUT").unwrap(); let server_path = matches.value_of("SERVER_LIST").unwrap(); let (work_stack, acc_len) = parse_account_list(acc_path); let server_list = parse_server_list(server_path); let server_len = server_list.len(); let timeout = if let Some(b) = matches.value_of("timeout") { b.parse().expect("Incorrect timeout supplied!") } else { 0 }; let scheduler = Arc::new(Scheduler::with_worker_count(server_list, timeout)); let counter = Arc::new(AtomicUsize::new(1)); let mut f = File::create(format!("{}/analysis.csv", root_path)).expect("Could not create csv file!"); f.write_all("address, steal ether, trigger suicide, hijack control flow\n".as_bytes()).expect("Could not write header to cvs!"); let csv_writer = Arc::new(Mutex::new(BufWriter::new(f))); info!("Starting Analysis"); let mut threads = Vec::new(); for _ in 0..server_len { let work_stack_clone = Arc::clone(&work_stack); let scheduler_clone = Arc::clone(&scheduler); let counter_clone = Arc::clone(&counter); let root_path_clone = Arc::clone(&root_path); let csv_clone = Arc::clone(&csv_writer); let json = matches.is_present("json"); let join_handle = thread::spawn(move || { execute( work_stack_clone, scheduler_clone, counter_clone, acc_len, root_path_clone, &csv_clone, json, ) }); threads.push(join_handle); } csv_writer.lock().unwrap().flush().expect("Could not finally flush writer"); for handle in threads { let _res = handle.join(); } info!("Finished Analysis"); }
}
random_line_split
scheduler.rs
extern crate clap; extern crate esvm; extern crate fern; extern crate ethereum_newtypes; extern crate rayon; extern crate regex; extern crate reqwest; extern crate hexdecode; extern crate serde_json; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate chrono; use std::fs::{self, File}; use std::io::{BufWriter, Read, Write}; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, Mutex, }; use std::thread; use std::time::Duration; use esvm::{AttackType, TimeoutAnalysis, AnalysisSuccess}; use serde_json::json; use chrono::prelude::Local; use clap::{App, Arg, ArgMatches}; use ethereum_newtypes::{Address}; use regex::Regex; use reqwest::Client; fn init_logger() -> Result<()> { fern::Dispatch::new() // Perform allocation-free log formatting .format(|out, message, record| { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message )) }) // Add blanket level filter - .level(log::LevelFilter::Info) // Output to stdout, files, and other Dispatch configurations .chain(std::io::stdout()) .chain(fern::log_file("log/evmse-scheduler.log")?) // Apply globally .apply()?; Ok(()) } #[derive(Debug)] struct Worker { client: Client, url: String, timeout: Duration, } impl Worker { fn new(url: &str, timeout: usize) -> Result<Worker> { let client = reqwest::Client::builder().timeout(None).build()?; let mut url = format!("{}/analyze_address", url); if timeout > 0 { url.push_str("_timeout"); } let timeout = Duration::from_secs((timeout * 60) as u64); Ok(Worker { client, url: url, timeout, }) } fn analyze(&self, address: Address) -> Result<AnalysisSuccess> { info!("Analyzing {:x}", address.0); let mut res = if self.timeout > Duration::from_secs(0) { self .client .post(&self.url) .json(&TimeoutAnalysis { address, timeout: self.timeout}) .send()? } else { self .client .post(&self.url) .json(&address) .send()? }; Ok(res.json()?) } fn check_alive(&self) -> Result<()> { self.client .get(&format!("{}/alive", &self.url)) .send() .map_err(|e| e.into()) .map(|_| ()) } } struct WorkerHandle<'a> { worker: Option<Worker>, scheduler: &'a Scheduler, kill: bool, } impl<'a> WorkerHandle<'a> { // specifically consume the handle to force readding the worker fn analyze(mut self, addr: Address) -> Result<AnalysisSuccess> { let res = self.worker.as_ref().unwrap().analyze(addr); if let Err(ref error) = res { error!("Error analyzing {:x?}, checking worker!", error); if let Err(_) = self.worker.as_ref().unwrap().check_alive() { error!("Worker died analyzing {:x?}, shuting down worker!", error); self.kill = true; } else { return Err(Error::retry()); } } res } } impl<'a> Drop for WorkerHandle<'a> { fn drop(&mut self) { if!self.kill { let worker = self .worker .take() .expect("Worker replaced before adding back"); self.scheduler.add_worker(worker) } else { self.worker .take() .expect("Worker replaced before adding back"); } } } #[derive(Debug)] struct Scheduler { queue: Arc<Mutex<Vec<Worker>>>, } impl Scheduler { fn new() -> Self { let queue = Arc::new(Mutex::new(Vec::new())); Self { queue } } fn with_worker_count(urls: Vec<String>, timeout: usize) -> Self { let s = Scheduler::new(); for url in &urls { s.queue.lock().unwrap().push(Worker::new(url, timeout).unwrap()); // if the workers can not connect initially fail } s } fn add_worker(&self, worker: Worker) { self.queue.lock().unwrap().push(worker); } fn get_worker(&self) -> WorkerHandle { let worker; loop { if let Some(w) = self.queue.lock().unwrap().pop() { worker = Some(w); break; } } WorkerHandle { worker, scheduler: self, kill: false, } } } type Result<T> = ::std::result::Result<T, Error>; #[derive(Debug)] struct Error { kind: Kind, } impl Error { fn from_str(s: String) -> Self { Self { kind: Kind::Execution(s), } } fn retry() -> Self { Self { kind: Kind::Retry, } } fn kind(&self) -> &Kind { &self.kind } } macro_rules! impl_error_kind { ( $(#[$struct_attr:meta])* enum Kind { $( $enum_variant_name:ident($error_type:path), )+ ; $( $single_variant_name:ident, )+ } ) => { // meta attributes $(#[$struct_attr])* // enum definition enum Kind { $( $enum_variant_name($error_type), )+ $( $single_variant_name, )+ } // impl error conversion for each type $( impl ::std::convert::From<$error_type> for Error { fn from(error: $error_type) -> Self { Self { kind: Kind::$enum_variant_name(error), } } } )+ }; } impl_error_kind!(#[derive(Debug)] enum Kind { Reqwest(reqwest::Error), SerdeJson(serde_json::Error), Log(log::SetLoggerError), IO(std::io::Error), Execution(String), ; Retry, }); fn parse_args<'a>() -> ArgMatches<'a> { App::new("EthAEG scheduler for analyzing a large list of contracts") .arg( Arg::with_name("INPUT") .help("Set the list of accounts to scan") .required(true) .index(1), ) .arg( Arg::with_name("SERVER_LIST") .help("Set the list of backend servers") .required(true) .index(2), ) .arg(Arg::with_name("timeout").long("timeout").takes_value(true).help("Specify a timeout for the analysis, none used by default")) .arg(Arg::with_name("json").long("json").help("Dump the analysis result in json format.")) .get_matches() } fn parse_account_list(path: &str) -> (Arc<Mutex<Vec<(usize, String)>>>, usize) { let mut acc_list = String::new(); File::open(path) .expect("Could not open account list") .read_to_string(&mut acc_list) .expect("Could not read account list"); let acc_vec: Vec<(usize, String)> = acc_list .lines() .filter_map(|line| match ACC_RE.captures(line) { Some(cap) => { let capture = cap.get(0).unwrap().as_str(); Some((0, capture.to_string())) } None => { warn!("Could not process: {}", line); None } }) .collect(); let len = acc_vec.len(); (Arc::new(Mutex::new(acc_vec)), len) } fn parse_server_list(path: &str) -> Vec<String> { let mut server_list = String::new(); File::open(path) .expect("Could not open server list") .read_to_string(&mut server_list) .expect("Could not read server list"); server_list .lines() .map(|line| { let line = line.trim(); if line.starts_with("http") || line.starts_with("https") { line.to_string() } else { format!("http://{}", line) } }) .collect() } lazy_static! { static ref ACC_RE: Regex = Regex::new(r"0x[A-za-z0-9]{40}").unwrap(); } fn execute( work_stack: Arc<Mutex<Vec<(usize, String)>>>, scheduler: Arc<Scheduler>, counter: Arc<AtomicUsize>, acc_len: usize, root_path: Arc<String>, csv: &Mutex<BufWriter<File>>, json: bool, ) -> Result<()> { loop { let (c, acc) = match work_stack.lock().unwrap().pop() { Some(work) => work, None => { info!("Could not fetch new work, exiting loop!"); return Ok(()); } }; if c >= 5 { info!("Account {} seed {} times, discarding!", acc, c); continue; } let a = Address(hexdecode::decode(&acc.as_bytes()).unwrap().as_slice().into()); let worker = scheduler.get_worker(); let res = worker.analyze(a); match res { Ok(r) => { let file_path = if json { format!("{}/{}.json", root_path, acc) } else { format!("{}/{}", root_path, acc) }; let mut f = match File::create(file_path) { Ok(f) => f, Err(e) => { error!("Could not create file for {}: {:?}", acc, e); return Err(Error::from_str(format!( "Could not create file for {}: {:?}", acc, e ))); } }; if json { if let AnalysisSuccess::Success(ref analysis) = r { let mut res = (false, false, false); if let Some(ref attacks) = analysis.attacks { for attack in attacks { if attack.attack_type == AttackType::StealMoney { res.0 = true; } if attack.attack_type == AttackType::DeleteContract { res.1 = true; } if attack.attack_type == AttackType::HijackControlFlow { res.2 = true; } } } csv.lock().unwrap().write_all(format!("{:x}, {}, {}, {}\n", analysis.address, res.0, res.1, res.2).as_bytes()).expect("Could not write to csv file!"); } let _write_res = f.write_all(json!(r).to_string().as_bytes()); } else { let content = match r { AnalysisSuccess::Success(analysis) => { let mut res = (false, false, false); if let Some(ref attacks) = analysis.attacks { for attack in attacks { if attack.attack_type == AttackType::StealMoney
if attack.attack_type == AttackType::DeleteContract { res.1 = true; } if attack.attack_type == AttackType::HijackControlFlow { res.2 = true; } } } csv.lock().unwrap().write_all(format!("{:x}, {}, {}, {}\n", analysis.address, res.0, res.1, res.2).as_bytes()).expect("Could not write to csv file!"); format!("{}", analysis) }, AnalysisSuccess::Failure(s) => { warn!("Failure during analysing {}: {}", acc, s); s }, AnalysisSuccess::Timeout => { warn!("Timeout during analysis: {:?}", acc); format!("Timeout analysing {:?}", acc) }, }; let _write_res = f.write_all(content.as_bytes()); } } Err(e) => { if let Kind::Retry = e.kind() { error!("Error analyzing {}, retrying...", acc); work_stack.lock().unwrap().push((c+1, acc)); } else { error!("Error analyzing {}: {:?} worker died!", acc, e); } } }; info!( "Analyzed {} of {} contracts", counter.fetch_add(1, Ordering::Relaxed), acc_len ); } } fn main() { // init logger init_logger().expect("Could not initialize logger"); // parse args let matches = parse_args(); // create root path let root_path = format!( "analysis/{}/", Local::now().format("%Y-%m-%d-%H:%M:%S").to_string() ); fs::create_dir_all(root_path.clone()).expect("Could not create root folder for analysis"); let root_path = Arc::new(root_path); let acc_path = matches.value_of("INPUT").unwrap(); let server_path = matches.value_of("SERVER_LIST").unwrap(); let (work_stack, acc_len) = parse_account_list(acc_path); let server_list = parse_server_list(server_path); let server_len = server_list.len(); let timeout = if let Some(b) = matches.value_of("timeout") { b.parse().expect("Incorrect timeout supplied!") } else { 0 }; let scheduler = Arc::new(Scheduler::with_worker_count(server_list, timeout)); let counter = Arc::new(AtomicUsize::new(1)); let mut f = File::create(format!("{}/analysis.csv", root_path)).expect("Could not create csv file!"); f.write_all("address, steal ether, trigger suicide, hijack control flow\n".as_bytes()).expect("Could not write header to cvs!"); let csv_writer = Arc::new(Mutex::new(BufWriter::new(f))); info!("Starting Analysis"); let mut threads = Vec::new(); for _ in 0..server_len { let work_stack_clone = Arc::clone(&work_stack); let scheduler_clone = Arc::clone(&scheduler); let counter_clone = Arc::clone(&counter); let root_path_clone = Arc::clone(&root_path); let csv_clone = Arc::clone(&csv_writer); let json = matches.is_present("json"); let join_handle = thread::spawn(move || { execute( work_stack_clone, scheduler_clone, counter_clone, acc_len, root_path_clone, &csv_clone, json, ) }); threads.push(join_handle); } csv_writer.lock().unwrap().flush().expect("Could not finally flush writer"); for handle in threads { let _res = handle.join(); } info!("Finished Analysis"); }
{ res.0 = true; }
conditional_block
lib.rs
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![deny(missing_docs)] //! This module provides a test HTTP(S) server that can be instantiated simply by a unit test, for //! connecting components to where you need to vary the response(s) from the HTTP(S) server during //! the operation of the test. //! //! It handles the TCP setup, letting the user specify `Handler` implementations which return the //! responses from the server. `Handler` implementations are meant to be composable to provide //! for fault injection and varying behavior in tests. // This is gratuitously borrowed from src/sys/pkg/lib/fuchsia-pkg-testing/src/serve.rs, and then // made generic across all requests by removing the repo-serving aspects of it. use { anyhow::Error, chrono::Utc, fuchsia_async::{self as fasync, Task}, fuchsia_hyper, futures::{future::BoxFuture, prelude::*}, hyper::{ server::{accept::from_stream, Server}, service::{make_service_fn, service_fn}, Body, Request, Response, StatusCode, }, std::{ convert::Infallible, net::{Ipv6Addr, SocketAddr}, pin::Pin, sync::Arc, }, }; // Some provided Handler implementations. pub mod handler; // Some provided Handler implementations for injecting faults into the server's behavior. pub mod fault_injection; /// A "test" HTTP(S) server which is composed of `Handler` implementations, and holding the /// connection state. pub struct TestServer { stop: futures::channel::oneshot::Sender<()>, addr: SocketAddr, use_https: bool, task: Task<()>, } /// Base trait that all Handlers implement. pub trait Handler:'static + Send + Sync { /// A Handler impl signals that it wishes to handle a request by returning a response for it, /// otherwise it returns None. fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>>; } impl Handler for Arc<dyn Handler> { fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>> { (**self).handles(request) } } impl TestServer { /// return the scheme of the TestServer fn scheme(&self) -> &'static str { if self.use_https { "https" } else { "http" } } /// Returns the URL that can be used to connect to this repository from this device. pub fn local_url(&self) -> String { format!("{}://localhost:{}", self.scheme(), self.addr.port()) } /// Returns the URL for the given path that can be used to connect to this repository from this /// device. pub fn local_url_for_path(&self, path: &str) -> String { let path = path.trim_start_matches('/'); format!("{}://localhost:{}/{}", self.scheme(), self.addr.port(), path) } /// Gracefully signal the server to stop and returns a future that resolves when it terminates. pub fn stop(self) -> impl Future<Output = ()> { self.stop.send(()).expect("remote end to still be open"); self.task } /// Internal helper which iterates over all Handlers until it finds one that will respond to the /// request. It then returns that response. If not response is found, it returns 404 NOT_FOUND. async fn handle_request( handlers: Arc<Vec<Arc<dyn Handler>>>, req: Request<Body>, ) -> Response<Body> { let response = handlers.iter().find_map(|h| h.handles(&req)); match response { Some(response) => response.await, None => Response::builder().status(StatusCode::NOT_FOUND).body(Body::empty()).unwrap(), } } /// Create a Builder pub fn builder() -> TestServerBuilder { TestServerBuilder::new() } } /// A builder to construct a `TestServer`. #[derive(Default)] pub struct TestServerBuilder { handlers: Vec<Arc<dyn Handler>>, https_certs: Option<(Vec<rustls::Certificate>, rustls::PrivateKey)>, } impl TestServerBuilder { /// Create a new TestServerBuilder pub fn new() -> Self { Self::default() } /// Serve over TLS, using a server certificate rooted the provided certs pub fn use_https(mut self, cert_chain: &[u8], private_key: &[u8]) -> Self { let cert_chain = parse_cert_chain(cert_chain); let private_key = parse_private_key(private_key); self.https_certs = Some((cert_chain, private_key)); self } /// Add a Handler which implements the server's behavior. These are given the ability to /// handle a request in the order in which they are added to the `TestServerBuilder`. pub fn handler(mut self, handler: impl Handler +'static) -> Self { self.handlers.push(Arc::new(handler)); self } /// Spawn the server on the current executor, returning a handle to manage the server. pub async fn start(self) -> TestServer { let (mut listener, addr) = { let addr = SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), 0); let listener = bind_listener(&addr).await; let local_addr = listener.local_addr().unwrap(); (listener, local_addr) }; let (stop, rx_stop) = futures::channel::oneshot::channel(); let (tls_acceptor, use_https) = if let Some((cert_chain, private_key)) = self.https_certs { // build a server configuration using a test CA and cert chain let mut tls_config = rustls::ServerConfig::new(rustls::NoClientAuth::new()); tls_config.set_single_cert(cert_chain, private_key).unwrap(); let tls_acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(tls_config)); (Some(tls_acceptor), true) } else { (None, false) }; let task = fasync::Task::spawn(async move { let listener = accept_stream(&mut listener); let listener = listener .map_err(Error::from) .map_ok(|conn| fuchsia_hyper::TcpStream { stream: conn }); let connections = if let Some(tls_acceptor) = tls_acceptor { // wrap incoming tcp streams listener .and_then(move |conn| { tls_acceptor.accept(conn).map(|res| match res { Ok(conn) => { Ok(Pin::new(Box::new(conn)) as Pin<Box<dyn AsyncReadWrite>>) } Err(e) => Err(Error::from(e)), }) }) .boxed() // connections } else { listener .map_ok(|conn| Pin::new(Box::new(conn)) as Pin<Box<dyn AsyncReadWrite>>) .boxed() // connections }; // This is the root Arc<Vec<Arc<dyn Handler>>>. let handlers = Arc::new(self.handlers); let make_svc = make_service_fn(move |_socket| { // Each connection to the server receives a separate service_fn instance, and so // needs it's own copy of the handlers, this is a factory of sorts. let handlers = Arc::clone(&handlers); async move { Ok::<_, Infallible>(service_fn(move |req| { // Each request made by a connection is serviced by the service_fn created from // this scope, which is why there is another cloning of the Arc of Handlers. let method = req.method().to_owned(); let path = req.uri().path().to_owned(); TestServer::handle_request(Arc::clone(&handlers), req) .inspect(move |x| { println!( "{} [test http] {} {} => {}", Utc::now().format("%T.%6f"), method, path, x.status() ) }) .map(Ok::<_, Infallible>) })) } }); Server::builder(from_stream(connections)) .executor(fuchsia_hyper::Executor) .serve(make_svc) .with_graceful_shutdown( rx_stop.map(|res| res.unwrap_or_else(|futures::channel::oneshot::Canceled| ())), ) .unwrap_or_else(|e| panic!("error serving repo over http: {}", e)) .await; }); TestServer { stop, addr, use_https, task } } } #[cfg(target_os = "fuchsia")] async fn bind_listener(addr: &SocketAddr) -> fuchsia_async::net::TcpListener { fuchsia_async::net::TcpListener::bind(addr).unwrap() } #[cfg(not(target_os = "fuchsia"))] async fn bind_listener(&addr: &SocketAddr) -> async_net::TcpListener { async_net::TcpListener::bind(addr).await.unwrap() } #[cfg(target_os = "fuchsia")] fn
<'a>( listener: &'a mut fuchsia_async::net::TcpListener, ) -> impl Stream<Item = std::io::Result<fuchsia_async::net::TcpStream>> + 'a { use std::task::{Context, Poll}; #[pin_project::pin_project] struct AcceptStream<'a> { #[pin] listener: &'a mut fuchsia_async::net::TcpListener, } impl<'a> Stream for AcceptStream<'a> { type Item = std::io::Result<fuchsia_async::net::TcpStream>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let mut this = self.project(); match this.listener.async_accept(cx) { Poll::Ready(Ok((conn, _addr))) => Poll::Ready(Some(Ok(conn))), Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))), Poll::Pending => Poll::Pending, } } } AcceptStream { listener } } #[cfg(not(target_os = "fuchsia"))] fn accept_stream<'a>( listener: &'a mut async_net::TcpListener, ) -> impl Stream<Item = std::io::Result<async_net::TcpStream>> + 'a { listener.incoming() } fn parse_cert_chain(mut bytes: &[u8]) -> Vec<rustls::Certificate> { rustls::internal::pemfile::certs(&mut bytes).expect("certs to parse") } fn parse_private_key(mut bytes: &[u8]) -> rustls::PrivateKey { let keys = rustls::internal::pemfile::rsa_private_keys(&mut bytes).expect("private keys to parse"); assert_eq!(keys.len(), 1, "expecting a single private key"); keys.into_iter().next().unwrap() } trait AsyncReadWrite: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send {} impl<T> AsyncReadWrite for T where T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send {} // These are a set of useful functions when writing tests. /// Create a GET request for a given url, which can be used with any hyper client. pub fn make_get(url: impl AsRef<str>) -> Result<Request<Body>, Error> { Request::get(url.as_ref()).body(Body::empty()).map_err(Error::from) } /// Perform an HTTP GET for the given url, returning the result. pub async fn get(url: impl AsRef<str>) -> Result<Response<Body>, Error> { let request = make_get(url)?; let client = fuchsia_hyper::new_client(); let response = client.request(request).await?; Ok(response) } /// Collect a Response into a single Vec of bytes. pub async fn body_as_bytes(response: Response<Body>) -> Result<Vec<u8>, Error> { let bytes = response .into_body() .try_fold(Vec::new(), |mut vec, b| async move { vec.extend(b); Ok(vec) }) .await?; Ok(bytes) } /// Collect a Response's Body and convert the body to a tring. pub async fn body_as_string(response: Response<Body>) -> Result<String, Error> { let bytes = body_as_bytes(response).await?; let string = String::from_utf8(bytes)?; Ok(string) } /// Get a url and return the body of the response as a string. pub async fn get_body_as_string(url: impl AsRef<str>) -> Result<String, Error> { let response = get(url).await?; body_as_string(response).await } #[cfg(test)] mod tests { use super::*; use crate::{fault_injection::*, handler::*}; use anyhow::anyhow; use fasync::TimeoutExt; #[fuchsia_async::run_singlethreaded(test)] async fn test_start_stop() { let server = TestServer::builder().start().await; server.stop().await; } #[fuchsia_async::run_singlethreaded(test)] async fn test_empty_server_404s() { let server = TestServer::builder().start().await; let result = get(server.local_url()).await; assert_eq!(result.unwrap().status(), StatusCode::NOT_FOUND); } #[fuchsia_async::run_singlethreaded(test)] async fn test_shared_handler() { let shared: Arc<dyn Handler> = Arc::new(StaticResponse::ok_body("shared")); let server = TestServer::builder() .handler(ForPath::new("/a", Arc::clone(&shared))) .handler(shared) .start() .await; assert_eq!(get_body_as_string(server.local_url_for_path("/a")).await.unwrap(), "shared"); assert_eq!(get_body_as_string(server.local_url_for_path("/foo")).await.unwrap(), "shared"); } #[fuchsia_async::run_singlethreaded(test)] async fn test_simple_responder() { let server = TestServer::builder().handler(StaticResponse::ok_body("some data")).start().await; assert_eq!( get_body_as_string(server.local_url_for_path("ignored")).await.unwrap(), "some data" ); } #[fuchsia_async::run_singlethreaded(test)] async fn test_simple_path() { let server = TestServer::builder() .handler(ForPath::new("/some/path", StaticResponse::ok_body("some data"))) .start() .await; assert_eq!( get_body_as_string(server.local_url_for_path("/some/path")).await.unwrap(), "some data" ); } #[fuchsia_async::run_singlethreaded(test)] async fn test_simple_path_doesnt_respond_to_wrong_path() { let server = TestServer::builder() .handler(ForPath::new("/some/path", StaticResponse::ok_body("some data"))) .start() .await; // make sure a non-matching path fails let result = get(server.local_url_for_path("/other/path")).await; assert_eq!(result.unwrap().status(), StatusCode::NOT_FOUND); } #[fuchsia_async::run_singlethreaded(test)] async fn test_hang() { let server = TestServer::builder().handler(Hang).start().await; let result = get(server.local_url_for_path("ignored")) .on_timeout(std::time::Duration::from_secs(1), || Err(anyhow!("timed out"))) .await; assert_eq!(result.unwrap_err().to_string(), Error::msg("timed out").to_string()); } #[fuchsia_async::run_singlethreaded(test)] async fn test_hang_body() { let server = TestServer::builder().handler(HangBody::content_length(500)).start().await; let result = get_body_as_string(server.local_url_for_path("ignored")) .on_timeout(std::time::Duration::from_secs(1), || Err(anyhow!("timed out"))) .await; assert_eq!(result.unwrap_err().to_string(), Error::msg("timed out").to_string()); } }
accept_stream
identifier_name
lib.rs
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![deny(missing_docs)] //! This module provides a test HTTP(S) server that can be instantiated simply by a unit test, for //! connecting components to where you need to vary the response(s) from the HTTP(S) server during //! the operation of the test. //! //! It handles the TCP setup, letting the user specify `Handler` implementations which return the //! responses from the server. `Handler` implementations are meant to be composable to provide //! for fault injection and varying behavior in tests. // This is gratuitously borrowed from src/sys/pkg/lib/fuchsia-pkg-testing/src/serve.rs, and then // made generic across all requests by removing the repo-serving aspects of it. use { anyhow::Error, chrono::Utc, fuchsia_async::{self as fasync, Task}, fuchsia_hyper, futures::{future::BoxFuture, prelude::*}, hyper::{ server::{accept::from_stream, Server}, service::{make_service_fn, service_fn}, Body, Request, Response, StatusCode, }, std::{ convert::Infallible, net::{Ipv6Addr, SocketAddr}, pin::Pin, sync::Arc, }, }; // Some provided Handler implementations. pub mod handler; // Some provided Handler implementations for injecting faults into the server's behavior. pub mod fault_injection; /// A "test" HTTP(S) server which is composed of `Handler` implementations, and holding the /// connection state. pub struct TestServer { stop: futures::channel::oneshot::Sender<()>, addr: SocketAddr, use_https: bool, task: Task<()>, } /// Base trait that all Handlers implement. pub trait Handler:'static + Send + Sync { /// A Handler impl signals that it wishes to handle a request by returning a response for it, /// otherwise it returns None. fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>>; } impl Handler for Arc<dyn Handler> { fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>> { (**self).handles(request) } } impl TestServer { /// return the scheme of the TestServer fn scheme(&self) -> &'static str { if self.use_https { "https" } else { "http" } } /// Returns the URL that can be used to connect to this repository from this device. pub fn local_url(&self) -> String { format!("{}://localhost:{}", self.scheme(), self.addr.port()) } /// Returns the URL for the given path that can be used to connect to this repository from this /// device. pub fn local_url_for_path(&self, path: &str) -> String { let path = path.trim_start_matches('/'); format!("{}://localhost:{}/{}", self.scheme(), self.addr.port(), path) } /// Gracefully signal the server to stop and returns a future that resolves when it terminates. pub fn stop(self) -> impl Future<Output = ()> { self.stop.send(()).expect("remote end to still be open"); self.task } /// Internal helper which iterates over all Handlers until it finds one that will respond to the /// request. It then returns that response. If not response is found, it returns 404 NOT_FOUND. async fn handle_request( handlers: Arc<Vec<Arc<dyn Handler>>>, req: Request<Body>, ) -> Response<Body> { let response = handlers.iter().find_map(|h| h.handles(&req)); match response { Some(response) => response.await, None => Response::builder().status(StatusCode::NOT_FOUND).body(Body::empty()).unwrap(), } } /// Create a Builder pub fn builder() -> TestServerBuilder { TestServerBuilder::new() } } /// A builder to construct a `TestServer`. #[derive(Default)] pub struct TestServerBuilder { handlers: Vec<Arc<dyn Handler>>, https_certs: Option<(Vec<rustls::Certificate>, rustls::PrivateKey)>, } impl TestServerBuilder { /// Create a new TestServerBuilder pub fn new() -> Self { Self::default() } /// Serve over TLS, using a server certificate rooted the provided certs pub fn use_https(mut self, cert_chain: &[u8], private_key: &[u8]) -> Self { let cert_chain = parse_cert_chain(cert_chain); let private_key = parse_private_key(private_key); self.https_certs = Some((cert_chain, private_key)); self } /// Add a Handler which implements the server's behavior. These are given the ability to /// handle a request in the order in which they are added to the `TestServerBuilder`. pub fn handler(mut self, handler: impl Handler +'static) -> Self { self.handlers.push(Arc::new(handler)); self } /// Spawn the server on the current executor, returning a handle to manage the server. pub async fn start(self) -> TestServer { let (mut listener, addr) = { let addr = SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), 0); let listener = bind_listener(&addr).await; let local_addr = listener.local_addr().unwrap(); (listener, local_addr) }; let (stop, rx_stop) = futures::channel::oneshot::channel(); let (tls_acceptor, use_https) = if let Some((cert_chain, private_key)) = self.https_certs
else { (None, false) }; let task = fasync::Task::spawn(async move { let listener = accept_stream(&mut listener); let listener = listener .map_err(Error::from) .map_ok(|conn| fuchsia_hyper::TcpStream { stream: conn }); let connections = if let Some(tls_acceptor) = tls_acceptor { // wrap incoming tcp streams listener .and_then(move |conn| { tls_acceptor.accept(conn).map(|res| match res { Ok(conn) => { Ok(Pin::new(Box::new(conn)) as Pin<Box<dyn AsyncReadWrite>>) } Err(e) => Err(Error::from(e)), }) }) .boxed() // connections } else { listener .map_ok(|conn| Pin::new(Box::new(conn)) as Pin<Box<dyn AsyncReadWrite>>) .boxed() // connections }; // This is the root Arc<Vec<Arc<dyn Handler>>>. let handlers = Arc::new(self.handlers); let make_svc = make_service_fn(move |_socket| { // Each connection to the server receives a separate service_fn instance, and so // needs it's own copy of the handlers, this is a factory of sorts. let handlers = Arc::clone(&handlers); async move { Ok::<_, Infallible>(service_fn(move |req| { // Each request made by a connection is serviced by the service_fn created from // this scope, which is why there is another cloning of the Arc of Handlers. let method = req.method().to_owned(); let path = req.uri().path().to_owned(); TestServer::handle_request(Arc::clone(&handlers), req) .inspect(move |x| { println!( "{} [test http] {} {} => {}", Utc::now().format("%T.%6f"), method, path, x.status() ) }) .map(Ok::<_, Infallible>) })) } }); Server::builder(from_stream(connections)) .executor(fuchsia_hyper::Executor) .serve(make_svc) .with_graceful_shutdown( rx_stop.map(|res| res.unwrap_or_else(|futures::channel::oneshot::Canceled| ())), ) .unwrap_or_else(|e| panic!("error serving repo over http: {}", e)) .await; }); TestServer { stop, addr, use_https, task } } } #[cfg(target_os = "fuchsia")] async fn bind_listener(addr: &SocketAddr) -> fuchsia_async::net::TcpListener { fuchsia_async::net::TcpListener::bind(addr).unwrap() } #[cfg(not(target_os = "fuchsia"))] async fn bind_listener(&addr: &SocketAddr) -> async_net::TcpListener { async_net::TcpListener::bind(addr).await.unwrap() } #[cfg(target_os = "fuchsia")] fn accept_stream<'a>( listener: &'a mut fuchsia_async::net::TcpListener, ) -> impl Stream<Item = std::io::Result<fuchsia_async::net::TcpStream>> + 'a { use std::task::{Context, Poll}; #[pin_project::pin_project] struct AcceptStream<'a> { #[pin] listener: &'a mut fuchsia_async::net::TcpListener, } impl<'a> Stream for AcceptStream<'a> { type Item = std::io::Result<fuchsia_async::net::TcpStream>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let mut this = self.project(); match this.listener.async_accept(cx) { Poll::Ready(Ok((conn, _addr))) => Poll::Ready(Some(Ok(conn))), Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))), Poll::Pending => Poll::Pending, } } } AcceptStream { listener } } #[cfg(not(target_os = "fuchsia"))] fn accept_stream<'a>( listener: &'a mut async_net::TcpListener, ) -> impl Stream<Item = std::io::Result<async_net::TcpStream>> + 'a { listener.incoming() } fn parse_cert_chain(mut bytes: &[u8]) -> Vec<rustls::Certificate> { rustls::internal::pemfile::certs(&mut bytes).expect("certs to parse") } fn parse_private_key(mut bytes: &[u8]) -> rustls::PrivateKey { let keys = rustls::internal::pemfile::rsa_private_keys(&mut bytes).expect("private keys to parse"); assert_eq!(keys.len(), 1, "expecting a single private key"); keys.into_iter().next().unwrap() } trait AsyncReadWrite: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send {} impl<T> AsyncReadWrite for T where T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send {} // These are a set of useful functions when writing tests. /// Create a GET request for a given url, which can be used with any hyper client. pub fn make_get(url: impl AsRef<str>) -> Result<Request<Body>, Error> { Request::get(url.as_ref()).body(Body::empty()).map_err(Error::from) } /// Perform an HTTP GET for the given url, returning the result. pub async fn get(url: impl AsRef<str>) -> Result<Response<Body>, Error> { let request = make_get(url)?; let client = fuchsia_hyper::new_client(); let response = client.request(request).await?; Ok(response) } /// Collect a Response into a single Vec of bytes. pub async fn body_as_bytes(response: Response<Body>) -> Result<Vec<u8>, Error> { let bytes = response .into_body() .try_fold(Vec::new(), |mut vec, b| async move { vec.extend(b); Ok(vec) }) .await?; Ok(bytes) } /// Collect a Response's Body and convert the body to a tring. pub async fn body_as_string(response: Response<Body>) -> Result<String, Error> { let bytes = body_as_bytes(response).await?; let string = String::from_utf8(bytes)?; Ok(string) } /// Get a url and return the body of the response as a string. pub async fn get_body_as_string(url: impl AsRef<str>) -> Result<String, Error> { let response = get(url).await?; body_as_string(response).await } #[cfg(test)] mod tests { use super::*; use crate::{fault_injection::*, handler::*}; use anyhow::anyhow; use fasync::TimeoutExt; #[fuchsia_async::run_singlethreaded(test)] async fn test_start_stop() { let server = TestServer::builder().start().await; server.stop().await; } #[fuchsia_async::run_singlethreaded(test)] async fn test_empty_server_404s() { let server = TestServer::builder().start().await; let result = get(server.local_url()).await; assert_eq!(result.unwrap().status(), StatusCode::NOT_FOUND); } #[fuchsia_async::run_singlethreaded(test)] async fn test_shared_handler() { let shared: Arc<dyn Handler> = Arc::new(StaticResponse::ok_body("shared")); let server = TestServer::builder() .handler(ForPath::new("/a", Arc::clone(&shared))) .handler(shared) .start() .await; assert_eq!(get_body_as_string(server.local_url_for_path("/a")).await.unwrap(), "shared"); assert_eq!(get_body_as_string(server.local_url_for_path("/foo")).await.unwrap(), "shared"); } #[fuchsia_async::run_singlethreaded(test)] async fn test_simple_responder() { let server = TestServer::builder().handler(StaticResponse::ok_body("some data")).start().await; assert_eq!( get_body_as_string(server.local_url_for_path("ignored")).await.unwrap(), "some data" ); } #[fuchsia_async::run_singlethreaded(test)] async fn test_simple_path() { let server = TestServer::builder() .handler(ForPath::new("/some/path", StaticResponse::ok_body("some data"))) .start() .await; assert_eq!( get_body_as_string(server.local_url_for_path("/some/path")).await.unwrap(), "some data" ); } #[fuchsia_async::run_singlethreaded(test)] async fn test_simple_path_doesnt_respond_to_wrong_path() { let server = TestServer::builder() .handler(ForPath::new("/some/path", StaticResponse::ok_body("some data"))) .start() .await; // make sure a non-matching path fails let result = get(server.local_url_for_path("/other/path")).await; assert_eq!(result.unwrap().status(), StatusCode::NOT_FOUND); } #[fuchsia_async::run_singlethreaded(test)] async fn test_hang() { let server = TestServer::builder().handler(Hang).start().await; let result = get(server.local_url_for_path("ignored")) .on_timeout(std::time::Duration::from_secs(1), || Err(anyhow!("timed out"))) .await; assert_eq!(result.unwrap_err().to_string(), Error::msg("timed out").to_string()); } #[fuchsia_async::run_singlethreaded(test)] async fn test_hang_body() { let server = TestServer::builder().handler(HangBody::content_length(500)).start().await; let result = get_body_as_string(server.local_url_for_path("ignored")) .on_timeout(std::time::Duration::from_secs(1), || Err(anyhow!("timed out"))) .await; assert_eq!(result.unwrap_err().to_string(), Error::msg("timed out").to_string()); } }
{ // build a server configuration using a test CA and cert chain let mut tls_config = rustls::ServerConfig::new(rustls::NoClientAuth::new()); tls_config.set_single_cert(cert_chain, private_key).unwrap(); let tls_acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(tls_config)); (Some(tls_acceptor), true) }
conditional_block
lib.rs
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![deny(missing_docs)] //! This module provides a test HTTP(S) server that can be instantiated simply by a unit test, for //! connecting components to where you need to vary the response(s) from the HTTP(S) server during //! the operation of the test. //! //! It handles the TCP setup, letting the user specify `Handler` implementations which return the //! responses from the server. `Handler` implementations are meant to be composable to provide //! for fault injection and varying behavior in tests. // This is gratuitously borrowed from src/sys/pkg/lib/fuchsia-pkg-testing/src/serve.rs, and then // made generic across all requests by removing the repo-serving aspects of it. use { anyhow::Error, chrono::Utc, fuchsia_async::{self as fasync, Task}, fuchsia_hyper, futures::{future::BoxFuture, prelude::*}, hyper::{ server::{accept::from_stream, Server}, service::{make_service_fn, service_fn}, Body, Request, Response, StatusCode, }, std::{ convert::Infallible, net::{Ipv6Addr, SocketAddr}, pin::Pin, sync::Arc, }, }; // Some provided Handler implementations. pub mod handler; // Some provided Handler implementations for injecting faults into the server's behavior. pub mod fault_injection; /// A "test" HTTP(S) server which is composed of `Handler` implementations, and holding the /// connection state. pub struct TestServer { stop: futures::channel::oneshot::Sender<()>, addr: SocketAddr, use_https: bool, task: Task<()>, } /// Base trait that all Handlers implement. pub trait Handler:'static + Send + Sync { /// A Handler impl signals that it wishes to handle a request by returning a response for it, /// otherwise it returns None. fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>>; } impl Handler for Arc<dyn Handler> { fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>> { (**self).handles(request) } } impl TestServer { /// return the scheme of the TestServer fn scheme(&self) -> &'static str { if self.use_https { "https" } else { "http" } } /// Returns the URL that can be used to connect to this repository from this device. pub fn local_url(&self) -> String { format!("{}://localhost:{}", self.scheme(), self.addr.port()) } /// Returns the URL for the given path that can be used to connect to this repository from this /// device. pub fn local_url_for_path(&self, path: &str) -> String { let path = path.trim_start_matches('/'); format!("{}://localhost:{}/{}", self.scheme(), self.addr.port(), path) } /// Gracefully signal the server to stop and returns a future that resolves when it terminates. pub fn stop(self) -> impl Future<Output = ()> { self.stop.send(()).expect("remote end to still be open"); self.task } /// Internal helper which iterates over all Handlers until it finds one that will respond to the /// request. It then returns that response. If not response is found, it returns 404 NOT_FOUND. async fn handle_request( handlers: Arc<Vec<Arc<dyn Handler>>>, req: Request<Body>, ) -> Response<Body> { let response = handlers.iter().find_map(|h| h.handles(&req)); match response { Some(response) => response.await, None => Response::builder().status(StatusCode::NOT_FOUND).body(Body::empty()).unwrap(), } } /// Create a Builder pub fn builder() -> TestServerBuilder { TestServerBuilder::new() } } /// A builder to construct a `TestServer`. #[derive(Default)] pub struct TestServerBuilder { handlers: Vec<Arc<dyn Handler>>, https_certs: Option<(Vec<rustls::Certificate>, rustls::PrivateKey)>, } impl TestServerBuilder { /// Create a new TestServerBuilder pub fn new() -> Self { Self::default() } /// Serve over TLS, using a server certificate rooted the provided certs pub fn use_https(mut self, cert_chain: &[u8], private_key: &[u8]) -> Self { let cert_chain = parse_cert_chain(cert_chain); let private_key = parse_private_key(private_key); self.https_certs = Some((cert_chain, private_key)); self } /// Add a Handler which implements the server's behavior. These are given the ability to /// handle a request in the order in which they are added to the `TestServerBuilder`. pub fn handler(mut self, handler: impl Handler +'static) -> Self { self.handlers.push(Arc::new(handler)); self } /// Spawn the server on the current executor, returning a handle to manage the server. pub async fn start(self) -> TestServer { let (mut listener, addr) = { let addr = SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), 0); let listener = bind_listener(&addr).await; let local_addr = listener.local_addr().unwrap(); (listener, local_addr) }; let (stop, rx_stop) = futures::channel::oneshot::channel(); let (tls_acceptor, use_https) = if let Some((cert_chain, private_key)) = self.https_certs { // build a server configuration using a test CA and cert chain let mut tls_config = rustls::ServerConfig::new(rustls::NoClientAuth::new()); tls_config.set_single_cert(cert_chain, private_key).unwrap(); let tls_acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(tls_config)); (Some(tls_acceptor), true) } else { (None, false) }; let task = fasync::Task::spawn(async move { let listener = accept_stream(&mut listener); let listener = listener .map_err(Error::from) .map_ok(|conn| fuchsia_hyper::TcpStream { stream: conn }); let connections = if let Some(tls_acceptor) = tls_acceptor { // wrap incoming tcp streams listener .and_then(move |conn| { tls_acceptor.accept(conn).map(|res| match res { Ok(conn) => { Ok(Pin::new(Box::new(conn)) as Pin<Box<dyn AsyncReadWrite>>) } Err(e) => Err(Error::from(e)), }) }) .boxed() // connections } else { listener .map_ok(|conn| Pin::new(Box::new(conn)) as Pin<Box<dyn AsyncReadWrite>>) .boxed() // connections }; // This is the root Arc<Vec<Arc<dyn Handler>>>. let handlers = Arc::new(self.handlers); let make_svc = make_service_fn(move |_socket| { // Each connection to the server receives a separate service_fn instance, and so // needs it's own copy of the handlers, this is a factory of sorts. let handlers = Arc::clone(&handlers); async move { Ok::<_, Infallible>(service_fn(move |req| { // Each request made by a connection is serviced by the service_fn created from // this scope, which is why there is another cloning of the Arc of Handlers. let method = req.method().to_owned(); let path = req.uri().path().to_owned(); TestServer::handle_request(Arc::clone(&handlers), req) .inspect(move |x| { println!( "{} [test http] {} {} => {}", Utc::now().format("%T.%6f"), method, path, x.status() ) }) .map(Ok::<_, Infallible>) })) } }); Server::builder(from_stream(connections)) .executor(fuchsia_hyper::Executor) .serve(make_svc) .with_graceful_shutdown( rx_stop.map(|res| res.unwrap_or_else(|futures::channel::oneshot::Canceled| ())), ) .unwrap_or_else(|e| panic!("error serving repo over http: {}", e)) .await; }); TestServer { stop, addr, use_https, task } } } #[cfg(target_os = "fuchsia")] async fn bind_listener(addr: &SocketAddr) -> fuchsia_async::net::TcpListener { fuchsia_async::net::TcpListener::bind(addr).unwrap() } #[cfg(not(target_os = "fuchsia"))] async fn bind_listener(&addr: &SocketAddr) -> async_net::TcpListener { async_net::TcpListener::bind(addr).await.unwrap() } #[cfg(target_os = "fuchsia")] fn accept_stream<'a>( listener: &'a mut fuchsia_async::net::TcpListener, ) -> impl Stream<Item = std::io::Result<fuchsia_async::net::TcpStream>> + 'a { use std::task::{Context, Poll}; #[pin_project::pin_project] struct AcceptStream<'a> { #[pin] listener: &'a mut fuchsia_async::net::TcpListener, } impl<'a> Stream for AcceptStream<'a> { type Item = std::io::Result<fuchsia_async::net::TcpStream>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>
} AcceptStream { listener } } #[cfg(not(target_os = "fuchsia"))] fn accept_stream<'a>( listener: &'a mut async_net::TcpListener, ) -> impl Stream<Item = std::io::Result<async_net::TcpStream>> + 'a { listener.incoming() } fn parse_cert_chain(mut bytes: &[u8]) -> Vec<rustls::Certificate> { rustls::internal::pemfile::certs(&mut bytes).expect("certs to parse") } fn parse_private_key(mut bytes: &[u8]) -> rustls::PrivateKey { let keys = rustls::internal::pemfile::rsa_private_keys(&mut bytes).expect("private keys to parse"); assert_eq!(keys.len(), 1, "expecting a single private key"); keys.into_iter().next().unwrap() } trait AsyncReadWrite: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send {} impl<T> AsyncReadWrite for T where T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send {} // These are a set of useful functions when writing tests. /// Create a GET request for a given url, which can be used with any hyper client. pub fn make_get(url: impl AsRef<str>) -> Result<Request<Body>, Error> { Request::get(url.as_ref()).body(Body::empty()).map_err(Error::from) } /// Perform an HTTP GET for the given url, returning the result. pub async fn get(url: impl AsRef<str>) -> Result<Response<Body>, Error> { let request = make_get(url)?; let client = fuchsia_hyper::new_client(); let response = client.request(request).await?; Ok(response) } /// Collect a Response into a single Vec of bytes. pub async fn body_as_bytes(response: Response<Body>) -> Result<Vec<u8>, Error> { let bytes = response .into_body() .try_fold(Vec::new(), |mut vec, b| async move { vec.extend(b); Ok(vec) }) .await?; Ok(bytes) } /// Collect a Response's Body and convert the body to a tring. pub async fn body_as_string(response: Response<Body>) -> Result<String, Error> { let bytes = body_as_bytes(response).await?; let string = String::from_utf8(bytes)?; Ok(string) } /// Get a url and return the body of the response as a string. pub async fn get_body_as_string(url: impl AsRef<str>) -> Result<String, Error> { let response = get(url).await?; body_as_string(response).await } #[cfg(test)] mod tests { use super::*; use crate::{fault_injection::*, handler::*}; use anyhow::anyhow; use fasync::TimeoutExt; #[fuchsia_async::run_singlethreaded(test)] async fn test_start_stop() { let server = TestServer::builder().start().await; server.stop().await; } #[fuchsia_async::run_singlethreaded(test)] async fn test_empty_server_404s() { let server = TestServer::builder().start().await; let result = get(server.local_url()).await; assert_eq!(result.unwrap().status(), StatusCode::NOT_FOUND); } #[fuchsia_async::run_singlethreaded(test)] async fn test_shared_handler() { let shared: Arc<dyn Handler> = Arc::new(StaticResponse::ok_body("shared")); let server = TestServer::builder() .handler(ForPath::new("/a", Arc::clone(&shared))) .handler(shared) .start() .await; assert_eq!(get_body_as_string(server.local_url_for_path("/a")).await.unwrap(), "shared"); assert_eq!(get_body_as_string(server.local_url_for_path("/foo")).await.unwrap(), "shared"); } #[fuchsia_async::run_singlethreaded(test)] async fn test_simple_responder() { let server = TestServer::builder().handler(StaticResponse::ok_body("some data")).start().await; assert_eq!( get_body_as_string(server.local_url_for_path("ignored")).await.unwrap(), "some data" ); } #[fuchsia_async::run_singlethreaded(test)] async fn test_simple_path() { let server = TestServer::builder() .handler(ForPath::new("/some/path", StaticResponse::ok_body("some data"))) .start() .await; assert_eq!( get_body_as_string(server.local_url_for_path("/some/path")).await.unwrap(), "some data" ); } #[fuchsia_async::run_singlethreaded(test)] async fn test_simple_path_doesnt_respond_to_wrong_path() { let server = TestServer::builder() .handler(ForPath::new("/some/path", StaticResponse::ok_body("some data"))) .start() .await; // make sure a non-matching path fails let result = get(server.local_url_for_path("/other/path")).await; assert_eq!(result.unwrap().status(), StatusCode::NOT_FOUND); } #[fuchsia_async::run_singlethreaded(test)] async fn test_hang() { let server = TestServer::builder().handler(Hang).start().await; let result = get(server.local_url_for_path("ignored")) .on_timeout(std::time::Duration::from_secs(1), || Err(anyhow!("timed out"))) .await; assert_eq!(result.unwrap_err().to_string(), Error::msg("timed out").to_string()); } #[fuchsia_async::run_singlethreaded(test)] async fn test_hang_body() { let server = TestServer::builder().handler(HangBody::content_length(500)).start().await; let result = get_body_as_string(server.local_url_for_path("ignored")) .on_timeout(std::time::Duration::from_secs(1), || Err(anyhow!("timed out"))) .await; assert_eq!(result.unwrap_err().to_string(), Error::msg("timed out").to_string()); } }
{ let mut this = self.project(); match this.listener.async_accept(cx) { Poll::Ready(Ok((conn, _addr))) => Poll::Ready(Some(Ok(conn))), Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))), Poll::Pending => Poll::Pending, } }
identifier_body
lib.rs
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![deny(missing_docs)] //! This module provides a test HTTP(S) server that can be instantiated simply by a unit test, for //! connecting components to where you need to vary the response(s) from the HTTP(S) server during //! the operation of the test. //! //! It handles the TCP setup, letting the user specify `Handler` implementations which return the //! responses from the server. `Handler` implementations are meant to be composable to provide //! for fault injection and varying behavior in tests. // This is gratuitously borrowed from src/sys/pkg/lib/fuchsia-pkg-testing/src/serve.rs, and then // made generic across all requests by removing the repo-serving aspects of it. use { anyhow::Error, chrono::Utc, fuchsia_async::{self as fasync, Task}, fuchsia_hyper, futures::{future::BoxFuture, prelude::*}, hyper::{ server::{accept::from_stream, Server}, service::{make_service_fn, service_fn}, Body, Request, Response, StatusCode, }, std::{ convert::Infallible, net::{Ipv6Addr, SocketAddr}, pin::Pin, sync::Arc, }, }; // Some provided Handler implementations. pub mod handler; // Some provided Handler implementations for injecting faults into the server's behavior. pub mod fault_injection; /// A "test" HTTP(S) server which is composed of `Handler` implementations, and holding the /// connection state. pub struct TestServer { stop: futures::channel::oneshot::Sender<()>, addr: SocketAddr, use_https: bool, task: Task<()>, } /// Base trait that all Handlers implement. pub trait Handler:'static + Send + Sync { /// A Handler impl signals that it wishes to handle a request by returning a response for it, /// otherwise it returns None. fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>>; } impl Handler for Arc<dyn Handler> { fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>> { (**self).handles(request) } } impl TestServer { /// return the scheme of the TestServer fn scheme(&self) -> &'static str { if self.use_https { "https" } else { "http" } } /// Returns the URL that can be used to connect to this repository from this device. pub fn local_url(&self) -> String { format!("{}://localhost:{}", self.scheme(), self.addr.port()) } /// Returns the URL for the given path that can be used to connect to this repository from this /// device. pub fn local_url_for_path(&self, path: &str) -> String { let path = path.trim_start_matches('/'); format!("{}://localhost:{}/{}", self.scheme(), self.addr.port(), path) } /// Gracefully signal the server to stop and returns a future that resolves when it terminates. pub fn stop(self) -> impl Future<Output = ()> { self.stop.send(()).expect("remote end to still be open"); self.task } /// Internal helper which iterates over all Handlers until it finds one that will respond to the /// request. It then returns that response. If not response is found, it returns 404 NOT_FOUND. async fn handle_request( handlers: Arc<Vec<Arc<dyn Handler>>>, req: Request<Body>, ) -> Response<Body> { let response = handlers.iter().find_map(|h| h.handles(&req)); match response { Some(response) => response.await, None => Response::builder().status(StatusCode::NOT_FOUND).body(Body::empty()).unwrap(), } }
/// A builder to construct a `TestServer`. #[derive(Default)] pub struct TestServerBuilder { handlers: Vec<Arc<dyn Handler>>, https_certs: Option<(Vec<rustls::Certificate>, rustls::PrivateKey)>, } impl TestServerBuilder { /// Create a new TestServerBuilder pub fn new() -> Self { Self::default() } /// Serve over TLS, using a server certificate rooted the provided certs pub fn use_https(mut self, cert_chain: &[u8], private_key: &[u8]) -> Self { let cert_chain = parse_cert_chain(cert_chain); let private_key = parse_private_key(private_key); self.https_certs = Some((cert_chain, private_key)); self } /// Add a Handler which implements the server's behavior. These are given the ability to /// handle a request in the order in which they are added to the `TestServerBuilder`. pub fn handler(mut self, handler: impl Handler +'static) -> Self { self.handlers.push(Arc::new(handler)); self } /// Spawn the server on the current executor, returning a handle to manage the server. pub async fn start(self) -> TestServer { let (mut listener, addr) = { let addr = SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), 0); let listener = bind_listener(&addr).await; let local_addr = listener.local_addr().unwrap(); (listener, local_addr) }; let (stop, rx_stop) = futures::channel::oneshot::channel(); let (tls_acceptor, use_https) = if let Some((cert_chain, private_key)) = self.https_certs { // build a server configuration using a test CA and cert chain let mut tls_config = rustls::ServerConfig::new(rustls::NoClientAuth::new()); tls_config.set_single_cert(cert_chain, private_key).unwrap(); let tls_acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(tls_config)); (Some(tls_acceptor), true) } else { (None, false) }; let task = fasync::Task::spawn(async move { let listener = accept_stream(&mut listener); let listener = listener .map_err(Error::from) .map_ok(|conn| fuchsia_hyper::TcpStream { stream: conn }); let connections = if let Some(tls_acceptor) = tls_acceptor { // wrap incoming tcp streams listener .and_then(move |conn| { tls_acceptor.accept(conn).map(|res| match res { Ok(conn) => { Ok(Pin::new(Box::new(conn)) as Pin<Box<dyn AsyncReadWrite>>) } Err(e) => Err(Error::from(e)), }) }) .boxed() // connections } else { listener .map_ok(|conn| Pin::new(Box::new(conn)) as Pin<Box<dyn AsyncReadWrite>>) .boxed() // connections }; // This is the root Arc<Vec<Arc<dyn Handler>>>. let handlers = Arc::new(self.handlers); let make_svc = make_service_fn(move |_socket| { // Each connection to the server receives a separate service_fn instance, and so // needs it's own copy of the handlers, this is a factory of sorts. let handlers = Arc::clone(&handlers); async move { Ok::<_, Infallible>(service_fn(move |req| { // Each request made by a connection is serviced by the service_fn created from // this scope, which is why there is another cloning of the Arc of Handlers. let method = req.method().to_owned(); let path = req.uri().path().to_owned(); TestServer::handle_request(Arc::clone(&handlers), req) .inspect(move |x| { println!( "{} [test http] {} {} => {}", Utc::now().format("%T.%6f"), method, path, x.status() ) }) .map(Ok::<_, Infallible>) })) } }); Server::builder(from_stream(connections)) .executor(fuchsia_hyper::Executor) .serve(make_svc) .with_graceful_shutdown( rx_stop.map(|res| res.unwrap_or_else(|futures::channel::oneshot::Canceled| ())), ) .unwrap_or_else(|e| panic!("error serving repo over http: {}", e)) .await; }); TestServer { stop, addr, use_https, task } } } #[cfg(target_os = "fuchsia")] async fn bind_listener(addr: &SocketAddr) -> fuchsia_async::net::TcpListener { fuchsia_async::net::TcpListener::bind(addr).unwrap() } #[cfg(not(target_os = "fuchsia"))] async fn bind_listener(&addr: &SocketAddr) -> async_net::TcpListener { async_net::TcpListener::bind(addr).await.unwrap() } #[cfg(target_os = "fuchsia")] fn accept_stream<'a>( listener: &'a mut fuchsia_async::net::TcpListener, ) -> impl Stream<Item = std::io::Result<fuchsia_async::net::TcpStream>> + 'a { use std::task::{Context, Poll}; #[pin_project::pin_project] struct AcceptStream<'a> { #[pin] listener: &'a mut fuchsia_async::net::TcpListener, } impl<'a> Stream for AcceptStream<'a> { type Item = std::io::Result<fuchsia_async::net::TcpStream>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let mut this = self.project(); match this.listener.async_accept(cx) { Poll::Ready(Ok((conn, _addr))) => Poll::Ready(Some(Ok(conn))), Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))), Poll::Pending => Poll::Pending, } } } AcceptStream { listener } } #[cfg(not(target_os = "fuchsia"))] fn accept_stream<'a>( listener: &'a mut async_net::TcpListener, ) -> impl Stream<Item = std::io::Result<async_net::TcpStream>> + 'a { listener.incoming() } fn parse_cert_chain(mut bytes: &[u8]) -> Vec<rustls::Certificate> { rustls::internal::pemfile::certs(&mut bytes).expect("certs to parse") } fn parse_private_key(mut bytes: &[u8]) -> rustls::PrivateKey { let keys = rustls::internal::pemfile::rsa_private_keys(&mut bytes).expect("private keys to parse"); assert_eq!(keys.len(), 1, "expecting a single private key"); keys.into_iter().next().unwrap() } trait AsyncReadWrite: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send {} impl<T> AsyncReadWrite for T where T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send {} // These are a set of useful functions when writing tests. /// Create a GET request for a given url, which can be used with any hyper client. pub fn make_get(url: impl AsRef<str>) -> Result<Request<Body>, Error> { Request::get(url.as_ref()).body(Body::empty()).map_err(Error::from) } /// Perform an HTTP GET for the given url, returning the result. pub async fn get(url: impl AsRef<str>) -> Result<Response<Body>, Error> { let request = make_get(url)?; let client = fuchsia_hyper::new_client(); let response = client.request(request).await?; Ok(response) } /// Collect a Response into a single Vec of bytes. pub async fn body_as_bytes(response: Response<Body>) -> Result<Vec<u8>, Error> { let bytes = response .into_body() .try_fold(Vec::new(), |mut vec, b| async move { vec.extend(b); Ok(vec) }) .await?; Ok(bytes) } /// Collect a Response's Body and convert the body to a tring. pub async fn body_as_string(response: Response<Body>) -> Result<String, Error> { let bytes = body_as_bytes(response).await?; let string = String::from_utf8(bytes)?; Ok(string) } /// Get a url and return the body of the response as a string. pub async fn get_body_as_string(url: impl AsRef<str>) -> Result<String, Error> { let response = get(url).await?; body_as_string(response).await } #[cfg(test)] mod tests { use super::*; use crate::{fault_injection::*, handler::*}; use anyhow::anyhow; use fasync::TimeoutExt; #[fuchsia_async::run_singlethreaded(test)] async fn test_start_stop() { let server = TestServer::builder().start().await; server.stop().await; } #[fuchsia_async::run_singlethreaded(test)] async fn test_empty_server_404s() { let server = TestServer::builder().start().await; let result = get(server.local_url()).await; assert_eq!(result.unwrap().status(), StatusCode::NOT_FOUND); } #[fuchsia_async::run_singlethreaded(test)] async fn test_shared_handler() { let shared: Arc<dyn Handler> = Arc::new(StaticResponse::ok_body("shared")); let server = TestServer::builder() .handler(ForPath::new("/a", Arc::clone(&shared))) .handler(shared) .start() .await; assert_eq!(get_body_as_string(server.local_url_for_path("/a")).await.unwrap(), "shared"); assert_eq!(get_body_as_string(server.local_url_for_path("/foo")).await.unwrap(), "shared"); } #[fuchsia_async::run_singlethreaded(test)] async fn test_simple_responder() { let server = TestServer::builder().handler(StaticResponse::ok_body("some data")).start().await; assert_eq!( get_body_as_string(server.local_url_for_path("ignored")).await.unwrap(), "some data" ); } #[fuchsia_async::run_singlethreaded(test)] async fn test_simple_path() { let server = TestServer::builder() .handler(ForPath::new("/some/path", StaticResponse::ok_body("some data"))) .start() .await; assert_eq!( get_body_as_string(server.local_url_for_path("/some/path")).await.unwrap(), "some data" ); } #[fuchsia_async::run_singlethreaded(test)] async fn test_simple_path_doesnt_respond_to_wrong_path() { let server = TestServer::builder() .handler(ForPath::new("/some/path", StaticResponse::ok_body("some data"))) .start() .await; // make sure a non-matching path fails let result = get(server.local_url_for_path("/other/path")).await; assert_eq!(result.unwrap().status(), StatusCode::NOT_FOUND); } #[fuchsia_async::run_singlethreaded(test)] async fn test_hang() { let server = TestServer::builder().handler(Hang).start().await; let result = get(server.local_url_for_path("ignored")) .on_timeout(std::time::Duration::from_secs(1), || Err(anyhow!("timed out"))) .await; assert_eq!(result.unwrap_err().to_string(), Error::msg("timed out").to_string()); } #[fuchsia_async::run_singlethreaded(test)] async fn test_hang_body() { let server = TestServer::builder().handler(HangBody::content_length(500)).start().await; let result = get_body_as_string(server.local_url_for_path("ignored")) .on_timeout(std::time::Duration::from_secs(1), || Err(anyhow!("timed out"))) .await; assert_eq!(result.unwrap_err().to_string(), Error::msg("timed out").to_string()); } }
/// Create a Builder pub fn builder() -> TestServerBuilder { TestServerBuilder::new() } }
random_line_split
spline.rs
use ordered_float::NotNan; use crate::hitobject::SliderSplineKind; use crate::math::{Math, Point}; /// Represents a spline, a set of points that represents the actual shape of a slider, generated /// from the control points. #[derive(Clone, Debug)] pub struct Spline { /// The actual points pub spline_points: Vec<P>, /// The cumulative lengths over the points. The indices correspond to the spline_points field pub cumulative_lengths: Vec<NotNan<f64>>, } impl Spline { /// Create a new spline from the control points of a slider. /// /// Pixel length gives the length in osu!pixels that the slider should be. If it's not given, /// the full slider will be rendered. pub fn from_control( kind: SliderSplineKind, control_points: &[Point<i32>], pixel_length: Option<f64>, ) -> Self { // no matter what, if there's 2 control points, it's linear let mut kind = kind; let mut control_points = control_points.to_vec(); if control_points.len() == 2 { kind = SliderSplineKind::Linear; } if control_points.len() == 3 && Math::is_line( control_points[0].to_float::<f64>().unwrap(), control_points[1].to_float::<f64>().unwrap(), control_points[2].to_float::<f64>().unwrap(), ) { kind = SliderSplineKind::Linear; control_points.remove(1); } let points = control_points .iter() .map(|p| Point::new(p.x as f64, p.y as f64)) .collect::<Vec<_>>(); let spline_points = match kind { SliderSplineKind::Linear => { let start = points[0]; let end = if let Some(pixel_length) = pixel_length { Math::point_on_line(points[0], points[1], pixel_length) } else { points[1] }; vec![start, end] } SliderSplineKind::Perfect => { let (p1, p2, p3) = (points[0], points[1], points[2]); let (center, radius) = Math::circumcircle(p1, p2, p3); // find the t-values of the start and end of the slider let t0 = (center.y - p1.y).atan2(p1.x - center.x); let mut mid = (center.y - p2.y).atan2(p2.x - center.x); let mut t1 = (center.y - p3.y).atan2(p3.x - center.x); // make sure t0 is less than t1 while mid < t0 { mid += std::f64::consts::TAU; } while t1 < t0 { t1 += std::f64::consts::TAU; } if mid > t1 { t1 -= std::f64::consts::TAU; } let diff = (t1 - t0).abs(); let pixel_length = pixel_length.unwrap_or(radius * diff); // circumference is 2 * pi * r, slider length over circumference is length/(2 * pi * r) let direction_unit = (t1 - t0) / (t1 - t0).abs(); let new_t1 = t0 + direction_unit * (pixel_length / radius); let mut t = t0; let mut c = Vec::new(); loop { if!((new_t1 >= t0 && t < new_t1) || (new_t1 < t0 && t > new_t1)) { break; } let rel = Point::new(t.cos() * radius, -t.sin() * radius); c.push(center + rel); t += (new_t1 - t0) / pixel_length; } c } SliderSplineKind::Bezier => { let mut output = Vec::new(); let mut last_index = 0; let mut i = 0; while i < points.len() { let multipart_segment = i < points.len() - 2 && (points[i] == points[i + 1]); if multipart_segment || i == points.len() - 1 { let sub = &points[last_index..i + 1]; if sub.len() == 2 { output.push(points[0]); output.push(points[1]); } else { create_singlebezier(&mut output, sub); } if multipart_segment { i += 1; } last_index = i; } i += 1; } output } _ => todo!(), }; let mut cumulative_lengths = Vec::with_capacity(spline_points.len()); let mut curr = 0.0; // using NotNan here because these need to be binary-searched over // and f64 isn't Ord cumulative_lengths.push(NotNan::new(curr).unwrap()); for points in spline_points.windows(2) { let dist = points[0].distance(points[1]); curr += dist; cumulative_lengths.push(NotNan::new(curr).unwrap()); } Spline { spline_points, cumulative_lengths, } } /// Truncate the length of the spline irreversibly pub fn truncate(&mut self, to_length: f64) { debug!("truncating to {} pixels", to_length); let mut limit_idx = None; for (i, cumul_length) in self.cumulative_lengths.iter().enumerate() { if cumul_length.into_inner() > to_length { limit_idx = Some(i); break; } } let limit_idx = match limit_idx { Some(v) if v > 0 => v, _ => return, }; let prev_idx = limit_idx - 1; let a = self.spline_points[prev_idx]; let b = self.spline_points[limit_idx]; let a_len = self.cumulative_lengths[prev_idx]; debug!("a={:?} (a_len={}) b={:?}", a, b, a_len); let remain = to_length - a_len.into_inner(); let mid = Math::point_on_line(a, b, remain); debug!("remain={:?} mid={:?}", remain, mid); self.spline_points[limit_idx] = mid; self.cumulative_lengths[limit_idx] = NotNan::new(to_length).unwrap(); debug!("spline_points[{}] = {:?}", limit_idx, mid); debug!("cumulative_lengths[{}] = {:?}", limit_idx, to_length); self.spline_points.truncate(limit_idx + 1); self.cumulative_lengths.truncate(limit_idx + 1); debug!("truncated to len {}", limit_idx + 1); } /// Return the pixel length of this spline pub fn pixel_length(&self) -> f64 { self.cumulative_lengths.last().unwrap().into_inner() } /// Return the endpoint of this spline pub fn end_point(&self) -> P { self.spline_points.last().cloned().unwrap() } /// Calculate the angle at the given length on the slider fn angle_at_length(&self, length: f64) -> P { let _length_notnan = NotNan::new(length).unwrap(); // match self.cumulative_lengths.binary_search(&length_notnan) { // Ok(_) => {} // Err(_) => {} // } todo!() } /// Calculate the point at which the slider ball would be after it has traveled a distance of /// `length` into the slider. pub fn point_at_length(&self, length: f64) -> P { let length_notnan = NotNan::new(length).unwrap(); match self.cumulative_lengths.binary_search(&length_notnan) { Ok(idx) => self.spline_points[idx], Err(idx) => { let n = self.spline_points.len(); if idx == 0 && self.spline_points.len() > 2 { return self.spline_points[0]; } else if idx == n { return self.spline_points[n - 1]; }
self.cumulative_lengths[idx].into_inner(), ); let proportion = (length - len1) / (len2 - len1); let (p1, p2) = (self.spline_points[idx - 1], self.spline_points[idx]); (p2 - p1) * P::new(proportion, proportion) + p1 } } } } type P = Point<f64>; fn subdivide(control_points: &[P], l: &mut [P], r: &mut [P], midpoints_buf: &mut [P]) { let count = control_points.len(); midpoints_buf.copy_from_slice(control_points); for i in 0..count { l[i] = midpoints_buf[0]; r[count - i - 1] = midpoints_buf[count - i - 1]; for j in 0..count - i - 1 { midpoints_buf[j] = (midpoints_buf[j] + midpoints_buf[j + 1]) / P::new(2.0, 2.0); } } } fn approximate( control_points: &[P], output: &mut Vec<P>, l_buf: &mut [P], r_buf: &mut [P], midpoints_buf: &mut [P], ) { let count = control_points.len(); subdivide(&control_points, l_buf, r_buf, midpoints_buf); l_buf[count..(count * 2) - 1].clone_from_slice(&r_buf[1..count]); output.push(control_points[0]); for i in 1..count - 1 { let index = 2 * i; let p = (l_buf[index] * P::new(2.0, 2.0) + l_buf[index - 1] + l_buf[index + 1]) * P::new(0.25, 0.25); output.push(p); } } fn is_flat_enough(control_points: &[P], tolerance_sq: f64) -> bool { for i in 1..control_points.len() - 1 { if (control_points[i - 1] - control_points[i] * P::new(2.0, 2.0) + control_points[i + 1]) .length_squared() > tolerance_sq { return false; } } true } fn create_singlebezier(output: &mut Vec<P>, control_points: &[P]) { let count = control_points.len(); const TOLERANCE: f64 = 0.25; const TOLERANCE_SQ: f64 = TOLERANCE * TOLERANCE; if count == 0 { return; } let mut to_flatten: Vec<Vec<P>> = Vec::new(); let mut free_buffers: Vec<Vec<P>> = Vec::new(); let last_control_point = control_points[count - 1]; to_flatten.push(control_points.to_vec()); let mut left_child = vec![P::new(0.0, 0.0); count * 2 - 1]; let mut l_buf = vec![P::new(0.0, 0.0); count * 2 - 1]; let mut r_buf = vec![P::new(0.0, 0.0); count]; let mut midpoints_buf = vec![P::new(0.0, 0.0); count]; while!to_flatten.is_empty() { let mut parent = to_flatten.pop().unwrap(); if is_flat_enough(&parent, TOLERANCE_SQ) { approximate( &parent, output, &mut l_buf[..count * 2 - 1], &mut r_buf[..count], &mut midpoints_buf[..count], ); free_buffers.push(parent); continue; } let mut right_child = free_buffers .pop() .unwrap_or_else(|| vec![P::new(0.0, 0.0); count]); subdivide( &parent, &mut left_child, &mut right_child, &mut midpoints_buf[..count], ); // We re-use the buffer of the parent for one of the children, so that we save one allocation per iteration. parent[..count].clone_from_slice(&left_child[..count]); to_flatten.push(right_child); to_flatten.push(parent); } output.push(last_control_point); }
let (len1, len2) = ( self.cumulative_lengths[idx - 1].into_inner(),
random_line_split
spline.rs
use ordered_float::NotNan; use crate::hitobject::SliderSplineKind; use crate::math::{Math, Point}; /// Represents a spline, a set of points that represents the actual shape of a slider, generated /// from the control points. #[derive(Clone, Debug)] pub struct Spline { /// The actual points pub spline_points: Vec<P>, /// The cumulative lengths over the points. The indices correspond to the spline_points field pub cumulative_lengths: Vec<NotNan<f64>>, } impl Spline { /// Create a new spline from the control points of a slider. /// /// Pixel length gives the length in osu!pixels that the slider should be. If it's not given, /// the full slider will be rendered. pub fn from_control( kind: SliderSplineKind, control_points: &[Point<i32>], pixel_length: Option<f64>, ) -> Self { // no matter what, if there's 2 control points, it's linear let mut kind = kind; let mut control_points = control_points.to_vec(); if control_points.len() == 2 { kind = SliderSplineKind::Linear; } if control_points.len() == 3 && Math::is_line( control_points[0].to_float::<f64>().unwrap(), control_points[1].to_float::<f64>().unwrap(), control_points[2].to_float::<f64>().unwrap(), ) { kind = SliderSplineKind::Linear; control_points.remove(1); } let points = control_points .iter() .map(|p| Point::new(p.x as f64, p.y as f64)) .collect::<Vec<_>>(); let spline_points = match kind { SliderSplineKind::Linear => { let start = points[0]; let end = if let Some(pixel_length) = pixel_length { Math::point_on_line(points[0], points[1], pixel_length) } else { points[1] }; vec![start, end] } SliderSplineKind::Perfect => { let (p1, p2, p3) = (points[0], points[1], points[2]); let (center, radius) = Math::circumcircle(p1, p2, p3); // find the t-values of the start and end of the slider let t0 = (center.y - p1.y).atan2(p1.x - center.x); let mut mid = (center.y - p2.y).atan2(p2.x - center.x); let mut t1 = (center.y - p3.y).atan2(p3.x - center.x); // make sure t0 is less than t1 while mid < t0 { mid += std::f64::consts::TAU; } while t1 < t0 { t1 += std::f64::consts::TAU; } if mid > t1 { t1 -= std::f64::consts::TAU; } let diff = (t1 - t0).abs(); let pixel_length = pixel_length.unwrap_or(radius * diff); // circumference is 2 * pi * r, slider length over circumference is length/(2 * pi * r) let direction_unit = (t1 - t0) / (t1 - t0).abs(); let new_t1 = t0 + direction_unit * (pixel_length / radius); let mut t = t0; let mut c = Vec::new(); loop { if!((new_t1 >= t0 && t < new_t1) || (new_t1 < t0 && t > new_t1)) { break; } let rel = Point::new(t.cos() * radius, -t.sin() * radius); c.push(center + rel); t += (new_t1 - t0) / pixel_length; } c } SliderSplineKind::Bezier => { let mut output = Vec::new(); let mut last_index = 0; let mut i = 0; while i < points.len() { let multipart_segment = i < points.len() - 2 && (points[i] == points[i + 1]); if multipart_segment || i == points.len() - 1 { let sub = &points[last_index..i + 1]; if sub.len() == 2 { output.push(points[0]); output.push(points[1]); } else { create_singlebezier(&mut output, sub); } if multipart_segment { i += 1; } last_index = i; } i += 1; } output } _ => todo!(), }; let mut cumulative_lengths = Vec::with_capacity(spline_points.len()); let mut curr = 0.0; // using NotNan here because these need to be binary-searched over // and f64 isn't Ord cumulative_lengths.push(NotNan::new(curr).unwrap()); for points in spline_points.windows(2) { let dist = points[0].distance(points[1]); curr += dist; cumulative_lengths.push(NotNan::new(curr).unwrap()); } Spline { spline_points, cumulative_lengths, } } /// Truncate the length of the spline irreversibly pub fn truncate(&mut self, to_length: f64) { debug!("truncating to {} pixels", to_length); let mut limit_idx = None; for (i, cumul_length) in self.cumulative_lengths.iter().enumerate() { if cumul_length.into_inner() > to_length { limit_idx = Some(i); break; } } let limit_idx = match limit_idx { Some(v) if v > 0 => v, _ => return, }; let prev_idx = limit_idx - 1; let a = self.spline_points[prev_idx]; let b = self.spline_points[limit_idx]; let a_len = self.cumulative_lengths[prev_idx]; debug!("a={:?} (a_len={}) b={:?}", a, b, a_len); let remain = to_length - a_len.into_inner(); let mid = Math::point_on_line(a, b, remain); debug!("remain={:?} mid={:?}", remain, mid); self.spline_points[limit_idx] = mid; self.cumulative_lengths[limit_idx] = NotNan::new(to_length).unwrap(); debug!("spline_points[{}] = {:?}", limit_idx, mid); debug!("cumulative_lengths[{}] = {:?}", limit_idx, to_length); self.spline_points.truncate(limit_idx + 1); self.cumulative_lengths.truncate(limit_idx + 1); debug!("truncated to len {}", limit_idx + 1); } /// Return the pixel length of this spline pub fn pixel_length(&self) -> f64 { self.cumulative_lengths.last().unwrap().into_inner() } /// Return the endpoint of this spline pub fn end_point(&self) -> P { self.spline_points.last().cloned().unwrap() } /// Calculate the angle at the given length on the slider fn angle_at_length(&self, length: f64) -> P { let _length_notnan = NotNan::new(length).unwrap(); // match self.cumulative_lengths.binary_search(&length_notnan) { // Ok(_) => {} // Err(_) => {} // } todo!() } /// Calculate the point at which the slider ball would be after it has traveled a distance of /// `length` into the slider. pub fn point_at_length(&self, length: f64) -> P { let length_notnan = NotNan::new(length).unwrap(); match self.cumulative_lengths.binary_search(&length_notnan) { Ok(idx) => self.spline_points[idx], Err(idx) => { let n = self.spline_points.len(); if idx == 0 && self.spline_points.len() > 2 { return self.spline_points[0]; } else if idx == n { return self.spline_points[n - 1]; } let (len1, len2) = ( self.cumulative_lengths[idx - 1].into_inner(), self.cumulative_lengths[idx].into_inner(), ); let proportion = (length - len1) / (len2 - len1); let (p1, p2) = (self.spline_points[idx - 1], self.spline_points[idx]); (p2 - p1) * P::new(proportion, proportion) + p1 } } } } type P = Point<f64>; fn
(control_points: &[P], l: &mut [P], r: &mut [P], midpoints_buf: &mut [P]) { let count = control_points.len(); midpoints_buf.copy_from_slice(control_points); for i in 0..count { l[i] = midpoints_buf[0]; r[count - i - 1] = midpoints_buf[count - i - 1]; for j in 0..count - i - 1 { midpoints_buf[j] = (midpoints_buf[j] + midpoints_buf[j + 1]) / P::new(2.0, 2.0); } } } fn approximate( control_points: &[P], output: &mut Vec<P>, l_buf: &mut [P], r_buf: &mut [P], midpoints_buf: &mut [P], ) { let count = control_points.len(); subdivide(&control_points, l_buf, r_buf, midpoints_buf); l_buf[count..(count * 2) - 1].clone_from_slice(&r_buf[1..count]); output.push(control_points[0]); for i in 1..count - 1 { let index = 2 * i; let p = (l_buf[index] * P::new(2.0, 2.0) + l_buf[index - 1] + l_buf[index + 1]) * P::new(0.25, 0.25); output.push(p); } } fn is_flat_enough(control_points: &[P], tolerance_sq: f64) -> bool { for i in 1..control_points.len() - 1 { if (control_points[i - 1] - control_points[i] * P::new(2.0, 2.0) + control_points[i + 1]) .length_squared() > tolerance_sq { return false; } } true } fn create_singlebezier(output: &mut Vec<P>, control_points: &[P]) { let count = control_points.len(); const TOLERANCE: f64 = 0.25; const TOLERANCE_SQ: f64 = TOLERANCE * TOLERANCE; if count == 0 { return; } let mut to_flatten: Vec<Vec<P>> = Vec::new(); let mut free_buffers: Vec<Vec<P>> = Vec::new(); let last_control_point = control_points[count - 1]; to_flatten.push(control_points.to_vec()); let mut left_child = vec![P::new(0.0, 0.0); count * 2 - 1]; let mut l_buf = vec![P::new(0.0, 0.0); count * 2 - 1]; let mut r_buf = vec![P::new(0.0, 0.0); count]; let mut midpoints_buf = vec![P::new(0.0, 0.0); count]; while!to_flatten.is_empty() { let mut parent = to_flatten.pop().unwrap(); if is_flat_enough(&parent, TOLERANCE_SQ) { approximate( &parent, output, &mut l_buf[..count * 2 - 1], &mut r_buf[..count], &mut midpoints_buf[..count], ); free_buffers.push(parent); continue; } let mut right_child = free_buffers .pop() .unwrap_or_else(|| vec![P::new(0.0, 0.0); count]); subdivide( &parent, &mut left_child, &mut right_child, &mut midpoints_buf[..count], ); // We re-use the buffer of the parent for one of the children, so that we save one allocation per iteration. parent[..count].clone_from_slice(&left_child[..count]); to_flatten.push(right_child); to_flatten.push(parent); } output.push(last_control_point); }
subdivide
identifier_name
spline.rs
use ordered_float::NotNan; use crate::hitobject::SliderSplineKind; use crate::math::{Math, Point}; /// Represents a spline, a set of points that represents the actual shape of a slider, generated /// from the control points. #[derive(Clone, Debug)] pub struct Spline { /// The actual points pub spline_points: Vec<P>, /// The cumulative lengths over the points. The indices correspond to the spline_points field pub cumulative_lengths: Vec<NotNan<f64>>, } impl Spline { /// Create a new spline from the control points of a slider. /// /// Pixel length gives the length in osu!pixels that the slider should be. If it's not given, /// the full slider will be rendered. pub fn from_control( kind: SliderSplineKind, control_points: &[Point<i32>], pixel_length: Option<f64>, ) -> Self { // no matter what, if there's 2 control points, it's linear let mut kind = kind; let mut control_points = control_points.to_vec(); if control_points.len() == 2 { kind = SliderSplineKind::Linear; } if control_points.len() == 3 && Math::is_line( control_points[0].to_float::<f64>().unwrap(), control_points[1].to_float::<f64>().unwrap(), control_points[2].to_float::<f64>().unwrap(), ) { kind = SliderSplineKind::Linear; control_points.remove(1); } let points = control_points .iter() .map(|p| Point::new(p.x as f64, p.y as f64)) .collect::<Vec<_>>(); let spline_points = match kind { SliderSplineKind::Linear => { let start = points[0]; let end = if let Some(pixel_length) = pixel_length { Math::point_on_line(points[0], points[1], pixel_length) } else { points[1] }; vec![start, end] } SliderSplineKind::Perfect => { let (p1, p2, p3) = (points[0], points[1], points[2]); let (center, radius) = Math::circumcircle(p1, p2, p3); // find the t-values of the start and end of the slider let t0 = (center.y - p1.y).atan2(p1.x - center.x); let mut mid = (center.y - p2.y).atan2(p2.x - center.x); let mut t1 = (center.y - p3.y).atan2(p3.x - center.x); // make sure t0 is less than t1 while mid < t0 { mid += std::f64::consts::TAU; } while t1 < t0 { t1 += std::f64::consts::TAU; } if mid > t1 { t1 -= std::f64::consts::TAU; } let diff = (t1 - t0).abs(); let pixel_length = pixel_length.unwrap_or(radius * diff); // circumference is 2 * pi * r, slider length over circumference is length/(2 * pi * r) let direction_unit = (t1 - t0) / (t1 - t0).abs(); let new_t1 = t0 + direction_unit * (pixel_length / radius); let mut t = t0; let mut c = Vec::new(); loop { if!((new_t1 >= t0 && t < new_t1) || (new_t1 < t0 && t > new_t1)) { break; } let rel = Point::new(t.cos() * radius, -t.sin() * radius); c.push(center + rel); t += (new_t1 - t0) / pixel_length; } c } SliderSplineKind::Bezier => { let mut output = Vec::new(); let mut last_index = 0; let mut i = 0; while i < points.len() { let multipart_segment = i < points.len() - 2 && (points[i] == points[i + 1]); if multipart_segment || i == points.len() - 1 { let sub = &points[last_index..i + 1]; if sub.len() == 2 { output.push(points[0]); output.push(points[1]); } else { create_singlebezier(&mut output, sub); } if multipart_segment { i += 1; } last_index = i; } i += 1; } output } _ => todo!(), }; let mut cumulative_lengths = Vec::with_capacity(spline_points.len()); let mut curr = 0.0; // using NotNan here because these need to be binary-searched over // and f64 isn't Ord cumulative_lengths.push(NotNan::new(curr).unwrap()); for points in spline_points.windows(2) { let dist = points[0].distance(points[1]); curr += dist; cumulative_lengths.push(NotNan::new(curr).unwrap()); } Spline { spline_points, cumulative_lengths, } } /// Truncate the length of the spline irreversibly pub fn truncate(&mut self, to_length: f64) { debug!("truncating to {} pixels", to_length); let mut limit_idx = None; for (i, cumul_length) in self.cumulative_lengths.iter().enumerate() { if cumul_length.into_inner() > to_length { limit_idx = Some(i); break; } } let limit_idx = match limit_idx { Some(v) if v > 0 => v, _ => return, }; let prev_idx = limit_idx - 1; let a = self.spline_points[prev_idx]; let b = self.spline_points[limit_idx]; let a_len = self.cumulative_lengths[prev_idx]; debug!("a={:?} (a_len={}) b={:?}", a, b, a_len); let remain = to_length - a_len.into_inner(); let mid = Math::point_on_line(a, b, remain); debug!("remain={:?} mid={:?}", remain, mid); self.spline_points[limit_idx] = mid; self.cumulative_lengths[limit_idx] = NotNan::new(to_length).unwrap(); debug!("spline_points[{}] = {:?}", limit_idx, mid); debug!("cumulative_lengths[{}] = {:?}", limit_idx, to_length); self.spline_points.truncate(limit_idx + 1); self.cumulative_lengths.truncate(limit_idx + 1); debug!("truncated to len {}", limit_idx + 1); } /// Return the pixel length of this spline pub fn pixel_length(&self) -> f64 { self.cumulative_lengths.last().unwrap().into_inner() } /// Return the endpoint of this spline pub fn end_point(&self) -> P
/// Calculate the angle at the given length on the slider fn angle_at_length(&self, length: f64) -> P { let _length_notnan = NotNan::new(length).unwrap(); // match self.cumulative_lengths.binary_search(&length_notnan) { // Ok(_) => {} // Err(_) => {} // } todo!() } /// Calculate the point at which the slider ball would be after it has traveled a distance of /// `length` into the slider. pub fn point_at_length(&self, length: f64) -> P { let length_notnan = NotNan::new(length).unwrap(); match self.cumulative_lengths.binary_search(&length_notnan) { Ok(idx) => self.spline_points[idx], Err(idx) => { let n = self.spline_points.len(); if idx == 0 && self.spline_points.len() > 2 { return self.spline_points[0]; } else if idx == n { return self.spline_points[n - 1]; } let (len1, len2) = ( self.cumulative_lengths[idx - 1].into_inner(), self.cumulative_lengths[idx].into_inner(), ); let proportion = (length - len1) / (len2 - len1); let (p1, p2) = (self.spline_points[idx - 1], self.spline_points[idx]); (p2 - p1) * P::new(proportion, proportion) + p1 } } } } type P = Point<f64>; fn subdivide(control_points: &[P], l: &mut [P], r: &mut [P], midpoints_buf: &mut [P]) { let count = control_points.len(); midpoints_buf.copy_from_slice(control_points); for i in 0..count { l[i] = midpoints_buf[0]; r[count - i - 1] = midpoints_buf[count - i - 1]; for j in 0..count - i - 1 { midpoints_buf[j] = (midpoints_buf[j] + midpoints_buf[j + 1]) / P::new(2.0, 2.0); } } } fn approximate( control_points: &[P], output: &mut Vec<P>, l_buf: &mut [P], r_buf: &mut [P], midpoints_buf: &mut [P], ) { let count = control_points.len(); subdivide(&control_points, l_buf, r_buf, midpoints_buf); l_buf[count..(count * 2) - 1].clone_from_slice(&r_buf[1..count]); output.push(control_points[0]); for i in 1..count - 1 { let index = 2 * i; let p = (l_buf[index] * P::new(2.0, 2.0) + l_buf[index - 1] + l_buf[index + 1]) * P::new(0.25, 0.25); output.push(p); } } fn is_flat_enough(control_points: &[P], tolerance_sq: f64) -> bool { for i in 1..control_points.len() - 1 { if (control_points[i - 1] - control_points[i] * P::new(2.0, 2.0) + control_points[i + 1]) .length_squared() > tolerance_sq { return false; } } true } fn create_singlebezier(output: &mut Vec<P>, control_points: &[P]) { let count = control_points.len(); const TOLERANCE: f64 = 0.25; const TOLERANCE_SQ: f64 = TOLERANCE * TOLERANCE; if count == 0 { return; } let mut to_flatten: Vec<Vec<P>> = Vec::new(); let mut free_buffers: Vec<Vec<P>> = Vec::new(); let last_control_point = control_points[count - 1]; to_flatten.push(control_points.to_vec()); let mut left_child = vec![P::new(0.0, 0.0); count * 2 - 1]; let mut l_buf = vec![P::new(0.0, 0.0); count * 2 - 1]; let mut r_buf = vec![P::new(0.0, 0.0); count]; let mut midpoints_buf = vec![P::new(0.0, 0.0); count]; while!to_flatten.is_empty() { let mut parent = to_flatten.pop().unwrap(); if is_flat_enough(&parent, TOLERANCE_SQ) { approximate( &parent, output, &mut l_buf[..count * 2 - 1], &mut r_buf[..count], &mut midpoints_buf[..count], ); free_buffers.push(parent); continue; } let mut right_child = free_buffers .pop() .unwrap_or_else(|| vec![P::new(0.0, 0.0); count]); subdivide( &parent, &mut left_child, &mut right_child, &mut midpoints_buf[..count], ); // We re-use the buffer of the parent for one of the children, so that we save one allocation per iteration. parent[..count].clone_from_slice(&left_child[..count]); to_flatten.push(right_child); to_flatten.push(parent); } output.push(last_control_point); }
{ self.spline_points.last().cloned().unwrap() }
identifier_body
spline.rs
use ordered_float::NotNan; use crate::hitobject::SliderSplineKind; use crate::math::{Math, Point}; /// Represents a spline, a set of points that represents the actual shape of a slider, generated /// from the control points. #[derive(Clone, Debug)] pub struct Spline { /// The actual points pub spline_points: Vec<P>, /// The cumulative lengths over the points. The indices correspond to the spline_points field pub cumulative_lengths: Vec<NotNan<f64>>, } impl Spline { /// Create a new spline from the control points of a slider. /// /// Pixel length gives the length in osu!pixels that the slider should be. If it's not given, /// the full slider will be rendered. pub fn from_control( kind: SliderSplineKind, control_points: &[Point<i32>], pixel_length: Option<f64>, ) -> Self { // no matter what, if there's 2 control points, it's linear let mut kind = kind; let mut control_points = control_points.to_vec(); if control_points.len() == 2 { kind = SliderSplineKind::Linear; } if control_points.len() == 3 && Math::is_line( control_points[0].to_float::<f64>().unwrap(), control_points[1].to_float::<f64>().unwrap(), control_points[2].to_float::<f64>().unwrap(), ) { kind = SliderSplineKind::Linear; control_points.remove(1); } let points = control_points .iter() .map(|p| Point::new(p.x as f64, p.y as f64)) .collect::<Vec<_>>(); let spline_points = match kind { SliderSplineKind::Linear => { let start = points[0]; let end = if let Some(pixel_length) = pixel_length { Math::point_on_line(points[0], points[1], pixel_length) } else { points[1] }; vec![start, end] } SliderSplineKind::Perfect =>
let diff = (t1 - t0).abs(); let pixel_length = pixel_length.unwrap_or(radius * diff); // circumference is 2 * pi * r, slider length over circumference is length/(2 * pi * r) let direction_unit = (t1 - t0) / (t1 - t0).abs(); let new_t1 = t0 + direction_unit * (pixel_length / radius); let mut t = t0; let mut c = Vec::new(); loop { if!((new_t1 >= t0 && t < new_t1) || (new_t1 < t0 && t > new_t1)) { break; } let rel = Point::new(t.cos() * radius, -t.sin() * radius); c.push(center + rel); t += (new_t1 - t0) / pixel_length; } c } SliderSplineKind::Bezier => { let mut output = Vec::new(); let mut last_index = 0; let mut i = 0; while i < points.len() { let multipart_segment = i < points.len() - 2 && (points[i] == points[i + 1]); if multipart_segment || i == points.len() - 1 { let sub = &points[last_index..i + 1]; if sub.len() == 2 { output.push(points[0]); output.push(points[1]); } else { create_singlebezier(&mut output, sub); } if multipart_segment { i += 1; } last_index = i; } i += 1; } output } _ => todo!(), }; let mut cumulative_lengths = Vec::with_capacity(spline_points.len()); let mut curr = 0.0; // using NotNan here because these need to be binary-searched over // and f64 isn't Ord cumulative_lengths.push(NotNan::new(curr).unwrap()); for points in spline_points.windows(2) { let dist = points[0].distance(points[1]); curr += dist; cumulative_lengths.push(NotNan::new(curr).unwrap()); } Spline { spline_points, cumulative_lengths, } } /// Truncate the length of the spline irreversibly pub fn truncate(&mut self, to_length: f64) { debug!("truncating to {} pixels", to_length); let mut limit_idx = None; for (i, cumul_length) in self.cumulative_lengths.iter().enumerate() { if cumul_length.into_inner() > to_length { limit_idx = Some(i); break; } } let limit_idx = match limit_idx { Some(v) if v > 0 => v, _ => return, }; let prev_idx = limit_idx - 1; let a = self.spline_points[prev_idx]; let b = self.spline_points[limit_idx]; let a_len = self.cumulative_lengths[prev_idx]; debug!("a={:?} (a_len={}) b={:?}", a, b, a_len); let remain = to_length - a_len.into_inner(); let mid = Math::point_on_line(a, b, remain); debug!("remain={:?} mid={:?}", remain, mid); self.spline_points[limit_idx] = mid; self.cumulative_lengths[limit_idx] = NotNan::new(to_length).unwrap(); debug!("spline_points[{}] = {:?}", limit_idx, mid); debug!("cumulative_lengths[{}] = {:?}", limit_idx, to_length); self.spline_points.truncate(limit_idx + 1); self.cumulative_lengths.truncate(limit_idx + 1); debug!("truncated to len {}", limit_idx + 1); } /// Return the pixel length of this spline pub fn pixel_length(&self) -> f64 { self.cumulative_lengths.last().unwrap().into_inner() } /// Return the endpoint of this spline pub fn end_point(&self) -> P { self.spline_points.last().cloned().unwrap() } /// Calculate the angle at the given length on the slider fn angle_at_length(&self, length: f64) -> P { let _length_notnan = NotNan::new(length).unwrap(); // match self.cumulative_lengths.binary_search(&length_notnan) { // Ok(_) => {} // Err(_) => {} // } todo!() } /// Calculate the point at which the slider ball would be after it has traveled a distance of /// `length` into the slider. pub fn point_at_length(&self, length: f64) -> P { let length_notnan = NotNan::new(length).unwrap(); match self.cumulative_lengths.binary_search(&length_notnan) { Ok(idx) => self.spline_points[idx], Err(idx) => { let n = self.spline_points.len(); if idx == 0 && self.spline_points.len() > 2 { return self.spline_points[0]; } else if idx == n { return self.spline_points[n - 1]; } let (len1, len2) = ( self.cumulative_lengths[idx - 1].into_inner(), self.cumulative_lengths[idx].into_inner(), ); let proportion = (length - len1) / (len2 - len1); let (p1, p2) = (self.spline_points[idx - 1], self.spline_points[idx]); (p2 - p1) * P::new(proportion, proportion) + p1 } } } } type P = Point<f64>; fn subdivide(control_points: &[P], l: &mut [P], r: &mut [P], midpoints_buf: &mut [P]) { let count = control_points.len(); midpoints_buf.copy_from_slice(control_points); for i in 0..count { l[i] = midpoints_buf[0]; r[count - i - 1] = midpoints_buf[count - i - 1]; for j in 0..count - i - 1 { midpoints_buf[j] = (midpoints_buf[j] + midpoints_buf[j + 1]) / P::new(2.0, 2.0); } } } fn approximate( control_points: &[P], output: &mut Vec<P>, l_buf: &mut [P], r_buf: &mut [P], midpoints_buf: &mut [P], ) { let count = control_points.len(); subdivide(&control_points, l_buf, r_buf, midpoints_buf); l_buf[count..(count * 2) - 1].clone_from_slice(&r_buf[1..count]); output.push(control_points[0]); for i in 1..count - 1 { let index = 2 * i; let p = (l_buf[index] * P::new(2.0, 2.0) + l_buf[index - 1] + l_buf[index + 1]) * P::new(0.25, 0.25); output.push(p); } } fn is_flat_enough(control_points: &[P], tolerance_sq: f64) -> bool { for i in 1..control_points.len() - 1 { if (control_points[i - 1] - control_points[i] * P::new(2.0, 2.0) + control_points[i + 1]) .length_squared() > tolerance_sq { return false; } } true } fn create_singlebezier(output: &mut Vec<P>, control_points: &[P]) { let count = control_points.len(); const TOLERANCE: f64 = 0.25; const TOLERANCE_SQ: f64 = TOLERANCE * TOLERANCE; if count == 0 { return; } let mut to_flatten: Vec<Vec<P>> = Vec::new(); let mut free_buffers: Vec<Vec<P>> = Vec::new(); let last_control_point = control_points[count - 1]; to_flatten.push(control_points.to_vec()); let mut left_child = vec![P::new(0.0, 0.0); count * 2 - 1]; let mut l_buf = vec![P::new(0.0, 0.0); count * 2 - 1]; let mut r_buf = vec![P::new(0.0, 0.0); count]; let mut midpoints_buf = vec![P::new(0.0, 0.0); count]; while!to_flatten.is_empty() { let mut parent = to_flatten.pop().unwrap(); if is_flat_enough(&parent, TOLERANCE_SQ) { approximate( &parent, output, &mut l_buf[..count * 2 - 1], &mut r_buf[..count], &mut midpoints_buf[..count], ); free_buffers.push(parent); continue; } let mut right_child = free_buffers .pop() .unwrap_or_else(|| vec![P::new(0.0, 0.0); count]); subdivide( &parent, &mut left_child, &mut right_child, &mut midpoints_buf[..count], ); // We re-use the buffer of the parent for one of the children, so that we save one allocation per iteration. parent[..count].clone_from_slice(&left_child[..count]); to_flatten.push(right_child); to_flatten.push(parent); } output.push(last_control_point); }
{ let (p1, p2, p3) = (points[0], points[1], points[2]); let (center, radius) = Math::circumcircle(p1, p2, p3); // find the t-values of the start and end of the slider let t0 = (center.y - p1.y).atan2(p1.x - center.x); let mut mid = (center.y - p2.y).atan2(p2.x - center.x); let mut t1 = (center.y - p3.y).atan2(p3.x - center.x); // make sure t0 is less than t1 while mid < t0 { mid += std::f64::consts::TAU; } while t1 < t0 { t1 += std::f64::consts::TAU; } if mid > t1 { t1 -= std::f64::consts::TAU; }
conditional_block
pattern.rs
use fmt::Formatter; use log::*; use std::borrow::Cow; use std::fmt::{self, Display}; use std::{convert::TryFrom, str::FromStr}; use thiserror::Error; use crate::*; /// A pattern that can function as either a [`Searcher`] or [`Applier`]. /// /// A [`Pattern`] is essentially a for-all quantified expression with /// [`Var`]s as the variables (in the logical sense). /// /// When creating a [`Rewrite`], the most common thing to use as either /// the left hand side (the [`Searcher`]) or the right hand side /// (the [`Applier`]) is a [`Pattern`]. /// /// As a [`Searcher`], a [`Pattern`] does the intuitive /// thing. /// Here is a somewhat verbose formal-ish statement: /// Searching for a pattern in an egraph yields substitutions /// ([`Subst`]s) _s_ such that, for any _s'_—where instead of /// mapping a variables to an eclass as _s_ does, _s'_ maps /// a variable to an arbitrary expression represented by that /// eclass—_p[s']_ (the pattern under substitution _s'_) is also /// represented by the egraph. /// /// As an [`Applier`], a [`Pattern`] performs the given substitution /// and adds the result to the [`EGraph`]. /// /// Importantly, [`Pattern`] implements [`FromStr`] if the /// [`Language`] does. /// This is probably how you'll create most [`Pattern`]s. /// /// ``` /// use egg::*; /// define_language! { /// enum Math { /// Num(i32), /// "+" = Add([Id; 2]), /// } /// } /// /// let mut egraph = EGraph::<Math, ()>::default(); /// let a11 = egraph.add_expr(&"(+ 1 1)".parse().unwrap()); /// let a22 = egraph.add_expr(&"(+ 2 2)".parse().unwrap()); /// /// // use Var syntax (leading question mark) to get a /// // variable in the Pattern /// let same_add: Pattern<Math> = "(+?a?a)".parse().unwrap(); /// /// // Rebuild before searching /// egraph.rebuild(); /// /// // This is the search method from the Searcher trait /// let matches = same_add.search(&egraph); /// let matched_eclasses: Vec<Id> = matches.iter().map(|m| m.eclass).collect(); /// assert_eq!(matched_eclasses, vec![a11, a22]); /// ``` /// /// [`FromStr`]: std::str::FromStr #[derive(Debug, PartialEq, Clone)] pub struct Pattern<L> { /// The actual pattern as a [`RecExpr`] pub ast: PatternAst<L>, program: machine::Program<L>, } /// A [`RecExpr`] that represents a /// [`Pattern`]. pub type PatternAst<L> = RecExpr<ENodeOrVar<L>>; impl<L: Language> PatternAst<L> { /// Returns a new `PatternAst` with the variables renames canonically pub fn alpha_rename(&self) -> Self { let mut vars = HashMap::<Var, Var>::default(); let mut new = PatternAst::default(); fn mkvar(i: usize) -> Var { let vs = &["?x", "?y", "?z", "?w"]; match vs.get(i) { Some(v) => v.parse().unwrap(), None => format!("?v{}", i - vs.len()).parse().unwrap(), } } for n in self.as_ref() { new.add(match n { ENodeOrVar::ENode(_) => n.clone(), ENodeOrVar::Var(v) => { let i = vars.len(); ENodeOrVar::Var(*vars.entry(*v).or_insert_with(|| mkvar(i))) } }); } new } } impl<L: Language> Pattern<L> { /// Creates a new pattern from the given pattern ast. pub fn new(ast: PatternAst<L>) -> Self { let ast = ast.compact(); let program = machine::Program::compile_from_pat(&ast); Pattern { ast, program } } /// Returns a list of the [`Var`]s in this pattern. pub fn vars(&self) -> Vec<Var> { let mut vars = vec![]; for n in self.ast.as_ref() { if let ENodeOrVar::Var(v) = n { if!vars.contains(v) { vars.push(*v) } } } vars } } impl<L: Language + Display> Pattern<L> { /// Pretty print this pattern as a sexp with the given width pub fn pretty(&self, width: usize) -> String { self.ast.pretty(width) } } /// The language of [`Pattern`]s. /// #[derive(Debug, Hash, PartialEq, Eq, Clone, PartialOrd, Ord)] pub enum ENodeOrVar<L> { /// An enode from the underlying [`Language`] ENode(L), /// A pattern variable Var(Var), } impl<L: Language> Language for ENodeOrVar<L> { fn matches(&self, _other: &Self) -> bool { panic!("Should never call this") } fn children(&self) -> &[Id] { match self { ENodeOrVar::ENode(n) => n.children(), ENodeOrVar::Var(_) => &[], } } fn children_mut(&mut self) -> &mut [Id] { match self { ENodeOrVar::ENode(n) => n.children_mut(), ENodeOrVar::Var(_) => &mut [], } } } impl<L: Language + Display> Display for ENodeOrVar<L> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Self::ENode(node) => Display::fmt(node, f), Self::Var(var) => Display::fmt(var, f), } } } #[derive(Debug, Error)] pub enum ENodeOrVarParseError<E> { #[error(transparent)] BadVar(<Var as FromStr>::Err), #[error("tried to parse pattern variable {0:?} as an operator")] UnexpectedVar(String), #[error(transparent)] BadOp(E), } impl<L: FromOp> FromOp for ENodeOrVar<L> { type Error = ENodeOrVarParseError<L::Error>; fn from_op(op: &str, children: Vec<Id>) -> Result<Self, Self::Error> { use ENodeOrVarParseError::*; if op.starts_with('?') && op.len() > 1 { if children.is_empty() { op.parse().map(Self::Var).map_err(BadVar) } else { Err(UnexpectedVar(op.to_owned())) } } else { L::from_op(op, children).map(Self::ENode).map_err(BadOp) } } } impl<L: FromOp> std::str::FromStr for Pattern<L> { type Err = RecExprParseError<ENodeOrVarParseError<L::Error>>; fn from_str(s: &str) -> Result<Self, Self::Err> { PatternAst::from_str(s).map(Self::from) } } impl<'a, L: Language> From<&'a [L]> for Pattern<L> { fn from(expr: &'a [L]) -> Self { let nodes: Vec<_> = expr.iter().cloned().map(ENodeOrVar::ENode).collect(); let ast = RecExpr::from(nodes); Self::new(ast) } } impl<L: Language> From<PatternAst<L>> for Pattern<L> { fn from(ast: PatternAst<L>) -> Self { Self::new(ast) } } impl<L: Language> TryFrom<Pattern<L>> for RecExpr<L> { type Error = Var; fn try_from(pat: Pattern<L>) -> Result<Self, Self::Error> { let nodes = pat.ast.as_ref().iter().cloned(); let ns: Result<Vec<_>, _> = nodes .map(|n| match n { ENodeOrVar::ENode(n) => Ok(n), ENodeOrVar::Var(v) => Err(v), }) .collect(); ns.map(RecExpr::from) } } impl<L: Language + Display> Display for Pattern<L> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Display::fmt(&self.ast, f) } } /// The result of searching a [`Searcher`] over one eclass. /// /// Note that one [`SearchMatches`] can contain many found /// substititions. So taking the length of a list of [`SearchMatches`] /// tells you how many eclasses something was matched in, _not_ how /// many matches were found total. /// #[derive(Debug)] pub struct SearchMatches<'a, L: Language> { /// The eclass id that these matches were found in. pub eclass: Id, /// The substitutions for each match. pub substs: Vec<Subst>, /// Optionally, an ast for the matches used in proof production. pub ast: Option<Cow<'a, PatternAst<L>>>, } impl<L: Language, A: Analysis<L>> Searcher<L, A> for Pattern<L> { fn get_pattern_ast(&self) -> Option<&PatternAst<L>> { Some(&self.ast) } fn search(&self, egraph: &EGraph<L, A>) -> Vec<SearchMatches<L>> { match self.ast.as_ref().last().unwrap() { ENodeOrVar::ENode(e) => { #[allow(clippy::mem_discriminant_non_enum)] let key = std::mem::discriminant(e); match egraph.classes_by_op.get(&key) { None => vec![], Some(ids) => ids .iter() .filter_map(|&id| self.search_eclass(egraph, id)) .collect(), } } ENodeOrVar::Var(_) => egraph .classes() .filter_map(|e| self.search_eclass(egraph, e.id)) .collect(), } } fn search_eclass(&self, egraph: &EGraph<L, A>, eclass: Id) -> Option<SearchMatches<L>> { let substs = self.program.run(egraph, eclass); if substs.is_empty() { None } else { let ast = Some(Cow::Borrowed(&self.ast)); Some(SearchMatches { eclass, substs, ast, }) } } fn vars
lf) -> Vec<Var> { Pattern::vars(self) } } impl<L, A> Applier<L, A> for Pattern<L> where L: Language, A: Analysis<L>, { fn get_pattern_ast(&self) -> Option<&PatternAst<L>> { Some(&self.ast) } fn apply_matches( &self, egraph: &mut EGraph<L, A>, matches: &[SearchMatches<L>], rule_name: Symbol, ) -> Vec<Id> { let mut added = vec![]; let ast = self.ast.as_ref(); let mut id_buf = vec![0.into(); ast.len()]; for mat in matches { let sast = mat.ast.as_ref().map(|cow| cow.as_ref()); for subst in &mat.substs { let did_something; let id; if egraph.are_explanations_enabled() { let (id_temp, did_something_temp) = egraph.union_instantiations(sast.unwrap(), &self.ast, subst, rule_name); did_something = did_something_temp; id = id_temp; } else { id = apply_pat(&mut id_buf, ast, egraph, subst); did_something = egraph.union(id, mat.eclass); } if did_something { added.push(id) } } } added } fn apply_one( &self, egraph: &mut EGraph<L, A>, eclass: Id, subst: &Subst, searcher_ast: Option<&PatternAst<L>>, rule_name: Symbol, ) -> Vec<Id> { let ast = self.ast.as_ref(); let mut id_buf = vec![0.into(); ast.len()]; let id = apply_pat(&mut id_buf, ast, egraph, subst); if let Some(ast) = searcher_ast { let (from, did_something) = egraph.union_instantiations(ast, &self.ast, subst, rule_name); if did_something { vec![from] } else { vec![] } } else if egraph.union(eclass, id) { vec![eclass] } else { vec![] } } fn vars(&self) -> Vec<Var> { Pattern::vars(self) } } pub(crate) fn apply_pat<L: Language, A: Analysis<L>>( ids: &mut [Id], pat: &[ENodeOrVar<L>], egraph: &mut EGraph<L, A>, subst: &Subst, ) -> Id { debug_assert_eq!(pat.len(), ids.len()); trace!("apply_rec {:2?} {:?}", pat, subst); for (i, pat_node) in pat.iter().enumerate() { let id = match pat_node { ENodeOrVar::Var(w) => subst[*w], ENodeOrVar::ENode(e) => { let n = e.clone().map_children(|child| ids[usize::from(child)]); trace!("adding: {:?}", n); egraph.add(n) } }; ids[i] = id; } *ids.last().unwrap() } #[cfg(test)] mod tests { use crate::{SymbolLang as S, *}; type EGraph = crate::EGraph<S, ()>; #[test] fn simple_match() { crate::init_logger(); let mut egraph = EGraph::default(); let (plus_id, _) = egraph.union_instantiations( &"(+ x y)".parse().unwrap(), &"(+ z w)".parse().unwrap(), &Default::default(), "union_plus".to_string(), ); egraph.rebuild(); let commute_plus = rewrite!( "commute_plus"; "(+?a?b)" => "(+?b?a)" ); let matches = commute_plus.search(&egraph); let n_matches: usize = matches.iter().map(|m| m.substs.len()).sum(); assert_eq!(n_matches, 2, "matches is wrong: {:#?}", matches); let applications = commute_plus.apply(&mut egraph, &matches); egraph.rebuild(); assert_eq!(applications.len(), 2); let actual_substs: Vec<Subst> = matches.iter().flat_map(|m| m.substs.clone()).collect(); println!("Here are the substs!"); for m in &actual_substs { println!("substs: {:?}", m); } egraph.dot().to_dot("target/simple-match.dot").unwrap(); use crate::extract::{AstSize, Extractor}; let ext = Extractor::new(&egraph, AstSize); let (_, best) = ext.find_best(plus_id); eprintln!("Best: {:#?}", best); } #[test] fn nonlinear_patterns() { crate::init_logger(); let mut egraph = EGraph::default(); egraph.add_expr(&"(f a a)".parse().unwrap()); egraph.add_expr(&"(f a (g a))))".parse().unwrap()); egraph.add_expr(&"(f a (g b))))".parse().unwrap()); egraph.add_expr(&"(h (foo a b) 0 1)".parse().unwrap()); egraph.add_expr(&"(h (foo a b) 1 0)".parse().unwrap()); egraph.add_expr(&"(h (foo a b) 0 0)".parse().unwrap()); egraph.rebuild(); let n_matches = |s: &str| s.parse::<Pattern<S>>().unwrap().n_matches(&egraph); assert_eq!(n_matches("(f?x?y)"), 3); assert_eq!(n_matches("(f?x?x)"), 1); assert_eq!(n_matches("(f?x (g?y))))"), 2); assert_eq!(n_matches("(f?x (g?x))))"), 1); assert_eq!(n_matches("(h?x 0 0)"), 1); } }
(&se
identifier_name
pattern.rs
use fmt::Formatter; use log::*; use std::borrow::Cow; use std::fmt::{self, Display}; use std::{convert::TryFrom, str::FromStr}; use thiserror::Error; use crate::*; /// A pattern that can function as either a [`Searcher`] or [`Applier`]. /// /// A [`Pattern`] is essentially a for-all quantified expression with /// [`Var`]s as the variables (in the logical sense). /// /// When creating a [`Rewrite`], the most common thing to use as either /// the left hand side (the [`Searcher`]) or the right hand side /// (the [`Applier`]) is a [`Pattern`]. /// /// As a [`Searcher`], a [`Pattern`] does the intuitive /// thing. /// Here is a somewhat verbose formal-ish statement: /// Searching for a pattern in an egraph yields substitutions /// ([`Subst`]s) _s_ such that, for any _s'_—where instead of /// mapping a variables to an eclass as _s_ does, _s'_ maps /// a variable to an arbitrary expression represented by that /// eclass—_p[s']_ (the pattern under substitution _s'_) is also /// represented by the egraph. /// /// As an [`Applier`], a [`Pattern`] performs the given substitution /// and adds the result to the [`EGraph`]. /// /// Importantly, [`Pattern`] implements [`FromStr`] if the /// [`Language`] does. /// This is probably how you'll create most [`Pattern`]s. /// /// ``` /// use egg::*; /// define_language! { /// enum Math { /// Num(i32), /// "+" = Add([Id; 2]), /// } /// } /// /// let mut egraph = EGraph::<Math, ()>::default(); /// let a11 = egraph.add_expr(&"(+ 1 1)".parse().unwrap()); /// let a22 = egraph.add_expr(&"(+ 2 2)".parse().unwrap()); /// /// // use Var syntax (leading question mark) to get a /// // variable in the Pattern /// let same_add: Pattern<Math> = "(+?a?a)".parse().unwrap(); /// /// // Rebuild before searching /// egraph.rebuild(); /// /// // This is the search method from the Searcher trait /// let matches = same_add.search(&egraph); /// let matched_eclasses: Vec<Id> = matches.iter().map(|m| m.eclass).collect(); /// assert_eq!(matched_eclasses, vec![a11, a22]); /// ``` /// /// [`FromStr`]: std::str::FromStr #[derive(Debug, PartialEq, Clone)] pub struct Pattern<L> { /// The actual pattern as a [`RecExpr`] pub ast: PatternAst<L>, program: machine::Program<L>, } /// A [`RecExpr`] that represents a /// [`Pattern`]. pub type PatternAst<L> = RecExpr<ENodeOrVar<L>>; impl<L: Language> PatternAst<L> { /// Returns a new `PatternAst` with the variables renames canonically pub fn alpha_rename(&self) -> Self { let mut vars = HashMap::<Var, Var>::default(); let mut new = PatternAst::default(); fn mkvar(i: usize) -> Var { let vs = &["?x", "?y", "?z", "?w"]; match vs.get(i) { Some(v) => v.parse().unwrap(), None => format!("?v{}", i - vs.len()).parse().unwrap(), } } for n in self.as_ref() { new.add(match n { ENodeOrVar::ENode(_) => n.clone(), ENodeOrVar::Var(v) => { let i = vars.len(); ENodeOrVar::Var(*vars.entry(*v).or_insert_with(|| mkvar(i))) } }); } new } } impl<L: Language> Pattern<L> { /// Creates a new pattern from the given pattern ast. pub fn new(ast: PatternAst<L>) -> Self { let ast = ast.compact(); let program = machine::Program::compile_from_pat(&ast); Pattern { ast, program } } /// Returns a list of the [`Var`]s in this pattern. pub fn vars(&self) -> Vec<Var> { let mut vars = vec![]; for n in self.ast.as_ref() { if let ENodeOrVar::Var(v) = n { if!vars.contains(v) { vars.push(*v) } } } vars } } impl<L: Language + Display> Pattern<L> { /// Pretty print this pattern as a sexp with the given width pub fn pretty(&self, width: usize) -> String { self.ast.pretty(width) } } /// The language of [`Pattern`]s. /// #[derive(Debug, Hash, PartialEq, Eq, Clone, PartialOrd, Ord)] pub enum ENodeOrVar<L> { /// An enode from the underlying [`Language`] ENode(L), /// A pattern variable Var(Var), } impl<L: Language> Language for ENodeOrVar<L> { fn matches(&self, _other: &Self) -> bool { panic!("Should never call this") } fn children(&self) -> &[Id] { match self { ENodeOrVar::ENode(n) => n.children(), ENodeOrVar::Var(_) => &[], } } fn children_mut(&mut self) -> &mut [Id] { match self { ENodeOrVar::ENode(n) => n.children_mut(), ENodeOrVar::Var(_) => &mut [], } } } impl<L: Language + Display> Display for ENodeOrVar<L> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Self::ENode(node) => Display::fmt(node, f), Self::Var(var) => Display::fmt(var, f), } } } #[derive(Debug, Error)] pub enum ENodeOrVarParseError<E> { #[error(transparent)] BadVar(<Var as FromStr>::Err), #[error("tried to parse pattern variable {0:?} as an operator")] UnexpectedVar(String), #[error(transparent)] BadOp(E), } impl<L: FromOp> FromOp for ENodeOrVar<L> { type Error = ENodeOrVarParseError<L::Error>; fn from_op(op: &str, children: Vec<Id>) -> Result<Self, Self::Error> { use ENodeOrVarParseError::*; if op.starts_with('?') && op.len() > 1 { if children.is_empty() { op.parse().map(Self::Var).map_err(BadVar) } else { Err(UnexpectedVar(op.to_owned())) } } else { L::from_op(op, children).map(Self::ENode).map_err(BadOp) } } } impl<L: FromOp> std::str::FromStr for Pattern<L> { type Err = RecExprParseError<ENodeOrVarParseError<L::Error>>; fn from_str(s: &str) -> Result<Self, Self::Err> { PatternAst::from_str(s).map(Self::from) } } impl<'a, L: Language> From<&'a [L]> for Pattern<L> { fn from(expr: &'a [L]) -> Self { let nodes: Vec<_> = expr.iter().cloned().map(ENodeOrVar::ENode).collect(); let ast = RecExpr::from(nodes); Self::new(ast) } } impl<L: Language> From<PatternAst<L>> for Pattern<L> { fn from(ast: PatternAst<L>) -> Self { Self::new(ast) } } impl<L: Language> TryFrom<Pattern<L>> for RecExpr<L> { type Error = Var; fn try_from(pat: Pattern<L>) -> Result<Self, Self::Error> { let nodes = pat.ast.as_ref().iter().cloned(); let ns: Result<Vec<_>, _> = nodes .map(|n| match n { ENodeOrVar::ENode(n) => Ok(n), ENodeOrVar::Var(v) => Err(v), }) .collect(); ns.map(RecExpr::from) } } impl<L: Language + Display> Display for Pattern<L> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Display::fmt(&self.ast, f) } } /// The result of searching a [`Searcher`] over one eclass. /// /// Note that one [`SearchMatches`] can contain many found /// substititions. So taking the length of a list of [`SearchMatches`] /// tells you how many eclasses something was matched in, _not_ how /// many matches were found total. /// #[derive(Debug)] pub struct SearchMatches<'a, L: Language> { /// The eclass id that these matches were found in. pub eclass: Id, /// The substitutions for each match. pub substs: Vec<Subst>, /// Optionally, an ast for the matches used in proof production. pub ast: Option<Cow<'a, PatternAst<L>>>, } impl<L: Language, A: Analysis<L>> Searcher<L, A> for Pattern<L> { fn get_pattern_ast(&self) -> Option<&PatternAst<L>> { Some(&self.ast) } fn search(&self, egraph: &EGraph<L, A>) -> Vec<SearchMatches<L>> { match self.ast.as_ref().last().unwrap() { ENodeOrVar::ENode(e) => { #[allow(clippy::mem_discriminant_non_enum)] let key = std::mem::discriminant(e); match egraph.classes_by_op.get(&key) { None => vec![], Some(ids) => ids .iter() .filter_map(|&id| self.search_eclass(egraph, id)) .collect(), } } ENodeOrVar::Var(_) => egraph .classes() .filter_map(|e| self.search_eclass(egraph, e.id)) .collect(), } } fn search_eclass(&self, egraph: &EGraph<L, A>, eclass: Id) -> Option<SearchMatches<L>> { let substs = self.program.run(egraph, eclass); if substs.is_empty() { None } else { let ast = Some(Cow::Borrowed(&self.ast)); Some(SearchMatches { eclass, substs, ast, }) } } fn vars(&self) -> Vec<Var> { Pattern::vars(self) } } impl<L, A> Applier<L, A> for Pattern<L> where L: Language, A: Analysis<L>, { fn get_pattern_ast(&self) -> Option<&PatternAst<L>> { Some(&self.ast) } fn apply_matches( &self, egraph: &mut EGraph<L, A>, matches: &[SearchMatches<L>], rule_name: Symbol, ) -> Vec<Id> { let mut added = vec![]; let ast = self.ast.as_ref(); let mut id_buf = vec![0.into(); ast.len()]; for mat in matches { let sast = mat.ast.as_ref().map(|cow| cow.as_ref()); for subst in &mat.substs { let did_something; let id; if egraph.are_explanations_enabled() { let (id_temp, did_something_temp) = egraph.union_instantiations(sast.unwrap(), &self.ast, subst, rule_name); did_something = did_something_temp; id = id_temp; } else { id = apply_pat(&mut id_buf, ast, egraph, subst); did_something = egraph.union(id, mat.eclass); } if did_something { added.push(id) } } } added } fn apply_one( &self, egraph: &mut EGraph<L, A>, eclass: Id, subst: &Subst, searcher_ast: Option<&PatternAst<L>>, rule_name: Symbol, ) -> Vec<Id> { let ast = self.ast.as_ref(); let mut id_buf = vec![0.into(); ast.len()]; let id = apply_pat(&mut id_buf, ast, egraph, subst); if let Some(ast) = searcher_ast { let (from, did_something) = egraph.union_instantiations(ast, &self.ast, subst, rule_name); if did_something { vec![from] } else { vec![] } } else if egraph.union(eclass, id) { vec![eclass] } else { vec![] } } fn vars(&self) -> Vec<Var> { Pattern::vars(self) } } pub(crate) fn apply_pat<L: Language, A: Analysis<L>>( ids: &mut [Id], pat: &[ENodeOrVar<L>], egraph: &mut EGraph<L, A>, subst: &Subst, ) -> Id { debug_assert_eq!(pat.len(), ids.len()); trace!("apply_rec {:2?} {:?}", pat, subst); for (i, pat_node) in pat.iter().enumerate() { let id = match pat_node { ENodeOrVar::Var(w) => subst[*w], ENodeOrVar::ENode(e) => { let n = e.clone().map_children(|child| ids[usize::from(child)]); trace!("adding: {:?}", n); egraph.add(n) }
} *ids.last().unwrap() } #[cfg(test)] mod tests { use crate::{SymbolLang as S, *}; type EGraph = crate::EGraph<S, ()>; #[test] fn simple_match() { crate::init_logger(); let mut egraph = EGraph::default(); let (plus_id, _) = egraph.union_instantiations( &"(+ x y)".parse().unwrap(), &"(+ z w)".parse().unwrap(), &Default::default(), "union_plus".to_string(), ); egraph.rebuild(); let commute_plus = rewrite!( "commute_plus"; "(+?a?b)" => "(+?b?a)" ); let matches = commute_plus.search(&egraph); let n_matches: usize = matches.iter().map(|m| m.substs.len()).sum(); assert_eq!(n_matches, 2, "matches is wrong: {:#?}", matches); let applications = commute_plus.apply(&mut egraph, &matches); egraph.rebuild(); assert_eq!(applications.len(), 2); let actual_substs: Vec<Subst> = matches.iter().flat_map(|m| m.substs.clone()).collect(); println!("Here are the substs!"); for m in &actual_substs { println!("substs: {:?}", m); } egraph.dot().to_dot("target/simple-match.dot").unwrap(); use crate::extract::{AstSize, Extractor}; let ext = Extractor::new(&egraph, AstSize); let (_, best) = ext.find_best(plus_id); eprintln!("Best: {:#?}", best); } #[test] fn nonlinear_patterns() { crate::init_logger(); let mut egraph = EGraph::default(); egraph.add_expr(&"(f a a)".parse().unwrap()); egraph.add_expr(&"(f a (g a))))".parse().unwrap()); egraph.add_expr(&"(f a (g b))))".parse().unwrap()); egraph.add_expr(&"(h (foo a b) 0 1)".parse().unwrap()); egraph.add_expr(&"(h (foo a b) 1 0)".parse().unwrap()); egraph.add_expr(&"(h (foo a b) 0 0)".parse().unwrap()); egraph.rebuild(); let n_matches = |s: &str| s.parse::<Pattern<S>>().unwrap().n_matches(&egraph); assert_eq!(n_matches("(f?x?y)"), 3); assert_eq!(n_matches("(f?x?x)"), 1); assert_eq!(n_matches("(f?x (g?y))))"), 2); assert_eq!(n_matches("(f?x (g?x))))"), 1); assert_eq!(n_matches("(h?x 0 0)"), 1); } }
}; ids[i] = id;
random_line_split
pattern.rs
use fmt::Formatter; use log::*; use std::borrow::Cow; use std::fmt::{self, Display}; use std::{convert::TryFrom, str::FromStr}; use thiserror::Error; use crate::*; /// A pattern that can function as either a [`Searcher`] or [`Applier`]. /// /// A [`Pattern`] is essentially a for-all quantified expression with /// [`Var`]s as the variables (in the logical sense). /// /// When creating a [`Rewrite`], the most common thing to use as either /// the left hand side (the [`Searcher`]) or the right hand side /// (the [`Applier`]) is a [`Pattern`]. /// /// As a [`Searcher`], a [`Pattern`] does the intuitive /// thing. /// Here is a somewhat verbose formal-ish statement: /// Searching for a pattern in an egraph yields substitutions /// ([`Subst`]s) _s_ such that, for any _s'_—where instead of /// mapping a variables to an eclass as _s_ does, _s'_ maps /// a variable to an arbitrary expression represented by that /// eclass—_p[s']_ (the pattern under substitution _s'_) is also /// represented by the egraph. /// /// As an [`Applier`], a [`Pattern`] performs the given substitution /// and adds the result to the [`EGraph`]. /// /// Importantly, [`Pattern`] implements [`FromStr`] if the /// [`Language`] does. /// This is probably how you'll create most [`Pattern`]s. /// /// ``` /// use egg::*; /// define_language! { /// enum Math { /// Num(i32), /// "+" = Add([Id; 2]), /// } /// } /// /// let mut egraph = EGraph::<Math, ()>::default(); /// let a11 = egraph.add_expr(&"(+ 1 1)".parse().unwrap()); /// let a22 = egraph.add_expr(&"(+ 2 2)".parse().unwrap()); /// /// // use Var syntax (leading question mark) to get a /// // variable in the Pattern /// let same_add: Pattern<Math> = "(+?a?a)".parse().unwrap(); /// /// // Rebuild before searching /// egraph.rebuild(); /// /// // This is the search method from the Searcher trait /// let matches = same_add.search(&egraph); /// let matched_eclasses: Vec<Id> = matches.iter().map(|m| m.eclass).collect(); /// assert_eq!(matched_eclasses, vec![a11, a22]); /// ``` /// /// [`FromStr`]: std::str::FromStr #[derive(Debug, PartialEq, Clone)] pub struct Pattern<L> { /// The actual pattern as a [`RecExpr`] pub ast: PatternAst<L>, program: machine::Program<L>, } /// A [`RecExpr`] that represents a /// [`Pattern`]. pub type PatternAst<L> = RecExpr<ENodeOrVar<L>>; impl<L: Language> PatternAst<L> { /// Returns a new `PatternAst` with the variables renames canonically pub fn alpha_rename(&self) -> Self { let mut vars = HashMap::<Var, Var>::default(); let mut new = PatternAst::default(); fn mkvar(i: usize) -> Var { let vs = &["?x", "?y", "?z", "?w"]; match vs.get(i) { Some(v) => v.parse().unwrap(), None => format!("?v{}", i - vs.len()).parse().unwrap(), } } for n in self.as_ref() { new.add(match n { ENodeOrVar::ENode(_) => n.clone(), ENodeOrVar::Var(v) => { let i = vars.len(); ENodeOrVar::Var(*vars.entry(*v).or_insert_with(|| mkvar(i))) } }); } new } } impl<L: Language> Pattern<L> { /// Creates a new pattern from the given pattern ast. pub fn new(ast: PatternAst<L>) -> Self { let ast = ast.compact(); let program = machine::Program::compile_from_pat(&ast); Pattern { ast, program } } /// Returns a list of the [`Var`]s in this pattern. pub fn vars(&self) -> Vec<Var> { let mut vars = vec![]; for n in self.ast.as_ref() { if let ENodeOrVar::Var(v) = n { if!vars.contains(v) { vars.push(*v) } } } vars } } impl<L: Language + Display> Pattern<L> { /// Pretty print this pattern as a sexp with the given width pub fn pretty(&self, width: usize) -> String { self.ast.pretty(width) } } /// The language of [`Pattern`]s. /// #[derive(Debug, Hash, PartialEq, Eq, Clone, PartialOrd, Ord)] pub enum ENodeOrVar<L> { /// An enode from the underlying [`Language`] ENode(L), /// A pattern variable Var(Var), } impl<L: Language> Language for ENodeOrVar<L> { fn matches(&self, _other: &Self) -> bool { panic!("Should never call this") } fn children(&self) -> &[Id] { match self { ENodeOrVar::ENode(n) => n.children(), ENodeOrVar::Var(_) => &[], } } fn children_mut(&mut self) -> &mut [Id] { match self { ENodeOrVar::ENode(n) => n.children_mut(), ENodeOrVar::Var(_) => &mut [], } } } impl<L: Language + Display> Display for ENodeOrVar<L> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Self::ENode(node) => Display::fmt(node, f), Self::Var(var) => Display::fmt(var, f), } } } #[derive(Debug, Error)] pub enum ENodeOrVarParseError<E> { #[error(transparent)] BadVar(<Var as FromStr>::Err), #[error("tried to parse pattern variable {0:?} as an operator")] UnexpectedVar(String), #[error(transparent)] BadOp(E), } impl<L: FromOp> FromOp for ENodeOrVar<L> { type Error = ENodeOrVarParseError<L::Error>; fn from_op(op: &str, children: Vec<Id>) -> Result<Self, Self::Error> { use ENodeOrVarParseError::*; if op.starts_with('?') && op.len() > 1 { if children.is_empty() { op.parse().map(Self::Var).map_err(BadVar) } else { Err(UnexpectedVar(op.to_owned())) } } else { L::from_op(op, children).map(Self::ENode).map_err(BadOp) } } } impl<L: FromOp> std::str::FromStr for Pattern<L> { type Err = RecExprParseError<ENodeOrVarParseError<L::Error>>; fn from_str(s: &str) -> Result<Self, Self::Err> { PatternAst::from_str(s).map(Self::from) } } impl<'a, L: Language> From<&'a [L]> for Pattern<L> { fn from(expr: &'a [L]) -> Self { let nodes: Vec<_> = expr.iter().cloned().map(ENodeOrVar::ENode).collect(); let ast = RecExpr::from(nodes); Self::new(ast) } } impl<L: Language> From<PatternAst<L>> for Pattern<L> { fn from(ast: PatternAst<L>) -> Self { Self::new(ast) } } impl<L: Language> TryFrom<Pattern<L>> for RecExpr<L> { type Error = Var; fn try_from(pat: Pattern<L>) -> Result<Self, Self::Error> { let nodes = pat.ast.as_ref().iter().cloned(); let ns: Result<Vec<_>, _> = nodes .map(|n| match n { ENodeOrVar::ENode(n) => Ok(n), ENodeOrVar::Var(v) => Err(v), }) .collect(); ns.map(RecExpr::from) } } impl<L: Language + Display> Display for Pattern<L> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Display::fmt(&self.ast, f) } } /// The result of searching a [`Searcher`] over one eclass. /// /// Note that one [`SearchMatches`] can contain many found /// substititions. So taking the length of a list of [`SearchMatches`] /// tells you how many eclasses something was matched in, _not_ how /// many matches were found total. /// #[derive(Debug)] pub struct SearchMatches<'a, L: Language> { /// The eclass id that these matches were found in. pub eclass: Id, /// The substitutions for each match. pub substs: Vec<Subst>, /// Optionally, an ast for the matches used in proof production. pub ast: Option<Cow<'a, PatternAst<L>>>, } impl<L: Language, A: Analysis<L>> Searcher<L, A> for Pattern<L> { fn get_pattern_ast(&self) -> Option<&PatternAst<L>> { Some(&self.ast) } fn search(&self, egraph: &EGraph<L, A>) -> Vec<SearchMatches<L>> { match self.ast.as_ref().last().unwrap() { ENodeOrVar::ENode(e) => { #[allow(clippy::mem_discriminant_non_enum)] let key = std::mem::discriminant(e); match egraph.classes_by_op.get(&key) { None => vec![], Some(ids) => ids .iter() .filter_map(|&id| self.search_eclass(egraph, id)) .collect(), } } ENodeOrVar::Var(_) => egraph .classes() .filter_map(|e| self.search_eclass(egraph, e.id)) .collect(), } } fn search_eclass(&self, egraph: &EGraph<L, A>, eclass: Id) -> Option<SearchMatches<L>> {
fn vars(&self) -> Vec<Var> { Pattern::vars(self) } } impl<L, A> Applier<L, A> for Pattern<L> where L: Language, A: Analysis<L>, { fn get_pattern_ast(&self) -> Option<&PatternAst<L>> { Some(&self.ast) } fn apply_matches( &self, egraph: &mut EGraph<L, A>, matches: &[SearchMatches<L>], rule_name: Symbol, ) -> Vec<Id> { let mut added = vec![]; let ast = self.ast.as_ref(); let mut id_buf = vec![0.into(); ast.len()]; for mat in matches { let sast = mat.ast.as_ref().map(|cow| cow.as_ref()); for subst in &mat.substs { let did_something; let id; if egraph.are_explanations_enabled() { let (id_temp, did_something_temp) = egraph.union_instantiations(sast.unwrap(), &self.ast, subst, rule_name); did_something = did_something_temp; id = id_temp; } else { id = apply_pat(&mut id_buf, ast, egraph, subst); did_something = egraph.union(id, mat.eclass); } if did_something { added.push(id) } } } added } fn apply_one( &self, egraph: &mut EGraph<L, A>, eclass: Id, subst: &Subst, searcher_ast: Option<&PatternAst<L>>, rule_name: Symbol, ) -> Vec<Id> { let ast = self.ast.as_ref(); let mut id_buf = vec![0.into(); ast.len()]; let id = apply_pat(&mut id_buf, ast, egraph, subst); if let Some(ast) = searcher_ast { let (from, did_something) = egraph.union_instantiations(ast, &self.ast, subst, rule_name); if did_something { vec![from] } else { vec![] } } else if egraph.union(eclass, id) { vec![eclass] } else { vec![] } } fn vars(&self) -> Vec<Var> { Pattern::vars(self) } } pub(crate) fn apply_pat<L: Language, A: Analysis<L>>( ids: &mut [Id], pat: &[ENodeOrVar<L>], egraph: &mut EGraph<L, A>, subst: &Subst, ) -> Id { debug_assert_eq!(pat.len(), ids.len()); trace!("apply_rec {:2?} {:?}", pat, subst); for (i, pat_node) in pat.iter().enumerate() { let id = match pat_node { ENodeOrVar::Var(w) => subst[*w], ENodeOrVar::ENode(e) => { let n = e.clone().map_children(|child| ids[usize::from(child)]); trace!("adding: {:?}", n); egraph.add(n) } }; ids[i] = id; } *ids.last().unwrap() } #[cfg(test)] mod tests { use crate::{SymbolLang as S, *}; type EGraph = crate::EGraph<S, ()>; #[test] fn simple_match() { crate::init_logger(); let mut egraph = EGraph::default(); let (plus_id, _) = egraph.union_instantiations( &"(+ x y)".parse().unwrap(), &"(+ z w)".parse().unwrap(), &Default::default(), "union_plus".to_string(), ); egraph.rebuild(); let commute_plus = rewrite!( "commute_plus"; "(+?a?b)" => "(+?b?a)" ); let matches = commute_plus.search(&egraph); let n_matches: usize = matches.iter().map(|m| m.substs.len()).sum(); assert_eq!(n_matches, 2, "matches is wrong: {:#?}", matches); let applications = commute_plus.apply(&mut egraph, &matches); egraph.rebuild(); assert_eq!(applications.len(), 2); let actual_substs: Vec<Subst> = matches.iter().flat_map(|m| m.substs.clone()).collect(); println!("Here are the substs!"); for m in &actual_substs { println!("substs: {:?}", m); } egraph.dot().to_dot("target/simple-match.dot").unwrap(); use crate::extract::{AstSize, Extractor}; let ext = Extractor::new(&egraph, AstSize); let (_, best) = ext.find_best(plus_id); eprintln!("Best: {:#?}", best); } #[test] fn nonlinear_patterns() { crate::init_logger(); let mut egraph = EGraph::default(); egraph.add_expr(&"(f a a)".parse().unwrap()); egraph.add_expr(&"(f a (g a))))".parse().unwrap()); egraph.add_expr(&"(f a (g b))))".parse().unwrap()); egraph.add_expr(&"(h (foo a b) 0 1)".parse().unwrap()); egraph.add_expr(&"(h (foo a b) 1 0)".parse().unwrap()); egraph.add_expr(&"(h (foo a b) 0 0)".parse().unwrap()); egraph.rebuild(); let n_matches = |s: &str| s.parse::<Pattern<S>>().unwrap().n_matches(&egraph); assert_eq!(n_matches("(f?x?y)"), 3); assert_eq!(n_matches("(f?x?x)"), 1); assert_eq!(n_matches("(f?x (g?y))))"), 2); assert_eq!(n_matches("(f?x (g?x))))"), 1); assert_eq!(n_matches("(h?x 0 0)"), 1); } }
let substs = self.program.run(egraph, eclass); if substs.is_empty() { None } else { let ast = Some(Cow::Borrowed(&self.ast)); Some(SearchMatches { eclass, substs, ast, }) } }
identifier_body
pattern.rs
use fmt::Formatter; use log::*; use std::borrow::Cow; use std::fmt::{self, Display}; use std::{convert::TryFrom, str::FromStr}; use thiserror::Error; use crate::*; /// A pattern that can function as either a [`Searcher`] or [`Applier`]. /// /// A [`Pattern`] is essentially a for-all quantified expression with /// [`Var`]s as the variables (in the logical sense). /// /// When creating a [`Rewrite`], the most common thing to use as either /// the left hand side (the [`Searcher`]) or the right hand side /// (the [`Applier`]) is a [`Pattern`]. /// /// As a [`Searcher`], a [`Pattern`] does the intuitive /// thing. /// Here is a somewhat verbose formal-ish statement: /// Searching for a pattern in an egraph yields substitutions /// ([`Subst`]s) _s_ such that, for any _s'_—where instead of /// mapping a variables to an eclass as _s_ does, _s'_ maps /// a variable to an arbitrary expression represented by that /// eclass—_p[s']_ (the pattern under substitution _s'_) is also /// represented by the egraph. /// /// As an [`Applier`], a [`Pattern`] performs the given substitution /// and adds the result to the [`EGraph`]. /// /// Importantly, [`Pattern`] implements [`FromStr`] if the /// [`Language`] does. /// This is probably how you'll create most [`Pattern`]s. /// /// ``` /// use egg::*; /// define_language! { /// enum Math { /// Num(i32), /// "+" = Add([Id; 2]), /// } /// } /// /// let mut egraph = EGraph::<Math, ()>::default(); /// let a11 = egraph.add_expr(&"(+ 1 1)".parse().unwrap()); /// let a22 = egraph.add_expr(&"(+ 2 2)".parse().unwrap()); /// /// // use Var syntax (leading question mark) to get a /// // variable in the Pattern /// let same_add: Pattern<Math> = "(+?a?a)".parse().unwrap(); /// /// // Rebuild before searching /// egraph.rebuild(); /// /// // This is the search method from the Searcher trait /// let matches = same_add.search(&egraph); /// let matched_eclasses: Vec<Id> = matches.iter().map(|m| m.eclass).collect(); /// assert_eq!(matched_eclasses, vec![a11, a22]); /// ``` /// /// [`FromStr`]: std::str::FromStr #[derive(Debug, PartialEq, Clone)] pub struct Pattern<L> { /// The actual pattern as a [`RecExpr`] pub ast: PatternAst<L>, program: machine::Program<L>, } /// A [`RecExpr`] that represents a /// [`Pattern`]. pub type PatternAst<L> = RecExpr<ENodeOrVar<L>>; impl<L: Language> PatternAst<L> { /// Returns a new `PatternAst` with the variables renames canonically pub fn alpha_rename(&self) -> Self { let mut vars = HashMap::<Var, Var>::default(); let mut new = PatternAst::default(); fn mkvar(i: usize) -> Var { let vs = &["?x", "?y", "?z", "?w"]; match vs.get(i) { Some(v) => v.parse().unwrap(), None => format!("?v{}", i - vs.len()).parse().unwrap(), } } for n in self.as_ref() { new.add(match n { ENodeOrVar::ENode(_) => n.clone(), ENodeOrVar::Var(v) => { let i = vars.len(); ENodeOrVar::Var(*vars.entry(*v).or_insert_with(|| mkvar(i))) } }); } new } } impl<L: Language> Pattern<L> { /// Creates a new pattern from the given pattern ast. pub fn new(ast: PatternAst<L>) -> Self { let ast = ast.compact(); let program = machine::Program::compile_from_pat(&ast); Pattern { ast, program } } /// Returns a list of the [`Var`]s in this pattern. pub fn vars(&self) -> Vec<Var> { let mut vars = vec![]; for n in self.ast.as_ref() { if let ENodeOrVar::Var(v) = n { if!vars.contains(v) { vars.push(*v) } } } vars } } impl<L: Language + Display> Pattern<L> { /// Pretty print this pattern as a sexp with the given width pub fn pretty(&self, width: usize) -> String { self.ast.pretty(width) } } /// The language of [`Pattern`]s. /// #[derive(Debug, Hash, PartialEq, Eq, Clone, PartialOrd, Ord)] pub enum ENodeOrVar<L> { /// An enode from the underlying [`Language`] ENode(L), /// A pattern variable Var(Var), } impl<L: Language> Language for ENodeOrVar<L> { fn matches(&self, _other: &Self) -> bool { panic!("Should never call this") } fn children(&self) -> &[Id] { match self { ENodeOrVar::ENode(n) => n.children(), ENodeOrVar::Var(_) => &[], } } fn children_mut(&mut self) -> &mut [Id] { match self { ENodeOrVar::ENode(n) => n.children_mut(), ENodeOrVar::Var(_) => &mut [], } } } impl<L: Language + Display> Display for ENodeOrVar<L> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Self::ENode(node) => Display::fmt(node, f), Self::Var(var) => Display::fmt(var, f), } } } #[derive(Debug, Error)] pub enum ENodeOrVarParseError<E> { #[error(transparent)] BadVar(<Var as FromStr>::Err), #[error("tried to parse pattern variable {0:?} as an operator")] UnexpectedVar(String), #[error(transparent)] BadOp(E), } impl<L: FromOp> FromOp for ENodeOrVar<L> { type Error = ENodeOrVarParseError<L::Error>; fn from_op(op: &str, children: Vec<Id>) -> Result<Self, Self::Error> { use ENodeOrVarParseError::*; if op.starts_with('?') && op.len() > 1 { if children.is_empty() { op.parse().map(Self::Var).map_err(BadVar) } else { Err(UnexpectedVar(op.to_owned())) } } else { L::from_op(op, children).map(Self::ENode).map_err(BadOp) } } } impl<L: FromOp> std::str::FromStr for Pattern<L> { type Err = RecExprParseError<ENodeOrVarParseError<L::Error>>; fn from_str(s: &str) -> Result<Self, Self::Err> { PatternAst::from_str(s).map(Self::from) } } impl<'a, L: Language> From<&'a [L]> for Pattern<L> { fn from(expr: &'a [L]) -> Self { let nodes: Vec<_> = expr.iter().cloned().map(ENodeOrVar::ENode).collect(); let ast = RecExpr::from(nodes); Self::new(ast) } } impl<L: Language> From<PatternAst<L>> for Pattern<L> { fn from(ast: PatternAst<L>) -> Self { Self::new(ast) } } impl<L: Language> TryFrom<Pattern<L>> for RecExpr<L> { type Error = Var; fn try_from(pat: Pattern<L>) -> Result<Self, Self::Error> { let nodes = pat.ast.as_ref().iter().cloned(); let ns: Result<Vec<_>, _> = nodes .map(|n| match n { ENodeOrVar::ENode(n) => Ok(n), ENodeOrVar::Var(v) => Err(v), }) .collect(); ns.map(RecExpr::from) } } impl<L: Language + Display> Display for Pattern<L> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Display::fmt(&self.ast, f) } } /// The result of searching a [`Searcher`] over one eclass. /// /// Note that one [`SearchMatches`] can contain many found /// substititions. So taking the length of a list of [`SearchMatches`] /// tells you how many eclasses something was matched in, _not_ how /// many matches were found total. /// #[derive(Debug)] pub struct SearchMatches<'a, L: Language> { /// The eclass id that these matches were found in. pub eclass: Id, /// The substitutions for each match. pub substs: Vec<Subst>, /// Optionally, an ast for the matches used in proof production. pub ast: Option<Cow<'a, PatternAst<L>>>, } impl<L: Language, A: Analysis<L>> Searcher<L, A> for Pattern<L> { fn get_pattern_ast(&self) -> Option<&PatternAst<L>> { Some(&self.ast) } fn search(&self, egraph: &EGraph<L, A>) -> Vec<SearchMatches<L>> { match self.ast.as_ref().last().unwrap() { ENodeOrVar::ENode(e) => { #[allow(clippy::mem_discriminant_non_enum)] let key = std::mem::discriminant(e); match egraph.classes_by_op.get(&key) { None => vec![], Some(ids) => ids .iter() .filter_map(|&id| self.search_eclass(egraph, id)) .collect(), } } ENodeOrVar::Var(_) => egraph .classes() .filter_map(|e| self.search_eclass(egraph, e.id)) .collect(), } } fn search_eclass(&self, egraph: &EGraph<L, A>, eclass: Id) -> Option<SearchMatches<L>> { let substs = self.program.run(egraph, eclass); if substs.is_empty() { None } else { let ast = Some(Cow::Borrowed(&self.ast)); Some(SearchMatches { eclass, substs, ast, }) } } fn vars(&self) -> Vec<Var> { Pattern::vars(self) } } impl<L, A> Applier<L, A> for Pattern<L> where L: Language, A: Analysis<L>, { fn get_pattern_ast(&self) -> Option<&PatternAst<L>> { Some(&self.ast) } fn apply_matches( &self, egraph: &mut EGraph<L, A>, matches: &[SearchMatches<L>], rule_name: Symbol, ) -> Vec<Id> { let mut added = vec![]; let ast = self.ast.as_ref(); let mut id_buf = vec![0.into(); ast.len()]; for mat in matches { let sast = mat.ast.as_ref().map(|cow| cow.as_ref()); for subst in &mat.substs { let did_something; let id; if egraph.are_explanations_enabled() { let (id_temp, did_something_temp) = egraph.union_instantiations(sast.unwrap(), &self.ast, subst, rule_name); did_something = did_something_temp; id = id_temp; } else { id = apply_pat(&mut id_buf, ast, egraph, subst); did_something = egraph.union(id, mat.eclass); } if did_something { added.push(id) } } } added } fn apply_one( &self, egraph: &mut EGraph<L, A>, eclass: Id, subst: &Subst, searcher_ast: Option<&PatternAst<L>>, rule_name: Symbol, ) -> Vec<Id> { let ast = self.ast.as_ref(); let mut id_buf = vec![0.into(); ast.len()]; let id = apply_pat(&mut id_buf, ast, egraph, subst); if let Some(ast) = searcher_ast { let (from, did_something) = egraph.union_instantiations(ast, &self.ast, subst, rule_name); if did_something { vec![from] } else { vec![] } } else if egraph.union(eclass, id) { vec![eclass] } else { vec![] } } fn vars(&self) -> Vec<Var> { Pattern::vars(self) } } pub(crate) fn apply_pat<L: Language, A: Analysis<L>>( ids: &mut [Id], pat: &[ENodeOrVar<L>], egraph: &mut EGraph<L, A>, subst: &Subst, ) -> Id { debug_assert_eq!(pat.len(), ids.len()); trace!("apply_rec {:2?} {:?}", pat, subst); for (i, pat_node) in pat.iter().enumerate() { let id = match pat_node { ENodeOrVar::Var(w) => subst[*w], ENodeOrVar::ENode(e) => {
}; ids[i] = id; } *ids.last().unwrap() } #[cfg(test)] mod tests { use crate::{SymbolLang as S, *}; type EGraph = crate::EGraph<S, ()>; #[test] fn simple_match() { crate::init_logger(); let mut egraph = EGraph::default(); let (plus_id, _) = egraph.union_instantiations( &"(+ x y)".parse().unwrap(), &"(+ z w)".parse().unwrap(), &Default::default(), "union_plus".to_string(), ); egraph.rebuild(); let commute_plus = rewrite!( "commute_plus"; "(+?a?b)" => "(+?b?a)" ); let matches = commute_plus.search(&egraph); let n_matches: usize = matches.iter().map(|m| m.substs.len()).sum(); assert_eq!(n_matches, 2, "matches is wrong: {:#?}", matches); let applications = commute_plus.apply(&mut egraph, &matches); egraph.rebuild(); assert_eq!(applications.len(), 2); let actual_substs: Vec<Subst> = matches.iter().flat_map(|m| m.substs.clone()).collect(); println!("Here are the substs!"); for m in &actual_substs { println!("substs: {:?}", m); } egraph.dot().to_dot("target/simple-match.dot").unwrap(); use crate::extract::{AstSize, Extractor}; let ext = Extractor::new(&egraph, AstSize); let (_, best) = ext.find_best(plus_id); eprintln!("Best: {:#?}", best); } #[test] fn nonlinear_patterns() { crate::init_logger(); let mut egraph = EGraph::default(); egraph.add_expr(&"(f a a)".parse().unwrap()); egraph.add_expr(&"(f a (g a))))".parse().unwrap()); egraph.add_expr(&"(f a (g b))))".parse().unwrap()); egraph.add_expr(&"(h (foo a b) 0 1)".parse().unwrap()); egraph.add_expr(&"(h (foo a b) 1 0)".parse().unwrap()); egraph.add_expr(&"(h (foo a b) 0 0)".parse().unwrap()); egraph.rebuild(); let n_matches = |s: &str| s.parse::<Pattern<S>>().unwrap().n_matches(&egraph); assert_eq!(n_matches("(f?x?y)"), 3); assert_eq!(n_matches("(f?x?x)"), 1); assert_eq!(n_matches("(f?x (g?y))))"), 2); assert_eq!(n_matches("(f?x (g?x))))"), 1); assert_eq!(n_matches("(h?x 0 0)"), 1); } }
let n = e.clone().map_children(|child| ids[usize::from(child)]); trace!("adding: {:?}", n); egraph.add(n) }
conditional_block
main.rs
#![allow(clippy::single_match)] use ::std::collections::HashMap; use ::std::sync::Mutex; use anyhow::Error; use chrono::naive::NaiveDate as Date; use derive_more::Display; use log::*; use serde::{Deserialize, Deserializer, Serialize, Serializer}; mod citation; mod filters; mod github; mod md; lazy_static::lazy_static! { static ref FOOTNOTES: Mutex<Option<HashMap<String, usize>>> = Mutex::new(Some(HashMap::new())); } struct DateRange { start: Date, end: Option<Date>, } impl DateRange { fn to_resume_string(&self) -> String { if let Some(end) = self.end { format!( "{} - {}", self.start.format("%b,&nbsp;%Y"), end.format("%b,&nbsp;%Y") ) } else { format!("{} - Current", self.start.format("%b,&nbsp;%Y")) } } } impl std::fmt::Display for DateRange { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(end) = self.end { write!(f, "{}~{}", self.start.format("%Y-%m"), end.format("%Y-%m")) } else { write!(f, "{}~", self.start.format("%Y-%m")) } } } impl std::str::FromStr for DateRange { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let p: Vec<_> = s.split('~').collect(); if p.len()!= 2 { Err(anyhow::anyhow!( "A date range should have 2 and only 2 dates" )) } else { Ok(DateRange { start: Date::parse_from_str(&format!("{}-01", p[0]), "%Y-%m-%d").unwrap(), end: if p[1].is_empty() { None } else { Some(Date::parse_from_str(&format!("{}-01", p[1]), "%Y-%m-%d").unwrap()) }, }) } } } impl Serialize for DateRange { fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { s.serialize_str(&self.to_string()) } } impl<'a> Deserialize<'a> for DateRange { fn deserialize<D: Deserializer<'a>>(d: D) -> Result<Self, D::Error> { let s = String::deserialize(d)?; s.parse().map_err(serde::de::Error::custom) } } #[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] enum Citation { Raw(String), RawWithYear { text: String, year: Option<u32> }, Url(citation::UrlCitation), Doi(citation::DoiCitation), Bibtex(citation::BibtexCitation), } impl Citation { fn to_raw(&self) -> Option<Citation> { use Citation::*; match self { Raw(s) => Some(Raw(s.clone())), RawWithYear { text,.. } => Some(Raw(text.clone())), Url(url) => url.to_raw(), Doi(doi) => doi.to_raw(), Bibtex(bib) => bib.to_raw(), } } fn set_year(self, year: Option<u32>) -> Citation { use Citation::*; if let Raw(s) = self { RawWithYear { text: s, year } } else { self } } fn to_raw_with_year(&self) -> Option<Citation> { use Citation::*; match self { Raw(s) => Some(RawWithYear { text: s.clone(), year: None, }), RawWithYear { text, year } => Some(RawWithYear { text: text.clone(), year: *year, }), Url(url) => url.to_raw().map(|v| v.set_year(url.year())), Doi(doi) => doi.to_raw().map(|v| v.set_year(doi.year())), Bibtex(bib) => bib.to_raw().map(|v| v.set_year(bib.year())), } } } #[derive(Serialize, Deserialize)] enum Degree { BS, MS, PhD, } impl Degree { fn
(&self) -> String { match self { Self::BS => "Bachelor of Science".into(), Self::MS => "Master of Science".into(), Self::PhD => "PhD".into(), } } } #[derive(Serialize, Deserialize)] struct Education { institution: String, degree: Degree, major: String, duration: DateRange, #[serde(skip_serializing_if = "Option::is_none", default)] location: Option<String>, #[serde(skip_serializing_if = "Option::is_none", default)] gpa: Option<f32>, #[serde(skip_serializing_if = "Option::is_none", default)] courses: Option<Vec<String>>, } #[derive(Serialize, Deserialize)] struct Experience { company: String, position: String, duration: DateRange, description: String, #[serde(skip_serializing_if = "Option::is_none", default)] location: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] tags: Vec<String>, } #[derive(Serialize, Deserialize)] struct Contact { #[serde(rename = "type")] type_: String, value: String, } #[derive(Serialize, Deserialize)] struct Skill { category: String, #[serde(default)] description: Option<String>, } #[derive(Serialize, Deserialize)] struct Person { name: String, #[serde(default)] resume_url: Option<String>, contacts: Vec<Contact>, educations: Vec<Education>, experiences: Vec<Experience>, projects: Vec<ProjectParam>, #[serde(default)] skills: Vec<Skill>, #[serde(default)] references: HashMap<String, Citation>, #[serde(default)] publications: Vec<Citation>, } #[allow(clippy::large_enum_variant)] #[derive(Serialize, Deserialize)] #[serde(untagged)] enum ProjectParam { Import(ProjectImport), Sort { order_by: ProjectSortOrder }, ImportMode { import_mode: ProjectImportMode }, Raw(Project), } #[derive(Serialize, Deserialize, Copy, Clone, PartialEq)] #[serde(rename_all = "snake_case")] enum ProjectImportMode { Whitelist, Combine, } impl Default for ProjectImportMode { fn default() -> Self { Self::Combine } } #[derive(Serialize, Deserialize, Copy, Clone)] #[serde(rename_all = "snake_case")] enum ProjectSortOrder { Stars, Forks, StarsThenForks, ForksThenStars, Manual, } #[derive(Serialize, Deserialize)] #[serde(tag = "from", rename_all = "lowercase")] enum ProjectImport { GitHub { #[serde(default)] ignore_forks: bool, #[serde(default)] repos: Option<Vec<String>>, #[serde(default)] token: Option<String>, }, } #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Display)] #[serde(rename_all = "lowercase")] enum ProjectRole { Owner, Maintainer, Contributor, } /// Single digit precision deciaml real number #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Ord, Eq)] struct Decimal1(u64); impl ::std::fmt::Display for Decimal1 { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { <f64 as ::std::fmt::Display>::fmt(&(*self).into(), f) } } impl ::std::ops::Add<Decimal1> for Decimal1 { type Output = Self; fn add(self, rhs: Self) -> Self::Output { Self(rhs.0 + self.0) } } impl ::std::ops::AddAssign<Decimal1> for Decimal1 { fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0; } } impl From<f64> for Decimal1 { fn from(f: f64) -> Self { Self((f * 10.0) as u64) } } impl From<Decimal1> for f64 { fn from(f: Decimal1) -> f64 { f.0 as f64 / 10.0 } } impl<'de> ::serde::Deserialize<'de> for Decimal1 { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = Decimal1; fn expecting(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { write!(fmt, "a float") } fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E> where E: ::serde::de::Error, { Ok(v.into()) } } deserializer.deserialize_f64(Visitor) } } impl ::serde::Serialize for Decimal1 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_f64((*self).into()) } } #[derive(Serialize, Deserialize, Debug, Clone)] struct LanguageStat { language: String, percentage: Decimal1, } #[serde_with::serde_as] #[derive(Serialize, Deserialize, Debug, Clone)] struct Project { name: String, #[serde(default, skip_serializing_if = "Option::is_none")] description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] contributions: Option<String>, #[serde( with = "serde_option_display_fromstr", default, skip_serializing_if = "Option::is_none" )] url: Option<url::Url>, #[serde(default, skip_serializing_if = "Option::is_none")] stars: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")] forks: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")] active: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] owner: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] commits: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")] additions: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")] deletions: Option<u64>, #[serde(default, skip_serializing_if = "Vec::is_empty")] languages: Vec<LanguageStat>, #[serde(default, skip_serializing_if = "Vec::is_empty")] tags: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] role: Option<ProjectRole>, } mod serde_option_display_fromstr { pub(crate) fn deserialize<'de, D, T>(deser: D) -> Result<Option<T>, D::Error> where D: serde::Deserializer<'de>, T: ::std::str::FromStr, <T as ::std::str::FromStr>::Err: ::std::fmt::Display, { #[derive(Default)] struct Visitor<T>(::std::marker::PhantomData<T>); impl<'de, T> serde::de::Visitor<'de> for Visitor<T> where T: ::std::str::FromStr, <T as ::std::str::FromStr>::Err: ::std::fmt::Display, { type Value = Option<T>; fn expecting(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { write!(fmt, "a string") } fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> { v.parse() .map_err(serde::de::Error::custom) .map(Option::Some) } } deser.deserialize_str(Visitor::<T>(Default::default())) } pub(crate) fn serialize<S, T>(v: &Option<T>, ser: S) -> Result<S::Ok, S::Error> where S: serde::ser::Serializer, T: ::std::fmt::Display, { match v { Some(v) => ser.serialize_str(&v.to_string()), None => ser.serialize_none(), } } } use askama::Template; struct ContactParams { value: String, icon: Option<String>, link: Option<String>, } #[derive(Template)] #[template(path = "resume.html", escape = "none")] struct ResumeParams<'a> { name: &'a str, resume_url: Option<&'a str>, contacts: Vec<ContactParams>, educations: &'a [Education], experiences: &'a [Experience], projects: Vec<Project>, references: Vec<(&'a str, &'a str)>, publications: Vec<(&'a str, Option<u32>)>, skills: &'a [Skill], } async fn fetch(mut person: Person) -> anyhow::Result<Person> { use futures::stream::TryStreamExt; let github_username = person .contacts .iter() .find(|v| v.type_ == "github") .map(|v| v.value.as_str()); let mut project_map = HashMap::new(); let mut sort_order = None; let mut import_mode = ProjectImportMode::Combine; // Process project imports first for pi in person.projects.iter() { match pi { ProjectParam::Import(ProjectImport::GitHub { ignore_forks, repos: None, token, }) => project_map.extend( github::get_user_projects_from_github(*ignore_forks, token.clone()) .await? .into_iter() .map(|v| (v.name.clone(), v)), ), ProjectParam::Import(ProjectImport::GitHub { repos: Some(repos), token, .. }) => { project_map.extend( github::get_projects_info_from_github( repos, token.clone(), github_username.map(ToOwned::to_owned), ) .await? .into_iter() .map(|v| (v.name.clone(), v)), ); } ProjectParam::Sort { order_by } => { sort_order = Some(*order_by); } ProjectParam::ImportMode { import_mode: im } => { import_mode = *im; } _ => {} } } if sort_order.is_none() && import_mode == ProjectImportMode::Whitelist { sort_order = Some(ProjectSortOrder::Manual); } // Adding manually project entries for pi in person.projects.iter_mut() { match pi { ProjectParam::Raw(p) => { p.languages .sort_unstable_by_key(|v| ::std::cmp::Reverse(v.percentage)); if let Some(old) = project_map.get_mut(&p.name) { debug!("Merging project entry {}", p.name); if p.url.is_some() { old.url = p.url.clone(); } if p.description.is_some() { old.description = p.description.clone(); } if p.owner.is_some() { old.owner = p.owner.clone(); } if p.contributions.is_some() { old.contributions = p.contributions.clone(); } if!p.tags.is_empty() { old.tags = p.tags.clone(); } if p.role.is_some() { old.role = p.role; } } else { project_map.insert(p.name.clone(), p.clone()); } } _ => {} } } let mut projects: Vec<_>; if let ProjectImportMode::Whitelist = import_mode { let raw_entries: Vec<_> = person .projects .iter() .filter_map(|p| match p { ProjectParam::Raw(p) => Some(&p.name), _ => None, }) .collect(); projects = raw_entries .into_iter() .filter_map(|name| project_map.get(name).map(Clone::clone)) .collect(); } else { projects = project_map.iter().map(|(_, v)| v.clone()).collect(); } if let Some(sort_order) = sort_order { use ::std::cmp::Reverse; match sort_order { ProjectSortOrder::Stars => projects.sort_unstable_by_key(|v| Reverse(v.stars)), ProjectSortOrder::Forks => projects.sort_unstable_by_key(|v| Reverse(v.forks)), ProjectSortOrder::ForksThenStars => { projects.sort_unstable_by_key(|v| Reverse((v.forks, v.stars))) } ProjectSortOrder::StarsThenForks => { projects.sort_unstable_by_key(|v| Reverse((v.stars, v.forks))) } ProjectSortOrder::Manual if import_mode!= ProjectImportMode::Whitelist => { debug!("Manual sort"); let raw_entries: HashMap<_, _> = person .projects .iter() .filter_map(|p| match p { ProjectParam::Raw(p) => Some(&p.name), _ => None, }) .enumerate() .map(|(i, v)| (v, i)) .collect(); projects.sort_unstable_by_key(|v| raw_entries.get(&v.name).map(|v| *v)); } _ => {} } } debug!("{}", serde_yaml::to_string(&projects)?); person.projects = projects.into_iter().map(|v| ProjectParam::Raw(v)).collect(); person.projects.push(ProjectParam::Sort { order_by: ProjectSortOrder::Manual, }); // Fetch citations use ::futures::FutureExt; debug!("{:?}", person.references); let fut: futures::stream::FuturesUnordered<_> = person .references .iter_mut() .map(|(_, v)| v) .chain(person.publications.iter_mut()) .map(|v| { async move { Result::<_, Error>::Ok(match v { Citation::Url(url) => url.fetch().await?, Citation::Doi(doi) => doi.fetch().await?, Citation::Bibtex(bib) => bib.fetch().await?, _ => (), }) } .boxed() }) .collect(); let () = fut.try_collect().await?; person.references = person .references .into_iter() .filter_map(|(k, v)| v.to_raw().map(|v| (k, v))) .collect(); person.publications = person .publications .into_iter() .filter_map(|v| v.to_raw_with_year()) .collect(); debug!("{:?}", person.references); Ok(person) } fn build_params<'a>( p: &'a Person, footnotes: Option<HashMap<String, usize>>, ) -> Result<ResumeParams<'a>, Error> { let mut c = Vec::new(); let it = p.references.iter().filter_map(|(k, v)| match v { Citation::Raw(s) => Some((k.as_str(), s.as_str())), _ => None, }); let mut references: Vec<_> = if let Some(footnotes) = footnotes.as_ref() { // Remove unused references it.filter(|(k, _)| footnotes.get(*k).is_some()).collect() } else { it.collect() }; // Sort references if let Some(footnotes) = footnotes { references.sort_unstable_by_key(|(k, _)| footnotes.get(*k).unwrap()); } for i in p.contacts.iter() { c.push(ContactParams { link: match i.type_.as_str() { "github" => Some(format!("https://github.com/{}", i.value)), "email" => Some(format!("mailto:{}", i.value)), "blog" => Some(i.value.clone()), _ => None, }, icon: match i.type_.as_str() { "github" => Some("icons/github.svg".into()), "email" => Some("icons/mail.svg".into()), "blog" => Some("icons/blog.svg".into()), _ => None, }, value: i.value.clone(), }); } Ok(ResumeParams { name: &p.name, resume_url: p.resume_url.as_ref().map(String::as_str), contacts: c, educations: p.educations.as_slice(), experiences: p.experiences.as_slice(), projects: p .projects .iter() .filter_map(|v| match v { ProjectParam::Raw(p) => Some(p.clone()), _ => None, }) .collect(), publications: p .publications .iter() .filter_map(|v| match v { Citation::RawWithYear { text, year } => Some((text.as_str(), *year)), _ => None, }) .collect(), references, skills: p.skills.as_slice(), }) } fn main() -> Result<(), Error> { env_logger::init(); let args = clap::Command::new("resume") .arg(clap::Arg::new("input").required(true)) .get_matches(); let input_filename = args.get_one::<String>("input").unwrap(); let cache_filename = format!("{}-cache", input_filename); let cache_info = std::fs::metadata(&cache_filename); let input_info = std::fs::metadata(&input_filename)?; let cache_data = if cache_info.is_ok() { std::fs::read(&cache_filename).ok() } else { None }; let r = if cache_data.is_some() && cache_info?.modified()? >= input_info.modified()? { serde_yaml::from_slice::<Person>(cache_data.unwrap().as_slice())? } else { let f = std::fs::read(input_filename).unwrap(); let r = serde_yaml::from_slice::<Person>(f.as_slice())?; debug!("{}", serde_yaml::to_string(&r)?); let mut runtime = tokio::runtime::Runtime::new()?; let r = runtime.block_on(fetch(r))?; if let Some(mut cache_f) = std::fs::File::create(format!("{}-cache", input_filename)).ok() { use ::std::io::Write; write!(cache_f, "{}", serde_yaml::to_string(&r)?)?; } r }; let resume = build_params(&r, None)?; resume.render()?; let footnotes = FOOTNOTES.lock().unwrap().replace(HashMap::new()).unwrap(); let resume = build_params(&r, Some(footnotes))?; println!("{}", resume.render()?); Ok(()) }
to_resume_string
identifier_name
main.rs
#![allow(clippy::single_match)] use ::std::collections::HashMap; use ::std::sync::Mutex; use anyhow::Error; use chrono::naive::NaiveDate as Date; use derive_more::Display; use log::*; use serde::{Deserialize, Deserializer, Serialize, Serializer}; mod citation; mod filters; mod github; mod md; lazy_static::lazy_static! { static ref FOOTNOTES: Mutex<Option<HashMap<String, usize>>> = Mutex::new(Some(HashMap::new())); } struct DateRange { start: Date, end: Option<Date>, } impl DateRange { fn to_resume_string(&self) -> String { if let Some(end) = self.end { format!( "{} - {}", self.start.format("%b,&nbsp;%Y"), end.format("%b,&nbsp;%Y") ) } else { format!("{} - Current", self.start.format("%b,&nbsp;%Y")) } } } impl std::fmt::Display for DateRange { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(end) = self.end { write!(f, "{}~{}", self.start.format("%Y-%m"), end.format("%Y-%m")) } else { write!(f, "{}~", self.start.format("%Y-%m")) } } } impl std::str::FromStr for DateRange { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let p: Vec<_> = s.split('~').collect(); if p.len()!= 2 { Err(anyhow::anyhow!( "A date range should have 2 and only 2 dates" )) } else { Ok(DateRange { start: Date::parse_from_str(&format!("{}-01", p[0]), "%Y-%m-%d").unwrap(), end: if p[1].is_empty() { None } else { Some(Date::parse_from_str(&format!("{}-01", p[1]), "%Y-%m-%d").unwrap()) }, }) } } } impl Serialize for DateRange { fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { s.serialize_str(&self.to_string()) }
fn deserialize<D: Deserializer<'a>>(d: D) -> Result<Self, D::Error> { let s = String::deserialize(d)?; s.parse().map_err(serde::de::Error::custom) } } #[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] enum Citation { Raw(String), RawWithYear { text: String, year: Option<u32> }, Url(citation::UrlCitation), Doi(citation::DoiCitation), Bibtex(citation::BibtexCitation), } impl Citation { fn to_raw(&self) -> Option<Citation> { use Citation::*; match self { Raw(s) => Some(Raw(s.clone())), RawWithYear { text,.. } => Some(Raw(text.clone())), Url(url) => url.to_raw(), Doi(doi) => doi.to_raw(), Bibtex(bib) => bib.to_raw(), } } fn set_year(self, year: Option<u32>) -> Citation { use Citation::*; if let Raw(s) = self { RawWithYear { text: s, year } } else { self } } fn to_raw_with_year(&self) -> Option<Citation> { use Citation::*; match self { Raw(s) => Some(RawWithYear { text: s.clone(), year: None, }), RawWithYear { text, year } => Some(RawWithYear { text: text.clone(), year: *year, }), Url(url) => url.to_raw().map(|v| v.set_year(url.year())), Doi(doi) => doi.to_raw().map(|v| v.set_year(doi.year())), Bibtex(bib) => bib.to_raw().map(|v| v.set_year(bib.year())), } } } #[derive(Serialize, Deserialize)] enum Degree { BS, MS, PhD, } impl Degree { fn to_resume_string(&self) -> String { match self { Self::BS => "Bachelor of Science".into(), Self::MS => "Master of Science".into(), Self::PhD => "PhD".into(), } } } #[derive(Serialize, Deserialize)] struct Education { institution: String, degree: Degree, major: String, duration: DateRange, #[serde(skip_serializing_if = "Option::is_none", default)] location: Option<String>, #[serde(skip_serializing_if = "Option::is_none", default)] gpa: Option<f32>, #[serde(skip_serializing_if = "Option::is_none", default)] courses: Option<Vec<String>>, } #[derive(Serialize, Deserialize)] struct Experience { company: String, position: String, duration: DateRange, description: String, #[serde(skip_serializing_if = "Option::is_none", default)] location: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] tags: Vec<String>, } #[derive(Serialize, Deserialize)] struct Contact { #[serde(rename = "type")] type_: String, value: String, } #[derive(Serialize, Deserialize)] struct Skill { category: String, #[serde(default)] description: Option<String>, } #[derive(Serialize, Deserialize)] struct Person { name: String, #[serde(default)] resume_url: Option<String>, contacts: Vec<Contact>, educations: Vec<Education>, experiences: Vec<Experience>, projects: Vec<ProjectParam>, #[serde(default)] skills: Vec<Skill>, #[serde(default)] references: HashMap<String, Citation>, #[serde(default)] publications: Vec<Citation>, } #[allow(clippy::large_enum_variant)] #[derive(Serialize, Deserialize)] #[serde(untagged)] enum ProjectParam { Import(ProjectImport), Sort { order_by: ProjectSortOrder }, ImportMode { import_mode: ProjectImportMode }, Raw(Project), } #[derive(Serialize, Deserialize, Copy, Clone, PartialEq)] #[serde(rename_all = "snake_case")] enum ProjectImportMode { Whitelist, Combine, } impl Default for ProjectImportMode { fn default() -> Self { Self::Combine } } #[derive(Serialize, Deserialize, Copy, Clone)] #[serde(rename_all = "snake_case")] enum ProjectSortOrder { Stars, Forks, StarsThenForks, ForksThenStars, Manual, } #[derive(Serialize, Deserialize)] #[serde(tag = "from", rename_all = "lowercase")] enum ProjectImport { GitHub { #[serde(default)] ignore_forks: bool, #[serde(default)] repos: Option<Vec<String>>, #[serde(default)] token: Option<String>, }, } #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Display)] #[serde(rename_all = "lowercase")] enum ProjectRole { Owner, Maintainer, Contributor, } /// Single digit precision deciaml real number #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Ord, Eq)] struct Decimal1(u64); impl ::std::fmt::Display for Decimal1 { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { <f64 as ::std::fmt::Display>::fmt(&(*self).into(), f) } } impl ::std::ops::Add<Decimal1> for Decimal1 { type Output = Self; fn add(self, rhs: Self) -> Self::Output { Self(rhs.0 + self.0) } } impl ::std::ops::AddAssign<Decimal1> for Decimal1 { fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0; } } impl From<f64> for Decimal1 { fn from(f: f64) -> Self { Self((f * 10.0) as u64) } } impl From<Decimal1> for f64 { fn from(f: Decimal1) -> f64 { f.0 as f64 / 10.0 } } impl<'de> ::serde::Deserialize<'de> for Decimal1 { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct Visitor; impl<'de> ::serde::de::Visitor<'de> for Visitor { type Value = Decimal1; fn expecting(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { write!(fmt, "a float") } fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E> where E: ::serde::de::Error, { Ok(v.into()) } } deserializer.deserialize_f64(Visitor) } } impl ::serde::Serialize for Decimal1 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_f64((*self).into()) } } #[derive(Serialize, Deserialize, Debug, Clone)] struct LanguageStat { language: String, percentage: Decimal1, } #[serde_with::serde_as] #[derive(Serialize, Deserialize, Debug, Clone)] struct Project { name: String, #[serde(default, skip_serializing_if = "Option::is_none")] description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] contributions: Option<String>, #[serde( with = "serde_option_display_fromstr", default, skip_serializing_if = "Option::is_none" )] url: Option<url::Url>, #[serde(default, skip_serializing_if = "Option::is_none")] stars: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")] forks: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")] active: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] owner: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] commits: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")] additions: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")] deletions: Option<u64>, #[serde(default, skip_serializing_if = "Vec::is_empty")] languages: Vec<LanguageStat>, #[serde(default, skip_serializing_if = "Vec::is_empty")] tags: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] role: Option<ProjectRole>, } mod serde_option_display_fromstr { pub(crate) fn deserialize<'de, D, T>(deser: D) -> Result<Option<T>, D::Error> where D: serde::Deserializer<'de>, T: ::std::str::FromStr, <T as ::std::str::FromStr>::Err: ::std::fmt::Display, { #[derive(Default)] struct Visitor<T>(::std::marker::PhantomData<T>); impl<'de, T> serde::de::Visitor<'de> for Visitor<T> where T: ::std::str::FromStr, <T as ::std::str::FromStr>::Err: ::std::fmt::Display, { type Value = Option<T>; fn expecting(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { write!(fmt, "a string") } fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> { v.parse() .map_err(serde::de::Error::custom) .map(Option::Some) } } deser.deserialize_str(Visitor::<T>(Default::default())) } pub(crate) fn serialize<S, T>(v: &Option<T>, ser: S) -> Result<S::Ok, S::Error> where S: serde::ser::Serializer, T: ::std::fmt::Display, { match v { Some(v) => ser.serialize_str(&v.to_string()), None => ser.serialize_none(), } } } use askama::Template; struct ContactParams { value: String, icon: Option<String>, link: Option<String>, } #[derive(Template)] #[template(path = "resume.html", escape = "none")] struct ResumeParams<'a> { name: &'a str, resume_url: Option<&'a str>, contacts: Vec<ContactParams>, educations: &'a [Education], experiences: &'a [Experience], projects: Vec<Project>, references: Vec<(&'a str, &'a str)>, publications: Vec<(&'a str, Option<u32>)>, skills: &'a [Skill], } async fn fetch(mut person: Person) -> anyhow::Result<Person> { use futures::stream::TryStreamExt; let github_username = person .contacts .iter() .find(|v| v.type_ == "github") .map(|v| v.value.as_str()); let mut project_map = HashMap::new(); let mut sort_order = None; let mut import_mode = ProjectImportMode::Combine; // Process project imports first for pi in person.projects.iter() { match pi { ProjectParam::Import(ProjectImport::GitHub { ignore_forks, repos: None, token, }) => project_map.extend( github::get_user_projects_from_github(*ignore_forks, token.clone()) .await? .into_iter() .map(|v| (v.name.clone(), v)), ), ProjectParam::Import(ProjectImport::GitHub { repos: Some(repos), token, .. }) => { project_map.extend( github::get_projects_info_from_github( repos, token.clone(), github_username.map(ToOwned::to_owned), ) .await? .into_iter() .map(|v| (v.name.clone(), v)), ); } ProjectParam::Sort { order_by } => { sort_order = Some(*order_by); } ProjectParam::ImportMode { import_mode: im } => { import_mode = *im; } _ => {} } } if sort_order.is_none() && import_mode == ProjectImportMode::Whitelist { sort_order = Some(ProjectSortOrder::Manual); } // Adding manually project entries for pi in person.projects.iter_mut() { match pi { ProjectParam::Raw(p) => { p.languages .sort_unstable_by_key(|v| ::std::cmp::Reverse(v.percentage)); if let Some(old) = project_map.get_mut(&p.name) { debug!("Merging project entry {}", p.name); if p.url.is_some() { old.url = p.url.clone(); } if p.description.is_some() { old.description = p.description.clone(); } if p.owner.is_some() { old.owner = p.owner.clone(); } if p.contributions.is_some() { old.contributions = p.contributions.clone(); } if!p.tags.is_empty() { old.tags = p.tags.clone(); } if p.role.is_some() { old.role = p.role; } } else { project_map.insert(p.name.clone(), p.clone()); } } _ => {} } } let mut projects: Vec<_>; if let ProjectImportMode::Whitelist = import_mode { let raw_entries: Vec<_> = person .projects .iter() .filter_map(|p| match p { ProjectParam::Raw(p) => Some(&p.name), _ => None, }) .collect(); projects = raw_entries .into_iter() .filter_map(|name| project_map.get(name).map(Clone::clone)) .collect(); } else { projects = project_map.iter().map(|(_, v)| v.clone()).collect(); } if let Some(sort_order) = sort_order { use ::std::cmp::Reverse; match sort_order { ProjectSortOrder::Stars => projects.sort_unstable_by_key(|v| Reverse(v.stars)), ProjectSortOrder::Forks => projects.sort_unstable_by_key(|v| Reverse(v.forks)), ProjectSortOrder::ForksThenStars => { projects.sort_unstable_by_key(|v| Reverse((v.forks, v.stars))) } ProjectSortOrder::StarsThenForks => { projects.sort_unstable_by_key(|v| Reverse((v.stars, v.forks))) } ProjectSortOrder::Manual if import_mode!= ProjectImportMode::Whitelist => { debug!("Manual sort"); let raw_entries: HashMap<_, _> = person .projects .iter() .filter_map(|p| match p { ProjectParam::Raw(p) => Some(&p.name), _ => None, }) .enumerate() .map(|(i, v)| (v, i)) .collect(); projects.sort_unstable_by_key(|v| raw_entries.get(&v.name).map(|v| *v)); } _ => {} } } debug!("{}", serde_yaml::to_string(&projects)?); person.projects = projects.into_iter().map(|v| ProjectParam::Raw(v)).collect(); person.projects.push(ProjectParam::Sort { order_by: ProjectSortOrder::Manual, }); // Fetch citations use ::futures::FutureExt; debug!("{:?}", person.references); let fut: futures::stream::FuturesUnordered<_> = person .references .iter_mut() .map(|(_, v)| v) .chain(person.publications.iter_mut()) .map(|v| { async move { Result::<_, Error>::Ok(match v { Citation::Url(url) => url.fetch().await?, Citation::Doi(doi) => doi.fetch().await?, Citation::Bibtex(bib) => bib.fetch().await?, _ => (), }) } .boxed() }) .collect(); let () = fut.try_collect().await?; person.references = person .references .into_iter() .filter_map(|(k, v)| v.to_raw().map(|v| (k, v))) .collect(); person.publications = person .publications .into_iter() .filter_map(|v| v.to_raw_with_year()) .collect(); debug!("{:?}", person.references); Ok(person) } fn build_params<'a>( p: &'a Person, footnotes: Option<HashMap<String, usize>>, ) -> Result<ResumeParams<'a>, Error> { let mut c = Vec::new(); let it = p.references.iter().filter_map(|(k, v)| match v { Citation::Raw(s) => Some((k.as_str(), s.as_str())), _ => None, }); let mut references: Vec<_> = if let Some(footnotes) = footnotes.as_ref() { // Remove unused references it.filter(|(k, _)| footnotes.get(*k).is_some()).collect() } else { it.collect() }; // Sort references if let Some(footnotes) = footnotes { references.sort_unstable_by_key(|(k, _)| footnotes.get(*k).unwrap()); } for i in p.contacts.iter() { c.push(ContactParams { link: match i.type_.as_str() { "github" => Some(format!("https://github.com/{}", i.value)), "email" => Some(format!("mailto:{}", i.value)), "blog" => Some(i.value.clone()), _ => None, }, icon: match i.type_.as_str() { "github" => Some("icons/github.svg".into()), "email" => Some("icons/mail.svg".into()), "blog" => Some("icons/blog.svg".into()), _ => None, }, value: i.value.clone(), }); } Ok(ResumeParams { name: &p.name, resume_url: p.resume_url.as_ref().map(String::as_str), contacts: c, educations: p.educations.as_slice(), experiences: p.experiences.as_slice(), projects: p .projects .iter() .filter_map(|v| match v { ProjectParam::Raw(p) => Some(p.clone()), _ => None, }) .collect(), publications: p .publications .iter() .filter_map(|v| match v { Citation::RawWithYear { text, year } => Some((text.as_str(), *year)), _ => None, }) .collect(), references, skills: p.skills.as_slice(), }) } fn main() -> Result<(), Error> { env_logger::init(); let args = clap::Command::new("resume") .arg(clap::Arg::new("input").required(true)) .get_matches(); let input_filename = args.get_one::<String>("input").unwrap(); let cache_filename = format!("{}-cache", input_filename); let cache_info = std::fs::metadata(&cache_filename); let input_info = std::fs::metadata(&input_filename)?; let cache_data = if cache_info.is_ok() { std::fs::read(&cache_filename).ok() } else { None }; let r = if cache_data.is_some() && cache_info?.modified()? >= input_info.modified()? { serde_yaml::from_slice::<Person>(cache_data.unwrap().as_slice())? } else { let f = std::fs::read(input_filename).unwrap(); let r = serde_yaml::from_slice::<Person>(f.as_slice())?; debug!("{}", serde_yaml::to_string(&r)?); let mut runtime = tokio::runtime::Runtime::new()?; let r = runtime.block_on(fetch(r))?; if let Some(mut cache_f) = std::fs::File::create(format!("{}-cache", input_filename)).ok() { use ::std::io::Write; write!(cache_f, "{}", serde_yaml::to_string(&r)?)?; } r }; let resume = build_params(&r, None)?; resume.render()?; let footnotes = FOOTNOTES.lock().unwrap().replace(HashMap::new()).unwrap(); let resume = build_params(&r, Some(footnotes))?; println!("{}", resume.render()?); Ok(()) }
} impl<'a> Deserialize<'a> for DateRange {
random_line_split
readbuf.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License.. use crate::fmt::{self, Debug, Formatter}; use crate::io::{Result, Write}; use crate::mem::{self, MaybeUninit}; use crate::{cmp, ptr};
/// A borrowed byte buffer which is incrementally filled and initialized. /// /// This type is a sort of "double cursor". It tracks three regions in the buffer: a region at the beginning of the /// buffer that has been logically filled with data, a region that has been initialized at some point but not yet /// logically filled, and a region at the end that is fully uninitialized. The filled region is guaranteed to be a /// subset of the initialized region. /// /// In summary, the contents of the buffer can be visualized as: /// ```not_rust /// [ capacity ] /// [ filled | unfilled ] /// [ initialized | uninitialized ] /// ``` /// /// A `BorrowedBuf` is created around some existing data (or capacity for data) via a unique reference /// (`&mut`). The `BorrowedBuf` can be configured (e.g., using `clear` or `set_init`), but cannot be /// directly written. To write into the buffer, use `unfilled` to create a `BorrowedCursor`. The cursor /// has write-only access to the unfilled portion of the buffer (you can think of it as a /// write-only iterator). /// /// The lifetime `'data` is a bound on the lifetime of the underlying data. pub struct BorrowedBuf<'data> { /// The buffer's underlying data. buf: &'data mut [MaybeUninit<u8>], /// The length of `self.buf` which is known to be filled. filled: usize, /// The length of `self.buf` which is known to be initialized. init: usize, } impl Debug for BorrowedBuf<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("BorrowedBuf") .field("init", &self.init) .field("filled", &self.filled) .field("capacity", &self.capacity()) .finish() } } /// Create a new `BorrowedBuf` from a fully initialized slice. impl<'data> From<&'data mut [u8]> for BorrowedBuf<'data> { #[inline] fn from(slice: &'data mut [u8]) -> BorrowedBuf<'data> { let len = slice.len(); BorrowedBuf { // SAFETY: initialized data never becoming uninitialized is an invariant of BorrowedBuf buf: unsafe { (slice as *mut [u8]).as_uninit_slice_mut().unwrap() }, filled: 0, init: len, } } } /// Create a new `BorrowedBuf` from an uninitialized buffer. /// /// Use `set_init` if part of the buffer is known to be already initialized. impl<'data> From<&'data mut [MaybeUninit<u8>]> for BorrowedBuf<'data> { #[inline] fn from(buf: &'data mut [MaybeUninit<u8>]) -> BorrowedBuf<'data> { BorrowedBuf { buf, filled: 0, init: 0 } } } impl<'data> BorrowedBuf<'data> { /// Returns the total capacity of the buffer. #[inline] pub fn capacity(&self) -> usize { self.buf.len() } /// Returns the length of the filled part of the buffer. #[inline] pub fn len(&self) -> usize { self.filled } /// Returns the length of the initialized part of the buffer. #[inline] pub fn init_len(&self) -> usize { self.init } /// Returns a shared reference to the filled portion of the buffer. #[inline] pub fn filled(&self) -> &[u8] { // SAFETY: We only slice the filled part of the buffer, which is always valid unsafe { MaybeUninit::slice_assume_init_ref(&self.buf[0..self.filled]) } } /// Returns a cursor over the unfilled part of the buffer. #[inline] pub fn unfilled<'this>(&'this mut self) -> BorrowedCursor<'this> { BorrowedCursor { start: self.filled, // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its // lifetime covariantly is safe. buf: unsafe { mem::transmute::<&'this mut BorrowedBuf<'data>, &'this mut BorrowedBuf<'this>>(self) }, } } /// Clears the buffer, resetting the filled region to empty. /// /// The number of initialized bytes is not changed, and the contents of the buffer are not modified. #[inline] pub fn clear(&mut self) -> &mut Self { self.filled = 0; self } /// Asserts that the first `n` bytes of the buffer are initialized. /// /// `BorrowedBuf` assumes that bytes are never de-initialized, so this method does nothing when called with fewer /// bytes than are already known to be initialized. /// /// # Safety /// /// The caller must ensure that the first `n` unfilled bytes of the buffer have already been initialized. #[inline] pub unsafe fn set_init(&mut self, n: usize) -> &mut Self { self.init = cmp::max(self.init, n); self } } /// A writeable view of the unfilled portion of a [`BorrowedBuf`](BorrowedBuf). /// /// Provides access to the initialized and uninitialized parts of the underlying `BorrowedBuf`. /// Data can be written directly to the cursor by using [`append`](BorrowedCursor::append) or /// indirectly by getting a slice of part or all of the cursor and writing into the slice. In the /// indirect case, the caller must call [`advance`](BorrowedCursor::advance) after writing to inform /// the cursor how many bytes have been written. /// /// Once data is written to the cursor, it becomes part of the filled portion of the underlying /// `BorrowedBuf` and can no longer be accessed or re-written by the cursor. I.e., the cursor tracks /// the unfilled part of the underlying `BorrowedBuf`. /// /// The lifetime `'a` is a bound on the lifetime of the underlying buffer (which means it is a bound /// on the data in that buffer by transitivity). #[derive(Debug)] pub struct BorrowedCursor<'a> { /// The underlying buffer. // Safety invariant: we treat the type of buf as covariant in the lifetime of `BorrowedBuf` when // we create a `BorrowedCursor`. This is only safe if we never replace `buf` by assigning into // it, so don't do that! buf: &'a mut BorrowedBuf<'a>, /// The length of the filled portion of the underlying buffer at the time of the cursor's /// creation. start: usize, } impl<'a> BorrowedCursor<'a> { /// Reborrow this cursor by cloning it with a smaller lifetime. /// /// Since a cursor maintains unique access to its underlying buffer, the borrowed cursor is /// not accessible while the new cursor exists. #[inline] pub fn reborrow<'this>(&'this mut self) -> BorrowedCursor<'this> { BorrowedCursor { // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its // lifetime covariantly is safe. buf: unsafe { mem::transmute::<&'this mut BorrowedBuf<'a>, &'this mut BorrowedBuf<'this>>( self.buf, ) }, start: self.start, } } /// Returns the available space in the cursor. #[inline] pub fn capacity(&self) -> usize { self.buf.capacity() - self.buf.filled } /// Returns the number of bytes written to this cursor since it was created from a `BorrowedBuf`. /// /// Note that if this cursor is a reborrowed clone of another, then the count returned is the /// count written via either cursor, not the count since the cursor was reborrowed. #[inline] pub fn written(&self) -> usize { self.buf.filled - self.start } /// Returns a shared reference to the initialized portion of the cursor. #[inline] pub fn init_ref(&self) -> &[u8] { // SAFETY: We only slice the initialized part of the buffer, which is always valid unsafe { MaybeUninit::slice_assume_init_ref(&self.buf.buf[self.buf.filled..self.buf.init]) } } /// Returns a mutable reference to the initialized portion of the cursor. #[inline] pub fn init_mut(&mut self) -> &mut [u8] { // SAFETY: We only slice the initialized part of the buffer, which is always valid unsafe { MaybeUninit::slice_assume_init_mut(&mut self.buf.buf[self.buf.filled..self.buf.init]) } } /// Returns a mutable reference to the uninitialized part of the cursor. /// /// It is safe to uninitialize any of these bytes. #[inline] pub fn uninit_mut(&mut self) -> &mut [MaybeUninit<u8>] { &mut self.buf.buf[self.buf.init..] } /// Returns a mutable reference to the whole cursor. /// /// # Safety /// /// The caller must not uninitialize any bytes in the initialized portion of the cursor. #[inline] pub unsafe fn as_mut(&mut self) -> &mut [MaybeUninit<u8>] { &mut self.buf.buf[self.buf.filled..] } /// Advance the cursor by asserting that `n` bytes have been filled. /// /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements. /// /// # Safety /// /// The caller must ensure that the first `n` bytes of the cursor have been properly /// initialised. #[inline] pub unsafe fn advance(&mut self, n: usize) -> &mut Self { self.buf.filled += n; self.buf.init = cmp::max(self.buf.init, self.buf.filled); self } /// Initializes all bytes in the cursor. #[inline] pub fn ensure_init(&mut self) -> &mut Self { let uninit = self.uninit_mut(); // SAFETY: 0 is a valid value for MaybeUninit<u8> and the length matches the allocation // since it is comes from a slice reference. unsafe { ptr::write_bytes(uninit.as_mut_ptr(), 0, uninit.len()); } self.buf.init = self.buf.capacity(); self } /// Asserts that the first `n` unfilled bytes of the cursor are initialized. /// /// `BorrowedBuf` assumes that bytes are never de-initialized, so this method does nothing when /// called with fewer bytes than are already known to be initialized. /// /// # Safety /// /// The caller must ensure that the first `n` bytes of the buffer have already been initialized. #[inline] pub unsafe fn set_init(&mut self, n: usize) -> &mut Self { self.buf.init = cmp::max(self.buf.init, self.buf.filled + n); self } /// Appends data to the cursor, advancing position within its buffer. /// /// # Panics /// /// Panics if `self.capacity()` is less than `buf.len()`. #[inline] pub fn append(&mut self, buf: &[u8]) { assert!(self.capacity() >= buf.len()); // SAFETY: we do not de-initialize any of the elements of the slice unsafe { MaybeUninit::write_slice(&mut self.as_mut()[..buf.len()], buf); } // SAFETY: We just added the entire contents of buf to the filled section. unsafe { self.set_init(buf.len()); } self.buf.filled += buf.len(); } } impl<'a> Write for BorrowedCursor<'a> { fn write(&mut self, buf: &[u8]) -> Result<usize> { self.append(buf); Ok(buf.len()) } fn flush(&mut self) -> Result<()> { Ok(()) } }
random_line_split
readbuf.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License.. use crate::fmt::{self, Debug, Formatter}; use crate::io::{Result, Write}; use crate::mem::{self, MaybeUninit}; use crate::{cmp, ptr}; /// A borrowed byte buffer which is incrementally filled and initialized. /// /// This type is a sort of "double cursor". It tracks three regions in the buffer: a region at the beginning of the /// buffer that has been logically filled with data, a region that has been initialized at some point but not yet /// logically filled, and a region at the end that is fully uninitialized. The filled region is guaranteed to be a /// subset of the initialized region. /// /// In summary, the contents of the buffer can be visualized as: /// ```not_rust /// [ capacity ] /// [ filled | unfilled ] /// [ initialized | uninitialized ] /// ``` /// /// A `BorrowedBuf` is created around some existing data (or capacity for data) via a unique reference /// (`&mut`). The `BorrowedBuf` can be configured (e.g., using `clear` or `set_init`), but cannot be /// directly written. To write into the buffer, use `unfilled` to create a `BorrowedCursor`. The cursor /// has write-only access to the unfilled portion of the buffer (you can think of it as a /// write-only iterator). /// /// The lifetime `'data` is a bound on the lifetime of the underlying data. pub struct BorrowedBuf<'data> { /// The buffer's underlying data. buf: &'data mut [MaybeUninit<u8>], /// The length of `self.buf` which is known to be filled. filled: usize, /// The length of `self.buf` which is known to be initialized. init: usize, } impl Debug for BorrowedBuf<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("BorrowedBuf") .field("init", &self.init) .field("filled", &self.filled) .field("capacity", &self.capacity()) .finish() } } /// Create a new `BorrowedBuf` from a fully initialized slice. impl<'data> From<&'data mut [u8]> for BorrowedBuf<'data> { #[inline] fn from(slice: &'data mut [u8]) -> BorrowedBuf<'data> { let len = slice.len(); BorrowedBuf { // SAFETY: initialized data never becoming uninitialized is an invariant of BorrowedBuf buf: unsafe { (slice as *mut [u8]).as_uninit_slice_mut().unwrap() }, filled: 0, init: len, } } } /// Create a new `BorrowedBuf` from an uninitialized buffer. /// /// Use `set_init` if part of the buffer is known to be already initialized. impl<'data> From<&'data mut [MaybeUninit<u8>]> for BorrowedBuf<'data> { #[inline] fn from(buf: &'data mut [MaybeUninit<u8>]) -> BorrowedBuf<'data> { BorrowedBuf { buf, filled: 0, init: 0 } } } impl<'data> BorrowedBuf<'data> { /// Returns the total capacity of the buffer. #[inline] pub fn capacity(&self) -> usize { self.buf.len() } /// Returns the length of the filled part of the buffer. #[inline] pub fn len(&self) -> usize { self.filled } /// Returns the length of the initialized part of the buffer. #[inline] pub fn init_len(&self) -> usize { self.init } /// Returns a shared reference to the filled portion of the buffer. #[inline] pub fn filled(&self) -> &[u8] { // SAFETY: We only slice the filled part of the buffer, which is always valid unsafe { MaybeUninit::slice_assume_init_ref(&self.buf[0..self.filled]) } } /// Returns a cursor over the unfilled part of the buffer. #[inline] pub fn unfilled<'this>(&'this mut self) -> BorrowedCursor<'this> { BorrowedCursor { start: self.filled, // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its // lifetime covariantly is safe. buf: unsafe { mem::transmute::<&'this mut BorrowedBuf<'data>, &'this mut BorrowedBuf<'this>>(self) }, } } /// Clears the buffer, resetting the filled region to empty. /// /// The number of initialized bytes is not changed, and the contents of the buffer are not modified. #[inline] pub fn clear(&mut self) -> &mut Self { self.filled = 0; self } /// Asserts that the first `n` bytes of the buffer are initialized. /// /// `BorrowedBuf` assumes that bytes are never de-initialized, so this method does nothing when called with fewer /// bytes than are already known to be initialized. /// /// # Safety /// /// The caller must ensure that the first `n` unfilled bytes of the buffer have already been initialized. #[inline] pub unsafe fn set_init(&mut self, n: usize) -> &mut Self { self.init = cmp::max(self.init, n); self } } /// A writeable view of the unfilled portion of a [`BorrowedBuf`](BorrowedBuf). /// /// Provides access to the initialized and uninitialized parts of the underlying `BorrowedBuf`. /// Data can be written directly to the cursor by using [`append`](BorrowedCursor::append) or /// indirectly by getting a slice of part or all of the cursor and writing into the slice. In the /// indirect case, the caller must call [`advance`](BorrowedCursor::advance) after writing to inform /// the cursor how many bytes have been written. /// /// Once data is written to the cursor, it becomes part of the filled portion of the underlying /// `BorrowedBuf` and can no longer be accessed or re-written by the cursor. I.e., the cursor tracks /// the unfilled part of the underlying `BorrowedBuf`. /// /// The lifetime `'a` is a bound on the lifetime of the underlying buffer (which means it is a bound /// on the data in that buffer by transitivity). #[derive(Debug)] pub struct BorrowedCursor<'a> { /// The underlying buffer. // Safety invariant: we treat the type of buf as covariant in the lifetime of `BorrowedBuf` when // we create a `BorrowedCursor`. This is only safe if we never replace `buf` by assigning into // it, so don't do that! buf: &'a mut BorrowedBuf<'a>, /// The length of the filled portion of the underlying buffer at the time of the cursor's /// creation. start: usize, } impl<'a> BorrowedCursor<'a> { /// Reborrow this cursor by cloning it with a smaller lifetime. /// /// Since a cursor maintains unique access to its underlying buffer, the borrowed cursor is /// not accessible while the new cursor exists. #[inline] pub fn reborrow<'this>(&'this mut self) -> BorrowedCursor<'this> { BorrowedCursor { // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its // lifetime covariantly is safe. buf: unsafe { mem::transmute::<&'this mut BorrowedBuf<'a>, &'this mut BorrowedBuf<'this>>( self.buf, ) }, start: self.start, } } /// Returns the available space in the cursor. #[inline] pub fn capacity(&self) -> usize { self.buf.capacity() - self.buf.filled } /// Returns the number of bytes written to this cursor since it was created from a `BorrowedBuf`. /// /// Note that if this cursor is a reborrowed clone of another, then the count returned is the /// count written via either cursor, not the count since the cursor was reborrowed. #[inline] pub fn written(&self) -> usize { self.buf.filled - self.start } /// Returns a shared reference to the initialized portion of the cursor. #[inline] pub fn init_ref(&self) -> &[u8]
/// Returns a mutable reference to the initialized portion of the cursor. #[inline] pub fn init_mut(&mut self) -> &mut [u8] { // SAFETY: We only slice the initialized part of the buffer, which is always valid unsafe { MaybeUninit::slice_assume_init_mut(&mut self.buf.buf[self.buf.filled..self.buf.init]) } } /// Returns a mutable reference to the uninitialized part of the cursor. /// /// It is safe to uninitialize any of these bytes. #[inline] pub fn uninit_mut(&mut self) -> &mut [MaybeUninit<u8>] { &mut self.buf.buf[self.buf.init..] } /// Returns a mutable reference to the whole cursor. /// /// # Safety /// /// The caller must not uninitialize any bytes in the initialized portion of the cursor. #[inline] pub unsafe fn as_mut(&mut self) -> &mut [MaybeUninit<u8>] { &mut self.buf.buf[self.buf.filled..] } /// Advance the cursor by asserting that `n` bytes have been filled. /// /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements. /// /// # Safety /// /// The caller must ensure that the first `n` bytes of the cursor have been properly /// initialised. #[inline] pub unsafe fn advance(&mut self, n: usize) -> &mut Self { self.buf.filled += n; self.buf.init = cmp::max(self.buf.init, self.buf.filled); self } /// Initializes all bytes in the cursor. #[inline] pub fn ensure_init(&mut self) -> &mut Self { let uninit = self.uninit_mut(); // SAFETY: 0 is a valid value for MaybeUninit<u8> and the length matches the allocation // since it is comes from a slice reference. unsafe { ptr::write_bytes(uninit.as_mut_ptr(), 0, uninit.len()); } self.buf.init = self.buf.capacity(); self } /// Asserts that the first `n` unfilled bytes of the cursor are initialized. /// /// `BorrowedBuf` assumes that bytes are never de-initialized, so this method does nothing when /// called with fewer bytes than are already known to be initialized. /// /// # Safety /// /// The caller must ensure that the first `n` bytes of the buffer have already been initialized. #[inline] pub unsafe fn set_init(&mut self, n: usize) -> &mut Self { self.buf.init = cmp::max(self.buf.init, self.buf.filled + n); self } /// Appends data to the cursor, advancing position within its buffer. /// /// # Panics /// /// Panics if `self.capacity()` is less than `buf.len()`. #[inline] pub fn append(&mut self, buf: &[u8]) { assert!(self.capacity() >= buf.len()); // SAFETY: we do not de-initialize any of the elements of the slice unsafe { MaybeUninit::write_slice(&mut self.as_mut()[..buf.len()], buf); } // SAFETY: We just added the entire contents of buf to the filled section. unsafe { self.set_init(buf.len()); } self.buf.filled += buf.len(); } } impl<'a> Write for BorrowedCursor<'a> { fn write(&mut self, buf: &[u8]) -> Result<usize> { self.append(buf); Ok(buf.len()) } fn flush(&mut self) -> Result<()> { Ok(()) } }
{ // SAFETY: We only slice the initialized part of the buffer, which is always valid unsafe { MaybeUninit::slice_assume_init_ref(&self.buf.buf[self.buf.filled..self.buf.init]) } }
identifier_body
readbuf.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License.. use crate::fmt::{self, Debug, Formatter}; use crate::io::{Result, Write}; use crate::mem::{self, MaybeUninit}; use crate::{cmp, ptr}; /// A borrowed byte buffer which is incrementally filled and initialized. /// /// This type is a sort of "double cursor". It tracks three regions in the buffer: a region at the beginning of the /// buffer that has been logically filled with data, a region that has been initialized at some point but not yet /// logically filled, and a region at the end that is fully uninitialized. The filled region is guaranteed to be a /// subset of the initialized region. /// /// In summary, the contents of the buffer can be visualized as: /// ```not_rust /// [ capacity ] /// [ filled | unfilled ] /// [ initialized | uninitialized ] /// ``` /// /// A `BorrowedBuf` is created around some existing data (or capacity for data) via a unique reference /// (`&mut`). The `BorrowedBuf` can be configured (e.g., using `clear` or `set_init`), but cannot be /// directly written. To write into the buffer, use `unfilled` to create a `BorrowedCursor`. The cursor /// has write-only access to the unfilled portion of the buffer (you can think of it as a /// write-only iterator). /// /// The lifetime `'data` is a bound on the lifetime of the underlying data. pub struct BorrowedBuf<'data> { /// The buffer's underlying data. buf: &'data mut [MaybeUninit<u8>], /// The length of `self.buf` which is known to be filled. filled: usize, /// The length of `self.buf` which is known to be initialized. init: usize, } impl Debug for BorrowedBuf<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("BorrowedBuf") .field("init", &self.init) .field("filled", &self.filled) .field("capacity", &self.capacity()) .finish() } } /// Create a new `BorrowedBuf` from a fully initialized slice. impl<'data> From<&'data mut [u8]> for BorrowedBuf<'data> { #[inline] fn from(slice: &'data mut [u8]) -> BorrowedBuf<'data> { let len = slice.len(); BorrowedBuf { // SAFETY: initialized data never becoming uninitialized is an invariant of BorrowedBuf buf: unsafe { (slice as *mut [u8]).as_uninit_slice_mut().unwrap() }, filled: 0, init: len, } } } /// Create a new `BorrowedBuf` from an uninitialized buffer. /// /// Use `set_init` if part of the buffer is known to be already initialized. impl<'data> From<&'data mut [MaybeUninit<u8>]> for BorrowedBuf<'data> { #[inline] fn from(buf: &'data mut [MaybeUninit<u8>]) -> BorrowedBuf<'data> { BorrowedBuf { buf, filled: 0, init: 0 } } } impl<'data> BorrowedBuf<'data> { /// Returns the total capacity of the buffer. #[inline] pub fn capacity(&self) -> usize { self.buf.len() } /// Returns the length of the filled part of the buffer. #[inline] pub fn len(&self) -> usize { self.filled } /// Returns the length of the initialized part of the buffer. #[inline] pub fn init_len(&self) -> usize { self.init } /// Returns a shared reference to the filled portion of the buffer. #[inline] pub fn filled(&self) -> &[u8] { // SAFETY: We only slice the filled part of the buffer, which is always valid unsafe { MaybeUninit::slice_assume_init_ref(&self.buf[0..self.filled]) } } /// Returns a cursor over the unfilled part of the buffer. #[inline] pub fn unfilled<'this>(&'this mut self) -> BorrowedCursor<'this> { BorrowedCursor { start: self.filled, // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its // lifetime covariantly is safe. buf: unsafe { mem::transmute::<&'this mut BorrowedBuf<'data>, &'this mut BorrowedBuf<'this>>(self) }, } } /// Clears the buffer, resetting the filled region to empty. /// /// The number of initialized bytes is not changed, and the contents of the buffer are not modified. #[inline] pub fn clear(&mut self) -> &mut Self { self.filled = 0; self } /// Asserts that the first `n` bytes of the buffer are initialized. /// /// `BorrowedBuf` assumes that bytes are never de-initialized, so this method does nothing when called with fewer /// bytes than are already known to be initialized. /// /// # Safety /// /// The caller must ensure that the first `n` unfilled bytes of the buffer have already been initialized. #[inline] pub unsafe fn set_init(&mut self, n: usize) -> &mut Self { self.init = cmp::max(self.init, n); self } } /// A writeable view of the unfilled portion of a [`BorrowedBuf`](BorrowedBuf). /// /// Provides access to the initialized and uninitialized parts of the underlying `BorrowedBuf`. /// Data can be written directly to the cursor by using [`append`](BorrowedCursor::append) or /// indirectly by getting a slice of part or all of the cursor and writing into the slice. In the /// indirect case, the caller must call [`advance`](BorrowedCursor::advance) after writing to inform /// the cursor how many bytes have been written. /// /// Once data is written to the cursor, it becomes part of the filled portion of the underlying /// `BorrowedBuf` and can no longer be accessed or re-written by the cursor. I.e., the cursor tracks /// the unfilled part of the underlying `BorrowedBuf`. /// /// The lifetime `'a` is a bound on the lifetime of the underlying buffer (which means it is a bound /// on the data in that buffer by transitivity). #[derive(Debug)] pub struct BorrowedCursor<'a> { /// The underlying buffer. // Safety invariant: we treat the type of buf as covariant in the lifetime of `BorrowedBuf` when // we create a `BorrowedCursor`. This is only safe if we never replace `buf` by assigning into // it, so don't do that! buf: &'a mut BorrowedBuf<'a>, /// The length of the filled portion of the underlying buffer at the time of the cursor's /// creation. start: usize, } impl<'a> BorrowedCursor<'a> { /// Reborrow this cursor by cloning it with a smaller lifetime. /// /// Since a cursor maintains unique access to its underlying buffer, the borrowed cursor is /// not accessible while the new cursor exists. #[inline] pub fn reborrow<'this>(&'this mut self) -> BorrowedCursor<'this> { BorrowedCursor { // SAFETY: we never assign into `BorrowedCursor::buf`, so treating its // lifetime covariantly is safe. buf: unsafe { mem::transmute::<&'this mut BorrowedBuf<'a>, &'this mut BorrowedBuf<'this>>( self.buf, ) }, start: self.start, } } /// Returns the available space in the cursor. #[inline] pub fn capacity(&self) -> usize { self.buf.capacity() - self.buf.filled } /// Returns the number of bytes written to this cursor since it was created from a `BorrowedBuf`. /// /// Note that if this cursor is a reborrowed clone of another, then the count returned is the /// count written via either cursor, not the count since the cursor was reborrowed. #[inline] pub fn written(&self) -> usize { self.buf.filled - self.start } /// Returns a shared reference to the initialized portion of the cursor. #[inline] pub fn init_ref(&self) -> &[u8] { // SAFETY: We only slice the initialized part of the buffer, which is always valid unsafe { MaybeUninit::slice_assume_init_ref(&self.buf.buf[self.buf.filled..self.buf.init]) } } /// Returns a mutable reference to the initialized portion of the cursor. #[inline] pub fn init_mut(&mut self) -> &mut [u8] { // SAFETY: We only slice the initialized part of the buffer, which is always valid unsafe { MaybeUninit::slice_assume_init_mut(&mut self.buf.buf[self.buf.filled..self.buf.init]) } } /// Returns a mutable reference to the uninitialized part of the cursor. /// /// It is safe to uninitialize any of these bytes. #[inline] pub fn uninit_mut(&mut self) -> &mut [MaybeUninit<u8>] { &mut self.buf.buf[self.buf.init..] } /// Returns a mutable reference to the whole cursor. /// /// # Safety /// /// The caller must not uninitialize any bytes in the initialized portion of the cursor. #[inline] pub unsafe fn as_mut(&mut self) -> &mut [MaybeUninit<u8>] { &mut self.buf.buf[self.buf.filled..] } /// Advance the cursor by asserting that `n` bytes have been filled. /// /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements /// and its unfilled portion (and the capacity of this cursor) shrinks by `n` elements. /// /// # Safety /// /// The caller must ensure that the first `n` bytes of the cursor have been properly /// initialised. #[inline] pub unsafe fn advance(&mut self, n: usize) -> &mut Self { self.buf.filled += n; self.buf.init = cmp::max(self.buf.init, self.buf.filled); self } /// Initializes all bytes in the cursor. #[inline] pub fn ensure_init(&mut self) -> &mut Self { let uninit = self.uninit_mut(); // SAFETY: 0 is a valid value for MaybeUninit<u8> and the length matches the allocation // since it is comes from a slice reference. unsafe { ptr::write_bytes(uninit.as_mut_ptr(), 0, uninit.len()); } self.buf.init = self.buf.capacity(); self } /// Asserts that the first `n` unfilled bytes of the cursor are initialized. /// /// `BorrowedBuf` assumes that bytes are never de-initialized, so this method does nothing when /// called with fewer bytes than are already known to be initialized. /// /// # Safety /// /// The caller must ensure that the first `n` bytes of the buffer have already been initialized. #[inline] pub unsafe fn set_init(&mut self, n: usize) -> &mut Self { self.buf.init = cmp::max(self.buf.init, self.buf.filled + n); self } /// Appends data to the cursor, advancing position within its buffer. /// /// # Panics /// /// Panics if `self.capacity()` is less than `buf.len()`. #[inline] pub fn append(&mut self, buf: &[u8]) { assert!(self.capacity() >= buf.len()); // SAFETY: we do not de-initialize any of the elements of the slice unsafe { MaybeUninit::write_slice(&mut self.as_mut()[..buf.len()], buf); } // SAFETY: We just added the entire contents of buf to the filled section. unsafe { self.set_init(buf.len()); } self.buf.filled += buf.len(); } } impl<'a> Write for BorrowedCursor<'a> { fn
(&mut self, buf: &[u8]) -> Result<usize> { self.append(buf); Ok(buf.len()) } fn flush(&mut self) -> Result<()> { Ok(()) } }
write
identifier_name
shadow_logger.rs
use std::cell::RefCell; use std::sync::mpsc::{Receiver, Sender}; use std::sync::Arc; use std::sync::{Mutex, RwLock}; use std::time::Duration; use crossbeam::queue::ArrayQueue; use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; use logger as c_log; use once_cell::sync::{Lazy, OnceCell}; use shadow_shim_helper_rs::emulated_time::EmulatedTime; use shadow_shim_helper_rs::util::time::TimeParts; use crate::core::worker::Worker; use crate::host::host::HostInfo; /// Trigger an asynchronous flush when this many lines are queued. const ASYNC_FLUSH_QD_LINES_THRESHOLD: usize = 100_000; /// Performs a *synchronous* flush when this many lines are queued. i.e. if /// after reaching the `ASYNC_FLUSH_QD_LINES_THRESHOLD`, log lines are still /// coming in faster than they can actually be flushed, when we reach this limit /// we'll pause and let it finish flushing rather than letting the queue /// continue growing. const SYNC_FLUSH_QD_LINES_THRESHOLD: usize = 10 * ASYNC_FLUSH_QD_LINES_THRESHOLD; /// Logging thread flushes at least this often. const MIN_FLUSH_FREQUENCY: Duration = Duration::from_secs(10); static SHADOW_LOGGER: Lazy<ShadowLogger> = Lazy::new(ShadowLogger::new); /// Initialize the Shadow logger. pub fn init(max_log_level: LevelFilter, log_errors_to_stderr: bool) -> Result<(), SetLoggerError> { SHADOW_LOGGER.set_max_level(max_log_level); SHADOW_LOGGER.set_log_errors_to_stderr(log_errors_to_stderr); log::set_logger(&*SHADOW_LOGGER)?; // Shadow's logger has its own logic for deciding the max level (see `ShadowLogger::enabled`), // so the log crate should give us all log messages and we can decide whether to show it or not. log::set_max_level(log::LevelFilter::Trace); // Start the thread that will receive log records and flush them to output. std::thread::Builder::new() .name("shadow-logger".to_string()) .spawn(move || SHADOW_LOGGER.logger_thread_fn()) .unwrap(); // Arrange to flush the logger on panic. let default_panic_handler = std::panic::take_hook(); std::panic::set_hook(Box::new(move |panic_info| { // Attempt to flush the logger. We want to avoid a recursive panic, so // we flush the queue on the current thread instead of trying to send // a command to the logger thread (because our thread-local sender // may have already been destructed, and because the logger thread // itself may be in a bad state), and ignore errors. SHADOW_LOGGER.flush_records(None).ok(); default_panic_handler(panic_info); })); Ok(()) } /// A logger specialized for Shadow. It attaches simulation context to log /// entries (e.g. sim time, running process, etc.). It's also designed for /// high performance to accomodate heavy logging from multiple threads. pub struct ShadowLogger { // Channel used to send commands to the logger's thread. // // The Sender half of a channel isn't Sync, so we must protect it with a // Mutex to make ShadowLogger be Sync. This is only accessed once per // thread, though, to clone into the thread-local SENDER. command_sender: Mutex<Sender<LoggerCommand>>, // Like the sender, needs a Mutex for ShadowLogger to be Sync. // The Mutex is only locked once though by the logger thread, which keeps // it locked for as long as it's running. command_receiver: Mutex<Receiver<LoggerCommand>>, // A lock-free queue for individual log records. We don't put the records // themselves in the `command_sender`, because `Sender` doesn't support // getting the queue length. Conversely we don't put commands in this queue // because it doesn't support blocking operations. // // The size is roughly SYNC_FLUSH_QD_LINES_THRESHOLD * // size_of<ShadowLogRecord>; we might want to consider SegQueue (which grows // and shrinks dynamically) instead if we ever make SYNC_FLUSH_QD_LINES_THRESHOLD very // large. records: ArrayQueue<ShadowLogRecord>, // When false, sends a (still-asynchronous) flush command to the logger // thread every time a record is pushed into `records`. buffering_enabled: RwLock<bool>, // The maximum log level, unless overridden by a host-specific log level. max_log_level: OnceCell<LevelFilter>, // Whether to log errors to stderr in addition to stdout. log_errors_to_stderr: OnceCell<bool>, } thread_local!(static SENDER: RefCell<Option<Sender<LoggerCommand>>> = RefCell::new(None)); thread_local!(static THREAD_NAME: Lazy<String> = Lazy::new(|| { get_thread_name() })); thread_local!(static THREAD_ID: Lazy<nix::unistd::Pid> = Lazy::new(|| { nix::unistd::gettid() })); fn get_thread_name() -> String { let mut thread_name = Vec::<i8>::with_capacity(16); let res = unsafe { thread_name.set_len(thread_name.capacity()); // ~infallible when host_name is at least 16 bytes. libc::pthread_getname_np( libc::pthread_self(), thread_name.as_mut_ptr(), thread_name.len(), ) }; // The most likely cause of failure is a bug in the caller. debug_assert_eq!(res, 0, "pthread_getname_np: {}", nix::errno::from_i32(res)); if res == 0 { // SAFETY: We just initialized the input buffer `thread_name`, and // `thread_name_cstr` won't outlive it. let thread_name_cstr = unsafe { std::ffi::CStr::from_ptr(thread_name.as_ptr()) }; return thread_name_cstr.to_owned().to_string_lossy().to_string(); } // Another potential reason for failure is if it couldn't open // /proc/self/task/[tid]/comm. We're probably in a bad state anyway if that // happens, but try to recover anyway. // Empty string String::new() } impl ShadowLogger { fn new() -> ShadowLogger { let (sender, receiver) = std::sync::mpsc::channel(); ShadowLogger { records: ArrayQueue::new(SYNC_FLUSH_QD_LINES_THRESHOLD), command_sender: Mutex::new(sender), command_receiver: Mutex::new(receiver), buffering_enabled: RwLock::new(false), max_log_level: OnceCell::new(), log_errors_to_stderr: OnceCell::new(), } } // Function executed by the logger's helper thread, onto which we offload as // much work as we can. fn logger_thread_fn(&self) { let command_receiver = self.command_receiver.lock().unwrap(); loop { use std::sync::mpsc::RecvTimeoutError; match command_receiver.recv_timeout(MIN_FLUSH_FREQUENCY) { Ok(LoggerCommand::Flush(done_sender)) => self.flush_records(done_sender).unwrap(), Err(RecvTimeoutError::Timeout) => { // Flush self.flush_records(None).unwrap(); } Err(e) => panic!("Unexpected error {}", e), } } } // Function called by the logger's helper thread to flush the contents of // self.records. If `done_sender` is provided, it's notified after the flush // has completed. fn flush_records(&self, done_sender: Option<Sender<()>>) -> std::io::Result<()> { use std::io::Write; // Only flush records that are already in the queue, not ones that // arrive while we're flushing. Otherwise callers who perform a // synchronous flush (whether this flush operation or another one that // arrives while we're flushing) will be left waiting longer than // necessary. Also keeps us from holding the stdout lock indefinitely. let mut toflush = self.records.len(); let stdout_unlocked = std::io::stdout(); let stdout_locked = stdout_unlocked.lock(); let mut stdout = std::io::BufWriter::new(stdout_locked); while toflush > 0 { let record = match self.records.pop() { Some(r) => r, None => { // This can happen if another thread panics while the // logging thread is flushing. In that case both threads // will be consuming from the queue. break; } }; toflush -= 1; if record.level <= Level::Error && *self.log_errors_to_stderr.get().unwrap() { // Send to both stdout and stderr. let stderr_unlocked = std::io::stderr(); let stderr_locked = stderr_unlocked.lock(); let mut stderr = std::io::BufWriter::new(stderr_locked); let line = format!("{record}"); write!(stdout, "{line}")?; write!(stderr, "{line}")?; } else { write!(stdout, "{record}")?; } } if let Some(done_sender) = done_sender { // We can't log from this thread without risking deadlock, so in the // unlikely case that the calling thread has gone away, just print // directly. done_sender.send(()).unwrap_or_else(|e| { println!( "WARNING: Logger couldn't notify calling thread: {:?}", e ) }); } Ok(()) } /// When disabled, the logger thread is notified to write each record as /// soon as it's created. The calling thread still isn't blocked on the /// record actually being written, though. pub fn set_buffering_enabled(&self, buffering_enabled: bool) { let mut writer = self.buffering_enabled.write().unwrap(); *writer = buffering_enabled; } /// If the maximum log level has not yet been set, returns `LevelFilter::Trace`. pub fn max_level(&self) -> LevelFilter { self.max_log_level .get() .copied() .unwrap_or(LevelFilter::Trace) } /// Set the default maximum log level, but this can be overridden per-host. Is only intended to /// be called from `init()`. Will panic if called more than once. fn set_max_level(&self, level: LevelFilter) { self.max_log_level.set(level).unwrap() } /// Set whether to log errors to stderr in addition to stdout. /// /// Is only intended to be called from `init()`. Will panic if called more /// than once. fn set_log_errors_to_stderr(&self, val: bool) { self.log_errors_to_stderr.set(val).unwrap() } // Send a flush command to the logger thread. fn flush_impl(&self, notify_done: Option<Sender<()>>) { self.send_command(LoggerCommand::Flush(notify_done)) } // Send a flush command to the logger thread and block until it's completed. fn flush_sync(&self) { let (done_sender, done_receiver) = std::sync::mpsc::channel(); self.flush_impl(Some(done_sender)); done_receiver.recv().unwrap(); } // Send a flush command to the logger thread. fn flush_async(&self) { self.flush_impl(None); } // Send a command to the logger thread. fn send_command(&self, cmd: LoggerCommand) { SENDER .try_with(|thread_sender| { if thread_sender.borrow().is_none() { let lock = self.command_sender.lock().unwrap(); *thread_sender.borrow_mut() = Some(lock.clone()); } thread_sender .borrow() .as_ref() .unwrap() .send(cmd) .unwrap_or_else(|e| { println!("WARNING: Couldn't send command to logger thread: {:?}", e); }); }) .unwrap_or_else(|e| { println!( "WARNING: Couldn't get sender channel to logger thread: {:?}", e ); }); } } impl Log for ShadowLogger { fn enabled(&self, metadata: &Metadata) -> bool { let filter = match Worker::with_active_host(|host| host.info().log_level) { Some(Some(level)) => level, _ => self.max_level(), }; metadata.level() <= filter } fn log(&self, record: &Record) { if!self.enabled(record.metadata()) { return; } let message = std::fmt::format(*record.args()); let host_info = Worker::with_active_host(|host| host.info().clone()); let mut shadowrecord = ShadowLogRecord { level: record.level(), file: record.file_static(), module_path: record.module_path_static(), line: record.line(), message, wall_time: Duration::from_micros(unsafe { u64::try_from(c_log::logger_elapsed_micros()).unwrap() }), emu_time: Worker::current_time(), thread_name: THREAD_NAME .try_with(|name| (*name).clone()) .unwrap_or_else(|_| get_thread_name()), thread_id: THREAD_ID .try_with(|id| **id) .unwrap_or_else(|_| nix::unistd::gettid()), host_info, }; loop { match self.records.push(shadowrecord) { Ok(()) => break, Err(r) => { // Queue is full. Flush it and try again. shadowrecord = r; self.flush_sync(); } } } if record.level() == Level::Error { // Unlike in Shadow's C code, we don't abort the program on Error // logs. In Rust the same purpose is filled with `panic` and // `unwrap`. C callers will still exit or abort via the lib/logger wrapper. // // Flush *synchronously*, since we're likely about to crash one way or another. self.flush_sync(); } else if self.records.len() > ASYNC_FLUSH_QD_LINES_THRESHOLD ||!*self.buffering_enabled.read().unwrap() { self.flush_async(); } } fn flush(&self) { self.flush_sync(); } } struct ShadowLogRecord { level: Level, file: Option<&'static str>, module_path: Option<&'static str>, line: Option<u32>, message: String, wall_time: Duration, emu_time: Option<EmulatedTime>, thread_name: String, thread_id: nix::unistd::Pid, host_info: Option<Arc<HostInfo>>, } impl std::fmt::Display for ShadowLogRecord { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { { let parts = TimeParts::from_nanos(self.wall_time.as_nanos()); write!( f, "{:02}:{:02}:{:02}.{:06}", parts.hours, parts.mins, parts.secs, parts.nanos / 1000 )?; } write!(f, " [{}:{}]", self.thread_id, self.thread_name)?; if let Some(emu_time) = self.emu_time { let sim_time = emu_time.duration_since(&EmulatedTime::SIMULATION_START); let parts = TimeParts::from_nanos(sim_time.as_nanos()); write!( f, " {:02}:{:02}:{:02}.{:09}", parts.hours, parts.mins, parts.secs, parts.nanos )?; } else { write!(f, " n/a")?; } write!(f, " [{level}]", level = self.level)?; if let Some(host) = &self.host_info { write!( f, " [{hostname}:{ip}]", hostname = host.name, ip = host.default_ip, )?; } else { write!(f, " [n/a]",)?; } write!( f, " [{file}:", file = self .file .map(|f| if let Some(sep_pos) = f.rfind('/') { &f[(sep_pos + 1)..] } else { f }) .unwrap_or("n/a"), )?; if let Some(line) = self.line { write!(f, "{line}", line = line)?; } else { write!(f, "n/a")?; } writeln!( f, "] [{module}] {msg}", module = self.module_path.unwrap_or("n/a"), msg = self.message )?; Ok(()) } } enum LoggerCommand { // Flush; takes an optional one-shot channel to notify that the flush has completed. Flush(Option<Sender<()>>), } pub fn set_buffering_enabled(buffering_enabled: bool) { SHADOW_LOGGER.set_buffering_enabled(buffering_enabled); } mod export { use super::*; /// When disabled, the logger thread is notified to write each record as /// soon as it's created. The calling thread still isn't blocked on the /// record actually being written, though. #[no_mangle] pub unsafe extern "C" fn shadow_logger_setEnableBuffering(buffering_enabled: i32)
}
{ set_buffering_enabled(buffering_enabled != 0) }
identifier_body
shadow_logger.rs
use std::cell::RefCell; use std::sync::mpsc::{Receiver, Sender}; use std::sync::Arc; use std::sync::{Mutex, RwLock}; use std::time::Duration; use crossbeam::queue::ArrayQueue; use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; use logger as c_log; use once_cell::sync::{Lazy, OnceCell}; use shadow_shim_helper_rs::emulated_time::EmulatedTime; use shadow_shim_helper_rs::util::time::TimeParts; use crate::core::worker::Worker; use crate::host::host::HostInfo; /// Trigger an asynchronous flush when this many lines are queued. const ASYNC_FLUSH_QD_LINES_THRESHOLD: usize = 100_000; /// Performs a *synchronous* flush when this many lines are queued. i.e. if /// after reaching the `ASYNC_FLUSH_QD_LINES_THRESHOLD`, log lines are still /// coming in faster than they can actually be flushed, when we reach this limit /// we'll pause and let it finish flushing rather than letting the queue /// continue growing. const SYNC_FLUSH_QD_LINES_THRESHOLD: usize = 10 * ASYNC_FLUSH_QD_LINES_THRESHOLD; /// Logging thread flushes at least this often. const MIN_FLUSH_FREQUENCY: Duration = Duration::from_secs(10); static SHADOW_LOGGER: Lazy<ShadowLogger> = Lazy::new(ShadowLogger::new); /// Initialize the Shadow logger. pub fn init(max_log_level: LevelFilter, log_errors_to_stderr: bool) -> Result<(), SetLoggerError> { SHADOW_LOGGER.set_max_level(max_log_level); SHADOW_LOGGER.set_log_errors_to_stderr(log_errors_to_stderr); log::set_logger(&*SHADOW_LOGGER)?; // Shadow's logger has its own logic for deciding the max level (see `ShadowLogger::enabled`), // so the log crate should give us all log messages and we can decide whether to show it or not. log::set_max_level(log::LevelFilter::Trace); // Start the thread that will receive log records and flush them to output. std::thread::Builder::new() .name("shadow-logger".to_string()) .spawn(move || SHADOW_LOGGER.logger_thread_fn()) .unwrap(); // Arrange to flush the logger on panic. let default_panic_handler = std::panic::take_hook(); std::panic::set_hook(Box::new(move |panic_info| { // Attempt to flush the logger. We want to avoid a recursive panic, so // we flush the queue on the current thread instead of trying to send // a command to the logger thread (because our thread-local sender // may have already been destructed, and because the logger thread // itself may be in a bad state), and ignore errors. SHADOW_LOGGER.flush_records(None).ok(); default_panic_handler(panic_info); })); Ok(()) } /// A logger specialized for Shadow. It attaches simulation context to log /// entries (e.g. sim time, running process, etc.). It's also designed for /// high performance to accomodate heavy logging from multiple threads. pub struct ShadowLogger { // Channel used to send commands to the logger's thread. // // The Sender half of a channel isn't Sync, so we must protect it with a // Mutex to make ShadowLogger be Sync. This is only accessed once per // thread, though, to clone into the thread-local SENDER. command_sender: Mutex<Sender<LoggerCommand>>, // Like the sender, needs a Mutex for ShadowLogger to be Sync. // The Mutex is only locked once though by the logger thread, which keeps // it locked for as long as it's running. command_receiver: Mutex<Receiver<LoggerCommand>>, // A lock-free queue for individual log records. We don't put the records // themselves in the `command_sender`, because `Sender` doesn't support // getting the queue length. Conversely we don't put commands in this queue // because it doesn't support blocking operations. // // The size is roughly SYNC_FLUSH_QD_LINES_THRESHOLD * // size_of<ShadowLogRecord>; we might want to consider SegQueue (which grows // and shrinks dynamically) instead if we ever make SYNC_FLUSH_QD_LINES_THRESHOLD very // large. records: ArrayQueue<ShadowLogRecord>, // When false, sends a (still-asynchronous) flush command to the logger // thread every time a record is pushed into `records`. buffering_enabled: RwLock<bool>, // The maximum log level, unless overridden by a host-specific log level. max_log_level: OnceCell<LevelFilter>, // Whether to log errors to stderr in addition to stdout. log_errors_to_stderr: OnceCell<bool>, } thread_local!(static SENDER: RefCell<Option<Sender<LoggerCommand>>> = RefCell::new(None)); thread_local!(static THREAD_NAME: Lazy<String> = Lazy::new(|| { get_thread_name() })); thread_local!(static THREAD_ID: Lazy<nix::unistd::Pid> = Lazy::new(|| { nix::unistd::gettid() })); fn get_thread_name() -> String { let mut thread_name = Vec::<i8>::with_capacity(16); let res = unsafe { thread_name.set_len(thread_name.capacity()); // ~infallible when host_name is at least 16 bytes. libc::pthread_getname_np( libc::pthread_self(), thread_name.as_mut_ptr(), thread_name.len(), ) }; // The most likely cause of failure is a bug in the caller. debug_assert_eq!(res, 0, "pthread_getname_np: {}", nix::errno::from_i32(res)); if res == 0 { // SAFETY: We just initialized the input buffer `thread_name`, and // `thread_name_cstr` won't outlive it. let thread_name_cstr = unsafe { std::ffi::CStr::from_ptr(thread_name.as_ptr()) }; return thread_name_cstr.to_owned().to_string_lossy().to_string(); } // Another potential reason for failure is if it couldn't open // /proc/self/task/[tid]/comm. We're probably in a bad state anyway if that // happens, but try to recover anyway. // Empty string String::new() } impl ShadowLogger { fn new() -> ShadowLogger { let (sender, receiver) = std::sync::mpsc::channel(); ShadowLogger { records: ArrayQueue::new(SYNC_FLUSH_QD_LINES_THRESHOLD), command_sender: Mutex::new(sender), command_receiver: Mutex::new(receiver), buffering_enabled: RwLock::new(false), max_log_level: OnceCell::new(), log_errors_to_stderr: OnceCell::new(), } } // Function executed by the logger's helper thread, onto which we offload as // much work as we can. fn logger_thread_fn(&self) { let command_receiver = self.command_receiver.lock().unwrap(); loop { use std::sync::mpsc::RecvTimeoutError; match command_receiver.recv_timeout(MIN_FLUSH_FREQUENCY) { Ok(LoggerCommand::Flush(done_sender)) => self.flush_records(done_sender).unwrap(), Err(RecvTimeoutError::Timeout) => { // Flush self.flush_records(None).unwrap(); } Err(e) => panic!("Unexpected error {}", e), } } } // Function called by the logger's helper thread to flush the contents of // self.records. If `done_sender` is provided, it's notified after the flush // has completed. fn flush_records(&self, done_sender: Option<Sender<()>>) -> std::io::Result<()> { use std::io::Write; // Only flush records that are already in the queue, not ones that // arrive while we're flushing. Otherwise callers who perform a // synchronous flush (whether this flush operation or another one that // arrives while we're flushing) will be left waiting longer than // necessary. Also keeps us from holding the stdout lock indefinitely. let mut toflush = self.records.len(); let stdout_unlocked = std::io::stdout(); let stdout_locked = stdout_unlocked.lock(); let mut stdout = std::io::BufWriter::new(stdout_locked); while toflush > 0 { let record = match self.records.pop() { Some(r) => r, None => { // This can happen if another thread panics while the // logging thread is flushing. In that case both threads // will be consuming from the queue. break; } }; toflush -= 1; if record.level <= Level::Error && *self.log_errors_to_stderr.get().unwrap() { // Send to both stdout and stderr. let stderr_unlocked = std::io::stderr(); let stderr_locked = stderr_unlocked.lock(); let mut stderr = std::io::BufWriter::new(stderr_locked); let line = format!("{record}"); write!(stdout, "{line}")?; write!(stderr, "{line}")?; } else { write!(stdout, "{record}")?; } } if let Some(done_sender) = done_sender { // We can't log from this thread without risking deadlock, so in the // unlikely case that the calling thread has gone away, just print // directly. done_sender.send(()).unwrap_or_else(|e| { println!( "WARNING: Logger couldn't notify calling thread: {:?}", e ) }); } Ok(()) } /// When disabled, the logger thread is notified to write each record as /// soon as it's created. The calling thread still isn't blocked on the /// record actually being written, though. pub fn set_buffering_enabled(&self, buffering_enabled: bool) { let mut writer = self.buffering_enabled.write().unwrap(); *writer = buffering_enabled; } /// If the maximum log level has not yet been set, returns `LevelFilter::Trace`. pub fn max_level(&self) -> LevelFilter { self.max_log_level .get() .copied() .unwrap_or(LevelFilter::Trace) } /// Set the default maximum log level, but this can be overridden per-host. Is only intended to /// be called from `init()`. Will panic if called more than once. fn set_max_level(&self, level: LevelFilter) { self.max_log_level.set(level).unwrap() } /// Set whether to log errors to stderr in addition to stdout. /// /// Is only intended to be called from `init()`. Will panic if called more /// than once. fn set_log_errors_to_stderr(&self, val: bool) { self.log_errors_to_stderr.set(val).unwrap() } // Send a flush command to the logger thread. fn flush_impl(&self, notify_done: Option<Sender<()>>) { self.send_command(LoggerCommand::Flush(notify_done)) } // Send a flush command to the logger thread and block until it's completed. fn flush_sync(&self) { let (done_sender, done_receiver) = std::sync::mpsc::channel(); self.flush_impl(Some(done_sender)); done_receiver.recv().unwrap(); } // Send a flush command to the logger thread. fn flush_async(&self) { self.flush_impl(None); } // Send a command to the logger thread. fn send_command(&self, cmd: LoggerCommand) { SENDER .try_with(|thread_sender| { if thread_sender.borrow().is_none() { let lock = self.command_sender.lock().unwrap(); *thread_sender.borrow_mut() = Some(lock.clone()); } thread_sender .borrow() .as_ref() .unwrap() .send(cmd) .unwrap_or_else(|e| { println!("WARNING: Couldn't send command to logger thread: {:?}", e); }); }) .unwrap_or_else(|e| { println!( "WARNING: Couldn't get sender channel to logger thread: {:?}", e ); }); } } impl Log for ShadowLogger { fn
(&self, metadata: &Metadata) -> bool { let filter = match Worker::with_active_host(|host| host.info().log_level) { Some(Some(level)) => level, _ => self.max_level(), }; metadata.level() <= filter } fn log(&self, record: &Record) { if!self.enabled(record.metadata()) { return; } let message = std::fmt::format(*record.args()); let host_info = Worker::with_active_host(|host| host.info().clone()); let mut shadowrecord = ShadowLogRecord { level: record.level(), file: record.file_static(), module_path: record.module_path_static(), line: record.line(), message, wall_time: Duration::from_micros(unsafe { u64::try_from(c_log::logger_elapsed_micros()).unwrap() }), emu_time: Worker::current_time(), thread_name: THREAD_NAME .try_with(|name| (*name).clone()) .unwrap_or_else(|_| get_thread_name()), thread_id: THREAD_ID .try_with(|id| **id) .unwrap_or_else(|_| nix::unistd::gettid()), host_info, }; loop { match self.records.push(shadowrecord) { Ok(()) => break, Err(r) => { // Queue is full. Flush it and try again. shadowrecord = r; self.flush_sync(); } } } if record.level() == Level::Error { // Unlike in Shadow's C code, we don't abort the program on Error // logs. In Rust the same purpose is filled with `panic` and // `unwrap`. C callers will still exit or abort via the lib/logger wrapper. // // Flush *synchronously*, since we're likely about to crash one way or another. self.flush_sync(); } else if self.records.len() > ASYNC_FLUSH_QD_LINES_THRESHOLD ||!*self.buffering_enabled.read().unwrap() { self.flush_async(); } } fn flush(&self) { self.flush_sync(); } } struct ShadowLogRecord { level: Level, file: Option<&'static str>, module_path: Option<&'static str>, line: Option<u32>, message: String, wall_time: Duration, emu_time: Option<EmulatedTime>, thread_name: String, thread_id: nix::unistd::Pid, host_info: Option<Arc<HostInfo>>, } impl std::fmt::Display for ShadowLogRecord { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { { let parts = TimeParts::from_nanos(self.wall_time.as_nanos()); write!( f, "{:02}:{:02}:{:02}.{:06}", parts.hours, parts.mins, parts.secs, parts.nanos / 1000 )?; } write!(f, " [{}:{}]", self.thread_id, self.thread_name)?; if let Some(emu_time) = self.emu_time { let sim_time = emu_time.duration_since(&EmulatedTime::SIMULATION_START); let parts = TimeParts::from_nanos(sim_time.as_nanos()); write!( f, " {:02}:{:02}:{:02}.{:09}", parts.hours, parts.mins, parts.secs, parts.nanos )?; } else { write!(f, " n/a")?; } write!(f, " [{level}]", level = self.level)?; if let Some(host) = &self.host_info { write!( f, " [{hostname}:{ip}]", hostname = host.name, ip = host.default_ip, )?; } else { write!(f, " [n/a]",)?; } write!( f, " [{file}:", file = self .file .map(|f| if let Some(sep_pos) = f.rfind('/') { &f[(sep_pos + 1)..] } else { f }) .unwrap_or("n/a"), )?; if let Some(line) = self.line { write!(f, "{line}", line = line)?; } else { write!(f, "n/a")?; } writeln!( f, "] [{module}] {msg}", module = self.module_path.unwrap_or("n/a"), msg = self.message )?; Ok(()) } } enum LoggerCommand { // Flush; takes an optional one-shot channel to notify that the flush has completed. Flush(Option<Sender<()>>), } pub fn set_buffering_enabled(buffering_enabled: bool) { SHADOW_LOGGER.set_buffering_enabled(buffering_enabled); } mod export { use super::*; /// When disabled, the logger thread is notified to write each record as /// soon as it's created. The calling thread still isn't blocked on the /// record actually being written, though. #[no_mangle] pub unsafe extern "C" fn shadow_logger_setEnableBuffering(buffering_enabled: i32) { set_buffering_enabled(buffering_enabled!= 0) } }
enabled
identifier_name
shadow_logger.rs
use std::cell::RefCell; use std::sync::mpsc::{Receiver, Sender}; use std::sync::Arc; use std::sync::{Mutex, RwLock}; use std::time::Duration; use crossbeam::queue::ArrayQueue; use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError}; use logger as c_log; use once_cell::sync::{Lazy, OnceCell}; use shadow_shim_helper_rs::emulated_time::EmulatedTime; use shadow_shim_helper_rs::util::time::TimeParts; use crate::core::worker::Worker; use crate::host::host::HostInfo; /// Trigger an asynchronous flush when this many lines are queued. const ASYNC_FLUSH_QD_LINES_THRESHOLD: usize = 100_000; /// Performs a *synchronous* flush when this many lines are queued. i.e. if /// after reaching the `ASYNC_FLUSH_QD_LINES_THRESHOLD`, log lines are still /// coming in faster than they can actually be flushed, when we reach this limit /// we'll pause and let it finish flushing rather than letting the queue /// continue growing. const SYNC_FLUSH_QD_LINES_THRESHOLD: usize = 10 * ASYNC_FLUSH_QD_LINES_THRESHOLD; /// Logging thread flushes at least this often. const MIN_FLUSH_FREQUENCY: Duration = Duration::from_secs(10); static SHADOW_LOGGER: Lazy<ShadowLogger> = Lazy::new(ShadowLogger::new); /// Initialize the Shadow logger. pub fn init(max_log_level: LevelFilter, log_errors_to_stderr: bool) -> Result<(), SetLoggerError> { SHADOW_LOGGER.set_max_level(max_log_level); SHADOW_LOGGER.set_log_errors_to_stderr(log_errors_to_stderr); log::set_logger(&*SHADOW_LOGGER)?; // Shadow's logger has its own logic for deciding the max level (see `ShadowLogger::enabled`), // so the log crate should give us all log messages and we can decide whether to show it or not. log::set_max_level(log::LevelFilter::Trace); // Start the thread that will receive log records and flush them to output. std::thread::Builder::new() .name("shadow-logger".to_string()) .spawn(move || SHADOW_LOGGER.logger_thread_fn()) .unwrap(); // Arrange to flush the logger on panic. let default_panic_handler = std::panic::take_hook(); std::panic::set_hook(Box::new(move |panic_info| { // Attempt to flush the logger. We want to avoid a recursive panic, so // we flush the queue on the current thread instead of trying to send // a command to the logger thread (because our thread-local sender // may have already been destructed, and because the logger thread // itself may be in a bad state), and ignore errors. SHADOW_LOGGER.flush_records(None).ok(); default_panic_handler(panic_info); })); Ok(()) } /// A logger specialized for Shadow. It attaches simulation context to log /// entries (e.g. sim time, running process, etc.). It's also designed for /// high performance to accomodate heavy logging from multiple threads. pub struct ShadowLogger { // Channel used to send commands to the logger's thread. // // The Sender half of a channel isn't Sync, so we must protect it with a // Mutex to make ShadowLogger be Sync. This is only accessed once per // thread, though, to clone into the thread-local SENDER. command_sender: Mutex<Sender<LoggerCommand>>, // Like the sender, needs a Mutex for ShadowLogger to be Sync. // The Mutex is only locked once though by the logger thread, which keeps // it locked for as long as it's running. command_receiver: Mutex<Receiver<LoggerCommand>>, // A lock-free queue for individual log records. We don't put the records // themselves in the `command_sender`, because `Sender` doesn't support // getting the queue length. Conversely we don't put commands in this queue // because it doesn't support blocking operations. // // The size is roughly SYNC_FLUSH_QD_LINES_THRESHOLD * // size_of<ShadowLogRecord>; we might want to consider SegQueue (which grows // and shrinks dynamically) instead if we ever make SYNC_FLUSH_QD_LINES_THRESHOLD very // large. records: ArrayQueue<ShadowLogRecord>, // When false, sends a (still-asynchronous) flush command to the logger // thread every time a record is pushed into `records`. buffering_enabled: RwLock<bool>, // The maximum log level, unless overridden by a host-specific log level. max_log_level: OnceCell<LevelFilter>, // Whether to log errors to stderr in addition to stdout. log_errors_to_stderr: OnceCell<bool>, } thread_local!(static SENDER: RefCell<Option<Sender<LoggerCommand>>> = RefCell::new(None)); thread_local!(static THREAD_NAME: Lazy<String> = Lazy::new(|| { get_thread_name() })); thread_local!(static THREAD_ID: Lazy<nix::unistd::Pid> = Lazy::new(|| { nix::unistd::gettid() })); fn get_thread_name() -> String { let mut thread_name = Vec::<i8>::with_capacity(16); let res = unsafe { thread_name.set_len(thread_name.capacity()); // ~infallible when host_name is at least 16 bytes. libc::pthread_getname_np( libc::pthread_self(), thread_name.as_mut_ptr(), thread_name.len(), ) }; // The most likely cause of failure is a bug in the caller. debug_assert_eq!(res, 0, "pthread_getname_np: {}", nix::errno::from_i32(res)); if res == 0 { // SAFETY: We just initialized the input buffer `thread_name`, and // `thread_name_cstr` won't outlive it. let thread_name_cstr = unsafe { std::ffi::CStr::from_ptr(thread_name.as_ptr()) }; return thread_name_cstr.to_owned().to_string_lossy().to_string(); } // Another potential reason for failure is if it couldn't open // /proc/self/task/[tid]/comm. We're probably in a bad state anyway if that // happens, but try to recover anyway. // Empty string String::new() } impl ShadowLogger { fn new() -> ShadowLogger { let (sender, receiver) = std::sync::mpsc::channel(); ShadowLogger { records: ArrayQueue::new(SYNC_FLUSH_QD_LINES_THRESHOLD), command_sender: Mutex::new(sender), command_receiver: Mutex::new(receiver), buffering_enabled: RwLock::new(false), max_log_level: OnceCell::new(), log_errors_to_stderr: OnceCell::new(), } } // Function executed by the logger's helper thread, onto which we offload as // much work as we can. fn logger_thread_fn(&self) { let command_receiver = self.command_receiver.lock().unwrap(); loop { use std::sync::mpsc::RecvTimeoutError; match command_receiver.recv_timeout(MIN_FLUSH_FREQUENCY) { Ok(LoggerCommand::Flush(done_sender)) => self.flush_records(done_sender).unwrap(), Err(RecvTimeoutError::Timeout) => { // Flush self.flush_records(None).unwrap(); } Err(e) => panic!("Unexpected error {}", e), } } } // Function called by the logger's helper thread to flush the contents of // self.records. If `done_sender` is provided, it's notified after the flush // has completed. fn flush_records(&self, done_sender: Option<Sender<()>>) -> std::io::Result<()> { use std::io::Write; // Only flush records that are already in the queue, not ones that // arrive while we're flushing. Otherwise callers who perform a // synchronous flush (whether this flush operation or another one that // arrives while we're flushing) will be left waiting longer than // necessary. Also keeps us from holding the stdout lock indefinitely. let mut toflush = self.records.len(); let stdout_unlocked = std::io::stdout(); let stdout_locked = stdout_unlocked.lock(); let mut stdout = std::io::BufWriter::new(stdout_locked); while toflush > 0 { let record = match self.records.pop() { Some(r) => r, None => { // This can happen if another thread panics while the // logging thread is flushing. In that case both threads // will be consuming from the queue. break; } }; toflush -= 1; if record.level <= Level::Error && *self.log_errors_to_stderr.get().unwrap() { // Send to both stdout and stderr. let stderr_unlocked = std::io::stderr(); let stderr_locked = stderr_unlocked.lock(); let mut stderr = std::io::BufWriter::new(stderr_locked); let line = format!("{record}"); write!(stdout, "{line}")?; write!(stderr, "{line}")?; } else { write!(stdout, "{record}")?; } } if let Some(done_sender) = done_sender { // We can't log from this thread without risking deadlock, so in the // unlikely case that the calling thread has gone away, just print // directly. done_sender.send(()).unwrap_or_else(|e| { println!( "WARNING: Logger couldn't notify calling thread: {:?}", e ) }); } Ok(()) } /// When disabled, the logger thread is notified to write each record as /// soon as it's created. The calling thread still isn't blocked on the /// record actually being written, though. pub fn set_buffering_enabled(&self, buffering_enabled: bool) { let mut writer = self.buffering_enabled.write().unwrap(); *writer = buffering_enabled; } /// If the maximum log level has not yet been set, returns `LevelFilter::Trace`. pub fn max_level(&self) -> LevelFilter { self.max_log_level .get() .copied() .unwrap_or(LevelFilter::Trace) } /// Set the default maximum log level, but this can be overridden per-host. Is only intended to /// be called from `init()`. Will panic if called more than once. fn set_max_level(&self, level: LevelFilter) { self.max_log_level.set(level).unwrap() } /// Set whether to log errors to stderr in addition to stdout. /// /// Is only intended to be called from `init()`. Will panic if called more /// than once. fn set_log_errors_to_stderr(&self, val: bool) { self.log_errors_to_stderr.set(val).unwrap() } // Send a flush command to the logger thread. fn flush_impl(&self, notify_done: Option<Sender<()>>) { self.send_command(LoggerCommand::Flush(notify_done)) } // Send a flush command to the logger thread and block until it's completed. fn flush_sync(&self) { let (done_sender, done_receiver) = std::sync::mpsc::channel(); self.flush_impl(Some(done_sender)); done_receiver.recv().unwrap(); } // Send a flush command to the logger thread. fn flush_async(&self) { self.flush_impl(None); } // Send a command to the logger thread. fn send_command(&self, cmd: LoggerCommand) { SENDER .try_with(|thread_sender| { if thread_sender.borrow().is_none() { let lock = self.command_sender.lock().unwrap(); *thread_sender.borrow_mut() = Some(lock.clone()); } thread_sender .borrow() .as_ref() .unwrap() .send(cmd) .unwrap_or_else(|e| { println!("WARNING: Couldn't send command to logger thread: {:?}", e); }); }) .unwrap_or_else(|e| { println!( "WARNING: Couldn't get sender channel to logger thread: {:?}", e ); }); } } impl Log for ShadowLogger { fn enabled(&self, metadata: &Metadata) -> bool { let filter = match Worker::with_active_host(|host| host.info().log_level) { Some(Some(level)) => level, _ => self.max_level(), }; metadata.level() <= filter
fn log(&self, record: &Record) { if!self.enabled(record.metadata()) { return; } let message = std::fmt::format(*record.args()); let host_info = Worker::with_active_host(|host| host.info().clone()); let mut shadowrecord = ShadowLogRecord { level: record.level(), file: record.file_static(), module_path: record.module_path_static(), line: record.line(), message, wall_time: Duration::from_micros(unsafe { u64::try_from(c_log::logger_elapsed_micros()).unwrap() }), emu_time: Worker::current_time(), thread_name: THREAD_NAME .try_with(|name| (*name).clone()) .unwrap_or_else(|_| get_thread_name()), thread_id: THREAD_ID .try_with(|id| **id) .unwrap_or_else(|_| nix::unistd::gettid()), host_info, }; loop { match self.records.push(shadowrecord) { Ok(()) => break, Err(r) => { // Queue is full. Flush it and try again. shadowrecord = r; self.flush_sync(); } } } if record.level() == Level::Error { // Unlike in Shadow's C code, we don't abort the program on Error // logs. In Rust the same purpose is filled with `panic` and // `unwrap`. C callers will still exit or abort via the lib/logger wrapper. // // Flush *synchronously*, since we're likely about to crash one way or another. self.flush_sync(); } else if self.records.len() > ASYNC_FLUSH_QD_LINES_THRESHOLD ||!*self.buffering_enabled.read().unwrap() { self.flush_async(); } } fn flush(&self) { self.flush_sync(); } } struct ShadowLogRecord { level: Level, file: Option<&'static str>, module_path: Option<&'static str>, line: Option<u32>, message: String, wall_time: Duration, emu_time: Option<EmulatedTime>, thread_name: String, thread_id: nix::unistd::Pid, host_info: Option<Arc<HostInfo>>, } impl std::fmt::Display for ShadowLogRecord { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { { let parts = TimeParts::from_nanos(self.wall_time.as_nanos()); write!( f, "{:02}:{:02}:{:02}.{:06}", parts.hours, parts.mins, parts.secs, parts.nanos / 1000 )?; } write!(f, " [{}:{}]", self.thread_id, self.thread_name)?; if let Some(emu_time) = self.emu_time { let sim_time = emu_time.duration_since(&EmulatedTime::SIMULATION_START); let parts = TimeParts::from_nanos(sim_time.as_nanos()); write!( f, " {:02}:{:02}:{:02}.{:09}", parts.hours, parts.mins, parts.secs, parts.nanos )?; } else { write!(f, " n/a")?; } write!(f, " [{level}]", level = self.level)?; if let Some(host) = &self.host_info { write!( f, " [{hostname}:{ip}]", hostname = host.name, ip = host.default_ip, )?; } else { write!(f, " [n/a]",)?; } write!( f, " [{file}:", file = self .file .map(|f| if let Some(sep_pos) = f.rfind('/') { &f[(sep_pos + 1)..] } else { f }) .unwrap_or("n/a"), )?; if let Some(line) = self.line { write!(f, "{line}", line = line)?; } else { write!(f, "n/a")?; } writeln!( f, "] [{module}] {msg}", module = self.module_path.unwrap_or("n/a"), msg = self.message )?; Ok(()) } } enum LoggerCommand { // Flush; takes an optional one-shot channel to notify that the flush has completed. Flush(Option<Sender<()>>), } pub fn set_buffering_enabled(buffering_enabled: bool) { SHADOW_LOGGER.set_buffering_enabled(buffering_enabled); } mod export { use super::*; /// When disabled, the logger thread is notified to write each record as /// soon as it's created. The calling thread still isn't blocked on the /// record actually being written, though. #[no_mangle] pub unsafe extern "C" fn shadow_logger_setEnableBuffering(buffering_enabled: i32) { set_buffering_enabled(buffering_enabled!= 0) } }
}
random_line_split
main.rs
extern crate byteorder; ///Used to get screen resolution. extern crate screenshot; extern crate inputbot; extern crate ron; extern crate bincode; #[macro_use] extern crate serde_derive; extern crate serde; use prelude::*; use std::{ net::{TcpStream}, io::{self,BufRead,BufReader}, fs::{File}, cmp::{Ordering}, env, ops::{self,RangeInclusive}, path::{Path}, }; use byteorder::{NetworkEndian,ByteOrder,ReadBytesExt}; use inputbot::{MouseCursor}; use rect::*; use network::{Remote}; use absm::{AbsmSession,ServerInfo}; mod prelude { pub use std::error::Error as ErrorTrait; pub type Error = Box<ErrorTrait>; pub type Result<T> = ::std::result::Result<T,Error>; pub use std::{ io::{Write,Read}, fmt,mem, }; pub use serde::{Serialize,Deserialize}; pub use network::{Connection,LocalBuffer,NetBuffer}; pub enum Never {} impl Never { fn as_never(&self)->! {unsafe{::std::hint::unreachable_unchecked()}} } impl fmt::Display for Never { fn fmt(&self,_: &mut fmt::Formatter)->fmt::Result {self.as_never()} } impl fmt::Debug for Never { fn fmt(&self,_: &mut fmt::Formatter)->fmt::Result {self.as_never()} } impl ErrorTrait for Never {} } #[macro_use] mod rect; mod network; mod absm; pub struct Setup { ///Map from input device coordinates to output client coordinates. pub mapping: Mapping, ///Specify a minimum and a maximum on the final client coordinates. pub clip: Rect<i32>, ///Specify a range of pressures. ///Events with a pressure outside this range are ignored. pub pressure: [f32; 2], ///Specify a range of sizes, similarly to `pressure`. pub size: [f32; 2], } impl Setup { fn new(info: &ServerInfo,config: &Config)->Setup { //Target area is set immutably by the config let target=config.target; //Start off with source area as the entire device screen //Source area is more mutable than target area let mut source=Rect{min: Pair([0.0; 2]),max: info.server_screen_res}; println!("device screen area: {}",source); //Correct any device rotations if config.correct_device_orientation { if source.aspect()!=target.aspect() { //Source screen should be rotated 90° counterclockwise to correct orientation source.rotate_negative(); println!("rotated 90° counterclockwise to correct device orientation"); }else{ println!("device orientation is aligned with client orientation"); } }else{ println!("device orientation correction is disabled"); } //Apply config device source area proportions let mut source=Rect{ min: source.map(|int| int as f32).denormalizer().apply(config.source.min), max: source.map(|int| int as f32).denormalizer().apply(config.source.max), }; //Correct orientation if source and target don't have matching aspects if config.correct_orientation { if source.aspect()!=target.aspect() { source.rotate_negative(); println!("rotated 90° counterclockwise to correct orientation mismatch"); }else{ println!("final orientation matches target orientation"); } }else{ println!("final orientation correction is disabled"); } //Shrink a source axis to match target aspect ratio if config.keep_aspect_ratio { let shrink=|source: &mut Rect<f32>,shrink_axis: Axis| { let fixed_axis=shrink_axis.swap(); //Get the target size of the shrink axis let target=target.virtual_size(shrink_axis) as f32*source.virtual_size(fixed_axis) / target.virtual_size(fixed_axis) as f32; source.resize_virtual_axis(shrink_axis,target); }; match target.map(|int| int as f32).aspect_ratio().partial_cmp(&source.aspect_ratio()).unwrap() { Ordering::Greater=>{ //Shrink vertically to match aspect ratio let old=source.virtual_size(Axis::Y); shrink(&mut source,Axis::Y); println!( "shrank source area vertically from {} to {} to match target aspect ratio", old,source.virtual_size(Axis::Y) ); }, Ordering::Less=>{ //Shrink horizontally to match aspect ratio let old=source.virtual_size(Axis::X); shrink(&mut source,Axis::X); println!( "shrank source area horizontally from {} to {} to match target aspect ratio", old,source.virtual_size(Axis::X) ); }, Ordering::Equal=>{ println!("source aspect ratio matches target aspect ratio"); }, } }else{ println!("aspect ratio correction is disabled"); } println!("mapping source area {} to target area {}",source,target); let pressure=[ config.pressure_range[0].unwrap_or(-std::f32::INFINITY), config.pressure_range[1].unwrap_or(std::f32::INFINITY), ]; let size=[ config.size_range[0].unwrap_or(-std::f32::INFINITY), config.size_range[1].unwrap_or(std::f32::INFINITY), ]; println!("clipping target to {}",config.clip); println!("only allowing touches with pressures inside {:?} and sizes inside {:?}",pressure,size); Setup{ mapping: source.normalizer().chain(&target.map(|int| int as f32).denormalizer()), clip: config.clip, pressure,size, } } fn consume(&mut self,ev: MouseMove) { if ev.pressure<self.pressure[0] || ev.pressure>self.pressure[1] {return} if ev.size<self.size[0] || ev.size>self.size[1] {return} let pos=self.mapping.apply(ev.pos); let adjusted=pair!(i=> (pos[i] as i32).max(self.clip.min[i]).min(self.clip.max[i])); MouseCursor.move_abs(adjusted[Axis::X],adjusted[Axis::Y]); } } #[derive(Deserialize,Serialize)] #[serde(default)] pub struct Config { ///The target area to be mapped, in screen pixels. pub target: Rect<i32>, ///The source area to be mapped, in normalized coordinates from `0.0` to `1.0`. pub source: Rect<f32>, ///After all transformations, clip mouse positions to this rectangle. pub clip: Rect<i32>, ///If the device screen is rotated, rotate it back to compensate. pub correct_device_orientation: bool, ///If after all transformations the source area is rotated, rotate it back to match target ///orientation (landscape or portrait). pub correct_orientation: bool, ///If the source area does not have the same aspect ratio as the target area, shrink it a bit ///in a single axis to fit. pub keep_aspect_ratio: bool, ///Only allow touches within this pressure range to go through. pub pressure_range: [Option<f32>; 2], ///Only allow touches within this size range to go through. pub size_range: [Option<f32>; 2], ///Connect to this remote. pub remote: Remote, ///When ADB port forwarding, map this port on the device. pub android_usb_port: u16,
impl Default for Config { fn default()->Config { let screen_res=get_screen_resolution(); Config{ target: Rect{min: pair!(_=>0),max: screen_res}, source: Rect{min: pair!(_=>0.05),max: pair!(_=>0.95)}, clip: Rect{min: pair!(_=>0),max: screen_res}, correct_device_orientation: true, correct_orientation: true, keep_aspect_ratio: true, pressure_range: [None; 2], size_range: [None; 2], remote: Remote::Tcp("localhost".into(),8517), android_usb_port: 8517, android_attempt_usb_connection: true, } } } impl Config { fn load_path(cfg_path: &str)->Config { println!("loading config file at '{}'",cfg_path); match File::open(&cfg_path) { Err(err)=>{ println!("failed to open config at '{}', using defaults:\n {}",cfg_path,err); let config=Config::default(); match File::create(&cfg_path) { Err(err)=>{ println!("failed to create config file on '{}':\n {}",cfg_path,err); }, Ok(mut file)=>{ let cfg=ron::ser::to_string_pretty(&config,Default::default()).expect("error serializing default config"); file.write_all(cfg.as_bytes()).expect("failed to write config file"); println!("created default config file on '{}'",cfg_path); }, } config }, Ok(file)=>{ let config=ron::de::from_reader(file).expect("malformed configuration file"); println!("loaded config file '{}'",cfg_path); config }, } } } #[derive(Deserialize)] struct MouseMove { pos: Pair<f32>, pressure: f32, size: f32, } fn get_screen_resolution()->Pair<i32> { let screenshot=screenshot::get_screenshot(0).expect("failed to get screen dimensions"); Pair([screenshot.width() as i32,screenshot.height() as i32]) } fn try_adb_forward<P: AsRef<Path>>(path: P,config: &Config)->Result<()> { use std::process::{Command}; let local_port=match config.remote { Remote::Tcp(_,port)=>port, _ => { println!("not connecting through tcp, skipping adb port forwarding"); return Ok(()) }, }; println!("attempting to adb port forward using executable on '{}'",path.as_ref().display()); let out=Command::new(path.as_ref()) .arg("forward") .arg(format!("tcp:{}",local_port)) .arg(format!("tcp:{}",config.android_usb_port)) .output(); match out { Ok(out)=>{ if out.status.success() { println!(" adb exit code indicates success"); Ok(()) }else{ println!(" adb exited with error exit code {:?}",out.status.code()); let lines=|out| for line in String::from_utf8_lossy(out).trim().lines() { println!(" {}",line.trim()); }; println!(" adb output:"); lines(&out.stdout); println!(" adb error output:"); lines(&out.stderr); println!(" device might be disconnected or usb debugging disabled"); Err("error exit code".into()) } }, Err(err)=>{ println!( " failed to run command: {}", err ); Err("failed to run command".into()) }, } } fn main() { //Parse arguments let exec_path; let cfg_path; { let mut args=env::args(); exec_path=args.next().expect("first argument should always be executable path!"); cfg_path=args.next().unwrap_or_else(|| String::from("config.txt")); } //Load configuration let config=Config::load_path(&cfg_path); //Try port forwarding using adb if config.android_attempt_usb_connection { let ok=try_adb_forward(&Path::new(&exec_path).with_file_name("adb"),&config) .or_else(|_err| try_adb_forward("adb",&config)); match ok { Ok(())=>println!( "opened communication tunnel to android device" ), Err(_err)=>println!( "failed to open communication to android device, is USB Debugging enabled?" ), } }else{ println!("usb android device connection is disabled"); } let mut session=AbsmSession::new(config); loop { session.wait_for_event(); } /* //Create tcp stream to device //Tcp is used instead of udp because adb can only forward tcp ports println!("connecting to device at {}:{}...",config.host,config.port); let mut conn=TcpStream::connect((&*config.host,config.port)).expect("failed to connect to server"); conn.set_nodelay(true).expect("failed to enable nodelay"); conn.set_read_timeout(None).expect("failed to set timeout"); conn.set_nonblocking(false).expect("failed to set nonblocking"); println!("connected"); let mut bincode_cfg=bincode::config(); bincode_cfg.big_endian(); loop { let mut msg_type=[0; 4]; conn.read_exact(&mut msg_type).expect("failed to receive message"); match &msg_type { b""=>{ //Mousemove message let mut data=[0; 16]; conn.read_exact(&mut data).expect("failed to read message data"); let mousemove=bincode_cfg.deserialize(&data).expect("malformed mousemove message"); if let Some(ref mut setup) = setup { setup.consume(mousemove); }else{ println!("failed to process mousemove, not setup yet!"); } }, [0xAD]=>{ //Setup message let mut data=[0; 8]; conn.read_exact(&mut data).expect("failed to read setup data"); let info=bincode_cfg.deserialize(&data).expect("malformed setup message"); setup=Some(Setup::new(info,&config)); }, [ty]=>println!("invalid message type {:x}",ty), } } */ }
///Whether to attempt to do ADB port forwarding automatically. ///The android device needs to have `USB Debugging` enabled. pub android_attempt_usb_connection: bool, }
random_line_split
main.rs
extern crate byteorder; ///Used to get screen resolution. extern crate screenshot; extern crate inputbot; extern crate ron; extern crate bincode; #[macro_use] extern crate serde_derive; extern crate serde; use prelude::*; use std::{ net::{TcpStream}, io::{self,BufRead,BufReader}, fs::{File}, cmp::{Ordering}, env, ops::{self,RangeInclusive}, path::{Path}, }; use byteorder::{NetworkEndian,ByteOrder,ReadBytesExt}; use inputbot::{MouseCursor}; use rect::*; use network::{Remote}; use absm::{AbsmSession,ServerInfo}; mod prelude { pub use std::error::Error as ErrorTrait; pub type Error = Box<ErrorTrait>; pub type Result<T> = ::std::result::Result<T,Error>; pub use std::{ io::{Write,Read}, fmt,mem, }; pub use serde::{Serialize,Deserialize}; pub use network::{Connection,LocalBuffer,NetBuffer}; pub enum Never {} impl Never { fn as_never(&self)->! {unsafe{::std::hint::unreachable_unchecked()}} } impl fmt::Display for Never { fn fmt(&self,_: &mut fmt::Formatter)->fmt::Result {self.as_never()} } impl fmt::Debug for Never { fn fmt(&self,_: &mut fmt::Formatter)->fmt::Result {self.as_never()} } impl ErrorTrait for Never {} } #[macro_use] mod rect; mod network; mod absm; pub struct Setup { ///Map from input device coordinates to output client coordinates. pub mapping: Mapping, ///Specify a minimum and a maximum on the final client coordinates. pub clip: Rect<i32>, ///Specify a range of pressures. ///Events with a pressure outside this range are ignored. pub pressure: [f32; 2], ///Specify a range of sizes, similarly to `pressure`. pub size: [f32; 2], } impl Setup { fn new(info: &ServerInfo,config: &Config)->Setup { //Target area is set immutably by the config let target=config.target; //Start off with source area as the entire device screen //Source area is more mutable than target area let mut source=Rect{min: Pair([0.0; 2]),max: info.server_screen_res}; println!("device screen area: {}",source); //Correct any device rotations if config.correct_device_orientation { if source.aspect()!=target.aspect() { //Source screen should be rotated 90° counterclockwise to correct orientation source.rotate_negative(); println!("rotated 90° counterclockwise to correct device orientation"); }else{ println!("device orientation is aligned with client orientation"); } }else{ println!("device orientation correction is disabled"); } //Apply config device source area proportions let mut source=Rect{ min: source.map(|int| int as f32).denormalizer().apply(config.source.min), max: source.map(|int| int as f32).denormalizer().apply(config.source.max), }; //Correct orientation if source and target don't have matching aspects if config.correct_orientation { if source.aspect()!=target.aspect() { source.rotate_negative(); println!("rotated 90° counterclockwise to correct orientation mismatch"); }else{ println!("final orientation matches target orientation"); } }else{ println!("final orientation correction is disabled"); } //Shrink a source axis to match target aspect ratio if config.keep_aspect_ratio { let shrink=|source: &mut Rect<f32>,shrink_axis: Axis| { let fixed_axis=shrink_axis.swap(); //Get the target size of the shrink axis let target=target.virtual_size(shrink_axis) as f32*source.virtual_size(fixed_axis) / target.virtual_size(fixed_axis) as f32; source.resize_virtual_axis(shrink_axis,target); }; match target.map(|int| int as f32).aspect_ratio().partial_cmp(&source.aspect_ratio()).unwrap() { Ordering::Greater=>{ //Shrink vertically to match aspect ratio let old=source.virtual_size(Axis::Y); shrink(&mut source,Axis::Y); println!( "shrank source area vertically from {} to {} to match target aspect ratio", old,source.virtual_size(Axis::Y) ); }, Ordering::Less=>{ //Shrink horizontally to match aspect ratio let old=source.virtual_size(Axis::X); shrink(&mut source,Axis::X); println!( "shrank source area horizontally from {} to {} to match target aspect ratio", old,source.virtual_size(Axis::X) ); }, Ordering::Equal=>{ println!("source aspect ratio matches target aspect ratio"); }, } }else{ println!("aspect ratio correction is disabled"); } println!("mapping source area {} to target area {}",source,target); let pressure=[ config.pressure_range[0].unwrap_or(-std::f32::INFINITY), config.pressure_range[1].unwrap_or(std::f32::INFINITY), ]; let size=[ config.size_range[0].unwrap_or(-std::f32::INFINITY), config.size_range[1].unwrap_or(std::f32::INFINITY), ]; println!("clipping target to {}",config.clip); println!("only allowing touches with pressures inside {:?} and sizes inside {:?}",pressure,size); Setup{ mapping: source.normalizer().chain(&target.map(|int| int as f32).denormalizer()), clip: config.clip, pressure,size, } } fn consume(&mut self,ev: MouseMove) { if ev.pressure<self.pressure[0] || ev.pressure>self.pressure[1] {return} if ev.size<self.size[0] || ev.size>self.size[1] {return} let pos=self.mapping.apply(ev.pos); let adjusted=pair!(i=> (pos[i] as i32).max(self.clip.min[i]).min(self.clip.max[i])); MouseCursor.move_abs(adjusted[Axis::X],adjusted[Axis::Y]); } } #[derive(Deserialize,Serialize)] #[serde(default)] pub struct Config { ///The target area to be mapped, in screen pixels. pub target: Rect<i32>, ///The source area to be mapped, in normalized coordinates from `0.0` to `1.0`. pub source: Rect<f32>, ///After all transformations, clip mouse positions to this rectangle. pub clip: Rect<i32>, ///If the device screen is rotated, rotate it back to compensate. pub correct_device_orientation: bool, ///If after all transformations the source area is rotated, rotate it back to match target ///orientation (landscape or portrait). pub correct_orientation: bool, ///If the source area does not have the same aspect ratio as the target area, shrink it a bit ///in a single axis to fit. pub keep_aspect_ratio: bool, ///Only allow touches within this pressure range to go through. pub pressure_range: [Option<f32>; 2], ///Only allow touches within this size range to go through. pub size_range: [Option<f32>; 2], ///Connect to this remote. pub remote: Remote, ///When ADB port forwarding, map this port on the device. pub android_usb_port: u16, ///Whether to attempt to do ADB port forwarding automatically. ///The android device needs to have `USB Debugging` enabled. pub android_attempt_usb_connection: bool, } impl Default for Config { fn default()->Config { let screen_res=get_screen_resolution(); Config{ target: Rect{min: pair!(_=>0),max: screen_res}, source: Rect{min: pair!(_=>0.05),max: pair!(_=>0.95)}, clip: Rect{min: pair!(_=>0),max: screen_res}, correct_device_orientation: true, correct_orientation: true, keep_aspect_ratio: true, pressure_range: [None; 2], size_range: [None; 2], remote: Remote::Tcp("localhost".into(),8517), android_usb_port: 8517, android_attempt_usb_connection: true, } } } impl Config { fn load_path(cfg_path: &str)->Config { println!("loading config file at '{}'",cfg_path); match File::open(&cfg_path) { Err(err)=>{ println!("failed to open config at '{}', using defaults:\n {}",cfg_path,err); let config=Config::default(); match File::create(&cfg_path) { Err(err)=>{ println!("failed to create config file on '{}':\n {}",cfg_path,err); }, Ok(mut file)=>{ let cfg=ron::ser::to_string_pretty(&config,Default::default()).expect("error serializing default config"); file.write_all(cfg.as_bytes()).expect("failed to write config file"); println!("created default config file on '{}'",cfg_path); }, } config }, Ok(file)=>{ let config=ron::de::from_reader(file).expect("malformed configuration file"); println!("loaded config file '{}'",cfg_path); config }, } } } #[derive(Deserialize)] struct MouseMove { pos: Pair<f32>, pressure: f32, size: f32, } fn get_screen_resolution()->Pair<i32> { let screenshot=screenshot::get_screenshot(0).expect("failed to get screen dimensions"); Pair([screenshot.width() as i32,screenshot.height() as i32]) } fn try_adb_forward<P: AsRef<Path>>(path: P,config: &Config)->Result<()> { use std::process::{Command}; let local_port=match config.remote { Remote::Tcp(_,port)=>port, _ => { println!("not connecting through tcp, skipping adb port forwarding"); return Ok(()) }, }; println!("attempting to adb port forward using executable on '{}'",path.as_ref().display()); let out=Command::new(path.as_ref()) .arg("forward") .arg(format!("tcp:{}",local_port)) .arg(format!("tcp:{}",config.android_usb_port)) .output(); match out { Ok(out)=>{ if out.status.success() { println!(" adb exit code indicates success"); Ok(()) }else{ println!(" adb exited with error exit code {:?}",out.status.code()); let lines=|out| for line in String::from_utf8_lossy(out).trim().lines() { println!(" {}",line.trim()); }; println!(" adb output:"); lines(&out.stdout); println!(" adb error output:"); lines(&out.stderr); println!(" device might be disconnected or usb debugging disabled"); Err("error exit code".into()) } }, Err(err)=>{ println!( " failed to run command: {}", err ); Err("failed to run command".into()) }, } } fn main() {
Err(_err)=>println!( "failed to open communication to android device, is USB Debugging enabled?" ), } }else{ println!("usb android device connection is disabled"); } let mut session=AbsmSession::new(config); loop { session.wait_for_event(); } /* //Create tcp stream to device //Tcp is used instead of udp because adb can only forward tcp ports println!("connecting to device at {}:{}...",config.host,config.port); let mut conn=TcpStream::connect((&*config.host,config.port)).expect("failed to connect to server"); conn.set_nodelay(true).expect("failed to enable nodelay"); conn.set_read_timeout(None).expect("failed to set timeout"); conn.set_nonblocking(false).expect("failed to set nonblocking"); println!("connected"); let mut bincode_cfg=bincode::config(); bincode_cfg.big_endian(); loop { let mut msg_type=[0; 4]; conn.read_exact(&mut msg_type).expect("failed to receive message"); match &msg_type { b""=>{ //Mousemove message let mut data=[0; 16]; conn.read_exact(&mut data).expect("failed to read message data"); let mousemove=bincode_cfg.deserialize(&data).expect("malformed mousemove message"); if let Some(ref mut setup) = setup { setup.consume(mousemove); }else{ println!("failed to process mousemove, not setup yet!"); } }, [0xAD]=>{ //Setup message let mut data=[0; 8]; conn.read_exact(&mut data).expect("failed to read setup data"); let info=bincode_cfg.deserialize(&data).expect("malformed setup message"); setup=Some(Setup::new(info,&config)); }, [ty]=>println!("invalid message type {:x}",ty), } } */ }
//Parse arguments let exec_path; let cfg_path; { let mut args=env::args(); exec_path=args.next().expect("first argument should always be executable path!"); cfg_path=args.next().unwrap_or_else(|| String::from("config.txt")); } //Load configuration let config=Config::load_path(&cfg_path); //Try port forwarding using adb if config.android_attempt_usb_connection { let ok=try_adb_forward(&Path::new(&exec_path).with_file_name("adb"),&config) .or_else(|_err| try_adb_forward("adb",&config)); match ok { Ok(())=>println!( "opened communication tunnel to android device" ),
identifier_body
main.rs
extern crate byteorder; ///Used to get screen resolution. extern crate screenshot; extern crate inputbot; extern crate ron; extern crate bincode; #[macro_use] extern crate serde_derive; extern crate serde; use prelude::*; use std::{ net::{TcpStream}, io::{self,BufRead,BufReader}, fs::{File}, cmp::{Ordering}, env, ops::{self,RangeInclusive}, path::{Path}, }; use byteorder::{NetworkEndian,ByteOrder,ReadBytesExt}; use inputbot::{MouseCursor}; use rect::*; use network::{Remote}; use absm::{AbsmSession,ServerInfo}; mod prelude { pub use std::error::Error as ErrorTrait; pub type Error = Box<ErrorTrait>; pub type Result<T> = ::std::result::Result<T,Error>; pub use std::{ io::{Write,Read}, fmt,mem, }; pub use serde::{Serialize,Deserialize}; pub use network::{Connection,LocalBuffer,NetBuffer}; pub enum Never {} impl Never { fn as_never(&self)->! {unsafe{::std::hint::unreachable_unchecked()}} } impl fmt::Display for Never { fn fmt(&self,_: &mut fmt::Formatter)->fmt::Result {self.as_never()} } impl fmt::Debug for Never { fn fmt(&self,_: &mut fmt::Formatter)->fmt::Result {self.as_never()} } impl ErrorTrait for Never {} } #[macro_use] mod rect; mod network; mod absm; pub struct Setup { ///Map from input device coordinates to output client coordinates. pub mapping: Mapping, ///Specify a minimum and a maximum on the final client coordinates. pub clip: Rect<i32>, ///Specify a range of pressures. ///Events with a pressure outside this range are ignored. pub pressure: [f32; 2], ///Specify a range of sizes, similarly to `pressure`. pub size: [f32; 2], } impl Setup { fn new(info: &ServerInfo,config: &Config)->Setup { //Target area is set immutably by the config let target=config.target; //Start off with source area as the entire device screen //Source area is more mutable than target area let mut source=Rect{min: Pair([0.0; 2]),max: info.server_screen_res}; println!("device screen area: {}",source); //Correct any device rotations if config.correct_device_orientation { if source.aspect()!=target.aspect() { //Source screen should be rotated 90° counterclockwise to correct orientation source.rotate_negative(); println!("rotated 90° counterclockwise to correct device orientation"); }else{ println!("device orientation is aligned with client orientation"); } }else{ println!("device orientation correction is disabled"); } //Apply config device source area proportions let mut source=Rect{ min: source.map(|int| int as f32).denormalizer().apply(config.source.min), max: source.map(|int| int as f32).denormalizer().apply(config.source.max), }; //Correct orientation if source and target don't have matching aspects if config.correct_orientation { if source.aspect()!=target.aspect() { source.rotate_negative(); println!("rotated 90° counterclockwise to correct orientation mismatch"); }else{ println!("final orientation matches target orientation"); } }else{ println!("final orientation correction is disabled"); } //Shrink a source axis to match target aspect ratio if config.keep_aspect_ratio { let shrink=|source: &mut Rect<f32>,shrink_axis: Axis| { let fixed_axis=shrink_axis.swap(); //Get the target size of the shrink axis let target=target.virtual_size(shrink_axis) as f32*source.virtual_size(fixed_axis) / target.virtual_size(fixed_axis) as f32; source.resize_virtual_axis(shrink_axis,target); }; match target.map(|int| int as f32).aspect_ratio().partial_cmp(&source.aspect_ratio()).unwrap() { Ordering::Greater=>{ //Shrink vertically to match aspect ratio let old=source.virtual_size(Axis::Y); shrink(&mut source,Axis::Y); println!( "shrank source area vertically from {} to {} to match target aspect ratio", old,source.virtual_size(Axis::Y) ); }, Ordering::Less=>{ //Shrink horizontally to match aspect ratio let old=source.virtual_size(Axis::X); shrink(&mut source,Axis::X); println!( "shrank source area horizontally from {} to {} to match target aspect ratio", old,source.virtual_size(Axis::X) ); }, Ordering::Equal=>{ println!("source aspect ratio matches target aspect ratio"); }, } }else{ println!("aspect ratio correction is disabled"); } println!("mapping source area {} to target area {}",source,target); let pressure=[ config.pressure_range[0].unwrap_or(-std::f32::INFINITY), config.pressure_range[1].unwrap_or(std::f32::INFINITY), ]; let size=[ config.size_range[0].unwrap_or(-std::f32::INFINITY), config.size_range[1].unwrap_or(std::f32::INFINITY), ]; println!("clipping target to {}",config.clip); println!("only allowing touches with pressures inside {:?} and sizes inside {:?}",pressure,size); Setup{ mapping: source.normalizer().chain(&target.map(|int| int as f32).denormalizer()), clip: config.clip, pressure,size, } } fn consume(&mut self,ev: MouseMove) { if ev.pressure<self.pressure[0] || ev.pressure>self.pressure[1] {return} if ev.size<self.size[0] || ev.size>self.size[1] {return} let pos=self.mapping.apply(ev.pos); let adjusted=pair!(i=> (pos[i] as i32).max(self.clip.min[i]).min(self.clip.max[i])); MouseCursor.move_abs(adjusted[Axis::X],adjusted[Axis::Y]); } } #[derive(Deserialize,Serialize)] #[serde(default)] pub struct Config { ///The target area to be mapped, in screen pixels. pub target: Rect<i32>, ///The source area to be mapped, in normalized coordinates from `0.0` to `1.0`. pub source: Rect<f32>, ///After all transformations, clip mouse positions to this rectangle. pub clip: Rect<i32>, ///If the device screen is rotated, rotate it back to compensate. pub correct_device_orientation: bool, ///If after all transformations the source area is rotated, rotate it back to match target ///orientation (landscape or portrait). pub correct_orientation: bool, ///If the source area does not have the same aspect ratio as the target area, shrink it a bit ///in a single axis to fit. pub keep_aspect_ratio: bool, ///Only allow touches within this pressure range to go through. pub pressure_range: [Option<f32>; 2], ///Only allow touches within this size range to go through. pub size_range: [Option<f32>; 2], ///Connect to this remote. pub remote: Remote, ///When ADB port forwarding, map this port on the device. pub android_usb_port: u16, ///Whether to attempt to do ADB port forwarding automatically. ///The android device needs to have `USB Debugging` enabled. pub android_attempt_usb_connection: bool, } impl Default for Config { fn default()->Config { let screen_res=get_screen_resolution(); Config{ target: Rect{min: pair!(_=>0),max: screen_res}, source: Rect{min: pair!(_=>0.05),max: pair!(_=>0.95)}, clip: Rect{min: pair!(_=>0),max: screen_res}, correct_device_orientation: true, correct_orientation: true, keep_aspect_ratio: true, pressure_range: [None; 2], size_range: [None; 2], remote: Remote::Tcp("localhost".into(),8517), android_usb_port: 8517, android_attempt_usb_connection: true, } } } impl Config { fn load_path(cfg_path: &str)->Config { println!("loading config file at '{}'",cfg_path); match File::open(&cfg_path) { Err(err)=>{ println!("failed to open config at '{}', using defaults:\n {}",cfg_path,err); let config=Config::default(); match File::create(&cfg_path) { Err(err)=>{ println!("failed to create config file on '{}':\n {}",cfg_path,err); }, Ok(mut file)=>{ let cfg=ron::ser::to_string_pretty(&config,Default::default()).expect("error serializing default config"); file.write_all(cfg.as_bytes()).expect("failed to write config file"); println!("created default config file on '{}'",cfg_path); }, } config }, Ok(file)=>{ let config=ron::de::from_reader(file).expect("malformed configuration file"); println!("loaded config file '{}'",cfg_path); config }, } } } #[derive(Deserialize)] struct MouseMove { pos: Pair<f32>, pressure: f32, size: f32, } fn get_screen_resolution()->Pair<i32> { let screenshot=screenshot::get_screenshot(0).expect("failed to get screen dimensions"); Pair([screenshot.width() as i32,screenshot.height() as i32]) } fn try
AsRef<Path>>(path: P,config: &Config)->Result<()> { use std::process::{Command}; let local_port=match config.remote { Remote::Tcp(_,port)=>port, _ => { println!("not connecting through tcp, skipping adb port forwarding"); return Ok(()) }, }; println!("attempting to adb port forward using executable on '{}'",path.as_ref().display()); let out=Command::new(path.as_ref()) .arg("forward") .arg(format!("tcp:{}",local_port)) .arg(format!("tcp:{}",config.android_usb_port)) .output(); match out { Ok(out)=>{ if out.status.success() { println!(" adb exit code indicates success"); Ok(()) }else{ println!(" adb exited with error exit code {:?}",out.status.code()); let lines=|out| for line in String::from_utf8_lossy(out).trim().lines() { println!(" {}",line.trim()); }; println!(" adb output:"); lines(&out.stdout); println!(" adb error output:"); lines(&out.stderr); println!(" device might be disconnected or usb debugging disabled"); Err("error exit code".into()) } }, Err(err)=>{ println!( " failed to run command: {}", err ); Err("failed to run command".into()) }, } } fn main() { //Parse arguments let exec_path; let cfg_path; { let mut args=env::args(); exec_path=args.next().expect("first argument should always be executable path!"); cfg_path=args.next().unwrap_or_else(|| String::from("config.txt")); } //Load configuration let config=Config::load_path(&cfg_path); //Try port forwarding using adb if config.android_attempt_usb_connection { let ok=try_adb_forward(&Path::new(&exec_path).with_file_name("adb"),&config) .or_else(|_err| try_adb_forward("adb",&config)); match ok { Ok(())=>println!( "opened communication tunnel to android device" ), Err(_err)=>println!( "failed to open communication to android device, is USB Debugging enabled?" ), } }else{ println!("usb android device connection is disabled"); } let mut session=AbsmSession::new(config); loop { session.wait_for_event(); } /* //Create tcp stream to device //Tcp is used instead of udp because adb can only forward tcp ports println!("connecting to device at {}:{}...",config.host,config.port); let mut conn=TcpStream::connect((&*config.host,config.port)).expect("failed to connect to server"); conn.set_nodelay(true).expect("failed to enable nodelay"); conn.set_read_timeout(None).expect("failed to set timeout"); conn.set_nonblocking(false).expect("failed to set nonblocking"); println!("connected"); let mut bincode_cfg=bincode::config(); bincode_cfg.big_endian(); loop { let mut msg_type=[0; 4]; conn.read_exact(&mut msg_type).expect("failed to receive message"); match &msg_type { b""=>{ //Mousemove message let mut data=[0; 16]; conn.read_exact(&mut data).expect("failed to read message data"); let mousemove=bincode_cfg.deserialize(&data).expect("malformed mousemove message"); if let Some(ref mut setup) = setup { setup.consume(mousemove); }else{ println!("failed to process mousemove, not setup yet!"); } }, [0xAD]=>{ //Setup message let mut data=[0; 8]; conn.read_exact(&mut data).expect("failed to read setup data"); let info=bincode_cfg.deserialize(&data).expect("malformed setup message"); setup=Some(Setup::new(info,&config)); }, [ty]=>println!("invalid message type {:x}",ty), } } */ }
_adb_forward<P:
identifier_name
offset-monitor.rs
extern crate kafka; extern crate getopts; extern crate env_logger; extern crate time; #[macro_use] extern crate error_chain; use std::ascii::AsciiExt; use std::cmp; use std::env; use std::io::{self, stdout, stderr, BufWriter, Write}; use std::process; use std::thread; use std::time as stdtime; use kafka::client::{KafkaClient, FetchOffset, GroupOffsetStorage}; /// A very simple offset monitor for a particular topic able to show /// the lag for a particular consumer group. Dumps the offset/lag of /// the monitored topic/group to stdout every few seconds. fn main() { env_logger::init().unwrap(); macro_rules! abort { ($e:expr) => {{ let mut out = stderr(); let _ = write!(out, "error: {}\n", $e); let _ = out.flush(); process::exit(1); }} }; let cfg = match Config::from_cmdline() { Ok(cfg) => cfg, Err(e) => abort!(e), }; if let Err(e) = run(cfg) { abort!(e); } } fn run(cfg: Config) -> Result<()> { let mut client = KafkaClient::new(cfg.brokers.clone()); client.set_group_offset_storage(cfg.offset_storage); try!(client.load_metadata_all()); // ~ if no topic specified, print all available and be done. if cfg.topic.is_empty() { let ts = client.topics(); let num_topics = ts.len(); if num_topics == 0 { bail!("no topics available"); } let mut names: Vec<&str> = Vec::with_capacity(ts.len()); names.extend(ts.names()); names.sort(); let mut buf = BufWriter::with_capacity(1024, stdout()); for name in names { let _ = write!(buf, "topic: {}\n", name); } bail!("choose a topic"); } // ~ otherwise let's loop over the topic partition offsets let num_partitions = match client.topics().partitions(&cfg.topic) { None => bail!(format!("no such topic: {}", &cfg.topic)), Some(partitions) => partitions.len(), }; let mut state = State::new(num_partitions, cfg.commited_not_consumed); let mut printer = Printer::new(stdout(), &cfg); try!(printer.print_head(num_partitions)); // ~ initialize the state let mut first_time = true; loop { let t = time::now(); try!(state.update_partitions(&mut client, &cfg.topic, &cfg.group)); if first_time { state.curr_to_prev(); first_time = false; } try!(printer.print_offsets(&t, &state.offsets)); thread::sleep(cfg.period); } } #[derive(Copy, Clone)] struct Partition { prev_latest: i64, curr_latest: i64, curr_lag: i64, } impl Default for Partition { fn default() -> Self { Partition { prev_latest: -1, curr_latest: -1, curr_lag: -1, } } } struct State { offsets: Vec<Partition>, lag_decr: i64, } impl State { fn new(num_partitions: usize, commited_not_consumed: bool) -> State { State { offsets: vec![Default::default(); num_partitions], lag_decr: if commited_not_consumed { 0 } else { 1 }, } } fn update_partitions( &mut self, client: &mut KafkaClient, topic: &str, group: &str, ) -> Result<()> { // ~ get the latest topic offsets let latests = try!(client.fetch_topic_offsets(topic, FetchOffset::Latest)); for l in latests { let off = self.offsets.get_mut(l.partition as usize).expect( "[topic offset] non-existent partition", ); off.prev_latest = off.curr_latest; off.curr_latest = l.offset; } if!group.is_empty() { // ~ get the current group offsets let groups = try!(client.fetch_group_topic_offsets(group, topic)); for g in groups { let off = self.offsets.get_mut(g.partition as usize).expect( "[group offset] non-existent partition", ); // ~ it's quite likely that we fetched group offsets // which are a bit ahead of the topic's latest offset // since we issued the fetch-latest-offset request // earlier than the request for the group offsets off.curr_lag = cmp::max(0, off.curr_latest - g.offset - self.lag_decr); } } Ok(()) } fn curr_to_prev(&mut self) { for o in &mut self.offsets { o.prev_latest = o.curr_latest; } } } struct Printer<W> { out: W, timefmt: String, fmt_buf: String, out_buf: String, time_width: usize, offset_width: usize, diff_width: usize, lag_width: usize, print_diff: bool, print_lag: bool, print_summary: bool, } impl<W: Write> Printer<W> { fn new(out: W, cfg: &Config) -> Printer<W> { Printer { out: out, timefmt: "%H:%M:%S".into(), fmt_buf: String::with_capacity(30), out_buf: String::with_capacity(160), time_width: 10, offset_width: 11, diff_width: 8, lag_width: 6, print_diff: cfg.diff, print_lag:!cfg.group.is_empty(), print_summary: cfg.summary, } } fn print_head(&mut self, num_partitions: usize) -> Result<()> { self.out_buf.clear(); { // ~ format use std::fmt::Write; let _ = write!(self.out_buf, "{1:<0$}", self.time_width, "time"); if self.print_summary { let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, "topic"); if self.print_diff { let _ = write!(self.out_buf, " [{1:>0$}]", self.diff_width, "growth"); } if self.print_lag { let _ = write!(self.out_buf, " {1:0$}", self.lag_width, "(lag)"); } } else { for i in 0..num_partitions { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "p-{}", i); let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, self.fmt_buf); if self.print_diff { let _ = write!(self.out_buf, " [{1:>0$}]", self.diff_width, "growth"); } if self.print_lag { let _ = write!(self.out_buf, " {1:0$}", self.lag_width, "(lag)"); } } } self.out_buf.push('\n'); } { // ~ print try!(self.out.write_all(self.out_buf.as_bytes())); Ok(()) } } fn print_offsets(&mut self, time: &time::Tm, partitions: &[Partition]) -> Result<()> { self.out_buf.clear(); { // ~ format use std::fmt::Write; self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "{}", time.strftime(&self.timefmt).expect("invalid timefmt")); let _ = write!(self.out_buf, "{1:<0$}", self.time_width, self.fmt_buf); if self.print_summary { let mut prev_latest = 0; let mut curr_latest = 0; let mut curr_lag = 0; for p in partitions { macro_rules! cond_add { ($v:ident) => { if $v!= -1 { if p.$v < 0 { $v = -1; } else { $v += p.$v; } } } }; cond_add!(prev_latest); cond_add!(curr_latest); cond_add!(curr_lag); } let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, curr_latest); if self.print_diff { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "{:+}", curr_latest - prev_latest); let _ = write!(self.out_buf, " [{1:>0$}]", self.diff_width, self.fmt_buf); } if self.print_lag {
let _ = write!(self.fmt_buf, "({})", curr_lag); let _ = write!(self.out_buf, " {1:<0$}", self.lag_width, self.fmt_buf); } } else { for p in partitions { let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, p.curr_latest); if self.print_diff { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "{:+}", p.curr_latest - p.prev_latest); let _ = write!(self.out_buf, " [{1:>0$}]", self.diff_width, self.fmt_buf); } if self.print_lag { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "({})", p.curr_lag); let _ = write!(self.out_buf, " {1:<0$}", self.lag_width, self.fmt_buf); } } } } self.out_buf.push('\n'); try!(self.out.write_all(self.out_buf.as_bytes())); Ok(()) } } // -------------------------------------------------------------------- struct Config { brokers: Vec<String>, topic: String, group: String, offset_storage: GroupOffsetStorage, period: stdtime::Duration, commited_not_consumed: bool, summary: bool, diff: bool, } impl Config { fn from_cmdline() -> Result<Config> { let args: Vec<String> = env::args().collect(); let mut opts = getopts::Options::new(); opts.optflag("h", "help", "Print this help screen"); opts.optopt("", "brokers", "Specify kafka bootstrap brokers (comma separated)", "HOSTS"); opts.optopt("", "topic", "Specify the topic to monitor", "TOPIC"); opts.optopt("", "group", "Specify the group to monitor", "GROUP"); opts.optopt("", "storage", "Specify offset store [zookeeper, kafka]", "STORE"); opts.optopt("", "sleep", "Specify the sleep time", "SECS"); opts.optflag("", "partitions", "Print each partition instead of the summary"); opts.optflag("", "no-growth", "Don't print offset growth"); opts.optflag( "", "committed-not-yet-consumed", "Assume commited group offsets specify \ messages the group will start consuming \ (including those at these offsets)", ); let m = match opts.parse(&args[1..]) { Ok(m) => m, Err(e) => bail!(e), }; if m.opt_present("help") { let brief = format!("{} [options]", args[0]); bail!(opts.usage(&brief)); } let mut offset_storage = GroupOffsetStorage::Zookeeper; if let Some(s) = m.opt_str("storage") { if s.eq_ignore_ascii_case("zookeeper") { offset_storage = GroupOffsetStorage::Zookeeper; } else if s.eq_ignore_ascii_case("kafka") { offset_storage = GroupOffsetStorage::Kafka; } else { bail!(format!("unknown offset store: {}", s)); } } let mut period = stdtime::Duration::from_secs(5); if let Some(s) = m.opt_str("sleep") { match s.parse::<u64>() { Ok(n) if n!= 0 => period = stdtime::Duration::from_secs(n), _ => bail!(format!("not a number greater than zero: {}", s)), } } Ok(Config { brokers: m.opt_str("brokers") .unwrap_or_else(|| "localhost:9092".to_owned()) .split(',') .map(|s| s.trim().to_owned()) .collect(), topic: m.opt_str("topic").unwrap_or_else(|| String::new()), group: m.opt_str("group").unwrap_or_else(|| String::new()), offset_storage: offset_storage, period: period, commited_not_consumed: m.opt_present("committed-not-yet-consumed"), summary:!m.opt_present("partitions"), diff:!m.opt_present("no-growth"), }) } } // -------------------------------------------------------------------- error_chain! { foreign_links { Kafka(kafka::error::Error); Io(io::Error); Opt(getopts::Fail); } }
self.fmt_buf.clear();
random_line_split
offset-monitor.rs
extern crate kafka; extern crate getopts; extern crate env_logger; extern crate time; #[macro_use] extern crate error_chain; use std::ascii::AsciiExt; use std::cmp; use std::env; use std::io::{self, stdout, stderr, BufWriter, Write}; use std::process; use std::thread; use std::time as stdtime; use kafka::client::{KafkaClient, FetchOffset, GroupOffsetStorage}; /// A very simple offset monitor for a particular topic able to show /// the lag for a particular consumer group. Dumps the offset/lag of /// the monitored topic/group to stdout every few seconds. fn main() { env_logger::init().unwrap(); macro_rules! abort { ($e:expr) => {{ let mut out = stderr(); let _ = write!(out, "error: {}\n", $e); let _ = out.flush(); process::exit(1); }} }; let cfg = match Config::from_cmdline() { Ok(cfg) => cfg, Err(e) => abort!(e), }; if let Err(e) = run(cfg) { abort!(e); } } fn run(cfg: Config) -> Result<()> { let mut client = KafkaClient::new(cfg.brokers.clone()); client.set_group_offset_storage(cfg.offset_storage); try!(client.load_metadata_all()); // ~ if no topic specified, print all available and be done. if cfg.topic.is_empty() { let ts = client.topics(); let num_topics = ts.len(); if num_topics == 0 { bail!("no topics available"); } let mut names: Vec<&str> = Vec::with_capacity(ts.len()); names.extend(ts.names()); names.sort(); let mut buf = BufWriter::with_capacity(1024, stdout()); for name in names { let _ = write!(buf, "topic: {}\n", name); } bail!("choose a topic"); } // ~ otherwise let's loop over the topic partition offsets let num_partitions = match client.topics().partitions(&cfg.topic) { None => bail!(format!("no such topic: {}", &cfg.topic)), Some(partitions) => partitions.len(), }; let mut state = State::new(num_partitions, cfg.commited_not_consumed); let mut printer = Printer::new(stdout(), &cfg); try!(printer.print_head(num_partitions)); // ~ initialize the state let mut first_time = true; loop { let t = time::now(); try!(state.update_partitions(&mut client, &cfg.topic, &cfg.group)); if first_time { state.curr_to_prev(); first_time = false; } try!(printer.print_offsets(&t, &state.offsets)); thread::sleep(cfg.period); } } #[derive(Copy, Clone)] struct
{ prev_latest: i64, curr_latest: i64, curr_lag: i64, } impl Default for Partition { fn default() -> Self { Partition { prev_latest: -1, curr_latest: -1, curr_lag: -1, } } } struct State { offsets: Vec<Partition>, lag_decr: i64, } impl State { fn new(num_partitions: usize, commited_not_consumed: bool) -> State { State { offsets: vec![Default::default(); num_partitions], lag_decr: if commited_not_consumed { 0 } else { 1 }, } } fn update_partitions( &mut self, client: &mut KafkaClient, topic: &str, group: &str, ) -> Result<()> { // ~ get the latest topic offsets let latests = try!(client.fetch_topic_offsets(topic, FetchOffset::Latest)); for l in latests { let off = self.offsets.get_mut(l.partition as usize).expect( "[topic offset] non-existent partition", ); off.prev_latest = off.curr_latest; off.curr_latest = l.offset; } if!group.is_empty() { // ~ get the current group offsets let groups = try!(client.fetch_group_topic_offsets(group, topic)); for g in groups { let off = self.offsets.get_mut(g.partition as usize).expect( "[group offset] non-existent partition", ); // ~ it's quite likely that we fetched group offsets // which are a bit ahead of the topic's latest offset // since we issued the fetch-latest-offset request // earlier than the request for the group offsets off.curr_lag = cmp::max(0, off.curr_latest - g.offset - self.lag_decr); } } Ok(()) } fn curr_to_prev(&mut self) { for o in &mut self.offsets { o.prev_latest = o.curr_latest; } } } struct Printer<W> { out: W, timefmt: String, fmt_buf: String, out_buf: String, time_width: usize, offset_width: usize, diff_width: usize, lag_width: usize, print_diff: bool, print_lag: bool, print_summary: bool, } impl<W: Write> Printer<W> { fn new(out: W, cfg: &Config) -> Printer<W> { Printer { out: out, timefmt: "%H:%M:%S".into(), fmt_buf: String::with_capacity(30), out_buf: String::with_capacity(160), time_width: 10, offset_width: 11, diff_width: 8, lag_width: 6, print_diff: cfg.diff, print_lag:!cfg.group.is_empty(), print_summary: cfg.summary, } } fn print_head(&mut self, num_partitions: usize) -> Result<()> { self.out_buf.clear(); { // ~ format use std::fmt::Write; let _ = write!(self.out_buf, "{1:<0$}", self.time_width, "time"); if self.print_summary { let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, "topic"); if self.print_diff { let _ = write!(self.out_buf, " [{1:>0$}]", self.diff_width, "growth"); } if self.print_lag { let _ = write!(self.out_buf, " {1:0$}", self.lag_width, "(lag)"); } } else { for i in 0..num_partitions { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "p-{}", i); let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, self.fmt_buf); if self.print_diff { let _ = write!(self.out_buf, " [{1:>0$}]", self.diff_width, "growth"); } if self.print_lag { let _ = write!(self.out_buf, " {1:0$}", self.lag_width, "(lag)"); } } } self.out_buf.push('\n'); } { // ~ print try!(self.out.write_all(self.out_buf.as_bytes())); Ok(()) } } fn print_offsets(&mut self, time: &time::Tm, partitions: &[Partition]) -> Result<()> { self.out_buf.clear(); { // ~ format use std::fmt::Write; self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "{}", time.strftime(&self.timefmt).expect("invalid timefmt")); let _ = write!(self.out_buf, "{1:<0$}", self.time_width, self.fmt_buf); if self.print_summary { let mut prev_latest = 0; let mut curr_latest = 0; let mut curr_lag = 0; for p in partitions { macro_rules! cond_add { ($v:ident) => { if $v!= -1 { if p.$v < 0 { $v = -1; } else { $v += p.$v; } } } }; cond_add!(prev_latest); cond_add!(curr_latest); cond_add!(curr_lag); } let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, curr_latest); if self.print_diff { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "{:+}", curr_latest - prev_latest); let _ = write!(self.out_buf, " [{1:>0$}]", self.diff_width, self.fmt_buf); } if self.print_lag { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "({})", curr_lag); let _ = write!(self.out_buf, " {1:<0$}", self.lag_width, self.fmt_buf); } } else { for p in partitions { let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, p.curr_latest); if self.print_diff { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "{:+}", p.curr_latest - p.prev_latest); let _ = write!(self.out_buf, " [{1:>0$}]", self.diff_width, self.fmt_buf); } if self.print_lag { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "({})", p.curr_lag); let _ = write!(self.out_buf, " {1:<0$}", self.lag_width, self.fmt_buf); } } } } self.out_buf.push('\n'); try!(self.out.write_all(self.out_buf.as_bytes())); Ok(()) } } // -------------------------------------------------------------------- struct Config { brokers: Vec<String>, topic: String, group: String, offset_storage: GroupOffsetStorage, period: stdtime::Duration, commited_not_consumed: bool, summary: bool, diff: bool, } impl Config { fn from_cmdline() -> Result<Config> { let args: Vec<String> = env::args().collect(); let mut opts = getopts::Options::new(); opts.optflag("h", "help", "Print this help screen"); opts.optopt("", "brokers", "Specify kafka bootstrap brokers (comma separated)", "HOSTS"); opts.optopt("", "topic", "Specify the topic to monitor", "TOPIC"); opts.optopt("", "group", "Specify the group to monitor", "GROUP"); opts.optopt("", "storage", "Specify offset store [zookeeper, kafka]", "STORE"); opts.optopt("", "sleep", "Specify the sleep time", "SECS"); opts.optflag("", "partitions", "Print each partition instead of the summary"); opts.optflag("", "no-growth", "Don't print offset growth"); opts.optflag( "", "committed-not-yet-consumed", "Assume commited group offsets specify \ messages the group will start consuming \ (including those at these offsets)", ); let m = match opts.parse(&args[1..]) { Ok(m) => m, Err(e) => bail!(e), }; if m.opt_present("help") { let brief = format!("{} [options]", args[0]); bail!(opts.usage(&brief)); } let mut offset_storage = GroupOffsetStorage::Zookeeper; if let Some(s) = m.opt_str("storage") { if s.eq_ignore_ascii_case("zookeeper") { offset_storage = GroupOffsetStorage::Zookeeper; } else if s.eq_ignore_ascii_case("kafka") { offset_storage = GroupOffsetStorage::Kafka; } else { bail!(format!("unknown offset store: {}", s)); } } let mut period = stdtime::Duration::from_secs(5); if let Some(s) = m.opt_str("sleep") { match s.parse::<u64>() { Ok(n) if n!= 0 => period = stdtime::Duration::from_secs(n), _ => bail!(format!("not a number greater than zero: {}", s)), } } Ok(Config { brokers: m.opt_str("brokers") .unwrap_or_else(|| "localhost:9092".to_owned()) .split(',') .map(|s| s.trim().to_owned()) .collect(), topic: m.opt_str("topic").unwrap_or_else(|| String::new()), group: m.opt_str("group").unwrap_or_else(|| String::new()), offset_storage: offset_storage, period: period, commited_not_consumed: m.opt_present("committed-not-yet-consumed"), summary:!m.opt_present("partitions"), diff:!m.opt_present("no-growth"), }) } } // -------------------------------------------------------------------- error_chain! { foreign_links { Kafka(kafka::error::Error); Io(io::Error); Opt(getopts::Fail); } }
Partition
identifier_name
offset-monitor.rs
extern crate kafka; extern crate getopts; extern crate env_logger; extern crate time; #[macro_use] extern crate error_chain; use std::ascii::AsciiExt; use std::cmp; use std::env; use std::io::{self, stdout, stderr, BufWriter, Write}; use std::process; use std::thread; use std::time as stdtime; use kafka::client::{KafkaClient, FetchOffset, GroupOffsetStorage}; /// A very simple offset monitor for a particular topic able to show /// the lag for a particular consumer group. Dumps the offset/lag of /// the monitored topic/group to stdout every few seconds. fn main() { env_logger::init().unwrap(); macro_rules! abort { ($e:expr) => {{ let mut out = stderr(); let _ = write!(out, "error: {}\n", $e); let _ = out.flush(); process::exit(1); }} }; let cfg = match Config::from_cmdline() { Ok(cfg) => cfg, Err(e) => abort!(e), }; if let Err(e) = run(cfg) { abort!(e); } } fn run(cfg: Config) -> Result<()> { let mut client = KafkaClient::new(cfg.brokers.clone()); client.set_group_offset_storage(cfg.offset_storage); try!(client.load_metadata_all()); // ~ if no topic specified, print all available and be done. if cfg.topic.is_empty() { let ts = client.topics(); let num_topics = ts.len(); if num_topics == 0 { bail!("no topics available"); } let mut names: Vec<&str> = Vec::with_capacity(ts.len()); names.extend(ts.names()); names.sort(); let mut buf = BufWriter::with_capacity(1024, stdout()); for name in names { let _ = write!(buf, "topic: {}\n", name); } bail!("choose a topic"); } // ~ otherwise let's loop over the topic partition offsets let num_partitions = match client.topics().partitions(&cfg.topic) { None => bail!(format!("no such topic: {}", &cfg.topic)), Some(partitions) => partitions.len(), }; let mut state = State::new(num_partitions, cfg.commited_not_consumed); let mut printer = Printer::new(stdout(), &cfg); try!(printer.print_head(num_partitions)); // ~ initialize the state let mut first_time = true; loop { let t = time::now(); try!(state.update_partitions(&mut client, &cfg.topic, &cfg.group)); if first_time { state.curr_to_prev(); first_time = false; } try!(printer.print_offsets(&t, &state.offsets)); thread::sleep(cfg.period); } } #[derive(Copy, Clone)] struct Partition { prev_latest: i64, curr_latest: i64, curr_lag: i64, } impl Default for Partition { fn default() -> Self { Partition { prev_latest: -1, curr_latest: -1, curr_lag: -1, } } } struct State { offsets: Vec<Partition>, lag_decr: i64, } impl State { fn new(num_partitions: usize, commited_not_consumed: bool) -> State { State { offsets: vec![Default::default(); num_partitions], lag_decr: if commited_not_consumed { 0 } else { 1 }, } } fn update_partitions( &mut self, client: &mut KafkaClient, topic: &str, group: &str, ) -> Result<()> { // ~ get the latest topic offsets let latests = try!(client.fetch_topic_offsets(topic, FetchOffset::Latest)); for l in latests { let off = self.offsets.get_mut(l.partition as usize).expect( "[topic offset] non-existent partition", ); off.prev_latest = off.curr_latest; off.curr_latest = l.offset; } if!group.is_empty() { // ~ get the current group offsets let groups = try!(client.fetch_group_topic_offsets(group, topic)); for g in groups { let off = self.offsets.get_mut(g.partition as usize).expect( "[group offset] non-existent partition", ); // ~ it's quite likely that we fetched group offsets // which are a bit ahead of the topic's latest offset // since we issued the fetch-latest-offset request // earlier than the request for the group offsets off.curr_lag = cmp::max(0, off.curr_latest - g.offset - self.lag_decr); } } Ok(()) } fn curr_to_prev(&mut self) { for o in &mut self.offsets { o.prev_latest = o.curr_latest; } } } struct Printer<W> { out: W, timefmt: String, fmt_buf: String, out_buf: String, time_width: usize, offset_width: usize, diff_width: usize, lag_width: usize, print_diff: bool, print_lag: bool, print_summary: bool, } impl<W: Write> Printer<W> { fn new(out: W, cfg: &Config) -> Printer<W>
fn print_head(&mut self, num_partitions: usize) -> Result<()> { self.out_buf.clear(); { // ~ format use std::fmt::Write; let _ = write!(self.out_buf, "{1:<0$}", self.time_width, "time"); if self.print_summary { let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, "topic"); if self.print_diff { let _ = write!(self.out_buf, " [{1:>0$}]", self.diff_width, "growth"); } if self.print_lag { let _ = write!(self.out_buf, " {1:0$}", self.lag_width, "(lag)"); } } else { for i in 0..num_partitions { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "p-{}", i); let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, self.fmt_buf); if self.print_diff { let _ = write!(self.out_buf, " [{1:>0$}]", self.diff_width, "growth"); } if self.print_lag { let _ = write!(self.out_buf, " {1:0$}", self.lag_width, "(lag)"); } } } self.out_buf.push('\n'); } { // ~ print try!(self.out.write_all(self.out_buf.as_bytes())); Ok(()) } } fn print_offsets(&mut self, time: &time::Tm, partitions: &[Partition]) -> Result<()> { self.out_buf.clear(); { // ~ format use std::fmt::Write; self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "{}", time.strftime(&self.timefmt).expect("invalid timefmt")); let _ = write!(self.out_buf, "{1:<0$}", self.time_width, self.fmt_buf); if self.print_summary { let mut prev_latest = 0; let mut curr_latest = 0; let mut curr_lag = 0; for p in partitions { macro_rules! cond_add { ($v:ident) => { if $v!= -1 { if p.$v < 0 { $v = -1; } else { $v += p.$v; } } } }; cond_add!(prev_latest); cond_add!(curr_latest); cond_add!(curr_lag); } let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, curr_latest); if self.print_diff { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "{:+}", curr_latest - prev_latest); let _ = write!(self.out_buf, " [{1:>0$}]", self.diff_width, self.fmt_buf); } if self.print_lag { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "({})", curr_lag); let _ = write!(self.out_buf, " {1:<0$}", self.lag_width, self.fmt_buf); } } else { for p in partitions { let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, p.curr_latest); if self.print_diff { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "{:+}", p.curr_latest - p.prev_latest); let _ = write!(self.out_buf, " [{1:>0$}]", self.diff_width, self.fmt_buf); } if self.print_lag { self.fmt_buf.clear(); let _ = write!(self.fmt_buf, "({})", p.curr_lag); let _ = write!(self.out_buf, " {1:<0$}", self.lag_width, self.fmt_buf); } } } } self.out_buf.push('\n'); try!(self.out.write_all(self.out_buf.as_bytes())); Ok(()) } } // -------------------------------------------------------------------- struct Config { brokers: Vec<String>, topic: String, group: String, offset_storage: GroupOffsetStorage, period: stdtime::Duration, commited_not_consumed: bool, summary: bool, diff: bool, } impl Config { fn from_cmdline() -> Result<Config> { let args: Vec<String> = env::args().collect(); let mut opts = getopts::Options::new(); opts.optflag("h", "help", "Print this help screen"); opts.optopt("", "brokers", "Specify kafka bootstrap brokers (comma separated)", "HOSTS"); opts.optopt("", "topic", "Specify the topic to monitor", "TOPIC"); opts.optopt("", "group", "Specify the group to monitor", "GROUP"); opts.optopt("", "storage", "Specify offset store [zookeeper, kafka]", "STORE"); opts.optopt("", "sleep", "Specify the sleep time", "SECS"); opts.optflag("", "partitions", "Print each partition instead of the summary"); opts.optflag("", "no-growth", "Don't print offset growth"); opts.optflag( "", "committed-not-yet-consumed", "Assume commited group offsets specify \ messages the group will start consuming \ (including those at these offsets)", ); let m = match opts.parse(&args[1..]) { Ok(m) => m, Err(e) => bail!(e), }; if m.opt_present("help") { let brief = format!("{} [options]", args[0]); bail!(opts.usage(&brief)); } let mut offset_storage = GroupOffsetStorage::Zookeeper; if let Some(s) = m.opt_str("storage") { if s.eq_ignore_ascii_case("zookeeper") { offset_storage = GroupOffsetStorage::Zookeeper; } else if s.eq_ignore_ascii_case("kafka") { offset_storage = GroupOffsetStorage::Kafka; } else { bail!(format!("unknown offset store: {}", s)); } } let mut period = stdtime::Duration::from_secs(5); if let Some(s) = m.opt_str("sleep") { match s.parse::<u64>() { Ok(n) if n!= 0 => period = stdtime::Duration::from_secs(n), _ => bail!(format!("not a number greater than zero: {}", s)), } } Ok(Config { brokers: m.opt_str("brokers") .unwrap_or_else(|| "localhost:9092".to_owned()) .split(',') .map(|s| s.trim().to_owned()) .collect(), topic: m.opt_str("topic").unwrap_or_else(|| String::new()), group: m.opt_str("group").unwrap_or_else(|| String::new()), offset_storage: offset_storage, period: period, commited_not_consumed: m.opt_present("committed-not-yet-consumed"), summary:!m.opt_present("partitions"), diff:!m.opt_present("no-growth"), }) } } // -------------------------------------------------------------------- error_chain! { foreign_links { Kafka(kafka::error::Error); Io(io::Error); Opt(getopts::Fail); } }
{ Printer { out: out, timefmt: "%H:%M:%S".into(), fmt_buf: String::with_capacity(30), out_buf: String::with_capacity(160), time_width: 10, offset_width: 11, diff_width: 8, lag_width: 6, print_diff: cfg.diff, print_lag: !cfg.group.is_empty(), print_summary: cfg.summary, } }
identifier_body
mock.rs
// Copyright 2019-2021 PureStake Inc. // This file is part of Moonbeam. // Moonbeam is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Moonbeam is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Moonbeam. If not, see <http://www.gnu.org/licenses/>. //! Test utilities use crate as stake; use crate::{pallet, AwardedPts, Config, InflationInfo, Points, Range}; use frame_support::{ construct_runtime, parameter_types, traits::{Everything, GenesisBuild, OnFinalize, OnInitialize}, weights::Weight, }; use sp_core::H256; use sp_runtime::{ testing::{Header, UintAuthorityId}, traits::{BlakeTwo256, IdentityLookup, OpaqueKeys}, Perbill, Percent, RuntimeAppPublic, }; pub type AccountId = u64; pub type Balance = u128; pub type BlockNumber = u64; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type Block = frame_system::mocking::MockBlock<Test>; // Configure a mock runtime to test the pallet. construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>}, Stake: stake::{Pallet, Call, Storage, Config<T>, Event<T>}, Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>}, Aura: pallet_aura::{Pallet, Storage, Config<T>}, } ); parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const SS58Prefix: u8 = 42; } impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData<Balance>; type AccountId = AccountId; type BaseCallFilter = Everything; type BlockHashCount = BlockHashCount; type BlockLength = (); type BlockNumber = BlockNumber; type BlockWeights = (); type Call = Call; type DbWeight = (); type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; type Header = Header; type Index = u64; type Lookup = IdentityLookup<Self::AccountId>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); } parameter_types! { pub const ExistentialDeposit: u128 = 1; } impl pallet_balances::Config for Test { type AccountStore = System; type Balance = Balance; type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = [u8; 4]; type WeightInfo = (); } parameter_types! { pub const MinimumPeriod: u64 = 1; } impl pallet_timestamp::Config for Test { type MinimumPeriod = MinimumPeriod; type Moment = u64; type OnTimestampSet = Aura; type WeightInfo = (); } parameter_types! { pub const MaxAuthorities: u32 = 100_000; } impl pallet_aura::Config for Test { type AuthorityId = sp_consensus_aura::sr25519::AuthorityId; type DisabledValidators = (); type MaxAuthorities = MaxAuthorities; } sp_runtime::impl_opaque_keys! { pub struct MockSessionKeys { // a key for aura authoring pub aura: UintAuthorityId, } } impl From<UintAuthorityId> for MockSessionKeys { fn from(aura: sp_runtime::testing::UintAuthorityId) -> Self { Self { aura } } } parameter_types! { pub static SessionHandlerCollators: Vec<u64> = vec![]; pub static SessionChangeBlock: u64 = 0; } pub struct TestSessionHandler; impl pallet_session::SessionHandler<u64> for TestSessionHandler { const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID]; fn on_genesis_session<Ks: OpaqueKeys>(keys: &[(u64, Ks)]) { SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>()) } fn on_new_session<Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) { SessionChangeBlock::set(System::block_number()); dbg!(keys.len()); SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>()) } fn on_before_session_ending() {} fn on_disabled(_: u32) {} } impl pallet_session::Config for Test { type Event = Event; type Keys = MockSessionKeys; type NextSessionRotation = Stake; type SessionHandler = TestSessionHandler; type SessionManager = Stake; type ShouldEndSession = Stake; type ValidatorId = <Self as frame_system::Config>::AccountId; // we don't have stash and controller, thus we don't need the convert as well. type ValidatorIdOf = crate::IdentityCollator; type WeightInfo = (); } parameter_types! { pub const MinBlocksPerRound: u32 = 3; pub const BlocksPerRound: u32 = 5; pub const LeaveCandidatesDelay: u32 = 2; pub const LeaveNominatorsDelay: u32 = 2; pub const RevokeNominationDelay: u32 = 2; pub const RewardPaymentDelay: u32 = 2; pub const MinSelectedCandidates: u32 = 5; pub const MaxNominatorsPerCollator: u32 = 4; pub const MaxCollatorsPerNominator: u32 = 4; pub const DefaultCollatorCommission: Perbill = Perbill::from_percent(20); pub const DefaultParachainBondReservePercent: Percent = Percent::from_percent(30); pub const MinCollatorStk: u128 = 10; pub const MinNominatorStk: u128 = 5; pub const MinNomination: u128 = 3; } impl Config for Test { type BlocksPerRound = BlocksPerRound; type Currency = Balances; type DefaultCollatorCommission = DefaultCollatorCommission; type DefaultParachainBondReservePercent = DefaultParachainBondReservePercent; type Event = Event; type LeaveCandidatesDelay = LeaveCandidatesDelay; type LeaveNominatorsDelay = LeaveNominatorsDelay; type MaxCollatorsPerNominator = MaxCollatorsPerNominator; type MaxNominatorsPerCollator = MaxNominatorsPerCollator; type MinBlocksPerRound = MinBlocksPerRound; type MinCollatorCandidateStk = MinCollatorStk; type MinCollatorStk = MinCollatorStk; type MinNomination = MinNomination; type MinNominatorStk = MinNominatorStk; type MinSelectedCandidates = MinSelectedCandidates; type MonetaryGovernanceOrigin = frame_system::EnsureRoot<AccountId>; type RevokeNominationDelay = RevokeNominationDelay; type RewardPaymentDelay = RewardPaymentDelay; type WeightInfo = (); } pub(crate) struct ExtBuilder { // endowed accounts with balances balances: Vec<(AccountId, Balance)>, // [collator, amount] collators: Vec<(AccountId, Balance)>, // [nominator, collator, nomination_amount] nominations: Vec<(AccountId, AccountId, Balance)>, // inflation config inflation: InflationInfo<Balance>, } impl Default for ExtBuilder { fn default() -> ExtBuilder { ExtBuilder { balances: vec![], nominations: vec![], collators: vec![], inflation: InflationInfo { expect: Range { min: 700, ideal: 700, max: 700, }, // not used annual: Range { min: Perbill::from_percent(50), ideal: Perbill::from_percent(50), max: Perbill::from_percent(50), }, // unrealistically high parameterization, only for testing round: Range { min: Perbill::from_percent(5), ideal: Perbill::from_percent(5), max: Perbill::from_percent(5), }, }, } } } impl ExtBuilder { pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self { self.balances = balances; self } pub(crate) fn with_candidates(mut self, collators: Vec<(AccountId, Balance)>) -> Self { self.collators = collators; self } pub(crate) fn with_nominations(mut self, nominations: Vec<(AccountId, AccountId, Balance)>) -> Self { self.nominations = nominations; self } #[allow(dead_code)] pub(crate) fn with_inflation(mut self, inflation: InflationInfo<Balance>) -> Self { self.inflation = inflation; self } pub(crate) fn build(self) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() .build_storage::<Test>() .expect("Frame system builds valid default genesis config"); pallet_balances::GenesisConfig::<Test> { balances: self.balances, } .assimilate_storage(&mut t) .expect("Pallet balances storage can be assimilated"); stake::GenesisConfig::<Test> { candidates: self.collators, nominations: self.nominations, inflation_config: self.inflation, } .assimilate_storage(&mut t) .expect("Parachain Staking's storage can be assimilated"); let validators = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let keys = validators .iter() .map(|i| { (*i, *i, MockSessionKeys { aura: UintAuthorityId(*i), }) }) .collect::<Vec<_>>(); pallet_session::GenesisConfig::<Test> { keys } .assimilate_storage(&mut t) .expect("Pallet session storage can be assimilated"); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext } } pub(crate) fn roll_to(n: u64) { while System::block_number() < n { Balances::on_finalize(System::block_number()); Stake::on_finalize(System::block_number()); Session::on_finalize(System::block_number()); Aura::on_finalize(System::block_number()); System::on_finalize(System::block_number()); System::set_block_number(System::block_number() + 1); System::on_initialize(System::block_number()); Timestamp::on_initialize(System::block_number()); Balances::on_initialize(System::block_number()); Stake::on_initialize(System::block_number()); Session::on_initialize(System::block_number()); Aura::on_initialize(System::block_number()); } } pub(crate) fn last_event() -> Event
pub(crate) fn events() -> Vec<pallet::Event<Test>> { System::events() .into_iter() .map(|r| r.event) .filter_map(|e| if let Event::Stake(inner) = e { Some(inner) } else { None }) .collect::<Vec<_>>() } // Same storage changes as EventHandler::note_author impl pub(crate) fn set_author(round: u32, acc: u64, pts: u32) { <Points<Test>>::mutate(round, |p| *p += pts); <AwardedPts<Test>>::mutate(round, acc, |p| *p += pts); } #[test] fn geneses() { ExtBuilder::default() .with_balances(vec![ (1, 1000), (2, 300), (3, 100), (4, 100), (5, 100), (6, 100), (7, 100), (8, 9), (9, 4), ]) .with_candidates(vec![(1, 500), (2, 200)]) .with_nominations(vec![(3, 1, 100), (4, 1, 100), (5, 2, 100), (6, 2, 100)]) .build() .execute_with(|| { assert!(System::events().is_empty()); // collators assert_eq!(Balances::reserved_balance(&1), 500); assert_eq!(Balances::free_balance(&1), 500); assert!(Stake::is_candidate(&1)); assert_eq!(Balances::reserved_balance(&2), 200); assert_eq!(Balances::free_balance(&2), 100); assert!(Stake::is_candidate(&2)); // nominators for x in 3..7 { assert!(Stake::is_nominator(&x)); assert_eq!(Balances::free_balance(&x), 0); assert_eq!(Balances::reserved_balance(&x), 100); } // uninvolved for x in 7..10 { assert!(!Stake::is_nominator(&x)); } assert_eq!(Balances::free_balance(&7), 100); assert_eq!(Balances::reserved_balance(&7), 0); assert_eq!(Balances::free_balance(&8), 9); assert_eq!(Balances::reserved_balance(&8), 0); assert_eq!(Balances::free_balance(&9), 4); assert_eq!(Balances::reserved_balance(&9), 0); }); ExtBuilder::default() .with_balances(vec![ (1, 100), (2, 100), (3, 100), (4, 100), (5, 100), (6, 100), (7, 100), (8, 100), (9, 100), (10, 100), ]) .with_candidates(vec![(1, 20), (2, 20), (3, 20), (4, 20), (5, 10)]) .with_nominations(vec![(6, 1, 10), (7, 1, 10), (8, 2, 10), (9, 2, 10), (10, 1, 10)]) .build() .execute_with(|| { assert!(System::events().is_empty()); // collators for x in 1..5 { assert!(Stake::is_candidate(&x)); assert_eq!(Balances::free_balance(&x), 80); assert_eq!(Balances::reserved_balance(&x), 20); } assert!(Stake::is_candidate(&5)); assert_eq!(Balances::free_balance(&5), 90); assert_eq!(Balances::reserved_balance(&5), 10); // nominators for x in 6..11 { assert!(Stake::is_nominator(&x)); assert_eq!(Balances::free_balance(&x), 90); assert_eq!(Balances::reserved_balance(&x), 10); } }); }
{ System::events().pop().expect("Event expected").event }
identifier_body
mock.rs
// Copyright 2019-2021 PureStake Inc. // This file is part of Moonbeam. // Moonbeam is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Moonbeam is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Moonbeam. If not, see <http://www.gnu.org/licenses/>. //! Test utilities use crate as stake; use crate::{pallet, AwardedPts, Config, InflationInfo, Points, Range}; use frame_support::{ construct_runtime, parameter_types, traits::{Everything, GenesisBuild, OnFinalize, OnInitialize}, weights::Weight, }; use sp_core::H256; use sp_runtime::{ testing::{Header, UintAuthorityId}, traits::{BlakeTwo256, IdentityLookup, OpaqueKeys}, Perbill, Percent, RuntimeAppPublic, }; pub type AccountId = u64;
type Block = frame_system::mocking::MockBlock<Test>; // Configure a mock runtime to test the pallet. construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>}, Stake: stake::{Pallet, Call, Storage, Config<T>, Event<T>}, Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>}, Aura: pallet_aura::{Pallet, Storage, Config<T>}, } ); parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const SS58Prefix: u8 = 42; } impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData<Balance>; type AccountId = AccountId; type BaseCallFilter = Everything; type BlockHashCount = BlockHashCount; type BlockLength = (); type BlockNumber = BlockNumber; type BlockWeights = (); type Call = Call; type DbWeight = (); type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; type Header = Header; type Index = u64; type Lookup = IdentityLookup<Self::AccountId>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); } parameter_types! { pub const ExistentialDeposit: u128 = 1; } impl pallet_balances::Config for Test { type AccountStore = System; type Balance = Balance; type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = [u8; 4]; type WeightInfo = (); } parameter_types! { pub const MinimumPeriod: u64 = 1; } impl pallet_timestamp::Config for Test { type MinimumPeriod = MinimumPeriod; type Moment = u64; type OnTimestampSet = Aura; type WeightInfo = (); } parameter_types! { pub const MaxAuthorities: u32 = 100_000; } impl pallet_aura::Config for Test { type AuthorityId = sp_consensus_aura::sr25519::AuthorityId; type DisabledValidators = (); type MaxAuthorities = MaxAuthorities; } sp_runtime::impl_opaque_keys! { pub struct MockSessionKeys { // a key for aura authoring pub aura: UintAuthorityId, } } impl From<UintAuthorityId> for MockSessionKeys { fn from(aura: sp_runtime::testing::UintAuthorityId) -> Self { Self { aura } } } parameter_types! { pub static SessionHandlerCollators: Vec<u64> = vec![]; pub static SessionChangeBlock: u64 = 0; } pub struct TestSessionHandler; impl pallet_session::SessionHandler<u64> for TestSessionHandler { const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID]; fn on_genesis_session<Ks: OpaqueKeys>(keys: &[(u64, Ks)]) { SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>()) } fn on_new_session<Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) { SessionChangeBlock::set(System::block_number()); dbg!(keys.len()); SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>()) } fn on_before_session_ending() {} fn on_disabled(_: u32) {} } impl pallet_session::Config for Test { type Event = Event; type Keys = MockSessionKeys; type NextSessionRotation = Stake; type SessionHandler = TestSessionHandler; type SessionManager = Stake; type ShouldEndSession = Stake; type ValidatorId = <Self as frame_system::Config>::AccountId; // we don't have stash and controller, thus we don't need the convert as well. type ValidatorIdOf = crate::IdentityCollator; type WeightInfo = (); } parameter_types! { pub const MinBlocksPerRound: u32 = 3; pub const BlocksPerRound: u32 = 5; pub const LeaveCandidatesDelay: u32 = 2; pub const LeaveNominatorsDelay: u32 = 2; pub const RevokeNominationDelay: u32 = 2; pub const RewardPaymentDelay: u32 = 2; pub const MinSelectedCandidates: u32 = 5; pub const MaxNominatorsPerCollator: u32 = 4; pub const MaxCollatorsPerNominator: u32 = 4; pub const DefaultCollatorCommission: Perbill = Perbill::from_percent(20); pub const DefaultParachainBondReservePercent: Percent = Percent::from_percent(30); pub const MinCollatorStk: u128 = 10; pub const MinNominatorStk: u128 = 5; pub const MinNomination: u128 = 3; } impl Config for Test { type BlocksPerRound = BlocksPerRound; type Currency = Balances; type DefaultCollatorCommission = DefaultCollatorCommission; type DefaultParachainBondReservePercent = DefaultParachainBondReservePercent; type Event = Event; type LeaveCandidatesDelay = LeaveCandidatesDelay; type LeaveNominatorsDelay = LeaveNominatorsDelay; type MaxCollatorsPerNominator = MaxCollatorsPerNominator; type MaxNominatorsPerCollator = MaxNominatorsPerCollator; type MinBlocksPerRound = MinBlocksPerRound; type MinCollatorCandidateStk = MinCollatorStk; type MinCollatorStk = MinCollatorStk; type MinNomination = MinNomination; type MinNominatorStk = MinNominatorStk; type MinSelectedCandidates = MinSelectedCandidates; type MonetaryGovernanceOrigin = frame_system::EnsureRoot<AccountId>; type RevokeNominationDelay = RevokeNominationDelay; type RewardPaymentDelay = RewardPaymentDelay; type WeightInfo = (); } pub(crate) struct ExtBuilder { // endowed accounts with balances balances: Vec<(AccountId, Balance)>, // [collator, amount] collators: Vec<(AccountId, Balance)>, // [nominator, collator, nomination_amount] nominations: Vec<(AccountId, AccountId, Balance)>, // inflation config inflation: InflationInfo<Balance>, } impl Default for ExtBuilder { fn default() -> ExtBuilder { ExtBuilder { balances: vec![], nominations: vec![], collators: vec![], inflation: InflationInfo { expect: Range { min: 700, ideal: 700, max: 700, }, // not used annual: Range { min: Perbill::from_percent(50), ideal: Perbill::from_percent(50), max: Perbill::from_percent(50), }, // unrealistically high parameterization, only for testing round: Range { min: Perbill::from_percent(5), ideal: Perbill::from_percent(5), max: Perbill::from_percent(5), }, }, } } } impl ExtBuilder { pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self { self.balances = balances; self } pub(crate) fn with_candidates(mut self, collators: Vec<(AccountId, Balance)>) -> Self { self.collators = collators; self } pub(crate) fn with_nominations(mut self, nominations: Vec<(AccountId, AccountId, Balance)>) -> Self { self.nominations = nominations; self } #[allow(dead_code)] pub(crate) fn with_inflation(mut self, inflation: InflationInfo<Balance>) -> Self { self.inflation = inflation; self } pub(crate) fn build(self) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() .build_storage::<Test>() .expect("Frame system builds valid default genesis config"); pallet_balances::GenesisConfig::<Test> { balances: self.balances, } .assimilate_storage(&mut t) .expect("Pallet balances storage can be assimilated"); stake::GenesisConfig::<Test> { candidates: self.collators, nominations: self.nominations, inflation_config: self.inflation, } .assimilate_storage(&mut t) .expect("Parachain Staking's storage can be assimilated"); let validators = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let keys = validators .iter() .map(|i| { (*i, *i, MockSessionKeys { aura: UintAuthorityId(*i), }) }) .collect::<Vec<_>>(); pallet_session::GenesisConfig::<Test> { keys } .assimilate_storage(&mut t) .expect("Pallet session storage can be assimilated"); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext } } pub(crate) fn roll_to(n: u64) { while System::block_number() < n { Balances::on_finalize(System::block_number()); Stake::on_finalize(System::block_number()); Session::on_finalize(System::block_number()); Aura::on_finalize(System::block_number()); System::on_finalize(System::block_number()); System::set_block_number(System::block_number() + 1); System::on_initialize(System::block_number()); Timestamp::on_initialize(System::block_number()); Balances::on_initialize(System::block_number()); Stake::on_initialize(System::block_number()); Session::on_initialize(System::block_number()); Aura::on_initialize(System::block_number()); } } pub(crate) fn last_event() -> Event { System::events().pop().expect("Event expected").event } pub(crate) fn events() -> Vec<pallet::Event<Test>> { System::events() .into_iter() .map(|r| r.event) .filter_map(|e| if let Event::Stake(inner) = e { Some(inner) } else { None }) .collect::<Vec<_>>() } // Same storage changes as EventHandler::note_author impl pub(crate) fn set_author(round: u32, acc: u64, pts: u32) { <Points<Test>>::mutate(round, |p| *p += pts); <AwardedPts<Test>>::mutate(round, acc, |p| *p += pts); } #[test] fn geneses() { ExtBuilder::default() .with_balances(vec![ (1, 1000), (2, 300), (3, 100), (4, 100), (5, 100), (6, 100), (7, 100), (8, 9), (9, 4), ]) .with_candidates(vec![(1, 500), (2, 200)]) .with_nominations(vec![(3, 1, 100), (4, 1, 100), (5, 2, 100), (6, 2, 100)]) .build() .execute_with(|| { assert!(System::events().is_empty()); // collators assert_eq!(Balances::reserved_balance(&1), 500); assert_eq!(Balances::free_balance(&1), 500); assert!(Stake::is_candidate(&1)); assert_eq!(Balances::reserved_balance(&2), 200); assert_eq!(Balances::free_balance(&2), 100); assert!(Stake::is_candidate(&2)); // nominators for x in 3..7 { assert!(Stake::is_nominator(&x)); assert_eq!(Balances::free_balance(&x), 0); assert_eq!(Balances::reserved_balance(&x), 100); } // uninvolved for x in 7..10 { assert!(!Stake::is_nominator(&x)); } assert_eq!(Balances::free_balance(&7), 100); assert_eq!(Balances::reserved_balance(&7), 0); assert_eq!(Balances::free_balance(&8), 9); assert_eq!(Balances::reserved_balance(&8), 0); assert_eq!(Balances::free_balance(&9), 4); assert_eq!(Balances::reserved_balance(&9), 0); }); ExtBuilder::default() .with_balances(vec![ (1, 100), (2, 100), (3, 100), (4, 100), (5, 100), (6, 100), (7, 100), (8, 100), (9, 100), (10, 100), ]) .with_candidates(vec![(1, 20), (2, 20), (3, 20), (4, 20), (5, 10)]) .with_nominations(vec![(6, 1, 10), (7, 1, 10), (8, 2, 10), (9, 2, 10), (10, 1, 10)]) .build() .execute_with(|| { assert!(System::events().is_empty()); // collators for x in 1..5 { assert!(Stake::is_candidate(&x)); assert_eq!(Balances::free_balance(&x), 80); assert_eq!(Balances::reserved_balance(&x), 20); } assert!(Stake::is_candidate(&5)); assert_eq!(Balances::free_balance(&5), 90); assert_eq!(Balances::reserved_balance(&5), 10); // nominators for x in 6..11 { assert!(Stake::is_nominator(&x)); assert_eq!(Balances::free_balance(&x), 90); assert_eq!(Balances::reserved_balance(&x), 10); } }); }
pub type Balance = u128; pub type BlockNumber = u64; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
random_line_split
mock.rs
// Copyright 2019-2021 PureStake Inc. // This file is part of Moonbeam. // Moonbeam is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Moonbeam is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Moonbeam. If not, see <http://www.gnu.org/licenses/>. //! Test utilities use crate as stake; use crate::{pallet, AwardedPts, Config, InflationInfo, Points, Range}; use frame_support::{ construct_runtime, parameter_types, traits::{Everything, GenesisBuild, OnFinalize, OnInitialize}, weights::Weight, }; use sp_core::H256; use sp_runtime::{ testing::{Header, UintAuthorityId}, traits::{BlakeTwo256, IdentityLookup, OpaqueKeys}, Perbill, Percent, RuntimeAppPublic, }; pub type AccountId = u64; pub type Balance = u128; pub type BlockNumber = u64; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type Block = frame_system::mocking::MockBlock<Test>; // Configure a mock runtime to test the pallet. construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>}, Stake: stake::{Pallet, Call, Storage, Config<T>, Event<T>}, Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>}, Aura: pallet_aura::{Pallet, Storage, Config<T>}, } ); parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const SS58Prefix: u8 = 42; } impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData<Balance>; type AccountId = AccountId; type BaseCallFilter = Everything; type BlockHashCount = BlockHashCount; type BlockLength = (); type BlockNumber = BlockNumber; type BlockWeights = (); type Call = Call; type DbWeight = (); type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; type Header = Header; type Index = u64; type Lookup = IdentityLookup<Self::AccountId>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); } parameter_types! { pub const ExistentialDeposit: u128 = 1; } impl pallet_balances::Config for Test { type AccountStore = System; type Balance = Balance; type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = [u8; 4]; type WeightInfo = (); } parameter_types! { pub const MinimumPeriod: u64 = 1; } impl pallet_timestamp::Config for Test { type MinimumPeriod = MinimumPeriod; type Moment = u64; type OnTimestampSet = Aura; type WeightInfo = (); } parameter_types! { pub const MaxAuthorities: u32 = 100_000; } impl pallet_aura::Config for Test { type AuthorityId = sp_consensus_aura::sr25519::AuthorityId; type DisabledValidators = (); type MaxAuthorities = MaxAuthorities; } sp_runtime::impl_opaque_keys! { pub struct MockSessionKeys { // a key for aura authoring pub aura: UintAuthorityId, } } impl From<UintAuthorityId> for MockSessionKeys { fn from(aura: sp_runtime::testing::UintAuthorityId) -> Self { Self { aura } } } parameter_types! { pub static SessionHandlerCollators: Vec<u64> = vec![]; pub static SessionChangeBlock: u64 = 0; } pub struct TestSessionHandler; impl pallet_session::SessionHandler<u64> for TestSessionHandler { const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID]; fn on_genesis_session<Ks: OpaqueKeys>(keys: &[(u64, Ks)]) { SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>()) } fn
<Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) { SessionChangeBlock::set(System::block_number()); dbg!(keys.len()); SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>()) } fn on_before_session_ending() {} fn on_disabled(_: u32) {} } impl pallet_session::Config for Test { type Event = Event; type Keys = MockSessionKeys; type NextSessionRotation = Stake; type SessionHandler = TestSessionHandler; type SessionManager = Stake; type ShouldEndSession = Stake; type ValidatorId = <Self as frame_system::Config>::AccountId; // we don't have stash and controller, thus we don't need the convert as well. type ValidatorIdOf = crate::IdentityCollator; type WeightInfo = (); } parameter_types! { pub const MinBlocksPerRound: u32 = 3; pub const BlocksPerRound: u32 = 5; pub const LeaveCandidatesDelay: u32 = 2; pub const LeaveNominatorsDelay: u32 = 2; pub const RevokeNominationDelay: u32 = 2; pub const RewardPaymentDelay: u32 = 2; pub const MinSelectedCandidates: u32 = 5; pub const MaxNominatorsPerCollator: u32 = 4; pub const MaxCollatorsPerNominator: u32 = 4; pub const DefaultCollatorCommission: Perbill = Perbill::from_percent(20); pub const DefaultParachainBondReservePercent: Percent = Percent::from_percent(30); pub const MinCollatorStk: u128 = 10; pub const MinNominatorStk: u128 = 5; pub const MinNomination: u128 = 3; } impl Config for Test { type BlocksPerRound = BlocksPerRound; type Currency = Balances; type DefaultCollatorCommission = DefaultCollatorCommission; type DefaultParachainBondReservePercent = DefaultParachainBondReservePercent; type Event = Event; type LeaveCandidatesDelay = LeaveCandidatesDelay; type LeaveNominatorsDelay = LeaveNominatorsDelay; type MaxCollatorsPerNominator = MaxCollatorsPerNominator; type MaxNominatorsPerCollator = MaxNominatorsPerCollator; type MinBlocksPerRound = MinBlocksPerRound; type MinCollatorCandidateStk = MinCollatorStk; type MinCollatorStk = MinCollatorStk; type MinNomination = MinNomination; type MinNominatorStk = MinNominatorStk; type MinSelectedCandidates = MinSelectedCandidates; type MonetaryGovernanceOrigin = frame_system::EnsureRoot<AccountId>; type RevokeNominationDelay = RevokeNominationDelay; type RewardPaymentDelay = RewardPaymentDelay; type WeightInfo = (); } pub(crate) struct ExtBuilder { // endowed accounts with balances balances: Vec<(AccountId, Balance)>, // [collator, amount] collators: Vec<(AccountId, Balance)>, // [nominator, collator, nomination_amount] nominations: Vec<(AccountId, AccountId, Balance)>, // inflation config inflation: InflationInfo<Balance>, } impl Default for ExtBuilder { fn default() -> ExtBuilder { ExtBuilder { balances: vec![], nominations: vec![], collators: vec![], inflation: InflationInfo { expect: Range { min: 700, ideal: 700, max: 700, }, // not used annual: Range { min: Perbill::from_percent(50), ideal: Perbill::from_percent(50), max: Perbill::from_percent(50), }, // unrealistically high parameterization, only for testing round: Range { min: Perbill::from_percent(5), ideal: Perbill::from_percent(5), max: Perbill::from_percent(5), }, }, } } } impl ExtBuilder { pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self { self.balances = balances; self } pub(crate) fn with_candidates(mut self, collators: Vec<(AccountId, Balance)>) -> Self { self.collators = collators; self } pub(crate) fn with_nominations(mut self, nominations: Vec<(AccountId, AccountId, Balance)>) -> Self { self.nominations = nominations; self } #[allow(dead_code)] pub(crate) fn with_inflation(mut self, inflation: InflationInfo<Balance>) -> Self { self.inflation = inflation; self } pub(crate) fn build(self) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() .build_storage::<Test>() .expect("Frame system builds valid default genesis config"); pallet_balances::GenesisConfig::<Test> { balances: self.balances, } .assimilate_storage(&mut t) .expect("Pallet balances storage can be assimilated"); stake::GenesisConfig::<Test> { candidates: self.collators, nominations: self.nominations, inflation_config: self.inflation, } .assimilate_storage(&mut t) .expect("Parachain Staking's storage can be assimilated"); let validators = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let keys = validators .iter() .map(|i| { (*i, *i, MockSessionKeys { aura: UintAuthorityId(*i), }) }) .collect::<Vec<_>>(); pallet_session::GenesisConfig::<Test> { keys } .assimilate_storage(&mut t) .expect("Pallet session storage can be assimilated"); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext } } pub(crate) fn roll_to(n: u64) { while System::block_number() < n { Balances::on_finalize(System::block_number()); Stake::on_finalize(System::block_number()); Session::on_finalize(System::block_number()); Aura::on_finalize(System::block_number()); System::on_finalize(System::block_number()); System::set_block_number(System::block_number() + 1); System::on_initialize(System::block_number()); Timestamp::on_initialize(System::block_number()); Balances::on_initialize(System::block_number()); Stake::on_initialize(System::block_number()); Session::on_initialize(System::block_number()); Aura::on_initialize(System::block_number()); } } pub(crate) fn last_event() -> Event { System::events().pop().expect("Event expected").event } pub(crate) fn events() -> Vec<pallet::Event<Test>> { System::events() .into_iter() .map(|r| r.event) .filter_map(|e| if let Event::Stake(inner) = e { Some(inner) } else { None }) .collect::<Vec<_>>() } // Same storage changes as EventHandler::note_author impl pub(crate) fn set_author(round: u32, acc: u64, pts: u32) { <Points<Test>>::mutate(round, |p| *p += pts); <AwardedPts<Test>>::mutate(round, acc, |p| *p += pts); } #[test] fn geneses() { ExtBuilder::default() .with_balances(vec![ (1, 1000), (2, 300), (3, 100), (4, 100), (5, 100), (6, 100), (7, 100), (8, 9), (9, 4), ]) .with_candidates(vec![(1, 500), (2, 200)]) .with_nominations(vec![(3, 1, 100), (4, 1, 100), (5, 2, 100), (6, 2, 100)]) .build() .execute_with(|| { assert!(System::events().is_empty()); // collators assert_eq!(Balances::reserved_balance(&1), 500); assert_eq!(Balances::free_balance(&1), 500); assert!(Stake::is_candidate(&1)); assert_eq!(Balances::reserved_balance(&2), 200); assert_eq!(Balances::free_balance(&2), 100); assert!(Stake::is_candidate(&2)); // nominators for x in 3..7 { assert!(Stake::is_nominator(&x)); assert_eq!(Balances::free_balance(&x), 0); assert_eq!(Balances::reserved_balance(&x), 100); } // uninvolved for x in 7..10 { assert!(!Stake::is_nominator(&x)); } assert_eq!(Balances::free_balance(&7), 100); assert_eq!(Balances::reserved_balance(&7), 0); assert_eq!(Balances::free_balance(&8), 9); assert_eq!(Balances::reserved_balance(&8), 0); assert_eq!(Balances::free_balance(&9), 4); assert_eq!(Balances::reserved_balance(&9), 0); }); ExtBuilder::default() .with_balances(vec![ (1, 100), (2, 100), (3, 100), (4, 100), (5, 100), (6, 100), (7, 100), (8, 100), (9, 100), (10, 100), ]) .with_candidates(vec![(1, 20), (2, 20), (3, 20), (4, 20), (5, 10)]) .with_nominations(vec![(6, 1, 10), (7, 1, 10), (8, 2, 10), (9, 2, 10), (10, 1, 10)]) .build() .execute_with(|| { assert!(System::events().is_empty()); // collators for x in 1..5 { assert!(Stake::is_candidate(&x)); assert_eq!(Balances::free_balance(&x), 80); assert_eq!(Balances::reserved_balance(&x), 20); } assert!(Stake::is_candidate(&5)); assert_eq!(Balances::free_balance(&5), 90); assert_eq!(Balances::reserved_balance(&5), 10); // nominators for x in 6..11 { assert!(Stake::is_nominator(&x)); assert_eq!(Balances::free_balance(&x), 90); assert_eq!(Balances::reserved_balance(&x), 10); } }); }
on_new_session
identifier_name
mock.rs
// Copyright 2019-2021 PureStake Inc. // This file is part of Moonbeam. // Moonbeam is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Moonbeam is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Moonbeam. If not, see <http://www.gnu.org/licenses/>. //! Test utilities use crate as stake; use crate::{pallet, AwardedPts, Config, InflationInfo, Points, Range}; use frame_support::{ construct_runtime, parameter_types, traits::{Everything, GenesisBuild, OnFinalize, OnInitialize}, weights::Weight, }; use sp_core::H256; use sp_runtime::{ testing::{Header, UintAuthorityId}, traits::{BlakeTwo256, IdentityLookup, OpaqueKeys}, Perbill, Percent, RuntimeAppPublic, }; pub type AccountId = u64; pub type Balance = u128; pub type BlockNumber = u64; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type Block = frame_system::mocking::MockBlock<Test>; // Configure a mock runtime to test the pallet. construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>}, Stake: stake::{Pallet, Call, Storage, Config<T>, Event<T>}, Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>}, Aura: pallet_aura::{Pallet, Storage, Config<T>}, } ); parameter_types! { pub const BlockHashCount: u64 = 250; pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const SS58Prefix: u8 = 42; } impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData<Balance>; type AccountId = AccountId; type BaseCallFilter = Everything; type BlockHashCount = BlockHashCount; type BlockLength = (); type BlockNumber = BlockNumber; type BlockWeights = (); type Call = Call; type DbWeight = (); type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; type Header = Header; type Index = u64; type Lookup = IdentityLookup<Self::AccountId>; type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); type Origin = Origin; type PalletInfo = PalletInfo; type SS58Prefix = SS58Prefix; type SystemWeightInfo = (); type Version = (); } parameter_types! { pub const ExistentialDeposit: u128 = 1; } impl pallet_balances::Config for Test { type AccountStore = System; type Balance = Balance; type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = [u8; 4]; type WeightInfo = (); } parameter_types! { pub const MinimumPeriod: u64 = 1; } impl pallet_timestamp::Config for Test { type MinimumPeriod = MinimumPeriod; type Moment = u64; type OnTimestampSet = Aura; type WeightInfo = (); } parameter_types! { pub const MaxAuthorities: u32 = 100_000; } impl pallet_aura::Config for Test { type AuthorityId = sp_consensus_aura::sr25519::AuthorityId; type DisabledValidators = (); type MaxAuthorities = MaxAuthorities; } sp_runtime::impl_opaque_keys! { pub struct MockSessionKeys { // a key for aura authoring pub aura: UintAuthorityId, } } impl From<UintAuthorityId> for MockSessionKeys { fn from(aura: sp_runtime::testing::UintAuthorityId) -> Self { Self { aura } } } parameter_types! { pub static SessionHandlerCollators: Vec<u64> = vec![]; pub static SessionChangeBlock: u64 = 0; } pub struct TestSessionHandler; impl pallet_session::SessionHandler<u64> for TestSessionHandler { const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID]; fn on_genesis_session<Ks: OpaqueKeys>(keys: &[(u64, Ks)]) { SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>()) } fn on_new_session<Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) { SessionChangeBlock::set(System::block_number()); dbg!(keys.len()); SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>()) } fn on_before_session_ending() {} fn on_disabled(_: u32) {} } impl pallet_session::Config for Test { type Event = Event; type Keys = MockSessionKeys; type NextSessionRotation = Stake; type SessionHandler = TestSessionHandler; type SessionManager = Stake; type ShouldEndSession = Stake; type ValidatorId = <Self as frame_system::Config>::AccountId; // we don't have stash and controller, thus we don't need the convert as well. type ValidatorIdOf = crate::IdentityCollator; type WeightInfo = (); } parameter_types! { pub const MinBlocksPerRound: u32 = 3; pub const BlocksPerRound: u32 = 5; pub const LeaveCandidatesDelay: u32 = 2; pub const LeaveNominatorsDelay: u32 = 2; pub const RevokeNominationDelay: u32 = 2; pub const RewardPaymentDelay: u32 = 2; pub const MinSelectedCandidates: u32 = 5; pub const MaxNominatorsPerCollator: u32 = 4; pub const MaxCollatorsPerNominator: u32 = 4; pub const DefaultCollatorCommission: Perbill = Perbill::from_percent(20); pub const DefaultParachainBondReservePercent: Percent = Percent::from_percent(30); pub const MinCollatorStk: u128 = 10; pub const MinNominatorStk: u128 = 5; pub const MinNomination: u128 = 3; } impl Config for Test { type BlocksPerRound = BlocksPerRound; type Currency = Balances; type DefaultCollatorCommission = DefaultCollatorCommission; type DefaultParachainBondReservePercent = DefaultParachainBondReservePercent; type Event = Event; type LeaveCandidatesDelay = LeaveCandidatesDelay; type LeaveNominatorsDelay = LeaveNominatorsDelay; type MaxCollatorsPerNominator = MaxCollatorsPerNominator; type MaxNominatorsPerCollator = MaxNominatorsPerCollator; type MinBlocksPerRound = MinBlocksPerRound; type MinCollatorCandidateStk = MinCollatorStk; type MinCollatorStk = MinCollatorStk; type MinNomination = MinNomination; type MinNominatorStk = MinNominatorStk; type MinSelectedCandidates = MinSelectedCandidates; type MonetaryGovernanceOrigin = frame_system::EnsureRoot<AccountId>; type RevokeNominationDelay = RevokeNominationDelay; type RewardPaymentDelay = RewardPaymentDelay; type WeightInfo = (); } pub(crate) struct ExtBuilder { // endowed accounts with balances balances: Vec<(AccountId, Balance)>, // [collator, amount] collators: Vec<(AccountId, Balance)>, // [nominator, collator, nomination_amount] nominations: Vec<(AccountId, AccountId, Balance)>, // inflation config inflation: InflationInfo<Balance>, } impl Default for ExtBuilder { fn default() -> ExtBuilder { ExtBuilder { balances: vec![], nominations: vec![], collators: vec![], inflation: InflationInfo { expect: Range { min: 700, ideal: 700, max: 700, }, // not used annual: Range { min: Perbill::from_percent(50), ideal: Perbill::from_percent(50), max: Perbill::from_percent(50), }, // unrealistically high parameterization, only for testing round: Range { min: Perbill::from_percent(5), ideal: Perbill::from_percent(5), max: Perbill::from_percent(5), }, }, } } } impl ExtBuilder { pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self { self.balances = balances; self } pub(crate) fn with_candidates(mut self, collators: Vec<(AccountId, Balance)>) -> Self { self.collators = collators; self } pub(crate) fn with_nominations(mut self, nominations: Vec<(AccountId, AccountId, Balance)>) -> Self { self.nominations = nominations; self } #[allow(dead_code)] pub(crate) fn with_inflation(mut self, inflation: InflationInfo<Balance>) -> Self { self.inflation = inflation; self } pub(crate) fn build(self) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() .build_storage::<Test>() .expect("Frame system builds valid default genesis config"); pallet_balances::GenesisConfig::<Test> { balances: self.balances, } .assimilate_storage(&mut t) .expect("Pallet balances storage can be assimilated"); stake::GenesisConfig::<Test> { candidates: self.collators, nominations: self.nominations, inflation_config: self.inflation, } .assimilate_storage(&mut t) .expect("Parachain Staking's storage can be assimilated"); let validators = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let keys = validators .iter() .map(|i| { (*i, *i, MockSessionKeys { aura: UintAuthorityId(*i), }) }) .collect::<Vec<_>>(); pallet_session::GenesisConfig::<Test> { keys } .assimilate_storage(&mut t) .expect("Pallet session storage can be assimilated"); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); ext } } pub(crate) fn roll_to(n: u64) { while System::block_number() < n { Balances::on_finalize(System::block_number()); Stake::on_finalize(System::block_number()); Session::on_finalize(System::block_number()); Aura::on_finalize(System::block_number()); System::on_finalize(System::block_number()); System::set_block_number(System::block_number() + 1); System::on_initialize(System::block_number()); Timestamp::on_initialize(System::block_number()); Balances::on_initialize(System::block_number()); Stake::on_initialize(System::block_number()); Session::on_initialize(System::block_number()); Aura::on_initialize(System::block_number()); } } pub(crate) fn last_event() -> Event { System::events().pop().expect("Event expected").event } pub(crate) fn events() -> Vec<pallet::Event<Test>> { System::events() .into_iter() .map(|r| r.event) .filter_map(|e| if let Event::Stake(inner) = e { Some(inner) } else
) .collect::<Vec<_>>() } // Same storage changes as EventHandler::note_author impl pub(crate) fn set_author(round: u32, acc: u64, pts: u32) { <Points<Test>>::mutate(round, |p| *p += pts); <AwardedPts<Test>>::mutate(round, acc, |p| *p += pts); } #[test] fn geneses() { ExtBuilder::default() .with_balances(vec![ (1, 1000), (2, 300), (3, 100), (4, 100), (5, 100), (6, 100), (7, 100), (8, 9), (9, 4), ]) .with_candidates(vec![(1, 500), (2, 200)]) .with_nominations(vec![(3, 1, 100), (4, 1, 100), (5, 2, 100), (6, 2, 100)]) .build() .execute_with(|| { assert!(System::events().is_empty()); // collators assert_eq!(Balances::reserved_balance(&1), 500); assert_eq!(Balances::free_balance(&1), 500); assert!(Stake::is_candidate(&1)); assert_eq!(Balances::reserved_balance(&2), 200); assert_eq!(Balances::free_balance(&2), 100); assert!(Stake::is_candidate(&2)); // nominators for x in 3..7 { assert!(Stake::is_nominator(&x)); assert_eq!(Balances::free_balance(&x), 0); assert_eq!(Balances::reserved_balance(&x), 100); } // uninvolved for x in 7..10 { assert!(!Stake::is_nominator(&x)); } assert_eq!(Balances::free_balance(&7), 100); assert_eq!(Balances::reserved_balance(&7), 0); assert_eq!(Balances::free_balance(&8), 9); assert_eq!(Balances::reserved_balance(&8), 0); assert_eq!(Balances::free_balance(&9), 4); assert_eq!(Balances::reserved_balance(&9), 0); }); ExtBuilder::default() .with_balances(vec![ (1, 100), (2, 100), (3, 100), (4, 100), (5, 100), (6, 100), (7, 100), (8, 100), (9, 100), (10, 100), ]) .with_candidates(vec![(1, 20), (2, 20), (3, 20), (4, 20), (5, 10)]) .with_nominations(vec![(6, 1, 10), (7, 1, 10), (8, 2, 10), (9, 2, 10), (10, 1, 10)]) .build() .execute_with(|| { assert!(System::events().is_empty()); // collators for x in 1..5 { assert!(Stake::is_candidate(&x)); assert_eq!(Balances::free_balance(&x), 80); assert_eq!(Balances::reserved_balance(&x), 20); } assert!(Stake::is_candidate(&5)); assert_eq!(Balances::free_balance(&5), 90); assert_eq!(Balances::reserved_balance(&5), 10); // nominators for x in 6..11 { assert!(Stake::is_nominator(&x)); assert_eq!(Balances::free_balance(&x), 90); assert_eq!(Balances::reserved_balance(&x), 10); } }); }
{ None }
conditional_block
non_blocking.rs
//! A non-blocking, off-thread writer. //! //! This spawns a dedicated worker thread which is responsible for writing log //! lines to the provided writer. When a line is written using the returned //! `NonBlocking` struct's `make_writer` method, it will be enqueued to be //! written by the worker thread. //! //! The queue has a fixed capacity, and if it becomes full, any logs written //! to it will be dropped until capacity is once again available. This may //! occur if logs are consistently produced faster than the worker thread can //! output them. The queue capacity and behavior when full (i.e., whether to //! drop logs or to exert backpressure to slow down senders) can be configured //! using [`NonBlockingBuilder::default()`][builder]. //! This function returns the default configuration. It is equivalent to: //! //! ```rust //! # use tracing_appender::non_blocking::{NonBlocking, WorkerGuard}; //! # fn doc() -> (NonBlocking, WorkerGuard) { //! tracing_appender::non_blocking(std::io::stdout()) //! # } //! ``` //! [builder]: NonBlockingBuilder::default() //! //! <br/> This function returns a tuple of `NonBlocking` and `WorkerGuard`. //! `NonBlocking` implements [`MakeWriter`] which integrates with `tracing_subscriber`. //! `WorkerGuard` is a drop guard that is responsible for flushing any remaining logs when //! the program terminates. //! //! Note that the `WorkerGuard` returned by `non_blocking` _must_ be assigned to a binding that //! is not `_`, as `_` will result in the `WorkerGuard` being dropped immediately. //! Unintentional drops of `WorkerGuard` remove the guarantee that logs will be flushed //! during a program's termination, in a panic or otherwise. //! //! See [`WorkerGuard`][worker_guard] for examples of using the guard. //! //! [worker_guard]: WorkerGuard //! //! # Examples //! //! ``` rust //! # fn docs() { //! let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout()); //! let collector = tracing_subscriber::fmt().with_writer(non_blocking); //! tracing::collect::with_default(collector.finish(), || { //! tracing::event!(tracing::Level::INFO, "Hello"); //! }); //! # } //! ``` use crate::worker::Worker; use crate::Msg; use crossbeam_channel::{bounded, SendTimeoutError, Sender}; use std::io; use std::io::Write; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread::JoinHandle; use std::time::Duration; use tracing_subscriber::fmt::MakeWriter; /// The default maximum number of buffered log lines. /// /// If [`NonBlocking`][non-blocking] is lossy, it will drop spans/events at capacity. /// If [`NonBlocking`][non-blocking] is _not_ lossy, /// backpressure will be exerted on senders, causing them to block their /// respective threads until there is available capacity. /// /// [non-blocking]: NonBlocking /// Recommended to be a power of 2. pub const DEFAULT_BUFFERED_LINES_LIMIT: usize = 128_000; /// A guard that flushes spans/events associated to a [`NonBlocking`] on a drop /// /// Writing to a [`NonBlocking`] writer will **not** immediately write a span or event to the underlying /// output. Instead, the span or event will be written by a dedicated logging thread at some later point. /// To increase throughput, the non-blocking writer will flush to the underlying output on /// a periodic basis rather than every time a span or event is written. This means that if the program /// terminates abruptly (such as through an uncaught `panic` or a `std::process::exit`), some spans /// or events may not be written. /// /// Since spans/events and events recorded near a crash are often necessary for diagnosing the failure, /// `WorkerGuard` provides a mechanism to ensure that _all_ buffered logs are flushed to their output. /// `WorkerGuard` should be assigned in the `main` function or whatever the entrypoint of the program is. /// This will ensure that the guard will be dropped during an unwinding or when `main` exits /// successfully. /// /// # Examples /// /// ``` rust /// # #[clippy::allow(needless_doctest_main)] /// fn main () { /// # fn doc() { /// let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout()); /// let collector = tracing_subscriber::fmt().with_writer(non_blocking); /// tracing::collect::with_default(collector.finish(), || { /// // Emit some tracing events within context of the non_blocking `_guard` and tracing subscriber /// tracing::event!(tracing::Level::INFO, "Hello"); /// }); /// // Exiting the context of `main` will drop the `_guard` and any remaining logs should get flushed /// # } /// } /// ``` #[must_use] #[derive(Debug)] pub struct WorkerGuard { handle: Option<JoinHandle<()>>, sender: Sender<Msg>, shutdown: Sender<()>, } /// A non-blocking writer. /// /// While the line between "blocking" and "non-blocking" IO is fuzzy, writing to a file is typically /// considered to be a _blocking_ operation. For an application whose `Collector` writes spans and events /// as they are emitted, an application might find the latency profile to be unacceptable. /// `NonBlocking` moves the writing out of an application's data path by sending spans and events /// to a dedicated logging thread. /// /// This struct implements [`MakeWriter`][make_writer] from the `tracing-subscriber` /// crate. Therefore, it can be used with the [`tracing_subscriber::fmt`][fmt] module /// or with any other collector/subscriber implementation that uses the `MakeWriter` trait. /// /// [make_writer]: tracing_subscriber::fmt::MakeWriter /// [fmt]: mod@tracing_subscriber::fmt #[derive(Clone, Debug)] pub struct NonBlocking { error_counter: ErrorCounter, channel: Sender<Msg>, is_lossy: bool, } /// Tracks the number of times a log line was dropped by the background thread. /// /// If the non-blocking writer is not configured in [lossy mode], the error /// count should always be 0. /// /// [lossy mode]: NonBlockingBuilder::lossy #[derive(Clone, Debug)] pub struct ErrorCounter(Arc<AtomicUsize>); impl NonBlocking { /// Returns a new `NonBlocking` writer wrapping the provided `writer`. /// /// The returned `NonBlocking` writer will have the [default configuration][default] values. /// Other configurations can be specified using the [builder] interface. /// /// [default]: NonBlockingBuilder::default() /// [builder]: NonBlockingBuilder pub fn new<T: Write + Send + Sync +'static>(writer: T) -> (NonBlocking, WorkerGuard) { NonBlockingBuilder::default().finish(writer) } fn create<T: Write + Send + Sync +'static>( writer: T, buffered_lines_limit: usize, is_lossy: bool, thread_name: String, ) -> (NonBlocking, WorkerGuard) { let (sender, receiver) = bounded(buffered_lines_limit); let (shutdown_sender, shutdown_receiver) = bounded(0); let worker = Worker::new(receiver, writer, shutdown_receiver); let worker_guard = WorkerGuard::new( worker.worker_thread(thread_name), sender.clone(), shutdown_sender, ); ( Self { channel: sender, error_counter: ErrorCounter(Arc::new(AtomicUsize::new(0))), is_lossy, }, worker_guard, ) } /// Returns a counter for the number of times logs where dropped. This will always return zero if /// `NonBlocking` is not lossy. pub fn error_counter(&self) -> ErrorCounter { self.error_counter.clone() } } /// A builder for [`NonBlocking`][non-blocking]. /// /// [non-blocking]: NonBlocking #[derive(Debug)] pub struct NonBlockingBuilder { buffered_lines_limit: usize, is_lossy: bool, thread_name: String, } impl NonBlockingBuilder { /// Sets the number of lines to buffer before dropping logs or exerting backpressure on senders pub fn buffered_lines_limit(mut self, buffered_lines_limit: usize) -> NonBlockingBuilder { self.buffered_lines_limit = buffered_lines_limit; self } /// Sets whether `NonBlocking` should be lossy or not. /// /// If set to `true`, logs will be dropped when the buffered limit is reached. If `false`, backpressure /// will be exerted on senders, blocking them until the buffer has capacity again. /// /// By default, the built `NonBlocking` will be lossy. pub fn lossy(mut self, is_lossy: bool) -> NonBlockingBuilder { self.is_lossy = is_lossy; self } /// Override the worker thread's name. /// /// The default worker thread name is "tracing-appender". pub fn thread_name(mut self, name: &str) -> NonBlockingBuilder { self.thread_name = name.to_string(); self } /// Completes the builder, returning the configured `NonBlocking`. pub fn finish<T: Write + Send + Sync +'static>(self, writer: T) -> (NonBlocking, WorkerGuard) { NonBlocking::create( writer, self.buffered_lines_limit, self.is_lossy, self.thread_name, ) } } impl Default for NonBlockingBuilder { fn default() -> Self { NonBlockingBuilder { buffered_lines_limit: DEFAULT_BUFFERED_LINES_LIMIT, is_lossy: true, thread_name: "tracing-appender".to_string(), } } } impl std::io::Write for NonBlocking { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let buf_size = buf.len(); if self.is_lossy { if self.channel.try_send(Msg::Line(buf.to_vec())).is_err() { self.error_counter.incr_saturating(); } } else { return match self.channel.send(Msg::Line(buf.to_vec())) { Ok(_) => Ok(buf_size), Err(_) => Err(io::Error::from(io::ErrorKind::Other)), }; } Ok(buf_size) } fn flush(&mut self) -> io::Result<()> { Ok(()) } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.write(buf).map(|_| ()) } } impl<'a> MakeWriter<'a> for NonBlocking { type Writer = NonBlocking; fn make_writer(&'a self) -> Self::Writer { self.clone() } } impl WorkerGuard { fn new(handle: JoinHandle<()>, sender: Sender<Msg>, shutdown: Sender<()>) -> Self { WorkerGuard { handle: Some(handle), sender, shutdown, } } } impl Drop for WorkerGuard { fn drop(&mut self) { let timeout = Duration::from_millis(100); match self.sender.send_timeout(Msg::Shutdown, timeout) { Ok(_) => { // Attempt to wait for `Worker` to flush all messages before dropping. This happens // when the `Worker` calls `recv()` on a zero-capacity channel. Use `send_timeout` // so that drop is not blocked indefinitely. // TODO: Make timeout configurable. let timeout = Duration::from_millis(1000); match self.shutdown.send_timeout((), timeout) { Err(SendTimeoutError::Timeout(_)) => { eprintln!( "Shutting down logging worker timed out after {:?}.", timeout ); } _ => { // At this point it is safe to wait for `Worker` destruction without blocking if let Some(handle) = self.handle.take() { if handle.join().is_err() { eprintln!("Logging worker thread panicked"); } }; } } } Err(SendTimeoutError::Disconnected(_)) => (), Err(SendTimeoutError::Timeout(_)) => eprintln!( "Sending shutdown signal to logging worker timed out after {:?}", timeout ), } } } // === impl ErrorCounter === impl ErrorCounter { /// Returns the number of log lines that have been dropped. /// /// If the non-blocking writer is not configured in [lossy mode], the error /// count should always be 0. /// /// [lossy mode]: NonBlockingBuilder::lossy pub fn dropped_lines(&self) -> usize { self.0.load(Ordering::Acquire) } fn incr_saturating(&self) { let mut curr = self.0.load(Ordering::Acquire); // We don't need to enter the CAS loop if the current value is already // `usize::MAX`. if curr == usize::MAX { return; } // This is implemented as a CAS loop rather than as a simple // `fetch_add`, because we don't want to wrap on overflow. Instead, we // need to ensure that saturating addition is performed. loop { let val = curr.saturating_add(1); match self .0 .compare_exchange(curr, val, Ordering::AcqRel, Ordering::Acquire) { Ok(_) => return, Err(actual) => curr = actual, } } } } #[cfg(test)] mod test { use super::*; use std::sync::mpsc; use std::thread; use std::time::Duration; struct MockWriter { tx: mpsc::SyncSender<String>, } impl MockWriter { fn new(capacity: usize) -> (Self, mpsc::Receiver<String>) { let (tx, rx) = mpsc::sync_channel(capacity); (Self { tx }, rx) } } impl std::io::Write for MockWriter { fn
(&mut self, buf: &[u8]) -> std::io::Result<usize> { let buf_len = buf.len(); let _ = self.tx.send(String::from_utf8_lossy(buf).to_string()); Ok(buf_len) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } #[test] fn backpressure_exerted() { let (mock_writer, rx) = MockWriter::new(1); let (mut non_blocking, _guard) = self::NonBlockingBuilder::default() .lossy(false) .buffered_lines_limit(1) .finish(mock_writer); let error_count = non_blocking.error_counter(); non_blocking.write_all(b"Hello").expect("Failed to write"); assert_eq!(0, error_count.dropped_lines()); let handle = thread::spawn(move || { non_blocking.write_all(b", World").expect("Failed to write"); }); // Sleep a little to ensure previously spawned thread gets blocked on write. thread::sleep(Duration::from_millis(100)); // We should not drop logs when blocked. assert_eq!(0, error_count.dropped_lines()); // Read the first message to unblock sender. let mut line = rx.recv().unwrap(); assert_eq!(line, "Hello"); // Wait for thread to finish. handle.join().expect("thread should not panic"); // Thread has joined, we should be able to read the message it sent. line = rx.recv().unwrap(); assert_eq!(line, ", World"); } fn write_non_blocking(non_blocking: &mut NonBlocking, msg: &[u8]) { non_blocking.write_all(msg).expect("Failed to write"); // Sleep a bit to prevent races. thread::sleep(Duration::from_millis(200)); } #[test] #[ignore] // flaky, see https://github.com/tokio-rs/tracing/issues/751 fn logs_dropped_if_lossy() { let (mock_writer, rx) = MockWriter::new(1); let (mut non_blocking, _guard) = self::NonBlockingBuilder::default() .lossy(true) .buffered_lines_limit(1) .finish(mock_writer); let error_count = non_blocking.error_counter(); // First write will not block write_non_blocking(&mut non_blocking, b"Hello"); assert_eq!(0, error_count.dropped_lines()); // Second write will not block as Worker will have called `recv` on channel. // "Hello" is not yet consumed. MockWriter call to write_all will block until // "Hello" is consumed. write_non_blocking(&mut non_blocking, b", World"); assert_eq!(0, error_count.dropped_lines()); // Will sit in NonBlocking channel's buffer. write_non_blocking(&mut non_blocking, b"Test"); assert_eq!(0, error_count.dropped_lines()); // Allow a line to be written. "Hello" message will be consumed. // ", World" will be able to write to MockWriter. // "Test" will block on call to MockWriter's `write_all` let line = rx.recv().unwrap(); assert_eq!(line, "Hello"); // This will block as NonBlocking channel is full. write_non_blocking(&mut non_blocking, b"Universe"); assert_eq!(1, error_count.dropped_lines()); // Finally the second message sent will be consumed. let line = rx.recv().unwrap(); assert_eq!(line, ", World"); assert_eq!(1, error_count.dropped_lines()); } #[test] fn multi_threaded_writes() { let (mock_writer, rx) = MockWriter::new(DEFAULT_BUFFERED_LINES_LIMIT); let (non_blocking, _guard) = self::NonBlockingBuilder::default() .lossy(true) .finish(mock_writer); let error_count = non_blocking.error_counter(); let mut join_handles: Vec<JoinHandle<()>> = Vec::with_capacity(10); for _ in 0..10 { let cloned_non_blocking = non_blocking.clone(); join_handles.push(thread::spawn(move || { let collector = tracing_subscriber::fmt().with_writer(cloned_non_blocking); tracing::collect::with_default(collector.finish(), || { tracing::event!(tracing::Level::INFO, "Hello"); }); })); } for handle in join_handles { handle.join().expect("Failed to join thread"); } let mut hello_count: u8 = 0; while let Ok(event_str) = rx.recv_timeout(Duration::from_secs(5)) { assert!(event_str.contains("Hello")); hello_count += 1; } assert_eq!(10, hello_count); assert_eq!(0, error_count.dropped_lines()); } }
write
identifier_name
non_blocking.rs
//! A non-blocking, off-thread writer. //! //! This spawns a dedicated worker thread which is responsible for writing log //! lines to the provided writer. When a line is written using the returned //! `NonBlocking` struct's `make_writer` method, it will be enqueued to be //! written by the worker thread. //! //! The queue has a fixed capacity, and if it becomes full, any logs written //! to it will be dropped until capacity is once again available. This may //! occur if logs are consistently produced faster than the worker thread can //! output them. The queue capacity and behavior when full (i.e., whether to //! drop logs or to exert backpressure to slow down senders) can be configured //! using [`NonBlockingBuilder::default()`][builder]. //! This function returns the default configuration. It is equivalent to: //! //! ```rust //! # use tracing_appender::non_blocking::{NonBlocking, WorkerGuard}; //! # fn doc() -> (NonBlocking, WorkerGuard) { //! tracing_appender::non_blocking(std::io::stdout()) //! # } //! ``` //! [builder]: NonBlockingBuilder::default() //! //! <br/> This function returns a tuple of `NonBlocking` and `WorkerGuard`. //! `NonBlocking` implements [`MakeWriter`] which integrates with `tracing_subscriber`. //! `WorkerGuard` is a drop guard that is responsible for flushing any remaining logs when //! the program terminates. //! //! Note that the `WorkerGuard` returned by `non_blocking` _must_ be assigned to a binding that //! is not `_`, as `_` will result in the `WorkerGuard` being dropped immediately. //! Unintentional drops of `WorkerGuard` remove the guarantee that logs will be flushed //! during a program's termination, in a panic or otherwise. //! //! See [`WorkerGuard`][worker_guard] for examples of using the guard. //! //! [worker_guard]: WorkerGuard //! //! # Examples //! //! ``` rust //! # fn docs() { //! let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout()); //! let collector = tracing_subscriber::fmt().with_writer(non_blocking); //! tracing::collect::with_default(collector.finish(), || { //! tracing::event!(tracing::Level::INFO, "Hello"); //! }); //! # } //! ``` use crate::worker::Worker; use crate::Msg; use crossbeam_channel::{bounded, SendTimeoutError, Sender}; use std::io; use std::io::Write; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread::JoinHandle; use std::time::Duration; use tracing_subscriber::fmt::MakeWriter; /// The default maximum number of buffered log lines. /// /// If [`NonBlocking`][non-blocking] is lossy, it will drop spans/events at capacity. /// If [`NonBlocking`][non-blocking] is _not_ lossy, /// backpressure will be exerted on senders, causing them to block their /// respective threads until there is available capacity. /// /// [non-blocking]: NonBlocking /// Recommended to be a power of 2. pub const DEFAULT_BUFFERED_LINES_LIMIT: usize = 128_000; /// A guard that flushes spans/events associated to a [`NonBlocking`] on a drop /// /// Writing to a [`NonBlocking`] writer will **not** immediately write a span or event to the underlying /// output. Instead, the span or event will be written by a dedicated logging thread at some later point. /// To increase throughput, the non-blocking writer will flush to the underlying output on /// a periodic basis rather than every time a span or event is written. This means that if the program /// terminates abruptly (such as through an uncaught `panic` or a `std::process::exit`), some spans /// or events may not be written. /// /// Since spans/events and events recorded near a crash are often necessary for diagnosing the failure, /// `WorkerGuard` provides a mechanism to ensure that _all_ buffered logs are flushed to their output. /// `WorkerGuard` should be assigned in the `main` function or whatever the entrypoint of the program is. /// This will ensure that the guard will be dropped during an unwinding or when `main` exits /// successfully. /// /// # Examples /// /// ``` rust /// # #[clippy::allow(needless_doctest_main)] /// fn main () { /// # fn doc() { /// let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout()); /// let collector = tracing_subscriber::fmt().with_writer(non_blocking); /// tracing::collect::with_default(collector.finish(), || { /// // Emit some tracing events within context of the non_blocking `_guard` and tracing subscriber /// tracing::event!(tracing::Level::INFO, "Hello"); /// }); /// // Exiting the context of `main` will drop the `_guard` and any remaining logs should get flushed /// # } /// } /// ``` #[must_use] #[derive(Debug)] pub struct WorkerGuard { handle: Option<JoinHandle<()>>, sender: Sender<Msg>, shutdown: Sender<()>, } /// A non-blocking writer. /// /// While the line between "blocking" and "non-blocking" IO is fuzzy, writing to a file is typically /// considered to be a _blocking_ operation. For an application whose `Collector` writes spans and events /// as they are emitted, an application might find the latency profile to be unacceptable. /// `NonBlocking` moves the writing out of an application's data path by sending spans and events /// to a dedicated logging thread. /// /// This struct implements [`MakeWriter`][make_writer] from the `tracing-subscriber` /// crate. Therefore, it can be used with the [`tracing_subscriber::fmt`][fmt] module /// or with any other collector/subscriber implementation that uses the `MakeWriter` trait. /// /// [make_writer]: tracing_subscriber::fmt::MakeWriter /// [fmt]: mod@tracing_subscriber::fmt #[derive(Clone, Debug)] pub struct NonBlocking { error_counter: ErrorCounter, channel: Sender<Msg>, is_lossy: bool, } /// Tracks the number of times a log line was dropped by the background thread. /// /// If the non-blocking writer is not configured in [lossy mode], the error /// count should always be 0. /// /// [lossy mode]: NonBlockingBuilder::lossy #[derive(Clone, Debug)] pub struct ErrorCounter(Arc<AtomicUsize>); impl NonBlocking { /// Returns a new `NonBlocking` writer wrapping the provided `writer`. /// /// The returned `NonBlocking` writer will have the [default configuration][default] values. /// Other configurations can be specified using the [builder] interface. /// /// [default]: NonBlockingBuilder::default() /// [builder]: NonBlockingBuilder pub fn new<T: Write + Send + Sync +'static>(writer: T) -> (NonBlocking, WorkerGuard) { NonBlockingBuilder::default().finish(writer) } fn create<T: Write + Send + Sync +'static>( writer: T, buffered_lines_limit: usize, is_lossy: bool, thread_name: String, ) -> (NonBlocking, WorkerGuard) { let (sender, receiver) = bounded(buffered_lines_limit); let (shutdown_sender, shutdown_receiver) = bounded(0); let worker = Worker::new(receiver, writer, shutdown_receiver); let worker_guard = WorkerGuard::new( worker.worker_thread(thread_name), sender.clone(), shutdown_sender, ); ( Self { channel: sender, error_counter: ErrorCounter(Arc::new(AtomicUsize::new(0))), is_lossy, }, worker_guard, ) } /// Returns a counter for the number of times logs where dropped. This will always return zero if /// `NonBlocking` is not lossy. pub fn error_counter(&self) -> ErrorCounter { self.error_counter.clone() } } /// A builder for [`NonBlocking`][non-blocking]. /// /// [non-blocking]: NonBlocking #[derive(Debug)] pub struct NonBlockingBuilder { buffered_lines_limit: usize, is_lossy: bool, thread_name: String, } impl NonBlockingBuilder { /// Sets the number of lines to buffer before dropping logs or exerting backpressure on senders pub fn buffered_lines_limit(mut self, buffered_lines_limit: usize) -> NonBlockingBuilder { self.buffered_lines_limit = buffered_lines_limit; self } /// Sets whether `NonBlocking` should be lossy or not. /// /// If set to `true`, logs will be dropped when the buffered limit is reached. If `false`, backpressure /// will be exerted on senders, blocking them until the buffer has capacity again. /// /// By default, the built `NonBlocking` will be lossy. pub fn lossy(mut self, is_lossy: bool) -> NonBlockingBuilder { self.is_lossy = is_lossy; self } /// Override the worker thread's name. /// /// The default worker thread name is "tracing-appender". pub fn thread_name(mut self, name: &str) -> NonBlockingBuilder { self.thread_name = name.to_string(); self } /// Completes the builder, returning the configured `NonBlocking`. pub fn finish<T: Write + Send + Sync +'static>(self, writer: T) -> (NonBlocking, WorkerGuard) { NonBlocking::create( writer, self.buffered_lines_limit, self.is_lossy, self.thread_name, ) } } impl Default for NonBlockingBuilder { fn default() -> Self { NonBlockingBuilder { buffered_lines_limit: DEFAULT_BUFFERED_LINES_LIMIT, is_lossy: true, thread_name: "tracing-appender".to_string(), } } } impl std::io::Write for NonBlocking { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let buf_size = buf.len(); if self.is_lossy { if self.channel.try_send(Msg::Line(buf.to_vec())).is_err() { self.error_counter.incr_saturating(); } } else
Ok(buf_size) } fn flush(&mut self) -> io::Result<()> { Ok(()) } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.write(buf).map(|_| ()) } } impl<'a> MakeWriter<'a> for NonBlocking { type Writer = NonBlocking; fn make_writer(&'a self) -> Self::Writer { self.clone() } } impl WorkerGuard { fn new(handle: JoinHandle<()>, sender: Sender<Msg>, shutdown: Sender<()>) -> Self { WorkerGuard { handle: Some(handle), sender, shutdown, } } } impl Drop for WorkerGuard { fn drop(&mut self) { let timeout = Duration::from_millis(100); match self.sender.send_timeout(Msg::Shutdown, timeout) { Ok(_) => { // Attempt to wait for `Worker` to flush all messages before dropping. This happens // when the `Worker` calls `recv()` on a zero-capacity channel. Use `send_timeout` // so that drop is not blocked indefinitely. // TODO: Make timeout configurable. let timeout = Duration::from_millis(1000); match self.shutdown.send_timeout((), timeout) { Err(SendTimeoutError::Timeout(_)) => { eprintln!( "Shutting down logging worker timed out after {:?}.", timeout ); } _ => { // At this point it is safe to wait for `Worker` destruction without blocking if let Some(handle) = self.handle.take() { if handle.join().is_err() { eprintln!("Logging worker thread panicked"); } }; } } } Err(SendTimeoutError::Disconnected(_)) => (), Err(SendTimeoutError::Timeout(_)) => eprintln!( "Sending shutdown signal to logging worker timed out after {:?}", timeout ), } } } // === impl ErrorCounter === impl ErrorCounter { /// Returns the number of log lines that have been dropped. /// /// If the non-blocking writer is not configured in [lossy mode], the error /// count should always be 0. /// /// [lossy mode]: NonBlockingBuilder::lossy pub fn dropped_lines(&self) -> usize { self.0.load(Ordering::Acquire) } fn incr_saturating(&self) { let mut curr = self.0.load(Ordering::Acquire); // We don't need to enter the CAS loop if the current value is already // `usize::MAX`. if curr == usize::MAX { return; } // This is implemented as a CAS loop rather than as a simple // `fetch_add`, because we don't want to wrap on overflow. Instead, we // need to ensure that saturating addition is performed. loop { let val = curr.saturating_add(1); match self .0 .compare_exchange(curr, val, Ordering::AcqRel, Ordering::Acquire) { Ok(_) => return, Err(actual) => curr = actual, } } } } #[cfg(test)] mod test { use super::*; use std::sync::mpsc; use std::thread; use std::time::Duration; struct MockWriter { tx: mpsc::SyncSender<String>, } impl MockWriter { fn new(capacity: usize) -> (Self, mpsc::Receiver<String>) { let (tx, rx) = mpsc::sync_channel(capacity); (Self { tx }, rx) } } impl std::io::Write for MockWriter { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { let buf_len = buf.len(); let _ = self.tx.send(String::from_utf8_lossy(buf).to_string()); Ok(buf_len) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } #[test] fn backpressure_exerted() { let (mock_writer, rx) = MockWriter::new(1); let (mut non_blocking, _guard) = self::NonBlockingBuilder::default() .lossy(false) .buffered_lines_limit(1) .finish(mock_writer); let error_count = non_blocking.error_counter(); non_blocking.write_all(b"Hello").expect("Failed to write"); assert_eq!(0, error_count.dropped_lines()); let handle = thread::spawn(move || { non_blocking.write_all(b", World").expect("Failed to write"); }); // Sleep a little to ensure previously spawned thread gets blocked on write. thread::sleep(Duration::from_millis(100)); // We should not drop logs when blocked. assert_eq!(0, error_count.dropped_lines()); // Read the first message to unblock sender. let mut line = rx.recv().unwrap(); assert_eq!(line, "Hello"); // Wait for thread to finish. handle.join().expect("thread should not panic"); // Thread has joined, we should be able to read the message it sent. line = rx.recv().unwrap(); assert_eq!(line, ", World"); } fn write_non_blocking(non_blocking: &mut NonBlocking, msg: &[u8]) { non_blocking.write_all(msg).expect("Failed to write"); // Sleep a bit to prevent races. thread::sleep(Duration::from_millis(200)); } #[test] #[ignore] // flaky, see https://github.com/tokio-rs/tracing/issues/751 fn logs_dropped_if_lossy() { let (mock_writer, rx) = MockWriter::new(1); let (mut non_blocking, _guard) = self::NonBlockingBuilder::default() .lossy(true) .buffered_lines_limit(1) .finish(mock_writer); let error_count = non_blocking.error_counter(); // First write will not block write_non_blocking(&mut non_blocking, b"Hello"); assert_eq!(0, error_count.dropped_lines()); // Second write will not block as Worker will have called `recv` on channel. // "Hello" is not yet consumed. MockWriter call to write_all will block until // "Hello" is consumed. write_non_blocking(&mut non_blocking, b", World"); assert_eq!(0, error_count.dropped_lines()); // Will sit in NonBlocking channel's buffer. write_non_blocking(&mut non_blocking, b"Test"); assert_eq!(0, error_count.dropped_lines()); // Allow a line to be written. "Hello" message will be consumed. // ", World" will be able to write to MockWriter. // "Test" will block on call to MockWriter's `write_all` let line = rx.recv().unwrap(); assert_eq!(line, "Hello"); // This will block as NonBlocking channel is full. write_non_blocking(&mut non_blocking, b"Universe"); assert_eq!(1, error_count.dropped_lines()); // Finally the second message sent will be consumed. let line = rx.recv().unwrap(); assert_eq!(line, ", World"); assert_eq!(1, error_count.dropped_lines()); } #[test] fn multi_threaded_writes() { let (mock_writer, rx) = MockWriter::new(DEFAULT_BUFFERED_LINES_LIMIT); let (non_blocking, _guard) = self::NonBlockingBuilder::default() .lossy(true) .finish(mock_writer); let error_count = non_blocking.error_counter(); let mut join_handles: Vec<JoinHandle<()>> = Vec::with_capacity(10); for _ in 0..10 { let cloned_non_blocking = non_blocking.clone(); join_handles.push(thread::spawn(move || { let collector = tracing_subscriber::fmt().with_writer(cloned_non_blocking); tracing::collect::with_default(collector.finish(), || { tracing::event!(tracing::Level::INFO, "Hello"); }); })); } for handle in join_handles { handle.join().expect("Failed to join thread"); } let mut hello_count: u8 = 0; while let Ok(event_str) = rx.recv_timeout(Duration::from_secs(5)) { assert!(event_str.contains("Hello")); hello_count += 1; } assert_eq!(10, hello_count); assert_eq!(0, error_count.dropped_lines()); } }
{ return match self.channel.send(Msg::Line(buf.to_vec())) { Ok(_) => Ok(buf_size), Err(_) => Err(io::Error::from(io::ErrorKind::Other)), }; }
conditional_block
non_blocking.rs
//! A non-blocking, off-thread writer. //! //! This spawns a dedicated worker thread which is responsible for writing log //! lines to the provided writer. When a line is written using the returned //! `NonBlocking` struct's `make_writer` method, it will be enqueued to be //! written by the worker thread. //! //! The queue has a fixed capacity, and if it becomes full, any logs written //! to it will be dropped until capacity is once again available. This may //! occur if logs are consistently produced faster than the worker thread can //! output them. The queue capacity and behavior when full (i.e., whether to //! drop logs or to exert backpressure to slow down senders) can be configured //! using [`NonBlockingBuilder::default()`][builder]. //! This function returns the default configuration. It is equivalent to: //! //! ```rust //! # use tracing_appender::non_blocking::{NonBlocking, WorkerGuard}; //! # fn doc() -> (NonBlocking, WorkerGuard) { //! tracing_appender::non_blocking(std::io::stdout()) //! # } //! ``` //! [builder]: NonBlockingBuilder::default() //! //! <br/> This function returns a tuple of `NonBlocking` and `WorkerGuard`. //! `NonBlocking` implements [`MakeWriter`] which integrates with `tracing_subscriber`. //! `WorkerGuard` is a drop guard that is responsible for flushing any remaining logs when //! the program terminates. //! //! Note that the `WorkerGuard` returned by `non_blocking` _must_ be assigned to a binding that //! is not `_`, as `_` will result in the `WorkerGuard` being dropped immediately. //! Unintentional drops of `WorkerGuard` remove the guarantee that logs will be flushed //! during a program's termination, in a panic or otherwise. //! //! See [`WorkerGuard`][worker_guard] for examples of using the guard. //! //! [worker_guard]: WorkerGuard //! //! # Examples //! //! ``` rust //! # fn docs() { //! let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout()); //! let collector = tracing_subscriber::fmt().with_writer(non_blocking); //! tracing::collect::with_default(collector.finish(), || { //! tracing::event!(tracing::Level::INFO, "Hello"); //! }); //! # } //! ``` use crate::worker::Worker; use crate::Msg; use crossbeam_channel::{bounded, SendTimeoutError, Sender}; use std::io; use std::io::Write; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread::JoinHandle; use std::time::Duration; use tracing_subscriber::fmt::MakeWriter; /// The default maximum number of buffered log lines. /// /// If [`NonBlocking`][non-blocking] is lossy, it will drop spans/events at capacity. /// If [`NonBlocking`][non-blocking] is _not_ lossy, /// backpressure will be exerted on senders, causing them to block their /// respective threads until there is available capacity. /// /// [non-blocking]: NonBlocking /// Recommended to be a power of 2. pub const DEFAULT_BUFFERED_LINES_LIMIT: usize = 128_000; /// A guard that flushes spans/events associated to a [`NonBlocking`] on a drop /// /// Writing to a [`NonBlocking`] writer will **not** immediately write a span or event to the underlying /// output. Instead, the span or event will be written by a dedicated logging thread at some later point. /// To increase throughput, the non-blocking writer will flush to the underlying output on /// a periodic basis rather than every time a span or event is written. This means that if the program /// terminates abruptly (such as through an uncaught `panic` or a `std::process::exit`), some spans /// or events may not be written. /// /// Since spans/events and events recorded near a crash are often necessary for diagnosing the failure, /// `WorkerGuard` provides a mechanism to ensure that _all_ buffered logs are flushed to their output. /// `WorkerGuard` should be assigned in the `main` function or whatever the entrypoint of the program is. /// This will ensure that the guard will be dropped during an unwinding or when `main` exits /// successfully. /// /// # Examples /// /// ``` rust /// # #[clippy::allow(needless_doctest_main)] /// fn main () { /// # fn doc() { /// let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout()); /// let collector = tracing_subscriber::fmt().with_writer(non_blocking); /// tracing::collect::with_default(collector.finish(), || { /// // Emit some tracing events within context of the non_blocking `_guard` and tracing subscriber /// tracing::event!(tracing::Level::INFO, "Hello"); /// }); /// // Exiting the context of `main` will drop the `_guard` and any remaining logs should get flushed /// # } /// } /// ``` #[must_use] #[derive(Debug)] pub struct WorkerGuard { handle: Option<JoinHandle<()>>, sender: Sender<Msg>, shutdown: Sender<()>, } /// A non-blocking writer. /// /// While the line between "blocking" and "non-blocking" IO is fuzzy, writing to a file is typically /// considered to be a _blocking_ operation. For an application whose `Collector` writes spans and events /// as they are emitted, an application might find the latency profile to be unacceptable. /// `NonBlocking` moves the writing out of an application's data path by sending spans and events /// to a dedicated logging thread. /// /// This struct implements [`MakeWriter`][make_writer] from the `tracing-subscriber` /// crate. Therefore, it can be used with the [`tracing_subscriber::fmt`][fmt] module /// or with any other collector/subscriber implementation that uses the `MakeWriter` trait. /// /// [make_writer]: tracing_subscriber::fmt::MakeWriter /// [fmt]: mod@tracing_subscriber::fmt #[derive(Clone, Debug)] pub struct NonBlocking { error_counter: ErrorCounter, channel: Sender<Msg>, is_lossy: bool, } /// Tracks the number of times a log line was dropped by the background thread. /// /// If the non-blocking writer is not configured in [lossy mode], the error /// count should always be 0. /// /// [lossy mode]: NonBlockingBuilder::lossy #[derive(Clone, Debug)] pub struct ErrorCounter(Arc<AtomicUsize>); impl NonBlocking { /// Returns a new `NonBlocking` writer wrapping the provided `writer`. /// /// The returned `NonBlocking` writer will have the [default configuration][default] values. /// Other configurations can be specified using the [builder] interface. /// /// [default]: NonBlockingBuilder::default() /// [builder]: NonBlockingBuilder pub fn new<T: Write + Send + Sync +'static>(writer: T) -> (NonBlocking, WorkerGuard) { NonBlockingBuilder::default().finish(writer) } fn create<T: Write + Send + Sync +'static>( writer: T, buffered_lines_limit: usize, is_lossy: bool, thread_name: String, ) -> (NonBlocking, WorkerGuard) { let (sender, receiver) = bounded(buffered_lines_limit); let (shutdown_sender, shutdown_receiver) = bounded(0); let worker = Worker::new(receiver, writer, shutdown_receiver); let worker_guard = WorkerGuard::new( worker.worker_thread(thread_name), sender.clone(), shutdown_sender, ); ( Self { channel: sender, error_counter: ErrorCounter(Arc::new(AtomicUsize::new(0))), is_lossy, }, worker_guard, ) } /// Returns a counter for the number of times logs where dropped. This will always return zero if /// `NonBlocking` is not lossy. pub fn error_counter(&self) -> ErrorCounter { self.error_counter.clone() } } /// A builder for [`NonBlocking`][non-blocking]. /// /// [non-blocking]: NonBlocking #[derive(Debug)] pub struct NonBlockingBuilder { buffered_lines_limit: usize, is_lossy: bool, thread_name: String, } impl NonBlockingBuilder { /// Sets the number of lines to buffer before dropping logs or exerting backpressure on senders pub fn buffered_lines_limit(mut self, buffered_lines_limit: usize) -> NonBlockingBuilder { self.buffered_lines_limit = buffered_lines_limit; self } /// Sets whether `NonBlocking` should be lossy or not. /// /// If set to `true`, logs will be dropped when the buffered limit is reached. If `false`, backpressure /// will be exerted on senders, blocking them until the buffer has capacity again.
/// /// By default, the built `NonBlocking` will be lossy. pub fn lossy(mut self, is_lossy: bool) -> NonBlockingBuilder { self.is_lossy = is_lossy; self } /// Override the worker thread's name. /// /// The default worker thread name is "tracing-appender". pub fn thread_name(mut self, name: &str) -> NonBlockingBuilder { self.thread_name = name.to_string(); self } /// Completes the builder, returning the configured `NonBlocking`. pub fn finish<T: Write + Send + Sync +'static>(self, writer: T) -> (NonBlocking, WorkerGuard) { NonBlocking::create( writer, self.buffered_lines_limit, self.is_lossy, self.thread_name, ) } } impl Default for NonBlockingBuilder { fn default() -> Self { NonBlockingBuilder { buffered_lines_limit: DEFAULT_BUFFERED_LINES_LIMIT, is_lossy: true, thread_name: "tracing-appender".to_string(), } } } impl std::io::Write for NonBlocking { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let buf_size = buf.len(); if self.is_lossy { if self.channel.try_send(Msg::Line(buf.to_vec())).is_err() { self.error_counter.incr_saturating(); } } else { return match self.channel.send(Msg::Line(buf.to_vec())) { Ok(_) => Ok(buf_size), Err(_) => Err(io::Error::from(io::ErrorKind::Other)), }; } Ok(buf_size) } fn flush(&mut self) -> io::Result<()> { Ok(()) } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.write(buf).map(|_| ()) } } impl<'a> MakeWriter<'a> for NonBlocking { type Writer = NonBlocking; fn make_writer(&'a self) -> Self::Writer { self.clone() } } impl WorkerGuard { fn new(handle: JoinHandle<()>, sender: Sender<Msg>, shutdown: Sender<()>) -> Self { WorkerGuard { handle: Some(handle), sender, shutdown, } } } impl Drop for WorkerGuard { fn drop(&mut self) { let timeout = Duration::from_millis(100); match self.sender.send_timeout(Msg::Shutdown, timeout) { Ok(_) => { // Attempt to wait for `Worker` to flush all messages before dropping. This happens // when the `Worker` calls `recv()` on a zero-capacity channel. Use `send_timeout` // so that drop is not blocked indefinitely. // TODO: Make timeout configurable. let timeout = Duration::from_millis(1000); match self.shutdown.send_timeout((), timeout) { Err(SendTimeoutError::Timeout(_)) => { eprintln!( "Shutting down logging worker timed out after {:?}.", timeout ); } _ => { // At this point it is safe to wait for `Worker` destruction without blocking if let Some(handle) = self.handle.take() { if handle.join().is_err() { eprintln!("Logging worker thread panicked"); } }; } } } Err(SendTimeoutError::Disconnected(_)) => (), Err(SendTimeoutError::Timeout(_)) => eprintln!( "Sending shutdown signal to logging worker timed out after {:?}", timeout ), } } } // === impl ErrorCounter === impl ErrorCounter { /// Returns the number of log lines that have been dropped. /// /// If the non-blocking writer is not configured in [lossy mode], the error /// count should always be 0. /// /// [lossy mode]: NonBlockingBuilder::lossy pub fn dropped_lines(&self) -> usize { self.0.load(Ordering::Acquire) } fn incr_saturating(&self) { let mut curr = self.0.load(Ordering::Acquire); // We don't need to enter the CAS loop if the current value is already // `usize::MAX`. if curr == usize::MAX { return; } // This is implemented as a CAS loop rather than as a simple // `fetch_add`, because we don't want to wrap on overflow. Instead, we // need to ensure that saturating addition is performed. loop { let val = curr.saturating_add(1); match self .0 .compare_exchange(curr, val, Ordering::AcqRel, Ordering::Acquire) { Ok(_) => return, Err(actual) => curr = actual, } } } } #[cfg(test)] mod test { use super::*; use std::sync::mpsc; use std::thread; use std::time::Duration; struct MockWriter { tx: mpsc::SyncSender<String>, } impl MockWriter { fn new(capacity: usize) -> (Self, mpsc::Receiver<String>) { let (tx, rx) = mpsc::sync_channel(capacity); (Self { tx }, rx) } } impl std::io::Write for MockWriter { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { let buf_len = buf.len(); let _ = self.tx.send(String::from_utf8_lossy(buf).to_string()); Ok(buf_len) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } #[test] fn backpressure_exerted() { let (mock_writer, rx) = MockWriter::new(1); let (mut non_blocking, _guard) = self::NonBlockingBuilder::default() .lossy(false) .buffered_lines_limit(1) .finish(mock_writer); let error_count = non_blocking.error_counter(); non_blocking.write_all(b"Hello").expect("Failed to write"); assert_eq!(0, error_count.dropped_lines()); let handle = thread::spawn(move || { non_blocking.write_all(b", World").expect("Failed to write"); }); // Sleep a little to ensure previously spawned thread gets blocked on write. thread::sleep(Duration::from_millis(100)); // We should not drop logs when blocked. assert_eq!(0, error_count.dropped_lines()); // Read the first message to unblock sender. let mut line = rx.recv().unwrap(); assert_eq!(line, "Hello"); // Wait for thread to finish. handle.join().expect("thread should not panic"); // Thread has joined, we should be able to read the message it sent. line = rx.recv().unwrap(); assert_eq!(line, ", World"); } fn write_non_blocking(non_blocking: &mut NonBlocking, msg: &[u8]) { non_blocking.write_all(msg).expect("Failed to write"); // Sleep a bit to prevent races. thread::sleep(Duration::from_millis(200)); } #[test] #[ignore] // flaky, see https://github.com/tokio-rs/tracing/issues/751 fn logs_dropped_if_lossy() { let (mock_writer, rx) = MockWriter::new(1); let (mut non_blocking, _guard) = self::NonBlockingBuilder::default() .lossy(true) .buffered_lines_limit(1) .finish(mock_writer); let error_count = non_blocking.error_counter(); // First write will not block write_non_blocking(&mut non_blocking, b"Hello"); assert_eq!(0, error_count.dropped_lines()); // Second write will not block as Worker will have called `recv` on channel. // "Hello" is not yet consumed. MockWriter call to write_all will block until // "Hello" is consumed. write_non_blocking(&mut non_blocking, b", World"); assert_eq!(0, error_count.dropped_lines()); // Will sit in NonBlocking channel's buffer. write_non_blocking(&mut non_blocking, b"Test"); assert_eq!(0, error_count.dropped_lines()); // Allow a line to be written. "Hello" message will be consumed. // ", World" will be able to write to MockWriter. // "Test" will block on call to MockWriter's `write_all` let line = rx.recv().unwrap(); assert_eq!(line, "Hello"); // This will block as NonBlocking channel is full. write_non_blocking(&mut non_blocking, b"Universe"); assert_eq!(1, error_count.dropped_lines()); // Finally the second message sent will be consumed. let line = rx.recv().unwrap(); assert_eq!(line, ", World"); assert_eq!(1, error_count.dropped_lines()); } #[test] fn multi_threaded_writes() { let (mock_writer, rx) = MockWriter::new(DEFAULT_BUFFERED_LINES_LIMIT); let (non_blocking, _guard) = self::NonBlockingBuilder::default() .lossy(true) .finish(mock_writer); let error_count = non_blocking.error_counter(); let mut join_handles: Vec<JoinHandle<()>> = Vec::with_capacity(10); for _ in 0..10 { let cloned_non_blocking = non_blocking.clone(); join_handles.push(thread::spawn(move || { let collector = tracing_subscriber::fmt().with_writer(cloned_non_blocking); tracing::collect::with_default(collector.finish(), || { tracing::event!(tracing::Level::INFO, "Hello"); }); })); } for handle in join_handles { handle.join().expect("Failed to join thread"); } let mut hello_count: u8 = 0; while let Ok(event_str) = rx.recv_timeout(Duration::from_secs(5)) { assert!(event_str.contains("Hello")); hello_count += 1; } assert_eq!(10, hello_count); assert_eq!(0, error_count.dropped_lines()); } }
random_line_split
non_blocking.rs
//! A non-blocking, off-thread writer. //! //! This spawns a dedicated worker thread which is responsible for writing log //! lines to the provided writer. When a line is written using the returned //! `NonBlocking` struct's `make_writer` method, it will be enqueued to be //! written by the worker thread. //! //! The queue has a fixed capacity, and if it becomes full, any logs written //! to it will be dropped until capacity is once again available. This may //! occur if logs are consistently produced faster than the worker thread can //! output them. The queue capacity and behavior when full (i.e., whether to //! drop logs or to exert backpressure to slow down senders) can be configured //! using [`NonBlockingBuilder::default()`][builder]. //! This function returns the default configuration. It is equivalent to: //! //! ```rust //! # use tracing_appender::non_blocking::{NonBlocking, WorkerGuard}; //! # fn doc() -> (NonBlocking, WorkerGuard) { //! tracing_appender::non_blocking(std::io::stdout()) //! # } //! ``` //! [builder]: NonBlockingBuilder::default() //! //! <br/> This function returns a tuple of `NonBlocking` and `WorkerGuard`. //! `NonBlocking` implements [`MakeWriter`] which integrates with `tracing_subscriber`. //! `WorkerGuard` is a drop guard that is responsible for flushing any remaining logs when //! the program terminates. //! //! Note that the `WorkerGuard` returned by `non_blocking` _must_ be assigned to a binding that //! is not `_`, as `_` will result in the `WorkerGuard` being dropped immediately. //! Unintentional drops of `WorkerGuard` remove the guarantee that logs will be flushed //! during a program's termination, in a panic or otherwise. //! //! See [`WorkerGuard`][worker_guard] for examples of using the guard. //! //! [worker_guard]: WorkerGuard //! //! # Examples //! //! ``` rust //! # fn docs() { //! let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout()); //! let collector = tracing_subscriber::fmt().with_writer(non_blocking); //! tracing::collect::with_default(collector.finish(), || { //! tracing::event!(tracing::Level::INFO, "Hello"); //! }); //! # } //! ``` use crate::worker::Worker; use crate::Msg; use crossbeam_channel::{bounded, SendTimeoutError, Sender}; use std::io; use std::io::Write; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread::JoinHandle; use std::time::Duration; use tracing_subscriber::fmt::MakeWriter; /// The default maximum number of buffered log lines. /// /// If [`NonBlocking`][non-blocking] is lossy, it will drop spans/events at capacity. /// If [`NonBlocking`][non-blocking] is _not_ lossy, /// backpressure will be exerted on senders, causing them to block their /// respective threads until there is available capacity. /// /// [non-blocking]: NonBlocking /// Recommended to be a power of 2. pub const DEFAULT_BUFFERED_LINES_LIMIT: usize = 128_000; /// A guard that flushes spans/events associated to a [`NonBlocking`] on a drop /// /// Writing to a [`NonBlocking`] writer will **not** immediately write a span or event to the underlying /// output. Instead, the span or event will be written by a dedicated logging thread at some later point. /// To increase throughput, the non-blocking writer will flush to the underlying output on /// a periodic basis rather than every time a span or event is written. This means that if the program /// terminates abruptly (such as through an uncaught `panic` or a `std::process::exit`), some spans /// or events may not be written. /// /// Since spans/events and events recorded near a crash are often necessary for diagnosing the failure, /// `WorkerGuard` provides a mechanism to ensure that _all_ buffered logs are flushed to their output. /// `WorkerGuard` should be assigned in the `main` function or whatever the entrypoint of the program is. /// This will ensure that the guard will be dropped during an unwinding or when `main` exits /// successfully. /// /// # Examples /// /// ``` rust /// # #[clippy::allow(needless_doctest_main)] /// fn main () { /// # fn doc() { /// let (non_blocking, _guard) = tracing_appender::non_blocking(std::io::stdout()); /// let collector = tracing_subscriber::fmt().with_writer(non_blocking); /// tracing::collect::with_default(collector.finish(), || { /// // Emit some tracing events within context of the non_blocking `_guard` and tracing subscriber /// tracing::event!(tracing::Level::INFO, "Hello"); /// }); /// // Exiting the context of `main` will drop the `_guard` and any remaining logs should get flushed /// # } /// } /// ``` #[must_use] #[derive(Debug)] pub struct WorkerGuard { handle: Option<JoinHandle<()>>, sender: Sender<Msg>, shutdown: Sender<()>, } /// A non-blocking writer. /// /// While the line between "blocking" and "non-blocking" IO is fuzzy, writing to a file is typically /// considered to be a _blocking_ operation. For an application whose `Collector` writes spans and events /// as they are emitted, an application might find the latency profile to be unacceptable. /// `NonBlocking` moves the writing out of an application's data path by sending spans and events /// to a dedicated logging thread. /// /// This struct implements [`MakeWriter`][make_writer] from the `tracing-subscriber` /// crate. Therefore, it can be used with the [`tracing_subscriber::fmt`][fmt] module /// or with any other collector/subscriber implementation that uses the `MakeWriter` trait. /// /// [make_writer]: tracing_subscriber::fmt::MakeWriter /// [fmt]: mod@tracing_subscriber::fmt #[derive(Clone, Debug)] pub struct NonBlocking { error_counter: ErrorCounter, channel: Sender<Msg>, is_lossy: bool, } /// Tracks the number of times a log line was dropped by the background thread. /// /// If the non-blocking writer is not configured in [lossy mode], the error /// count should always be 0. /// /// [lossy mode]: NonBlockingBuilder::lossy #[derive(Clone, Debug)] pub struct ErrorCounter(Arc<AtomicUsize>); impl NonBlocking { /// Returns a new `NonBlocking` writer wrapping the provided `writer`. /// /// The returned `NonBlocking` writer will have the [default configuration][default] values. /// Other configurations can be specified using the [builder] interface. /// /// [default]: NonBlockingBuilder::default() /// [builder]: NonBlockingBuilder pub fn new<T: Write + Send + Sync +'static>(writer: T) -> (NonBlocking, WorkerGuard) { NonBlockingBuilder::default().finish(writer) } fn create<T: Write + Send + Sync +'static>( writer: T, buffered_lines_limit: usize, is_lossy: bool, thread_name: String, ) -> (NonBlocking, WorkerGuard) { let (sender, receiver) = bounded(buffered_lines_limit); let (shutdown_sender, shutdown_receiver) = bounded(0); let worker = Worker::new(receiver, writer, shutdown_receiver); let worker_guard = WorkerGuard::new( worker.worker_thread(thread_name), sender.clone(), shutdown_sender, ); ( Self { channel: sender, error_counter: ErrorCounter(Arc::new(AtomicUsize::new(0))), is_lossy, }, worker_guard, ) } /// Returns a counter for the number of times logs where dropped. This will always return zero if /// `NonBlocking` is not lossy. pub fn error_counter(&self) -> ErrorCounter { self.error_counter.clone() } } /// A builder for [`NonBlocking`][non-blocking]. /// /// [non-blocking]: NonBlocking #[derive(Debug)] pub struct NonBlockingBuilder { buffered_lines_limit: usize, is_lossy: bool, thread_name: String, } impl NonBlockingBuilder { /// Sets the number of lines to buffer before dropping logs or exerting backpressure on senders pub fn buffered_lines_limit(mut self, buffered_lines_limit: usize) -> NonBlockingBuilder { self.buffered_lines_limit = buffered_lines_limit; self } /// Sets whether `NonBlocking` should be lossy or not. /// /// If set to `true`, logs will be dropped when the buffered limit is reached. If `false`, backpressure /// will be exerted on senders, blocking them until the buffer has capacity again. /// /// By default, the built `NonBlocking` will be lossy. pub fn lossy(mut self, is_lossy: bool) -> NonBlockingBuilder
/// Override the worker thread's name. /// /// The default worker thread name is "tracing-appender". pub fn thread_name(mut self, name: &str) -> NonBlockingBuilder { self.thread_name = name.to_string(); self } /// Completes the builder, returning the configured `NonBlocking`. pub fn finish<T: Write + Send + Sync +'static>(self, writer: T) -> (NonBlocking, WorkerGuard) { NonBlocking::create( writer, self.buffered_lines_limit, self.is_lossy, self.thread_name, ) } } impl Default for NonBlockingBuilder { fn default() -> Self { NonBlockingBuilder { buffered_lines_limit: DEFAULT_BUFFERED_LINES_LIMIT, is_lossy: true, thread_name: "tracing-appender".to_string(), } } } impl std::io::Write for NonBlocking { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let buf_size = buf.len(); if self.is_lossy { if self.channel.try_send(Msg::Line(buf.to_vec())).is_err() { self.error_counter.incr_saturating(); } } else { return match self.channel.send(Msg::Line(buf.to_vec())) { Ok(_) => Ok(buf_size), Err(_) => Err(io::Error::from(io::ErrorKind::Other)), }; } Ok(buf_size) } fn flush(&mut self) -> io::Result<()> { Ok(()) } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.write(buf).map(|_| ()) } } impl<'a> MakeWriter<'a> for NonBlocking { type Writer = NonBlocking; fn make_writer(&'a self) -> Self::Writer { self.clone() } } impl WorkerGuard { fn new(handle: JoinHandle<()>, sender: Sender<Msg>, shutdown: Sender<()>) -> Self { WorkerGuard { handle: Some(handle), sender, shutdown, } } } impl Drop for WorkerGuard { fn drop(&mut self) { let timeout = Duration::from_millis(100); match self.sender.send_timeout(Msg::Shutdown, timeout) { Ok(_) => { // Attempt to wait for `Worker` to flush all messages before dropping. This happens // when the `Worker` calls `recv()` on a zero-capacity channel. Use `send_timeout` // so that drop is not blocked indefinitely. // TODO: Make timeout configurable. let timeout = Duration::from_millis(1000); match self.shutdown.send_timeout((), timeout) { Err(SendTimeoutError::Timeout(_)) => { eprintln!( "Shutting down logging worker timed out after {:?}.", timeout ); } _ => { // At this point it is safe to wait for `Worker` destruction without blocking if let Some(handle) = self.handle.take() { if handle.join().is_err() { eprintln!("Logging worker thread panicked"); } }; } } } Err(SendTimeoutError::Disconnected(_)) => (), Err(SendTimeoutError::Timeout(_)) => eprintln!( "Sending shutdown signal to logging worker timed out after {:?}", timeout ), } } } // === impl ErrorCounter === impl ErrorCounter { /// Returns the number of log lines that have been dropped. /// /// If the non-blocking writer is not configured in [lossy mode], the error /// count should always be 0. /// /// [lossy mode]: NonBlockingBuilder::lossy pub fn dropped_lines(&self) -> usize { self.0.load(Ordering::Acquire) } fn incr_saturating(&self) { let mut curr = self.0.load(Ordering::Acquire); // We don't need to enter the CAS loop if the current value is already // `usize::MAX`. if curr == usize::MAX { return; } // This is implemented as a CAS loop rather than as a simple // `fetch_add`, because we don't want to wrap on overflow. Instead, we // need to ensure that saturating addition is performed. loop { let val = curr.saturating_add(1); match self .0 .compare_exchange(curr, val, Ordering::AcqRel, Ordering::Acquire) { Ok(_) => return, Err(actual) => curr = actual, } } } } #[cfg(test)] mod test { use super::*; use std::sync::mpsc; use std::thread; use std::time::Duration; struct MockWriter { tx: mpsc::SyncSender<String>, } impl MockWriter { fn new(capacity: usize) -> (Self, mpsc::Receiver<String>) { let (tx, rx) = mpsc::sync_channel(capacity); (Self { tx }, rx) } } impl std::io::Write for MockWriter { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { let buf_len = buf.len(); let _ = self.tx.send(String::from_utf8_lossy(buf).to_string()); Ok(buf_len) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } #[test] fn backpressure_exerted() { let (mock_writer, rx) = MockWriter::new(1); let (mut non_blocking, _guard) = self::NonBlockingBuilder::default() .lossy(false) .buffered_lines_limit(1) .finish(mock_writer); let error_count = non_blocking.error_counter(); non_blocking.write_all(b"Hello").expect("Failed to write"); assert_eq!(0, error_count.dropped_lines()); let handle = thread::spawn(move || { non_blocking.write_all(b", World").expect("Failed to write"); }); // Sleep a little to ensure previously spawned thread gets blocked on write. thread::sleep(Duration::from_millis(100)); // We should not drop logs when blocked. assert_eq!(0, error_count.dropped_lines()); // Read the first message to unblock sender. let mut line = rx.recv().unwrap(); assert_eq!(line, "Hello"); // Wait for thread to finish. handle.join().expect("thread should not panic"); // Thread has joined, we should be able to read the message it sent. line = rx.recv().unwrap(); assert_eq!(line, ", World"); } fn write_non_blocking(non_blocking: &mut NonBlocking, msg: &[u8]) { non_blocking.write_all(msg).expect("Failed to write"); // Sleep a bit to prevent races. thread::sleep(Duration::from_millis(200)); } #[test] #[ignore] // flaky, see https://github.com/tokio-rs/tracing/issues/751 fn logs_dropped_if_lossy() { let (mock_writer, rx) = MockWriter::new(1); let (mut non_blocking, _guard) = self::NonBlockingBuilder::default() .lossy(true) .buffered_lines_limit(1) .finish(mock_writer); let error_count = non_blocking.error_counter(); // First write will not block write_non_blocking(&mut non_blocking, b"Hello"); assert_eq!(0, error_count.dropped_lines()); // Second write will not block as Worker will have called `recv` on channel. // "Hello" is not yet consumed. MockWriter call to write_all will block until // "Hello" is consumed. write_non_blocking(&mut non_blocking, b", World"); assert_eq!(0, error_count.dropped_lines()); // Will sit in NonBlocking channel's buffer. write_non_blocking(&mut non_blocking, b"Test"); assert_eq!(0, error_count.dropped_lines()); // Allow a line to be written. "Hello" message will be consumed. // ", World" will be able to write to MockWriter. // "Test" will block on call to MockWriter's `write_all` let line = rx.recv().unwrap(); assert_eq!(line, "Hello"); // This will block as NonBlocking channel is full. write_non_blocking(&mut non_blocking, b"Universe"); assert_eq!(1, error_count.dropped_lines()); // Finally the second message sent will be consumed. let line = rx.recv().unwrap(); assert_eq!(line, ", World"); assert_eq!(1, error_count.dropped_lines()); } #[test] fn multi_threaded_writes() { let (mock_writer, rx) = MockWriter::new(DEFAULT_BUFFERED_LINES_LIMIT); let (non_blocking, _guard) = self::NonBlockingBuilder::default() .lossy(true) .finish(mock_writer); let error_count = non_blocking.error_counter(); let mut join_handles: Vec<JoinHandle<()>> = Vec::with_capacity(10); for _ in 0..10 { let cloned_non_blocking = non_blocking.clone(); join_handles.push(thread::spawn(move || { let collector = tracing_subscriber::fmt().with_writer(cloned_non_blocking); tracing::collect::with_default(collector.finish(), || { tracing::event!(tracing::Level::INFO, "Hello"); }); })); } for handle in join_handles { handle.join().expect("Failed to join thread"); } let mut hello_count: u8 = 0; while let Ok(event_str) = rx.recv_timeout(Duration::from_secs(5)) { assert!(event_str.contains("Hello")); hello_count += 1; } assert_eq!(10, hello_count); assert_eq!(0, error_count.dropped_lines()); } }
{ self.is_lossy = is_lossy; self }
identifier_body
key.rs
//! Protected key //! use std::cell::{Cell, Ref, RefCell, RefMut, BorrowState}; use std::fmt::{self, Debug}; use std::ops::{Deref, DerefMut}; use std::rc::Rc; use allocator::{Allocator, KeyAllocator, DefaultKeyAllocator}; use buf::ProtBuf; /// Key of bytes pub type ProtKey8<A = DefaultKeyAllocator> = ProtKey<u8, A>; const NOREAD: usize = 0; /// A protected key /// /// Transform a `ProtBuf` instance into a protected key `ProtKey` and provide /// tigher access control on its memory. /// /// By default a `ProtKey` cannot be read nor written to and will only /// provide separated accesses with limited scopes. Thus, RAII accessor /// methods must be used to read and write to a `ProtKey`. Accessing the /// underlying key is a bit similar to the way of manipulating an object /// wrapped in `RefCell`. /// /// ```rust /// # extern crate tars; /// # use tars::allocator::ProtectedKeyAllocator; /// # use tars::{ProtKey, ProtBuf, ProtKey8}; /// # fn encrypt(_: &[u8], _: &[u8]) {} /// # fn main() { /// // Instantiate a new buffer initialized with random bytes. /// // Same as an usual ProtBuf instance but with a different allocator /// let buf_rnd = ProtBuf::<u8, ProtectedKeyAllocator>::new_rand_os(32); /// /// // Until here memory buffer is read/write. Turns-it into a key /// let key = ProtKey::new(buf_rnd); /// /// // Or more simply, like this with exactly the same result /// let key: ProtKey8 = ProtBuf::new_rand_os(32).into_key(); /// /// { /// // Request access in read-mode /// let key_read = key.read(); /// let byte = key_read[16]; /// //... /// } // Relinquish its read-access /// /// // Alternative way to read its content /// key.read_with(|k| encrypt(&k[..], b"abc")); /// /// // Access it in write-mode /// let key_write = key.try_write(); /// if let Some(mut kw) = key_write { /// kw[16] = 42; /// } /// # } /// ``` pub struct ProtKey<T: Copy, A: KeyAllocator = DefaultKeyAllocator> { key: RefCell<ProtBuf<T, A>>, read_ctr: Rc<Cell<usize>> } impl<T: Copy, A: KeyAllocator> ProtKey<T, A> { /// Take ownership of `prot_buf` and transform it into a `ProtKey`. By /// default prevent any access. pub fn new(prot_buf: ProtBuf<T, A>) -> ProtKey<T, A> { unsafe { <A as KeyAllocator>::protect_none(prot_buf.as_ptr() as *mut u8, prot_buf.len_bytes()); } ProtKey { key: RefCell::new(prot_buf), read_ctr: Rc::new(Cell::new(NOREAD)) } } /// Consume and copy `prot_buf` to force using `ProtKey`'s allocator. /// If `prot_buf` already uses a `KeyAllocator` there is no need to make /// a copy so directly call the default cstor `new` instead. pub fn from_buf<B: Allocator>(prot_buf: ProtBuf<T, B>) -> ProtKey<T, A> { let buf = ProtBuf::from_slice(&prot_buf); ProtKey::new(buf) } /// Return a wrapper to the key in read mode. This method `panic!` if /// this key is already accessed in write mode. // FIXME: Not sure if it's the best interface to provide a `try_read` // variant to this `fail`ing method. It would maybe be better to // implement a single method returning a `Result`. See this RFC // https://github.com/rust-lang/rfcs/blob/master/text/0236-error-conventions.md pub fn read(&self) -> ProtKeyRead<T, A> { ProtKeyRead::new(self.key.borrow(), self.read_ctr.clone()) } /// Return a wrapper to the key in read mode. Return `None` /// if the key is already accessed in write mode. pub fn try_read(&self) -> Option<ProtKeyRead<T, A>> { match self.key.borrow_state() { BorrowState::Reading|BorrowState::Unused => Some(self.read()), _ => None } } /// Access the key in read mode and pass a reference to closure `f`. /// The key can only be read during this call. This method will `panic!` /// if a read access cannot be acquired on this key. pub fn read_with<F>(&self, mut f: F) where F: FnMut(ProtKeyRead<T, A>){ f(self.read()) } /// Return a wrapper to the key in write mode. This method `panic!` if /// the key is already currently accessed in read or write mode. pub fn write(&self) -> ProtKeyWrite<T, A> { let key_write = ProtKeyWrite::new(self.key.borrow_mut()); assert_eq!(self.read_ctr.get(), NOREAD); key_write } /// Return a wrapper to the key in write mode. Return `None` /// if the key is already accessed in read or write mode. pub fn try_write(&self) -> Option<ProtKeyWrite<T, A>> { match self.key.borrow_state() { BorrowState::Unused => Some(self.write()), _ => None } } /// Access the key in write mode and pass a reference to closure `f`. /// The key can only be writtent during this call. This method will /// `panic!` if a write access cannot be acquired on this key. pub fn write_with<F>(&self, mut f: F) where F: FnMut(&mut ProtKeyWrite<T, A>) { f(&mut self.write()) } } impl<T: Copy, A: KeyAllocator> Drop for ProtKey<T, A> { fn drop(&mut self) { // FIXME: without this assert this drop is useless. assert_eq!(self.read_ctr.get(), NOREAD); } } impl<T: Copy, A: KeyAllocator> Clone for ProtKey<T, A> { fn clone(&self) -> ProtKey<T, A> { ProtKey::new(self.read().clone()) } } impl<T: Copy, A: KeyAllocator> PartialEq for ProtKey<T, A> { fn eq(&self, other: &ProtKey<T, A>) -> bool { match (self.try_read(), other.try_read()) { (Some(ref s), Some(ref o)) => *s == *o, (_, _) => false } } } impl<T: Debug + Copy, A: KeyAllocator> Debug for ProtKey<T, A> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.try_read() { Some(r) => r.fmt(f), None => Err(fmt::Error) } } } /// An RAII protected key with read access /// /// This instance is the result of a `read` request on a `ProtKey`. If no /// other similar instance on the same `ProtKey` exists, raw memory access /// will be revoked when this instance is destructed. pub struct ProtKeyRead<'a, T: Copy + 'a, A: KeyAllocator + 'a> { ref_key: Ref<'a, ProtBuf<T, A>>, read_ctr: Rc<Cell<usize>> } impl<'a, T: Copy, A: KeyAllocator> ProtKeyRead<'a, T, A> { fn new(ref_key: Ref<'a, ProtBuf<T, A>>, read_ctr: Rc<Cell<usize>>) -> ProtKeyRead<'a, T, A> { if read_ctr.get() == NOREAD { unsafe { <A as KeyAllocator>::protect_read(ref_key.as_ptr() as *mut u8, ref_key.len_bytes()); } } read_ctr.set(read_ctr.get().checked_add(1).unwrap()); ProtKeyRead { ref_key: ref_key, read_ctr: read_ctr } } /// Clone this instance. // FIXME: Currently does not implement `clone()` as it would interfere // with `ProtKey::clone()`. pub fn clone_it(&self) -> ProtKeyRead<T, A> { ProtKeyRead::new(Ref::clone(&self.ref_key), self.read_ctr.clone()) } } impl<'a, T: Copy, A: KeyAllocator> Drop for ProtKeyRead<'a, T, A> { fn drop(&mut self) { self.read_ctr.set(self.read_ctr.get().checked_sub(1).unwrap()); if self.read_ctr.get() == NOREAD { unsafe { <A as KeyAllocator>::protect_none( self.ref_key.as_ptr() as *mut u8, self.ref_key.len_bytes()); } } } } impl<'a, T: Copy, A: KeyAllocator> Deref for ProtKeyRead<'a, T, A> { type Target = ProtBuf<T, A>; fn deref(&self) -> &ProtBuf<T, A> { &*self.ref_key } } impl<'a, T: Copy, A: KeyAllocator> AsRef<[T]> for ProtKeyRead<'a, T, A> { fn as_ref(&self) -> &[T] { &***self } } impl<'a, T: Copy, A: KeyAllocator> PartialEq for ProtKeyRead<'a, T, A> { fn eq(&self, other: &ProtKeyRead<T, A>) -> bool { **self == **other } } impl<'a, T: Debug + Copy, A: KeyAllocator> Debug for ProtKeyRead<'a, T, A> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} /// An RAII protected key with write access /// /// This instance is the result of a `write` request on a `ProtKey`. Its /// raw memory may only be written during the lifetime of this object. pub struct ProtKeyWrite<'a, T: Copy + 'a, A: KeyAllocator + 'a> { ref_key: RefMut<'a, ProtBuf<T, A>>, } impl<'a, T: Copy, A: KeyAllocator> ProtKeyWrite<'a, T, A> { fn new(ref_key: RefMut<'a, ProtBuf<T, A>>) -> ProtKeyWrite<'a, T, A> { unsafe { <A as KeyAllocator>::protect_write(ref_key.as_ptr() as *mut u8, ref_key.len_bytes()); } ProtKeyWrite { ref_key: ref_key, } } } impl<'a, T: Copy, A: KeyAllocator> Drop for ProtKeyWrite<'a, T, A> { fn drop(&mut self) { unsafe { <A as KeyAllocator>::protect_none(self.ref_key.as_ptr() as *mut u8, self.ref_key.len_bytes()); } } } /// This method is mandatory, but it should not be used for reading the /// content of the underlying key... #[allow(unreachable_code)] impl<'a, T: Copy, A: KeyAllocator> Deref for ProtKeyWrite<'a, T, A> { type Target = ProtBuf<T, A>; fn deref(&self) -> &ProtBuf<T, A> { unreachable!("key must only be written"); &*self.ref_key } } impl<'a, T: Copy, A: KeyAllocator> DerefMut for ProtKeyWrite<'a, T, A> { fn deref_mut(&mut self) -> &mut ProtBuf<T, A> { &mut *self.ref_key } } #[cfg(test)] mod test { use allocator::ProtectedKeyAllocator; use buf::ProtBuf; use key::{ProtKey, ProtKey8}; #[test] fn test_read() { let s1 = ProtBuf::<u8, ProtectedKeyAllocator>::new_rand_os(256); let s2 = s1.clone(); let key = ProtKey::new(s1); assert_eq!(&**key.read(), &*s2); assert_eq!(&key.read()[..], &s2[..]); assert_eq!(*key.read(), s2); { let r1 = key.read(); let r2 = key.try_read().unwrap(); assert_eq!(r1, r2); assert!(key.try_write().is_none()); let r3 = r1.clone_it(); assert_eq!(r3, r2); } key.read_with(|k| assert_eq!(&k[..], &*s2)); assert!(key.try_write().is_some()); } #[test] fn test_write() { let zero = ProtBuf::<u8, ProtectedKeyAllocator>::new_zero(256); let key = ProtBuf::<u8, ProtectedKeyAllocator>::new_rand_os(256).into_key(); for i in key.write().iter_mut() { *i = 0; } assert_eq!(*key.read(), zero); { let _w = key.write(); assert!(key.try_write().is_none()); assert!(key.try_read().is_none()); } let mut c = 0_usize; key.write_with(|k| {k[42] = 42; c = 1;}); assert_eq!(c, 1); assert!(key.try_write().is_some()); assert!(key.try_read().is_some()); } #[test] fn test_default_params() { let b = ProtBuf::new_zero(42); let _: ProtKey8 = ProtKey::new(b); let b = ProtBuf::new_zero(42); let _: ProtKey<u8> = ProtKey::new(b); } }
{ self.ref_key.fmt(f) }
identifier_body
key.rs
//! Protected key //! use std::cell::{Cell, Ref, RefCell, RefMut, BorrowState}; use std::fmt::{self, Debug}; use std::ops::{Deref, DerefMut}; use std::rc::Rc; use allocator::{Allocator, KeyAllocator, DefaultKeyAllocator}; use buf::ProtBuf; /// Key of bytes pub type ProtKey8<A = DefaultKeyAllocator> = ProtKey<u8, A>; const NOREAD: usize = 0; /// A protected key /// /// Transform a `ProtBuf` instance into a protected key `ProtKey` and provide /// tigher access control on its memory. /// /// By default a `ProtKey` cannot be read nor written to and will only /// provide separated accesses with limited scopes. Thus, RAII accessor /// methods must be used to read and write to a `ProtKey`. Accessing the /// underlying key is a bit similar to the way of manipulating an object /// wrapped in `RefCell`. /// /// ```rust /// # extern crate tars; /// # use tars::allocator::ProtectedKeyAllocator; /// # use tars::{ProtKey, ProtBuf, ProtKey8}; /// # fn encrypt(_: &[u8], _: &[u8]) {} /// # fn main() { /// // Instantiate a new buffer initialized with random bytes. /// // Same as an usual ProtBuf instance but with a different allocator /// let buf_rnd = ProtBuf::<u8, ProtectedKeyAllocator>::new_rand_os(32); /// /// // Until here memory buffer is read/write. Turns-it into a key /// let key = ProtKey::new(buf_rnd); /// /// // Or more simply, like this with exactly the same result /// let key: ProtKey8 = ProtBuf::new_rand_os(32).into_key(); /// /// { /// // Request access in read-mode /// let key_read = key.read(); /// let byte = key_read[16]; /// //... /// } // Relinquish its read-access /// /// // Alternative way to read its content /// key.read_with(|k| encrypt(&k[..], b"abc")); /// /// // Access it in write-mode /// let key_write = key.try_write(); /// if let Some(mut kw) = key_write { /// kw[16] = 42; /// } /// # } /// ``` pub struct ProtKey<T: Copy, A: KeyAllocator = DefaultKeyAllocator> { key: RefCell<ProtBuf<T, A>>, read_ctr: Rc<Cell<usize>> } impl<T: Copy, A: KeyAllocator> ProtKey<T, A> { /// Take ownership of `prot_buf` and transform it into a `ProtKey`. By /// default prevent any access. pub fn new(prot_buf: ProtBuf<T, A>) -> ProtKey<T, A> { unsafe { <A as KeyAllocator>::protect_none(prot_buf.as_ptr() as *mut u8, prot_buf.len_bytes()); } ProtKey { key: RefCell::new(prot_buf), read_ctr: Rc::new(Cell::new(NOREAD)) } } /// Consume and copy `prot_buf` to force using `ProtKey`'s allocator. /// If `prot_buf` already uses a `KeyAllocator` there is no need to make /// a copy so directly call the default cstor `new` instead. pub fn from_buf<B: Allocator>(prot_buf: ProtBuf<T, B>) -> ProtKey<T, A> { let buf = ProtBuf::from_slice(&prot_buf); ProtKey::new(buf) } /// Return a wrapper to the key in read mode. This method `panic!` if /// this key is already accessed in write mode. // FIXME: Not sure if it's the best interface to provide a `try_read` // variant to this `fail`ing method. It would maybe be better to // implement a single method returning a `Result`. See this RFC // https://github.com/rust-lang/rfcs/blob/master/text/0236-error-conventions.md pub fn read(&self) -> ProtKeyRead<T, A> { ProtKeyRead::new(self.key.borrow(), self.read_ctr.clone()) } /// Return a wrapper to the key in read mode. Return `None` /// if the key is already accessed in write mode. pub fn try_read(&self) -> Option<ProtKeyRead<T, A>> { match self.key.borrow_state() { BorrowState::Reading|BorrowState::Unused => Some(self.read()), _ => None } } /// Access the key in read mode and pass a reference to closure `f`. /// The key can only be read during this call. This method will `panic!` /// if a read access cannot be acquired on this key. pub fn read_with<F>(&self, mut f: F) where F: FnMut(ProtKeyRead<T, A>){ f(self.read()) } /// Return a wrapper to the key in write mode. This method `panic!` if /// the key is already currently accessed in read or write mode. pub fn write(&self) -> ProtKeyWrite<T, A> { let key_write = ProtKeyWrite::new(self.key.borrow_mut()); assert_eq!(self.read_ctr.get(), NOREAD); key_write } /// Return a wrapper to the key in write mode. Return `None` /// if the key is already accessed in read or write mode. pub fn try_write(&self) -> Option<ProtKeyWrite<T, A>> { match self.key.borrow_state() { BorrowState::Unused => Some(self.write()), _ => None } } /// Access the key in write mode and pass a reference to closure `f`. /// The key can only be writtent during this call. This method will /// `panic!` if a write access cannot be acquired on this key. pub fn write_with<F>(&self, mut f: F) where F: FnMut(&mut ProtKeyWrite<T, A>) { f(&mut self.write()) } } impl<T: Copy, A: KeyAllocator> Drop for ProtKey<T, A> { fn drop(&mut self) { // FIXME: without this assert this drop is useless. assert_eq!(self.read_ctr.get(), NOREAD); } } impl<T: Copy, A: KeyAllocator> Clone for ProtKey<T, A> { fn clone(&self) -> ProtKey<T, A> { ProtKey::new(self.read().clone()) } } impl<T: Copy, A: KeyAllocator> PartialEq for ProtKey<T, A> { fn eq(&self, other: &ProtKey<T, A>) -> bool { match (self.try_read(), other.try_read()) { (Some(ref s), Some(ref o)) => *s == *o, (_, _) => false } } } impl<T: Debug + Copy, A: KeyAllocator> Debug for ProtKey<T, A> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.try_read() { Some(r) => r.fmt(f), None => Err(fmt::Error) } } } /// An RAII protected key with read access /// /// This instance is the result of a `read` request on a `ProtKey`. If no /// other similar instance on the same `ProtKey` exists, raw memory access /// will be revoked when this instance is destructed. pub struct ProtKeyRead<'a, T: Copy + 'a, A: KeyAllocator + 'a> { ref_key: Ref<'a, ProtBuf<T, A>>, read_ctr: Rc<Cell<usize>> } impl<'a, T: Copy, A: KeyAllocator> ProtKeyRead<'a, T, A> { fn new(ref_key: Ref<'a, ProtBuf<T, A>>, read_ctr: Rc<Cell<usize>>) -> ProtKeyRead<'a, T, A> { if read_ctr.get() == NOREAD { unsafe { <A as KeyAllocator>::protect_read(ref_key.as_ptr() as *mut u8, ref_key.len_bytes()); } } read_ctr.set(read_ctr.get().checked_add(1).unwrap()); ProtKeyRead { ref_key: ref_key, read_ctr: read_ctr } } /// Clone this instance. // FIXME: Currently does not implement `clone()` as it would interfere // with `ProtKey::clone()`.
} impl<'a, T: Copy, A: KeyAllocator> Drop for ProtKeyRead<'a, T, A> { fn drop(&mut self) { self.read_ctr.set(self.read_ctr.get().checked_sub(1).unwrap()); if self.read_ctr.get() == NOREAD { unsafe { <A as KeyAllocator>::protect_none( self.ref_key.as_ptr() as *mut u8, self.ref_key.len_bytes()); } } } } impl<'a, T: Copy, A: KeyAllocator> Deref for ProtKeyRead<'a, T, A> { type Target = ProtBuf<T, A>; fn deref(&self) -> &ProtBuf<T, A> { &*self.ref_key } } impl<'a, T: Copy, A: KeyAllocator> AsRef<[T]> for ProtKeyRead<'a, T, A> { fn as_ref(&self) -> &[T] { &***self } } impl<'a, T: Copy, A: KeyAllocator> PartialEq for ProtKeyRead<'a, T, A> { fn eq(&self, other: &ProtKeyRead<T, A>) -> bool { **self == **other } } impl<'a, T: Debug + Copy, A: KeyAllocator> Debug for ProtKeyRead<'a, T, A> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.ref_key.fmt(f) } } /// An RAII protected key with write access /// /// This instance is the result of a `write` request on a `ProtKey`. Its /// raw memory may only be written during the lifetime of this object. pub struct ProtKeyWrite<'a, T: Copy + 'a, A: KeyAllocator + 'a> { ref_key: RefMut<'a, ProtBuf<T, A>>, } impl<'a, T: Copy, A: KeyAllocator> ProtKeyWrite<'a, T, A> { fn new(ref_key: RefMut<'a, ProtBuf<T, A>>) -> ProtKeyWrite<'a, T, A> { unsafe { <A as KeyAllocator>::protect_write(ref_key.as_ptr() as *mut u8, ref_key.len_bytes()); } ProtKeyWrite { ref_key: ref_key, } } } impl<'a, T: Copy, A: KeyAllocator> Drop for ProtKeyWrite<'a, T, A> { fn drop(&mut self) { unsafe { <A as KeyAllocator>::protect_none(self.ref_key.as_ptr() as *mut u8, self.ref_key.len_bytes()); } } } /// This method is mandatory, but it should not be used for reading the /// content of the underlying key... #[allow(unreachable_code)] impl<'a, T: Copy, A: KeyAllocator> Deref for ProtKeyWrite<'a, T, A> { type Target = ProtBuf<T, A>; fn deref(&self) -> &ProtBuf<T, A> { unreachable!("key must only be written"); &*self.ref_key } } impl<'a, T: Copy, A: KeyAllocator> DerefMut for ProtKeyWrite<'a, T, A> { fn deref_mut(&mut self) -> &mut ProtBuf<T, A> { &mut *self.ref_key } } #[cfg(test)] mod test { use allocator::ProtectedKeyAllocator; use buf::ProtBuf; use key::{ProtKey, ProtKey8}; #[test] fn test_read() { let s1 = ProtBuf::<u8, ProtectedKeyAllocator>::new_rand_os(256); let s2 = s1.clone(); let key = ProtKey::new(s1); assert_eq!(&**key.read(), &*s2); assert_eq!(&key.read()[..], &s2[..]); assert_eq!(*key.read(), s2); { let r1 = key.read(); let r2 = key.try_read().unwrap(); assert_eq!(r1, r2); assert!(key.try_write().is_none()); let r3 = r1.clone_it(); assert_eq!(r3, r2); } key.read_with(|k| assert_eq!(&k[..], &*s2)); assert!(key.try_write().is_some()); } #[test] fn test_write() { let zero = ProtBuf::<u8, ProtectedKeyAllocator>::new_zero(256); let key = ProtBuf::<u8, ProtectedKeyAllocator>::new_rand_os(256).into_key(); for i in key.write().iter_mut() { *i = 0; } assert_eq!(*key.read(), zero); { let _w = key.write(); assert!(key.try_write().is_none()); assert!(key.try_read().is_none()); } let mut c = 0_usize; key.write_with(|k| {k[42] = 42; c = 1;}); assert_eq!(c, 1); assert!(key.try_write().is_some()); assert!(key.try_read().is_some()); } #[test] fn test_default_params() { let b = ProtBuf::new_zero(42); let _: ProtKey8 = ProtKey::new(b); let b = ProtBuf::new_zero(42); let _: ProtKey<u8> = ProtKey::new(b); } }
pub fn clone_it(&self) -> ProtKeyRead<T, A> { ProtKeyRead::new(Ref::clone(&self.ref_key), self.read_ctr.clone()) }
random_line_split
key.rs
//! Protected key //! use std::cell::{Cell, Ref, RefCell, RefMut, BorrowState}; use std::fmt::{self, Debug}; use std::ops::{Deref, DerefMut}; use std::rc::Rc; use allocator::{Allocator, KeyAllocator, DefaultKeyAllocator}; use buf::ProtBuf; /// Key of bytes pub type ProtKey8<A = DefaultKeyAllocator> = ProtKey<u8, A>; const NOREAD: usize = 0; /// A protected key /// /// Transform a `ProtBuf` instance into a protected key `ProtKey` and provide /// tigher access control on its memory. /// /// By default a `ProtKey` cannot be read nor written to and will only /// provide separated accesses with limited scopes. Thus, RAII accessor /// methods must be used to read and write to a `ProtKey`. Accessing the /// underlying key is a bit similar to the way of manipulating an object /// wrapped in `RefCell`. /// /// ```rust /// # extern crate tars; /// # use tars::allocator::ProtectedKeyAllocator; /// # use tars::{ProtKey, ProtBuf, ProtKey8}; /// # fn encrypt(_: &[u8], _: &[u8]) {} /// # fn main() { /// // Instantiate a new buffer initialized with random bytes. /// // Same as an usual ProtBuf instance but with a different allocator /// let buf_rnd = ProtBuf::<u8, ProtectedKeyAllocator>::new_rand_os(32); /// /// // Until here memory buffer is read/write. Turns-it into a key /// let key = ProtKey::new(buf_rnd); /// /// // Or more simply, like this with exactly the same result /// let key: ProtKey8 = ProtBuf::new_rand_os(32).into_key(); /// /// { /// // Request access in read-mode /// let key_read = key.read(); /// let byte = key_read[16]; /// //... /// } // Relinquish its read-access /// /// // Alternative way to read its content /// key.read_with(|k| encrypt(&k[..], b"abc")); /// /// // Access it in write-mode /// let key_write = key.try_write(); /// if let Some(mut kw) = key_write { /// kw[16] = 42; /// } /// # } /// ``` pub struct ProtKey<T: Copy, A: KeyAllocator = DefaultKeyAllocator> { key: RefCell<ProtBuf<T, A>>, read_ctr: Rc<Cell<usize>> } impl<T: Copy, A: KeyAllocator> ProtKey<T, A> { /// Take ownership of `prot_buf` and transform it into a `ProtKey`. By /// default prevent any access. pub fn new(prot_buf: ProtBuf<T, A>) -> ProtKey<T, A> { unsafe { <A as KeyAllocator>::protect_none(prot_buf.as_ptr() as *mut u8, prot_buf.len_bytes()); } ProtKey { key: RefCell::new(prot_buf), read_ctr: Rc::new(Cell::new(NOREAD)) } } /// Consume and copy `prot_buf` to force using `ProtKey`'s allocator. /// If `prot_buf` already uses a `KeyAllocator` there is no need to make /// a copy so directly call the default cstor `new` instead. pub fn from_buf<B: Allocator>(prot_buf: ProtBuf<T, B>) -> ProtKey<T, A> { let buf = ProtBuf::from_slice(&prot_buf); ProtKey::new(buf) } /// Return a wrapper to the key in read mode. This method `panic!` if /// this key is already accessed in write mode. // FIXME: Not sure if it's the best interface to provide a `try_read` // variant to this `fail`ing method. It would maybe be better to // implement a single method returning a `Result`. See this RFC // https://github.com/rust-lang/rfcs/blob/master/text/0236-error-conventions.md pub fn read(&self) -> ProtKeyRead<T, A> { ProtKeyRead::new(self.key.borrow(), self.read_ctr.clone()) } /// Return a wrapper to the key in read mode. Return `None` /// if the key is already accessed in write mode. pub fn try_read(&self) -> Option<ProtKeyRead<T, A>> { match self.key.borrow_state() { BorrowState::Reading|BorrowState::Unused => Some(self.read()), _ => None } } /// Access the key in read mode and pass a reference to closure `f`. /// The key can only be read during this call. This method will `panic!` /// if a read access cannot be acquired on this key. pub fn read_with<F>(&self, mut f: F) where F: FnMut(ProtKeyRead<T, A>){ f(self.read()) } /// Return a wrapper to the key in write mode. This method `panic!` if /// the key is already currently accessed in read or write mode. pub fn write(&self) -> ProtKeyWrite<T, A> { let key_write = ProtKeyWrite::new(self.key.borrow_mut()); assert_eq!(self.read_ctr.get(), NOREAD); key_write } /// Return a wrapper to the key in write mode. Return `None` /// if the key is already accessed in read or write mode. pub fn try_write(&self) -> Option<ProtKeyWrite<T, A>> { match self.key.borrow_state() { BorrowState::Unused => Some(self.write()), _ => None } } /// Access the key in write mode and pass a reference to closure `f`. /// The key can only be writtent during this call. This method will /// `panic!` if a write access cannot be acquired on this key. pub fn write_with<F>(&self, mut f: F) where F: FnMut(&mut ProtKeyWrite<T, A>) { f(&mut self.write()) } } impl<T: Copy, A: KeyAllocator> Drop for ProtKey<T, A> { fn drop(&mut self) { // FIXME: without this assert this drop is useless. assert_eq!(self.read_ctr.get(), NOREAD); } } impl<T: Copy, A: KeyAllocator> Clone for ProtKey<T, A> { fn
(&self) -> ProtKey<T, A> { ProtKey::new(self.read().clone()) } } impl<T: Copy, A: KeyAllocator> PartialEq for ProtKey<T, A> { fn eq(&self, other: &ProtKey<T, A>) -> bool { match (self.try_read(), other.try_read()) { (Some(ref s), Some(ref o)) => *s == *o, (_, _) => false } } } impl<T: Debug + Copy, A: KeyAllocator> Debug for ProtKey<T, A> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.try_read() { Some(r) => r.fmt(f), None => Err(fmt::Error) } } } /// An RAII protected key with read access /// /// This instance is the result of a `read` request on a `ProtKey`. If no /// other similar instance on the same `ProtKey` exists, raw memory access /// will be revoked when this instance is destructed. pub struct ProtKeyRead<'a, T: Copy + 'a, A: KeyAllocator + 'a> { ref_key: Ref<'a, ProtBuf<T, A>>, read_ctr: Rc<Cell<usize>> } impl<'a, T: Copy, A: KeyAllocator> ProtKeyRead<'a, T, A> { fn new(ref_key: Ref<'a, ProtBuf<T, A>>, read_ctr: Rc<Cell<usize>>) -> ProtKeyRead<'a, T, A> { if read_ctr.get() == NOREAD { unsafe { <A as KeyAllocator>::protect_read(ref_key.as_ptr() as *mut u8, ref_key.len_bytes()); } } read_ctr.set(read_ctr.get().checked_add(1).unwrap()); ProtKeyRead { ref_key: ref_key, read_ctr: read_ctr } } /// Clone this instance. // FIXME: Currently does not implement `clone()` as it would interfere // with `ProtKey::clone()`. pub fn clone_it(&self) -> ProtKeyRead<T, A> { ProtKeyRead::new(Ref::clone(&self.ref_key), self.read_ctr.clone()) } } impl<'a, T: Copy, A: KeyAllocator> Drop for ProtKeyRead<'a, T, A> { fn drop(&mut self) { self.read_ctr.set(self.read_ctr.get().checked_sub(1).unwrap()); if self.read_ctr.get() == NOREAD { unsafe { <A as KeyAllocator>::protect_none( self.ref_key.as_ptr() as *mut u8, self.ref_key.len_bytes()); } } } } impl<'a, T: Copy, A: KeyAllocator> Deref for ProtKeyRead<'a, T, A> { type Target = ProtBuf<T, A>; fn deref(&self) -> &ProtBuf<T, A> { &*self.ref_key } } impl<'a, T: Copy, A: KeyAllocator> AsRef<[T]> for ProtKeyRead<'a, T, A> { fn as_ref(&self) -> &[T] { &***self } } impl<'a, T: Copy, A: KeyAllocator> PartialEq for ProtKeyRead<'a, T, A> { fn eq(&self, other: &ProtKeyRead<T, A>) -> bool { **self == **other } } impl<'a, T: Debug + Copy, A: KeyAllocator> Debug for ProtKeyRead<'a, T, A> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.ref_key.fmt(f) } } /// An RAII protected key with write access /// /// This instance is the result of a `write` request on a `ProtKey`. Its /// raw memory may only be written during the lifetime of this object. pub struct ProtKeyWrite<'a, T: Copy + 'a, A: KeyAllocator + 'a> { ref_key: RefMut<'a, ProtBuf<T, A>>, } impl<'a, T: Copy, A: KeyAllocator> ProtKeyWrite<'a, T, A> { fn new(ref_key: RefMut<'a, ProtBuf<T, A>>) -> ProtKeyWrite<'a, T, A> { unsafe { <A as KeyAllocator>::protect_write(ref_key.as_ptr() as *mut u8, ref_key.len_bytes()); } ProtKeyWrite { ref_key: ref_key, } } } impl<'a, T: Copy, A: KeyAllocator> Drop for ProtKeyWrite<'a, T, A> { fn drop(&mut self) { unsafe { <A as KeyAllocator>::protect_none(self.ref_key.as_ptr() as *mut u8, self.ref_key.len_bytes()); } } } /// This method is mandatory, but it should not be used for reading the /// content of the underlying key... #[allow(unreachable_code)] impl<'a, T: Copy, A: KeyAllocator> Deref for ProtKeyWrite<'a, T, A> { type Target = ProtBuf<T, A>; fn deref(&self) -> &ProtBuf<T, A> { unreachable!("key must only be written"); &*self.ref_key } } impl<'a, T: Copy, A: KeyAllocator> DerefMut for ProtKeyWrite<'a, T, A> { fn deref_mut(&mut self) -> &mut ProtBuf<T, A> { &mut *self.ref_key } } #[cfg(test)] mod test { use allocator::ProtectedKeyAllocator; use buf::ProtBuf; use key::{ProtKey, ProtKey8}; #[test] fn test_read() { let s1 = ProtBuf::<u8, ProtectedKeyAllocator>::new_rand_os(256); let s2 = s1.clone(); let key = ProtKey::new(s1); assert_eq!(&**key.read(), &*s2); assert_eq!(&key.read()[..], &s2[..]); assert_eq!(*key.read(), s2); { let r1 = key.read(); let r2 = key.try_read().unwrap(); assert_eq!(r1, r2); assert!(key.try_write().is_none()); let r3 = r1.clone_it(); assert_eq!(r3, r2); } key.read_with(|k| assert_eq!(&k[..], &*s2)); assert!(key.try_write().is_some()); } #[test] fn test_write() { let zero = ProtBuf::<u8, ProtectedKeyAllocator>::new_zero(256); let key = ProtBuf::<u8, ProtectedKeyAllocator>::new_rand_os(256).into_key(); for i in key.write().iter_mut() { *i = 0; } assert_eq!(*key.read(), zero); { let _w = key.write(); assert!(key.try_write().is_none()); assert!(key.try_read().is_none()); } let mut c = 0_usize; key.write_with(|k| {k[42] = 42; c = 1;}); assert_eq!(c, 1); assert!(key.try_write().is_some()); assert!(key.try_read().is_some()); } #[test] fn test_default_params() { let b = ProtBuf::new_zero(42); let _: ProtKey8 = ProtKey::new(b); let b = ProtBuf::new_zero(42); let _: ProtKey<u8> = ProtKey::new(b); } }
clone
identifier_name
renderer.rs
use gpukit::wgpu; use std::sync::Arc; pub struct Renderer { context: Arc<gpukit::Context>, pipeline: wgpu::RenderPipeline, vertex_buffer: gpukit::Buffer<Vertex>, index_buffer: gpukit::Buffer<u32>, bind_group: gpukit::BindGroup, screen_uniforms: UniformBuffer<ScreenUniforms>, texture_bind_group: gpukit::BindGroup, texture_version: Option<u64>, texture: gpukit::Texture<gpukit::format::R8Unorm>, } #[derive(gpukit::Bindings)] struct Bindings<'a> { #[uniform(binding = 0)] screen_uniforms: &'a gpukit::Buffer<ScreenUniforms>, #[sampler(binding = 1, filtering)] sampler: &'a wgpu::Sampler, } #[derive(gpukit::Bindings)] struct TextureBindings<'a> { #[texture(binding = 0)] texture: &'a gpukit::TextureView<gpukit::format::R8Unorm>, } #[repr(C)] #[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] struct ScreenUniforms { width_in_points: f32, height_in_points: f32, pixels_per_point: f32, _padding: u32, } struct UniformBuffer<T: bytemuck::Pod> { buffer: gpukit::Buffer<T>, value: T, } impl<T: bytemuck::Pod> std::ops::Deref for UniformBuffer<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.value } } impl<T: bytemuck::Pod> std::ops::DerefMut for UniformBuffer<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.value } } impl<T: bytemuck::Pod> UniformBuffer<T> { pub fn new(context: &gpukit::Context, value: T) -> Self { let buffer = context .build_buffer() .with_usage(wgpu::BufferUsages::UNIFORM) .init_with_data(std::slice::from_ref(&value)); UniformBuffer { buffer, value } } fn update(&self, context: &gpukit::Context) { self.buffer .update(context, std::slice::from_ref(&self.value)); } } #[repr(transparent)] #[derive(Debug, Copy, Clone)] struct Vertex(egui::paint::Vertex); // SAFETY: `egui::paint::Vertex` is `#[repr(C)]`. unsafe impl bytemuck::Pod for Vertex {} unsafe impl bytemuck::Zeroable for Vertex {} impl Vertex { // SAFETY: `egui::paint::Vertex` is `#[repr(C)]`. fn cast_slice(vertices: &[egui::paint::Vertex]) -> &[Vertex] { let ptr = vertices.as_ptr() as *const Vertex; let len = vertices.len(); unsafe { std::slice::from_raw_parts(ptr, len) } } } pub struct RendererDescriptor { pub context: Arc<gpukit::Context>, pub target_format: wgpu::TextureFormat, // Size of the screen: [width, height] pub size: [u32; 2], // Number of pixels per point pub pixels_per_point: f32, } impl Renderer { pub fn new(desc: RendererDescriptor) -> anyhow::Result<Renderer> { let RendererDescriptor { context, target_format, size, pixels_per_point, } = desc; let vertex_buffer = Self::create_vertex_buffer(&context, 0); let index_buffer = Self::create_index_buffer(&context, 0); let uniforms = UniformBuffer::new( &context, ScreenUniforms { width_in_points: size[0] as f32 / pixels_per_point, height_in_points: size[1] as f32 / pixels_per_point, pixels_per_point, _padding: 0, }, ); let sampler = context.device.create_sampler(&wgpu::SamplerDescriptor { label: None, address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Nearest, min_filter: wgpu::FilterMode::Linear, ..Default::default() }); let bind_group = gpukit::BindGroup::new( &context, &Bindings { screen_uniforms: &uniforms.buffer, sampler: &sampler, }, ); let texture = context .build_texture() .with_usage(wgpu::TextureUsages::TEXTURE_BINDING) .init_with_data([1, 1], &[0]); let texture_bind_group = gpukit::BindGroup::new( &context, &TextureBindings { texture: &texture.create_view(), }, ); let vertex = context .build_shader("gukit_egui vertex shader") .init_from_glsl(include_str!("shader.vert"), gpukit::ShaderStage::Vertex)?; let fragment = context .build_shader("gukit_egui fragment shader") .init_from_glsl(include_str!("shader.frag"), gpukit::ShaderStage::Fragment)?; let pipeline = context.create_render_pipeline(gpukit::RenderPipelineDescriptor { label: Some("gpukit_egui renderer"), vertex: vertex.entry("main"), fragment: fragment.entry("main"), vertex_buffers: &[gpukit::vertex_buffer_layout![ // Position 0 => Float32x2, // Texture Coordinates 1 => Float32x2, // Color 2 => Uint32, ]], bind_group_layouts: &[&bind_group.layout, &texture_bind_group.layout], color_targets: &[wgpu::ColorTargetState { format: target_format, blend: Some(wgpu::BlendState { color: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, alpha: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::OneMinusDstAlpha, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add, }, }), write_mask: wgpu::ColorWrites::all(), }], depth_stencil: None, primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, })?; Ok(Renderer { context, pipeline, vertex_buffer, index_buffer, bind_group, screen_uniforms: uniforms, texture_bind_group, texture_version: None, texture, }) } fn create_vertex_buffer(context: &gpukit::Context, len: usize) -> gpukit::Buffer<Vertex> { context .build_buffer() .with_usage(wgpu::BufferUsages::VERTEX) .init_with_capacity(len) } fn create_index_buffer(context: &gpukit::Context, len: usize) -> gpukit::Buffer<u32> { context .build_buffer() .with_usage(wgpu::BufferUsages::INDEX) .init_with_capacity(len) } pub fn set_size(&mut self, size: [u32; 2], scale_factor: f32) { self.screen_uniforms.width_in_points = size[0] as f32 / scale_factor; self.screen_uniforms.height_in_points = size[1] as f32 / scale_factor; self.screen_uniforms.pixels_per_point = scale_factor; self.screen_uniforms.update(&self.context) } pub fn render<'encoder>( &'encoder mut self, rpass: &mut wgpu::RenderPass<'encoder>, meshes: &[egui::ClippedMesh], texture: &egui::Texture, ) { use gpukit::RenderPassExt; let offsets = self.update_buffers(meshes); self.update_texture(texture); rpass.set_pipeline(&self.pipeline); rpass.set_vertex_buffer(0, *self.vertex_buffer.slice(..)); rpass.set_index_buffer_ext(self.index_buffer.slice(..)); rpass.set_bind_group(0, &self.bind_group, &[]); rpass.set_bind_group(1, &self.texture_bind_group, &[]); for (egui::ClippedMesh(rect, mesh), offset) in meshes.iter().zip(offsets) { if Self::set_scissor_region(rpass, &self.screen_uniforms, *rect) { let index_range = offset.index..offset.index + mesh.indices.len() as u32; rpass.draw_indexed(index_range, offset.vertex as i32, 0..1); } } } fn set_scissor_region( rpass: &mut wgpu::RenderPass, screen: &ScreenUniforms, rect: egui::Rect, ) -> bool { let left = rect.left() * screen.pixels_per_point; let right = rect.right() * screen.pixels_per_point; let top = rect.top() * screen.pixels_per_point; let bottom = rect.bottom() * screen.pixels_per_point; let screen_width = screen.width_in_points * screen.pixels_per_point; let screen_height = screen.height_in_points * screen.pixels_per_point; let left = left.clamp(0.0, screen_width); let top = top.clamp(0.0, screen_height); let right = right.clamp(left, screen_width); let bottom = bottom.clamp(top, screen_height); let left = left.round() as u32; let top = top.round() as u32; let right = right.round() as u32; let bottom = bottom.round() as u32; let width = right - left; let height = bottom - top; if width == 0 || height == 0 { false } else { rpass.set_scissor_rect(left, top, width, height); true } } fn update_buffers(&mut self, meshes: &[egui::ClippedMesh]) -> Vec<BufferOffset> { let mut offsets = Vec::with_capacity(meshes.len()); // Find out how many vertices/indices we need to render let mut vertex_count = 0; let mut index_count = 0; for egui::ClippedMesh(_, mesh) in meshes { offsets.push(BufferOffset { vertex: vertex_count, index: index_count, }); vertex_count += align_to_power_of_two(mesh.vertices.len() as u32, BUFFER_ALIGNMENT); index_count += align_to_power_of_two(mesh.indices.len() as u32, BUFFER_ALIGNMENT); } // Allocate space for the vertices/indices if vertex_count as usize > self.vertex_buffer.len()
if index_count as usize > self.index_buffer.len() { self.index_buffer = Self::create_index_buffer(&self.context, index_count as usize); } // Write vertices/indices to their respective buffers for (egui::ClippedMesh(_, mesh), offset) in meshes.iter().zip(&offsets) { let vertex_slice = Vertex::cast_slice(&mesh.vertices); self.vertex_buffer .write(&self.context, offset.vertex as usize, vertex_slice); self.index_buffer .write(&self.context, offset.index as usize, &mesh.indices); } offsets } fn update_texture(&mut self, texture: &egui::Texture) { if self.texture_version!= Some(texture.version) { self.texture_version = Some(texture.version); self.texture = self .context .build_texture() .with_usage(wgpu::TextureUsages::TEXTURE_BINDING) .init_with_data( [texture.width as u32, texture.height as u32], &texture.pixels, ); self.texture_bind_group.update( &self.context, &TextureBindings { texture: &self.texture.create_view(), }, ); } } } struct BufferOffset { vertex: u32, index: u32, } const BUFFER_ALIGNMENT: u32 = wgpu::COPY_BUFFER_ALIGNMENT.next_power_of_two() as u32; const fn align_to_power_of_two(x: u32, power: u32) -> u32 { (x + (power - 1)) &!(power - 1) }
{ self.vertex_buffer = Self::create_vertex_buffer(&self.context, vertex_count as usize); }
conditional_block
renderer.rs
use gpukit::wgpu; use std::sync::Arc; pub struct Renderer { context: Arc<gpukit::Context>, pipeline: wgpu::RenderPipeline, vertex_buffer: gpukit::Buffer<Vertex>, index_buffer: gpukit::Buffer<u32>, bind_group: gpukit::BindGroup, screen_uniforms: UniformBuffer<ScreenUniforms>, texture_bind_group: gpukit::BindGroup, texture_version: Option<u64>, texture: gpukit::Texture<gpukit::format::R8Unorm>, } #[derive(gpukit::Bindings)] struct Bindings<'a> { #[uniform(binding = 0)] screen_uniforms: &'a gpukit::Buffer<ScreenUniforms>, #[sampler(binding = 1, filtering)] sampler: &'a wgpu::Sampler, } #[derive(gpukit::Bindings)] struct TextureBindings<'a> { #[texture(binding = 0)] texture: &'a gpukit::TextureView<gpukit::format::R8Unorm>, } #[repr(C)] #[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] struct ScreenUniforms { width_in_points: f32, height_in_points: f32, pixels_per_point: f32, _padding: u32, } struct UniformBuffer<T: bytemuck::Pod> { buffer: gpukit::Buffer<T>, value: T, } impl<T: bytemuck::Pod> std::ops::Deref for UniformBuffer<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.value } } impl<T: bytemuck::Pod> std::ops::DerefMut for UniformBuffer<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.value } } impl<T: bytemuck::Pod> UniformBuffer<T> { pub fn new(context: &gpukit::Context, value: T) -> Self { let buffer = context .build_buffer() .with_usage(wgpu::BufferUsages::UNIFORM) .init_with_data(std::slice::from_ref(&value)); UniformBuffer { buffer, value } } fn update(&self, context: &gpukit::Context) { self.buffer .update(context, std::slice::from_ref(&self.value)); } } #[repr(transparent)] #[derive(Debug, Copy, Clone)] struct Vertex(egui::paint::Vertex); // SAFETY: `egui::paint::Vertex` is `#[repr(C)]`. unsafe impl bytemuck::Pod for Vertex {} unsafe impl bytemuck::Zeroable for Vertex {} impl Vertex { // SAFETY: `egui::paint::Vertex` is `#[repr(C)]`. fn cast_slice(vertices: &[egui::paint::Vertex]) -> &[Vertex] { let ptr = vertices.as_ptr() as *const Vertex; let len = vertices.len(); unsafe { std::slice::from_raw_parts(ptr, len) } } } pub struct RendererDescriptor { pub context: Arc<gpukit::Context>, pub target_format: wgpu::TextureFormat, // Size of the screen: [width, height] pub size: [u32; 2], // Number of pixels per point pub pixels_per_point: f32, } impl Renderer { pub fn new(desc: RendererDescriptor) -> anyhow::Result<Renderer> { let RendererDescriptor { context, target_format, size, pixels_per_point, } = desc; let vertex_buffer = Self::create_vertex_buffer(&context, 0); let index_buffer = Self::create_index_buffer(&context, 0); let uniforms = UniformBuffer::new( &context, ScreenUniforms { width_in_points: size[0] as f32 / pixels_per_point, height_in_points: size[1] as f32 / pixels_per_point, pixels_per_point, _padding: 0, }, ); let sampler = context.device.create_sampler(&wgpu::SamplerDescriptor { label: None, address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Nearest, min_filter: wgpu::FilterMode::Linear, ..Default::default() }); let bind_group = gpukit::BindGroup::new( &context, &Bindings { screen_uniforms: &uniforms.buffer, sampler: &sampler, }, ); let texture = context .build_texture() .with_usage(wgpu::TextureUsages::TEXTURE_BINDING) .init_with_data([1, 1], &[0]); let texture_bind_group = gpukit::BindGroup::new( &context, &TextureBindings { texture: &texture.create_view(), }, ); let vertex = context .build_shader("gukit_egui vertex shader") .init_from_glsl(include_str!("shader.vert"), gpukit::ShaderStage::Vertex)?; let fragment = context .build_shader("gukit_egui fragment shader") .init_from_glsl(include_str!("shader.frag"), gpukit::ShaderStage::Fragment)?; let pipeline = context.create_render_pipeline(gpukit::RenderPipelineDescriptor { label: Some("gpukit_egui renderer"), vertex: vertex.entry("main"), fragment: fragment.entry("main"), vertex_buffers: &[gpukit::vertex_buffer_layout![ // Position 0 => Float32x2, // Texture Coordinates 1 => Float32x2, // Color
color_targets: &[wgpu::ColorTargetState { format: target_format, blend: Some(wgpu::BlendState { color: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, alpha: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::OneMinusDstAlpha, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add, }, }), write_mask: wgpu::ColorWrites::all(), }], depth_stencil: None, primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, })?; Ok(Renderer { context, pipeline, vertex_buffer, index_buffer, bind_group, screen_uniforms: uniforms, texture_bind_group, texture_version: None, texture, }) } fn create_vertex_buffer(context: &gpukit::Context, len: usize) -> gpukit::Buffer<Vertex> { context .build_buffer() .with_usage(wgpu::BufferUsages::VERTEX) .init_with_capacity(len) } fn create_index_buffer(context: &gpukit::Context, len: usize) -> gpukit::Buffer<u32> { context .build_buffer() .with_usage(wgpu::BufferUsages::INDEX) .init_with_capacity(len) } pub fn set_size(&mut self, size: [u32; 2], scale_factor: f32) { self.screen_uniforms.width_in_points = size[0] as f32 / scale_factor; self.screen_uniforms.height_in_points = size[1] as f32 / scale_factor; self.screen_uniforms.pixels_per_point = scale_factor; self.screen_uniforms.update(&self.context) } pub fn render<'encoder>( &'encoder mut self, rpass: &mut wgpu::RenderPass<'encoder>, meshes: &[egui::ClippedMesh], texture: &egui::Texture, ) { use gpukit::RenderPassExt; let offsets = self.update_buffers(meshes); self.update_texture(texture); rpass.set_pipeline(&self.pipeline); rpass.set_vertex_buffer(0, *self.vertex_buffer.slice(..)); rpass.set_index_buffer_ext(self.index_buffer.slice(..)); rpass.set_bind_group(0, &self.bind_group, &[]); rpass.set_bind_group(1, &self.texture_bind_group, &[]); for (egui::ClippedMesh(rect, mesh), offset) in meshes.iter().zip(offsets) { if Self::set_scissor_region(rpass, &self.screen_uniforms, *rect) { let index_range = offset.index..offset.index + mesh.indices.len() as u32; rpass.draw_indexed(index_range, offset.vertex as i32, 0..1); } } } fn set_scissor_region( rpass: &mut wgpu::RenderPass, screen: &ScreenUniforms, rect: egui::Rect, ) -> bool { let left = rect.left() * screen.pixels_per_point; let right = rect.right() * screen.pixels_per_point; let top = rect.top() * screen.pixels_per_point; let bottom = rect.bottom() * screen.pixels_per_point; let screen_width = screen.width_in_points * screen.pixels_per_point; let screen_height = screen.height_in_points * screen.pixels_per_point; let left = left.clamp(0.0, screen_width); let top = top.clamp(0.0, screen_height); let right = right.clamp(left, screen_width); let bottom = bottom.clamp(top, screen_height); let left = left.round() as u32; let top = top.round() as u32; let right = right.round() as u32; let bottom = bottom.round() as u32; let width = right - left; let height = bottom - top; if width == 0 || height == 0 { false } else { rpass.set_scissor_rect(left, top, width, height); true } } fn update_buffers(&mut self, meshes: &[egui::ClippedMesh]) -> Vec<BufferOffset> { let mut offsets = Vec::with_capacity(meshes.len()); // Find out how many vertices/indices we need to render let mut vertex_count = 0; let mut index_count = 0; for egui::ClippedMesh(_, mesh) in meshes { offsets.push(BufferOffset { vertex: vertex_count, index: index_count, }); vertex_count += align_to_power_of_two(mesh.vertices.len() as u32, BUFFER_ALIGNMENT); index_count += align_to_power_of_two(mesh.indices.len() as u32, BUFFER_ALIGNMENT); } // Allocate space for the vertices/indices if vertex_count as usize > self.vertex_buffer.len() { self.vertex_buffer = Self::create_vertex_buffer(&self.context, vertex_count as usize); } if index_count as usize > self.index_buffer.len() { self.index_buffer = Self::create_index_buffer(&self.context, index_count as usize); } // Write vertices/indices to their respective buffers for (egui::ClippedMesh(_, mesh), offset) in meshes.iter().zip(&offsets) { let vertex_slice = Vertex::cast_slice(&mesh.vertices); self.vertex_buffer .write(&self.context, offset.vertex as usize, vertex_slice); self.index_buffer .write(&self.context, offset.index as usize, &mesh.indices); } offsets } fn update_texture(&mut self, texture: &egui::Texture) { if self.texture_version!= Some(texture.version) { self.texture_version = Some(texture.version); self.texture = self .context .build_texture() .with_usage(wgpu::TextureUsages::TEXTURE_BINDING) .init_with_data( [texture.width as u32, texture.height as u32], &texture.pixels, ); self.texture_bind_group.update( &self.context, &TextureBindings { texture: &self.texture.create_view(), }, ); } } } struct BufferOffset { vertex: u32, index: u32, } const BUFFER_ALIGNMENT: u32 = wgpu::COPY_BUFFER_ALIGNMENT.next_power_of_two() as u32; const fn align_to_power_of_two(x: u32, power: u32) -> u32 { (x + (power - 1)) &!(power - 1) }
2 => Uint32, ]], bind_group_layouts: &[&bind_group.layout, &texture_bind_group.layout],
random_line_split
renderer.rs
use gpukit::wgpu; use std::sync::Arc; pub struct Renderer { context: Arc<gpukit::Context>, pipeline: wgpu::RenderPipeline, vertex_buffer: gpukit::Buffer<Vertex>, index_buffer: gpukit::Buffer<u32>, bind_group: gpukit::BindGroup, screen_uniforms: UniformBuffer<ScreenUniforms>, texture_bind_group: gpukit::BindGroup, texture_version: Option<u64>, texture: gpukit::Texture<gpukit::format::R8Unorm>, } #[derive(gpukit::Bindings)] struct Bindings<'a> { #[uniform(binding = 0)] screen_uniforms: &'a gpukit::Buffer<ScreenUniforms>, #[sampler(binding = 1, filtering)] sampler: &'a wgpu::Sampler, } #[derive(gpukit::Bindings)] struct TextureBindings<'a> { #[texture(binding = 0)] texture: &'a gpukit::TextureView<gpukit::format::R8Unorm>, } #[repr(C)] #[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] struct ScreenUniforms { width_in_points: f32, height_in_points: f32, pixels_per_point: f32, _padding: u32, } struct UniformBuffer<T: bytemuck::Pod> { buffer: gpukit::Buffer<T>, value: T, } impl<T: bytemuck::Pod> std::ops::Deref for UniformBuffer<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.value } } impl<T: bytemuck::Pod> std::ops::DerefMut for UniformBuffer<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.value } } impl<T: bytemuck::Pod> UniformBuffer<T> { pub fn
(context: &gpukit::Context, value: T) -> Self { let buffer = context .build_buffer() .with_usage(wgpu::BufferUsages::UNIFORM) .init_with_data(std::slice::from_ref(&value)); UniformBuffer { buffer, value } } fn update(&self, context: &gpukit::Context) { self.buffer .update(context, std::slice::from_ref(&self.value)); } } #[repr(transparent)] #[derive(Debug, Copy, Clone)] struct Vertex(egui::paint::Vertex); // SAFETY: `egui::paint::Vertex` is `#[repr(C)]`. unsafe impl bytemuck::Pod for Vertex {} unsafe impl bytemuck::Zeroable for Vertex {} impl Vertex { // SAFETY: `egui::paint::Vertex` is `#[repr(C)]`. fn cast_slice(vertices: &[egui::paint::Vertex]) -> &[Vertex] { let ptr = vertices.as_ptr() as *const Vertex; let len = vertices.len(); unsafe { std::slice::from_raw_parts(ptr, len) } } } pub struct RendererDescriptor { pub context: Arc<gpukit::Context>, pub target_format: wgpu::TextureFormat, // Size of the screen: [width, height] pub size: [u32; 2], // Number of pixels per point pub pixels_per_point: f32, } impl Renderer { pub fn new(desc: RendererDescriptor) -> anyhow::Result<Renderer> { let RendererDescriptor { context, target_format, size, pixels_per_point, } = desc; let vertex_buffer = Self::create_vertex_buffer(&context, 0); let index_buffer = Self::create_index_buffer(&context, 0); let uniforms = UniformBuffer::new( &context, ScreenUniforms { width_in_points: size[0] as f32 / pixels_per_point, height_in_points: size[1] as f32 / pixels_per_point, pixels_per_point, _padding: 0, }, ); let sampler = context.device.create_sampler(&wgpu::SamplerDescriptor { label: None, address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Nearest, min_filter: wgpu::FilterMode::Linear, ..Default::default() }); let bind_group = gpukit::BindGroup::new( &context, &Bindings { screen_uniforms: &uniforms.buffer, sampler: &sampler, }, ); let texture = context .build_texture() .with_usage(wgpu::TextureUsages::TEXTURE_BINDING) .init_with_data([1, 1], &[0]); let texture_bind_group = gpukit::BindGroup::new( &context, &TextureBindings { texture: &texture.create_view(), }, ); let vertex = context .build_shader("gukit_egui vertex shader") .init_from_glsl(include_str!("shader.vert"), gpukit::ShaderStage::Vertex)?; let fragment = context .build_shader("gukit_egui fragment shader") .init_from_glsl(include_str!("shader.frag"), gpukit::ShaderStage::Fragment)?; let pipeline = context.create_render_pipeline(gpukit::RenderPipelineDescriptor { label: Some("gpukit_egui renderer"), vertex: vertex.entry("main"), fragment: fragment.entry("main"), vertex_buffers: &[gpukit::vertex_buffer_layout![ // Position 0 => Float32x2, // Texture Coordinates 1 => Float32x2, // Color 2 => Uint32, ]], bind_group_layouts: &[&bind_group.layout, &texture_bind_group.layout], color_targets: &[wgpu::ColorTargetState { format: target_format, blend: Some(wgpu::BlendState { color: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, alpha: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::OneMinusDstAlpha, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add, }, }), write_mask: wgpu::ColorWrites::all(), }], depth_stencil: None, primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, })?; Ok(Renderer { context, pipeline, vertex_buffer, index_buffer, bind_group, screen_uniforms: uniforms, texture_bind_group, texture_version: None, texture, }) } fn create_vertex_buffer(context: &gpukit::Context, len: usize) -> gpukit::Buffer<Vertex> { context .build_buffer() .with_usage(wgpu::BufferUsages::VERTEX) .init_with_capacity(len) } fn create_index_buffer(context: &gpukit::Context, len: usize) -> gpukit::Buffer<u32> { context .build_buffer() .with_usage(wgpu::BufferUsages::INDEX) .init_with_capacity(len) } pub fn set_size(&mut self, size: [u32; 2], scale_factor: f32) { self.screen_uniforms.width_in_points = size[0] as f32 / scale_factor; self.screen_uniforms.height_in_points = size[1] as f32 / scale_factor; self.screen_uniforms.pixels_per_point = scale_factor; self.screen_uniforms.update(&self.context) } pub fn render<'encoder>( &'encoder mut self, rpass: &mut wgpu::RenderPass<'encoder>, meshes: &[egui::ClippedMesh], texture: &egui::Texture, ) { use gpukit::RenderPassExt; let offsets = self.update_buffers(meshes); self.update_texture(texture); rpass.set_pipeline(&self.pipeline); rpass.set_vertex_buffer(0, *self.vertex_buffer.slice(..)); rpass.set_index_buffer_ext(self.index_buffer.slice(..)); rpass.set_bind_group(0, &self.bind_group, &[]); rpass.set_bind_group(1, &self.texture_bind_group, &[]); for (egui::ClippedMesh(rect, mesh), offset) in meshes.iter().zip(offsets) { if Self::set_scissor_region(rpass, &self.screen_uniforms, *rect) { let index_range = offset.index..offset.index + mesh.indices.len() as u32; rpass.draw_indexed(index_range, offset.vertex as i32, 0..1); } } } fn set_scissor_region( rpass: &mut wgpu::RenderPass, screen: &ScreenUniforms, rect: egui::Rect, ) -> bool { let left = rect.left() * screen.pixels_per_point; let right = rect.right() * screen.pixels_per_point; let top = rect.top() * screen.pixels_per_point; let bottom = rect.bottom() * screen.pixels_per_point; let screen_width = screen.width_in_points * screen.pixels_per_point; let screen_height = screen.height_in_points * screen.pixels_per_point; let left = left.clamp(0.0, screen_width); let top = top.clamp(0.0, screen_height); let right = right.clamp(left, screen_width); let bottom = bottom.clamp(top, screen_height); let left = left.round() as u32; let top = top.round() as u32; let right = right.round() as u32; let bottom = bottom.round() as u32; let width = right - left; let height = bottom - top; if width == 0 || height == 0 { false } else { rpass.set_scissor_rect(left, top, width, height); true } } fn update_buffers(&mut self, meshes: &[egui::ClippedMesh]) -> Vec<BufferOffset> { let mut offsets = Vec::with_capacity(meshes.len()); // Find out how many vertices/indices we need to render let mut vertex_count = 0; let mut index_count = 0; for egui::ClippedMesh(_, mesh) in meshes { offsets.push(BufferOffset { vertex: vertex_count, index: index_count, }); vertex_count += align_to_power_of_two(mesh.vertices.len() as u32, BUFFER_ALIGNMENT); index_count += align_to_power_of_two(mesh.indices.len() as u32, BUFFER_ALIGNMENT); } // Allocate space for the vertices/indices if vertex_count as usize > self.vertex_buffer.len() { self.vertex_buffer = Self::create_vertex_buffer(&self.context, vertex_count as usize); } if index_count as usize > self.index_buffer.len() { self.index_buffer = Self::create_index_buffer(&self.context, index_count as usize); } // Write vertices/indices to their respective buffers for (egui::ClippedMesh(_, mesh), offset) in meshes.iter().zip(&offsets) { let vertex_slice = Vertex::cast_slice(&mesh.vertices); self.vertex_buffer .write(&self.context, offset.vertex as usize, vertex_slice); self.index_buffer .write(&self.context, offset.index as usize, &mesh.indices); } offsets } fn update_texture(&mut self, texture: &egui::Texture) { if self.texture_version!= Some(texture.version) { self.texture_version = Some(texture.version); self.texture = self .context .build_texture() .with_usage(wgpu::TextureUsages::TEXTURE_BINDING) .init_with_data( [texture.width as u32, texture.height as u32], &texture.pixels, ); self.texture_bind_group.update( &self.context, &TextureBindings { texture: &self.texture.create_view(), }, ); } } } struct BufferOffset { vertex: u32, index: u32, } const BUFFER_ALIGNMENT: u32 = wgpu::COPY_BUFFER_ALIGNMENT.next_power_of_two() as u32; const fn align_to_power_of_two(x: u32, power: u32) -> u32 { (x + (power - 1)) &!(power - 1) }
new
identifier_name
exec.rs
use crate::guest; use crate::guest::{Crash, Guest}; use crate::utils::cli::{App, Arg, OptVal}; use crate::utils::free_ipv4_port; use crate::Config; use core::c::to_prog; use core::prog::Prog; use core::target::Target; use executor::transfer::{async_recv_result, async_send}; use executor::{ExecResult, Reason}; use std::env::temp_dir; use std::path::PathBuf; use std::process::exit; use tokio::fs::write; use tokio::io::AsyncReadExt; use tokio::net::{TcpListener, TcpStream}; use tokio::process::Child; use tokio::sync::oneshot; use tokio::time::{delay_for, timeout, Duration}; // config for executor #[derive(Debug, Clone, Deserialize)] pub struct ExecutorConf { pub path: PathBuf, pub host_ip: Option<String>, pub concurrency: bool, pub memleak_check: bool, pub script_mode: bool, } impl ExecutorConf { pub fn check(&self) { if!self.path.is_file() { eprintln!( "Config Error: executor executable file {} is invalid", self.path.display() ); exit(exitcode::CONFIG) } if let Some(ip) = &self.host_ip { use std::net::ToSocketAddrs; let addr = format!("{}:8080", ip); if let Err(e) = addr.to_socket_addrs() { eprintln!( "Config Error: invalid host ip `{}`: {}", self.host_ip.as_ref().unwrap(), e ); exit(exitcode::CONFIG) } } } } pub struct Executor { inner: ExecutorImpl, } enum ExecutorImpl { Linux(LinuxExecutor), Scripy(ScriptExecutor), } impl Executor { pub fn new(cfg: &Config) -> Self { let inner = if cfg.executor.script_mode { ExecutorImpl::Scripy(ScriptExecutor::new(cfg)) } else { ExecutorImpl::Linux(LinuxExecutor::new(cfg)) }; Self { inner } } pub async fn
(&mut self) { match self.inner { ExecutorImpl::Linux(ref mut e) => e.start().await, ExecutorImpl::Scripy(ref mut e) => e.start().await, } } pub async fn exec(&mut self, p: &Prog, t: &Target) -> Result<ExecResult, Option<Crash>> { match self.inner { ExecutorImpl::Linux(ref mut e) => e.exec(p).await, ExecutorImpl::Scripy(ref mut e) => e.exec(p, t).await, } } } struct ScriptExecutor { path_on_host: PathBuf, guest: Guest, } impl ScriptExecutor { pub fn new(cfg: &Config) -> Self { let guest = Guest::new(cfg); Self { path_on_host: cfg.executor.path.clone(), guest, } } pub async fn start(&mut self) { self.guest.boot().await; } pub async fn exec(&mut self, p: &Prog, t: &Target) -> Result<ExecResult, Option<Crash>> { let p_text = to_prog(p, t); let tmp = temp_dir().join("HEALER_test_case_v1-1-1.c"); if let Err(e) = write(&tmp, &p_text).await { eprintln!( "Failed to write test case to tmp dir \"{}\": {}", tmp.display(), e ); exit(1); } let guest_case_file = self.guest.copy(&tmp).await; let mut executor = App::new(self.path_on_host.to_str().unwrap()); executor.arg(Arg::new_flag(guest_case_file.to_str().unwrap())); let mut exec_handle = self.guest.run_cmd(&executor).await; match timeout(Duration::new(15, 0), &mut exec_handle).await { Err(_) => Ok(ExecResult::Failed(Reason("Time out".to_string()))), Ok(_) => { let mut stdout = exec_handle.stdout.take().unwrap(); let mut output = String::new(); stdout.read_to_string(&mut output).await.unwrap(); self.parse_exec_result(output).await } } } pub async fn parse_exec_result(&mut self, out: String) -> Result<ExecResult, Option<Crash>> { let mut result_line = String::new(); for l in out.lines() { if l.contains("HEALER_EXEC_RESULT") { result_line = l.to_string(); } } if!result_line.is_empty() { let out = out.replace(&result_line, ""); if result_line.contains("success") { return Ok(ExecResult::Ok(Default::default())); } else if result_line.contains("failed") { return Ok(ExecResult::Failed(Reason(out))); } else if result_line.contains("crashed") { return Err(Some(Crash { inner: out })); } } if!self.guest.is_alive().await { Err(Some(Crash { inner: out })) } else { Ok(ExecResult::Ok(Default::default())) } } } struct LinuxExecutor { guest: Guest, port: u16, exec_handle: Option<Child>, conn: Option<TcpStream>, concurrency: bool, memleak_check: bool, executor_bin_path: PathBuf, target_path: PathBuf, host_ip: String, } impl LinuxExecutor { pub fn new(cfg: &Config) -> Self { let guest = Guest::new(cfg); let port = free_ipv4_port() .unwrap_or_else(|| exits!(exitcode::TEMPFAIL, "No Free port for executor driver")); let host_ip = cfg .executor .host_ip .as_ref() .map(String::from) .unwrap_or_else(|| String::from(guest::LINUX_QEMU_HOST_IP_ADDR)); Self { guest, port, exec_handle: None, conn: None, concurrency: cfg.executor.concurrency, memleak_check: cfg.executor.memleak_check, executor_bin_path: cfg.executor.path.clone(), target_path: PathBuf::from(&cfg.fots_bin), host_ip, } } pub async fn start(&mut self) { // handle should be set to kill on drop self.exec_handle = None; self.guest.boot().await; self.start_executer().await } pub async fn start_executer(&mut self) { use tokio::io::ErrorKind::*; self.exec_handle = None; let target = self.guest.copy(&self.target_path).await; let (tx, rx) = oneshot::channel(); let mut retry = 0; let mut listener; loop { let host_addr = format!("{}:{}", self.host_ip, self.port); listener = match TcpListener::bind(&host_addr).await { Ok(l) => l, Err(e) => { if e.kind() == AddrInUse && retry!= 5 { self.port = free_ipv4_port().unwrap(); retry += 1; continue; } else { eprintln!("Fail to listen on {}: {}", host_addr, e); exit(1); } } }; break; } let host_addr = listener.local_addr().unwrap(); tokio::spawn(async move { match listener.accept().await { Ok((conn, _addr)) => { tx.send(conn).unwrap(); } Err(e) => { eprintln!("Executor driver: fail to get client: {}", e); exit(exitcode::OSERR); } } }); let mut executor = App::new(self.executor_bin_path.to_str().unwrap()); executor .arg(Arg::new_opt("-t", OptVal::normal(target.to_str().unwrap()))) .arg(Arg::new_opt( "-a", OptVal::normal(&format!( "{}:{}", guest::LINUX_QEMU_USER_NET_HOST_IP_ADDR, self.port )), )); if self.memleak_check { executor.arg(Arg::new_flag("-m")); } if self.concurrency { executor.arg(Arg::new_flag("-c")); } self.exec_handle = Some(self.guest.run_cmd(&executor).await); self.conn = match timeout(Duration::new(32, 0), rx).await { Err(_) => { self.exec_handle = None; eprintln!("Time out: wait executor connection {}", host_addr); exit(1) } Ok(conn) => Some(conn.unwrap()), }; } pub async fn exec(&mut self, p: &Prog) -> Result<ExecResult, Option<Crash>> { // send must be success assert!(self.conn.is_some()); if let Err(e) = timeout( Duration::new(15, 0), async_send(p, self.conn.as_mut().unwrap()), ) .await { info!("Prog send blocked: {}, restarting...", e); self.start().await; return Ok(ExecResult::Failed(Reason("Prog send blocked".into()))); } // async_send(p, self.conn.as_mut().unwrap()).await.unwrap(); let ret = { match timeout( Duration::new(15, 0), async_recv_result(self.conn.as_mut().unwrap()), ) .await { Err(e) => { info!("Prog recv blocked: {}, restarting...", e); self.start().await; return Ok(ExecResult::Failed(Reason("Prog send blocked".into()))); } Ok(ret) => ret, } }; match ret { Ok(result) => { self.guest.clear().await; if let ExecResult::Failed(ref reason) = result { let rea = reason.to_string(); if rea.contains("CRASH-MEMLEAK") { return Err(Some(Crash { inner: rea })); } } return Ok(result); } Err(_) => { let mut crashed: bool; let mut retry: u8 = 0; loop { crashed =!self.guest.is_alive().await; if crashed || retry == 10 { break; } else { retry += 1; delay_for(Duration::from_millis(500)).await; } } if crashed { return Err(self.guest.try_collect_crash().await); } else { let mut handle = self.exec_handle.take().unwrap(); let mut stdout = handle.stdout.take().unwrap(); let mut stderr = handle.stderr.take().unwrap(); handle.await.unwrap_or_else(|e| { exits!(exitcode::OSERR, "Fail to wait executor handle:{}", e) }); let mut err = Vec::new(); stderr.read_to_end(&mut err).await.unwrap(); let mut out = Vec::new(); stdout.read_to_end(&mut out).await.unwrap(); warn!( "Executor: Connection lost. STDOUT:{}. STDERR: {}", String::from_utf8(out).unwrap(), String::from_utf8(err).unwrap() ); self.start_executer().await; } } } // Caused by internal err Ok(ExecResult::Ok(Vec::new())) } }
start
identifier_name
exec.rs
use crate::guest; use crate::guest::{Crash, Guest}; use crate::utils::cli::{App, Arg, OptVal}; use crate::utils::free_ipv4_port; use crate::Config; use core::c::to_prog; use core::prog::Prog; use core::target::Target; use executor::transfer::{async_recv_result, async_send}; use executor::{ExecResult, Reason}; use std::env::temp_dir; use std::path::PathBuf; use std::process::exit; use tokio::fs::write; use tokio::io::AsyncReadExt; use tokio::net::{TcpListener, TcpStream}; use tokio::process::Child; use tokio::sync::oneshot; use tokio::time::{delay_for, timeout, Duration}; // config for executor #[derive(Debug, Clone, Deserialize)] pub struct ExecutorConf { pub path: PathBuf, pub host_ip: Option<String>, pub concurrency: bool, pub memleak_check: bool, pub script_mode: bool, } impl ExecutorConf { pub fn check(&self) { if!self.path.is_file() { eprintln!( "Config Error: executor executable file {} is invalid", self.path.display() ); exit(exitcode::CONFIG) } if let Some(ip) = &self.host_ip { use std::net::ToSocketAddrs; let addr = format!("{}:8080", ip); if let Err(e) = addr.to_socket_addrs() { eprintln!( "Config Error: invalid host ip `{}`: {}", self.host_ip.as_ref().unwrap(), e ); exit(exitcode::CONFIG) } } } } pub struct Executor { inner: ExecutorImpl, } enum ExecutorImpl { Linux(LinuxExecutor), Scripy(ScriptExecutor), } impl Executor { pub fn new(cfg: &Config) -> Self { let inner = if cfg.executor.script_mode { ExecutorImpl::Scripy(ScriptExecutor::new(cfg)) } else { ExecutorImpl::Linux(LinuxExecutor::new(cfg)) }; Self { inner } } pub async fn start(&mut self) { match self.inner { ExecutorImpl::Linux(ref mut e) => e.start().await, ExecutorImpl::Scripy(ref mut e) => e.start().await, } } pub async fn exec(&mut self, p: &Prog, t: &Target) -> Result<ExecResult, Option<Crash>> { match self.inner { ExecutorImpl::Linux(ref mut e) => e.exec(p).await, ExecutorImpl::Scripy(ref mut e) => e.exec(p, t).await, } } } struct ScriptExecutor { path_on_host: PathBuf, guest: Guest, } impl ScriptExecutor { pub fn new(cfg: &Config) -> Self { let guest = Guest::new(cfg); Self { path_on_host: cfg.executor.path.clone(), guest, } } pub async fn start(&mut self) { self.guest.boot().await; } pub async fn exec(&mut self, p: &Prog, t: &Target) -> Result<ExecResult, Option<Crash>> { let p_text = to_prog(p, t); let tmp = temp_dir().join("HEALER_test_case_v1-1-1.c"); if let Err(e) = write(&tmp, &p_text).await { eprintln!( "Failed to write test case to tmp dir \"{}\": {}", tmp.display(), e ); exit(1); } let guest_case_file = self.guest.copy(&tmp).await; let mut executor = App::new(self.path_on_host.to_str().unwrap()); executor.arg(Arg::new_flag(guest_case_file.to_str().unwrap())); let mut exec_handle = self.guest.run_cmd(&executor).await; match timeout(Duration::new(15, 0), &mut exec_handle).await { Err(_) => Ok(ExecResult::Failed(Reason("Time out".to_string()))), Ok(_) => { let mut stdout = exec_handle.stdout.take().unwrap(); let mut output = String::new(); stdout.read_to_string(&mut output).await.unwrap(); self.parse_exec_result(output).await } } } pub async fn parse_exec_result(&mut self, out: String) -> Result<ExecResult, Option<Crash>> { let mut result_line = String::new(); for l in out.lines() { if l.contains("HEALER_EXEC_RESULT") { result_line = l.to_string(); } } if!result_line.is_empty() { let out = out.replace(&result_line, ""); if result_line.contains("success") { return Ok(ExecResult::Ok(Default::default())); } else if result_line.contains("failed") { return Ok(ExecResult::Failed(Reason(out))); } else if result_line.contains("crashed") { return Err(Some(Crash { inner: out })); } } if!self.guest.is_alive().await { Err(Some(Crash { inner: out })) } else { Ok(ExecResult::Ok(Default::default())) } } } struct LinuxExecutor { guest: Guest, port: u16, exec_handle: Option<Child>, conn: Option<TcpStream>, concurrency: bool, memleak_check: bool, executor_bin_path: PathBuf, target_path: PathBuf, host_ip: String, } impl LinuxExecutor { pub fn new(cfg: &Config) -> Self
target_path: PathBuf::from(&cfg.fots_bin), host_ip, } } pub async fn start(&mut self) { // handle should be set to kill on drop self.exec_handle = None; self.guest.boot().await; self.start_executer().await } pub async fn start_executer(&mut self) { use tokio::io::ErrorKind::*; self.exec_handle = None; let target = self.guest.copy(&self.target_path).await; let (tx, rx) = oneshot::channel(); let mut retry = 0; let mut listener; loop { let host_addr = format!("{}:{}", self.host_ip, self.port); listener = match TcpListener::bind(&host_addr).await { Ok(l) => l, Err(e) => { if e.kind() == AddrInUse && retry!= 5 { self.port = free_ipv4_port().unwrap(); retry += 1; continue; } else { eprintln!("Fail to listen on {}: {}", host_addr, e); exit(1); } } }; break; } let host_addr = listener.local_addr().unwrap(); tokio::spawn(async move { match listener.accept().await { Ok((conn, _addr)) => { tx.send(conn).unwrap(); } Err(e) => { eprintln!("Executor driver: fail to get client: {}", e); exit(exitcode::OSERR); } } }); let mut executor = App::new(self.executor_bin_path.to_str().unwrap()); executor .arg(Arg::new_opt("-t", OptVal::normal(target.to_str().unwrap()))) .arg(Arg::new_opt( "-a", OptVal::normal(&format!( "{}:{}", guest::LINUX_QEMU_USER_NET_HOST_IP_ADDR, self.port )), )); if self.memleak_check { executor.arg(Arg::new_flag("-m")); } if self.concurrency { executor.arg(Arg::new_flag("-c")); } self.exec_handle = Some(self.guest.run_cmd(&executor).await); self.conn = match timeout(Duration::new(32, 0), rx).await { Err(_) => { self.exec_handle = None; eprintln!("Time out: wait executor connection {}", host_addr); exit(1) } Ok(conn) => Some(conn.unwrap()), }; } pub async fn exec(&mut self, p: &Prog) -> Result<ExecResult, Option<Crash>> { // send must be success assert!(self.conn.is_some()); if let Err(e) = timeout( Duration::new(15, 0), async_send(p, self.conn.as_mut().unwrap()), ) .await { info!("Prog send blocked: {}, restarting...", e); self.start().await; return Ok(ExecResult::Failed(Reason("Prog send blocked".into()))); } // async_send(p, self.conn.as_mut().unwrap()).await.unwrap(); let ret = { match timeout( Duration::new(15, 0), async_recv_result(self.conn.as_mut().unwrap()), ) .await { Err(e) => { info!("Prog recv blocked: {}, restarting...", e); self.start().await; return Ok(ExecResult::Failed(Reason("Prog send blocked".into()))); } Ok(ret) => ret, } }; match ret { Ok(result) => { self.guest.clear().await; if let ExecResult::Failed(ref reason) = result { let rea = reason.to_string(); if rea.contains("CRASH-MEMLEAK") { return Err(Some(Crash { inner: rea })); } } return Ok(result); } Err(_) => { let mut crashed: bool; let mut retry: u8 = 0; loop { crashed =!self.guest.is_alive().await; if crashed || retry == 10 { break; } else { retry += 1; delay_for(Duration::from_millis(500)).await; } } if crashed { return Err(self.guest.try_collect_crash().await); } else { let mut handle = self.exec_handle.take().unwrap(); let mut stdout = handle.stdout.take().unwrap(); let mut stderr = handle.stderr.take().unwrap(); handle.await.unwrap_or_else(|e| { exits!(exitcode::OSERR, "Fail to wait executor handle:{}", e) }); let mut err = Vec::new(); stderr.read_to_end(&mut err).await.unwrap(); let mut out = Vec::new(); stdout.read_to_end(&mut out).await.unwrap(); warn!( "Executor: Connection lost. STDOUT:{}. STDERR: {}", String::from_utf8(out).unwrap(), String::from_utf8(err).unwrap() ); self.start_executer().await; } } } // Caused by internal err Ok(ExecResult::Ok(Vec::new())) } }
{ let guest = Guest::new(cfg); let port = free_ipv4_port() .unwrap_or_else(|| exits!(exitcode::TEMPFAIL, "No Free port for executor driver")); let host_ip = cfg .executor .host_ip .as_ref() .map(String::from) .unwrap_or_else(|| String::from(guest::LINUX_QEMU_HOST_IP_ADDR)); Self { guest, port, exec_handle: None, conn: None, concurrency: cfg.executor.concurrency, memleak_check: cfg.executor.memleak_check, executor_bin_path: cfg.executor.path.clone(),
identifier_body
exec.rs
use crate::guest; use crate::guest::{Crash, Guest}; use crate::utils::cli::{App, Arg, OptVal}; use crate::utils::free_ipv4_port; use crate::Config; use core::c::to_prog; use core::prog::Prog; use core::target::Target; use executor::transfer::{async_recv_result, async_send}; use executor::{ExecResult, Reason}; use std::env::temp_dir; use std::path::PathBuf; use std::process::exit; use tokio::fs::write; use tokio::io::AsyncReadExt; use tokio::net::{TcpListener, TcpStream}; use tokio::process::Child; use tokio::sync::oneshot; use tokio::time::{delay_for, timeout, Duration}; // config for executor #[derive(Debug, Clone, Deserialize)] pub struct ExecutorConf { pub path: PathBuf, pub host_ip: Option<String>, pub concurrency: bool, pub memleak_check: bool, pub script_mode: bool, } impl ExecutorConf { pub fn check(&self) { if!self.path.is_file() { eprintln!( "Config Error: executor executable file {} is invalid", self.path.display() ); exit(exitcode::CONFIG) } if let Some(ip) = &self.host_ip { use std::net::ToSocketAddrs; let addr = format!("{}:8080", ip); if let Err(e) = addr.to_socket_addrs() { eprintln!( "Config Error: invalid host ip `{}`: {}", self.host_ip.as_ref().unwrap(), e ); exit(exitcode::CONFIG) } } } } pub struct Executor { inner: ExecutorImpl, } enum ExecutorImpl { Linux(LinuxExecutor), Scripy(ScriptExecutor), } impl Executor { pub fn new(cfg: &Config) -> Self { let inner = if cfg.executor.script_mode { ExecutorImpl::Scripy(ScriptExecutor::new(cfg)) } else { ExecutorImpl::Linux(LinuxExecutor::new(cfg)) }; Self { inner } } pub async fn start(&mut self) { match self.inner { ExecutorImpl::Linux(ref mut e) => e.start().await, ExecutorImpl::Scripy(ref mut e) => e.start().await, } } pub async fn exec(&mut self, p: &Prog, t: &Target) -> Result<ExecResult, Option<Crash>> { match self.inner { ExecutorImpl::Linux(ref mut e) => e.exec(p).await, ExecutorImpl::Scripy(ref mut e) => e.exec(p, t).await, } } } struct ScriptExecutor { path_on_host: PathBuf, guest: Guest, } impl ScriptExecutor { pub fn new(cfg: &Config) -> Self { let guest = Guest::new(cfg); Self { path_on_host: cfg.executor.path.clone(), guest, } } pub async fn start(&mut self) { self.guest.boot().await; } pub async fn exec(&mut self, p: &Prog, t: &Target) -> Result<ExecResult, Option<Crash>> { let p_text = to_prog(p, t); let tmp = temp_dir().join("HEALER_test_case_v1-1-1.c"); if let Err(e) = write(&tmp, &p_text).await { eprintln!( "Failed to write test case to tmp dir \"{}\": {}", tmp.display(), e ); exit(1); } let guest_case_file = self.guest.copy(&tmp).await; let mut executor = App::new(self.path_on_host.to_str().unwrap()); executor.arg(Arg::new_flag(guest_case_file.to_str().unwrap())); let mut exec_handle = self.guest.run_cmd(&executor).await; match timeout(Duration::new(15, 0), &mut exec_handle).await { Err(_) => Ok(ExecResult::Failed(Reason("Time out".to_string()))), Ok(_) => { let mut stdout = exec_handle.stdout.take().unwrap(); let mut output = String::new(); stdout.read_to_string(&mut output).await.unwrap(); self.parse_exec_result(output).await } } } pub async fn parse_exec_result(&mut self, out: String) -> Result<ExecResult, Option<Crash>> { let mut result_line = String::new(); for l in out.lines() { if l.contains("HEALER_EXEC_RESULT") { result_line = l.to_string(); } } if!result_line.is_empty() { let out = out.replace(&result_line, ""); if result_line.contains("success") { return Ok(ExecResult::Ok(Default::default())); } else if result_line.contains("failed") { return Ok(ExecResult::Failed(Reason(out))); } else if result_line.contains("crashed") { return Err(Some(Crash { inner: out })); } } if!self.guest.is_alive().await { Err(Some(Crash { inner: out })) } else { Ok(ExecResult::Ok(Default::default())) } } } struct LinuxExecutor { guest: Guest, port: u16, exec_handle: Option<Child>, conn: Option<TcpStream>, concurrency: bool, memleak_check: bool, executor_bin_path: PathBuf, target_path: PathBuf, host_ip: String, } impl LinuxExecutor { pub fn new(cfg: &Config) -> Self { let guest = Guest::new(cfg); let port = free_ipv4_port() .unwrap_or_else(|| exits!(exitcode::TEMPFAIL, "No Free port for executor driver")); let host_ip = cfg .executor .host_ip .as_ref() .map(String::from) .unwrap_or_else(|| String::from(guest::LINUX_QEMU_HOST_IP_ADDR)); Self { guest, port, exec_handle: None, conn: None, concurrency: cfg.executor.concurrency, memleak_check: cfg.executor.memleak_check, executor_bin_path: cfg.executor.path.clone(), target_path: PathBuf::from(&cfg.fots_bin), host_ip, } } pub async fn start(&mut self) { // handle should be set to kill on drop self.exec_handle = None; self.guest.boot().await; self.start_executer().await } pub async fn start_executer(&mut self) { use tokio::io::ErrorKind::*; self.exec_handle = None; let target = self.guest.copy(&self.target_path).await; let (tx, rx) = oneshot::channel(); let mut retry = 0; let mut listener; loop { let host_addr = format!("{}:{}", self.host_ip, self.port); listener = match TcpListener::bind(&host_addr).await { Ok(l) => l, Err(e) => { if e.kind() == AddrInUse && retry!= 5 { self.port = free_ipv4_port().unwrap(); retry += 1; continue; } else { eprintln!("Fail to listen on {}: {}", host_addr, e); exit(1); } } }; break; } let host_addr = listener.local_addr().unwrap(); tokio::spawn(async move { match listener.accept().await { Ok((conn, _addr)) => { tx.send(conn).unwrap(); } Err(e) => { eprintln!("Executor driver: fail to get client: {}", e); exit(exitcode::OSERR); } } }); let mut executor = App::new(self.executor_bin_path.to_str().unwrap()); executor .arg(Arg::new_opt("-t", OptVal::normal(target.to_str().unwrap()))) .arg(Arg::new_opt( "-a", OptVal::normal(&format!( "{}:{}", guest::LINUX_QEMU_USER_NET_HOST_IP_ADDR, self.port )), )); if self.memleak_check { executor.arg(Arg::new_flag("-m")); } if self.concurrency { executor.arg(Arg::new_flag("-c")); } self.exec_handle = Some(self.guest.run_cmd(&executor).await); self.conn = match timeout(Duration::new(32, 0), rx).await { Err(_) =>
Ok(conn) => Some(conn.unwrap()), }; } pub async fn exec(&mut self, p: &Prog) -> Result<ExecResult, Option<Crash>> { // send must be success assert!(self.conn.is_some()); if let Err(e) = timeout( Duration::new(15, 0), async_send(p, self.conn.as_mut().unwrap()), ) .await { info!("Prog send blocked: {}, restarting...", e); self.start().await; return Ok(ExecResult::Failed(Reason("Prog send blocked".into()))); } // async_send(p, self.conn.as_mut().unwrap()).await.unwrap(); let ret = { match timeout( Duration::new(15, 0), async_recv_result(self.conn.as_mut().unwrap()), ) .await { Err(e) => { info!("Prog recv blocked: {}, restarting...", e); self.start().await; return Ok(ExecResult::Failed(Reason("Prog send blocked".into()))); } Ok(ret) => ret, } }; match ret { Ok(result) => { self.guest.clear().await; if let ExecResult::Failed(ref reason) = result { let rea = reason.to_string(); if rea.contains("CRASH-MEMLEAK") { return Err(Some(Crash { inner: rea })); } } return Ok(result); } Err(_) => { let mut crashed: bool; let mut retry: u8 = 0; loop { crashed =!self.guest.is_alive().await; if crashed || retry == 10 { break; } else { retry += 1; delay_for(Duration::from_millis(500)).await; } } if crashed { return Err(self.guest.try_collect_crash().await); } else { let mut handle = self.exec_handle.take().unwrap(); let mut stdout = handle.stdout.take().unwrap(); let mut stderr = handle.stderr.take().unwrap(); handle.await.unwrap_or_else(|e| { exits!(exitcode::OSERR, "Fail to wait executor handle:{}", e) }); let mut err = Vec::new(); stderr.read_to_end(&mut err).await.unwrap(); let mut out = Vec::new(); stdout.read_to_end(&mut out).await.unwrap(); warn!( "Executor: Connection lost. STDOUT:{}. STDERR: {}", String::from_utf8(out).unwrap(), String::from_utf8(err).unwrap() ); self.start_executer().await; } } } // Caused by internal err Ok(ExecResult::Ok(Vec::new())) } }
{ self.exec_handle = None; eprintln!("Time out: wait executor connection {}", host_addr); exit(1) }
conditional_block
exec.rs
use crate::guest; use crate::guest::{Crash, Guest}; use crate::utils::cli::{App, Arg, OptVal}; use crate::utils::free_ipv4_port; use crate::Config; use core::c::to_prog; use core::prog::Prog; use core::target::Target; use executor::transfer::{async_recv_result, async_send}; use executor::{ExecResult, Reason}; use std::env::temp_dir; use std::path::PathBuf; use std::process::exit; use tokio::fs::write; use tokio::io::AsyncReadExt; use tokio::net::{TcpListener, TcpStream}; use tokio::process::Child; use tokio::sync::oneshot; use tokio::time::{delay_for, timeout, Duration}; // config for executor #[derive(Debug, Clone, Deserialize)] pub struct ExecutorConf { pub path: PathBuf, pub host_ip: Option<String>, pub concurrency: bool, pub memleak_check: bool, pub script_mode: bool, } impl ExecutorConf { pub fn check(&self) { if!self.path.is_file() { eprintln!( "Config Error: executor executable file {} is invalid", self.path.display() ); exit(exitcode::CONFIG) } if let Some(ip) = &self.host_ip { use std::net::ToSocketAddrs; let addr = format!("{}:8080", ip); if let Err(e) = addr.to_socket_addrs() { eprintln!( "Config Error: invalid host ip `{}`: {}", self.host_ip.as_ref().unwrap(), e ); exit(exitcode::CONFIG) } } } } pub struct Executor { inner: ExecutorImpl, } enum ExecutorImpl { Linux(LinuxExecutor), Scripy(ScriptExecutor), } impl Executor { pub fn new(cfg: &Config) -> Self { let inner = if cfg.executor.script_mode { ExecutorImpl::Scripy(ScriptExecutor::new(cfg)) } else { ExecutorImpl::Linux(LinuxExecutor::new(cfg)) }; Self { inner } } pub async fn start(&mut self) { match self.inner { ExecutorImpl::Linux(ref mut e) => e.start().await, ExecutorImpl::Scripy(ref mut e) => e.start().await, } } pub async fn exec(&mut self, p: &Prog, t: &Target) -> Result<ExecResult, Option<Crash>> { match self.inner { ExecutorImpl::Linux(ref mut e) => e.exec(p).await, ExecutorImpl::Scripy(ref mut e) => e.exec(p, t).await, } } } struct ScriptExecutor { path_on_host: PathBuf, guest: Guest, } impl ScriptExecutor { pub fn new(cfg: &Config) -> Self { let guest = Guest::new(cfg); Self { path_on_host: cfg.executor.path.clone(), guest, } } pub async fn start(&mut self) { self.guest.boot().await; } pub async fn exec(&mut self, p: &Prog, t: &Target) -> Result<ExecResult, Option<Crash>> { let p_text = to_prog(p, t); let tmp = temp_dir().join("HEALER_test_case_v1-1-1.c"); if let Err(e) = write(&tmp, &p_text).await { eprintln!( "Failed to write test case to tmp dir \"{}\": {}", tmp.display(), e ); exit(1); } let guest_case_file = self.guest.copy(&tmp).await; let mut executor = App::new(self.path_on_host.to_str().unwrap()); executor.arg(Arg::new_flag(guest_case_file.to_str().unwrap())); let mut exec_handle = self.guest.run_cmd(&executor).await; match timeout(Duration::new(15, 0), &mut exec_handle).await { Err(_) => Ok(ExecResult::Failed(Reason("Time out".to_string()))), Ok(_) => { let mut stdout = exec_handle.stdout.take().unwrap(); let mut output = String::new(); stdout.read_to_string(&mut output).await.unwrap(); self.parse_exec_result(output).await } } } pub async fn parse_exec_result(&mut self, out: String) -> Result<ExecResult, Option<Crash>> { let mut result_line = String::new(); for l in out.lines() { if l.contains("HEALER_EXEC_RESULT") { result_line = l.to_string(); } } if!result_line.is_empty() { let out = out.replace(&result_line, ""); if result_line.contains("success") { return Ok(ExecResult::Ok(Default::default())); } else if result_line.contains("failed") { return Ok(ExecResult::Failed(Reason(out))); } else if result_line.contains("crashed") { return Err(Some(Crash { inner: out })); } } if!self.guest.is_alive().await { Err(Some(Crash { inner: out })) } else { Ok(ExecResult::Ok(Default::default())) } } } struct LinuxExecutor { guest: Guest, port: u16, exec_handle: Option<Child>, conn: Option<TcpStream>, concurrency: bool, memleak_check: bool, executor_bin_path: PathBuf, target_path: PathBuf, host_ip: String, } impl LinuxExecutor { pub fn new(cfg: &Config) -> Self { let guest = Guest::new(cfg); let port = free_ipv4_port() .unwrap_or_else(|| exits!(exitcode::TEMPFAIL, "No Free port for executor driver")); let host_ip = cfg .executor .host_ip .as_ref() .map(String::from) .unwrap_or_else(|| String::from(guest::LINUX_QEMU_HOST_IP_ADDR)); Self { guest, port, exec_handle: None, conn: None, concurrency: cfg.executor.concurrency, memleak_check: cfg.executor.memleak_check, executor_bin_path: cfg.executor.path.clone(), target_path: PathBuf::from(&cfg.fots_bin), host_ip, } } pub async fn start(&mut self) { // handle should be set to kill on drop self.exec_handle = None; self.guest.boot().await; self.start_executer().await } pub async fn start_executer(&mut self) { use tokio::io::ErrorKind::*; self.exec_handle = None; let target = self.guest.copy(&self.target_path).await; let (tx, rx) = oneshot::channel(); let mut retry = 0; let mut listener; loop {
listener = match TcpListener::bind(&host_addr).await { Ok(l) => l, Err(e) => { if e.kind() == AddrInUse && retry!= 5 { self.port = free_ipv4_port().unwrap(); retry += 1; continue; } else { eprintln!("Fail to listen on {}: {}", host_addr, e); exit(1); } } }; break; } let host_addr = listener.local_addr().unwrap(); tokio::spawn(async move { match listener.accept().await { Ok((conn, _addr)) => { tx.send(conn).unwrap(); } Err(e) => { eprintln!("Executor driver: fail to get client: {}", e); exit(exitcode::OSERR); } } }); let mut executor = App::new(self.executor_bin_path.to_str().unwrap()); executor .arg(Arg::new_opt("-t", OptVal::normal(target.to_str().unwrap()))) .arg(Arg::new_opt( "-a", OptVal::normal(&format!( "{}:{}", guest::LINUX_QEMU_USER_NET_HOST_IP_ADDR, self.port )), )); if self.memleak_check { executor.arg(Arg::new_flag("-m")); } if self.concurrency { executor.arg(Arg::new_flag("-c")); } self.exec_handle = Some(self.guest.run_cmd(&executor).await); self.conn = match timeout(Duration::new(32, 0), rx).await { Err(_) => { self.exec_handle = None; eprintln!("Time out: wait executor connection {}", host_addr); exit(1) } Ok(conn) => Some(conn.unwrap()), }; } pub async fn exec(&mut self, p: &Prog) -> Result<ExecResult, Option<Crash>> { // send must be success assert!(self.conn.is_some()); if let Err(e) = timeout( Duration::new(15, 0), async_send(p, self.conn.as_mut().unwrap()), ) .await { info!("Prog send blocked: {}, restarting...", e); self.start().await; return Ok(ExecResult::Failed(Reason("Prog send blocked".into()))); } // async_send(p, self.conn.as_mut().unwrap()).await.unwrap(); let ret = { match timeout( Duration::new(15, 0), async_recv_result(self.conn.as_mut().unwrap()), ) .await { Err(e) => { info!("Prog recv blocked: {}, restarting...", e); self.start().await; return Ok(ExecResult::Failed(Reason("Prog send blocked".into()))); } Ok(ret) => ret, } }; match ret { Ok(result) => { self.guest.clear().await; if let ExecResult::Failed(ref reason) = result { let rea = reason.to_string(); if rea.contains("CRASH-MEMLEAK") { return Err(Some(Crash { inner: rea })); } } return Ok(result); } Err(_) => { let mut crashed: bool; let mut retry: u8 = 0; loop { crashed =!self.guest.is_alive().await; if crashed || retry == 10 { break; } else { retry += 1; delay_for(Duration::from_millis(500)).await; } } if crashed { return Err(self.guest.try_collect_crash().await); } else { let mut handle = self.exec_handle.take().unwrap(); let mut stdout = handle.stdout.take().unwrap(); let mut stderr = handle.stderr.take().unwrap(); handle.await.unwrap_or_else(|e| { exits!(exitcode::OSERR, "Fail to wait executor handle:{}", e) }); let mut err = Vec::new(); stderr.read_to_end(&mut err).await.unwrap(); let mut out = Vec::new(); stdout.read_to_end(&mut out).await.unwrap(); warn!( "Executor: Connection lost. STDOUT:{}. STDERR: {}", String::from_utf8(out).unwrap(), String::from_utf8(err).unwrap() ); self.start_executer().await; } } } // Caused by internal err Ok(ExecResult::Ok(Vec::new())) } }
let host_addr = format!("{}:{}", self.host_ip, self.port);
random_line_split
main.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #![cfg_attr(test, feature(assert_matches))] #[cfg(feature = "teeracle")] use crate::teeracle::start_interval_market_update; use crate::{ account_funding::{setup_account_funding, EnclaveAccountInfoProvider}, error::Error, globals::tokio_handle::{GetTokioHandle, GlobalTokioHandle}, initialized_service::{ start_is_initialized_server, InitializationHandler, IsInitialized, TrackInitialization, }, ocall_bridge::{ bridge_api::Bridge as OCallBridge, component_factory::OCallBridgeComponentFactory, }, parentchain_handler::{HandleParentchain, ParentchainHandler}, prometheus_metrics::{start_metrics_server, EnclaveMetricsReceiver, MetricsHandler}, sidechain_setup::{sidechain_init_block_production, sidechain_start_untrusted_rpc_server}, sync_block_broadcaster::SyncBlockBroadcaster, utils::{check_files, extract_shard}, worker::Worker, worker_peers_updater::WorkerPeersUpdater, }; use base58::ToBase58; use clap::{load_yaml, App}; use codec::{Decode, Encode}; use config::Config; use enclave::{ api::enclave_init, tls_ra::{enclave_request_state_provisioning, enclave_run_state_provisioning_server}, }; use itp_enclave_api::{ direct_request::DirectRequest, enclave_base::EnclaveBase, remote_attestation::{RemoteAttestation, TlsRemoteAttestation}, sidechain::Sidechain, teeracle_api::TeeracleApi, Enclave, }; use itp_node_api::{ api_client::{AccountApi, PalletTeerexApi, ParentchainApi}, metadata::NodeMetadata, node_api_factory::{CreateNodeApi, NodeApiFactory}, }; use itp_settings::{ files::SIDECHAIN_STORAGE_PATH, worker_mode::{ProvideWorkerMode, WorkerMode, WorkerModeProvider}, }; use its_peer_fetch::{ block_fetch_client::BlockFetcher, untrusted_peer_fetch::UntrustedPeerFetcher, }; use its_primitives::types::block::SignedBlock as SignedSidechainBlock; use its_storage::{interface::FetchBlocks, BlockPruner, SidechainStorageLock}; use log::*; use my_node_runtime::{Event, Hash, Header}; use sgx_types::*; use sp_core::crypto::{AccountId32, Ss58Codec}; use sp_keyring::AccountKeyring; use std::{ path::PathBuf, str, sync::{ mpsc::{channel, Sender}, Arc, }, thread, time::Duration, }; use substrate_api_client::{utils::FromHexString, Header as HeaderTrait, XtStatus}; use teerex_primitives::ShardIdentifier; mod account_funding; mod config; mod enclave; mod error; mod globals; mod initialized_service; mod ocall_bridge; mod parentchain_handler; mod prometheus_metrics; mod setup; mod sidechain_setup; mod sync_block_broadcaster; mod sync_state; #[cfg(feature = "teeracle")] mod teeracle; mod tests; mod utils; mod worker; mod worker_peers_updater; const VERSION: &str = env!("CARGO_PKG_VERSION"); pub type EnclaveWorker = Worker<Config, NodeApiFactory, Enclave, InitializationHandler<WorkerModeProvider>>; fn main() { // Setup logging env_logger::init(); let yml = load_yaml!("cli.yml"); let matches = App::from_yaml(yml).get_matches(); let config = Config::from(&matches); GlobalTokioHandle::initialize(); // log this information, don't println because some python scripts for GA rely on the // stdout from the service #[cfg(feature = "production")] info!("*** Starting service in SGX production mode"); #[cfg(not(feature = "production"))] info!("*** Starting service in SGX debug mode"); info!("*** Running worker in mode: {:?} \n", WorkerModeProvider::worker_mode()); let clean_reset = matches.is_present("clean-reset"); if clean_reset { setup::purge_files_from_cwd().unwrap(); } // build the entire dependency tree let tokio_handle = Arc::new(GlobalTokioHandle {}); let sidechain_blockstorage = Arc::new( SidechainStorageLock::<SignedSidechainBlock>::new(PathBuf::from(&SIDECHAIN_STORAGE_PATH)) .unwrap(), ); let node_api_factory = Arc::new(NodeApiFactory::new(config.node_url(), AccountKeyring::Alice.pair())); let enclave = Arc::new(enclave_init(&config).unwrap()); let initialization_handler = Arc::new(InitializationHandler::default()); let worker = Arc::new(EnclaveWorker::new( config.clone(), enclave.clone(), node_api_factory.clone(), initialization_handler.clone(), Vec::new(), )); let sync_block_broadcaster = Arc::new(SyncBlockBroadcaster::new(tokio_handle.clone(), worker.clone())); let peer_updater = Arc::new(WorkerPeersUpdater::new(worker)); let untrusted_peer_fetcher = UntrustedPeerFetcher::new(node_api_factory.clone()); let peer_sidechain_block_fetcher = Arc::new(BlockFetcher::<SignedSidechainBlock, _>::new(untrusted_peer_fetcher)); let enclave_metrics_receiver = Arc::new(EnclaveMetricsReceiver {}); // initialize o-call bridge with a concrete factory implementation OCallBridge::initialize(Arc::new(OCallBridgeComponentFactory::new( node_api_factory.clone(), sync_block_broadcaster, enclave.clone(), sidechain_blockstorage.clone(), peer_updater, peer_sidechain_block_fetcher, tokio_handle.clone(), enclave_metrics_receiver, ))); if let Some(run_config) = &config.run_config { let shard = extract_shard(&run_config.shard, enclave.as_ref()); println!("Worker Config: {:?}", config); if clean_reset { setup::initialize_shard_and_keys(enclave.as_ref(), &shard).unwrap(); } let node_api = node_api_factory.create_api().expect("Failed to create parentchain node API"); if run_config.request_state { sync_state::sync_state::<_, _, WorkerModeProvider>( &node_api, &shard, enclave.as_ref(), run_config.skip_ra, ); } start_worker::<_, _, _, _, WorkerModeProvider>( config, &shard, enclave, sidechain_blockstorage, node_api, tokio_handle, initialization_handler, ); } else if let Some(smatches) = matches.subcommand_matches("request-state") { println!("*** Requesting state from a registered worker \n"); let node_api = node_api_factory.create_api().expect("Failed to create parentchain node API"); sync_state::sync_state::<_, _, WorkerModeProvider>( &node_api, &extract_shard(&smatches.value_of("shard").map(|s| s.to_string()), enclave.as_ref()), enclave.as_ref(), smatches.is_present("skip-ra"), ); } else if matches.is_present("shielding-key") { setup::generate_shielding_key_file(enclave.as_ref()); } else if matches.is_present("signing-key") { setup::generate_signing_key_file(enclave.as_ref()); } else if matches.is_present("dump-ra") { info!("*** Perform RA and dump cert to disk"); enclave.dump_ra_to_disk().unwrap(); } else if matches.is_present("mrenclave") { println!("{}", enclave.get_mrenclave().unwrap().encode().to_base58()); } else if let Some(sub_matches) = matches.subcommand_matches("init-shard") { setup::init_shard( enclave.as_ref(), &extract_shard(&sub_matches.value_of("shard").map(|s| s.to_string()), enclave.as_ref()), ); } else if let Some(sub_matches) = matches.subcommand_matches("test") { if sub_matches.is_present("provisioning-server") { println!("*** Running Enclave MU-RA TLS server\n"); enclave_run_state_provisioning_server( enclave.as_ref(), sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, &config.mu_ra_url(), sub_matches.is_present("skip-ra"), ); println!("[+] Done!"); } else if sub_matches.is_present("provisioning-client") { println!("*** Running Enclave MU-RA TLS client\n"); let shard = extract_shard( &sub_matches.value_of("shard").map(|s| s.to_string()), enclave.as_ref(), ); enclave_request_state_provisioning( enclave.as_ref(), sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, &config.mu_ra_url_external(), &shard, sub_matches.is_present("skip-ra"), ) .unwrap(); println!("[+] Done!"); } else { tests::run_enclave_tests(sub_matches); } } else { println!("For options: use --help"); } } /// FIXME: needs some discussion (restructuring?) #[allow(clippy::too_many_arguments)] fn start_worker<E, T, D, InitializationHandler, WorkerModeProvider>( config: Config, shard: &ShardIdentifier, enclave: Arc<E>, sidechain_storage: Arc<D>, node_api: ParentchainApi, tokio_handle_getter: Arc<T>, initialization_handler: Arc<InitializationHandler>, ) where T: GetTokioHandle, E: EnclaveBase + DirectRequest + Sidechain + RemoteAttestation + TlsRemoteAttestation + TeeracleApi + Clone, D: BlockPruner + FetchBlocks<SignedSidechainBlock> + Sync + Send +'static, InitializationHandler: TrackInitialization + IsInitialized + Sync + Send +'static, WorkerModeProvider: ProvideWorkerMode, { println!("Integritee Worker v{}", VERSION); info!("starting worker on shard {}", shard.encode().to_base58()); // ------------------------------------------------------------------------ // check for required files check_files(); // ------------------------------------------------------------------------ // initialize the enclave let mrenclave = enclave.get_mrenclave().unwrap(); println!("MRENCLAVE={}", mrenclave.to_base58()); println!("MRENCLAVE in hex {:?}", hex::encode(mrenclave)); // ------------------------------------------------------------------------ // let new workers call us for key provisioning println!("MU-RA server listening on {}", config.mu_ra_url()); let run_config = config.run_config.clone().expect("Run config missing"); let skip_ra = run_config.skip_ra; let is_development_mode = run_config.dev; let ra_url = config.mu_ra_url(); let enclave_api_key_prov = enclave.clone(); thread::spawn(move || { enclave_run_state_provisioning_server( enclave_api_key_prov.as_ref(), sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, &ra_url, skip_ra, ); info!("State provisioning server stopped."); }); let tokio_handle = tokio_handle_getter.get_handle(); #[cfg(feature = "teeracle")] let teeracle_tokio_handle = tokio_handle.clone(); // ------------------------------------------------------------------------ // Get the public key of our TEE. let tee_accountid = enclave_account(enclave.as_ref()); println!("Enclave account {:} ", &tee_accountid.to_ss58check()); // ------------------------------------------------------------------------ // Start `is_initialized` server. let untrusted_http_server_port = config .try_parse_untrusted_http_server_port() .expect("untrusted http server port to be a valid port number"); let initialization_handler_clone = initialization_handler.clone(); tokio_handle.spawn(async move { if let Err(e) = start_is_initialized_server(initialization_handler_clone, untrusted_http_server_port) .await { error!("Unexpected error in `is_initialized` server: {:?}", e); } }); // ------------------------------------------------------------------------ // Start prometheus metrics server. if config.enable_metrics_server { let enclave_wallet = Arc::new(EnclaveAccountInfoProvider::new(node_api.clone(), tee_accountid.clone())); let metrics_handler = Arc::new(MetricsHandler::new(enclave_wallet)); let metrics_server_port = config .try_parse_metrics_server_port() .expect("metrics server port to be a valid port number"); tokio_handle.spawn(async move { if let Err(e) = start_metrics_server(metrics_handler, metrics_server_port).await { error!("Unexpected error in Prometheus metrics server: {:?}", e); } }); } // ------------------------------------------------------------------------ // Start trusted worker rpc server if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain || WorkerModeProvider::worker_mode() == WorkerMode::OffChainWorker { let direct_invocation_server_addr = config.trusted_worker_url_internal(); let enclave_for_direct_invocation = enclave.clone(); thread::spawn(move || { println!( "[+] Trusted RPC direct invocation server listening on {}", direct_invocation_server_addr ); enclave_for_direct_invocation .init_direct_invocation_server(direct_invocation_server_addr) .unwrap(); println!("[+] RPC direct invocation server shut down"); }); } // ------------------------------------------------------------------------ // Start untrusted worker rpc server. // i.e move sidechain block importing to trusted worker. if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { sidechain_start_untrusted_rpc_server( &config, enclave.clone(), sidechain_storage.clone(), tokio_handle, ); } // ------------------------------------------------------------------------ // Init parentchain specific stuff. Needed for parentchain communication. let parentchain_handler = Arc::new(ParentchainHandler::new(node_api.clone(), enclave.clone())); let last_synced_header = parentchain_handler.init_parentchain_components().unwrap(); let nonce = node_api.get_nonce_of(&tee_accountid).unwrap(); info!("Enclave nonce = {:?}", nonce); enclave .set_nonce(nonce) .expect("Could not set nonce of enclave. Returning here..."); let metadata = node_api.metadata.clone(); let runtime_spec_version = node_api.runtime_version.spec_version; let runtime_transaction_version = node_api.runtime_version.transaction_version; enclave .set_node_metadata( NodeMetadata::new(metadata, runtime_spec_version, runtime_transaction_version).encode(), ) .expect("Could not set the node metadata in the enclave"); // ------------------------------------------------------------------------ // Perform a remote attestation and get an unchecked extrinsic back. let trusted_url = config.trusted_worker_url_external(); if skip_ra { println!( "[!] skipping remote attestation. Registering enclave without attestation report." ); } else { println!("[!] creating remote attestation report and create enclave register extrinsic."); }; let uxt = enclave.perform_ra(&trusted_url, skip_ra).unwrap(); let mut xthex = hex::encode(uxt); xthex.insert_str(0, "0x"); // Account funds if let Err(x) = setup_account_funding(&node_api, &tee_accountid, xthex.clone(), is_development_mode) { error!("Starting worker failed: {:?}", x); // Return without registering the enclave. This will fail and the transaction will be banned for 30min. return } println!("[>] Register the enclave (send the extrinsic)"); let register_enclave_xt_hash = node_api.send_extrinsic(xthex, XtStatus::Finalized).unwrap(); println!("[<] Extrinsic got finalized. Hash: {:?}\n", register_enclave_xt_hash); let register_enclave_xt_header = node_api.get_header(register_enclave_xt_hash).unwrap().unwrap(); let we_are_primary_validateer = we_are_primary_validateer(&node_api, &register_enclave_xt_header).unwrap(); if we_are_primary_validateer { println!("[+] We are the primary validateer"); } else { println!("[+] We are NOT the primary validateer"); } initialization_handler.registered_on_parentchain(); // ------------------------------------------------------------------------ // initialize teeracle interval #[cfg(feature = "teeracle")] if WorkerModeProvider::worker_mode() == WorkerMode::Teeracle { start_interval_market_update( &node_api, run_config.teeracle_update_interval, enclave.as_ref(), &teeracle_tokio_handle, ); } if WorkerModeProvider::worker_mode()!= WorkerMode::Teeracle { println!("*** [+] Finished syncing light client, syncing parentchain..."); // Syncing all parentchain blocks, this might take a while.. let mut last_synced_header = parentchain_handler.sync_parentchain(last_synced_header).unwrap(); // ------------------------------------------------------------------------ // Initialize the sidechain if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { last_synced_header = sidechain_init_block_production( enclave, &register_enclave_xt_header, we_are_primary_validateer, parentchain_handler.clone(), sidechain_storage, &last_synced_header, ) .unwrap(); } // ------------------------------------------------------------------------ // start parentchain syncing loop (subscribe to header updates) thread::Builder::new() .name("parentchain_sync_loop".to_owned()) .spawn(move || { if let Err(e) = subscribe_to_parentchain_new_headers(parentchain_handler, last_synced_header) { error!("Parentchain block syncing terminated with a failure: {:?}", e); } println!("[!] Parentchain block syncing has terminated"); }) .unwrap(); } // ------------------------------------------------------------------------ if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { spawn_worker_for_shard_polling(shard, node_api.clone(), initialization_handler); } // ------------------------------------------------------------------------ // subscribe to events and react on firing println!("*** Subscribing to events"); let (sender, receiver) = channel(); let sender2 = sender.clone(); let _eventsubscriber = thread::Builder::new() .name("eventsubscriber".to_owned()) .spawn(move || { node_api.subscribe_events(sender2).unwrap(); }) .unwrap(); println!("[+] Subscribed to events. waiting..."); let timeout = Duration::from_millis(10); loop { if let Ok(msg) = receiver.recv_timeout(timeout) { if let Ok(events) = parse_events(msg.clone()) { print_events(events, sender.clone()) } } } } /// Start polling loop to wait until we have a worker for a shard registered on /// the parentchain (TEEREX WorkerForShard). This is the pre-requisite to be /// considered initialized and ready for the next worker to start (in sidechain mode only). /// considered initialized and ready for the next worker to start. fn spawn_worker_for_shard_polling<InitializationHandler>( shard: &ShardIdentifier, node_api: ParentchainApi, initialization_handler: Arc<InitializationHandler>, ) where InitializationHandler: TrackInitialization + Sync + Send +'static, { let shard_for_initialized = *shard; thread::spawn(move || { const POLL_INTERVAL_SECS: u64 = 2; loop { info!("Polling for worker for shard ({} seconds interval)", POLL_INTERVAL_SECS); if let Ok(Some(_)) = node_api.worker_for_shard(&shard_for_initialized, None) { // Set that the service is initialized. initialization_handler.worker_for_shard_registered(); println!("[+] Found `WorkerForShard` on parentchain state"); break } thread::sleep(Duration::from_secs(POLL_INTERVAL_SECS)); } }); } type Events = Vec<frame_system::EventRecord<Event, Hash>>; fn parse_events(event: String) -> Result<Events, String> { let _unhex = Vec::from_hex(event).map_err(|_| "Decoding Events Failed".to_string())?; let mut _er_enc = _unhex.as_slice(); Events::decode(&mut _er_enc).map_err(|_| "Decoding Events Failed".to_string()) } fn print_events(events: Events, _sender: Sender<String>)
} }, Event::Teerex(re) => { debug!("{:?}", re); match &re { my_node_runtime::pallet_teerex::Event::AddedEnclave(sender, worker_url) => { println!("[+] Received AddedEnclave event"); println!(" Sender (Worker): {:?}", sender); println!(" Registered URL: {:?}", str::from_utf8(worker_url).unwrap()); }, my_node_runtime::pallet_teerex::Event::Forwarded(shard) => { println!( "[+] Received trusted call for shard {}", shard.encode().to_base58() ); }, my_node_runtime::pallet_teerex::Event::ProcessedParentchainBlock( sender, block_hash, merkle_root, block_number, ) => { info!("[+] Received ProcessedParentchainBlock event"); debug!(" From: {:?}", sender); debug!(" Block Hash: {:?}", hex::encode(block_hash)); debug!(" Merkle Root: {:?}", hex::encode(merkle_root)); debug!(" Block Number: {:?}", block_number); }, my_node_runtime::pallet_teerex::Event::ShieldFunds(incognito_account) => { info!("[+] Received ShieldFunds event"); debug!(" For: {:?}", incognito_account); }, my_node_runtime::pallet_teerex::Event::UnshieldedFunds(incognito_account) => { info!("[+] Received UnshieldedFunds event"); debug!(" For: {:?}", incognito_account); }, _ => { trace!("Ignoring unsupported pallet_teerex event"); }, } }, #[cfg(feature = "teeracle")] Event::Teeracle(re) => { debug!("{:?}", re); match &re { my_node_runtime::pallet_teeracle::Event::ExchangeRateUpdated( source, currency, new_value, ) => { println!("[+] Received ExchangeRateUpdated event"); println!(" Data source: {}", source); println!(" Currency: {}", currency); println!(" Exchange rate: {:?}", new_value); }, my_node_runtime::pallet_teeracle::Event::ExchangeRateDeleted( source, currency, ) => { println!("[+] Received ExchangeRateDeleted event"); println!(" Data source: {}", source); println!(" Currency: {}", currency); }, my_node_runtime::pallet_teeracle::Event::AddedToWhitelist( source, mrenclave, ) => { println!("[+] Received AddedToWhitelist event"); println!(" Data source: {}", source); println!(" Currency: {:?}", mrenclave); }, my_node_runtime::pallet_teeracle::Event::RemovedFromWhitelist( source, mrenclave, ) => { println!("[+] Received RemovedFromWhitelist event"); println!(" Data source: {}", source); println!(" Currency: {:?}", mrenclave); }, _ => { trace!("Ignoring unsupported pallet_teeracle event"); }, } }, #[cfg(feature = "sidechain")] Event::Sidechain(re) => match &re { my_node_runtime::pallet_sidechain::Event::ProposedSidechainBlock( sender, payload, ) => { info!("[+] Received ProposedSidechainBlock event"); debug!(" From: {:?}", sender); debug!(" Payload: {:?}", hex::encode(payload)); }, _ => { trace!("Ignoring unsupported pallet_sidechain event"); }, }, _ => { trace!("Ignoring event {:?}", evr); }, } } } /// Subscribe to the node API finalized heads stream and trigger a parent chain sync /// upon receiving a new header. fn subscribe_to_parentchain_new_headers<E: EnclaveBase + Sidechain>( parentchain_handler: Arc<ParentchainHandler<ParentchainApi, E>>, mut last_synced_header: Header, ) -> Result<(), Error> { let (sender, receiver) = channel(); //TODO: this should be implemented by parentchain_handler directly, and not via // exposed parentchain_api. Blocked by https://github.com/scs/substrate-api-client/issues/267. parentchain_handler .parentchain_api() .subscribe_finalized_heads(sender) .map_err(Error::ApiClient)?; loop { let new_header: Header = match receiver.recv() { Ok(header_str) => serde_json::from_str(&header_str).map_err(Error::Serialization), Err(e) => Err(Error::ApiSubscriptionDisconnected(e)), }?; println!( "[+] Received finalized header update ({}), syncing parent chain...", new_header.number ); last_synced_header = parentchain_handler.sync_parentchain(last_synced_header)?; } } /// Get the public signing key of the TEE. fn enclave_account<E: EnclaveBase>(enclave_api: &E) -> AccountId32 { let tee_public = enclave_api.get_ecc_signing_pubkey().unwrap(); trace!("[+] Got ed25519 account of TEE = {}", tee_public.to_ss58check()); AccountId32::from(*tee_public.as_array_ref()) } /// Checks if we are the first validateer to register on the parentchain. fn we_are_primary_validateer( node_api: &ParentchainApi, register_enclave_xt_header: &Header, ) -> Result<bool, Error> { let enclave_count_of_previous_block = node_api.enclave_count(Some(*register_enclave_xt_header.parent_hash()))?; Ok(enclave_count_of_previous_block == 0) }
{ for evr in &events { debug!("Decoded: phase = {:?}, event = {:?}", evr.phase, evr.event); match &evr.event { Event::Balances(be) => { info!("[+] Received balances event"); debug!("{:?}", be); match &be { pallet_balances::Event::Transfer { from: transactor, to: dest, amount: value, } => { debug!(" Transactor: {:?}", transactor.to_ss58check()); debug!(" Destination: {:?}", dest.to_ss58check()); debug!(" Value: {:?}", value); }, _ => { trace!("Ignoring unsupported balances event"); },
identifier_body
main.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #![cfg_attr(test, feature(assert_matches))] #[cfg(feature = "teeracle")] use crate::teeracle::start_interval_market_update; use crate::{ account_funding::{setup_account_funding, EnclaveAccountInfoProvider}, error::Error, globals::tokio_handle::{GetTokioHandle, GlobalTokioHandle}, initialized_service::{ start_is_initialized_server, InitializationHandler, IsInitialized, TrackInitialization, }, ocall_bridge::{ bridge_api::Bridge as OCallBridge, component_factory::OCallBridgeComponentFactory, }, parentchain_handler::{HandleParentchain, ParentchainHandler}, prometheus_metrics::{start_metrics_server, EnclaveMetricsReceiver, MetricsHandler}, sidechain_setup::{sidechain_init_block_production, sidechain_start_untrusted_rpc_server}, sync_block_broadcaster::SyncBlockBroadcaster, utils::{check_files, extract_shard}, worker::Worker, worker_peers_updater::WorkerPeersUpdater, }; use base58::ToBase58; use clap::{load_yaml, App}; use codec::{Decode, Encode}; use config::Config; use enclave::{ api::enclave_init, tls_ra::{enclave_request_state_provisioning, enclave_run_state_provisioning_server}, }; use itp_enclave_api::{ direct_request::DirectRequest, enclave_base::EnclaveBase, remote_attestation::{RemoteAttestation, TlsRemoteAttestation}, sidechain::Sidechain, teeracle_api::TeeracleApi, Enclave, }; use itp_node_api::{ api_client::{AccountApi, PalletTeerexApi, ParentchainApi}, metadata::NodeMetadata, node_api_factory::{CreateNodeApi, NodeApiFactory}, }; use itp_settings::{ files::SIDECHAIN_STORAGE_PATH, worker_mode::{ProvideWorkerMode, WorkerMode, WorkerModeProvider}, }; use its_peer_fetch::{ block_fetch_client::BlockFetcher, untrusted_peer_fetch::UntrustedPeerFetcher, }; use its_primitives::types::block::SignedBlock as SignedSidechainBlock; use its_storage::{interface::FetchBlocks, BlockPruner, SidechainStorageLock}; use log::*; use my_node_runtime::{Event, Hash, Header}; use sgx_types::*; use sp_core::crypto::{AccountId32, Ss58Codec}; use sp_keyring::AccountKeyring; use std::{ path::PathBuf, str, sync::{ mpsc::{channel, Sender}, Arc, }, thread, time::Duration, }; use substrate_api_client::{utils::FromHexString, Header as HeaderTrait, XtStatus}; use teerex_primitives::ShardIdentifier; mod account_funding; mod config; mod enclave; mod error; mod globals; mod initialized_service; mod ocall_bridge; mod parentchain_handler; mod prometheus_metrics; mod setup; mod sidechain_setup; mod sync_block_broadcaster; mod sync_state; #[cfg(feature = "teeracle")] mod teeracle; mod tests; mod utils; mod worker; mod worker_peers_updater; const VERSION: &str = env!("CARGO_PKG_VERSION"); pub type EnclaveWorker = Worker<Config, NodeApiFactory, Enclave, InitializationHandler<WorkerModeProvider>>; fn main() { // Setup logging env_logger::init(); let yml = load_yaml!("cli.yml"); let matches = App::from_yaml(yml).get_matches(); let config = Config::from(&matches); GlobalTokioHandle::initialize(); // log this information, don't println because some python scripts for GA rely on the // stdout from the service #[cfg(feature = "production")] info!("*** Starting service in SGX production mode"); #[cfg(not(feature = "production"))] info!("*** Starting service in SGX debug mode"); info!("*** Running worker in mode: {:?} \n", WorkerModeProvider::worker_mode()); let clean_reset = matches.is_present("clean-reset"); if clean_reset { setup::purge_files_from_cwd().unwrap(); } // build the entire dependency tree let tokio_handle = Arc::new(GlobalTokioHandle {}); let sidechain_blockstorage = Arc::new( SidechainStorageLock::<SignedSidechainBlock>::new(PathBuf::from(&SIDECHAIN_STORAGE_PATH)) .unwrap(), ); let node_api_factory = Arc::new(NodeApiFactory::new(config.node_url(), AccountKeyring::Alice.pair())); let enclave = Arc::new(enclave_init(&config).unwrap()); let initialization_handler = Arc::new(InitializationHandler::default()); let worker = Arc::new(EnclaveWorker::new( config.clone(), enclave.clone(), node_api_factory.clone(), initialization_handler.clone(), Vec::new(), )); let sync_block_broadcaster = Arc::new(SyncBlockBroadcaster::new(tokio_handle.clone(), worker.clone())); let peer_updater = Arc::new(WorkerPeersUpdater::new(worker)); let untrusted_peer_fetcher = UntrustedPeerFetcher::new(node_api_factory.clone()); let peer_sidechain_block_fetcher = Arc::new(BlockFetcher::<SignedSidechainBlock, _>::new(untrusted_peer_fetcher)); let enclave_metrics_receiver = Arc::new(EnclaveMetricsReceiver {}); // initialize o-call bridge with a concrete factory implementation OCallBridge::initialize(Arc::new(OCallBridgeComponentFactory::new( node_api_factory.clone(), sync_block_broadcaster, enclave.clone(), sidechain_blockstorage.clone(), peer_updater, peer_sidechain_block_fetcher, tokio_handle.clone(), enclave_metrics_receiver, ))); if let Some(run_config) = &config.run_config { let shard = extract_shard(&run_config.shard, enclave.as_ref()); println!("Worker Config: {:?}", config); if clean_reset { setup::initialize_shard_and_keys(enclave.as_ref(), &shard).unwrap(); } let node_api = node_api_factory.create_api().expect("Failed to create parentchain node API"); if run_config.request_state { sync_state::sync_state::<_, _, WorkerModeProvider>( &node_api, &shard, enclave.as_ref(), run_config.skip_ra, ); } start_worker::<_, _, _, _, WorkerModeProvider>( config, &shard, enclave, sidechain_blockstorage, node_api, tokio_handle, initialization_handler, ); } else if let Some(smatches) = matches.subcommand_matches("request-state") { println!("*** Requesting state from a registered worker \n"); let node_api = node_api_factory.create_api().expect("Failed to create parentchain node API"); sync_state::sync_state::<_, _, WorkerModeProvider>( &node_api, &extract_shard(&smatches.value_of("shard").map(|s| s.to_string()), enclave.as_ref()), enclave.as_ref(), smatches.is_present("skip-ra"), ); } else if matches.is_present("shielding-key") { setup::generate_shielding_key_file(enclave.as_ref()); } else if matches.is_present("signing-key") { setup::generate_signing_key_file(enclave.as_ref()); } else if matches.is_present("dump-ra") { info!("*** Perform RA and dump cert to disk"); enclave.dump_ra_to_disk().unwrap(); } else if matches.is_present("mrenclave") { println!("{}", enclave.get_mrenclave().unwrap().encode().to_base58()); } else if let Some(sub_matches) = matches.subcommand_matches("init-shard") { setup::init_shard( enclave.as_ref(), &extract_shard(&sub_matches.value_of("shard").map(|s| s.to_string()), enclave.as_ref()), ); } else if let Some(sub_matches) = matches.subcommand_matches("test") { if sub_matches.is_present("provisioning-server") { println!("*** Running Enclave MU-RA TLS server\n"); enclave_run_state_provisioning_server( enclave.as_ref(), sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, &config.mu_ra_url(), sub_matches.is_present("skip-ra"), ); println!("[+] Done!"); } else if sub_matches.is_present("provisioning-client") { println!("*** Running Enclave MU-RA TLS client\n"); let shard = extract_shard( &sub_matches.value_of("shard").map(|s| s.to_string()), enclave.as_ref(), ); enclave_request_state_provisioning( enclave.as_ref(), sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, &config.mu_ra_url_external(), &shard, sub_matches.is_present("skip-ra"), ) .unwrap(); println!("[+] Done!"); } else { tests::run_enclave_tests(sub_matches); } } else { println!("For options: use --help"); } } /// FIXME: needs some discussion (restructuring?) #[allow(clippy::too_many_arguments)] fn start_worker<E, T, D, InitializationHandler, WorkerModeProvider>( config: Config, shard: &ShardIdentifier, enclave: Arc<E>, sidechain_storage: Arc<D>, node_api: ParentchainApi, tokio_handle_getter: Arc<T>, initialization_handler: Arc<InitializationHandler>, ) where T: GetTokioHandle, E: EnclaveBase + DirectRequest + Sidechain + RemoteAttestation + TlsRemoteAttestation + TeeracleApi + Clone, D: BlockPruner + FetchBlocks<SignedSidechainBlock> + Sync + Send +'static, InitializationHandler: TrackInitialization + IsInitialized + Sync + Send +'static, WorkerModeProvider: ProvideWorkerMode, { println!("Integritee Worker v{}", VERSION); info!("starting worker on shard {}", shard.encode().to_base58()); // ------------------------------------------------------------------------ // check for required files check_files(); // ------------------------------------------------------------------------ // initialize the enclave let mrenclave = enclave.get_mrenclave().unwrap(); println!("MRENCLAVE={}", mrenclave.to_base58()); println!("MRENCLAVE in hex {:?}", hex::encode(mrenclave)); // ------------------------------------------------------------------------ // let new workers call us for key provisioning println!("MU-RA server listening on {}", config.mu_ra_url()); let run_config = config.run_config.clone().expect("Run config missing"); let skip_ra = run_config.skip_ra; let is_development_mode = run_config.dev; let ra_url = config.mu_ra_url(); let enclave_api_key_prov = enclave.clone(); thread::spawn(move || { enclave_run_state_provisioning_server( enclave_api_key_prov.as_ref(), sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, &ra_url, skip_ra, ); info!("State provisioning server stopped."); }); let tokio_handle = tokio_handle_getter.get_handle(); #[cfg(feature = "teeracle")] let teeracle_tokio_handle = tokio_handle.clone(); // ------------------------------------------------------------------------ // Get the public key of our TEE. let tee_accountid = enclave_account(enclave.as_ref()); println!("Enclave account {:} ", &tee_accountid.to_ss58check()); // ------------------------------------------------------------------------ // Start `is_initialized` server. let untrusted_http_server_port = config .try_parse_untrusted_http_server_port() .expect("untrusted http server port to be a valid port number"); let initialization_handler_clone = initialization_handler.clone(); tokio_handle.spawn(async move { if let Err(e) = start_is_initialized_server(initialization_handler_clone, untrusted_http_server_port) .await { error!("Unexpected error in `is_initialized` server: {:?}", e); } }); // ------------------------------------------------------------------------ // Start prometheus metrics server. if config.enable_metrics_server { let enclave_wallet = Arc::new(EnclaveAccountInfoProvider::new(node_api.clone(), tee_accountid.clone())); let metrics_handler = Arc::new(MetricsHandler::new(enclave_wallet)); let metrics_server_port = config .try_parse_metrics_server_port() .expect("metrics server port to be a valid port number"); tokio_handle.spawn(async move { if let Err(e) = start_metrics_server(metrics_handler, metrics_server_port).await { error!("Unexpected error in Prometheus metrics server: {:?}", e); } }); } // ------------------------------------------------------------------------ // Start trusted worker rpc server if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain || WorkerModeProvider::worker_mode() == WorkerMode::OffChainWorker { let direct_invocation_server_addr = config.trusted_worker_url_internal(); let enclave_for_direct_invocation = enclave.clone(); thread::spawn(move || { println!( "[+] Trusted RPC direct invocation server listening on {}", direct_invocation_server_addr ); enclave_for_direct_invocation .init_direct_invocation_server(direct_invocation_server_addr) .unwrap(); println!("[+] RPC direct invocation server shut down"); }); } // ------------------------------------------------------------------------ // Start untrusted worker rpc server. // i.e move sidechain block importing to trusted worker. if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { sidechain_start_untrusted_rpc_server( &config, enclave.clone(), sidechain_storage.clone(), tokio_handle, ); } // ------------------------------------------------------------------------ // Init parentchain specific stuff. Needed for parentchain communication. let parentchain_handler = Arc::new(ParentchainHandler::new(node_api.clone(), enclave.clone())); let last_synced_header = parentchain_handler.init_parentchain_components().unwrap(); let nonce = node_api.get_nonce_of(&tee_accountid).unwrap(); info!("Enclave nonce = {:?}", nonce); enclave .set_nonce(nonce) .expect("Could not set nonce of enclave. Returning here..."); let metadata = node_api.metadata.clone(); let runtime_spec_version = node_api.runtime_version.spec_version; let runtime_transaction_version = node_api.runtime_version.transaction_version; enclave .set_node_metadata( NodeMetadata::new(metadata, runtime_spec_version, runtime_transaction_version).encode(), ) .expect("Could not set the node metadata in the enclave"); // ------------------------------------------------------------------------ // Perform a remote attestation and get an unchecked extrinsic back. let trusted_url = config.trusted_worker_url_external(); if skip_ra { println!( "[!] skipping remote attestation. Registering enclave without attestation report." ); } else { println!("[!] creating remote attestation report and create enclave register extrinsic."); }; let uxt = enclave.perform_ra(&trusted_url, skip_ra).unwrap(); let mut xthex = hex::encode(uxt); xthex.insert_str(0, "0x"); // Account funds if let Err(x) = setup_account_funding(&node_api, &tee_accountid, xthex.clone(), is_development_mode) { error!("Starting worker failed: {:?}", x); // Return without registering the enclave. This will fail and the transaction will be banned for 30min. return } println!("[>] Register the enclave (send the extrinsic)"); let register_enclave_xt_hash = node_api.send_extrinsic(xthex, XtStatus::Finalized).unwrap(); println!("[<] Extrinsic got finalized. Hash: {:?}\n", register_enclave_xt_hash); let register_enclave_xt_header = node_api.get_header(register_enclave_xt_hash).unwrap().unwrap(); let we_are_primary_validateer = we_are_primary_validateer(&node_api, &register_enclave_xt_header).unwrap(); if we_are_primary_validateer { println!("[+] We are the primary validateer"); } else { println!("[+] We are NOT the primary validateer"); } initialization_handler.registered_on_parentchain(); // ------------------------------------------------------------------------ // initialize teeracle interval #[cfg(feature = "teeracle")] if WorkerModeProvider::worker_mode() == WorkerMode::Teeracle { start_interval_market_update( &node_api, run_config.teeracle_update_interval, enclave.as_ref(), &teeracle_tokio_handle, ); } if WorkerModeProvider::worker_mode()!= WorkerMode::Teeracle { println!("*** [+] Finished syncing light client, syncing parentchain..."); // Syncing all parentchain blocks, this might take a while.. let mut last_synced_header = parentchain_handler.sync_parentchain(last_synced_header).unwrap(); // ------------------------------------------------------------------------ // Initialize the sidechain if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { last_synced_header = sidechain_init_block_production( enclave, &register_enclave_xt_header, we_are_primary_validateer, parentchain_handler.clone(), sidechain_storage, &last_synced_header, ) .unwrap(); } // ------------------------------------------------------------------------ // start parentchain syncing loop (subscribe to header updates) thread::Builder::new() .name("parentchain_sync_loop".to_owned()) .spawn(move || { if let Err(e) = subscribe_to_parentchain_new_headers(parentchain_handler, last_synced_header) { error!("Parentchain block syncing terminated with a failure: {:?}", e); } println!("[!] Parentchain block syncing has terminated"); }) .unwrap(); } // ------------------------------------------------------------------------ if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { spawn_worker_for_shard_polling(shard, node_api.clone(), initialization_handler); } // ------------------------------------------------------------------------ // subscribe to events and react on firing println!("*** Subscribing to events"); let (sender, receiver) = channel(); let sender2 = sender.clone(); let _eventsubscriber = thread::Builder::new() .name("eventsubscriber".to_owned()) .spawn(move || { node_api.subscribe_events(sender2).unwrap(); }) .unwrap(); println!("[+] Subscribed to events. waiting..."); let timeout = Duration::from_millis(10); loop { if let Ok(msg) = receiver.recv_timeout(timeout) { if let Ok(events) = parse_events(msg.clone()) { print_events(events, sender.clone()) } } } } /// Start polling loop to wait until we have a worker for a shard registered on /// the parentchain (TEEREX WorkerForShard). This is the pre-requisite to be /// considered initialized and ready for the next worker to start (in sidechain mode only). /// considered initialized and ready for the next worker to start. fn spawn_worker_for_shard_polling<InitializationHandler>( shard: &ShardIdentifier, node_api: ParentchainApi, initialization_handler: Arc<InitializationHandler>, ) where InitializationHandler: TrackInitialization + Sync + Send +'static, { let shard_for_initialized = *shard; thread::spawn(move || { const POLL_INTERVAL_SECS: u64 = 2; loop { info!("Polling for worker for shard ({} seconds interval)", POLL_INTERVAL_SECS); if let Ok(Some(_)) = node_api.worker_for_shard(&shard_for_initialized, None) { // Set that the service is initialized. initialization_handler.worker_for_shard_registered(); println!("[+] Found `WorkerForShard` on parentchain state"); break } thread::sleep(Duration::from_secs(POLL_INTERVAL_SECS)); } }); } type Events = Vec<frame_system::EventRecord<Event, Hash>>; fn parse_events(event: String) -> Result<Events, String> { let _unhex = Vec::from_hex(event).map_err(|_| "Decoding Events Failed".to_string())?; let mut _er_enc = _unhex.as_slice(); Events::decode(&mut _er_enc).map_err(|_| "Decoding Events Failed".to_string()) } fn print_events(events: Events, _sender: Sender<String>) { for evr in &events { debug!("Decoded: phase = {:?}, event = {:?}", evr.phase, evr.event); match &evr.event { Event::Balances(be) => { info!("[+] Received balances event"); debug!("{:?}", be); match &be { pallet_balances::Event::Transfer { from: transactor, to: dest, amount: value, } => { debug!(" Transactor: {:?}", transactor.to_ss58check()); debug!(" Destination: {:?}", dest.to_ss58check()); debug!(" Value: {:?}", value); }, _ => { trace!("Ignoring unsupported balances event"); }, } }, Event::Teerex(re) => { debug!("{:?}", re); match &re { my_node_runtime::pallet_teerex::Event::AddedEnclave(sender, worker_url) => { println!("[+] Received AddedEnclave event"); println!(" Sender (Worker): {:?}", sender); println!(" Registered URL: {:?}", str::from_utf8(worker_url).unwrap()); }, my_node_runtime::pallet_teerex::Event::Forwarded(shard) => { println!( "[+] Received trusted call for shard {}", shard.encode().to_base58() ); }, my_node_runtime::pallet_teerex::Event::ProcessedParentchainBlock( sender, block_hash, merkle_root, block_number, ) => { info!("[+] Received ProcessedParentchainBlock event"); debug!(" From: {:?}", sender); debug!(" Block Hash: {:?}", hex::encode(block_hash)); debug!(" Merkle Root: {:?}", hex::encode(merkle_root)); debug!(" Block Number: {:?}", block_number); }, my_node_runtime::pallet_teerex::Event::ShieldFunds(incognito_account) => { info!("[+] Received ShieldFunds event"); debug!(" For: {:?}", incognito_account); }, my_node_runtime::pallet_teerex::Event::UnshieldedFunds(incognito_account) => { info!("[+] Received UnshieldedFunds event"); debug!(" For: {:?}", incognito_account); }, _ => { trace!("Ignoring unsupported pallet_teerex event"); }, } }, #[cfg(feature = "teeracle")] Event::Teeracle(re) => { debug!("{:?}", re); match &re { my_node_runtime::pallet_teeracle::Event::ExchangeRateUpdated( source, currency, new_value, ) => { println!("[+] Received ExchangeRateUpdated event"); println!(" Data source: {}", source); println!(" Currency: {}", currency); println!(" Exchange rate: {:?}", new_value); }, my_node_runtime::pallet_teeracle::Event::ExchangeRateDeleted( source, currency, ) => { println!("[+] Received ExchangeRateDeleted event"); println!(" Data source: {}", source); println!(" Currency: {}", currency); }, my_node_runtime::pallet_teeracle::Event::AddedToWhitelist( source, mrenclave, ) => { println!("[+] Received AddedToWhitelist event"); println!(" Data source: {}", source); println!(" Currency: {:?}", mrenclave); }, my_node_runtime::pallet_teeracle::Event::RemovedFromWhitelist( source, mrenclave, ) => { println!("[+] Received RemovedFromWhitelist event"); println!(" Data source: {}", source); println!(" Currency: {:?}", mrenclave); }, _ => { trace!("Ignoring unsupported pallet_teeracle event"); }, } }, #[cfg(feature = "sidechain")] Event::Sidechain(re) => match &re { my_node_runtime::pallet_sidechain::Event::ProposedSidechainBlock( sender, payload, ) => { info!("[+] Received ProposedSidechainBlock event"); debug!(" From: {:?}", sender); debug!(" Payload: {:?}", hex::encode(payload)); }, _ => { trace!("Ignoring unsupported pallet_sidechain event"); }, }, _ => { trace!("Ignoring event {:?}", evr); }, } } } /// Subscribe to the node API finalized heads stream and trigger a parent chain sync /// upon receiving a new header. fn subscribe_to_parentchain_new_headers<E: EnclaveBase + Sidechain>( parentchain_handler: Arc<ParentchainHandler<ParentchainApi, E>>, mut last_synced_header: Header, ) -> Result<(), Error> { let (sender, receiver) = channel();
.subscribe_finalized_heads(sender) .map_err(Error::ApiClient)?; loop { let new_header: Header = match receiver.recv() { Ok(header_str) => serde_json::from_str(&header_str).map_err(Error::Serialization), Err(e) => Err(Error::ApiSubscriptionDisconnected(e)), }?; println!( "[+] Received finalized header update ({}), syncing parent chain...", new_header.number ); last_synced_header = parentchain_handler.sync_parentchain(last_synced_header)?; } } /// Get the public signing key of the TEE. fn enclave_account<E: EnclaveBase>(enclave_api: &E) -> AccountId32 { let tee_public = enclave_api.get_ecc_signing_pubkey().unwrap(); trace!("[+] Got ed25519 account of TEE = {}", tee_public.to_ss58check()); AccountId32::from(*tee_public.as_array_ref()) } /// Checks if we are the first validateer to register on the parentchain. fn we_are_primary_validateer( node_api: &ParentchainApi, register_enclave_xt_header: &Header, ) -> Result<bool, Error> { let enclave_count_of_previous_block = node_api.enclave_count(Some(*register_enclave_xt_header.parent_hash()))?; Ok(enclave_count_of_previous_block == 0) }
//TODO: this should be implemented by parentchain_handler directly, and not via // exposed parentchain_api. Blocked by https://github.com/scs/substrate-api-client/issues/267. parentchain_handler .parentchain_api()
random_line_split
main.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #![cfg_attr(test, feature(assert_matches))] #[cfg(feature = "teeracle")] use crate::teeracle::start_interval_market_update; use crate::{ account_funding::{setup_account_funding, EnclaveAccountInfoProvider}, error::Error, globals::tokio_handle::{GetTokioHandle, GlobalTokioHandle}, initialized_service::{ start_is_initialized_server, InitializationHandler, IsInitialized, TrackInitialization, }, ocall_bridge::{ bridge_api::Bridge as OCallBridge, component_factory::OCallBridgeComponentFactory, }, parentchain_handler::{HandleParentchain, ParentchainHandler}, prometheus_metrics::{start_metrics_server, EnclaveMetricsReceiver, MetricsHandler}, sidechain_setup::{sidechain_init_block_production, sidechain_start_untrusted_rpc_server}, sync_block_broadcaster::SyncBlockBroadcaster, utils::{check_files, extract_shard}, worker::Worker, worker_peers_updater::WorkerPeersUpdater, }; use base58::ToBase58; use clap::{load_yaml, App}; use codec::{Decode, Encode}; use config::Config; use enclave::{ api::enclave_init, tls_ra::{enclave_request_state_provisioning, enclave_run_state_provisioning_server}, }; use itp_enclave_api::{ direct_request::DirectRequest, enclave_base::EnclaveBase, remote_attestation::{RemoteAttestation, TlsRemoteAttestation}, sidechain::Sidechain, teeracle_api::TeeracleApi, Enclave, }; use itp_node_api::{ api_client::{AccountApi, PalletTeerexApi, ParentchainApi}, metadata::NodeMetadata, node_api_factory::{CreateNodeApi, NodeApiFactory}, }; use itp_settings::{ files::SIDECHAIN_STORAGE_PATH, worker_mode::{ProvideWorkerMode, WorkerMode, WorkerModeProvider}, }; use its_peer_fetch::{ block_fetch_client::BlockFetcher, untrusted_peer_fetch::UntrustedPeerFetcher, }; use its_primitives::types::block::SignedBlock as SignedSidechainBlock; use its_storage::{interface::FetchBlocks, BlockPruner, SidechainStorageLock}; use log::*; use my_node_runtime::{Event, Hash, Header}; use sgx_types::*; use sp_core::crypto::{AccountId32, Ss58Codec}; use sp_keyring::AccountKeyring; use std::{ path::PathBuf, str, sync::{ mpsc::{channel, Sender}, Arc, }, thread, time::Duration, }; use substrate_api_client::{utils::FromHexString, Header as HeaderTrait, XtStatus}; use teerex_primitives::ShardIdentifier; mod account_funding; mod config; mod enclave; mod error; mod globals; mod initialized_service; mod ocall_bridge; mod parentchain_handler; mod prometheus_metrics; mod setup; mod sidechain_setup; mod sync_block_broadcaster; mod sync_state; #[cfg(feature = "teeracle")] mod teeracle; mod tests; mod utils; mod worker; mod worker_peers_updater; const VERSION: &str = env!("CARGO_PKG_VERSION"); pub type EnclaveWorker = Worker<Config, NodeApiFactory, Enclave, InitializationHandler<WorkerModeProvider>>; fn main() { // Setup logging env_logger::init(); let yml = load_yaml!("cli.yml"); let matches = App::from_yaml(yml).get_matches(); let config = Config::from(&matches); GlobalTokioHandle::initialize(); // log this information, don't println because some python scripts for GA rely on the // stdout from the service #[cfg(feature = "production")] info!("*** Starting service in SGX production mode"); #[cfg(not(feature = "production"))] info!("*** Starting service in SGX debug mode"); info!("*** Running worker in mode: {:?} \n", WorkerModeProvider::worker_mode()); let clean_reset = matches.is_present("clean-reset"); if clean_reset { setup::purge_files_from_cwd().unwrap(); } // build the entire dependency tree let tokio_handle = Arc::new(GlobalTokioHandle {}); let sidechain_blockstorage = Arc::new( SidechainStorageLock::<SignedSidechainBlock>::new(PathBuf::from(&SIDECHAIN_STORAGE_PATH)) .unwrap(), ); let node_api_factory = Arc::new(NodeApiFactory::new(config.node_url(), AccountKeyring::Alice.pair())); let enclave = Arc::new(enclave_init(&config).unwrap()); let initialization_handler = Arc::new(InitializationHandler::default()); let worker = Arc::new(EnclaveWorker::new( config.clone(), enclave.clone(), node_api_factory.clone(), initialization_handler.clone(), Vec::new(), )); let sync_block_broadcaster = Arc::new(SyncBlockBroadcaster::new(tokio_handle.clone(), worker.clone())); let peer_updater = Arc::new(WorkerPeersUpdater::new(worker)); let untrusted_peer_fetcher = UntrustedPeerFetcher::new(node_api_factory.clone()); let peer_sidechain_block_fetcher = Arc::new(BlockFetcher::<SignedSidechainBlock, _>::new(untrusted_peer_fetcher)); let enclave_metrics_receiver = Arc::new(EnclaveMetricsReceiver {}); // initialize o-call bridge with a concrete factory implementation OCallBridge::initialize(Arc::new(OCallBridgeComponentFactory::new( node_api_factory.clone(), sync_block_broadcaster, enclave.clone(), sidechain_blockstorage.clone(), peer_updater, peer_sidechain_block_fetcher, tokio_handle.clone(), enclave_metrics_receiver, ))); if let Some(run_config) = &config.run_config { let shard = extract_shard(&run_config.shard, enclave.as_ref()); println!("Worker Config: {:?}", config); if clean_reset { setup::initialize_shard_and_keys(enclave.as_ref(), &shard).unwrap(); } let node_api = node_api_factory.create_api().expect("Failed to create parentchain node API"); if run_config.request_state { sync_state::sync_state::<_, _, WorkerModeProvider>( &node_api, &shard, enclave.as_ref(), run_config.skip_ra, ); } start_worker::<_, _, _, _, WorkerModeProvider>( config, &shard, enclave, sidechain_blockstorage, node_api, tokio_handle, initialization_handler, ); } else if let Some(smatches) = matches.subcommand_matches("request-state") { println!("*** Requesting state from a registered worker \n"); let node_api = node_api_factory.create_api().expect("Failed to create parentchain node API"); sync_state::sync_state::<_, _, WorkerModeProvider>( &node_api, &extract_shard(&smatches.value_of("shard").map(|s| s.to_string()), enclave.as_ref()), enclave.as_ref(), smatches.is_present("skip-ra"), ); } else if matches.is_present("shielding-key") { setup::generate_shielding_key_file(enclave.as_ref()); } else if matches.is_present("signing-key") { setup::generate_signing_key_file(enclave.as_ref()); } else if matches.is_present("dump-ra") { info!("*** Perform RA and dump cert to disk"); enclave.dump_ra_to_disk().unwrap(); } else if matches.is_present("mrenclave") { println!("{}", enclave.get_mrenclave().unwrap().encode().to_base58()); } else if let Some(sub_matches) = matches.subcommand_matches("init-shard") { setup::init_shard( enclave.as_ref(), &extract_shard(&sub_matches.value_of("shard").map(|s| s.to_string()), enclave.as_ref()), ); } else if let Some(sub_matches) = matches.subcommand_matches("test") { if sub_matches.is_present("provisioning-server") { println!("*** Running Enclave MU-RA TLS server\n"); enclave_run_state_provisioning_server( enclave.as_ref(), sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, &config.mu_ra_url(), sub_matches.is_present("skip-ra"), ); println!("[+] Done!"); } else if sub_matches.is_present("provisioning-client") { println!("*** Running Enclave MU-RA TLS client\n"); let shard = extract_shard( &sub_matches.value_of("shard").map(|s| s.to_string()), enclave.as_ref(), ); enclave_request_state_provisioning( enclave.as_ref(), sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, &config.mu_ra_url_external(), &shard, sub_matches.is_present("skip-ra"), ) .unwrap(); println!("[+] Done!"); } else { tests::run_enclave_tests(sub_matches); } } else { println!("For options: use --help"); } } /// FIXME: needs some discussion (restructuring?) #[allow(clippy::too_many_arguments)] fn start_worker<E, T, D, InitializationHandler, WorkerModeProvider>( config: Config, shard: &ShardIdentifier, enclave: Arc<E>, sidechain_storage: Arc<D>, node_api: ParentchainApi, tokio_handle_getter: Arc<T>, initialization_handler: Arc<InitializationHandler>, ) where T: GetTokioHandle, E: EnclaveBase + DirectRequest + Sidechain + RemoteAttestation + TlsRemoteAttestation + TeeracleApi + Clone, D: BlockPruner + FetchBlocks<SignedSidechainBlock> + Sync + Send +'static, InitializationHandler: TrackInitialization + IsInitialized + Sync + Send +'static, WorkerModeProvider: ProvideWorkerMode, { println!("Integritee Worker v{}", VERSION); info!("starting worker on shard {}", shard.encode().to_base58()); // ------------------------------------------------------------------------ // check for required files check_files(); // ------------------------------------------------------------------------ // initialize the enclave let mrenclave = enclave.get_mrenclave().unwrap(); println!("MRENCLAVE={}", mrenclave.to_base58()); println!("MRENCLAVE in hex {:?}", hex::encode(mrenclave)); // ------------------------------------------------------------------------ // let new workers call us for key provisioning println!("MU-RA server listening on {}", config.mu_ra_url()); let run_config = config.run_config.clone().expect("Run config missing"); let skip_ra = run_config.skip_ra; let is_development_mode = run_config.dev; let ra_url = config.mu_ra_url(); let enclave_api_key_prov = enclave.clone(); thread::spawn(move || { enclave_run_state_provisioning_server( enclave_api_key_prov.as_ref(), sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, &ra_url, skip_ra, ); info!("State provisioning server stopped."); }); let tokio_handle = tokio_handle_getter.get_handle(); #[cfg(feature = "teeracle")] let teeracle_tokio_handle = tokio_handle.clone(); // ------------------------------------------------------------------------ // Get the public key of our TEE. let tee_accountid = enclave_account(enclave.as_ref()); println!("Enclave account {:} ", &tee_accountid.to_ss58check()); // ------------------------------------------------------------------------ // Start `is_initialized` server. let untrusted_http_server_port = config .try_parse_untrusted_http_server_port() .expect("untrusted http server port to be a valid port number"); let initialization_handler_clone = initialization_handler.clone(); tokio_handle.spawn(async move { if let Err(e) = start_is_initialized_server(initialization_handler_clone, untrusted_http_server_port) .await { error!("Unexpected error in `is_initialized` server: {:?}", e); } }); // ------------------------------------------------------------------------ // Start prometheus metrics server. if config.enable_metrics_server { let enclave_wallet = Arc::new(EnclaveAccountInfoProvider::new(node_api.clone(), tee_accountid.clone())); let metrics_handler = Arc::new(MetricsHandler::new(enclave_wallet)); let metrics_server_port = config .try_parse_metrics_server_port() .expect("metrics server port to be a valid port number"); tokio_handle.spawn(async move { if let Err(e) = start_metrics_server(metrics_handler, metrics_server_port).await { error!("Unexpected error in Prometheus metrics server: {:?}", e); } }); } // ------------------------------------------------------------------------ // Start trusted worker rpc server if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain || WorkerModeProvider::worker_mode() == WorkerMode::OffChainWorker { let direct_invocation_server_addr = config.trusted_worker_url_internal(); let enclave_for_direct_invocation = enclave.clone(); thread::spawn(move || { println!( "[+] Trusted RPC direct invocation server listening on {}", direct_invocation_server_addr ); enclave_for_direct_invocation .init_direct_invocation_server(direct_invocation_server_addr) .unwrap(); println!("[+] RPC direct invocation server shut down"); }); } // ------------------------------------------------------------------------ // Start untrusted worker rpc server. // i.e move sidechain block importing to trusted worker. if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { sidechain_start_untrusted_rpc_server( &config, enclave.clone(), sidechain_storage.clone(), tokio_handle, ); } // ------------------------------------------------------------------------ // Init parentchain specific stuff. Needed for parentchain communication. let parentchain_handler = Arc::new(ParentchainHandler::new(node_api.clone(), enclave.clone())); let last_synced_header = parentchain_handler.init_parentchain_components().unwrap(); let nonce = node_api.get_nonce_of(&tee_accountid).unwrap(); info!("Enclave nonce = {:?}", nonce); enclave .set_nonce(nonce) .expect("Could not set nonce of enclave. Returning here..."); let metadata = node_api.metadata.clone(); let runtime_spec_version = node_api.runtime_version.spec_version; let runtime_transaction_version = node_api.runtime_version.transaction_version; enclave .set_node_metadata( NodeMetadata::new(metadata, runtime_spec_version, runtime_transaction_version).encode(), ) .expect("Could not set the node metadata in the enclave"); // ------------------------------------------------------------------------ // Perform a remote attestation and get an unchecked extrinsic back. let trusted_url = config.trusted_worker_url_external(); if skip_ra { println!( "[!] skipping remote attestation. Registering enclave without attestation report." ); } else { println!("[!] creating remote attestation report and create enclave register extrinsic."); }; let uxt = enclave.perform_ra(&trusted_url, skip_ra).unwrap(); let mut xthex = hex::encode(uxt); xthex.insert_str(0, "0x"); // Account funds if let Err(x) = setup_account_funding(&node_api, &tee_accountid, xthex.clone(), is_development_mode) { error!("Starting worker failed: {:?}", x); // Return without registering the enclave. This will fail and the transaction will be banned for 30min. return } println!("[>] Register the enclave (send the extrinsic)"); let register_enclave_xt_hash = node_api.send_extrinsic(xthex, XtStatus::Finalized).unwrap(); println!("[<] Extrinsic got finalized. Hash: {:?}\n", register_enclave_xt_hash); let register_enclave_xt_header = node_api.get_header(register_enclave_xt_hash).unwrap().unwrap(); let we_are_primary_validateer = we_are_primary_validateer(&node_api, &register_enclave_xt_header).unwrap(); if we_are_primary_validateer { println!("[+] We are the primary validateer"); } else { println!("[+] We are NOT the primary validateer"); } initialization_handler.registered_on_parentchain(); // ------------------------------------------------------------------------ // initialize teeracle interval #[cfg(feature = "teeracle")] if WorkerModeProvider::worker_mode() == WorkerMode::Teeracle { start_interval_market_update( &node_api, run_config.teeracle_update_interval, enclave.as_ref(), &teeracle_tokio_handle, ); } if WorkerModeProvider::worker_mode()!= WorkerMode::Teeracle { println!("*** [+] Finished syncing light client, syncing parentchain..."); // Syncing all parentchain blocks, this might take a while.. let mut last_synced_header = parentchain_handler.sync_parentchain(last_synced_header).unwrap(); // ------------------------------------------------------------------------ // Initialize the sidechain if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { last_synced_header = sidechain_init_block_production( enclave, &register_enclave_xt_header, we_are_primary_validateer, parentchain_handler.clone(), sidechain_storage, &last_synced_header, ) .unwrap(); } // ------------------------------------------------------------------------ // start parentchain syncing loop (subscribe to header updates) thread::Builder::new() .name("parentchain_sync_loop".to_owned()) .spawn(move || { if let Err(e) = subscribe_to_parentchain_new_headers(parentchain_handler, last_synced_header) { error!("Parentchain block syncing terminated with a failure: {:?}", e); } println!("[!] Parentchain block syncing has terminated"); }) .unwrap(); } // ------------------------------------------------------------------------ if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { spawn_worker_for_shard_polling(shard, node_api.clone(), initialization_handler); } // ------------------------------------------------------------------------ // subscribe to events and react on firing println!("*** Subscribing to events"); let (sender, receiver) = channel(); let sender2 = sender.clone(); let _eventsubscriber = thread::Builder::new() .name("eventsubscriber".to_owned()) .spawn(move || { node_api.subscribe_events(sender2).unwrap(); }) .unwrap(); println!("[+] Subscribed to events. waiting..."); let timeout = Duration::from_millis(10); loop { if let Ok(msg) = receiver.recv_timeout(timeout) { if let Ok(events) = parse_events(msg.clone()) { print_events(events, sender.clone()) } } } } /// Start polling loop to wait until we have a worker for a shard registered on /// the parentchain (TEEREX WorkerForShard). This is the pre-requisite to be /// considered initialized and ready for the next worker to start (in sidechain mode only). /// considered initialized and ready for the next worker to start. fn spawn_worker_for_shard_polling<InitializationHandler>( shard: &ShardIdentifier, node_api: ParentchainApi, initialization_handler: Arc<InitializationHandler>, ) where InitializationHandler: TrackInitialization + Sync + Send +'static, { let shard_for_initialized = *shard; thread::spawn(move || { const POLL_INTERVAL_SECS: u64 = 2; loop { info!("Polling for worker for shard ({} seconds interval)", POLL_INTERVAL_SECS); if let Ok(Some(_)) = node_api.worker_for_shard(&shard_for_initialized, None) { // Set that the service is initialized. initialization_handler.worker_for_shard_registered(); println!("[+] Found `WorkerForShard` on parentchain state"); break } thread::sleep(Duration::from_secs(POLL_INTERVAL_SECS)); } }); } type Events = Vec<frame_system::EventRecord<Event, Hash>>; fn parse_events(event: String) -> Result<Events, String> { let _unhex = Vec::from_hex(event).map_err(|_| "Decoding Events Failed".to_string())?; let mut _er_enc = _unhex.as_slice(); Events::decode(&mut _er_enc).map_err(|_| "Decoding Events Failed".to_string()) } fn print_events(events: Events, _sender: Sender<String>) { for evr in &events { debug!("Decoded: phase = {:?}, event = {:?}", evr.phase, evr.event); match &evr.event { Event::Balances(be) => { info!("[+] Received balances event"); debug!("{:?}", be); match &be { pallet_balances::Event::Transfer { from: transactor, to: dest, amount: value, } => { debug!(" Transactor: {:?}", transactor.to_ss58check()); debug!(" Destination: {:?}", dest.to_ss58check()); debug!(" Value: {:?}", value); }, _ => { trace!("Ignoring unsupported balances event"); }, } }, Event::Teerex(re) => { debug!("{:?}", re); match &re { my_node_runtime::pallet_teerex::Event::AddedEnclave(sender, worker_url) => { println!("[+] Received AddedEnclave event"); println!(" Sender (Worker): {:?}", sender); println!(" Registered URL: {:?}", str::from_utf8(worker_url).unwrap()); }, my_node_runtime::pallet_teerex::Event::Forwarded(shard) => { println!( "[+] Received trusted call for shard {}", shard.encode().to_base58() ); }, my_node_runtime::pallet_teerex::Event::ProcessedParentchainBlock( sender, block_hash, merkle_root, block_number, ) => { info!("[+] Received ProcessedParentchainBlock event"); debug!(" From: {:?}", sender); debug!(" Block Hash: {:?}", hex::encode(block_hash)); debug!(" Merkle Root: {:?}", hex::encode(merkle_root)); debug!(" Block Number: {:?}", block_number); }, my_node_runtime::pallet_teerex::Event::ShieldFunds(incognito_account) => { info!("[+] Received ShieldFunds event"); debug!(" For: {:?}", incognito_account); }, my_node_runtime::pallet_teerex::Event::UnshieldedFunds(incognito_account) => { info!("[+] Received UnshieldedFunds event"); debug!(" For: {:?}", incognito_account); }, _ => { trace!("Ignoring unsupported pallet_teerex event"); }, } }, #[cfg(feature = "teeracle")] Event::Teeracle(re) => { debug!("{:?}", re); match &re { my_node_runtime::pallet_teeracle::Event::ExchangeRateUpdated( source, currency, new_value, ) => { println!("[+] Received ExchangeRateUpdated event"); println!(" Data source: {}", source); println!(" Currency: {}", currency); println!(" Exchange rate: {:?}", new_value); }, my_node_runtime::pallet_teeracle::Event::ExchangeRateDeleted( source, currency, ) => { println!("[+] Received ExchangeRateDeleted event"); println!(" Data source: {}", source); println!(" Currency: {}", currency); }, my_node_runtime::pallet_teeracle::Event::AddedToWhitelist( source, mrenclave, ) => { println!("[+] Received AddedToWhitelist event"); println!(" Data source: {}", source); println!(" Currency: {:?}", mrenclave); }, my_node_runtime::pallet_teeracle::Event::RemovedFromWhitelist( source, mrenclave, ) => { println!("[+] Received RemovedFromWhitelist event"); println!(" Data source: {}", source); println!(" Currency: {:?}", mrenclave); }, _ => { trace!("Ignoring unsupported pallet_teeracle event"); }, } }, #[cfg(feature = "sidechain")] Event::Sidechain(re) => match &re { my_node_runtime::pallet_sidechain::Event::ProposedSidechainBlock( sender, payload, ) => { info!("[+] Received ProposedSidechainBlock event"); debug!(" From: {:?}", sender); debug!(" Payload: {:?}", hex::encode(payload)); }, _ => { trace!("Ignoring unsupported pallet_sidechain event"); }, }, _ => { trace!("Ignoring event {:?}", evr); }, } } } /// Subscribe to the node API finalized heads stream and trigger a parent chain sync /// upon receiving a new header. fn subscribe_to_parentchain_new_headers<E: EnclaveBase + Sidechain>( parentchain_handler: Arc<ParentchainHandler<ParentchainApi, E>>, mut last_synced_header: Header, ) -> Result<(), Error> { let (sender, receiver) = channel(); //TODO: this should be implemented by parentchain_handler directly, and not via // exposed parentchain_api. Blocked by https://github.com/scs/substrate-api-client/issues/267. parentchain_handler .parentchain_api() .subscribe_finalized_heads(sender) .map_err(Error::ApiClient)?; loop { let new_header: Header = match receiver.recv() { Ok(header_str) => serde_json::from_str(&header_str).map_err(Error::Serialization), Err(e) => Err(Error::ApiSubscriptionDisconnected(e)), }?; println!( "[+] Received finalized header update ({}), syncing parent chain...", new_header.number ); last_synced_header = parentchain_handler.sync_parentchain(last_synced_header)?; } } /// Get the public signing key of the TEE. fn enclave_account<E: EnclaveBase>(enclave_api: &E) -> AccountId32 { let tee_public = enclave_api.get_ecc_signing_pubkey().unwrap(); trace!("[+] Got ed25519 account of TEE = {}", tee_public.to_ss58check()); AccountId32::from(*tee_public.as_array_ref()) } /// Checks if we are the first validateer to register on the parentchain. fn
( node_api: &ParentchainApi, register_enclave_xt_header: &Header, ) -> Result<bool, Error> { let enclave_count_of_previous_block = node_api.enclave_count(Some(*register_enclave_xt_header.parent_hash()))?; Ok(enclave_count_of_previous_block == 0) }
we_are_primary_validateer
identifier_name
main.rs
/* Copyright 2021 Integritee AG and Supercomputing Systems AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #![cfg_attr(test, feature(assert_matches))] #[cfg(feature = "teeracle")] use crate::teeracle::start_interval_market_update; use crate::{ account_funding::{setup_account_funding, EnclaveAccountInfoProvider}, error::Error, globals::tokio_handle::{GetTokioHandle, GlobalTokioHandle}, initialized_service::{ start_is_initialized_server, InitializationHandler, IsInitialized, TrackInitialization, }, ocall_bridge::{ bridge_api::Bridge as OCallBridge, component_factory::OCallBridgeComponentFactory, }, parentchain_handler::{HandleParentchain, ParentchainHandler}, prometheus_metrics::{start_metrics_server, EnclaveMetricsReceiver, MetricsHandler}, sidechain_setup::{sidechain_init_block_production, sidechain_start_untrusted_rpc_server}, sync_block_broadcaster::SyncBlockBroadcaster, utils::{check_files, extract_shard}, worker::Worker, worker_peers_updater::WorkerPeersUpdater, }; use base58::ToBase58; use clap::{load_yaml, App}; use codec::{Decode, Encode}; use config::Config; use enclave::{ api::enclave_init, tls_ra::{enclave_request_state_provisioning, enclave_run_state_provisioning_server}, }; use itp_enclave_api::{ direct_request::DirectRequest, enclave_base::EnclaveBase, remote_attestation::{RemoteAttestation, TlsRemoteAttestation}, sidechain::Sidechain, teeracle_api::TeeracleApi, Enclave, }; use itp_node_api::{ api_client::{AccountApi, PalletTeerexApi, ParentchainApi}, metadata::NodeMetadata, node_api_factory::{CreateNodeApi, NodeApiFactory}, }; use itp_settings::{ files::SIDECHAIN_STORAGE_PATH, worker_mode::{ProvideWorkerMode, WorkerMode, WorkerModeProvider}, }; use its_peer_fetch::{ block_fetch_client::BlockFetcher, untrusted_peer_fetch::UntrustedPeerFetcher, }; use its_primitives::types::block::SignedBlock as SignedSidechainBlock; use its_storage::{interface::FetchBlocks, BlockPruner, SidechainStorageLock}; use log::*; use my_node_runtime::{Event, Hash, Header}; use sgx_types::*; use sp_core::crypto::{AccountId32, Ss58Codec}; use sp_keyring::AccountKeyring; use std::{ path::PathBuf, str, sync::{ mpsc::{channel, Sender}, Arc, }, thread, time::Duration, }; use substrate_api_client::{utils::FromHexString, Header as HeaderTrait, XtStatus}; use teerex_primitives::ShardIdentifier; mod account_funding; mod config; mod enclave; mod error; mod globals; mod initialized_service; mod ocall_bridge; mod parentchain_handler; mod prometheus_metrics; mod setup; mod sidechain_setup; mod sync_block_broadcaster; mod sync_state; #[cfg(feature = "teeracle")] mod teeracle; mod tests; mod utils; mod worker; mod worker_peers_updater; const VERSION: &str = env!("CARGO_PKG_VERSION"); pub type EnclaveWorker = Worker<Config, NodeApiFactory, Enclave, InitializationHandler<WorkerModeProvider>>; fn main() { // Setup logging env_logger::init(); let yml = load_yaml!("cli.yml"); let matches = App::from_yaml(yml).get_matches(); let config = Config::from(&matches); GlobalTokioHandle::initialize(); // log this information, don't println because some python scripts for GA rely on the // stdout from the service #[cfg(feature = "production")] info!("*** Starting service in SGX production mode"); #[cfg(not(feature = "production"))] info!("*** Starting service in SGX debug mode"); info!("*** Running worker in mode: {:?} \n", WorkerModeProvider::worker_mode()); let clean_reset = matches.is_present("clean-reset"); if clean_reset { setup::purge_files_from_cwd().unwrap(); } // build the entire dependency tree let tokio_handle = Arc::new(GlobalTokioHandle {}); let sidechain_blockstorage = Arc::new( SidechainStorageLock::<SignedSidechainBlock>::new(PathBuf::from(&SIDECHAIN_STORAGE_PATH)) .unwrap(), ); let node_api_factory = Arc::new(NodeApiFactory::new(config.node_url(), AccountKeyring::Alice.pair())); let enclave = Arc::new(enclave_init(&config).unwrap()); let initialization_handler = Arc::new(InitializationHandler::default()); let worker = Arc::new(EnclaveWorker::new( config.clone(), enclave.clone(), node_api_factory.clone(), initialization_handler.clone(), Vec::new(), )); let sync_block_broadcaster = Arc::new(SyncBlockBroadcaster::new(tokio_handle.clone(), worker.clone())); let peer_updater = Arc::new(WorkerPeersUpdater::new(worker)); let untrusted_peer_fetcher = UntrustedPeerFetcher::new(node_api_factory.clone()); let peer_sidechain_block_fetcher = Arc::new(BlockFetcher::<SignedSidechainBlock, _>::new(untrusted_peer_fetcher)); let enclave_metrics_receiver = Arc::new(EnclaveMetricsReceiver {}); // initialize o-call bridge with a concrete factory implementation OCallBridge::initialize(Arc::new(OCallBridgeComponentFactory::new( node_api_factory.clone(), sync_block_broadcaster, enclave.clone(), sidechain_blockstorage.clone(), peer_updater, peer_sidechain_block_fetcher, tokio_handle.clone(), enclave_metrics_receiver, ))); if let Some(run_config) = &config.run_config { let shard = extract_shard(&run_config.shard, enclave.as_ref()); println!("Worker Config: {:?}", config); if clean_reset { setup::initialize_shard_and_keys(enclave.as_ref(), &shard).unwrap(); } let node_api = node_api_factory.create_api().expect("Failed to create parentchain node API"); if run_config.request_state { sync_state::sync_state::<_, _, WorkerModeProvider>( &node_api, &shard, enclave.as_ref(), run_config.skip_ra, ); } start_worker::<_, _, _, _, WorkerModeProvider>( config, &shard, enclave, sidechain_blockstorage, node_api, tokio_handle, initialization_handler, ); } else if let Some(smatches) = matches.subcommand_matches("request-state") { println!("*** Requesting state from a registered worker \n"); let node_api = node_api_factory.create_api().expect("Failed to create parentchain node API"); sync_state::sync_state::<_, _, WorkerModeProvider>( &node_api, &extract_shard(&smatches.value_of("shard").map(|s| s.to_string()), enclave.as_ref()), enclave.as_ref(), smatches.is_present("skip-ra"), ); } else if matches.is_present("shielding-key") { setup::generate_shielding_key_file(enclave.as_ref()); } else if matches.is_present("signing-key") { setup::generate_signing_key_file(enclave.as_ref()); } else if matches.is_present("dump-ra") { info!("*** Perform RA and dump cert to disk"); enclave.dump_ra_to_disk().unwrap(); } else if matches.is_present("mrenclave") { println!("{}", enclave.get_mrenclave().unwrap().encode().to_base58()); } else if let Some(sub_matches) = matches.subcommand_matches("init-shard") { setup::init_shard( enclave.as_ref(), &extract_shard(&sub_matches.value_of("shard").map(|s| s.to_string()), enclave.as_ref()), ); } else if let Some(sub_matches) = matches.subcommand_matches("test") { if sub_matches.is_present("provisioning-server") { println!("*** Running Enclave MU-RA TLS server\n"); enclave_run_state_provisioning_server( enclave.as_ref(), sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, &config.mu_ra_url(), sub_matches.is_present("skip-ra"), ); println!("[+] Done!"); } else if sub_matches.is_present("provisioning-client") { println!("*** Running Enclave MU-RA TLS client\n"); let shard = extract_shard( &sub_matches.value_of("shard").map(|s| s.to_string()), enclave.as_ref(), ); enclave_request_state_provisioning( enclave.as_ref(), sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, &config.mu_ra_url_external(), &shard, sub_matches.is_present("skip-ra"), ) .unwrap(); println!("[+] Done!"); } else { tests::run_enclave_tests(sub_matches); } } else { println!("For options: use --help"); } } /// FIXME: needs some discussion (restructuring?) #[allow(clippy::too_many_arguments)] fn start_worker<E, T, D, InitializationHandler, WorkerModeProvider>( config: Config, shard: &ShardIdentifier, enclave: Arc<E>, sidechain_storage: Arc<D>, node_api: ParentchainApi, tokio_handle_getter: Arc<T>, initialization_handler: Arc<InitializationHandler>, ) where T: GetTokioHandle, E: EnclaveBase + DirectRequest + Sidechain + RemoteAttestation + TlsRemoteAttestation + TeeracleApi + Clone, D: BlockPruner + FetchBlocks<SignedSidechainBlock> + Sync + Send +'static, InitializationHandler: TrackInitialization + IsInitialized + Sync + Send +'static, WorkerModeProvider: ProvideWorkerMode, { println!("Integritee Worker v{}", VERSION); info!("starting worker on shard {}", shard.encode().to_base58()); // ------------------------------------------------------------------------ // check for required files check_files(); // ------------------------------------------------------------------------ // initialize the enclave let mrenclave = enclave.get_mrenclave().unwrap(); println!("MRENCLAVE={}", mrenclave.to_base58()); println!("MRENCLAVE in hex {:?}", hex::encode(mrenclave)); // ------------------------------------------------------------------------ // let new workers call us for key provisioning println!("MU-RA server listening on {}", config.mu_ra_url()); let run_config = config.run_config.clone().expect("Run config missing"); let skip_ra = run_config.skip_ra; let is_development_mode = run_config.dev; let ra_url = config.mu_ra_url(); let enclave_api_key_prov = enclave.clone(); thread::spawn(move || { enclave_run_state_provisioning_server( enclave_api_key_prov.as_ref(), sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, &ra_url, skip_ra, ); info!("State provisioning server stopped."); }); let tokio_handle = tokio_handle_getter.get_handle(); #[cfg(feature = "teeracle")] let teeracle_tokio_handle = tokio_handle.clone(); // ------------------------------------------------------------------------ // Get the public key of our TEE. let tee_accountid = enclave_account(enclave.as_ref()); println!("Enclave account {:} ", &tee_accountid.to_ss58check()); // ------------------------------------------------------------------------ // Start `is_initialized` server. let untrusted_http_server_port = config .try_parse_untrusted_http_server_port() .expect("untrusted http server port to be a valid port number"); let initialization_handler_clone = initialization_handler.clone(); tokio_handle.spawn(async move { if let Err(e) = start_is_initialized_server(initialization_handler_clone, untrusted_http_server_port) .await { error!("Unexpected error in `is_initialized` server: {:?}", e); } }); // ------------------------------------------------------------------------ // Start prometheus metrics server. if config.enable_metrics_server { let enclave_wallet = Arc::new(EnclaveAccountInfoProvider::new(node_api.clone(), tee_accountid.clone())); let metrics_handler = Arc::new(MetricsHandler::new(enclave_wallet)); let metrics_server_port = config .try_parse_metrics_server_port() .expect("metrics server port to be a valid port number"); tokio_handle.spawn(async move { if let Err(e) = start_metrics_server(metrics_handler, metrics_server_port).await { error!("Unexpected error in Prometheus metrics server: {:?}", e); } }); } // ------------------------------------------------------------------------ // Start trusted worker rpc server if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain || WorkerModeProvider::worker_mode() == WorkerMode::OffChainWorker { let direct_invocation_server_addr = config.trusted_worker_url_internal(); let enclave_for_direct_invocation = enclave.clone(); thread::spawn(move || { println!( "[+] Trusted RPC direct invocation server listening on {}", direct_invocation_server_addr ); enclave_for_direct_invocation .init_direct_invocation_server(direct_invocation_server_addr) .unwrap(); println!("[+] RPC direct invocation server shut down"); }); } // ------------------------------------------------------------------------ // Start untrusted worker rpc server. // i.e move sidechain block importing to trusted worker. if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { sidechain_start_untrusted_rpc_server( &config, enclave.clone(), sidechain_storage.clone(), tokio_handle, ); } // ------------------------------------------------------------------------ // Init parentchain specific stuff. Needed for parentchain communication. let parentchain_handler = Arc::new(ParentchainHandler::new(node_api.clone(), enclave.clone())); let last_synced_header = parentchain_handler.init_parentchain_components().unwrap(); let nonce = node_api.get_nonce_of(&tee_accountid).unwrap(); info!("Enclave nonce = {:?}", nonce); enclave .set_nonce(nonce) .expect("Could not set nonce of enclave. Returning here..."); let metadata = node_api.metadata.clone(); let runtime_spec_version = node_api.runtime_version.spec_version; let runtime_transaction_version = node_api.runtime_version.transaction_version; enclave .set_node_metadata( NodeMetadata::new(metadata, runtime_spec_version, runtime_transaction_version).encode(), ) .expect("Could not set the node metadata in the enclave"); // ------------------------------------------------------------------------ // Perform a remote attestation and get an unchecked extrinsic back. let trusted_url = config.trusted_worker_url_external(); if skip_ra { println!( "[!] skipping remote attestation. Registering enclave without attestation report." ); } else { println!("[!] creating remote attestation report and create enclave register extrinsic."); }; let uxt = enclave.perform_ra(&trusted_url, skip_ra).unwrap(); let mut xthex = hex::encode(uxt); xthex.insert_str(0, "0x"); // Account funds if let Err(x) = setup_account_funding(&node_api, &tee_accountid, xthex.clone(), is_development_mode) { error!("Starting worker failed: {:?}", x); // Return without registering the enclave. This will fail and the transaction will be banned for 30min. return } println!("[>] Register the enclave (send the extrinsic)"); let register_enclave_xt_hash = node_api.send_extrinsic(xthex, XtStatus::Finalized).unwrap(); println!("[<] Extrinsic got finalized. Hash: {:?}\n", register_enclave_xt_hash); let register_enclave_xt_header = node_api.get_header(register_enclave_xt_hash).unwrap().unwrap(); let we_are_primary_validateer = we_are_primary_validateer(&node_api, &register_enclave_xt_header).unwrap(); if we_are_primary_validateer { println!("[+] We are the primary validateer"); } else { println!("[+] We are NOT the primary validateer"); } initialization_handler.registered_on_parentchain(); // ------------------------------------------------------------------------ // initialize teeracle interval #[cfg(feature = "teeracle")] if WorkerModeProvider::worker_mode() == WorkerMode::Teeracle
if WorkerModeProvider::worker_mode()!= WorkerMode::Teeracle { println!("*** [+] Finished syncing light client, syncing parentchain..."); // Syncing all parentchain blocks, this might take a while.. let mut last_synced_header = parentchain_handler.sync_parentchain(last_synced_header).unwrap(); // ------------------------------------------------------------------------ // Initialize the sidechain if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { last_synced_header = sidechain_init_block_production( enclave, &register_enclave_xt_header, we_are_primary_validateer, parentchain_handler.clone(), sidechain_storage, &last_synced_header, ) .unwrap(); } // ------------------------------------------------------------------------ // start parentchain syncing loop (subscribe to header updates) thread::Builder::new() .name("parentchain_sync_loop".to_owned()) .spawn(move || { if let Err(e) = subscribe_to_parentchain_new_headers(parentchain_handler, last_synced_header) { error!("Parentchain block syncing terminated with a failure: {:?}", e); } println!("[!] Parentchain block syncing has terminated"); }) .unwrap(); } // ------------------------------------------------------------------------ if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { spawn_worker_for_shard_polling(shard, node_api.clone(), initialization_handler); } // ------------------------------------------------------------------------ // subscribe to events and react on firing println!("*** Subscribing to events"); let (sender, receiver) = channel(); let sender2 = sender.clone(); let _eventsubscriber = thread::Builder::new() .name("eventsubscriber".to_owned()) .spawn(move || { node_api.subscribe_events(sender2).unwrap(); }) .unwrap(); println!("[+] Subscribed to events. waiting..."); let timeout = Duration::from_millis(10); loop { if let Ok(msg) = receiver.recv_timeout(timeout) { if let Ok(events) = parse_events(msg.clone()) { print_events(events, sender.clone()) } } } } /// Start polling loop to wait until we have a worker for a shard registered on /// the parentchain (TEEREX WorkerForShard). This is the pre-requisite to be /// considered initialized and ready for the next worker to start (in sidechain mode only). /// considered initialized and ready for the next worker to start. fn spawn_worker_for_shard_polling<InitializationHandler>( shard: &ShardIdentifier, node_api: ParentchainApi, initialization_handler: Arc<InitializationHandler>, ) where InitializationHandler: TrackInitialization + Sync + Send +'static, { let shard_for_initialized = *shard; thread::spawn(move || { const POLL_INTERVAL_SECS: u64 = 2; loop { info!("Polling for worker for shard ({} seconds interval)", POLL_INTERVAL_SECS); if let Ok(Some(_)) = node_api.worker_for_shard(&shard_for_initialized, None) { // Set that the service is initialized. initialization_handler.worker_for_shard_registered(); println!("[+] Found `WorkerForShard` on parentchain state"); break } thread::sleep(Duration::from_secs(POLL_INTERVAL_SECS)); } }); } type Events = Vec<frame_system::EventRecord<Event, Hash>>; fn parse_events(event: String) -> Result<Events, String> { let _unhex = Vec::from_hex(event).map_err(|_| "Decoding Events Failed".to_string())?; let mut _er_enc = _unhex.as_slice(); Events::decode(&mut _er_enc).map_err(|_| "Decoding Events Failed".to_string()) } fn print_events(events: Events, _sender: Sender<String>) { for evr in &events { debug!("Decoded: phase = {:?}, event = {:?}", evr.phase, evr.event); match &evr.event { Event::Balances(be) => { info!("[+] Received balances event"); debug!("{:?}", be); match &be { pallet_balances::Event::Transfer { from: transactor, to: dest, amount: value, } => { debug!(" Transactor: {:?}", transactor.to_ss58check()); debug!(" Destination: {:?}", dest.to_ss58check()); debug!(" Value: {:?}", value); }, _ => { trace!("Ignoring unsupported balances event"); }, } }, Event::Teerex(re) => { debug!("{:?}", re); match &re { my_node_runtime::pallet_teerex::Event::AddedEnclave(sender, worker_url) => { println!("[+] Received AddedEnclave event"); println!(" Sender (Worker): {:?}", sender); println!(" Registered URL: {:?}", str::from_utf8(worker_url).unwrap()); }, my_node_runtime::pallet_teerex::Event::Forwarded(shard) => { println!( "[+] Received trusted call for shard {}", shard.encode().to_base58() ); }, my_node_runtime::pallet_teerex::Event::ProcessedParentchainBlock( sender, block_hash, merkle_root, block_number, ) => { info!("[+] Received ProcessedParentchainBlock event"); debug!(" From: {:?}", sender); debug!(" Block Hash: {:?}", hex::encode(block_hash)); debug!(" Merkle Root: {:?}", hex::encode(merkle_root)); debug!(" Block Number: {:?}", block_number); }, my_node_runtime::pallet_teerex::Event::ShieldFunds(incognito_account) => { info!("[+] Received ShieldFunds event"); debug!(" For: {:?}", incognito_account); }, my_node_runtime::pallet_teerex::Event::UnshieldedFunds(incognito_account) => { info!("[+] Received UnshieldedFunds event"); debug!(" For: {:?}", incognito_account); }, _ => { trace!("Ignoring unsupported pallet_teerex event"); }, } }, #[cfg(feature = "teeracle")] Event::Teeracle(re) => { debug!("{:?}", re); match &re { my_node_runtime::pallet_teeracle::Event::ExchangeRateUpdated( source, currency, new_value, ) => { println!("[+] Received ExchangeRateUpdated event"); println!(" Data source: {}", source); println!(" Currency: {}", currency); println!(" Exchange rate: {:?}", new_value); }, my_node_runtime::pallet_teeracle::Event::ExchangeRateDeleted( source, currency, ) => { println!("[+] Received ExchangeRateDeleted event"); println!(" Data source: {}", source); println!(" Currency: {}", currency); }, my_node_runtime::pallet_teeracle::Event::AddedToWhitelist( source, mrenclave, ) => { println!("[+] Received AddedToWhitelist event"); println!(" Data source: {}", source); println!(" Currency: {:?}", mrenclave); }, my_node_runtime::pallet_teeracle::Event::RemovedFromWhitelist( source, mrenclave, ) => { println!("[+] Received RemovedFromWhitelist event"); println!(" Data source: {}", source); println!(" Currency: {:?}", mrenclave); }, _ => { trace!("Ignoring unsupported pallet_teeracle event"); }, } }, #[cfg(feature = "sidechain")] Event::Sidechain(re) => match &re { my_node_runtime::pallet_sidechain::Event::ProposedSidechainBlock( sender, payload, ) => { info!("[+] Received ProposedSidechainBlock event"); debug!(" From: {:?}", sender); debug!(" Payload: {:?}", hex::encode(payload)); }, _ => { trace!("Ignoring unsupported pallet_sidechain event"); }, }, _ => { trace!("Ignoring event {:?}", evr); }, } } } /// Subscribe to the node API finalized heads stream and trigger a parent chain sync /// upon receiving a new header. fn subscribe_to_parentchain_new_headers<E: EnclaveBase + Sidechain>( parentchain_handler: Arc<ParentchainHandler<ParentchainApi, E>>, mut last_synced_header: Header, ) -> Result<(), Error> { let (sender, receiver) = channel(); //TODO: this should be implemented by parentchain_handler directly, and not via // exposed parentchain_api. Blocked by https://github.com/scs/substrate-api-client/issues/267. parentchain_handler .parentchain_api() .subscribe_finalized_heads(sender) .map_err(Error::ApiClient)?; loop { let new_header: Header = match receiver.recv() { Ok(header_str) => serde_json::from_str(&header_str).map_err(Error::Serialization), Err(e) => Err(Error::ApiSubscriptionDisconnected(e)), }?; println!( "[+] Received finalized header update ({}), syncing parent chain...", new_header.number ); last_synced_header = parentchain_handler.sync_parentchain(last_synced_header)?; } } /// Get the public signing key of the TEE. fn enclave_account<E: EnclaveBase>(enclave_api: &E) -> AccountId32 { let tee_public = enclave_api.get_ecc_signing_pubkey().unwrap(); trace!("[+] Got ed25519 account of TEE = {}", tee_public.to_ss58check()); AccountId32::from(*tee_public.as_array_ref()) } /// Checks if we are the first validateer to register on the parentchain. fn we_are_primary_validateer( node_api: &ParentchainApi, register_enclave_xt_header: &Header, ) -> Result<bool, Error> { let enclave_count_of_previous_block = node_api.enclave_count(Some(*register_enclave_xt_header.parent_hash()))?; Ok(enclave_count_of_previous_block == 0) }
{ start_interval_market_update( &node_api, run_config.teeracle_update_interval, enclave.as_ref(), &teeracle_tokio_handle, ); }
conditional_block
material.rs
use std::ops::{Add, Div, Mul, Sub}; use crate::color::Color; use crate::hittable::HitRecord; use crate::ray::Ray; use crate::rtweekend; use crate::vec::Vec3; /// Generic material trait. pub trait Material<T: Copy> { /// Scatter an incoming light ray on a material. /// /// Returns a scattered ray and the attenuation color if there is reflection. /// Otherwise, none is returned. /// /// * `ray` - Incoming light ray. /// * `rec` - Previous hit record of the ray on some object. fn scatter(&self, ray: &Ray<T>, rec: &HitRecord<T>) -> Option<(Ray<T>, Color)>; } /// Lambertian (diffuse) material. /// /// In our diffuse reflection model, a lambertian material will always both scatter and attenuate /// by its own reflectance (albedo). /// /// Should only be used for smooth matte surfaces, not rough matte ones. /// See https://www.cs.cmu.edu/afs/cs/academic/class/15462-f09/www/lec/lec8.pdf for explanation. pub struct Lambertian { /// Color of the object. albedo: Color, } impl Lambertian { /// Create a new diffuse material from a given intrinsic object color. pub fn new(albedo: Color) -> Self { Lambertian { albedo } } } impl Material<f64> for Lambertian { fn scatter(&self, _ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // Diffuse reflection: True Lambertian reflection. // We aim for a Lambertian distribution of the reflected rays, which has a distribution of // cos(phi) instead of cos³(phi) for random vectors inside the unit sphere. // To achieve this, we pick a random point on the surface of the unit sphere, which is done // by picking a random point inside the sphere and then normalizing that point. let random_unit_vec = rtweekend::random_vec_in_unit_sphere().normalized(); // Diffuse reflection: send out a new ray from the hit position point pointing towards a // random point on the surface of the sphere tangent to that hit point. // Possible problem: the recursion depth may be too deep, so we blow up the stack. Avoid // this by limiting the number of child rays. let scatter_direction = rec.normal + random_unit_vec; let scatter = Ray::new(rec.point, scatter_direction); Some((scatter, self.albedo)) } } /// Metal (specular) material. /// /// For smooth metal surfaces, light is not randomly scattered. Instead, the angle of the incident /// ray is equal to that of the specular outgoing ray. /// /// V N ^ ^ /// \ ^ / | /// \ | / | B /// v|/ | /// S ------------x------------ /// \ | /// \ | B /// v | /// /// The elements of the figure are: /// * S: Metal surface /// * V: Incident ray /// * N: Surface normal
/// /// In our current design, N is a unit vector, but the same does not have to be true for V. /// Furthermore, V points inwards, so the sign has to be changed. /// All this is encoded in the reflect() function. pub struct Metal { /// Color of the object. albedo: Color, /// Fuziness of the specular reflections. fuzz: f64, } impl Metal { /// Create a new metallic material from a given intrinsic object color. /// /// * `albedo`: Intrinsic surface color. /// * `fuzz`: Fuzziness factor for specular reflection in the range [0.0, 1.0]. pub fn new(albedo: Color, fuzz: f64) -> Self { Metal { albedo, fuzz: rtweekend::clamp(fuzz, 0.0, 1.0), } } /// Returns the reflected ray. /// /// This basically just encodes the V + B + B term for the specular reflection. We flip the /// sign and simplify the term so it becomes V - 2B. pub fn reflect<T: Copy>(ray: &Vec3<T>, normal: &Vec3<T>) -> Vec3<T> where T: Add<Output = T> + Div<Output = T> + Mul<Output = T> + Mul<f64, Output = T> + Sub<Output = T> + From<f64> + Into<f64>, { let b = *normal * Vec3::dot(ray, normal); *ray - b * T::from(2.0) } } impl Material<f64> for Metal { fn scatter(&self, ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // specular reflection let direction = Metal::reflect(&ray.direction().normalized(), &rec.normal); // apply fuzzing let direction = direction + rtweekend::random_vec_in_unit_sphere() * self.fuzz; let scatter = Ray::new(rec.point, direction); if Vec3::dot(&scatter.direction(), &rec.normal) <= 0.0 { None } else { Some((scatter, self.albedo)) } } } /// Clear (dielectrics) material. /// /// Examples of dielectric materials are water, glass or diamond. /// When such a material it hit by a light ray, the ray is split into a reflected and a refracted /// (transmitted) ray. /// /// Refraction for dielectrics is described by Snell's law: /// /// η⋅sinθ = η′⋅sinθ′ /// /// where /// * θ/θ′: angles from the surface normal /// * η/η′: refractive indices (e.g. 1.0 for air, 1.3-1.7 for glass) /// /// R N /// \ ^ /// \ | /// η v| /// S ------------x------------ /// η′ |\ /// | \ /// | \ /// v v /// N´ R´ /// /// In the illustration above, R is the incident ray and N is the surface normal. θ is thus the /// angle between R and N, while θ′ is the angle between N´ and R´. In the illustration, the angles /// θ and θ′ are exactly the same, so the ray R would pass from air (η = 1.0) through air /// (η′ = 1.0). /// /// To calculate the angle θ′, we solve for sinθ′: /// /// sinθ′ = (η / η′)⋅sinθ /// /// We split R´ into two parts: one that is perpendicular to N´ and one that is parallel to N´: /// /// R´ = R′⊥ + R′∥ /// /// Solving for those parts yields: /// /// R′⊥ = (η / η′)⋅(R + cosθ⋅n) /// R′∥ = - sqrt(1 - |R′⊥|²)⋅n /// /// The next step is solving for cosθ. The dot product of two vectors can be expressed in terms of /// the cosine of the angle between them: /// /// a⋅b = |a||b| cosθ /// /// or, assuming unit vectors: /// /// a⋅b = cosθ /// /// Thus, we can rewrite R′⊥ as: /// /// R′⊥ = (η / η′)⋅(R + (-R⋅n)n) /// /// Sometimes, the refraction ratio η / η′ is too high (e.g. when a ray passes through glass and /// enters air), so a real solution to Snell's law does not exist. An example: /// /// sinθ′ = (η / η′)⋅sinθ /// /// given η = 1.5 (glass) and η´ = 1.0 (air): /// /// sinθ′ = (1.5 / 1.0)⋅sinθ /// /// Since sinθ′ can at maximum be 1.0, sinθ must at maximum be (1.0 / 1.5), otherwise the equation /// can no longer be satisfied. We can solve for sinθ using the following: /// /// sinθ = sqrt(1 - cos²θ) /// cosθ = R⋅n /// /// which yields: /// /// sinθ = sqrt(1 - (R⋅n)²) /// /// In case of sinθ > (1.0 / refraction ratio), we cannot refract and thus must reflect. This is /// called "total internal reflection". pub struct Dielectric { /// Refraction index. refraction: f64, } impl Dielectric { /// Create a new metallic material from a given intrinsic object color. /// /// * `refraction`: Refraction index. pub fn new(refraction: f64) -> Self { Dielectric { refraction } } /// Returns the refracted (trasmitted) ray. /// /// Based on Snell's law. /// /// * `ray`: Incident ray. /// * `normal`: Surface normal (in eta direction). /// * `refraction_ratio`: Refractive ratio (η over η´). pub fn refract(ray: &Vec3<f64>, normal: &Vec3<f64>, refraction_ratio: f64) -> Vec3<f64> { // the part of the refracted ray which is perpendicular to R´ let mut cos_theta = Vec3::dot(&(-(*ray)), normal); if cos_theta > 1.0 { cos_theta = 1.0; } let perpendicular = (*ray + *normal * cos_theta) * refraction_ratio; // the part that is parallel to R´ let parallel = *normal * (-((1.0 - perpendicular.length_squared()).abs()).sqrt()); perpendicular + parallel } /// Returns the reflectance on a dielectric surface at a given angle. /// /// Based on the polynomial approximation by Christophe Schlick. /// /// * `angle` - Angle of incoming ray. /// * `refraction_ratio`: - Refractive ratio (η over η´). pub fn reflectance(angle: f64, refraction_ratio: f64) -> f64 { let r0 = (1.0 - refraction_ratio) / (1.0 + refraction_ratio); let r0 = r0 * r0; r0 + (1.0 - r0) * (1.0 - angle).powf(5.0) } } impl Material<f64> for Dielectric { fn scatter(&self, ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // assume the material where the ray originates from is air let eta = 1.0; let eta_prime = self.refraction; let refraction_ratio = if rec.front_face { eta / eta_prime } else { eta_prime }; // Total internal reflection: if // // (η / η′)⋅sinθ > 1.0 // // we must not refract (and have to reflect) instead! let r = ray.direction().normalized(); // cosθ = R⋅n let mut cos_theta = Vec3::dot(&(-r), &rec.normal); if cos_theta > 1.0 { cos_theta = 1.0; } // sinθ = sqrt(1 - cos²θ) let sin_theta = (1.0 - cos_theta * cos_theta).sqrt(); // Snell's law let can_refract = refraction_ratio * sin_theta <= 1.0; // Schlick approximation let can_refract = can_refract && (Dielectric::reflectance(cos_theta, refraction_ratio)) < rtweekend::random(0.0..1.0); // direction of the scattered ray let direction = if!can_refract { // must reflect Metal::reflect(&r, &rec.normal) } else { // can refract Dielectric::refract(&r, &rec.normal, refraction_ratio) }; let scatter = Ray::new(rec.point, direction); // attenuation is always 1 since air/glass/diamond do not absorb let attenuation = Color::new3(1.0, 1.0, 1.0); Some((scatter, attenuation)) } }
/// /// Additionally, B is an additional vector for illustration purposes. /// The reflected ray (in between N and B) has the same angle as the incident ray V with regards to // the surface. It can be computed as V + B + B.
random_line_split
material.rs
use std::ops::{Add, Div, Mul, Sub}; use crate::color::Color; use crate::hittable::HitRecord; use crate::ray::Ray; use crate::rtweekend; use crate::vec::Vec3; /// Generic material trait. pub trait Material<T: Copy> { /// Scatter an incoming light ray on a material. /// /// Returns a scattered ray and the attenuation color if there is reflection. /// Otherwise, none is returned. /// /// * `ray` - Incoming light ray. /// * `rec` - Previous hit record of the ray on some object. fn scatter(&self, ray: &Ray<T>, rec: &HitRecord<T>) -> Option<(Ray<T>, Color)>; } /// Lambertian (diffuse) material. /// /// In our diffuse reflection model, a lambertian material will always both scatter and attenuate /// by its own reflectance (albedo). /// /// Should only be used for smooth matte surfaces, not rough matte ones. /// See https://www.cs.cmu.edu/afs/cs/academic/class/15462-f09/www/lec/lec8.pdf for explanation. pub struct Lambertian { /// Color of the object. albedo: Color, } impl Lambertian { /// Create a new diffuse material from a given intrinsic object color. pub fn new(albedo: Color) -> Self { Lambertian { albedo } } } impl Material<f64> for Lambertian { fn scatter(&self, _ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // Diffuse reflection: True Lambertian reflection. // We aim for a Lambertian distribution of the reflected rays, which has a distribution of // cos(phi) instead of cos³(phi) for random vectors inside the unit sphere. // To achieve this, we pick a random point on the surface of the unit sphere, which is done // by picking a random point inside the sphere and then normalizing that point. let random_unit_vec = rtweekend::random_vec_in_unit_sphere().normalized(); // Diffuse reflection: send out a new ray from the hit position point pointing towards a // random point on the surface of the sphere tangent to that hit point. // Possible problem: the recursion depth may be too deep, so we blow up the stack. Avoid // this by limiting the number of child rays. let scatter_direction = rec.normal + random_unit_vec; let scatter = Ray::new(rec.point, scatter_direction); Some((scatter, self.albedo)) } } /// Metal (specular) material. /// /// For smooth metal surfaces, light is not randomly scattered. Instead, the angle of the incident /// ray is equal to that of the specular outgoing ray. /// /// V N ^ ^ /// \ ^ / | /// \ | / | B /// v|/ | /// S ------------x------------ /// \ | /// \ | B /// v | /// /// The elements of the figure are: /// * S: Metal surface /// * V: Incident ray /// * N: Surface normal /// /// Additionally, B is an additional vector for illustration purposes. /// The reflected ray (in between N and B) has the same angle as the incident ray V with regards to // the surface. It can be computed as V + B + B. /// /// In our current design, N is a unit vector, but the same does not have to be true for V. /// Furthermore, V points inwards, so the sign has to be changed. /// All this is encoded in the reflect() function. pub struct Metal { /// Color of the object. albedo: Color, /// Fuziness of the specular reflections. fuzz: f64, } impl Metal { /// Create a new metallic material from a given intrinsic object color. /// /// * `albedo`: Intrinsic surface color. /// * `fuzz`: Fuzziness factor for specular reflection in the range [0.0, 1.0]. pub fn new(albedo: Color, fuzz: f64) -> Self { Metal { albedo, fuzz: rtweekend::clamp(fuzz, 0.0, 1.0), } } /// Returns the reflected ray. /// /// This basically just encodes the V + B + B term for the specular reflection. We flip the /// sign and simplify the term so it becomes V - 2B. pub fn reflect<T: Copy>(ray: &Vec3<T>, normal: &Vec3<T>) -> Vec3<T> where T: Add<Output = T> + Div<Output = T> + Mul<Output = T> + Mul<f64, Output = T> + Sub<Output = T> + From<f64> + Into<f64>, { let b = *normal * Vec3::dot(ray, normal); *ray - b * T::from(2.0) } } impl Material<f64> for Metal { fn scatter(&self, ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // specular reflection let direction = Metal::reflect(&ray.direction().normalized(), &rec.normal); // apply fuzzing let direction = direction + rtweekend::random_vec_in_unit_sphere() * self.fuzz; let scatter = Ray::new(rec.point, direction); if Vec3::dot(&scatter.direction(), &rec.normal) <= 0.0 { None } else { Some((scatter, self.albedo)) } } } /// Clear (dielectrics) material. /// /// Examples of dielectric materials are water, glass or diamond. /// When such a material it hit by a light ray, the ray is split into a reflected and a refracted /// (transmitted) ray. /// /// Refraction for dielectrics is described by Snell's law: /// /// η⋅sinθ = η′⋅sinθ′ /// /// where /// * θ/θ′: angles from the surface normal /// * η/η′: refractive indices (e.g. 1.0 for air, 1.3-1.7 for glass) /// /// R N /// \ ^ /// \ | /// η v| /// S ------------x------------ /// η′ |\ /// | \ /// | \ /// v v /// N´ R´ /// /// In the illustration above, R is the incident ray and N is the surface normal. θ is thus the /// angle between R and N, while θ′ is the angle between N´ and R´. In the illustration, the angles /// θ and θ′ are exactly the same, so the ray R would pass from air (η = 1.0) through air /// (η′ = 1.0). /// /// To calculate the angle θ′, we solve for sinθ′: /// /// sinθ′ = (η / η′)⋅sinθ /// /// We split R´ into two parts: one that is perpendicular to N´ and one that is parallel to N´: /// /// R´ = R′⊥ + R′∥ /// /// Solving for those parts yields: /// /// R′⊥ = (η / η′)⋅(R + cosθ⋅n) /// R′∥ = - sqrt(1 - |R′⊥|²)⋅n /// /// The next step is solving for cosθ. The dot product of two vectors can be expressed in terms of /// the cosine of the angle between them: /// /// a⋅b = |a||b| cosθ /// /// or, assuming unit vectors: /// /// a⋅b = cosθ /// /// Thus, we can rewrite R′⊥ as: /// /// R′⊥ = (η / η′)⋅(R + (-R⋅n)n) /// /// Sometimes, the refraction ratio η / η′ is too high (e.g. when a ray passes through glass and /// enters air), so a real solution to Snell's law does not exist. An example: /// /// sinθ′ = (η / η′)⋅sinθ /// /// given η = 1.5 (glass) and η´ = 1.0 (air): /// /// sinθ′ = (1.5 / 1.0)⋅sinθ /// /// Since sinθ′ can at maximum be 1.0, sinθ must at maximum be (1.0 / 1.5), otherwise the equation /// can no longer be satisfied. We can solve for sinθ using the following: /// /// sinθ = sqrt(1 - cos²θ) /// cosθ = R⋅n /// /// which yields: /// /// sinθ = sqrt(1 - (R⋅n)²) /// /// In case of sinθ > (1.0 / refraction ratio), we cannot refract and thus must reflect. This is /// called "total internal reflection". pub struct Dielectric { /// Refraction index. refraction: f64, } impl Dielectric { /// Create a new metallic material from a given intrinsic object color. /// /// * `refraction`: Refraction index. pub fn new(refraction: f64) -> Self { Dielectric { refraction } } /// Returns the refracted (trasmitted) ray. /// /// Based on Snell's law. /// /// * `ray`: Incident ray. /// * `normal`: Surface normal (in eta direction). /// * `refraction_ratio`: Refractive ratio (η over η´). pub fn refract(ray: &Vec3<f64>, normal: &Vec3<f64>, refraction_ratio: f64) -> Vec3<f64> { // the part of the refracted ray which is perpendicular to R´ let mut cos_theta = Vec3::dot(&(-(*ray)), normal); if cos_theta > 1.0 { cos_theta = 1.0; } let perpendicular = (*ray + *normal * cos_theta) * refraction_ratio; // the part that is parallel to R´ let parallel = *normal * (-((1.0 - perpendicular.length_squared()).abs()).sqrt()); perpendicular + parallel } /// Returns the reflectance on a dielectric surface at a given angle. /// /// Based on the polynomial approximation by Christophe Schlick. /// /// * `angle` - Angle of incoming ray. /// * `refraction_ratio`: - Refractive ratio (η over η´). pub fn reflectance(angle: f64, refraction_ratio: f64) -> f64 { let r0 = (1.0 - refraction_ratio) / (1.0 + refraction_ratio); let r0 = r0 * r0; r0 + (1.0 - r0) * (1.0 - angle).powf(5.0) } } impl Material<f64> for Dielectric { fn scatter(&self, ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // assume the material where the ray originates from is air let eta = 1.0; let eta_prime = self.refraction; let refraction_ratio = if rec.front_face { eta / eta_prime } else { eta_prime }; // Total internal reflection: if // // (η / η′)⋅sinθ > 1.0 // // we must not refract (
let r = ray.direction().normalized(); // cosθ = R⋅n let mut cos_theta = Vec3::dot(&(-r), &rec.normal); if cos_theta > 1.0 { cos_theta = 1.0; } // sinθ = sqrt(1 - cos²θ) let sin_theta = (1.0 - cos_theta * cos_theta).sqrt(); // Snell's law let can_refract = refraction_ratio * sin_theta <= 1.0; // Schlick approximation let can_refract = can_refract && (Dielectric::reflectance(cos_theta, refraction_ratio)) < rtweekend::random(0.0..1.0); // direction of the scattered ray let direction = if!can_refract { // must reflect Metal::reflect(&r, &rec.normal) } else { // can refract Dielectric::refract(&r, &rec.normal, refraction_ratio) }; let scatter = Ray::new(rec.point, direction); // attenuation is always 1 since air/glass/diamond do not absorb let attenuation = Color::new3(1.0, 1.0, 1.0); Some((scatter, attenuation)) } }
and have to reflect) instead!
conditional_block
material.rs
use std::ops::{Add, Div, Mul, Sub}; use crate::color::Color; use crate::hittable::HitRecord; use crate::ray::Ray; use crate::rtweekend; use crate::vec::Vec3; /// Generic material trait. pub trait Material<T: Copy> { /// Scatter an incoming light ray on a material. /// /// Returns a scattered ray and the attenuation color if there is reflection. /// Otherwise, none is returned. /// /// * `ray` - Incoming light ray. /// * `rec` - Previous hit record of the ray on some object. fn scatter(&self, ray: &Ray<T>, rec: &HitRecord<T>) -> Option<(Ray<T>, Color)>; } /// Lambertian (diffuse) material. /// /// In our diffuse reflection model, a lambertian material will always both scatter and attenuate /// by its own reflectance (albedo). /// /// Should only be used for smooth matte surfaces, not rough matte ones. /// See https://www.cs.cmu.edu/afs/cs/academic/class/15462-f09/www/lec/lec8.pdf for explanation. pub struct Lambertian { /// Color of the object. albedo: Color, } impl Lambertian { /// Create a new diffuse material from a given intrinsic object color. pub fn new(albedo: Color) -> Self
} impl Material<f64> for Lambertian { fn scatter(&self, _ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // Diffuse reflection: True Lambertian reflection. // We aim for a Lambertian distribution of the reflected rays, which has a distribution of // cos(phi) instead of cos³(phi) for random vectors inside the unit sphere. // To achieve this, we pick a random point on the surface of the unit sphere, which is done // by picking a random point inside the sphere and then normalizing that point. let random_unit_vec = rtweekend::random_vec_in_unit_sphere().normalized(); // Diffuse reflection: send out a new ray from the hit position point pointing towards a // random point on the surface of the sphere tangent to that hit point. // Possible problem: the recursion depth may be too deep, so we blow up the stack. Avoid // this by limiting the number of child rays. let scatter_direction = rec.normal + random_unit_vec; let scatter = Ray::new(rec.point, scatter_direction); Some((scatter, self.albedo)) } } /// Metal (specular) material. /// /// For smooth metal surfaces, light is not randomly scattered. Instead, the angle of the incident /// ray is equal to that of the specular outgoing ray. /// /// V N ^ ^ /// \ ^ / | /// \ | / | B /// v|/ | /// S ------------x------------ /// \ | /// \ | B /// v | /// /// The elements of the figure are: /// * S: Metal surface /// * V: Incident ray /// * N: Surface normal /// /// Additionally, B is an additional vector for illustration purposes. /// The reflected ray (in between N and B) has the same angle as the incident ray V with regards to // the surface. It can be computed as V + B + B. /// /// In our current design, N is a unit vector, but the same does not have to be true for V. /// Furthermore, V points inwards, so the sign has to be changed. /// All this is encoded in the reflect() function. pub struct Metal { /// Color of the object. albedo: Color, /// Fuziness of the specular reflections. fuzz: f64, } impl Metal { /// Create a new metallic material from a given intrinsic object color. /// /// * `albedo`: Intrinsic surface color. /// * `fuzz`: Fuzziness factor for specular reflection in the range [0.0, 1.0]. pub fn new(albedo: Color, fuzz: f64) -> Self { Metal { albedo, fuzz: rtweekend::clamp(fuzz, 0.0, 1.0), } } /// Returns the reflected ray. /// /// This basically just encodes the V + B + B term for the specular reflection. We flip the /// sign and simplify the term so it becomes V - 2B. pub fn reflect<T: Copy>(ray: &Vec3<T>, normal: &Vec3<T>) -> Vec3<T> where T: Add<Output = T> + Div<Output = T> + Mul<Output = T> + Mul<f64, Output = T> + Sub<Output = T> + From<f64> + Into<f64>, { let b = *normal * Vec3::dot(ray, normal); *ray - b * T::from(2.0) } } impl Material<f64> for Metal { fn scatter(&self, ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // specular reflection let direction = Metal::reflect(&ray.direction().normalized(), &rec.normal); // apply fuzzing let direction = direction + rtweekend::random_vec_in_unit_sphere() * self.fuzz; let scatter = Ray::new(rec.point, direction); if Vec3::dot(&scatter.direction(), &rec.normal) <= 0.0 { None } else { Some((scatter, self.albedo)) } } } /// Clear (dielectrics) material. /// /// Examples of dielectric materials are water, glass or diamond. /// When such a material it hit by a light ray, the ray is split into a reflected and a refracted /// (transmitted) ray. /// /// Refraction for dielectrics is described by Snell's law: /// /// η⋅sinθ = η′⋅sinθ′ /// /// where /// * θ/θ′: angles from the surface normal /// * η/η′: refractive indices (e.g. 1.0 for air, 1.3-1.7 for glass) /// /// R N /// \ ^ /// \ | /// η v| /// S ------------x------------ /// η′ |\ /// | \ /// | \ /// v v /// N´ R´ /// /// In the illustration above, R is the incident ray and N is the surface normal. θ is thus the /// angle between R and N, while θ′ is the angle between N´ and R´. In the illustration, the angles /// θ and θ′ are exactly the same, so the ray R would pass from air (η = 1.0) through air /// (η′ = 1.0). /// /// To calculate the angle θ′, we solve for sinθ′: /// /// sinθ′ = (η / η′)⋅sinθ /// /// We split R´ into two parts: one that is perpendicular to N´ and one that is parallel to N´: /// /// R´ = R′⊥ + R′∥ /// /// Solving for those parts yields: /// /// R′⊥ = (η / η′)⋅(R + cosθ⋅n) /// R′∥ = - sqrt(1 - |R′⊥|²)⋅n /// /// The next step is solving for cosθ. The dot product of two vectors can be expressed in terms of /// the cosine of the angle between them: /// /// a⋅b = |a||b| cosθ /// /// or, assuming unit vectors: /// /// a⋅b = cosθ /// /// Thus, we can rewrite R′⊥ as: /// /// R′⊥ = (η / η′)⋅(R + (-R⋅n)n) /// /// Sometimes, the refraction ratio η / η′ is too high (e.g. when a ray passes through glass and /// enters air), so a real solution to Snell's law does not exist. An example: /// /// sinθ′ = (η / η′)⋅sinθ /// /// given η = 1.5 (glass) and η´ = 1.0 (air): /// /// sinθ′ = (1.5 / 1.0)⋅sinθ /// /// Since sinθ′ can at maximum be 1.0, sinθ must at maximum be (1.0 / 1.5), otherwise the equation /// can no longer be satisfied. We can solve for sinθ using the following: /// /// sinθ = sqrt(1 - cos²θ) /// cosθ = R⋅n /// /// which yields: /// /// sinθ = sqrt(1 - (R⋅n)²) /// /// In case of sinθ > (1.0 / refraction ratio), we cannot refract and thus must reflect. This is /// called "total internal reflection". pub struct Dielectric { /// Refraction index. refraction: f64, } impl Dielectric { /// Create a new metallic material from a given intrinsic object color. /// /// * `refraction`: Refraction index. pub fn new(refraction: f64) -> Self { Dielectric { refraction } } /// Returns the refracted (trasmitted) ray. /// /// Based on Snell's law. /// /// * `ray`: Incident ray. /// * `normal`: Surface normal (in eta direction). /// * `refraction_ratio`: Refractive ratio (η over η´). pub fn refract(ray: &Vec3<f64>, normal: &Vec3<f64>, refraction_ratio: f64) -> Vec3<f64> { // the part of the refracted ray which is perpendicular to R´ let mut cos_theta = Vec3::dot(&(-(*ray)), normal); if cos_theta > 1.0 { cos_theta = 1.0; } let perpendicular = (*ray + *normal * cos_theta) * refraction_ratio; // the part that is parallel to R´ let parallel = *normal * (-((1.0 - perpendicular.length_squared()).abs()).sqrt()); perpendicular + parallel } /// Returns the reflectance on a dielectric surface at a given angle. /// /// Based on the polynomial approximation by Christophe Schlick. /// /// * `angle` - Angle of incoming ray. /// * `refraction_ratio`: - Refractive ratio (η over η´). pub fn reflectance(angle: f64, refraction_ratio: f64) -> f64 { let r0 = (1.0 - refraction_ratio) / (1.0 + refraction_ratio); let r0 = r0 * r0; r0 + (1.0 - r0) * (1.0 - angle).powf(5.0) } } impl Material<f64> for Dielectric { fn scatter(&self, ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // assume the material where the ray originates from is air let eta = 1.0; let eta_prime = self.refraction; let refraction_ratio = if rec.front_face { eta / eta_prime } else { eta_prime }; // Total internal reflection: if // // (η / η′)⋅sinθ > 1.0 // // we must not refract (and have to reflect) instead! let r = ray.direction().normalized(); // cosθ = R⋅n let mut cos_theta = Vec3::dot(&(-r), &rec.normal); if cos_theta > 1.0 { cos_theta = 1.0; } // sinθ = sqrt(1 - cos²θ) let sin_theta = (1.0 - cos_theta * cos_theta).sqrt(); // Snell's law let can_refract = refraction_ratio * sin_theta <= 1.0; // Schlick approximation let can_refract = can_refract && (Dielectric::reflectance(cos_theta, refraction_ratio)) < rtweekend::random(0.0..1.0); // direction of the scattered ray let direction = if!can_refract { // must reflect Metal::reflect(&r, &rec.normal) } else { // can refract Dielectric::refract(&r, &rec.normal, refraction_ratio) }; let scatter = Ray::new(rec.point, direction); // attenuation is always 1 since air/glass/diamond do not absorb let attenuation = Color::new3(1.0, 1.0, 1.0); Some((scatter, attenuation)) } }
{ Lambertian { albedo } }
identifier_body
material.rs
use std::ops::{Add, Div, Mul, Sub}; use crate::color::Color; use crate::hittable::HitRecord; use crate::ray::Ray; use crate::rtweekend; use crate::vec::Vec3; /// Generic material trait. pub trait Material<T: Copy> { /// Scatter an incoming light ray on a material. /// /// Returns a scattered ray and the attenuation color if there is reflection. /// Otherwise, none is returned. /// /// * `ray` - Incoming light ray. /// * `rec` - Previous hit record of the ray on some object. fn scatter(&self, ray: &Ray<T>, rec: &HitRecord<T>) -> Option<(Ray<T>, Color)>; } /// Lambertian (diffuse) material. /// /// In our diffuse reflection model, a lambertian material will always both scatter and attenuate /// by its own reflectance (albedo). /// /// Should only be used for smooth matte surfaces, not rough matte ones. /// See https://www.cs.cmu.edu/afs/cs/academic/class/15462-f09/www/lec/lec8.pdf for explanation. pub struct Lambertian { /// Color of the object. albedo: Color, } impl Lambertian { /// Create a new diffuse material from a given intrinsic object color. pub fn new(albedo: Color) -> Self { Lambertian { albedo } } } impl Material<f64> for Lambertian { fn scatter(&self, _ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // Diffuse reflection: True Lambertian reflection. // We aim for a Lambertian distribution of the reflected rays, which has a distribution of // cos(phi) instead of cos³(phi) for random vectors inside the unit sphere. // To achieve this, we pick a random point on the surface of the unit sphere, which is done // by picking a random point inside the sphere and then normalizing that point. let random_unit_vec = rtweekend::random_vec_in_unit_sphere().normalized(); // Diffuse reflection: send out a new ray from the hit position point pointing towards a // random point on the surface of the sphere tangent to that hit point. // Possible problem: the recursion depth may be too deep, so we blow up the stack. Avoid // this by limiting the number of child rays. let scatter_direction = rec.normal + random_unit_vec; let scatter = Ray::new(rec.point, scatter_direction); Some((scatter, self.albedo)) } } /// Metal (specular) material. /// /// For smooth metal surfaces, light is not randomly scattered. Instead, the angle of the incident /// ray is equal to that of the specular outgoing ray. /// /// V N ^ ^ /// \ ^ / | /// \ | / | B /// v|/ | /// S ------------x------------ /// \ | /// \ | B /// v | /// /// The elements of the figure are: /// * S: Metal surface /// * V: Incident ray /// * N: Surface normal /// /// Additionally, B is an additional vector for illustration purposes. /// The reflected ray (in between N and B) has the same angle as the incident ray V with regards to // the surface. It can be computed as V + B + B. /// /// In our current design, N is a unit vector, but the same does not have to be true for V. /// Furthermore, V points inwards, so the sign has to be changed. /// All this is encoded in the reflect() function. pub struct M
{ /// Color of the object. albedo: Color, /// Fuziness of the specular reflections. fuzz: f64, } impl Metal { /// Create a new metallic material from a given intrinsic object color. /// /// * `albedo`: Intrinsic surface color. /// * `fuzz`: Fuzziness factor for specular reflection in the range [0.0, 1.0]. pub fn new(albedo: Color, fuzz: f64) -> Self { Metal { albedo, fuzz: rtweekend::clamp(fuzz, 0.0, 1.0), } } /// Returns the reflected ray. /// /// This basically just encodes the V + B + B term for the specular reflection. We flip the /// sign and simplify the term so it becomes V - 2B. pub fn reflect<T: Copy>(ray: &Vec3<T>, normal: &Vec3<T>) -> Vec3<T> where T: Add<Output = T> + Div<Output = T> + Mul<Output = T> + Mul<f64, Output = T> + Sub<Output = T> + From<f64> + Into<f64>, { let b = *normal * Vec3::dot(ray, normal); *ray - b * T::from(2.0) } } impl Material<f64> for Metal { fn scatter(&self, ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // specular reflection let direction = Metal::reflect(&ray.direction().normalized(), &rec.normal); // apply fuzzing let direction = direction + rtweekend::random_vec_in_unit_sphere() * self.fuzz; let scatter = Ray::new(rec.point, direction); if Vec3::dot(&scatter.direction(), &rec.normal) <= 0.0 { None } else { Some((scatter, self.albedo)) } } } /// Clear (dielectrics) material. /// /// Examples of dielectric materials are water, glass or diamond. /// When such a material it hit by a light ray, the ray is split into a reflected and a refracted /// (transmitted) ray. /// /// Refraction for dielectrics is described by Snell's law: /// /// η⋅sinθ = η′⋅sinθ′ /// /// where /// * θ/θ′: angles from the surface normal /// * η/η′: refractive indices (e.g. 1.0 for air, 1.3-1.7 for glass) /// /// R N /// \ ^ /// \ | /// η v| /// S ------------x------------ /// η′ |\ /// | \ /// | \ /// v v /// N´ R´ /// /// In the illustration above, R is the incident ray and N is the surface normal. θ is thus the /// angle between R and N, while θ′ is the angle between N´ and R´. In the illustration, the angles /// θ and θ′ are exactly the same, so the ray R would pass from air (η = 1.0) through air /// (η′ = 1.0). /// /// To calculate the angle θ′, we solve for sinθ′: /// /// sinθ′ = (η / η′)⋅sinθ /// /// We split R´ into two parts: one that is perpendicular to N´ and one that is parallel to N´: /// /// R´ = R′⊥ + R′∥ /// /// Solving for those parts yields: /// /// R′⊥ = (η / η′)⋅(R + cosθ⋅n) /// R′∥ = - sqrt(1 - |R′⊥|²)⋅n /// /// The next step is solving for cosθ. The dot product of two vectors can be expressed in terms of /// the cosine of the angle between them: /// /// a⋅b = |a||b| cosθ /// /// or, assuming unit vectors: /// /// a⋅b = cosθ /// /// Thus, we can rewrite R′⊥ as: /// /// R′⊥ = (η / η′)⋅(R + (-R⋅n)n) /// /// Sometimes, the refraction ratio η / η′ is too high (e.g. when a ray passes through glass and /// enters air), so a real solution to Snell's law does not exist. An example: /// /// sinθ′ = (η / η′)⋅sinθ /// /// given η = 1.5 (glass) and η´ = 1.0 (air): /// /// sinθ′ = (1.5 / 1.0)⋅sinθ /// /// Since sinθ′ can at maximum be 1.0, sinθ must at maximum be (1.0 / 1.5), otherwise the equation /// can no longer be satisfied. We can solve for sinθ using the following: /// /// sinθ = sqrt(1 - cos²θ) /// cosθ = R⋅n /// /// which yields: /// /// sinθ = sqrt(1 - (R⋅n)²) /// /// In case of sinθ > (1.0 / refraction ratio), we cannot refract and thus must reflect. This is /// called "total internal reflection". pub struct Dielectric { /// Refraction index. refraction: f64, } impl Dielectric { /// Create a new metallic material from a given intrinsic object color. /// /// * `refraction`: Refraction index. pub fn new(refraction: f64) -> Self { Dielectric { refraction } } /// Returns the refracted (trasmitted) ray. /// /// Based on Snell's law. /// /// * `ray`: Incident ray. /// * `normal`: Surface normal (in eta direction). /// * `refraction_ratio`: Refractive ratio (η over η´). pub fn refract(ray: &Vec3<f64>, normal: &Vec3<f64>, refraction_ratio: f64) -> Vec3<f64> { // the part of the refracted ray which is perpendicular to R´ let mut cos_theta = Vec3::dot(&(-(*ray)), normal); if cos_theta > 1.0 { cos_theta = 1.0; } let perpendicular = (*ray + *normal * cos_theta) * refraction_ratio; // the part that is parallel to R´ let parallel = *normal * (-((1.0 - perpendicular.length_squared()).abs()).sqrt()); perpendicular + parallel } /// Returns the reflectance on a dielectric surface at a given angle. /// /// Based on the polynomial approximation by Christophe Schlick. /// /// * `angle` - Angle of incoming ray. /// * `refraction_ratio`: - Refractive ratio (η over η´). pub fn reflectance(angle: f64, refraction_ratio: f64) -> f64 { let r0 = (1.0 - refraction_ratio) / (1.0 + refraction_ratio); let r0 = r0 * r0; r0 + (1.0 - r0) * (1.0 - angle).powf(5.0) } } impl Material<f64> for Dielectric { fn scatter(&self, ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // assume the material where the ray originates from is air let eta = 1.0; let eta_prime = self.refraction; let refraction_ratio = if rec.front_face { eta / eta_prime } else { eta_prime }; // Total internal reflection: if // // (η / η′)⋅sinθ > 1.0 // // we must not refract (and have to reflect) instead! let r = ray.direction().normalized(); // cosθ = R⋅n let mut cos_theta = Vec3::dot(&(-r), &rec.normal); if cos_theta > 1.0 { cos_theta = 1.0; } // sinθ = sqrt(1 - cos²θ) let sin_theta = (1.0 - cos_theta * cos_theta).sqrt(); // Snell's law let can_refract = refraction_ratio * sin_theta <= 1.0; // Schlick approximation let can_refract = can_refract && (Dielectric::reflectance(cos_theta, refraction_ratio)) < rtweekend::random(0.0..1.0); // direction of the scattered ray let direction = if!can_refract { // must reflect Metal::reflect(&r, &rec.normal) } else { // can refract Dielectric::refract(&r, &rec.normal, refraction_ratio) }; let scatter = Ray::new(rec.point, direction); // attenuation is always 1 since air/glass/diamond do not absorb let attenuation = Color::new3(1.0, 1.0, 1.0); Some((scatter, attenuation)) } }
etal
identifier_name
actions.rs
use crate::cards::CardInstance; use crate::game::{Game, PlayerActionState, PlayerActiveInteraction, Time, UPDATE_DURATION}; use crate::geometry::{ Facing, FloatingVector, FloatingVectorExtension, GridVector, GridVectorExtension, Rotation, TILE_RADIUS, TILE_SIZE, TILE_WIDTH, }; use crate::mechanisms::{BuildMechanism, Conveyor, ConveyorSide, Mechanism, MechanismType}; use crate::ui_glue::Draw; use guard::guard; use ordered_float::OrderedFloat; use rand::prelude::*; use serde::{Deserialize, Serialize}; use std::fmt::Debug; pub enum ActionStatus { StillGoing, Completed, } pub struct ActionUpdateContext<'a> { pub game: &'a mut Game, } impl<'a> ActionUpdateContext<'a> { pub fn interaction_state(&self) -> &PlayerActiveInteraction { match &self.game.player.action_state { PlayerActionState::Interacting(i) => i, _ => unreachable!(), } } pub fn this_card(&self) -> &CardInstance { self.game.cards.selected().unwrap() } pub fn this_card_mut(&mut self) -> &mut CardInstance { self.game.cards.selected_mut().unwrap() } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub enum Cost { Fixed(i32), Variable, None, } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct ActionDisplayInfo { pub name: String, pub health_cost: Cost, pub time_cost: Cost, pub rules_text: String, pub flavor_text: String, } impl Default for ActionDisplayInfo { fn default() -> Self { ActionDisplayInfo { name: "".to_string(), health_cost: Cost::None, time_cost: Cost::Fixed(2), rules_text: "".to_string(), flavor_text: "".to_string(), } } } #[allow(unused)] pub trait ActionTrait { /** Perform a single time-step update on this action, possibly modifying the game state. Note that the action is removed from `game` before doing this, so that both mutable references can be held at the same time, so the action still stored in `game` is temporarily invalid. */ fn update(&mut self, context: ActionUpdateContext) -> ActionStatus; fn display_info(&self) -> ActionDisplayInfo; fn possible(&self, game: &Game) -> bool { true } fn draw_progress(&self, game: &Game, draw: &mut dyn Draw); fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) {} } trait_enum! { #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub enum Action: ActionTrait { SimpleAction, } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct SimpleAction { display_info: ActionDisplayInfo, is_card: bool, simple_action_type: SimpleActionType, progress: Time, cancel_progress: Time, } #[allow(unused)] pub trait SimpleActionTrait { fn finish(&self, context: ActionUpdateContext); fn possible(&self, game: &Game) -> bool { true } fn draw_progress(&self, game: &Game, draw: &mut dyn Draw) {} fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) {} } trait_enum! { #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub enum SimpleActionType: SimpleActionTrait { Reshuffle, BuildConveyor, BuildMechanism, } } fn smootherstep(a: f64, b: f64, x: f64) -> f64 { let x = ((x - a) / (b - a)).clamp(0.0, 1.0); x * x * x * (x * (x * 6.0 - 15.0) + 10.0) } impl SimpleAction { pub fn new( time_cost: i32, health_cost: Option<i32>, name: &str, rules_text: &str, flavor_text: &str, is_card: bool, simple_action_type: SimpleActionType, ) -> SimpleAction { SimpleAction { display_info: ActionDisplayInfo { name: name.to_string(), health_cost: match health_cost { Some(c) => Cost::Fixed(c), None => Cost::None, }, time_cost: Cost::Fixed(time_cost), rules_text: rules_text.to_string(), flavor_text: flavor_text.to_string(), }, is_card, simple_action_type, progress: 0.0, cancel_progress: 0.0, } } fn time_cost(&self) -> f64 { match self.display_info.time_cost { Cost::Fixed(cost) => cost as f64, _ => panic!(), } } fn health_cost(&self) -> f64 { match self.display_info.health_cost { Cost::Fixed(cost) => cost as f64, Cost::None => 0.0, _ => panic!(), } } fn cooldown_time(&self) -> f64 { self.time_cost() * 0.25 } fn startup_time(&self) -> f64 { self.time_cost() * 0.25 } fn finish_time(&self) -> f64 { self.time_cost() - self.cooldown_time() } fn finished(&self) -> bool { self.progress > self.finish_time() } fn health_to_pay_by(&self, progress: f64) -> f64 { smootherstep(self.startup_time(), self.finish_time(), progress) * self.health_cost() } } impl ActionTrait for SimpleAction { fn update(&mut self, context: ActionUpdateContext) -> ActionStatus { let simple_action_type = self.simple_action_type.clone(); let canceled = context.interaction_state().canceled &&!self.finished(); if canceled { self.cancel_progress += UPDATE_DURATION; } else { let was_finished = self.finished(); let health_paid_already = self.health_to_pay_by(self.progress); self.progress += UPDATE_DURATION; let health_payment = self.health_to_pay_by(self.progress) - health_paid_already; context.game.player.health -= health_payment; if self.finished() > was_finished { if self.is_card { match context.game.cards.selected_index { Some(index) => { if index + 1 == context.game.cards.deck.len() { context.game.cards.selected_index = None; } else { context.game.cards.selected_index = Some(index + 1); } } _ => unreachable!(), } } self.simple_action_type.finish(context); } } if self.progress > self.time_cost() || self.cancel_progress > self.cooldown_time() { ActionStatus::Completed } else { ActionStatus::StillGoing } } fn display_info(&self) -> ActionDisplayInfo { self.display_info.clone() } fn possible(&self, game: &Game) -> bool { self.simple_action_type.possible(game) } fn draw_progress(&self, game: &Game, draw: &mut dyn Draw) { self.simple_action_type.draw_progress(game, draw); let a = game.player.position + FloatingVector::new(-TILE_RADIUS as f64 * 0.5, 0.0); draw.rectangle_on_map( 70, a, FloatingVector::new(TILE_RADIUS as f64 * 0.25, TILE_WIDTH as f64), "#000", ); draw.rectangle_on_map( 71, a, FloatingVector::new( TILE_RADIUS as f64 * 0.25, TILE_WIDTH as f64 * self.progress / self.time_cost(), ), "#ff0", ); } fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) { self.simple_action_type.draw_preview(game, draw); } } impl SimpleActionTrait for BuildMechanism { fn finish(&self, context: ActionUpdateContext) { context.game.create_mechanism( context.game.player.position.containing_tile(), self.mechanism(context.game), ); } fn possible(&self, game: &Game) -> bool { let position = game.player.position.containing_tile(); game.grid.get(position).is_some() && game.mechanism(position).is_none() } fn draw_preview(&self, game: &Game, draw: &mut dyn Draw)
} #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct BuildConveyor { pub allow_splitting: bool, } #[derive(Copy, Clone, PartialEq, Serialize, Deserialize, Debug)] struct BuildConveyorCandidate { position: GridVector, input_side: Facing, } impl BuildConveyorCandidate { fn input_position(&self) -> GridVector { self.position + self.input_side.unit_vector() * TILE_WIDTH } fn output_side(&self) -> Facing { self.input_side + Rotation::U_TURN } } impl BuildConveyor { fn candidate_valid( game: &Game, candidate: BuildConveyorCandidate, allow_splitting: bool, ) -> bool { if game.grid.get(candidate.position).is_none() { return false; }; let output_mechanism = game.mechanism(candidate.position); //debug!("{:?}", (candidate, input_mechanism, output_mechanism)); guard!(let Some(input_mechanism) = game.mechanism(candidate.input_position()) else { return false }); if!input_mechanism .mechanism_type .can_be_material_source(candidate.output_side()) { return false; } if!allow_splitting { if matches!(&input_mechanism.mechanism_type, MechanismType::Conveyor(conveyor) if conveyor.sides.iter().filter(|&&side| side == ConveyorSide::Output).count() > 0) { return false; } } if let Some(output_mechanism) = output_mechanism { guard!(let Mechanism { mechanism_type: MechanismType::Conveyor(conveyor),.. } = output_mechanism else { return false }); if conveyor.sides[candidate.input_side.as_index()]!= ConveyorSide::Disconnected { return false; } } true } /// the returned facing is the input side of the new conveyor fn current_target(game: &Game, allow_splitting: bool) -> Option<BuildConveyorCandidate> { let player_position = game.player.position.containing_tile(); let player_offset = game.player.position - player_position.to_floating(); let mut candidates = Vec::new(); let mut consider = |candidate, score| { if Self::candidate_valid(game, candidate, allow_splitting) { candidates.push((candidate, score)) } }; for facing in Facing::ALL_FACINGS { consider( BuildConveyorCandidate { position: player_position, input_side: facing, }, (player_offset - facing.unit_vector().to_floating()).magnitude_squared(), ); consider( BuildConveyorCandidate { position: player_position - facing.unit_vector() * TILE_WIDTH, input_side: facing, }, (player_offset - -facing.unit_vector().to_floating()).magnitude_squared(), ); } candidates .into_iter() .min_by_key(|&(_, score)| OrderedFloat(score)) .map(|(c, _)| c) } } impl SimpleActionTrait for BuildConveyor { fn finish(&self, context: ActionUpdateContext) { let candidate = Self::current_target(context.game, self.allow_splitting).unwrap(); let mut sides = [ConveyorSide::Disconnected; 4]; sides[candidate.input_side.as_index()] = ConveyorSide::Input; context.game.create_mechanism( candidate.position, Mechanism { mechanism_type: MechanismType::Conveyor(Conveyor { sides, last_sent: Facing::from_index(0), }), }, ); context .game .mutate_mechanism(candidate.input_position(), |mechanism| { if let Mechanism { mechanism_type: MechanismType::Conveyor(Conveyor { sides,.. }), .. } = mechanism { sides[candidate.output_side().as_index()] = ConveyorSide::Output; } }); } fn possible(&self, game: &Game) -> bool { Self::current_target(game, self.allow_splitting).is_some() } fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) { if let Some(candidate) = Self::current_target(game, self.allow_splitting) { draw.rectangle_on_map( 5, candidate.position.to_floating(), TILE_SIZE.to_floating(), "#666", ); draw.rectangle_on_map( 5, candidate.input_position().to_floating(), TILE_SIZE.to_floating(), "#555", ); } else { draw.rectangle_on_map( 5, game.player.position.containing_tile().to_floating(), TILE_SIZE.to_floating(), "#555", ); } } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct Reshuffle; impl SimpleActionTrait for Reshuffle { fn finish(&self, context: ActionUpdateContext) { let cards = &mut context.game.cards; cards.deck.shuffle(&mut rand::thread_rng()); cards.selected_index = Some(0); } }
{ draw.rectangle_on_map( 5, game.player.position.containing_tile().to_floating(), TILE_SIZE.to_floating(), "#666", ); }
identifier_body
actions.rs
use crate::cards::CardInstance; use crate::game::{Game, PlayerActionState, PlayerActiveInteraction, Time, UPDATE_DURATION}; use crate::geometry::{ Facing, FloatingVector, FloatingVectorExtension, GridVector, GridVectorExtension, Rotation, TILE_RADIUS, TILE_SIZE, TILE_WIDTH, }; use crate::mechanisms::{BuildMechanism, Conveyor, ConveyorSide, Mechanism, MechanismType}; use crate::ui_glue::Draw; use guard::guard; use ordered_float::OrderedFloat; use rand::prelude::*; use serde::{Deserialize, Serialize}; use std::fmt::Debug; pub enum ActionStatus { StillGoing, Completed, } pub struct ActionUpdateContext<'a> { pub game: &'a mut Game, } impl<'a> ActionUpdateContext<'a> { pub fn interaction_state(&self) -> &PlayerActiveInteraction { match &self.game.player.action_state { PlayerActionState::Interacting(i) => i, _ => unreachable!(), } } pub fn this_card(&self) -> &CardInstance { self.game.cards.selected().unwrap() } pub fn this_card_mut(&mut self) -> &mut CardInstance { self.game.cards.selected_mut().unwrap() } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub enum Cost { Fixed(i32), Variable, None, } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct ActionDisplayInfo { pub name: String, pub health_cost: Cost, pub time_cost: Cost, pub rules_text: String, pub flavor_text: String, } impl Default for ActionDisplayInfo { fn default() -> Self { ActionDisplayInfo { name: "".to_string(), health_cost: Cost::None, time_cost: Cost::Fixed(2), rules_text: "".to_string(), flavor_text: "".to_string(), } } } #[allow(unused)] pub trait ActionTrait { /** Perform a single time-step update on this action, possibly modifying the game state. Note that the action is removed from `game` before doing this, so that both mutable references can be held at the same time, so the action still stored in `game` is temporarily invalid. */ fn update(&mut self, context: ActionUpdateContext) -> ActionStatus; fn display_info(&self) -> ActionDisplayInfo; fn possible(&self, game: &Game) -> bool { true } fn draw_progress(&self, game: &Game, draw: &mut dyn Draw); fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) {} } trait_enum! { #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub enum Action: ActionTrait { SimpleAction, } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct SimpleAction { display_info: ActionDisplayInfo, is_card: bool, simple_action_type: SimpleActionType, progress: Time, cancel_progress: Time, } #[allow(unused)] pub trait SimpleActionTrait { fn finish(&self, context: ActionUpdateContext); fn possible(&self, game: &Game) -> bool { true } fn draw_progress(&self, game: &Game, draw: &mut dyn Draw) {} fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) {} } trait_enum! { #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub enum SimpleActionType: SimpleActionTrait { Reshuffle, BuildConveyor, BuildMechanism, } } fn smootherstep(a: f64, b: f64, x: f64) -> f64 { let x = ((x - a) / (b - a)).clamp(0.0, 1.0); x * x * x * (x * (x * 6.0 - 15.0) + 10.0) } impl SimpleAction { pub fn new( time_cost: i32, health_cost: Option<i32>, name: &str, rules_text: &str, flavor_text: &str, is_card: bool, simple_action_type: SimpleActionType, ) -> SimpleAction { SimpleAction { display_info: ActionDisplayInfo { name: name.to_string(), health_cost: match health_cost { Some(c) => Cost::Fixed(c), None => Cost::None, }, time_cost: Cost::Fixed(time_cost), rules_text: rules_text.to_string(), flavor_text: flavor_text.to_string(), }, is_card, simple_action_type, progress: 0.0, cancel_progress: 0.0, } } fn time_cost(&self) -> f64 { match self.display_info.time_cost { Cost::Fixed(cost) => cost as f64, _ => panic!(), } } fn health_cost(&self) -> f64 { match self.display_info.health_cost { Cost::Fixed(cost) => cost as f64, Cost::None => 0.0, _ => panic!(), } } fn cooldown_time(&self) -> f64 { self.time_cost() * 0.25 } fn startup_time(&self) -> f64 { self.time_cost() * 0.25 } fn finish_time(&self) -> f64 { self.time_cost() - self.cooldown_time() } fn
(&self) -> bool { self.progress > self.finish_time() } fn health_to_pay_by(&self, progress: f64) -> f64 { smootherstep(self.startup_time(), self.finish_time(), progress) * self.health_cost() } } impl ActionTrait for SimpleAction { fn update(&mut self, context: ActionUpdateContext) -> ActionStatus { let simple_action_type = self.simple_action_type.clone(); let canceled = context.interaction_state().canceled &&!self.finished(); if canceled { self.cancel_progress += UPDATE_DURATION; } else { let was_finished = self.finished(); let health_paid_already = self.health_to_pay_by(self.progress); self.progress += UPDATE_DURATION; let health_payment = self.health_to_pay_by(self.progress) - health_paid_already; context.game.player.health -= health_payment; if self.finished() > was_finished { if self.is_card { match context.game.cards.selected_index { Some(index) => { if index + 1 == context.game.cards.deck.len() { context.game.cards.selected_index = None; } else { context.game.cards.selected_index = Some(index + 1); } } _ => unreachable!(), } } self.simple_action_type.finish(context); } } if self.progress > self.time_cost() || self.cancel_progress > self.cooldown_time() { ActionStatus::Completed } else { ActionStatus::StillGoing } } fn display_info(&self) -> ActionDisplayInfo { self.display_info.clone() } fn possible(&self, game: &Game) -> bool { self.simple_action_type.possible(game) } fn draw_progress(&self, game: &Game, draw: &mut dyn Draw) { self.simple_action_type.draw_progress(game, draw); let a = game.player.position + FloatingVector::new(-TILE_RADIUS as f64 * 0.5, 0.0); draw.rectangle_on_map( 70, a, FloatingVector::new(TILE_RADIUS as f64 * 0.25, TILE_WIDTH as f64), "#000", ); draw.rectangle_on_map( 71, a, FloatingVector::new( TILE_RADIUS as f64 * 0.25, TILE_WIDTH as f64 * self.progress / self.time_cost(), ), "#ff0", ); } fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) { self.simple_action_type.draw_preview(game, draw); } } impl SimpleActionTrait for BuildMechanism { fn finish(&self, context: ActionUpdateContext) { context.game.create_mechanism( context.game.player.position.containing_tile(), self.mechanism(context.game), ); } fn possible(&self, game: &Game) -> bool { let position = game.player.position.containing_tile(); game.grid.get(position).is_some() && game.mechanism(position).is_none() } fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) { draw.rectangle_on_map( 5, game.player.position.containing_tile().to_floating(), TILE_SIZE.to_floating(), "#666", ); } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct BuildConveyor { pub allow_splitting: bool, } #[derive(Copy, Clone, PartialEq, Serialize, Deserialize, Debug)] struct BuildConveyorCandidate { position: GridVector, input_side: Facing, } impl BuildConveyorCandidate { fn input_position(&self) -> GridVector { self.position + self.input_side.unit_vector() * TILE_WIDTH } fn output_side(&self) -> Facing { self.input_side + Rotation::U_TURN } } impl BuildConveyor { fn candidate_valid( game: &Game, candidate: BuildConveyorCandidate, allow_splitting: bool, ) -> bool { if game.grid.get(candidate.position).is_none() { return false; }; let output_mechanism = game.mechanism(candidate.position); //debug!("{:?}", (candidate, input_mechanism, output_mechanism)); guard!(let Some(input_mechanism) = game.mechanism(candidate.input_position()) else { return false }); if!input_mechanism .mechanism_type .can_be_material_source(candidate.output_side()) { return false; } if!allow_splitting { if matches!(&input_mechanism.mechanism_type, MechanismType::Conveyor(conveyor) if conveyor.sides.iter().filter(|&&side| side == ConveyorSide::Output).count() > 0) { return false; } } if let Some(output_mechanism) = output_mechanism { guard!(let Mechanism { mechanism_type: MechanismType::Conveyor(conveyor),.. } = output_mechanism else { return false }); if conveyor.sides[candidate.input_side.as_index()]!= ConveyorSide::Disconnected { return false; } } true } /// the returned facing is the input side of the new conveyor fn current_target(game: &Game, allow_splitting: bool) -> Option<BuildConveyorCandidate> { let player_position = game.player.position.containing_tile(); let player_offset = game.player.position - player_position.to_floating(); let mut candidates = Vec::new(); let mut consider = |candidate, score| { if Self::candidate_valid(game, candidate, allow_splitting) { candidates.push((candidate, score)) } }; for facing in Facing::ALL_FACINGS { consider( BuildConveyorCandidate { position: player_position, input_side: facing, }, (player_offset - facing.unit_vector().to_floating()).magnitude_squared(), ); consider( BuildConveyorCandidate { position: player_position - facing.unit_vector() * TILE_WIDTH, input_side: facing, }, (player_offset - -facing.unit_vector().to_floating()).magnitude_squared(), ); } candidates .into_iter() .min_by_key(|&(_, score)| OrderedFloat(score)) .map(|(c, _)| c) } } impl SimpleActionTrait for BuildConveyor { fn finish(&self, context: ActionUpdateContext) { let candidate = Self::current_target(context.game, self.allow_splitting).unwrap(); let mut sides = [ConveyorSide::Disconnected; 4]; sides[candidate.input_side.as_index()] = ConveyorSide::Input; context.game.create_mechanism( candidate.position, Mechanism { mechanism_type: MechanismType::Conveyor(Conveyor { sides, last_sent: Facing::from_index(0), }), }, ); context .game .mutate_mechanism(candidate.input_position(), |mechanism| { if let Mechanism { mechanism_type: MechanismType::Conveyor(Conveyor { sides,.. }), .. } = mechanism { sides[candidate.output_side().as_index()] = ConveyorSide::Output; } }); } fn possible(&self, game: &Game) -> bool { Self::current_target(game, self.allow_splitting).is_some() } fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) { if let Some(candidate) = Self::current_target(game, self.allow_splitting) { draw.rectangle_on_map( 5, candidate.position.to_floating(), TILE_SIZE.to_floating(), "#666", ); draw.rectangle_on_map( 5, candidate.input_position().to_floating(), TILE_SIZE.to_floating(), "#555", ); } else { draw.rectangle_on_map( 5, game.player.position.containing_tile().to_floating(), TILE_SIZE.to_floating(), "#555", ); } } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct Reshuffle; impl SimpleActionTrait for Reshuffle { fn finish(&self, context: ActionUpdateContext) { let cards = &mut context.game.cards; cards.deck.shuffle(&mut rand::thread_rng()); cards.selected_index = Some(0); } }
finished
identifier_name
actions.rs
use crate::cards::CardInstance; use crate::game::{Game, PlayerActionState, PlayerActiveInteraction, Time, UPDATE_DURATION}; use crate::geometry::{ Facing, FloatingVector, FloatingVectorExtension, GridVector, GridVectorExtension, Rotation, TILE_RADIUS, TILE_SIZE, TILE_WIDTH, }; use crate::mechanisms::{BuildMechanism, Conveyor, ConveyorSide, Mechanism, MechanismType}; use crate::ui_glue::Draw; use guard::guard; use ordered_float::OrderedFloat; use rand::prelude::*; use serde::{Deserialize, Serialize}; use std::fmt::Debug; pub enum ActionStatus { StillGoing, Completed, } pub struct ActionUpdateContext<'a> { pub game: &'a mut Game, } impl<'a> ActionUpdateContext<'a> { pub fn interaction_state(&self) -> &PlayerActiveInteraction { match &self.game.player.action_state { PlayerActionState::Interacting(i) => i, _ => unreachable!(), } } pub fn this_card(&self) -> &CardInstance { self.game.cards.selected().unwrap() } pub fn this_card_mut(&mut self) -> &mut CardInstance { self.game.cards.selected_mut().unwrap() } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub enum Cost { Fixed(i32), Variable, None, } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct ActionDisplayInfo { pub name: String, pub health_cost: Cost, pub time_cost: Cost, pub rules_text: String, pub flavor_text: String, } impl Default for ActionDisplayInfo { fn default() -> Self { ActionDisplayInfo { name: "".to_string(), health_cost: Cost::None, time_cost: Cost::Fixed(2), rules_text: "".to_string(), flavor_text: "".to_string(), } } } #[allow(unused)] pub trait ActionTrait { /** Perform a single time-step update on this action, possibly modifying the game state. Note that the action is removed from `game` before doing this, so that both mutable references can be held at the same time, so the action still stored in `game` is temporarily invalid. */ fn update(&mut self, context: ActionUpdateContext) -> ActionStatus; fn display_info(&self) -> ActionDisplayInfo; fn possible(&self, game: &Game) -> bool { true } fn draw_progress(&self, game: &Game, draw: &mut dyn Draw); fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) {} } trait_enum! { #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub enum Action: ActionTrait { SimpleAction, } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct SimpleAction { display_info: ActionDisplayInfo, is_card: bool, simple_action_type: SimpleActionType, progress: Time, cancel_progress: Time, } #[allow(unused)] pub trait SimpleActionTrait { fn finish(&self, context: ActionUpdateContext); fn possible(&self, game: &Game) -> bool { true } fn draw_progress(&self, game: &Game, draw: &mut dyn Draw) {} fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) {} } trait_enum! { #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub enum SimpleActionType: SimpleActionTrait { Reshuffle, BuildConveyor, BuildMechanism, } } fn smootherstep(a: f64, b: f64, x: f64) -> f64 { let x = ((x - a) / (b - a)).clamp(0.0, 1.0); x * x * x * (x * (x * 6.0 - 15.0) + 10.0) } impl SimpleAction { pub fn new( time_cost: i32, health_cost: Option<i32>, name: &str, rules_text: &str, flavor_text: &str, is_card: bool, simple_action_type: SimpleActionType, ) -> SimpleAction { SimpleAction { display_info: ActionDisplayInfo { name: name.to_string(), health_cost: match health_cost { Some(c) => Cost::Fixed(c), None => Cost::None, }, time_cost: Cost::Fixed(time_cost), rules_text: rules_text.to_string(), flavor_text: flavor_text.to_string(), }, is_card, simple_action_type, progress: 0.0, cancel_progress: 0.0, } } fn time_cost(&self) -> f64 { match self.display_info.time_cost { Cost::Fixed(cost) => cost as f64, _ => panic!(), } } fn health_cost(&self) -> f64 { match self.display_info.health_cost { Cost::Fixed(cost) => cost as f64, Cost::None => 0.0, _ => panic!(), } } fn cooldown_time(&self) -> f64 { self.time_cost() * 0.25 } fn startup_time(&self) -> f64 { self.time_cost() * 0.25 } fn finish_time(&self) -> f64 { self.time_cost() - self.cooldown_time() } fn finished(&self) -> bool { self.progress > self.finish_time() } fn health_to_pay_by(&self, progress: f64) -> f64 { smootherstep(self.startup_time(), self.finish_time(), progress) * self.health_cost() } } impl ActionTrait for SimpleAction { fn update(&mut self, context: ActionUpdateContext) -> ActionStatus { let simple_action_type = self.simple_action_type.clone(); let canceled = context.interaction_state().canceled &&!self.finished(); if canceled { self.cancel_progress += UPDATE_DURATION; } else { let was_finished = self.finished(); let health_paid_already = self.health_to_pay_by(self.progress); self.progress += UPDATE_DURATION; let health_payment = self.health_to_pay_by(self.progress) - health_paid_already; context.game.player.health -= health_payment; if self.finished() > was_finished { if self.is_card { match context.game.cards.selected_index { Some(index) => { if index + 1 == context.game.cards.deck.len() { context.game.cards.selected_index = None; } else
} _ => unreachable!(), } } self.simple_action_type.finish(context); } } if self.progress > self.time_cost() || self.cancel_progress > self.cooldown_time() { ActionStatus::Completed } else { ActionStatus::StillGoing } } fn display_info(&self) -> ActionDisplayInfo { self.display_info.clone() } fn possible(&self, game: &Game) -> bool { self.simple_action_type.possible(game) } fn draw_progress(&self, game: &Game, draw: &mut dyn Draw) { self.simple_action_type.draw_progress(game, draw); let a = game.player.position + FloatingVector::new(-TILE_RADIUS as f64 * 0.5, 0.0); draw.rectangle_on_map( 70, a, FloatingVector::new(TILE_RADIUS as f64 * 0.25, TILE_WIDTH as f64), "#000", ); draw.rectangle_on_map( 71, a, FloatingVector::new( TILE_RADIUS as f64 * 0.25, TILE_WIDTH as f64 * self.progress / self.time_cost(), ), "#ff0", ); } fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) { self.simple_action_type.draw_preview(game, draw); } } impl SimpleActionTrait for BuildMechanism { fn finish(&self, context: ActionUpdateContext) { context.game.create_mechanism( context.game.player.position.containing_tile(), self.mechanism(context.game), ); } fn possible(&self, game: &Game) -> bool { let position = game.player.position.containing_tile(); game.grid.get(position).is_some() && game.mechanism(position).is_none() } fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) { draw.rectangle_on_map( 5, game.player.position.containing_tile().to_floating(), TILE_SIZE.to_floating(), "#666", ); } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct BuildConveyor { pub allow_splitting: bool, } #[derive(Copy, Clone, PartialEq, Serialize, Deserialize, Debug)] struct BuildConveyorCandidate { position: GridVector, input_side: Facing, } impl BuildConveyorCandidate { fn input_position(&self) -> GridVector { self.position + self.input_side.unit_vector() * TILE_WIDTH } fn output_side(&self) -> Facing { self.input_side + Rotation::U_TURN } } impl BuildConveyor { fn candidate_valid( game: &Game, candidate: BuildConveyorCandidate, allow_splitting: bool, ) -> bool { if game.grid.get(candidate.position).is_none() { return false; }; let output_mechanism = game.mechanism(candidate.position); //debug!("{:?}", (candidate, input_mechanism, output_mechanism)); guard!(let Some(input_mechanism) = game.mechanism(candidate.input_position()) else { return false }); if!input_mechanism .mechanism_type .can_be_material_source(candidate.output_side()) { return false; } if!allow_splitting { if matches!(&input_mechanism.mechanism_type, MechanismType::Conveyor(conveyor) if conveyor.sides.iter().filter(|&&side| side == ConveyorSide::Output).count() > 0) { return false; } } if let Some(output_mechanism) = output_mechanism { guard!(let Mechanism { mechanism_type: MechanismType::Conveyor(conveyor),.. } = output_mechanism else { return false }); if conveyor.sides[candidate.input_side.as_index()]!= ConveyorSide::Disconnected { return false; } } true } /// the returned facing is the input side of the new conveyor fn current_target(game: &Game, allow_splitting: bool) -> Option<BuildConveyorCandidate> { let player_position = game.player.position.containing_tile(); let player_offset = game.player.position - player_position.to_floating(); let mut candidates = Vec::new(); let mut consider = |candidate, score| { if Self::candidate_valid(game, candidate, allow_splitting) { candidates.push((candidate, score)) } }; for facing in Facing::ALL_FACINGS { consider( BuildConveyorCandidate { position: player_position, input_side: facing, }, (player_offset - facing.unit_vector().to_floating()).magnitude_squared(), ); consider( BuildConveyorCandidate { position: player_position - facing.unit_vector() * TILE_WIDTH, input_side: facing, }, (player_offset - -facing.unit_vector().to_floating()).magnitude_squared(), ); } candidates .into_iter() .min_by_key(|&(_, score)| OrderedFloat(score)) .map(|(c, _)| c) } } impl SimpleActionTrait for BuildConveyor { fn finish(&self, context: ActionUpdateContext) { let candidate = Self::current_target(context.game, self.allow_splitting).unwrap(); let mut sides = [ConveyorSide::Disconnected; 4]; sides[candidate.input_side.as_index()] = ConveyorSide::Input; context.game.create_mechanism( candidate.position, Mechanism { mechanism_type: MechanismType::Conveyor(Conveyor { sides, last_sent: Facing::from_index(0), }), }, ); context .game .mutate_mechanism(candidate.input_position(), |mechanism| { if let Mechanism { mechanism_type: MechanismType::Conveyor(Conveyor { sides,.. }), .. } = mechanism { sides[candidate.output_side().as_index()] = ConveyorSide::Output; } }); } fn possible(&self, game: &Game) -> bool { Self::current_target(game, self.allow_splitting).is_some() } fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) { if let Some(candidate) = Self::current_target(game, self.allow_splitting) { draw.rectangle_on_map( 5, candidate.position.to_floating(), TILE_SIZE.to_floating(), "#666", ); draw.rectangle_on_map( 5, candidate.input_position().to_floating(), TILE_SIZE.to_floating(), "#555", ); } else { draw.rectangle_on_map( 5, game.player.position.containing_tile().to_floating(), TILE_SIZE.to_floating(), "#555", ); } } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct Reshuffle; impl SimpleActionTrait for Reshuffle { fn finish(&self, context: ActionUpdateContext) { let cards = &mut context.game.cards; cards.deck.shuffle(&mut rand::thread_rng()); cards.selected_index = Some(0); } }
{ context.game.cards.selected_index = Some(index + 1); }
conditional_block
actions.rs
use crate::cards::CardInstance; use crate::game::{Game, PlayerActionState, PlayerActiveInteraction, Time, UPDATE_DURATION}; use crate::geometry::{ Facing, FloatingVector, FloatingVectorExtension, GridVector, GridVectorExtension, Rotation, TILE_RADIUS, TILE_SIZE, TILE_WIDTH, }; use crate::mechanisms::{BuildMechanism, Conveyor, ConveyorSide, Mechanism, MechanismType}; use crate::ui_glue::Draw; use guard::guard; use ordered_float::OrderedFloat; use rand::prelude::*; use serde::{Deserialize, Serialize}; use std::fmt::Debug; pub enum ActionStatus { StillGoing, Completed, } pub struct ActionUpdateContext<'a> { pub game: &'a mut Game, } impl<'a> ActionUpdateContext<'a> { pub fn interaction_state(&self) -> &PlayerActiveInteraction { match &self.game.player.action_state { PlayerActionState::Interacting(i) => i, _ => unreachable!(), } } pub fn this_card(&self) -> &CardInstance { self.game.cards.selected().unwrap() } pub fn this_card_mut(&mut self) -> &mut CardInstance { self.game.cards.selected_mut().unwrap() } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub enum Cost { Fixed(i32), Variable, None, } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct ActionDisplayInfo { pub name: String, pub health_cost: Cost, pub time_cost: Cost, pub rules_text: String, pub flavor_text: String, } impl Default for ActionDisplayInfo { fn default() -> Self { ActionDisplayInfo { name: "".to_string(), health_cost: Cost::None, time_cost: Cost::Fixed(2), rules_text: "".to_string(), flavor_text: "".to_string(), } } } #[allow(unused)] pub trait ActionTrait { /** Perform a single time-step update on this action, possibly modifying the game state. Note that the action is removed from `game` before doing this, so that both mutable references can be held at the same time, so the action still stored in `game` is temporarily invalid. */ fn update(&mut self, context: ActionUpdateContext) -> ActionStatus; fn display_info(&self) -> ActionDisplayInfo; fn possible(&self, game: &Game) -> bool { true } fn draw_progress(&self, game: &Game, draw: &mut dyn Draw); fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) {} } trait_enum! { #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub enum Action: ActionTrait { SimpleAction, } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct SimpleAction { display_info: ActionDisplayInfo, is_card: bool, simple_action_type: SimpleActionType, progress: Time, cancel_progress: Time, } #[allow(unused)] pub trait SimpleActionTrait { fn finish(&self, context: ActionUpdateContext); fn possible(&self, game: &Game) -> bool { true } fn draw_progress(&self, game: &Game, draw: &mut dyn Draw) {} fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) {} } trait_enum! { #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub enum SimpleActionType: SimpleActionTrait { Reshuffle, BuildConveyor, BuildMechanism, } } fn smootherstep(a: f64, b: f64, x: f64) -> f64 { let x = ((x - a) / (b - a)).clamp(0.0, 1.0); x * x * x * (x * (x * 6.0 - 15.0) + 10.0) } impl SimpleAction { pub fn new( time_cost: i32, health_cost: Option<i32>, name: &str, rules_text: &str, flavor_text: &str, is_card: bool, simple_action_type: SimpleActionType, ) -> SimpleAction { SimpleAction { display_info: ActionDisplayInfo { name: name.to_string(), health_cost: match health_cost { Some(c) => Cost::Fixed(c), None => Cost::None, }, time_cost: Cost::Fixed(time_cost), rules_text: rules_text.to_string(), flavor_text: flavor_text.to_string(), }, is_card, simple_action_type, progress: 0.0, cancel_progress: 0.0, } } fn time_cost(&self) -> f64 { match self.display_info.time_cost { Cost::Fixed(cost) => cost as f64, _ => panic!(), } } fn health_cost(&self) -> f64 { match self.display_info.health_cost { Cost::Fixed(cost) => cost as f64, Cost::None => 0.0, _ => panic!(), } } fn cooldown_time(&self) -> f64 { self.time_cost() * 0.25 } fn startup_time(&self) -> f64 { self.time_cost() * 0.25 } fn finish_time(&self) -> f64 { self.time_cost() - self.cooldown_time() } fn finished(&self) -> bool { self.progress > self.finish_time() } fn health_to_pay_by(&self, progress: f64) -> f64 { smootherstep(self.startup_time(), self.finish_time(), progress) * self.health_cost() } } impl ActionTrait for SimpleAction { fn update(&mut self, context: ActionUpdateContext) -> ActionStatus { let simple_action_type = self.simple_action_type.clone(); let canceled = context.interaction_state().canceled &&!self.finished(); if canceled { self.cancel_progress += UPDATE_DURATION; } else { let was_finished = self.finished(); let health_paid_already = self.health_to_pay_by(self.progress); self.progress += UPDATE_DURATION; let health_payment = self.health_to_pay_by(self.progress) - health_paid_already; context.game.player.health -= health_payment; if self.finished() > was_finished { if self.is_card { match context.game.cards.selected_index { Some(index) => { if index + 1 == context.game.cards.deck.len() { context.game.cards.selected_index = None; } else { context.game.cards.selected_index = Some(index + 1); } } _ => unreachable!(), } } self.simple_action_type.finish(context); } } if self.progress > self.time_cost() || self.cancel_progress > self.cooldown_time() { ActionStatus::Completed } else { ActionStatus::StillGoing } } fn display_info(&self) -> ActionDisplayInfo { self.display_info.clone() } fn possible(&self, game: &Game) -> bool { self.simple_action_type.possible(game) } fn draw_progress(&self, game: &Game, draw: &mut dyn Draw) { self.simple_action_type.draw_progress(game, draw); let a = game.player.position + FloatingVector::new(-TILE_RADIUS as f64 * 0.5, 0.0); draw.rectangle_on_map( 70, a, FloatingVector::new(TILE_RADIUS as f64 * 0.25, TILE_WIDTH as f64), "#000", ); draw.rectangle_on_map( 71, a, FloatingVector::new( TILE_RADIUS as f64 * 0.25, TILE_WIDTH as f64 * self.progress / self.time_cost(), ), "#ff0", ); } fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) { self.simple_action_type.draw_preview(game, draw); } } impl SimpleActionTrait for BuildMechanism { fn finish(&self, context: ActionUpdateContext) { context.game.create_mechanism( context.game.player.position.containing_tile(), self.mechanism(context.game), ); } fn possible(&self, game: &Game) -> bool { let position = game.player.position.containing_tile(); game.grid.get(position).is_some() && game.mechanism(position).is_none() } fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) { draw.rectangle_on_map( 5, game.player.position.containing_tile().to_floating(), TILE_SIZE.to_floating(), "#666", ); } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct BuildConveyor { pub allow_splitting: bool, } #[derive(Copy, Clone, PartialEq, Serialize, Deserialize, Debug)] struct BuildConveyorCandidate { position: GridVector, input_side: Facing, } impl BuildConveyorCandidate { fn input_position(&self) -> GridVector { self.position + self.input_side.unit_vector() * TILE_WIDTH } fn output_side(&self) -> Facing { self.input_side + Rotation::U_TURN } } impl BuildConveyor { fn candidate_valid( game: &Game, candidate: BuildConveyorCandidate, allow_splitting: bool, ) -> bool { if game.grid.get(candidate.position).is_none() { return false; }; let output_mechanism = game.mechanism(candidate.position); //debug!("{:?}", (candidate, input_mechanism, output_mechanism)); guard!(let Some(input_mechanism) = game.mechanism(candidate.input_position()) else { return false }); if!input_mechanism .mechanism_type .can_be_material_source(candidate.output_side()) { return false; } if!allow_splitting { if matches!(&input_mechanism.mechanism_type, MechanismType::Conveyor(conveyor) if conveyor.sides.iter().filter(|&&side| side == ConveyorSide::Output).count() > 0) { return false; } } if let Some(output_mechanism) = output_mechanism { guard!(let Mechanism { mechanism_type: MechanismType::Conveyor(conveyor),.. } = output_mechanism else { return false }); if conveyor.sides[candidate.input_side.as_index()]!= ConveyorSide::Disconnected { return false; } } true } /// the returned facing is the input side of the new conveyor fn current_target(game: &Game, allow_splitting: bool) -> Option<BuildConveyorCandidate> { let player_position = game.player.position.containing_tile(); let player_offset = game.player.position - player_position.to_floating(); let mut candidates = Vec::new(); let mut consider = |candidate, score| { if Self::candidate_valid(game, candidate, allow_splitting) { candidates.push((candidate, score)) } }; for facing in Facing::ALL_FACINGS { consider( BuildConveyorCandidate { position: player_position, input_side: facing, }, (player_offset - facing.unit_vector().to_floating()).magnitude_squared(), ); consider( BuildConveyorCandidate { position: player_position - facing.unit_vector() * TILE_WIDTH, input_side: facing, }, (player_offset - -facing.unit_vector().to_floating()).magnitude_squared(), ); } candidates .into_iter() .min_by_key(|&(_, score)| OrderedFloat(score)) .map(|(c, _)| c) } } impl SimpleActionTrait for BuildConveyor { fn finish(&self, context: ActionUpdateContext) { let candidate = Self::current_target(context.game, self.allow_splitting).unwrap(); let mut sides = [ConveyorSide::Disconnected; 4]; sides[candidate.input_side.as_index()] = ConveyorSide::Input; context.game.create_mechanism( candidate.position, Mechanism { mechanism_type: MechanismType::Conveyor(Conveyor { sides, last_sent: Facing::from_index(0), }), }, ); context .game .mutate_mechanism(candidate.input_position(), |mechanism| { if let Mechanism { mechanism_type: MechanismType::Conveyor(Conveyor { sides,.. }), .. } = mechanism { sides[candidate.output_side().as_index()] = ConveyorSide::Output; } }); } fn possible(&self, game: &Game) -> bool { Self::current_target(game, self.allow_splitting).is_some() } fn draw_preview(&self, game: &Game, draw: &mut dyn Draw) { if let Some(candidate) = Self::current_target(game, self.allow_splitting) { draw.rectangle_on_map( 5, candidate.position.to_floating(), TILE_SIZE.to_floating(), "#666", ); draw.rectangle_on_map( 5, candidate.input_position().to_floating(), TILE_SIZE.to_floating(), "#555", ); } else { draw.rectangle_on_map( 5, game.player.position.containing_tile().to_floating(), TILE_SIZE.to_floating(), "#555", ); } } } #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct Reshuffle; impl SimpleActionTrait for Reshuffle { fn finish(&self, context: ActionUpdateContext) { let cards = &mut context.game.cards; cards.deck.shuffle(&mut rand::thread_rng()); cards.selected_index = Some(0); }
}
random_line_split
lib.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0. // BEGIN LINT CONFIG // DO NOT EDIT. Automatically generated by bin/gen-lints. // Have complaints about the noise? See the note in misc/python/materialize/cli/gen-lints.py first. #![allow(clippy::style)] #![allow(clippy::complexity)] #![allow(clippy::large_enum_variant)] #![allow(clippy::mutable_key_type)] #![allow(clippy::stable_sort_primitive)] #![allow(clippy::map_entry)] #![allow(clippy::box_default)] #![warn(clippy::bool_comparison)] #![warn(clippy::clone_on_ref_ptr)] #![warn(clippy::no_effect)] #![warn(clippy::unnecessary_unwrap)] #![warn(clippy::dbg_macro)] #![warn(clippy::todo)] #![warn(clippy::wildcard_dependencies)] #![warn(clippy::zero_prefixed_literal)] #![warn(clippy::borrowed_box)] #![warn(clippy::deref_addrof)] #![warn(clippy::double_must_use)] #![warn(clippy::double_parens)] #![warn(clippy::extra_unused_lifetimes)] #![warn(clippy::needless_borrow)] #![warn(clippy::needless_question_mark)] #![warn(clippy::needless_return)] #![warn(clippy::redundant_pattern)] #![warn(clippy::redundant_slicing)] #![warn(clippy::redundant_static_lifetimes)] #![warn(clippy::single_component_path_imports)] #![warn(clippy::unnecessary_cast)] #![warn(clippy::useless_asref)] #![warn(clippy::useless_conversion)] #![warn(clippy::builtin_type_shadow)] #![warn(clippy::duplicate_underscore_argument)] #![warn(clippy::double_neg)] #![warn(clippy::unnecessary_mut_passed)] #![warn(clippy::wildcard_in_or_patterns)] #![warn(clippy::crosspointer_transmute)] #![warn(clippy::excessive_precision)] #![warn(clippy::overflow_check_conditional)] #![warn(clippy::as_conversions)] #![warn(clippy::match_overlapping_arm)] #![warn(clippy::zero_divided_by_zero)] #![warn(clippy::must_use_unit)] #![warn(clippy::suspicious_assignment_formatting)] #![warn(clippy::suspicious_else_formatting)] #![warn(clippy::suspicious_unary_op_formatting)] #![warn(clippy::mut_mutex_lock)] #![warn(clippy::print_literal)] #![warn(clippy::same_item_push)] #![warn(clippy::useless_format)] #![warn(clippy::write_literal)] #![warn(clippy::redundant_closure)] #![warn(clippy::redundant_closure_call)] #![warn(clippy::unnecessary_lazy_evaluations)] #![warn(clippy::partialeq_ne_impl)] #![warn(clippy::redundant_field_names)] #![warn(clippy::transmutes_expressible_as_ptr_casts)] #![warn(clippy::unused_async)] #![warn(clippy::disallowed_methods)] #![warn(clippy::disallowed_macros)] #![warn(clippy::disallowed_types)] #![warn(clippy::from_over_into)] // END LINT CONFIG //! An API client for [Metabase]. //! //! Only the features presently required are implemented. Documentation is //! sparse to avoid duplicating information in the upstream API documentation. //! See: //! //! * [Using the REST API](https://github.com/metabase/metabase/wiki/Using-the-REST-API) //! * [Auto-generated API documentation](https://github.com/metabase/metabase/blob/master/docs/api-documentation.md) //! //! [Metabase]: https://metabase.com #![warn(missing_debug_implementations)] use std::fmt; use std::time::Duration; use reqwest::{IntoUrl, Url}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; /// A Metabase API client. #[derive(Debug)] pub struct Client { inner: reqwest::Client, url: Url, session_id: Option<String>, } impl Client { /// Constructs a new `Client` that will target a Metabase instance at `url`. /// /// `url` must not contain a path nor be a [cannot-be-a-base] URL. /// /// [cannot-be-a-base]: https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag pub fn new<U>(url: U) -> Result<Self, Error> where U: IntoUrl, { let mut url = url.into_url()?; if url.path()!= "/" { return Err(Error::InvalidUrl("base URL cannot have path".into())); } assert!(!url.cannot_be_a_base()); url.path_segments_mut() .expect("cannot-be-a-base checked to be false") .push("api"); Ok(Client { inner: reqwest::Client::new(), url, session_id: None, }) } /// Sets the session ID to include in future requests made by this client. pub fn set_session_id(&mut self, session_id: String) { self.session_id = Some(session_id); } /// Fetches public, global properties. /// /// The underlying API call is `GET /api/session/properties`. pub async fn session_properties(&self) -> Result<SessionPropertiesResponse, reqwest::Error> { let url = self.api_url(&["session", "properties"]); self.send_request(self.inner.get(url)).await } /// Requests a session ID for the username and password named in `request`. /// /// Note that usernames are typically email addresses. To authenticate /// future requests with the returned session ID, call `set_session_id`. /// /// The underlying API call is `POST /api/session`. pub async fn login(&self, request: &LoginRequest) -> Result<LoginResponse, reqwest::Error> { let url = self.api_url(&["session"]); self.send_request(self.inner.post(url).json(request)).await } /// Creates a user and database connection if the Metabase instance has not /// yet been set up. /// /// The request must include the `setup_token` from a /// `SessionPropertiesResponse`. If the setup token returned by /// [`Client::session_properties`] is `None`, the cluster is already set up, /// and this request will fail. /// /// The underlying API call is `POST /api/setup`. pub async fn setup(&self, request: &SetupRequest) -> Result<LoginResponse, reqwest::Error> { let url = self.api_url(&["setup"]); self.send_request(self.inner.post(url).json(request)).await } /// Fetches the list of databases known to Metabase. /// /// The underlying API call is `GET /database`. pub async fn databases(&self) -> Result<Vec<Database>, reqwest::Error> { let url = self.api_url(&["database"]); let res: ListWrapper<_> = self.send_request(self.inner.get(url)).await?; Ok(res.data) } /// Fetches metadata about a particular database. /// /// The underlying API call is `GET /database/:id/metadata`. pub async fn database_metadata(&self, id: usize) -> Result<DatabaseMetadata, reqwest::Error> { let url = self.api_url(&["database", &id.to_string(), "metadata"]); self.send_request(self.inner.get(url)).await } fn api_url(&self, endpoint: &[&str]) -> Url { let mut url = self.url.clone(); url.path_segments_mut() .expect("url validated on construction") .extend(endpoint); url } async fn send_request<T>(&self, mut req: reqwest::RequestBuilder) -> Result<T, reqwest::Error> where T: DeserializeOwned, { req = req.timeout(Duration::from_secs(5)); if let Some(session_id) = &self.session_id { req = req.header("X-Metabase-Session", session_id); } let res = req.send().await?.error_for_status()?; res.json().await } } /// A Metabase error. #[derive(Debug)] pub enum Error { /// The provided URL was invalid. InvalidUrl(String), /// The underlying transport mechanism returned na error. Transport(reqwest::Error), } impl From<reqwest::Error> for Error { fn from(e: reqwest::Error) -> Error { Error::Transport(e) } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error +'static)> { match self { Error::InvalidUrl(_) => None, Error::Transport(e) => Some(e), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::InvalidUrl(msg) => write!(f, "invalid url: {}", msg), Error::Transport(e) => write!(f, "transport: {}", e), } } } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] struct ListWrapper<T> { data: Vec<T>, } /// The response to [`Client::session_properties`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] #[serde(rename_all = "kebab-case")] pub struct SessionPropertiesResponse { pub setup_token: Option<String>, } /// The request for [`Client::setup`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct SetupRequest { pub allow_tracking: bool, pub database: SetupDatabase, pub token: String, pub prefs: SetupPrefs, pub user: SetupUser, } /// A database to create as part of a [`SetupRequest`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct SetupDatabase { pub engine: String, pub name: String, pub details: SetupDatabaseDetails, } /// Details for a [`SetupDatabase`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct SetupDatabaseDetails { pub host: String, pub port: usize, pub dbname: String, pub user: String, } /// Preferences for a [`SetupRequest`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct SetupPrefs { pub site_name: String, } /// A user to create as part of a [`SetupRequest`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct SetupUser { pub email: String, pub first_name: String, pub last_name: String, pub password: String, pub site_name: String, } /// The request for [`Client::login`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct LoginRequest { pub username: String, pub password: String, } /// The response to [`Client::login`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct LoginResponse { pub id: String, } /// A database returned by [`Client::databases`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct
{ pub name: String, pub id: usize, } /// The response to [`Client::database_metadata`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct DatabaseMetadata { pub tables: Vec<Table>, } /// A table that is part of [`DatabaseMetadata`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct Table { pub name: String, pub schema: String, pub fields: Vec<TableField>, } /// A field of a [`Table`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct TableField { pub name: String, pub database_type: String, pub base_type: String, pub special_type: Option<String>, }
Database
identifier_name
lib.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0. // BEGIN LINT CONFIG // DO NOT EDIT. Automatically generated by bin/gen-lints. // Have complaints about the noise? See the note in misc/python/materialize/cli/gen-lints.py first. #![allow(clippy::style)] #![allow(clippy::complexity)] #![allow(clippy::large_enum_variant)] #![allow(clippy::mutable_key_type)] #![allow(clippy::stable_sort_primitive)] #![allow(clippy::map_entry)] #![allow(clippy::box_default)] #![warn(clippy::bool_comparison)] #![warn(clippy::clone_on_ref_ptr)] #![warn(clippy::no_effect)] #![warn(clippy::unnecessary_unwrap)] #![warn(clippy::dbg_macro)] #![warn(clippy::todo)] #![warn(clippy::wildcard_dependencies)] #![warn(clippy::zero_prefixed_literal)] #![warn(clippy::borrowed_box)] #![warn(clippy::deref_addrof)] #![warn(clippy::double_must_use)] #![warn(clippy::double_parens)] #![warn(clippy::extra_unused_lifetimes)] #![warn(clippy::needless_borrow)] #![warn(clippy::needless_question_mark)] #![warn(clippy::needless_return)] #![warn(clippy::redundant_pattern)] #![warn(clippy::redundant_slicing)] #![warn(clippy::redundant_static_lifetimes)] #![warn(clippy::single_component_path_imports)] #![warn(clippy::unnecessary_cast)] #![warn(clippy::useless_asref)] #![warn(clippy::useless_conversion)] #![warn(clippy::builtin_type_shadow)] #![warn(clippy::duplicate_underscore_argument)] #![warn(clippy::double_neg)] #![warn(clippy::unnecessary_mut_passed)] #![warn(clippy::wildcard_in_or_patterns)] #![warn(clippy::crosspointer_transmute)] #![warn(clippy::excessive_precision)] #![warn(clippy::overflow_check_conditional)] #![warn(clippy::as_conversions)] #![warn(clippy::match_overlapping_arm)] #![warn(clippy::zero_divided_by_zero)] #![warn(clippy::must_use_unit)] #![warn(clippy::suspicious_assignment_formatting)] #![warn(clippy::suspicious_else_formatting)] #![warn(clippy::suspicious_unary_op_formatting)] #![warn(clippy::mut_mutex_lock)] #![warn(clippy::print_literal)] #![warn(clippy::same_item_push)] #![warn(clippy::useless_format)] #![warn(clippy::write_literal)] #![warn(clippy::redundant_closure)] #![warn(clippy::redundant_closure_call)] #![warn(clippy::unnecessary_lazy_evaluations)] #![warn(clippy::partialeq_ne_impl)] #![warn(clippy::redundant_field_names)] #![warn(clippy::transmutes_expressible_as_ptr_casts)] #![warn(clippy::unused_async)] #![warn(clippy::disallowed_methods)] #![warn(clippy::disallowed_macros)] #![warn(clippy::disallowed_types)] #![warn(clippy::from_over_into)] // END LINT CONFIG //! An API client for [Metabase]. //! //! Only the features presently required are implemented. Documentation is //! sparse to avoid duplicating information in the upstream API documentation. //! See: //! //! * [Using the REST API](https://github.com/metabase/metabase/wiki/Using-the-REST-API) //! * [Auto-generated API documentation](https://github.com/metabase/metabase/blob/master/docs/api-documentation.md) //! //! [Metabase]: https://metabase.com #![warn(missing_debug_implementations)] use std::fmt; use std::time::Duration; use reqwest::{IntoUrl, Url}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; /// A Metabase API client. #[derive(Debug)] pub struct Client { inner: reqwest::Client, url: Url, session_id: Option<String>, } impl Client { /// Constructs a new `Client` that will target a Metabase instance at `url`. /// /// `url` must not contain a path nor be a [cannot-be-a-base] URL. /// /// [cannot-be-a-base]: https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag pub fn new<U>(url: U) -> Result<Self, Error> where U: IntoUrl, { let mut url = url.into_url()?; if url.path()!= "/" { return Err(Error::InvalidUrl("base URL cannot have path".into())); } assert!(!url.cannot_be_a_base()); url.path_segments_mut() .expect("cannot-be-a-base checked to be false") .push("api"); Ok(Client { inner: reqwest::Client::new(), url, session_id: None, }) } /// Sets the session ID to include in future requests made by this client. pub fn set_session_id(&mut self, session_id: String) { self.session_id = Some(session_id); } /// Fetches public, global properties. /// /// The underlying API call is `GET /api/session/properties`. pub async fn session_properties(&self) -> Result<SessionPropertiesResponse, reqwest::Error> { let url = self.api_url(&["session", "properties"]); self.send_request(self.inner.get(url)).await } /// Requests a session ID for the username and password named in `request`. /// /// Note that usernames are typically email addresses. To authenticate /// future requests with the returned session ID, call `set_session_id`. /// /// The underlying API call is `POST /api/session`. pub async fn login(&self, request: &LoginRequest) -> Result<LoginResponse, reqwest::Error> { let url = self.api_url(&["session"]); self.send_request(self.inner.post(url).json(request)).await } /// Creates a user and database connection if the Metabase instance has not /// yet been set up. /// /// The request must include the `setup_token` from a /// `SessionPropertiesResponse`. If the setup token returned by /// [`Client::session_properties`] is `None`, the cluster is already set up, /// and this request will fail. /// /// The underlying API call is `POST /api/setup`. pub async fn setup(&self, request: &SetupRequest) -> Result<LoginResponse, reqwest::Error> { let url = self.api_url(&["setup"]); self.send_request(self.inner.post(url).json(request)).await } /// Fetches the list of databases known to Metabase. /// /// The underlying API call is `GET /database`. pub async fn databases(&self) -> Result<Vec<Database>, reqwest::Error> { let url = self.api_url(&["database"]); let res: ListWrapper<_> = self.send_request(self.inner.get(url)).await?; Ok(res.data) } /// Fetches metadata about a particular database. /// /// The underlying API call is `GET /database/:id/metadata`. pub async fn database_metadata(&self, id: usize) -> Result<DatabaseMetadata, reqwest::Error> { let url = self.api_url(&["database", &id.to_string(), "metadata"]); self.send_request(self.inner.get(url)).await } fn api_url(&self, endpoint: &[&str]) -> Url { let mut url = self.url.clone(); url.path_segments_mut() .expect("url validated on construction") .extend(endpoint); url } async fn send_request<T>(&self, mut req: reqwest::RequestBuilder) -> Result<T, reqwest::Error> where T: DeserializeOwned, { req = req.timeout(Duration::from_secs(5)); if let Some(session_id) = &self.session_id { req = req.header("X-Metabase-Session", session_id); } let res = req.send().await?.error_for_status()?; res.json().await } } /// A Metabase error. #[derive(Debug)] pub enum Error { /// The provided URL was invalid. InvalidUrl(String), /// The underlying transport mechanism returned na error. Transport(reqwest::Error), } impl From<reqwest::Error> for Error { fn from(e: reqwest::Error) -> Error { Error::Transport(e) } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error +'static)> { match self { Error::InvalidUrl(_) => None, Error::Transport(e) => Some(e), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::InvalidUrl(msg) => write!(f, "invalid url: {}", msg), Error::Transport(e) => write!(f, "transport: {}", e), } } } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] struct ListWrapper<T> { data: Vec<T>, } /// The response to [`Client::session_properties`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] #[serde(rename_all = "kebab-case")] pub struct SessionPropertiesResponse { pub setup_token: Option<String>, } /// The request for [`Client::setup`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct SetupRequest { pub allow_tracking: bool, pub database: SetupDatabase, pub token: String, pub prefs: SetupPrefs, pub user: SetupUser, } /// A database to create as part of a [`SetupRequest`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct SetupDatabase { pub engine: String, pub name: String, pub details: SetupDatabaseDetails, } /// Details for a [`SetupDatabase`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct SetupDatabaseDetails { pub host: String, pub port: usize, pub dbname: String, pub user: String, } /// Preferences for a [`SetupRequest`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct SetupPrefs { pub site_name: String, } /// A user to create as part of a [`SetupRequest`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct SetupUser { pub email: String, pub first_name: String, pub last_name: String, pub password: String, pub site_name: String, } /// The request for [`Client::login`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct LoginRequest { pub username: String, pub password: String, } /// The response to [`Client::login`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct LoginResponse { pub id: String, } /// A database returned by [`Client::databases`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct Database { pub name: String, pub id: usize, } /// The response to [`Client::database_metadata`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct DatabaseMetadata { pub tables: Vec<Table>, } /// A table that is part of [`DatabaseMetadata`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct Table {
/// A field of a [`Table`]. #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] pub struct TableField { pub name: String, pub database_type: String, pub base_type: String, pub special_type: Option<String>, }
pub name: String, pub schema: String, pub fields: Vec<TableField>, }
random_line_split
transaction.rs
use std::collections::HashMap; use std::hash::Hash; use std::ops::Range; use rusqlite::Connection; use ::serde::Serialize; use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime}; use crate::db::account_dao::AccountDao; use crate::db::transaction_dao::{Split, Transaction, TransactionDao}; use crate::db::account_dao::Account; use itertools::Itertools; fn parse_nd(s: &str) -> NaiveDate { let with_day = |s: &str| format!("{}-01", s); NaiveDate::parse_from_str(&with_day(&s.replace(" ", "")), "%Y-%m-%d").unwrap() } pub fn expense_splits( conn: &Connection, expense_name: String, month: String ) -> Vec<TranSplit> { let since_nd = parse_nd(&month); let until_nd = ( if (since_nd.month() == 12) { NaiveDate::from_ymd(since_nd.year() + 1, 1, 1) } else { NaiveDate::from_ymd(since_nd.year(), since_nd.month() + 1, 1) } ).pred(); let tran_dao = TransactionDao { conn: &conn }; let trans = tran_dao.list(&since_nd, &until_nd); let account_dao = AccountDao { conn: &conn }; let account = account_dao.list().into_iter().find(|acct| { acct.qualified_name() == expense_name }).unwrap(); // :(:( let mut splits = Vec::new(); for t in trans { for s in t.splits { if (s.account_guid == account.guid) { splits.push( TranSplit { account_guid: s.account_guid, transaction_guid: s.transaction_guid, value_num: s.value_num, memo: s.memo, date: t.post_date, description: t.description.clone(), }); } } } splits } #[derive(Debug)] #[derive(Serialize)] pub struct TranSplit { pub account_guid: String, pub transaction_guid: String, pub value_num: i64, pub memo: String, pub date: NaiveDateTime, pub description: String } pub fn list( conn: &Connection, since: Option<String>, until: Option<String>, months: Option<String>, year: Option<String> ) -> Vec<Transaction>
#[derive(Debug)] #[derive(Serialize)] pub struct MonthlyTotals { summaries: Vec<MonthTotal>, totalSpent: i64, pub acctSums: Vec<MonthlyExpenseGroup> } #[derive(Debug)] #[derive(Serialize)] pub struct AccountSummary { name: String, monthlyTotals: Vec<MonthlyTotal>, } #[derive(Debug)] #[derive(Serialize)] pub struct MonthlyTotal { month: NaiveDate, total: i64 } pub fn monthly_totals<'a>( conn: &Connection, since: Option<String>, until: Option<String>, months: Option<String>, year: Option<String> ) -> MonthlyTotals { let trans_dao = TransactionDao { conn: &conn }; let account_dao = AccountDao { conn: &conn }; let (since_nd, until_nd) = since_until(since, until, months, year); let trans = trans_dao.list(&since_nd, &until_nd); let mut accounts = account_dao.list(); let mut unfilled_months = expenses_by_month(&trans, &accounts); let mut months = fill_empty_months(&since_nd, &until_nd, &unfilled_months); months.sort_by(|a, b| b.total.cmp(&a.total)); let all_months = months.iter().flat_map(|m| &m.monthlyTotals); let grouped = group_by(all_months.collect::<Vec<_>>(), |m| m.month.clone()); let mut summed = grouped.into_iter().map(|(i, month_summary)| { MonthTotal { month: i, total: month_summary.into_iter().map(|m| m.total).sum() } }).collect::<Vec<_>>(); summed.sort_by(|a, b| parse_nd(&b.month).cmp(&parse_nd(&a.month))); let total_spent = summed.iter().map(|m| m.total).sum(); //let mut acct_sums = months.clone(); MonthlyTotals { summaries: summed, totalSpent: total_spent, acctSums: months.clone() } } // TODO need to understand the type option for 'function overloading' because // the following is not good fn since_until( since_p: Option<String>, until_p: Option<String>, mut months_p: Option<String>, // :(:( year_p: Option<String> ) -> (NaiveDate, NaiveDate) { let until = year_p.as_ref().map(|y| NaiveDate::from_ymd(y.parse::<i32>().unwrap(), 12, 31)) .unwrap_or({ until_p.map(|s| parse_nd(&s)).unwrap_or({ let now = Local::now().naive_local().date(); if (now.month() == 12) { NaiveDate::from_ymd(now.year(), 12, 31) } else { NaiveDate::from_ymd(now.year(), now.month() + 1, 1).pred() } }) }); months_p = year_p.map(|y| "12".to_string()).or(months_p); let since = since_p.map(|s| parse_nd(&s)).unwrap_or({ let months_since = months_p.map(|m| m.parse().unwrap()).unwrap_or(6); // yes I've (sort of) done the following twice, and it's crappy both times let mut curr_year = until.year(); let mut curr_month = until.month(); (0..months_since - 1).for_each(|i| { if curr_month == 1 { curr_year -= 1; curr_month = 12; } else { curr_month -= 1; }; }); NaiveDate::from_ymd(curr_year, curr_month, 1) }); (since, until) } fn months_between(since: &NaiveDate, until: &NaiveDate) -> u32 { let mut curr_year = until.year(); let mut curr_month = until.month(); let mut ctr = 0; while curr_year > since.year() || curr_year == since.year() && curr_month > since.month() { if curr_month == 1 { curr_year -= 1; curr_month = 12; } else { curr_month -= 1; }; ctr += 1; } ctr } fn fill_empty_months( since: &NaiveDate, until: &NaiveDate, expenses: &Vec<MonthlyExpenseGroup> ) -> Vec<MonthlyExpenseGroup> { // don't have moment like we do in node:( let mut curr_year = until.year(); let mut curr_month = until.month(); let num_months = months_between(since, until); let mut desired_months = (0..num_months).map(|i| { if curr_month == 1 { curr_year -= 1; curr_month = 12; } else { curr_month -= 1; }; NaiveDate::from_ymd(curr_year, curr_month, 1) }).collect::<Vec<_>>(); desired_months.insert(0, NaiveDate::from_ymd(until.year(), until.month(), 1)); let mut cloned_expenses = expenses.clone(); (0..cloned_expenses.len()).for_each(|i| { let mut exp = &mut cloned_expenses[i]; (0..num_months+1).for_each(|_j| { let j = _j as usize; let month_str = format_nd(desired_months[j]); let exp_month = exp.monthlyTotals.get(j).map(|mt| mt.clone()); if (exp_month.is_none() || month_str!= exp_month.unwrap().month) { exp.monthlyTotals.insert(j, MonthTotal { month: month_str, total: 0 }); } }); }); cloned_expenses } pub struct MonthlyExpense { name: String, date: NaiveDate, amount: i64, memo: String } struct ExpenseSplit { name: String, date: NaiveDateTime, amount: i64, memo: String } #[derive(Clone)] #[derive(Debug)] #[derive(Serialize)] struct MonthTotal { month: String, total: i64 } #[derive(Clone)] #[derive(Debug)] #[derive(Serialize)] pub struct MonthlyExpenseGroup { pub name: String, pub total: i64, monthlyTotals: Vec<MonthTotal>, } fn expenses_by_month( transactions: &Vec<Transaction>, accounts: &Vec<Account> ) -> Vec<MonthlyExpenseGroup> { let mut accounts_map = HashMap::new(); for a in accounts { accounts_map.insert(&a.guid, a); } // No need to fold/reduce here like we do in the node version. // That was probably just a mistake there. let mut splits = transactions.iter().flat_map(|tran| { let expenses = tran.splits.iter().filter(|s| accounts_map[&s.account_guid].is_expense()).collect::<Vec<&Split>>(); expenses.iter().map(|e| { ExpenseSplit { name: accounts_map[&e.account_guid].qualified_name(), date: tran.post_date, amount: e.value_num, memo: e.memo.clone() } }).collect::<Vec<_>>() }).collect::<Vec<_>>(); splits.sort_by(|a,b| a.name.cmp(&b.name)); let expense_groups = group_by(splits, |s| s.name.to_string()); let expense_groups_by_month = expense_groups.into_iter().map(|(name, exp_group)| { let mut start = HashMap::<String, Vec<ExpenseSplit>>::new(); let mut exp_splits = group_by(exp_group.into_iter().collect::<Vec<ExpenseSplit>>(), |item| { format_ndt(item.date) }).into_iter().collect::<Vec<_>>(); exp_splits.sort_by(|a,b| b.0.cmp(&a.0)); let monthly_totals = exp_splits.into_iter().map(|(month, splits)| { MonthTotal { month: month, total: splits.iter().map(|s| s.amount).sum() } }).collect::<Vec<_>>(); MonthlyExpenseGroup { name: name.to_string(), total: monthly_totals.iter().map(|mt| mt.total).sum(), monthlyTotals: monthly_totals } }); expense_groups_by_month.collect::<Vec<_>>() } fn format_ndt(d: NaiveDateTime) -> String { format_nd(d.date()) } fn format_nd(d: NaiveDate) -> String { let year = d.year(); let month = d.month(); format!("{}-{:02}", year, month) } pub fn group_by<T, K : Eq + Hash>(items: Vec<T>, to_key: fn(&T) -> K) -> HashMap<K, Vec<T>> { let mut start: HashMap<K, Vec<T>> = HashMap::new(); items.into_iter().for_each(|item| { let key = to_key(&item); let mut result = start.entry(key).or_insert(Vec::new()); result.push(item); }); start } #[cfg(test)] mod tests { use chrono::{Datelike, Local, NaiveDate}; #[test] fn since_until_with_year() { let year_param = Some("2017".to_string()); let (since, until) = super::since_until(None, None, None, year_param); assert_eq!(NaiveDate::from_ymd(2017, 1, 1), since); assert_eq!(NaiveDate::from_ymd(2017, 12, 31), until); } #[test] fn since_until_with_month() { let month_param = Some("1".to_string()); let (since, until) = super::since_until(None, None, month_param, None); let now = Local::now().naive_local().date(); let tup = |d:NaiveDate| (d.year(), d.month()); assert_eq!((tup(now), 0), (tup(since), 0)); assert_eq!(tup(now), tup(since)); // todo verify end day:( } #[test] fn since_until_december() { let since_param = Some("2017-12".to_string()); let (since, until) = super::since_until(since_param, None, None, None); assert_eq!(NaiveDate::from_ymd(2017, 12, 1), since); assert_eq!(NaiveDate::from_ymd(2019, 12, 31), until); } }
{ let (since_nd, until_nd) = since_until(since, until, months, year); let dao = TransactionDao { conn: &conn }; dao.list(&since_nd, &until_nd) }
identifier_body
transaction.rs
use std::collections::HashMap; use std::hash::Hash; use std::ops::Range; use rusqlite::Connection; use ::serde::Serialize; use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime}; use crate::db::account_dao::AccountDao; use crate::db::transaction_dao::{Split, Transaction, TransactionDao}; use crate::db::account_dao::Account; use itertools::Itertools; fn parse_nd(s: &str) -> NaiveDate { let with_day = |s: &str| format!("{}-01", s); NaiveDate::parse_from_str(&with_day(&s.replace(" ", "")), "%Y-%m-%d").unwrap() } pub fn expense_splits( conn: &Connection, expense_name: String, month: String ) -> Vec<TranSplit> { let since_nd = parse_nd(&month); let until_nd = ( if (since_nd.month() == 12) { NaiveDate::from_ymd(since_nd.year() + 1, 1, 1) } else { NaiveDate::from_ymd(since_nd.year(), since_nd.month() + 1, 1) } ).pred(); let tran_dao = TransactionDao { conn: &conn }; let trans = tran_dao.list(&since_nd, &until_nd); let account_dao = AccountDao { conn: &conn }; let account = account_dao.list().into_iter().find(|acct| { acct.qualified_name() == expense_name }).unwrap(); // :(:( let mut splits = Vec::new(); for t in trans { for s in t.splits { if (s.account_guid == account.guid) { splits.push( TranSplit { account_guid: s.account_guid, transaction_guid: s.transaction_guid, value_num: s.value_num, memo: s.memo, date: t.post_date, description: t.description.clone(), }); } } } splits } #[derive(Debug)] #[derive(Serialize)] pub struct TranSplit { pub account_guid: String, pub transaction_guid: String, pub value_num: i64, pub memo: String, pub date: NaiveDateTime, pub description: String } pub fn list( conn: &Connection, since: Option<String>, until: Option<String>, months: Option<String>, year: Option<String> ) -> Vec<Transaction> { let (since_nd, until_nd) = since_until(since, until, months, year); let dao = TransactionDao { conn: &conn }; dao.list(&since_nd, &until_nd) } #[derive(Debug)] #[derive(Serialize)] pub struct MonthlyTotals { summaries: Vec<MonthTotal>, totalSpent: i64, pub acctSums: Vec<MonthlyExpenseGroup> } #[derive(Debug)] #[derive(Serialize)] pub struct AccountSummary { name: String, monthlyTotals: Vec<MonthlyTotal>, } #[derive(Debug)] #[derive(Serialize)] pub struct MonthlyTotal { month: NaiveDate, total: i64 } pub fn monthly_totals<'a>( conn: &Connection, since: Option<String>, until: Option<String>, months: Option<String>, year: Option<String> ) -> MonthlyTotals { let trans_dao = TransactionDao { conn: &conn }; let account_dao = AccountDao { conn: &conn }; let (since_nd, until_nd) = since_until(since, until, months, year); let trans = trans_dao.list(&since_nd, &until_nd); let mut accounts = account_dao.list(); let mut unfilled_months = expenses_by_month(&trans, &accounts); let mut months = fill_empty_months(&since_nd, &until_nd, &unfilled_months); months.sort_by(|a, b| b.total.cmp(&a.total)); let all_months = months.iter().flat_map(|m| &m.monthlyTotals); let grouped = group_by(all_months.collect::<Vec<_>>(), |m| m.month.clone()); let mut summed = grouped.into_iter().map(|(i, month_summary)| { MonthTotal { month: i, total: month_summary.into_iter().map(|m| m.total).sum() } }).collect::<Vec<_>>(); summed.sort_by(|a, b| parse_nd(&b.month).cmp(&parse_nd(&a.month))); let total_spent = summed.iter().map(|m| m.total).sum(); //let mut acct_sums = months.clone(); MonthlyTotals { summaries: summed, totalSpent: total_spent, acctSums: months.clone() } } // TODO need to understand the type option for 'function overloading' because // the following is not good fn since_until( since_p: Option<String>, until_p: Option<String>, mut months_p: Option<String>, // :(:( year_p: Option<String> ) -> (NaiveDate, NaiveDate) { let until = year_p.as_ref().map(|y| NaiveDate::from_ymd(y.parse::<i32>().unwrap(), 12, 31)) .unwrap_or({ until_p.map(|s| parse_nd(&s)).unwrap_or({ let now = Local::now().naive_local().date(); if (now.month() == 12) { NaiveDate::from_ymd(now.year(), 12, 31) } else { NaiveDate::from_ymd(now.year(), now.month() + 1, 1).pred() } }) }); months_p = year_p.map(|y| "12".to_string()).or(months_p); let since = since_p.map(|s| parse_nd(&s)).unwrap_or({ let months_since = months_p.map(|m| m.parse().unwrap()).unwrap_or(6); // yes I've (sort of) done the following twice, and it's crappy both times let mut curr_year = until.year(); let mut curr_month = until.month(); (0..months_since - 1).for_each(|i| { if curr_month == 1 { curr_year -= 1; curr_month = 12; } else { curr_month -= 1; }; }); NaiveDate::from_ymd(curr_year, curr_month, 1) }); (since, until) } fn months_between(since: &NaiveDate, until: &NaiveDate) -> u32 { let mut curr_year = until.year(); let mut curr_month = until.month(); let mut ctr = 0; while curr_year > since.year() || curr_year == since.year() && curr_month > since.month() { if curr_month == 1 { curr_year -= 1; curr_month = 12; } else { curr_month -= 1; }; ctr += 1; } ctr } fn fill_empty_months( since: &NaiveDate, until: &NaiveDate, expenses: &Vec<MonthlyExpenseGroup> ) -> Vec<MonthlyExpenseGroup> { // don't have moment like we do in node:( let mut curr_year = until.year(); let mut curr_month = until.month(); let num_months = months_between(since, until); let mut desired_months = (0..num_months).map(|i| { if curr_month == 1 { curr_year -= 1; curr_month = 12; } else
; NaiveDate::from_ymd(curr_year, curr_month, 1) }).collect::<Vec<_>>(); desired_months.insert(0, NaiveDate::from_ymd(until.year(), until.month(), 1)); let mut cloned_expenses = expenses.clone(); (0..cloned_expenses.len()).for_each(|i| { let mut exp = &mut cloned_expenses[i]; (0..num_months+1).for_each(|_j| { let j = _j as usize; let month_str = format_nd(desired_months[j]); let exp_month = exp.monthlyTotals.get(j).map(|mt| mt.clone()); if (exp_month.is_none() || month_str!= exp_month.unwrap().month) { exp.monthlyTotals.insert(j, MonthTotal { month: month_str, total: 0 }); } }); }); cloned_expenses } pub struct MonthlyExpense { name: String, date: NaiveDate, amount: i64, memo: String } struct ExpenseSplit { name: String, date: NaiveDateTime, amount: i64, memo: String } #[derive(Clone)] #[derive(Debug)] #[derive(Serialize)] struct MonthTotal { month: String, total: i64 } #[derive(Clone)] #[derive(Debug)] #[derive(Serialize)] pub struct MonthlyExpenseGroup { pub name: String, pub total: i64, monthlyTotals: Vec<MonthTotal>, } fn expenses_by_month( transactions: &Vec<Transaction>, accounts: &Vec<Account> ) -> Vec<MonthlyExpenseGroup> { let mut accounts_map = HashMap::new(); for a in accounts { accounts_map.insert(&a.guid, a); } // No need to fold/reduce here like we do in the node version. // That was probably just a mistake there. let mut splits = transactions.iter().flat_map(|tran| { let expenses = tran.splits.iter().filter(|s| accounts_map[&s.account_guid].is_expense()).collect::<Vec<&Split>>(); expenses.iter().map(|e| { ExpenseSplit { name: accounts_map[&e.account_guid].qualified_name(), date: tran.post_date, amount: e.value_num, memo: e.memo.clone() } }).collect::<Vec<_>>() }).collect::<Vec<_>>(); splits.sort_by(|a,b| a.name.cmp(&b.name)); let expense_groups = group_by(splits, |s| s.name.to_string()); let expense_groups_by_month = expense_groups.into_iter().map(|(name, exp_group)| { let mut start = HashMap::<String, Vec<ExpenseSplit>>::new(); let mut exp_splits = group_by(exp_group.into_iter().collect::<Vec<ExpenseSplit>>(), |item| { format_ndt(item.date) }).into_iter().collect::<Vec<_>>(); exp_splits.sort_by(|a,b| b.0.cmp(&a.0)); let monthly_totals = exp_splits.into_iter().map(|(month, splits)| { MonthTotal { month: month, total: splits.iter().map(|s| s.amount).sum() } }).collect::<Vec<_>>(); MonthlyExpenseGroup { name: name.to_string(), total: monthly_totals.iter().map(|mt| mt.total).sum(), monthlyTotals: monthly_totals } }); expense_groups_by_month.collect::<Vec<_>>() } fn format_ndt(d: NaiveDateTime) -> String { format_nd(d.date()) } fn format_nd(d: NaiveDate) -> String { let year = d.year(); let month = d.month(); format!("{}-{:02}", year, month) } pub fn group_by<T, K : Eq + Hash>(items: Vec<T>, to_key: fn(&T) -> K) -> HashMap<K, Vec<T>> { let mut start: HashMap<K, Vec<T>> = HashMap::new(); items.into_iter().for_each(|item| { let key = to_key(&item); let mut result = start.entry(key).or_insert(Vec::new()); result.push(item); }); start } #[cfg(test)] mod tests { use chrono::{Datelike, Local, NaiveDate}; #[test] fn since_until_with_year() { let year_param = Some("2017".to_string()); let (since, until) = super::since_until(None, None, None, year_param); assert_eq!(NaiveDate::from_ymd(2017, 1, 1), since); assert_eq!(NaiveDate::from_ymd(2017, 12, 31), until); } #[test] fn since_until_with_month() { let month_param = Some("1".to_string()); let (since, until) = super::since_until(None, None, month_param, None); let now = Local::now().naive_local().date(); let tup = |d:NaiveDate| (d.year(), d.month()); assert_eq!((tup(now), 0), (tup(since), 0)); assert_eq!(tup(now), tup(since)); // todo verify end day:( } #[test] fn since_until_december() { let since_param = Some("2017-12".to_string()); let (since, until) = super::since_until(since_param, None, None, None); assert_eq!(NaiveDate::from_ymd(2017, 12, 1), since); assert_eq!(NaiveDate::from_ymd(2019, 12, 31), until); } }
{ curr_month -= 1; }
conditional_block
transaction.rs
use std::collections::HashMap; use std::hash::Hash; use std::ops::Range; use rusqlite::Connection; use ::serde::Serialize; use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime}; use crate::db::account_dao::AccountDao; use crate::db::transaction_dao::{Split, Transaction, TransactionDao}; use crate::db::account_dao::Account; use itertools::Itertools; fn parse_nd(s: &str) -> NaiveDate { let with_day = |s: &str| format!("{}-01", s); NaiveDate::parse_from_str(&with_day(&s.replace(" ", "")), "%Y-%m-%d").unwrap() } pub fn expense_splits( conn: &Connection, expense_name: String, month: String ) -> Vec<TranSplit> { let since_nd = parse_nd(&month); let until_nd = ( if (since_nd.month() == 12) { NaiveDate::from_ymd(since_nd.year() + 1, 1, 1) } else { NaiveDate::from_ymd(since_nd.year(), since_nd.month() + 1, 1) } ).pred(); let tran_dao = TransactionDao { conn: &conn }; let trans = tran_dao.list(&since_nd, &until_nd); let account_dao = AccountDao { conn: &conn }; let account = account_dao.list().into_iter().find(|acct| { acct.qualified_name() == expense_name }).unwrap(); // :(:( let mut splits = Vec::new(); for t in trans { for s in t.splits { if (s.account_guid == account.guid) { splits.push( TranSplit { account_guid: s.account_guid, transaction_guid: s.transaction_guid, value_num: s.value_num, memo: s.memo, date: t.post_date, description: t.description.clone(), }); } } } splits } #[derive(Debug)] #[derive(Serialize)] pub struct TranSplit { pub account_guid: String, pub transaction_guid: String, pub value_num: i64, pub memo: String, pub date: NaiveDateTime, pub description: String } pub fn list( conn: &Connection, since: Option<String>, until: Option<String>, months: Option<String>, year: Option<String> ) -> Vec<Transaction> { let (since_nd, until_nd) = since_until(since, until, months, year); let dao = TransactionDao { conn: &conn }; dao.list(&since_nd, &until_nd) } #[derive(Debug)] #[derive(Serialize)] pub struct MonthlyTotals { summaries: Vec<MonthTotal>, totalSpent: i64, pub acctSums: Vec<MonthlyExpenseGroup> } #[derive(Debug)] #[derive(Serialize)] pub struct AccountSummary { name: String, monthlyTotals: Vec<MonthlyTotal>, } #[derive(Debug)] #[derive(Serialize)] pub struct MonthlyTotal { month: NaiveDate, total: i64 } pub fn monthly_totals<'a>( conn: &Connection, since: Option<String>, until: Option<String>, months: Option<String>, year: Option<String> ) -> MonthlyTotals { let trans_dao = TransactionDao { conn: &conn }; let account_dao = AccountDao { conn: &conn }; let (since_nd, until_nd) = since_until(since, until, months, year); let trans = trans_dao.list(&since_nd, &until_nd); let mut accounts = account_dao.list(); let mut unfilled_months = expenses_by_month(&trans, &accounts); let mut months = fill_empty_months(&since_nd, &until_nd, &unfilled_months); months.sort_by(|a, b| b.total.cmp(&a.total)); let all_months = months.iter().flat_map(|m| &m.monthlyTotals); let grouped = group_by(all_months.collect::<Vec<_>>(), |m| m.month.clone()); let mut summed = grouped.into_iter().map(|(i, month_summary)| { MonthTotal { month: i, total: month_summary.into_iter().map(|m| m.total).sum() } }).collect::<Vec<_>>(); summed.sort_by(|a, b| parse_nd(&b.month).cmp(&parse_nd(&a.month))); let total_spent = summed.iter().map(|m| m.total).sum(); //let mut acct_sums = months.clone(); MonthlyTotals { summaries: summed, totalSpent: total_spent, acctSums: months.clone() } } // TODO need to understand the type option for 'function overloading' because // the following is not good fn since_until( since_p: Option<String>, until_p: Option<String>, mut months_p: Option<String>, // :(:( year_p: Option<String> ) -> (NaiveDate, NaiveDate) { let until = year_p.as_ref().map(|y| NaiveDate::from_ymd(y.parse::<i32>().unwrap(), 12, 31)) .unwrap_or({ until_p.map(|s| parse_nd(&s)).unwrap_or({ let now = Local::now().naive_local().date(); if (now.month() == 12) { NaiveDate::from_ymd(now.year(), 12, 31) } else { NaiveDate::from_ymd(now.year(), now.month() + 1, 1).pred() } }) }); months_p = year_p.map(|y| "12".to_string()).or(months_p); let since = since_p.map(|s| parse_nd(&s)).unwrap_or({ let months_since = months_p.map(|m| m.parse().unwrap()).unwrap_or(6); // yes I've (sort of) done the following twice, and it's crappy both times let mut curr_year = until.year(); let mut curr_month = until.month(); (0..months_since - 1).for_each(|i| { if curr_month == 1 { curr_year -= 1; curr_month = 12; } else { curr_month -= 1; }; }); NaiveDate::from_ymd(curr_year, curr_month, 1) }); (since, until) } fn months_between(since: &NaiveDate, until: &NaiveDate) -> u32 { let mut curr_year = until.year(); let mut curr_month = until.month(); let mut ctr = 0; while curr_year > since.year() || curr_year == since.year() && curr_month > since.month() { if curr_month == 1 { curr_year -= 1; curr_month = 12; } else { curr_month -= 1; }; ctr += 1; } ctr } fn fill_empty_months( since: &NaiveDate, until: &NaiveDate, expenses: &Vec<MonthlyExpenseGroup> ) -> Vec<MonthlyExpenseGroup> { // don't have moment like we do in node:( let mut curr_year = until.year(); let mut curr_month = until.month(); let num_months = months_between(since, until); let mut desired_months = (0..num_months).map(|i| { if curr_month == 1 { curr_year -= 1; curr_month = 12; } else { curr_month -= 1; }; NaiveDate::from_ymd(curr_year, curr_month, 1) }).collect::<Vec<_>>(); desired_months.insert(0, NaiveDate::from_ymd(until.year(), until.month(), 1)); let mut cloned_expenses = expenses.clone(); (0..cloned_expenses.len()).for_each(|i| { let mut exp = &mut cloned_expenses[i]; (0..num_months+1).for_each(|_j| { let j = _j as usize; let month_str = format_nd(desired_months[j]); let exp_month = exp.monthlyTotals.get(j).map(|mt| mt.clone()); if (exp_month.is_none() || month_str!= exp_month.unwrap().month) { exp.monthlyTotals.insert(j, MonthTotal { month: month_str, total: 0 }); } }); }); cloned_expenses } pub struct MonthlyExpense { name: String, date: NaiveDate, amount: i64, memo: String } struct ExpenseSplit { name: String, date: NaiveDateTime, amount: i64, memo: String } #[derive(Clone)] #[derive(Debug)] #[derive(Serialize)] struct MonthTotal { month: String, total: i64 } #[derive(Clone)] #[derive(Debug)] #[derive(Serialize)] pub struct
{ pub name: String, pub total: i64, monthlyTotals: Vec<MonthTotal>, } fn expenses_by_month( transactions: &Vec<Transaction>, accounts: &Vec<Account> ) -> Vec<MonthlyExpenseGroup> { let mut accounts_map = HashMap::new(); for a in accounts { accounts_map.insert(&a.guid, a); } // No need to fold/reduce here like we do in the node version. // That was probably just a mistake there. let mut splits = transactions.iter().flat_map(|tran| { let expenses = tran.splits.iter().filter(|s| accounts_map[&s.account_guid].is_expense()).collect::<Vec<&Split>>(); expenses.iter().map(|e| { ExpenseSplit { name: accounts_map[&e.account_guid].qualified_name(), date: tran.post_date, amount: e.value_num, memo: e.memo.clone() } }).collect::<Vec<_>>() }).collect::<Vec<_>>(); splits.sort_by(|a,b| a.name.cmp(&b.name)); let expense_groups = group_by(splits, |s| s.name.to_string()); let expense_groups_by_month = expense_groups.into_iter().map(|(name, exp_group)| { let mut start = HashMap::<String, Vec<ExpenseSplit>>::new(); let mut exp_splits = group_by(exp_group.into_iter().collect::<Vec<ExpenseSplit>>(), |item| { format_ndt(item.date) }).into_iter().collect::<Vec<_>>(); exp_splits.sort_by(|a,b| b.0.cmp(&a.0)); let monthly_totals = exp_splits.into_iter().map(|(month, splits)| { MonthTotal { month: month, total: splits.iter().map(|s| s.amount).sum() } }).collect::<Vec<_>>(); MonthlyExpenseGroup { name: name.to_string(), total: monthly_totals.iter().map(|mt| mt.total).sum(), monthlyTotals: monthly_totals } }); expense_groups_by_month.collect::<Vec<_>>() } fn format_ndt(d: NaiveDateTime) -> String { format_nd(d.date()) } fn format_nd(d: NaiveDate) -> String { let year = d.year(); let month = d.month(); format!("{}-{:02}", year, month) } pub fn group_by<T, K : Eq + Hash>(items: Vec<T>, to_key: fn(&T) -> K) -> HashMap<K, Vec<T>> { let mut start: HashMap<K, Vec<T>> = HashMap::new(); items.into_iter().for_each(|item| { let key = to_key(&item); let mut result = start.entry(key).or_insert(Vec::new()); result.push(item); }); start } #[cfg(test)] mod tests { use chrono::{Datelike, Local, NaiveDate}; #[test] fn since_until_with_year() { let year_param = Some("2017".to_string()); let (since, until) = super::since_until(None, None, None, year_param); assert_eq!(NaiveDate::from_ymd(2017, 1, 1), since); assert_eq!(NaiveDate::from_ymd(2017, 12, 31), until); } #[test] fn since_until_with_month() { let month_param = Some("1".to_string()); let (since, until) = super::since_until(None, None, month_param, None); let now = Local::now().naive_local().date(); let tup = |d:NaiveDate| (d.year(), d.month()); assert_eq!((tup(now), 0), (tup(since), 0)); assert_eq!(tup(now), tup(since)); // todo verify end day:( } #[test] fn since_until_december() { let since_param = Some("2017-12".to_string()); let (since, until) = super::since_until(since_param, None, None, None); assert_eq!(NaiveDate::from_ymd(2017, 12, 1), since); assert_eq!(NaiveDate::from_ymd(2019, 12, 31), until); } }
MonthlyExpenseGroup
identifier_name
transaction.rs
use std::collections::HashMap; use std::hash::Hash; use std::ops::Range; use rusqlite::Connection; use ::serde::Serialize; use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime}; use crate::db::account_dao::AccountDao; use crate::db::transaction_dao::{Split, Transaction, TransactionDao}; use crate::db::account_dao::Account; use itertools::Itertools; fn parse_nd(s: &str) -> NaiveDate { let with_day = |s: &str| format!("{}-01", s); NaiveDate::parse_from_str(&with_day(&s.replace(" ", "")), "%Y-%m-%d").unwrap() } pub fn expense_splits( conn: &Connection, expense_name: String, month: String ) -> Vec<TranSplit> { let since_nd = parse_nd(&month); let until_nd = ( if (since_nd.month() == 12) { NaiveDate::from_ymd(since_nd.year() + 1, 1, 1) } else { NaiveDate::from_ymd(since_nd.year(), since_nd.month() + 1, 1) } ).pred(); let tran_dao = TransactionDao { conn: &conn }; let trans = tran_dao.list(&since_nd, &until_nd); let account_dao = AccountDao { conn: &conn }; let account = account_dao.list().into_iter().find(|acct| { acct.qualified_name() == expense_name }).unwrap(); // :(:( let mut splits = Vec::new(); for t in trans { for s in t.splits { if (s.account_guid == account.guid) { splits.push( TranSplit { account_guid: s.account_guid, transaction_guid: s.transaction_guid, value_num: s.value_num, memo: s.memo, date: t.post_date, description: t.description.clone(), }); } } } splits } #[derive(Debug)] #[derive(Serialize)] pub struct TranSplit { pub account_guid: String, pub transaction_guid: String, pub value_num: i64, pub memo: String, pub date: NaiveDateTime, pub description: String } pub fn list( conn: &Connection, since: Option<String>, until: Option<String>, months: Option<String>, year: Option<String> ) -> Vec<Transaction> { let (since_nd, until_nd) = since_until(since, until, months, year); let dao = TransactionDao { conn: &conn }; dao.list(&since_nd, &until_nd) } #[derive(Debug)] #[derive(Serialize)] pub struct MonthlyTotals { summaries: Vec<MonthTotal>, totalSpent: i64, pub acctSums: Vec<MonthlyExpenseGroup> } #[derive(Debug)] #[derive(Serialize)] pub struct AccountSummary { name: String, monthlyTotals: Vec<MonthlyTotal>, } #[derive(Debug)] #[derive(Serialize)] pub struct MonthlyTotal { month: NaiveDate, total: i64 } pub fn monthly_totals<'a>( conn: &Connection, since: Option<String>, until: Option<String>, months: Option<String>, year: Option<String> ) -> MonthlyTotals { let trans_dao = TransactionDao { conn: &conn }; let account_dao = AccountDao { conn: &conn }; let (since_nd, until_nd) = since_until(since, until, months, year); let trans = trans_dao.list(&since_nd, &until_nd); let mut accounts = account_dao.list(); let mut unfilled_months = expenses_by_month(&trans, &accounts); let mut months = fill_empty_months(&since_nd, &until_nd, &unfilled_months); months.sort_by(|a, b| b.total.cmp(&a.total)); let all_months = months.iter().flat_map(|m| &m.monthlyTotals); let grouped = group_by(all_months.collect::<Vec<_>>(), |m| m.month.clone()); let mut summed = grouped.into_iter().map(|(i, month_summary)| { MonthTotal {
}).collect::<Vec<_>>(); summed.sort_by(|a, b| parse_nd(&b.month).cmp(&parse_nd(&a.month))); let total_spent = summed.iter().map(|m| m.total).sum(); //let mut acct_sums = months.clone(); MonthlyTotals { summaries: summed, totalSpent: total_spent, acctSums: months.clone() } } // TODO need to understand the type option for 'function overloading' because // the following is not good fn since_until( since_p: Option<String>, until_p: Option<String>, mut months_p: Option<String>, // :(:( year_p: Option<String> ) -> (NaiveDate, NaiveDate) { let until = year_p.as_ref().map(|y| NaiveDate::from_ymd(y.parse::<i32>().unwrap(), 12, 31)) .unwrap_or({ until_p.map(|s| parse_nd(&s)).unwrap_or({ let now = Local::now().naive_local().date(); if (now.month() == 12) { NaiveDate::from_ymd(now.year(), 12, 31) } else { NaiveDate::from_ymd(now.year(), now.month() + 1, 1).pred() } }) }); months_p = year_p.map(|y| "12".to_string()).or(months_p); let since = since_p.map(|s| parse_nd(&s)).unwrap_or({ let months_since = months_p.map(|m| m.parse().unwrap()).unwrap_or(6); // yes I've (sort of) done the following twice, and it's crappy both times let mut curr_year = until.year(); let mut curr_month = until.month(); (0..months_since - 1).for_each(|i| { if curr_month == 1 { curr_year -= 1; curr_month = 12; } else { curr_month -= 1; }; }); NaiveDate::from_ymd(curr_year, curr_month, 1) }); (since, until) } fn months_between(since: &NaiveDate, until: &NaiveDate) -> u32 { let mut curr_year = until.year(); let mut curr_month = until.month(); let mut ctr = 0; while curr_year > since.year() || curr_year == since.year() && curr_month > since.month() { if curr_month == 1 { curr_year -= 1; curr_month = 12; } else { curr_month -= 1; }; ctr += 1; } ctr } fn fill_empty_months( since: &NaiveDate, until: &NaiveDate, expenses: &Vec<MonthlyExpenseGroup> ) -> Vec<MonthlyExpenseGroup> { // don't have moment like we do in node:( let mut curr_year = until.year(); let mut curr_month = until.month(); let num_months = months_between(since, until); let mut desired_months = (0..num_months).map(|i| { if curr_month == 1 { curr_year -= 1; curr_month = 12; } else { curr_month -= 1; }; NaiveDate::from_ymd(curr_year, curr_month, 1) }).collect::<Vec<_>>(); desired_months.insert(0, NaiveDate::from_ymd(until.year(), until.month(), 1)); let mut cloned_expenses = expenses.clone(); (0..cloned_expenses.len()).for_each(|i| { let mut exp = &mut cloned_expenses[i]; (0..num_months+1).for_each(|_j| { let j = _j as usize; let month_str = format_nd(desired_months[j]); let exp_month = exp.monthlyTotals.get(j).map(|mt| mt.clone()); if (exp_month.is_none() || month_str!= exp_month.unwrap().month) { exp.monthlyTotals.insert(j, MonthTotal { month: month_str, total: 0 }); } }); }); cloned_expenses } pub struct MonthlyExpense { name: String, date: NaiveDate, amount: i64, memo: String } struct ExpenseSplit { name: String, date: NaiveDateTime, amount: i64, memo: String } #[derive(Clone)] #[derive(Debug)] #[derive(Serialize)] struct MonthTotal { month: String, total: i64 } #[derive(Clone)] #[derive(Debug)] #[derive(Serialize)] pub struct MonthlyExpenseGroup { pub name: String, pub total: i64, monthlyTotals: Vec<MonthTotal>, } fn expenses_by_month( transactions: &Vec<Transaction>, accounts: &Vec<Account> ) -> Vec<MonthlyExpenseGroup> { let mut accounts_map = HashMap::new(); for a in accounts { accounts_map.insert(&a.guid, a); } // No need to fold/reduce here like we do in the node version. // That was probably just a mistake there. let mut splits = transactions.iter().flat_map(|tran| { let expenses = tran.splits.iter().filter(|s| accounts_map[&s.account_guid].is_expense()).collect::<Vec<&Split>>(); expenses.iter().map(|e| { ExpenseSplit { name: accounts_map[&e.account_guid].qualified_name(), date: tran.post_date, amount: e.value_num, memo: e.memo.clone() } }).collect::<Vec<_>>() }).collect::<Vec<_>>(); splits.sort_by(|a,b| a.name.cmp(&b.name)); let expense_groups = group_by(splits, |s| s.name.to_string()); let expense_groups_by_month = expense_groups.into_iter().map(|(name, exp_group)| { let mut start = HashMap::<String, Vec<ExpenseSplit>>::new(); let mut exp_splits = group_by(exp_group.into_iter().collect::<Vec<ExpenseSplit>>(), |item| { format_ndt(item.date) }).into_iter().collect::<Vec<_>>(); exp_splits.sort_by(|a,b| b.0.cmp(&a.0)); let monthly_totals = exp_splits.into_iter().map(|(month, splits)| { MonthTotal { month: month, total: splits.iter().map(|s| s.amount).sum() } }).collect::<Vec<_>>(); MonthlyExpenseGroup { name: name.to_string(), total: monthly_totals.iter().map(|mt| mt.total).sum(), monthlyTotals: monthly_totals } }); expense_groups_by_month.collect::<Vec<_>>() } fn format_ndt(d: NaiveDateTime) -> String { format_nd(d.date()) } fn format_nd(d: NaiveDate) -> String { let year = d.year(); let month = d.month(); format!("{}-{:02}", year, month) } pub fn group_by<T, K : Eq + Hash>(items: Vec<T>, to_key: fn(&T) -> K) -> HashMap<K, Vec<T>> { let mut start: HashMap<K, Vec<T>> = HashMap::new(); items.into_iter().for_each(|item| { let key = to_key(&item); let mut result = start.entry(key).or_insert(Vec::new()); result.push(item); }); start } #[cfg(test)] mod tests { use chrono::{Datelike, Local, NaiveDate}; #[test] fn since_until_with_year() { let year_param = Some("2017".to_string()); let (since, until) = super::since_until(None, None, None, year_param); assert_eq!(NaiveDate::from_ymd(2017, 1, 1), since); assert_eq!(NaiveDate::from_ymd(2017, 12, 31), until); } #[test] fn since_until_with_month() { let month_param = Some("1".to_string()); let (since, until) = super::since_until(None, None, month_param, None); let now = Local::now().naive_local().date(); let tup = |d:NaiveDate| (d.year(), d.month()); assert_eq!((tup(now), 0), (tup(since), 0)); assert_eq!(tup(now), tup(since)); // todo verify end day:( } #[test] fn since_until_december() { let since_param = Some("2017-12".to_string()); let (since, until) = super::since_until(since_param, None, None, None); assert_eq!(NaiveDate::from_ymd(2017, 12, 1), since); assert_eq!(NaiveDate::from_ymd(2019, 12, 31), until); } }
month: i, total: month_summary.into_iter().map(|m| m.total).sum() }
random_line_split
glyph_brush.rs
mod builder; pub use self::builder::*; use super::*; use full_rusttype::gpu_cache::Cache; use hashbrown::hash_map::Entry; use log::error; use std::{ borrow::Cow, fmt, hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}, i32, }; /// A hash of `Section` data type SectionHash = u64; /// A "practically collision free" `Section` hasher type DefaultSectionHasher = BuildHasherDefault<seahash::SeaHasher>; /// Object allowing glyph drawing, containing cache state. Manages glyph positioning cacheing, /// glyph draw caching & efficient GPU texture cache updating. /// /// Build using a [`GlyphBrushBuilder`](struct.GlyphBrushBuilder.html). /// /// # Caching behaviour /// /// Calls to [`GlyphBrush::queue`](#method.queue), /// [`GlyphBrush::pixel_bounds`](#method.pixel_bounds), [`GlyphBrush::glyphs`](#method.glyphs) /// calculate the positioned glyphs for a section. /// This is cached so future calls to any of the methods for the same section are much /// cheaper. In the case of [`GlyphBrush::queue`](#method.queue) the calculations will also be /// used for actual drawing. /// /// The cache for a section will be **cleared** after a /// [`GlyphBrush::process_queued`](#method.process_queued) call when that section has not been used /// since the previous call. pub struct GlyphBrush<'font, H = DefaultSectionHasher> { fonts: Vec<Font<'font>>, texture_cache: Cache<'font>, last_draw: LastDrawInfo, // cache of section-layout hash -> computed glyphs, this avoid repeated glyph computation // for identical layout/sections common to repeated frame rendering calculate_glyph_cache: hashbrown::HashMap<SectionHash, GlyphedSection<'font>>, // buffer of section-layout hashs (that must exist in the calculate_glyph_cache) // to be used on the next `process_queued` call section_buffer: Vec<SectionHash>, // Set of section hashs to keep in the glyph cache this frame even if they haven't been drawn keep_in_cache: hashbrown::HashSet<SectionHash>, // config cache_glyph_positioning: bool, cache_glyph_drawing: bool, section_hasher: H, } impl<H> fmt::Debug for GlyphBrush<'_, H> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "GlyphBrush") } } impl<'font, H: BuildHasher> GlyphCruncher<'font> for GlyphBrush<'font, H> { fn pixel_bounds_custom_layout<'a, S, L>( &mut self, section: S, custom_layout: &L, ) -> Option<Rect<i32>> where L: GlyphPositioner + Hash, S: Into<Cow<'a, VariedSection<'a>>>, { let section_hash = self.cache_glyphs(&section.into(), custom_layout); self.keep_in_cache.insert(section_hash); self.calculate_glyph_cache[&section_hash].pixel_bounds() } fn glyphs_custom_layout<'a, 'b, S, L>( &'b mut self, section: S, custom_layout: &L, ) -> PositionedGlyphIter<'b, 'font> where L: GlyphPositioner + Hash, S: Into<Cow<'a, VariedSection<'a>>>, { let section_hash = self.cache_glyphs(&section.into(), custom_layout); self.keep_in_cache.insert(section_hash); self.calculate_glyph_cache[&section_hash].glyphs() } fn fonts(&self) -> &[Font<'font>] { &self.fonts } } impl<'font, H: BuildHasher> GlyphBrush<'font, H> { /// Queues a section/layout to be processed by the next call of /// [`process_queued`](struct.GlyphBrush.html#method.process_queued). Can be called multiple /// times to queue multiple sections for drawing. /// /// Used to provide custom `GlyphPositioner` logic, if using built-in /// [`Layout`](enum.Layout.html) simply use [`queue`](struct.GlyphBrush.html#method.queue) /// /// Benefits from caching, see [caching behaviour](#caching-behaviour). pub fn queue_custom_layout<'a, S, G>(&mut self, section: S, custom_layout: &G) where G: GlyphPositioner, S: Into<Cow<'a, VariedSection<'a>>>, { let section = section.into(); if cfg!(debug_assertions) { for text in &section.text { assert!(self.fonts.len() > text.font_id.0, "Invalid font id"); } } let section_hash = self.cache_glyphs(&section, custom_layout); self.section_buffer.push(section_hash); } /// Queues a section/layout to be processed by the next call of /// [`process_queued`](struct.GlyphBrush.html#method.process_queued). Can be called multiple /// times to queue multiple sections for drawing. /// /// Benefits from caching, see [caching behaviour](#caching-behaviour). /// /// ```no_run /// # use glyph_brush::*; /// # let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// glyph_brush.queue(Section { /// text: "Hello glyph_brush", /// ..Section::default() /// }); /// ``` pub fn queue<'a, S>(&mut self, section: S) where S: Into<Cow<'a, VariedSection<'a>>>, { profile_scope!("glyph_brush_queue"); let section = section.into(); let layout = section.layout; self.queue_custom_layout(section, &layout) } #[inline] fn hash<T: Hash>(&self, hashable: &T) -> SectionHash { let mut s = self.section_hasher.build_hasher(); hashable.hash(&mut s); s.finish() } /// Returns the calculate_glyph_cache key for this sections glyphs fn cache_glyphs<L>(&mut self, section: &VariedSection<'_>, layout: &L) -> SectionHash where L: GlyphPositioner, { profile_scope!("glyph_brush_cache_glyphs"); let section_hash = self.hash(&(section, layout)); if self.cache_glyph_positioning { if let Entry::Vacant(entry) = self.calculate_glyph_cache.entry(section_hash) { let geometry = SectionGeometry::from(section); entry.insert(GlyphedSection { bounds: layout.bounds_rect(&geometry), glyphs: layout.calculate_glyphs(&self.fonts, &geometry, &section.text), z: section.z, }); } } else { let geometry = SectionGeometry::from(section); self.calculate_glyph_cache.insert( section_hash, GlyphedSection { bounds: layout.bounds_rect(&geometry), glyphs: layout.calculate_glyphs(&self.fonts, &geometry, &section.text), z: section.z, }, ); } section_hash } /// Processes all queued sections, calling texture update logic when necessary & /// returning a `BrushAction`. /// See [`queue`](struct.GlyphBrush.html#method.queue). /// /// Two closures are required: /// * `update_texture` is called when new glyph texture data has been drawn for update in the /// actual texture. /// The arguments are the rect position of the data in the texture & the byte data itself /// which is a single `u8` alpha value per pixel. /// * `to_vertex` maps a single glyph's `GlyphVertex` data into a generic vertex type. The /// mapped vertices are returned in an `Ok(BrushAction::Draw(vertices))` result. /// It's recommended to use a single vertex per glyph quad for best performance. /// /// Trims the cache, see [caching behaviour](#caching-behaviour). /// /// ```no_run /// # use glyph_brush::*; /// # fn main() -> Result<(), BrushError> { /// # let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// # let update_texture = |_, _| {}; /// # let into_vertex = |_| (); /// glyph_brush.process_queued( /// (1024, 768), /// |rect, tex_data| update_texture(rect, tex_data), /// |vertex_data| into_vertex(vertex_data), /// )? /// # ; /// # Ok(()) /// # } /// ``` pub fn process_queued<V, F1, F2>( &mut self, (screen_w, screen_h): (u32, u32), update_texture: F1, to_vertex: F2, ) -> Result<BrushAction<V>, BrushError> where F1: FnMut(Rect<u32>, &[u8]), F2: Fn(GlyphVertex) -> V, { profile_scope!("glyph_brush_process_queue"); let current_text_state = self.hash(&(&self.section_buffer, screen_w, screen_h)); let result = if!self.cache_glyph_drawing || self.last_draw.text_state!= current_text_state { let mut some_text = false; for section_hash in &self.section_buffer { let GlyphedSection { ref glyphs,.. } = self.calculate_glyph_cache[section_hash]; for &(ref glyph, _, font_id) in glyphs { self.texture_cache.queue_glyph(font_id.0, glyph.clone()); some_text = true; } } if some_text && self.texture_cache.cache_queued(update_texture).is_err() { let (width, height) = self.texture_cache.dimensions(); return Err(BrushError::TextureTooSmall { suggested: (width * 2, height * 2), }); } let verts: Vec<V> = if some_text { let sections: Vec<_> = self .section_buffer .iter() .map(|hash| &self.calculate_glyph_cache[hash]) .collect(); let mut verts = Vec::with_capacity( sections .iter() .map(|section| section.glyphs.len()) .sum::<usize>(), ); for &GlyphedSection { ref glyphs, bounds, z, } in sections { verts.extend(glyphs.iter().filter_map(|(glyph, color, font_id)| { match self.texture_cache.rect_for(font_id.0, glyph) { Err(err) => { error!("Cache miss?: {:?}, {:?}: {}", font_id, glyph, err);
Ok(None) => None, Ok(Some((tex_coords, pixel_coords))) => { if pixel_coords.min.x as f32 > bounds.max.x || pixel_coords.min.y as f32 > bounds.max.y || bounds.min.x > pixel_coords.max.x as f32 || bounds.min.y > pixel_coords.max.y as f32 { // glyph is totally outside the bounds None } else { Some(to_vertex(GlyphVertex { tex_coords, pixel_coords, bounds, screen_dimensions: (screen_w as f32, screen_h as f32), color: *color, z, })) } } } })); } verts } else { vec![] }; self.last_draw.text_state = current_text_state; BrushAction::Draw(verts) } else { BrushAction::ReDraw }; self.clear_section_buffer(); Ok(result) } /// Rebuilds the logical texture cache with new dimensions. Should be avoided if possible. /// /// # Example /// /// ```no_run /// # use glyph_brush::GlyphBrushBuilder; /// # let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// glyph_brush.resize_texture(512, 512); /// ``` pub fn resize_texture(&mut self, new_width: u32, new_height: u32) { self.texture_cache .to_builder() .dimensions(new_width, new_height) .rebuild(&mut self.texture_cache); self.last_draw = LastDrawInfo::default(); } /// Returns the logical texture cache pixel dimensions `(width, height)`. pub fn texture_dimensions(&self) -> (u32, u32) { self.texture_cache.dimensions() } fn clear_section_buffer(&mut self) { if self.cache_glyph_positioning { // clear section_buffer & trim calculate_glyph_cache to active sections let active: hashbrown::HashSet<_> = self .section_buffer .drain(..) .chain(self.keep_in_cache.drain()) .collect(); self.calculate_glyph_cache .retain(|key, _| active.contains(key)); } else { self.section_buffer.clear(); self.calculate_glyph_cache.clear(); self.keep_in_cache.clear(); } } /// Adds an additional font to the one(s) initially added on build. /// /// Returns a new [`FontId`](struct.FontId.html) to reference this font. /// /// # Example /// /// ```no_run /// use glyph_brush::{GlyphBrushBuilder, Section}; /// # fn main() { /// /// // dejavu is built as default `FontId(0)` /// let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// /// // some time later, add another font referenced by a new `FontId` /// let open_sans_italic: &[u8] = include_bytes!("../../fonts/OpenSans-Italic.ttf"); /// let open_sans_italic_id = glyph_brush.add_font_bytes(open_sans_italic); /// # } /// ``` pub fn add_font_bytes<'a: 'font, B: Into<SharedBytes<'a>>>(&mut self, font_data: B) -> FontId { self.add_font(Font::from_bytes(font_data.into()).unwrap()) } /// Adds an additional font to the one(s) initially added on build. /// /// Returns a new [`FontId`](struct.FontId.html) to reference this font. pub fn add_font<'a: 'font>(&mut self, font_data: Font<'a>) -> FontId { self.fonts.push(font_data); FontId(self.fonts.len() - 1) } /// Retains the section in the cache as if it had been used in the last draw-frame. /// /// Should not generally be necessary, see [caching behaviour](#caching-behaviour). pub fn keep_cached_custom_layout<'a, S, G>(&mut self, section: S, custom_layout: &G) where S: Into<Cow<'a, VariedSection<'a>>>, G: GlyphPositioner, { if!self.cache_glyph_positioning { return; } let section = section.into(); if cfg!(debug_assertions) { for text in &section.text { assert!(self.fonts.len() > text.font_id.0, "Invalid font id"); } } self.keep_in_cache .insert(self.hash(&(section, custom_layout))); } /// Retains the section in the cache as if it had been used in the last draw-frame. /// /// Should not generally be necessary, see [caching behaviour](#caching-behaviour). pub fn keep_cached<'a, S>(&mut self, section: S) where S: Into<Cow<'a, VariedSection<'a>>>, { let section = section.into(); let layout = section.layout; self.keep_cached_custom_layout(section, &layout); } } #[derive(Debug, Default)] struct LastDrawInfo { text_state: u64, } // glyph: &PositionedGlyph, // color: Color, // font_id: FontId, // cache: &Cache, // bounds: Rect<f32>, // z: f32, // (screen_width, screen_height): (f32, f32), /// Data used to generate vertex information for a single glyph #[derive(Debug)] pub struct GlyphVertex { pub tex_coords: Rect<f32>, pub pixel_coords: Rect<i32>, pub bounds: Rect<f32>, pub screen_dimensions: (f32, f32), pub color: Color, pub z: f32, } /// Actions that should be taken after processing queue data pub enum BrushAction<V> { /// Draw new/changed vertix data. Draw(Vec<V>), /// Re-draw last frame's vertices unmodified. ReDraw, } #[derive(Debug)] pub enum BrushError { /// Texture is too small to cache queued glyphs /// /// A larger suggested size is included. TextureTooSmall { suggested: (u32, u32) }, } impl fmt::Display for BrushError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", std::error::Error::description(self)) } } impl std::error::Error for BrushError { fn description(&self) -> &str { match self { BrushError::TextureTooSmall {.. } => "Texture is too small to cache queued glyphs", } } }
None }
random_line_split
glyph_brush.rs
mod builder; pub use self::builder::*; use super::*; use full_rusttype::gpu_cache::Cache; use hashbrown::hash_map::Entry; use log::error; use std::{ borrow::Cow, fmt, hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}, i32, }; /// A hash of `Section` data type SectionHash = u64; /// A "practically collision free" `Section` hasher type DefaultSectionHasher = BuildHasherDefault<seahash::SeaHasher>; /// Object allowing glyph drawing, containing cache state. Manages glyph positioning cacheing, /// glyph draw caching & efficient GPU texture cache updating. /// /// Build using a [`GlyphBrushBuilder`](struct.GlyphBrushBuilder.html). /// /// # Caching behaviour /// /// Calls to [`GlyphBrush::queue`](#method.queue), /// [`GlyphBrush::pixel_bounds`](#method.pixel_bounds), [`GlyphBrush::glyphs`](#method.glyphs) /// calculate the positioned glyphs for a section. /// This is cached so future calls to any of the methods for the same section are much /// cheaper. In the case of [`GlyphBrush::queue`](#method.queue) the calculations will also be /// used for actual drawing. /// /// The cache for a section will be **cleared** after a /// [`GlyphBrush::process_queued`](#method.process_queued) call when that section has not been used /// since the previous call. pub struct GlyphBrush<'font, H = DefaultSectionHasher> { fonts: Vec<Font<'font>>, texture_cache: Cache<'font>, last_draw: LastDrawInfo, // cache of section-layout hash -> computed glyphs, this avoid repeated glyph computation // for identical layout/sections common to repeated frame rendering calculate_glyph_cache: hashbrown::HashMap<SectionHash, GlyphedSection<'font>>, // buffer of section-layout hashs (that must exist in the calculate_glyph_cache) // to be used on the next `process_queued` call section_buffer: Vec<SectionHash>, // Set of section hashs to keep in the glyph cache this frame even if they haven't been drawn keep_in_cache: hashbrown::HashSet<SectionHash>, // config cache_glyph_positioning: bool, cache_glyph_drawing: bool, section_hasher: H, } impl<H> fmt::Debug for GlyphBrush<'_, H> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "GlyphBrush") } } impl<'font, H: BuildHasher> GlyphCruncher<'font> for GlyphBrush<'font, H> { fn pixel_bounds_custom_layout<'a, S, L>( &mut self, section: S, custom_layout: &L, ) -> Option<Rect<i32>> where L: GlyphPositioner + Hash, S: Into<Cow<'a, VariedSection<'a>>>, { let section_hash = self.cache_glyphs(&section.into(), custom_layout); self.keep_in_cache.insert(section_hash); self.calculate_glyph_cache[&section_hash].pixel_bounds() } fn glyphs_custom_layout<'a, 'b, S, L>( &'b mut self, section: S, custom_layout: &L, ) -> PositionedGlyphIter<'b, 'font> where L: GlyphPositioner + Hash, S: Into<Cow<'a, VariedSection<'a>>>, { let section_hash = self.cache_glyphs(&section.into(), custom_layout); self.keep_in_cache.insert(section_hash); self.calculate_glyph_cache[&section_hash].glyphs() } fn fonts(&self) -> &[Font<'font>] { &self.fonts } } impl<'font, H: BuildHasher> GlyphBrush<'font, H> { /// Queues a section/layout to be processed by the next call of /// [`process_queued`](struct.GlyphBrush.html#method.process_queued). Can be called multiple /// times to queue multiple sections for drawing. /// /// Used to provide custom `GlyphPositioner` logic, if using built-in /// [`Layout`](enum.Layout.html) simply use [`queue`](struct.GlyphBrush.html#method.queue) /// /// Benefits from caching, see [caching behaviour](#caching-behaviour). pub fn queue_custom_layout<'a, S, G>(&mut self, section: S, custom_layout: &G) where G: GlyphPositioner, S: Into<Cow<'a, VariedSection<'a>>>, { let section = section.into(); if cfg!(debug_assertions) { for text in &section.text { assert!(self.fonts.len() > text.font_id.0, "Invalid font id"); } } let section_hash = self.cache_glyphs(&section, custom_layout); self.section_buffer.push(section_hash); } /// Queues a section/layout to be processed by the next call of /// [`process_queued`](struct.GlyphBrush.html#method.process_queued). Can be called multiple /// times to queue multiple sections for drawing. /// /// Benefits from caching, see [caching behaviour](#caching-behaviour). /// /// ```no_run /// # use glyph_brush::*; /// # let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// glyph_brush.queue(Section { /// text: "Hello glyph_brush", /// ..Section::default() /// }); /// ``` pub fn queue<'a, S>(&mut self, section: S) where S: Into<Cow<'a, VariedSection<'a>>>, { profile_scope!("glyph_brush_queue"); let section = section.into(); let layout = section.layout; self.queue_custom_layout(section, &layout) } #[inline] fn hash<T: Hash>(&self, hashable: &T) -> SectionHash { let mut s = self.section_hasher.build_hasher(); hashable.hash(&mut s); s.finish() } /// Returns the calculate_glyph_cache key for this sections glyphs fn cache_glyphs<L>(&mut self, section: &VariedSection<'_>, layout: &L) -> SectionHash where L: GlyphPositioner, { profile_scope!("glyph_brush_cache_glyphs"); let section_hash = self.hash(&(section, layout)); if self.cache_glyph_positioning { if let Entry::Vacant(entry) = self.calculate_glyph_cache.entry(section_hash) { let geometry = SectionGeometry::from(section); entry.insert(GlyphedSection { bounds: layout.bounds_rect(&geometry), glyphs: layout.calculate_glyphs(&self.fonts, &geometry, &section.text), z: section.z, }); } } else { let geometry = SectionGeometry::from(section); self.calculate_glyph_cache.insert( section_hash, GlyphedSection { bounds: layout.bounds_rect(&geometry), glyphs: layout.calculate_glyphs(&self.fonts, &geometry, &section.text), z: section.z, }, ); } section_hash } /// Processes all queued sections, calling texture update logic when necessary & /// returning a `BrushAction`. /// See [`queue`](struct.GlyphBrush.html#method.queue). /// /// Two closures are required: /// * `update_texture` is called when new glyph texture data has been drawn for update in the /// actual texture. /// The arguments are the rect position of the data in the texture & the byte data itself /// which is a single `u8` alpha value per pixel. /// * `to_vertex` maps a single glyph's `GlyphVertex` data into a generic vertex type. The /// mapped vertices are returned in an `Ok(BrushAction::Draw(vertices))` result. /// It's recommended to use a single vertex per glyph quad for best performance. /// /// Trims the cache, see [caching behaviour](#caching-behaviour). /// /// ```no_run /// # use glyph_brush::*; /// # fn main() -> Result<(), BrushError> { /// # let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// # let update_texture = |_, _| {}; /// # let into_vertex = |_| (); /// glyph_brush.process_queued( /// (1024, 768), /// |rect, tex_data| update_texture(rect, tex_data), /// |vertex_data| into_vertex(vertex_data), /// )? /// # ; /// # Ok(()) /// # } /// ``` pub fn process_queued<V, F1, F2>( &mut self, (screen_w, screen_h): (u32, u32), update_texture: F1, to_vertex: F2, ) -> Result<BrushAction<V>, BrushError> where F1: FnMut(Rect<u32>, &[u8]), F2: Fn(GlyphVertex) -> V, { profile_scope!("glyph_brush_process_queue"); let current_text_state = self.hash(&(&self.section_buffer, screen_w, screen_h)); let result = if!self.cache_glyph_drawing || self.last_draw.text_state!= current_text_state { let mut some_text = false; for section_hash in &self.section_buffer { let GlyphedSection { ref glyphs,.. } = self.calculate_glyph_cache[section_hash]; for &(ref glyph, _, font_id) in glyphs { self.texture_cache.queue_glyph(font_id.0, glyph.clone()); some_text = true; } } if some_text && self.texture_cache.cache_queued(update_texture).is_err()
let verts: Vec<V> = if some_text { let sections: Vec<_> = self .section_buffer .iter() .map(|hash| &self.calculate_glyph_cache[hash]) .collect(); let mut verts = Vec::with_capacity( sections .iter() .map(|section| section.glyphs.len()) .sum::<usize>(), ); for &GlyphedSection { ref glyphs, bounds, z, } in sections { verts.extend(glyphs.iter().filter_map(|(glyph, color, font_id)| { match self.texture_cache.rect_for(font_id.0, glyph) { Err(err) => { error!("Cache miss?: {:?}, {:?}: {}", font_id, glyph, err); None } Ok(None) => None, Ok(Some((tex_coords, pixel_coords))) => { if pixel_coords.min.x as f32 > bounds.max.x || pixel_coords.min.y as f32 > bounds.max.y || bounds.min.x > pixel_coords.max.x as f32 || bounds.min.y > pixel_coords.max.y as f32 { // glyph is totally outside the bounds None } else { Some(to_vertex(GlyphVertex { tex_coords, pixel_coords, bounds, screen_dimensions: (screen_w as f32, screen_h as f32), color: *color, z, })) } } } })); } verts } else { vec![] }; self.last_draw.text_state = current_text_state; BrushAction::Draw(verts) } else { BrushAction::ReDraw }; self.clear_section_buffer(); Ok(result) } /// Rebuilds the logical texture cache with new dimensions. Should be avoided if possible. /// /// # Example /// /// ```no_run /// # use glyph_brush::GlyphBrushBuilder; /// # let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// glyph_brush.resize_texture(512, 512); /// ``` pub fn resize_texture(&mut self, new_width: u32, new_height: u32) { self.texture_cache .to_builder() .dimensions(new_width, new_height) .rebuild(&mut self.texture_cache); self.last_draw = LastDrawInfo::default(); } /// Returns the logical texture cache pixel dimensions `(width, height)`. pub fn texture_dimensions(&self) -> (u32, u32) { self.texture_cache.dimensions() } fn clear_section_buffer(&mut self) { if self.cache_glyph_positioning { // clear section_buffer & trim calculate_glyph_cache to active sections let active: hashbrown::HashSet<_> = self .section_buffer .drain(..) .chain(self.keep_in_cache.drain()) .collect(); self.calculate_glyph_cache .retain(|key, _| active.contains(key)); } else { self.section_buffer.clear(); self.calculate_glyph_cache.clear(); self.keep_in_cache.clear(); } } /// Adds an additional font to the one(s) initially added on build. /// /// Returns a new [`FontId`](struct.FontId.html) to reference this font. /// /// # Example /// /// ```no_run /// use glyph_brush::{GlyphBrushBuilder, Section}; /// # fn main() { /// /// // dejavu is built as default `FontId(0)` /// let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// /// // some time later, add another font referenced by a new `FontId` /// let open_sans_italic: &[u8] = include_bytes!("../../fonts/OpenSans-Italic.ttf"); /// let open_sans_italic_id = glyph_brush.add_font_bytes(open_sans_italic); /// # } /// ``` pub fn add_font_bytes<'a: 'font, B: Into<SharedBytes<'a>>>(&mut self, font_data: B) -> FontId { self.add_font(Font::from_bytes(font_data.into()).unwrap()) } /// Adds an additional font to the one(s) initially added on build. /// /// Returns a new [`FontId`](struct.FontId.html) to reference this font. pub fn add_font<'a: 'font>(&mut self, font_data: Font<'a>) -> FontId { self.fonts.push(font_data); FontId(self.fonts.len() - 1) } /// Retains the section in the cache as if it had been used in the last draw-frame. /// /// Should not generally be necessary, see [caching behaviour](#caching-behaviour). pub fn keep_cached_custom_layout<'a, S, G>(&mut self, section: S, custom_layout: &G) where S: Into<Cow<'a, VariedSection<'a>>>, G: GlyphPositioner, { if!self.cache_glyph_positioning { return; } let section = section.into(); if cfg!(debug_assertions) { for text in &section.text { assert!(self.fonts.len() > text.font_id.0, "Invalid font id"); } } self.keep_in_cache .insert(self.hash(&(section, custom_layout))); } /// Retains the section in the cache as if it had been used in the last draw-frame. /// /// Should not generally be necessary, see [caching behaviour](#caching-behaviour). pub fn keep_cached<'a, S>(&mut self, section: S) where S: Into<Cow<'a, VariedSection<'a>>>, { let section = section.into(); let layout = section.layout; self.keep_cached_custom_layout(section, &layout); } } #[derive(Debug, Default)] struct LastDrawInfo { text_state: u64, } // glyph: &PositionedGlyph, // color: Color, // font_id: FontId, // cache: &Cache, // bounds: Rect<f32>, // z: f32, // (screen_width, screen_height): (f32, f32), /// Data used to generate vertex information for a single glyph #[derive(Debug)] pub struct GlyphVertex { pub tex_coords: Rect<f32>, pub pixel_coords: Rect<i32>, pub bounds: Rect<f32>, pub screen_dimensions: (f32, f32), pub color: Color, pub z: f32, } /// Actions that should be taken after processing queue data pub enum BrushAction<V> { /// Draw new/changed vertix data. Draw(Vec<V>), /// Re-draw last frame's vertices unmodified. ReDraw, } #[derive(Debug)] pub enum BrushError { /// Texture is too small to cache queued glyphs /// /// A larger suggested size is included. TextureTooSmall { suggested: (u32, u32) }, } impl fmt::Display for BrushError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", std::error::Error::description(self)) } } impl std::error::Error for BrushError { fn description(&self) -> &str { match self { BrushError::TextureTooSmall {.. } => "Texture is too small to cache queued glyphs", } } }
{ let (width, height) = self.texture_cache.dimensions(); return Err(BrushError::TextureTooSmall { suggested: (width * 2, height * 2), }); }
conditional_block
glyph_brush.rs
mod builder; pub use self::builder::*; use super::*; use full_rusttype::gpu_cache::Cache; use hashbrown::hash_map::Entry; use log::error; use std::{ borrow::Cow, fmt, hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}, i32, }; /// A hash of `Section` data type SectionHash = u64; /// A "practically collision free" `Section` hasher type DefaultSectionHasher = BuildHasherDefault<seahash::SeaHasher>; /// Object allowing glyph drawing, containing cache state. Manages glyph positioning cacheing, /// glyph draw caching & efficient GPU texture cache updating. /// /// Build using a [`GlyphBrushBuilder`](struct.GlyphBrushBuilder.html). /// /// # Caching behaviour /// /// Calls to [`GlyphBrush::queue`](#method.queue), /// [`GlyphBrush::pixel_bounds`](#method.pixel_bounds), [`GlyphBrush::glyphs`](#method.glyphs) /// calculate the positioned glyphs for a section. /// This is cached so future calls to any of the methods for the same section are much /// cheaper. In the case of [`GlyphBrush::queue`](#method.queue) the calculations will also be /// used for actual drawing. /// /// The cache for a section will be **cleared** after a /// [`GlyphBrush::process_queued`](#method.process_queued) call when that section has not been used /// since the previous call. pub struct GlyphBrush<'font, H = DefaultSectionHasher> { fonts: Vec<Font<'font>>, texture_cache: Cache<'font>, last_draw: LastDrawInfo, // cache of section-layout hash -> computed glyphs, this avoid repeated glyph computation // for identical layout/sections common to repeated frame rendering calculate_glyph_cache: hashbrown::HashMap<SectionHash, GlyphedSection<'font>>, // buffer of section-layout hashs (that must exist in the calculate_glyph_cache) // to be used on the next `process_queued` call section_buffer: Vec<SectionHash>, // Set of section hashs to keep in the glyph cache this frame even if they haven't been drawn keep_in_cache: hashbrown::HashSet<SectionHash>, // config cache_glyph_positioning: bool, cache_glyph_drawing: bool, section_hasher: H, } impl<H> fmt::Debug for GlyphBrush<'_, H> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "GlyphBrush") } } impl<'font, H: BuildHasher> GlyphCruncher<'font> for GlyphBrush<'font, H> { fn pixel_bounds_custom_layout<'a, S, L>( &mut self, section: S, custom_layout: &L, ) -> Option<Rect<i32>> where L: GlyphPositioner + Hash, S: Into<Cow<'a, VariedSection<'a>>>, { let section_hash = self.cache_glyphs(&section.into(), custom_layout); self.keep_in_cache.insert(section_hash); self.calculate_glyph_cache[&section_hash].pixel_bounds() } fn glyphs_custom_layout<'a, 'b, S, L>( &'b mut self, section: S, custom_layout: &L, ) -> PositionedGlyphIter<'b, 'font> where L: GlyphPositioner + Hash, S: Into<Cow<'a, VariedSection<'a>>>, { let section_hash = self.cache_glyphs(&section.into(), custom_layout); self.keep_in_cache.insert(section_hash); self.calculate_glyph_cache[&section_hash].glyphs() } fn fonts(&self) -> &[Font<'font>] { &self.fonts } } impl<'font, H: BuildHasher> GlyphBrush<'font, H> { /// Queues a section/layout to be processed by the next call of /// [`process_queued`](struct.GlyphBrush.html#method.process_queued). Can be called multiple /// times to queue multiple sections for drawing. /// /// Used to provide custom `GlyphPositioner` logic, if using built-in /// [`Layout`](enum.Layout.html) simply use [`queue`](struct.GlyphBrush.html#method.queue) /// /// Benefits from caching, see [caching behaviour](#caching-behaviour). pub fn queue_custom_layout<'a, S, G>(&mut self, section: S, custom_layout: &G) where G: GlyphPositioner, S: Into<Cow<'a, VariedSection<'a>>>, { let section = section.into(); if cfg!(debug_assertions) { for text in &section.text { assert!(self.fonts.len() > text.font_id.0, "Invalid font id"); } } let section_hash = self.cache_glyphs(&section, custom_layout); self.section_buffer.push(section_hash); } /// Queues a section/layout to be processed by the next call of /// [`process_queued`](struct.GlyphBrush.html#method.process_queued). Can be called multiple /// times to queue multiple sections for drawing. /// /// Benefits from caching, see [caching behaviour](#caching-behaviour). /// /// ```no_run /// # use glyph_brush::*; /// # let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// glyph_brush.queue(Section { /// text: "Hello glyph_brush", /// ..Section::default() /// }); /// ``` pub fn queue<'a, S>(&mut self, section: S) where S: Into<Cow<'a, VariedSection<'a>>>, { profile_scope!("glyph_brush_queue"); let section = section.into(); let layout = section.layout; self.queue_custom_layout(section, &layout) } #[inline] fn hash<T: Hash>(&self, hashable: &T) -> SectionHash { let mut s = self.section_hasher.build_hasher(); hashable.hash(&mut s); s.finish() } /// Returns the calculate_glyph_cache key for this sections glyphs fn cache_glyphs<L>(&mut self, section: &VariedSection<'_>, layout: &L) -> SectionHash where L: GlyphPositioner, { profile_scope!("glyph_brush_cache_glyphs"); let section_hash = self.hash(&(section, layout)); if self.cache_glyph_positioning { if let Entry::Vacant(entry) = self.calculate_glyph_cache.entry(section_hash) { let geometry = SectionGeometry::from(section); entry.insert(GlyphedSection { bounds: layout.bounds_rect(&geometry), glyphs: layout.calculate_glyphs(&self.fonts, &geometry, &section.text), z: section.z, }); } } else { let geometry = SectionGeometry::from(section); self.calculate_glyph_cache.insert( section_hash, GlyphedSection { bounds: layout.bounds_rect(&geometry), glyphs: layout.calculate_glyphs(&self.fonts, &geometry, &section.text), z: section.z, }, ); } section_hash } /// Processes all queued sections, calling texture update logic when necessary & /// returning a `BrushAction`. /// See [`queue`](struct.GlyphBrush.html#method.queue). /// /// Two closures are required: /// * `update_texture` is called when new glyph texture data has been drawn for update in the /// actual texture. /// The arguments are the rect position of the data in the texture & the byte data itself /// which is a single `u8` alpha value per pixel. /// * `to_vertex` maps a single glyph's `GlyphVertex` data into a generic vertex type. The /// mapped vertices are returned in an `Ok(BrushAction::Draw(vertices))` result. /// It's recommended to use a single vertex per glyph quad for best performance. /// /// Trims the cache, see [caching behaviour](#caching-behaviour). /// /// ```no_run /// # use glyph_brush::*; /// # fn main() -> Result<(), BrushError> { /// # let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// # let update_texture = |_, _| {}; /// # let into_vertex = |_| (); /// glyph_brush.process_queued( /// (1024, 768), /// |rect, tex_data| update_texture(rect, tex_data), /// |vertex_data| into_vertex(vertex_data), /// )? /// # ; /// # Ok(()) /// # } /// ``` pub fn process_queued<V, F1, F2>( &mut self, (screen_w, screen_h): (u32, u32), update_texture: F1, to_vertex: F2, ) -> Result<BrushAction<V>, BrushError> where F1: FnMut(Rect<u32>, &[u8]), F2: Fn(GlyphVertex) -> V, { profile_scope!("glyph_brush_process_queue"); let current_text_state = self.hash(&(&self.section_buffer, screen_w, screen_h)); let result = if!self.cache_glyph_drawing || self.last_draw.text_state!= current_text_state { let mut some_text = false; for section_hash in &self.section_buffer { let GlyphedSection { ref glyphs,.. } = self.calculate_glyph_cache[section_hash]; for &(ref glyph, _, font_id) in glyphs { self.texture_cache.queue_glyph(font_id.0, glyph.clone()); some_text = true; } } if some_text && self.texture_cache.cache_queued(update_texture).is_err() { let (width, height) = self.texture_cache.dimensions(); return Err(BrushError::TextureTooSmall { suggested: (width * 2, height * 2), }); } let verts: Vec<V> = if some_text { let sections: Vec<_> = self .section_buffer .iter() .map(|hash| &self.calculate_glyph_cache[hash]) .collect(); let mut verts = Vec::with_capacity( sections .iter() .map(|section| section.glyphs.len()) .sum::<usize>(), ); for &GlyphedSection { ref glyphs, bounds, z, } in sections { verts.extend(glyphs.iter().filter_map(|(glyph, color, font_id)| { match self.texture_cache.rect_for(font_id.0, glyph) { Err(err) => { error!("Cache miss?: {:?}, {:?}: {}", font_id, glyph, err); None } Ok(None) => None, Ok(Some((tex_coords, pixel_coords))) => { if pixel_coords.min.x as f32 > bounds.max.x || pixel_coords.min.y as f32 > bounds.max.y || bounds.min.x > pixel_coords.max.x as f32 || bounds.min.y > pixel_coords.max.y as f32 { // glyph is totally outside the bounds None } else { Some(to_vertex(GlyphVertex { tex_coords, pixel_coords, bounds, screen_dimensions: (screen_w as f32, screen_h as f32), color: *color, z, })) } } } })); } verts } else { vec![] }; self.last_draw.text_state = current_text_state; BrushAction::Draw(verts) } else { BrushAction::ReDraw }; self.clear_section_buffer(); Ok(result) } /// Rebuilds the logical texture cache with new dimensions. Should be avoided if possible. /// /// # Example /// /// ```no_run /// # use glyph_brush::GlyphBrushBuilder; /// # let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// glyph_brush.resize_texture(512, 512); /// ``` pub fn resize_texture(&mut self, new_width: u32, new_height: u32) { self.texture_cache .to_builder() .dimensions(new_width, new_height) .rebuild(&mut self.texture_cache); self.last_draw = LastDrawInfo::default(); } /// Returns the logical texture cache pixel dimensions `(width, height)`. pub fn texture_dimensions(&self) -> (u32, u32) { self.texture_cache.dimensions() } fn clear_section_buffer(&mut self) { if self.cache_glyph_positioning { // clear section_buffer & trim calculate_glyph_cache to active sections let active: hashbrown::HashSet<_> = self .section_buffer .drain(..) .chain(self.keep_in_cache.drain()) .collect(); self.calculate_glyph_cache .retain(|key, _| active.contains(key)); } else { self.section_buffer.clear(); self.calculate_glyph_cache.clear(); self.keep_in_cache.clear(); } } /// Adds an additional font to the one(s) initially added on build. /// /// Returns a new [`FontId`](struct.FontId.html) to reference this font. /// /// # Example /// /// ```no_run /// use glyph_brush::{GlyphBrushBuilder, Section}; /// # fn main() { /// /// // dejavu is built as default `FontId(0)` /// let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// /// // some time later, add another font referenced by a new `FontId` /// let open_sans_italic: &[u8] = include_bytes!("../../fonts/OpenSans-Italic.ttf"); /// let open_sans_italic_id = glyph_brush.add_font_bytes(open_sans_italic); /// # } /// ``` pub fn add_font_bytes<'a: 'font, B: Into<SharedBytes<'a>>>(&mut self, font_data: B) -> FontId
/// Adds an additional font to the one(s) initially added on build. /// /// Returns a new [`FontId`](struct.FontId.html) to reference this font. pub fn add_font<'a: 'font>(&mut self, font_data: Font<'a>) -> FontId { self.fonts.push(font_data); FontId(self.fonts.len() - 1) } /// Retains the section in the cache as if it had been used in the last draw-frame. /// /// Should not generally be necessary, see [caching behaviour](#caching-behaviour). pub fn keep_cached_custom_layout<'a, S, G>(&mut self, section: S, custom_layout: &G) where S: Into<Cow<'a, VariedSection<'a>>>, G: GlyphPositioner, { if!self.cache_glyph_positioning { return; } let section = section.into(); if cfg!(debug_assertions) { for text in &section.text { assert!(self.fonts.len() > text.font_id.0, "Invalid font id"); } } self.keep_in_cache .insert(self.hash(&(section, custom_layout))); } /// Retains the section in the cache as if it had been used in the last draw-frame. /// /// Should not generally be necessary, see [caching behaviour](#caching-behaviour). pub fn keep_cached<'a, S>(&mut self, section: S) where S: Into<Cow<'a, VariedSection<'a>>>, { let section = section.into(); let layout = section.layout; self.keep_cached_custom_layout(section, &layout); } } #[derive(Debug, Default)] struct LastDrawInfo { text_state: u64, } // glyph: &PositionedGlyph, // color: Color, // font_id: FontId, // cache: &Cache, // bounds: Rect<f32>, // z: f32, // (screen_width, screen_height): (f32, f32), /// Data used to generate vertex information for a single glyph #[derive(Debug)] pub struct GlyphVertex { pub tex_coords: Rect<f32>, pub pixel_coords: Rect<i32>, pub bounds: Rect<f32>, pub screen_dimensions: (f32, f32), pub color: Color, pub z: f32, } /// Actions that should be taken after processing queue data pub enum BrushAction<V> { /// Draw new/changed vertix data. Draw(Vec<V>), /// Re-draw last frame's vertices unmodified. ReDraw, } #[derive(Debug)] pub enum BrushError { /// Texture is too small to cache queued glyphs /// /// A larger suggested size is included. TextureTooSmall { suggested: (u32, u32) }, } impl fmt::Display for BrushError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", std::error::Error::description(self)) } } impl std::error::Error for BrushError { fn description(&self) -> &str { match self { BrushError::TextureTooSmall {.. } => "Texture is too small to cache queued glyphs", } } }
{ self.add_font(Font::from_bytes(font_data.into()).unwrap()) }
identifier_body
glyph_brush.rs
mod builder; pub use self::builder::*; use super::*; use full_rusttype::gpu_cache::Cache; use hashbrown::hash_map::Entry; use log::error; use std::{ borrow::Cow, fmt, hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}, i32, }; /// A hash of `Section` data type SectionHash = u64; /// A "practically collision free" `Section` hasher type DefaultSectionHasher = BuildHasherDefault<seahash::SeaHasher>; /// Object allowing glyph drawing, containing cache state. Manages glyph positioning cacheing, /// glyph draw caching & efficient GPU texture cache updating. /// /// Build using a [`GlyphBrushBuilder`](struct.GlyphBrushBuilder.html). /// /// # Caching behaviour /// /// Calls to [`GlyphBrush::queue`](#method.queue), /// [`GlyphBrush::pixel_bounds`](#method.pixel_bounds), [`GlyphBrush::glyphs`](#method.glyphs) /// calculate the positioned glyphs for a section. /// This is cached so future calls to any of the methods for the same section are much /// cheaper. In the case of [`GlyphBrush::queue`](#method.queue) the calculations will also be /// used for actual drawing. /// /// The cache for a section will be **cleared** after a /// [`GlyphBrush::process_queued`](#method.process_queued) call when that section has not been used /// since the previous call. pub struct GlyphBrush<'font, H = DefaultSectionHasher> { fonts: Vec<Font<'font>>, texture_cache: Cache<'font>, last_draw: LastDrawInfo, // cache of section-layout hash -> computed glyphs, this avoid repeated glyph computation // for identical layout/sections common to repeated frame rendering calculate_glyph_cache: hashbrown::HashMap<SectionHash, GlyphedSection<'font>>, // buffer of section-layout hashs (that must exist in the calculate_glyph_cache) // to be used on the next `process_queued` call section_buffer: Vec<SectionHash>, // Set of section hashs to keep in the glyph cache this frame even if they haven't been drawn keep_in_cache: hashbrown::HashSet<SectionHash>, // config cache_glyph_positioning: bool, cache_glyph_drawing: bool, section_hasher: H, } impl<H> fmt::Debug for GlyphBrush<'_, H> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "GlyphBrush") } } impl<'font, H: BuildHasher> GlyphCruncher<'font> for GlyphBrush<'font, H> { fn pixel_bounds_custom_layout<'a, S, L>( &mut self, section: S, custom_layout: &L, ) -> Option<Rect<i32>> where L: GlyphPositioner + Hash, S: Into<Cow<'a, VariedSection<'a>>>, { let section_hash = self.cache_glyphs(&section.into(), custom_layout); self.keep_in_cache.insert(section_hash); self.calculate_glyph_cache[&section_hash].pixel_bounds() } fn glyphs_custom_layout<'a, 'b, S, L>( &'b mut self, section: S, custom_layout: &L, ) -> PositionedGlyphIter<'b, 'font> where L: GlyphPositioner + Hash, S: Into<Cow<'a, VariedSection<'a>>>, { let section_hash = self.cache_glyphs(&section.into(), custom_layout); self.keep_in_cache.insert(section_hash); self.calculate_glyph_cache[&section_hash].glyphs() } fn fonts(&self) -> &[Font<'font>] { &self.fonts } } impl<'font, H: BuildHasher> GlyphBrush<'font, H> { /// Queues a section/layout to be processed by the next call of /// [`process_queued`](struct.GlyphBrush.html#method.process_queued). Can be called multiple /// times to queue multiple sections for drawing. /// /// Used to provide custom `GlyphPositioner` logic, if using built-in /// [`Layout`](enum.Layout.html) simply use [`queue`](struct.GlyphBrush.html#method.queue) /// /// Benefits from caching, see [caching behaviour](#caching-behaviour). pub fn queue_custom_layout<'a, S, G>(&mut self, section: S, custom_layout: &G) where G: GlyphPositioner, S: Into<Cow<'a, VariedSection<'a>>>, { let section = section.into(); if cfg!(debug_assertions) { for text in &section.text { assert!(self.fonts.len() > text.font_id.0, "Invalid font id"); } } let section_hash = self.cache_glyphs(&section, custom_layout); self.section_buffer.push(section_hash); } /// Queues a section/layout to be processed by the next call of /// [`process_queued`](struct.GlyphBrush.html#method.process_queued). Can be called multiple /// times to queue multiple sections for drawing. /// /// Benefits from caching, see [caching behaviour](#caching-behaviour). /// /// ```no_run /// # use glyph_brush::*; /// # let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// glyph_brush.queue(Section { /// text: "Hello glyph_brush", /// ..Section::default() /// }); /// ``` pub fn queue<'a, S>(&mut self, section: S) where S: Into<Cow<'a, VariedSection<'a>>>, { profile_scope!("glyph_brush_queue"); let section = section.into(); let layout = section.layout; self.queue_custom_layout(section, &layout) } #[inline] fn hash<T: Hash>(&self, hashable: &T) -> SectionHash { let mut s = self.section_hasher.build_hasher(); hashable.hash(&mut s); s.finish() } /// Returns the calculate_glyph_cache key for this sections glyphs fn cache_glyphs<L>(&mut self, section: &VariedSection<'_>, layout: &L) -> SectionHash where L: GlyphPositioner, { profile_scope!("glyph_brush_cache_glyphs"); let section_hash = self.hash(&(section, layout)); if self.cache_glyph_positioning { if let Entry::Vacant(entry) = self.calculate_glyph_cache.entry(section_hash) { let geometry = SectionGeometry::from(section); entry.insert(GlyphedSection { bounds: layout.bounds_rect(&geometry), glyphs: layout.calculate_glyphs(&self.fonts, &geometry, &section.text), z: section.z, }); } } else { let geometry = SectionGeometry::from(section); self.calculate_glyph_cache.insert( section_hash, GlyphedSection { bounds: layout.bounds_rect(&geometry), glyphs: layout.calculate_glyphs(&self.fonts, &geometry, &section.text), z: section.z, }, ); } section_hash } /// Processes all queued sections, calling texture update logic when necessary & /// returning a `BrushAction`. /// See [`queue`](struct.GlyphBrush.html#method.queue). /// /// Two closures are required: /// * `update_texture` is called when new glyph texture data has been drawn for update in the /// actual texture. /// The arguments are the rect position of the data in the texture & the byte data itself /// which is a single `u8` alpha value per pixel. /// * `to_vertex` maps a single glyph's `GlyphVertex` data into a generic vertex type. The /// mapped vertices are returned in an `Ok(BrushAction::Draw(vertices))` result. /// It's recommended to use a single vertex per glyph quad for best performance. /// /// Trims the cache, see [caching behaviour](#caching-behaviour). /// /// ```no_run /// # use glyph_brush::*; /// # fn main() -> Result<(), BrushError> { /// # let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// # let update_texture = |_, _| {}; /// # let into_vertex = |_| (); /// glyph_brush.process_queued( /// (1024, 768), /// |rect, tex_data| update_texture(rect, tex_data), /// |vertex_data| into_vertex(vertex_data), /// )? /// # ; /// # Ok(()) /// # } /// ``` pub fn process_queued<V, F1, F2>( &mut self, (screen_w, screen_h): (u32, u32), update_texture: F1, to_vertex: F2, ) -> Result<BrushAction<V>, BrushError> where F1: FnMut(Rect<u32>, &[u8]), F2: Fn(GlyphVertex) -> V, { profile_scope!("glyph_brush_process_queue"); let current_text_state = self.hash(&(&self.section_buffer, screen_w, screen_h)); let result = if!self.cache_glyph_drawing || self.last_draw.text_state!= current_text_state { let mut some_text = false; for section_hash in &self.section_buffer { let GlyphedSection { ref glyphs,.. } = self.calculate_glyph_cache[section_hash]; for &(ref glyph, _, font_id) in glyphs { self.texture_cache.queue_glyph(font_id.0, glyph.clone()); some_text = true; } } if some_text && self.texture_cache.cache_queued(update_texture).is_err() { let (width, height) = self.texture_cache.dimensions(); return Err(BrushError::TextureTooSmall { suggested: (width * 2, height * 2), }); } let verts: Vec<V> = if some_text { let sections: Vec<_> = self .section_buffer .iter() .map(|hash| &self.calculate_glyph_cache[hash]) .collect(); let mut verts = Vec::with_capacity( sections .iter() .map(|section| section.glyphs.len()) .sum::<usize>(), ); for &GlyphedSection { ref glyphs, bounds, z, } in sections { verts.extend(glyphs.iter().filter_map(|(glyph, color, font_id)| { match self.texture_cache.rect_for(font_id.0, glyph) { Err(err) => { error!("Cache miss?: {:?}, {:?}: {}", font_id, glyph, err); None } Ok(None) => None, Ok(Some((tex_coords, pixel_coords))) => { if pixel_coords.min.x as f32 > bounds.max.x || pixel_coords.min.y as f32 > bounds.max.y || bounds.min.x > pixel_coords.max.x as f32 || bounds.min.y > pixel_coords.max.y as f32 { // glyph is totally outside the bounds None } else { Some(to_vertex(GlyphVertex { tex_coords, pixel_coords, bounds, screen_dimensions: (screen_w as f32, screen_h as f32), color: *color, z, })) } } } })); } verts } else { vec![] }; self.last_draw.text_state = current_text_state; BrushAction::Draw(verts) } else { BrushAction::ReDraw }; self.clear_section_buffer(); Ok(result) } /// Rebuilds the logical texture cache with new dimensions. Should be avoided if possible. /// /// # Example /// /// ```no_run /// # use glyph_brush::GlyphBrushBuilder; /// # let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// # let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// glyph_brush.resize_texture(512, 512); /// ``` pub fn resize_texture(&mut self, new_width: u32, new_height: u32) { self.texture_cache .to_builder() .dimensions(new_width, new_height) .rebuild(&mut self.texture_cache); self.last_draw = LastDrawInfo::default(); } /// Returns the logical texture cache pixel dimensions `(width, height)`. pub fn texture_dimensions(&self) -> (u32, u32) { self.texture_cache.dimensions() } fn clear_section_buffer(&mut self) { if self.cache_glyph_positioning { // clear section_buffer & trim calculate_glyph_cache to active sections let active: hashbrown::HashSet<_> = self .section_buffer .drain(..) .chain(self.keep_in_cache.drain()) .collect(); self.calculate_glyph_cache .retain(|key, _| active.contains(key)); } else { self.section_buffer.clear(); self.calculate_glyph_cache.clear(); self.keep_in_cache.clear(); } } /// Adds an additional font to the one(s) initially added on build. /// /// Returns a new [`FontId`](struct.FontId.html) to reference this font. /// /// # Example /// /// ```no_run /// use glyph_brush::{GlyphBrushBuilder, Section}; /// # fn main() { /// /// // dejavu is built as default `FontId(0)` /// let dejavu: &[u8] = include_bytes!("../../fonts/DejaVuSans.ttf"); /// let mut glyph_brush = GlyphBrushBuilder::using_font_bytes(dejavu).build(); /// /// // some time later, add another font referenced by a new `FontId` /// let open_sans_italic: &[u8] = include_bytes!("../../fonts/OpenSans-Italic.ttf"); /// let open_sans_italic_id = glyph_brush.add_font_bytes(open_sans_italic); /// # } /// ``` pub fn add_font_bytes<'a: 'font, B: Into<SharedBytes<'a>>>(&mut self, font_data: B) -> FontId { self.add_font(Font::from_bytes(font_data.into()).unwrap()) } /// Adds an additional font to the one(s) initially added on build. /// /// Returns a new [`FontId`](struct.FontId.html) to reference this font. pub fn add_font<'a: 'font>(&mut self, font_data: Font<'a>) -> FontId { self.fonts.push(font_data); FontId(self.fonts.len() - 1) } /// Retains the section in the cache as if it had been used in the last draw-frame. /// /// Should not generally be necessary, see [caching behaviour](#caching-behaviour). pub fn
<'a, S, G>(&mut self, section: S, custom_layout: &G) where S: Into<Cow<'a, VariedSection<'a>>>, G: GlyphPositioner, { if!self.cache_glyph_positioning { return; } let section = section.into(); if cfg!(debug_assertions) { for text in &section.text { assert!(self.fonts.len() > text.font_id.0, "Invalid font id"); } } self.keep_in_cache .insert(self.hash(&(section, custom_layout))); } /// Retains the section in the cache as if it had been used in the last draw-frame. /// /// Should not generally be necessary, see [caching behaviour](#caching-behaviour). pub fn keep_cached<'a, S>(&mut self, section: S) where S: Into<Cow<'a, VariedSection<'a>>>, { let section = section.into(); let layout = section.layout; self.keep_cached_custom_layout(section, &layout); } } #[derive(Debug, Default)] struct LastDrawInfo { text_state: u64, } // glyph: &PositionedGlyph, // color: Color, // font_id: FontId, // cache: &Cache, // bounds: Rect<f32>, // z: f32, // (screen_width, screen_height): (f32, f32), /// Data used to generate vertex information for a single glyph #[derive(Debug)] pub struct GlyphVertex { pub tex_coords: Rect<f32>, pub pixel_coords: Rect<i32>, pub bounds: Rect<f32>, pub screen_dimensions: (f32, f32), pub color: Color, pub z: f32, } /// Actions that should be taken after processing queue data pub enum BrushAction<V> { /// Draw new/changed vertix data. Draw(Vec<V>), /// Re-draw last frame's vertices unmodified. ReDraw, } #[derive(Debug)] pub enum BrushError { /// Texture is too small to cache queued glyphs /// /// A larger suggested size is included. TextureTooSmall { suggested: (u32, u32) }, } impl fmt::Display for BrushError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", std::error::Error::description(self)) } } impl std::error::Error for BrushError { fn description(&self) -> &str { match self { BrushError::TextureTooSmall {.. } => "Texture is too small to cache queued glyphs", } } }
keep_cached_custom_layout
identifier_name
shared.rs
/* Copyright 2016 Torbjørn Birch Moltu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use Nbstr; use nbstr::{MAX_LENGTH,MAX_STACK,LITERAL,BOX}; extern crate std; use std::cmp::Ordering; use std::ops::Deref; use std::str as Str; use std::{mem,slice,ptr, fmt,hash}; use std::borrow::{Borrow,Cow}; /// Protected methods used by the impls below. pub trait Protected { /// create new of this variant with possibly uninitialized data fn new(u8) -> Self; /// store this str, which is either &'static or boxed fn with_pointer(u8, &str) -> Self; fn variant(&self) -> u8; /// get the area of self where (length,pointer)|inline is. fn data(&mut self) -> &mut [u8]; /// the root of AsRef,Borrow and Deref. fn get_slice(&self) -> &[u8]; } //////////////////// // public methods // //////////////////// impl Nbstr { #[cfg(feature="unstable")] /// Get the max length a Nbstr can store, /// as some compile-time features might limit it. pub const MAX_LENGTH: usize = MAX_LENGTH; /// Get the max length a Nbstr can store, /// as some compile-time features might limit it. /// /// This method will get deprecated once associated consts become stable. pub fn max_length() -> usize { MAX_LENGTH } // keeping all public methods under one impl gives cleaner rustdoc /// Create a Nbstr from a borrowed str with a limited lifetime. /// If the str is short enough it will be stored the inside struct itself and not boxed. pub fn from_str(s: &str) -> Self { Self::try_stack(s).unwrap_or_else(|| s.to_owned().into() ) } } //////////////// //Constructors// //////////////// impl Default for Nbstr { fn default() -> Self { let s = unsafe{ slice::from_raw_parts(1 as *const u8, 0) };//pointer must be nonzero Self::with_pointer(LITERAL, unsafe{ mem::transmute(s) }) } } impl From<&'static str> for Nbstr { fn from(s: &'static str) -> Self { Self::with_pointer(LITERAL, s) } } impl Nbstr { fn try_stack(s: &str) -> Option<Self> {match s.len() as u8 { // Cannot have stack str with length 0, as variant might be NonZero 0 => Some(Self::default()), 1...MAX_STACK => { let mut z = Self::new(s.len() as u8); for (d, s) in z.data().iter_mut().zip(s.bytes()) { *d = s; } Some(z) }, _ => None, }} } impl From<Box<str>> for Nbstr { fn from(s: Box<str>) -> Self { // Don't try stack; users might turn it back into a box later let z = if s.is_empty() {Self::default()}// Make it clear we don't own any memory. else {Self::with_pointer(BOX, &s)}; mem::forget(s); return z; } } impl From<String> for Nbstr { fn from(s: String) -> Self { if s.capacity()!= s.len() {// into_boxed will reallocate if let Some(inline) = Self::try_stack(&s) { return inline;// and drop s } } return Self::from(s.into_boxed_str()); } } impl From<Cow<'static, str>> for Nbstr { fn from(cow: Cow<'static, str>) -> Self {match cow { Cow::Owned(owned) => Self::from(owned), Cow::Borrowed(borrowed) => Self::from(borrowed), }} } impl Clone for Nbstr { fn clone(&self) -> Self { if self.variant() == BOX {// try stack Nbstr::from_str(self.deref()) } else {// copy the un-copyable unsafe{ ptr::read(self) } } } fn clone_from(&mut self, from: &Self) { // keep existing box if possible if self.variant() == BOX && self.len() == from.len() { unsafe{ ptr::copy_nonoverlapping( from.as_ptr(), mem::transmute(self.as_ptr()), self.len() )}; } else { *self = from.clone(); } } } /////////// //Getters// /////////// impl AsRef<[u8]> for Nbstr { fn as_ref(&self) -> &[u8] { self.get_slice() } } impl AsRef<str> for Nbstr { fn as_ref(&self) -> &str { let bytes: &[u8] = self.as_ref(); unsafe{ Str::from_utf8_unchecked( bytes )} } } impl Deref for Nbstr { type Target = str; fn deref(&self) -> &Self::Target { self.as_ref() } } impl Borrow<[u8]> for Nbstr { fn borrow(&self) -> &[u8] { self.as_ref() } } impl Borrow<str> for Nbstr { fn borrow(&self) -> &str { self.as_ref() } } ///////////////// //Common traits// ///////////////// impl hash::Hash for Nbstr { fn hash<H:hash::Hasher>(&self, h: &mut H) { self.deref().hash(h); } } impl fmt::Display for Nbstr { fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.deref(), fmtr) } } impl PartialOrd for Nbstr { fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> { self.deref().partial_cmp(rhs.deref()) } } impl Ord for Nbstr { fn cmp(&self, rhs: &Self) -> Ordering { self.deref().cmp(rhs.deref()) } } impl PartialEq for Nbstr { fn eq(&self, rhs: &Self) -> bool { self.deref() == rhs.deref() } } impl Eq for Nbstr {} /// Displays how the string is stored by prepending "stack: ", "literal: " or "boxed: ". impl fmt::Debug for Nbstr { fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result { write!(fmtr, "{}: {}", match self.variant() { 1...MAX_STACK => "stack", LITERAL => "literal", BOX => "boxed", _ => unreachable!("Unknown variant of Nbstr: {}", self.variant()) }, self.deref()) } } /////////////// //Destructors// /////////////// /// Returns Some if z contains a Box pub fn take_box(z: &mut Nbstr) -> Option<Box<str>> { if z.variant() == BOX { // I asked on #rust, and transmuting from & to mut is apparently undefined behaviour. // Is it really in this case? let s: *mut str = unsafe{ mem::transmute(z.get_slice()) }; // Cannot just assign default; then rust tries to drop the previous value! // .. which then calls this function. mem::forget(mem::replace(z, Nbstr::default())); Some(unsafe{ Box::from_raw(s) }) } else { None } } impl From<Nbstr> for Box<str> { fn from(mut z: Nbstr) -> Box<str> { take_box(&mut z).unwrap_or_else(|| z.deref().to_owned().into_boxed_str() ) } } impl From<Nbstr> for String { fn from(mut z: Nbstr) -> String { take_box(&mut z) .map(|b| b.into_string() ) .unwrap_or_else(|| z.deref().to_owned() ) } } impl From<Nbstr> for Cow<'static, str> { fn from(mut z: Nbstr) -> Cow<'static, str> { take_box(&mut z) .map(|b| Cow::from(b.into_string()) ) .unwrap_or_else(|| if z.variant() == LITERAL { let s: &'static str = unsafe{ mem::transmute(z.deref()) }; Cow::from(s) } else { Cow::from(z.deref().to_owned()) } ) } } #[cfg(not(test))]// Bugs in drop might cause stack overflow in suprising places. // The tests below should catch said bugs. impl Drop for Nbstr { fn drop(&mut self) { let _ = take_box(self); } } ////////////////////////////////////////////////////////////////////// // Tests that need private access or tests code that use cfg!(test) // ////////////////////////////////////////////////////////////////////// #[cfg(test)] mod tests { use nbstr::{Nbstr, MAX_STACK}; use super::*; use std::ops::Deref; use std::str as Str; use std::{mem,slice}; const STR: &'static str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; #[test] fn literal() { let mut z = Nbstr::from(STR); assert_eq!(z.deref().len(), STR.len()); assert_eq!(z.deref().as_ptr(), STR.as_ptr()); assert_eq!(z.deref(), STR); assert_eq!(take_box(&mut z), None); } #[test] fn stack() { let s = "abc"; let mut z = Nbstr::from_str(s); assert_eq!(z.deref().len(), s.len()); assert_eq!(z.deref().as_ptr() as usize, z.data().as_ptr() as usize); assert_eq!(z.deref(), s); assert_eq!(take_box(&mut z), None); } #[test]
let b2 = b.clone(); let mut z = Nbstr::from(b); assert_eq!(z.deref().len(), len); assert_eq!(z.deref().as_ptr(), ptr); assert_eq!(z.deref(), STR); assert_eq!(take_box(&mut z), Some(b2.clone())); assert_eq!(take_box(&mut Nbstr::from_str(STR)), Some(b2.clone())); } #[test] fn nuls() {// Is here because MAX_STACK let zeros_bytes = [0; MAX_STACK as usize]; let zeros_str = Str::from_utf8(&zeros_bytes).unwrap(); let zeros = Nbstr::from_str(zeros_str); assert_eq!(zeros.deref(), zeros_str); assert!(Some(zeros).is_some()); } #[test] #[cfg_attr(debug_assertions, should_panic)]// from arithmetic overflow or explicit panic fn too_long() {// Is here because no_giants has a custom panic message for tests, // because the normal one would segfault on the invalid test str. let b: &[u8] = unsafe{slice::from_raw_parts(1 as *const u8, 1+Nbstr::max_length() )}; let s: &'static str = unsafe{ mem::transmute(b) }; mem::forget(Nbstr::from(s)); } }
fn boxed() { let b: Box<str> = STR.to_string().into_boxed_str(); let len = b.len(); let ptr = b.as_ptr();
random_line_split
shared.rs
/* Copyright 2016 Torbjørn Birch Moltu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use Nbstr; use nbstr::{MAX_LENGTH,MAX_STACK,LITERAL,BOX}; extern crate std; use std::cmp::Ordering; use std::ops::Deref; use std::str as Str; use std::{mem,slice,ptr, fmt,hash}; use std::borrow::{Borrow,Cow}; /// Protected methods used by the impls below. pub trait Protected { /// create new of this variant with possibly uninitialized data fn new(u8) -> Self; /// store this str, which is either &'static or boxed fn with_pointer(u8, &str) -> Self; fn variant(&self) -> u8; /// get the area of self where (length,pointer)|inline is. fn data(&mut self) -> &mut [u8]; /// the root of AsRef,Borrow and Deref. fn get_slice(&self) -> &[u8]; } //////////////////// // public methods // //////////////////// impl Nbstr { #[cfg(feature="unstable")] /// Get the max length a Nbstr can store, /// as some compile-time features might limit it. pub const MAX_LENGTH: usize = MAX_LENGTH; /// Get the max length a Nbstr can store, /// as some compile-time features might limit it. /// /// This method will get deprecated once associated consts become stable. pub fn max_length() -> usize { MAX_LENGTH } // keeping all public methods under one impl gives cleaner rustdoc /// Create a Nbstr from a borrowed str with a limited lifetime. /// If the str is short enough it will be stored the inside struct itself and not boxed. pub fn from_str(s: &str) -> Self { Self::try_stack(s).unwrap_or_else(|| s.to_owned().into() ) } } //////////////// //Constructors// //////////////// impl Default for Nbstr { fn default() -> Self { let s = unsafe{ slice::from_raw_parts(1 as *const u8, 0) };//pointer must be nonzero Self::with_pointer(LITERAL, unsafe{ mem::transmute(s) }) } } impl From<&'static str> for Nbstr { fn from(s: &'static str) -> Self { Self::with_pointer(LITERAL, s) } } impl Nbstr { fn try_stack(s: &str) -> Option<Self> {match s.len() as u8 { // Cannot have stack str with length 0, as variant might be NonZero 0 => Some(Self::default()), 1...MAX_STACK => { let mut z = Self::new(s.len() as u8); for (d, s) in z.data().iter_mut().zip(s.bytes()) { *d = s; } Some(z) }, _ => None, }} } impl From<Box<str>> for Nbstr { fn from(s: Box<str>) -> Self { // Don't try stack; users might turn it back into a box later let z = if s.is_empty() {Self::default()}// Make it clear we don't own any memory. else {Self::with_pointer(BOX, &s)}; mem::forget(s); return z; } } impl From<String> for Nbstr { fn from(s: String) -> Self { if s.capacity()!= s.len() {// into_boxed will reallocate if let Some(inline) = Self::try_stack(&s) { return inline;// and drop s } } return Self::from(s.into_boxed_str()); } } impl From<Cow<'static, str>> for Nbstr { fn from(cow: Cow<'static, str>) -> Self {match cow { Cow::Owned(owned) => Self::from(owned), Cow::Borrowed(borrowed) => Self::from(borrowed), }} } impl Clone for Nbstr { fn clone(&self) -> Self { if self.variant() == BOX {// try stack Nbstr::from_str(self.deref()) } else {// copy the un-copyable unsafe{ ptr::read(self) } } } fn clone_from(&mut self, from: &Self) { // keep existing box if possible if self.variant() == BOX && self.len() == from.len() { unsafe{ ptr::copy_nonoverlapping( from.as_ptr(), mem::transmute(self.as_ptr()), self.len() )}; } else { *self = from.clone(); } } } /////////// //Getters// /////////// impl AsRef<[u8]> for Nbstr { fn as_ref(&self) -> &[u8] { self.get_slice() } } impl AsRef<str> for Nbstr { fn as_ref(&self) -> &str { let bytes: &[u8] = self.as_ref(); unsafe{ Str::from_utf8_unchecked( bytes )} } } impl Deref for Nbstr { type Target = str; fn deref(&self) -> &Self::Target { self.as_ref() } } impl Borrow<[u8]> for Nbstr { fn borrow(&self) -> &[u8] { self.as_ref() } } impl Borrow<str> for Nbstr { fn borrow(&self) -> &str { self.as_ref() } } ///////////////// //Common traits// ///////////////// impl hash::Hash for Nbstr { fn hash<H:hash::Hasher>(&self, h: &mut H) { self.deref().hash(h); } } impl fmt::Display for Nbstr { fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.deref(), fmtr) } } impl PartialOrd for Nbstr { fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> { self.deref().partial_cmp(rhs.deref()) } } impl Ord for Nbstr { fn cmp(&self, rhs: &Self) -> Ordering { self.deref().cmp(rhs.deref()) } } impl PartialEq for Nbstr { fn eq(&self, rhs: &Self) -> bool { self.deref() == rhs.deref() } } impl Eq for Nbstr {} /// Displays how the string is stored by prepending "stack: ", "literal: " or "boxed: ". impl fmt::Debug for Nbstr { fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result { write!(fmtr, "{}: {}", match self.variant() { 1...MAX_STACK => "stack", LITERAL => "literal", BOX => "boxed", _ => unreachable!("Unknown variant of Nbstr: {}", self.variant()) }, self.deref()) } } /////////////// //Destructors// /////////////// /// Returns Some if z contains a Box pub fn take_box(z: &mut Nbstr) -> Option<Box<str>> {
impl From<Nbstr> for Box<str> { fn from(mut z: Nbstr) -> Box<str> { take_box(&mut z).unwrap_or_else(|| z.deref().to_owned().into_boxed_str() ) } } impl From<Nbstr> for String { fn from(mut z: Nbstr) -> String { take_box(&mut z) .map(|b| b.into_string() ) .unwrap_or_else(|| z.deref().to_owned() ) } } impl From<Nbstr> for Cow<'static, str> { fn from(mut z: Nbstr) -> Cow<'static, str> { take_box(&mut z) .map(|b| Cow::from(b.into_string()) ) .unwrap_or_else(|| if z.variant() == LITERAL { let s: &'static str = unsafe{ mem::transmute(z.deref()) }; Cow::from(s) } else { Cow::from(z.deref().to_owned()) } ) } } #[cfg(not(test))]// Bugs in drop might cause stack overflow in suprising places. // The tests below should catch said bugs. impl Drop for Nbstr { fn drop(&mut self) { let _ = take_box(self); } } ////////////////////////////////////////////////////////////////////// // Tests that need private access or tests code that use cfg!(test) // ////////////////////////////////////////////////////////////////////// #[cfg(test)] mod tests { use nbstr::{Nbstr, MAX_STACK}; use super::*; use std::ops::Deref; use std::str as Str; use std::{mem,slice}; const STR: &'static str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; #[test] fn literal() { let mut z = Nbstr::from(STR); assert_eq!(z.deref().len(), STR.len()); assert_eq!(z.deref().as_ptr(), STR.as_ptr()); assert_eq!(z.deref(), STR); assert_eq!(take_box(&mut z), None); } #[test] fn stack() { let s = "abc"; let mut z = Nbstr::from_str(s); assert_eq!(z.deref().len(), s.len()); assert_eq!(z.deref().as_ptr() as usize, z.data().as_ptr() as usize); assert_eq!(z.deref(), s); assert_eq!(take_box(&mut z), None); } #[test] fn boxed() { let b: Box<str> = STR.to_string().into_boxed_str(); let len = b.len(); let ptr = b.as_ptr(); let b2 = b.clone(); let mut z = Nbstr::from(b); assert_eq!(z.deref().len(), len); assert_eq!(z.deref().as_ptr(), ptr); assert_eq!(z.deref(), STR); assert_eq!(take_box(&mut z), Some(b2.clone())); assert_eq!(take_box(&mut Nbstr::from_str(STR)), Some(b2.clone())); } #[test] fn nuls() {// Is here because MAX_STACK let zeros_bytes = [0; MAX_STACK as usize]; let zeros_str = Str::from_utf8(&zeros_bytes).unwrap(); let zeros = Nbstr::from_str(zeros_str); assert_eq!(zeros.deref(), zeros_str); assert!(Some(zeros).is_some()); } #[test] #[cfg_attr(debug_assertions, should_panic)]// from arithmetic overflow or explicit panic fn too_long() {// Is here because no_giants has a custom panic message for tests, // because the normal one would segfault on the invalid test str. let b: &[u8] = unsafe{slice::from_raw_parts(1 as *const u8, 1+Nbstr::max_length() )}; let s: &'static str = unsafe{ mem::transmute(b) }; mem::forget(Nbstr::from(s)); } }
if z.variant() == BOX { // I asked on #rust, and transmuting from & to mut is apparently undefined behaviour. // Is it really in this case? let s: *mut str = unsafe{ mem::transmute(z.get_slice()) }; // Cannot just assign default; then rust tries to drop the previous value! // .. which then calls this function. mem::forget(mem::replace(z, Nbstr::default())); Some(unsafe{ Box::from_raw(s) }) } else { None } }
identifier_body
shared.rs
/* Copyright 2016 Torbjørn Birch Moltu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use Nbstr; use nbstr::{MAX_LENGTH,MAX_STACK,LITERAL,BOX}; extern crate std; use std::cmp::Ordering; use std::ops::Deref; use std::str as Str; use std::{mem,slice,ptr, fmt,hash}; use std::borrow::{Borrow,Cow}; /// Protected methods used by the impls below. pub trait Protected { /// create new of this variant with possibly uninitialized data fn new(u8) -> Self; /// store this str, which is either &'static or boxed fn with_pointer(u8, &str) -> Self; fn variant(&self) -> u8; /// get the area of self where (length,pointer)|inline is. fn data(&mut self) -> &mut [u8]; /// the root of AsRef,Borrow and Deref. fn get_slice(&self) -> &[u8]; } //////////////////// // public methods // //////////////////// impl Nbstr { #[cfg(feature="unstable")] /// Get the max length a Nbstr can store, /// as some compile-time features might limit it. pub const MAX_LENGTH: usize = MAX_LENGTH; /// Get the max length a Nbstr can store, /// as some compile-time features might limit it. /// /// This method will get deprecated once associated consts become stable. pub fn max_length() -> usize { MAX_LENGTH } // keeping all public methods under one impl gives cleaner rustdoc /// Create a Nbstr from a borrowed str with a limited lifetime. /// If the str is short enough it will be stored the inside struct itself and not boxed. pub fn from_str(s: &str) -> Self { Self::try_stack(s).unwrap_or_else(|| s.to_owned().into() ) } } //////////////// //Constructors// //////////////// impl Default for Nbstr { fn default() -> Self { let s = unsafe{ slice::from_raw_parts(1 as *const u8, 0) };//pointer must be nonzero Self::with_pointer(LITERAL, unsafe{ mem::transmute(s) }) } } impl From<&'static str> for Nbstr { fn f
s: &'static str) -> Self { Self::with_pointer(LITERAL, s) } } impl Nbstr { fn try_stack(s: &str) -> Option<Self> {match s.len() as u8 { // Cannot have stack str with length 0, as variant might be NonZero 0 => Some(Self::default()), 1...MAX_STACK => { let mut z = Self::new(s.len() as u8); for (d, s) in z.data().iter_mut().zip(s.bytes()) { *d = s; } Some(z) }, _ => None, }} } impl From<Box<str>> for Nbstr { fn from(s: Box<str>) -> Self { // Don't try stack; users might turn it back into a box later let z = if s.is_empty() {Self::default()}// Make it clear we don't own any memory. else {Self::with_pointer(BOX, &s)}; mem::forget(s); return z; } } impl From<String> for Nbstr { fn from(s: String) -> Self { if s.capacity()!= s.len() {// into_boxed will reallocate if let Some(inline) = Self::try_stack(&s) { return inline;// and drop s } } return Self::from(s.into_boxed_str()); } } impl From<Cow<'static, str>> for Nbstr { fn from(cow: Cow<'static, str>) -> Self {match cow { Cow::Owned(owned) => Self::from(owned), Cow::Borrowed(borrowed) => Self::from(borrowed), }} } impl Clone for Nbstr { fn clone(&self) -> Self { if self.variant() == BOX {// try stack Nbstr::from_str(self.deref()) } else {// copy the un-copyable unsafe{ ptr::read(self) } } } fn clone_from(&mut self, from: &Self) { // keep existing box if possible if self.variant() == BOX && self.len() == from.len() { unsafe{ ptr::copy_nonoverlapping( from.as_ptr(), mem::transmute(self.as_ptr()), self.len() )}; } else { *self = from.clone(); } } } /////////// //Getters// /////////// impl AsRef<[u8]> for Nbstr { fn as_ref(&self) -> &[u8] { self.get_slice() } } impl AsRef<str> for Nbstr { fn as_ref(&self) -> &str { let bytes: &[u8] = self.as_ref(); unsafe{ Str::from_utf8_unchecked( bytes )} } } impl Deref for Nbstr { type Target = str; fn deref(&self) -> &Self::Target { self.as_ref() } } impl Borrow<[u8]> for Nbstr { fn borrow(&self) -> &[u8] { self.as_ref() } } impl Borrow<str> for Nbstr { fn borrow(&self) -> &str { self.as_ref() } } ///////////////// //Common traits// ///////////////// impl hash::Hash for Nbstr { fn hash<H:hash::Hasher>(&self, h: &mut H) { self.deref().hash(h); } } impl fmt::Display for Nbstr { fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.deref(), fmtr) } } impl PartialOrd for Nbstr { fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> { self.deref().partial_cmp(rhs.deref()) } } impl Ord for Nbstr { fn cmp(&self, rhs: &Self) -> Ordering { self.deref().cmp(rhs.deref()) } } impl PartialEq for Nbstr { fn eq(&self, rhs: &Self) -> bool { self.deref() == rhs.deref() } } impl Eq for Nbstr {} /// Displays how the string is stored by prepending "stack: ", "literal: " or "boxed: ". impl fmt::Debug for Nbstr { fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result { write!(fmtr, "{}: {}", match self.variant() { 1...MAX_STACK => "stack", LITERAL => "literal", BOX => "boxed", _ => unreachable!("Unknown variant of Nbstr: {}", self.variant()) }, self.deref()) } } /////////////// //Destructors// /////////////// /// Returns Some if z contains a Box pub fn take_box(z: &mut Nbstr) -> Option<Box<str>> { if z.variant() == BOX { // I asked on #rust, and transmuting from & to mut is apparently undefined behaviour. // Is it really in this case? let s: *mut str = unsafe{ mem::transmute(z.get_slice()) }; // Cannot just assign default; then rust tries to drop the previous value! // .. which then calls this function. mem::forget(mem::replace(z, Nbstr::default())); Some(unsafe{ Box::from_raw(s) }) } else { None } } impl From<Nbstr> for Box<str> { fn from(mut z: Nbstr) -> Box<str> { take_box(&mut z).unwrap_or_else(|| z.deref().to_owned().into_boxed_str() ) } } impl From<Nbstr> for String { fn from(mut z: Nbstr) -> String { take_box(&mut z) .map(|b| b.into_string() ) .unwrap_or_else(|| z.deref().to_owned() ) } } impl From<Nbstr> for Cow<'static, str> { fn from(mut z: Nbstr) -> Cow<'static, str> { take_box(&mut z) .map(|b| Cow::from(b.into_string()) ) .unwrap_or_else(|| if z.variant() == LITERAL { let s: &'static str = unsafe{ mem::transmute(z.deref()) }; Cow::from(s) } else { Cow::from(z.deref().to_owned()) } ) } } #[cfg(not(test))]// Bugs in drop might cause stack overflow in suprising places. // The tests below should catch said bugs. impl Drop for Nbstr { fn drop(&mut self) { let _ = take_box(self); } } ////////////////////////////////////////////////////////////////////// // Tests that need private access or tests code that use cfg!(test) // ////////////////////////////////////////////////////////////////////// #[cfg(test)] mod tests { use nbstr::{Nbstr, MAX_STACK}; use super::*; use std::ops::Deref; use std::str as Str; use std::{mem,slice}; const STR: &'static str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; #[test] fn literal() { let mut z = Nbstr::from(STR); assert_eq!(z.deref().len(), STR.len()); assert_eq!(z.deref().as_ptr(), STR.as_ptr()); assert_eq!(z.deref(), STR); assert_eq!(take_box(&mut z), None); } #[test] fn stack() { let s = "abc"; let mut z = Nbstr::from_str(s); assert_eq!(z.deref().len(), s.len()); assert_eq!(z.deref().as_ptr() as usize, z.data().as_ptr() as usize); assert_eq!(z.deref(), s); assert_eq!(take_box(&mut z), None); } #[test] fn boxed() { let b: Box<str> = STR.to_string().into_boxed_str(); let len = b.len(); let ptr = b.as_ptr(); let b2 = b.clone(); let mut z = Nbstr::from(b); assert_eq!(z.deref().len(), len); assert_eq!(z.deref().as_ptr(), ptr); assert_eq!(z.deref(), STR); assert_eq!(take_box(&mut z), Some(b2.clone())); assert_eq!(take_box(&mut Nbstr::from_str(STR)), Some(b2.clone())); } #[test] fn nuls() {// Is here because MAX_STACK let zeros_bytes = [0; MAX_STACK as usize]; let zeros_str = Str::from_utf8(&zeros_bytes).unwrap(); let zeros = Nbstr::from_str(zeros_str); assert_eq!(zeros.deref(), zeros_str); assert!(Some(zeros).is_some()); } #[test] #[cfg_attr(debug_assertions, should_panic)]// from arithmetic overflow or explicit panic fn too_long() {// Is here because no_giants has a custom panic message for tests, // because the normal one would segfault on the invalid test str. let b: &[u8] = unsafe{slice::from_raw_parts(1 as *const u8, 1+Nbstr::max_length() )}; let s: &'static str = unsafe{ mem::transmute(b) }; mem::forget(Nbstr::from(s)); } }
rom(
identifier_name
packfile.rs
use bytes::{BufMut, BytesMut}; use flate2::{write::ZlibEncoder, Compression}; use sha1::{ digest::{generic_array::GenericArray, FixedOutputDirty}, Digest, Sha1, }; use std::{convert::TryInto, fmt::Write, io::Write as IoWrite}; // The packfile itself is a very simple format. There is a header, a // series of packed objects (each with it's own header and body) and // then a checksum trailer. The first four bytes is the string 'PACK', // which is sort of used to make sure you're getting the start of the // packfile correctly. This is followed by a 4-byte packfile version // number and then a 4-byte number of entries in that file. pub struct PackFile<'a> { entries: Vec<PackFileEntry<'a>>, } impl<'a> PackFile<'a> { #[must_use] pub fn new(entries: Vec<PackFileEntry<'a>>) -> Self { Self { entries } } #[must_use] pub const fn header_size() -> usize { "PACK".len() + std::mem::size_of::<u32>() + std::mem::size_of::<u32>() } #[must_use] pub const fn footer_size() -> usize { 20 } pub fn encode_to(&self, original_buf: &mut BytesMut) -> Result<(), anyhow::Error> { let mut buf = original_buf.split_off(original_buf.len()); buf.reserve(Self::header_size() + Self::footer_size()); // header buf.extend_from_slice(b"PACK"); // magic header buf.put_u32(2); // version buf.put_u32(self.entries.len().try_into()?); // number of entries in the packfile // body for entry in &self.entries { entry.encode_to(&mut buf)?; } // footer buf.extend_from_slice(&sha1::Sha1::digest(&buf[..])); original_buf.unsplit(buf); Ok(()) } } #[derive(Debug)] pub struct Commit<'a> { pub tree: GenericArray<u8, <Sha1 as FixedOutputDirty>::OutputSize>, // [u8; 20], but sha-1 returns a GenericArray // pub parent: [u8; 20], pub author: CommitUserInfo<'a>, pub committer: CommitUserInfo<'a>, // pub gpgsig: &str, pub message: &'a str, } impl Commit<'_> { fn encode_to(&self, out: &mut BytesMut) -> Result<(), anyhow::Error> { let mut tree_hex = [0_u8; 20 * 2]; hex::encode_to_slice(self.tree, &mut tree_hex)?; out.write_str("tree ")?; out.extend_from_slice(&tree_hex); out.write_char('\n')?; writeln!(out, "author {}", self.author.encode())?; writeln!(out, "committer {}", self.committer.encode())?; write!(out, "\n{}", self.message)?; Ok(()) } #[must_use] pub fn size(&self) -> usize { let mut len = 0; len += "tree ".len() + (self.tree.len() * 2) + "\n".len(); len += "author ".len() + self.author.size() + "\n".len(); len += "committer ".len() + self.committer.size() + "\n".len(); len += "\n".len() + self.message.len(); len } } #[derive(Copy, Clone, Debug)] pub struct CommitUserInfo<'a> { pub name: &'a str, pub email: &'a str, pub time: chrono::DateTime<chrono::Utc>, } impl CommitUserInfo<'_> { fn encode(&self) -> String { // TODO: remove `format!`, `format_args!`? format!( "{} <{}> {} +0000", self.name, self.email, self.time.timestamp() ) } #[must_use] pub fn size(&self) -> usize { let timestamp_len = itoa::Buffer::new().format(self.time.timestamp()).len(); self.name.len() + "< ".len() + self.email.len() + "> ".len() + timestamp_len
} #[derive(Debug)] pub enum TreeItemKind { File, Directory, } impl TreeItemKind { #[must_use] pub const fn mode(&self) -> &'static str { match self { Self::File => "100644", Self::Directory => "40000", } } } #[derive(Debug)] pub struct TreeItem<'a> { pub kind: TreeItemKind, pub name: &'a str, pub hash: GenericArray<u8, <Sha1 as FixedOutputDirty>::OutputSize>, // [u8; 20] - but we have to deal with GenericArrays } // `[mode] [name]\0[hash]` impl TreeItem<'_> { fn encode_to(&self, out: &mut BytesMut) -> Result<(), anyhow::Error> { out.write_str(self.kind.mode())?; write!(out, " {}\0", self.name)?; out.extend_from_slice(&self.hash); Ok(()) } #[must_use] pub fn size(&self) -> usize { self.kind.mode().len() + " ".len() + self.name.len() + "\0".len() + self.hash.len() } } #[derive(Debug)] pub enum PackFileEntry<'a> { // jordan@Jordans-MacBook-Pro-2 0d % printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" | cat - f5/473259d9674ed66239766a013f96a3550374e3 | gzip -dc // commit 1068tree 0d586b48bc42e8591773d3d8a7223551c39d453c // parent c2a862612a14346ae95234f26efae1ee69b5b7a9 // author Jordan Doyle <[email protected]> 1630244577 +0100 // committer Jordan Doyle <[email protected]> 1630244577 +0100 // gpgsig -----BEGIN PGP SIGNATURE----- // // iQIzBAABCAAdFiEEMn1zof7yzaURQBGDHqa65vZtxJoFAmErjuEACgkQHqa65vZt // xJqhvhAAieKXnGRjT926qzozcvarC8D3TlA+Z1wVXueTAWqfusNIP0zCun/crOb2 // tOULO+/DXVBmwu5eInAf+t/wvlnIsrzJonhVr1ZT0f0vDX6fs2vflWg4UCVEuTsZ // tg+aTjcibwnmViIM9XVOzhU8Au2OIqMQLyQOMWSt8NhY0W2WhBCdQvhktvK1V8W6 // omPs04SrR39xWBDQaxsXYxq/1ZKUYXDwudvEfv14EvrxG1vWumpUVJd7Ib5w4gXX // fYa95DxYL720ZaiWPIYEG8FMBzSOpo6lUzY9g2/o/wKwSQZJNvpaMGCuouy8Fb+E // UaqC0XPxqpKG9duXPgCldUr+P7++48CF5zc358RBGz5OCNeTREsIQQo5PUO1k+wO // FnGOQTT8vvNOrxBgb3QgKu67RVwWDc6JnQCNpUrhUJrXMDWnYLBqo4Y+CdKGSQ4G // hW8V/hVTOlJZNi8bbU4v53cxh4nXiMM6NKUblUKs65ar3/2dkojwunz7r7GVZ6mG // QUpr9+ybG61XDqd1ad1A/B/i3WdWixTmJS3K/4uXjFjFX1f3RAk7O0gHc9I8HYOE // Vd8UsHzLOWAUHeaqbsd6xx3GCXF4D5D++kh9OY9Ov7CXlqbYbHd6Atg+PQ7VnqNf // bDqWN0Q2qcKX3k4ggtucmkkA6gP+K3+F5ANQj3AsGMQeddowC0Y= // =fXoH // -----END PGP SIGNATURE----- // // test Commit(Commit<'a>), // jordan@Jordans-MacBook-Pro-2 0d % printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" | cat - 0d/586b48bc42e8591773d3d8a7223551c39d453c | gzip -dc // tree 20940000.cargo���CYy��Ve�������100644.gitignore�K��_ow�]����4�n�ݺ100644 Cargo.lock�7�3-�?/�� // kt��c0C�100644 Cargo.toml�6�&(��]\8@�SHA�]f40000 src0QW��ƅ���b[�!�S&N�100644 test�G2Y�gN�b9vj?��Ut� Tree(Vec<TreeItem<'a>>), // jordan@Jordans-MacBook-Pro-2 objects % printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" | cat - f5/473259d9674ed66239766a013f96a3550374e3| gzip -dc // blob 23try and find me in.git Blob(&'a [u8]), // Tag, // OfsDelta, // RefDelta, } impl PackFileEntry<'_> { fn write_header(&self, buf: &mut BytesMut) { let mut size = self.uncompressed_size(); // write header { let mut val = 0b1000_0000_u8; val |= match self { Self::Commit(_) => 0b001, Self::Tree(_) => 0b010, Self::Blob(_) => 0b011, // Self::Tag => 0b100, // Self::OfsDelta => 0b110, // Self::RefDelta => 0b111, } << 4; // pack the 4 LSBs of the size into the header #[allow(clippy::cast_possible_truncation)] // value is masked { val |= (size & 0b1111) as u8; } size >>= 4; buf.put_u8(val); } // write size bytes while size!= 0 { // read 7 LSBs from the `size` and push them off for the next iteration #[allow(clippy::cast_possible_truncation)] // value is masked let mut val = (size & 0b111_1111) as u8; size >>= 7; if size!= 0 { // MSB set to 1 implies there's more size bytes to come, otherwise // the data starts after this byte val |= 1 << 7; } buf.put_u8(val); } } pub fn encode_to(&self, original_out: &mut BytesMut) -> Result<(), anyhow::Error> { self.write_header(original_out); // TODO: this needs space reserving for it // todo is there a way to stream through the zlibencoder so we don't have to // have this intermediate bytesmut and vec? let mut out = BytesMut::new(); let size = self.uncompressed_size(); original_out.reserve(size); // the data ends up getting compressed but we'll need at least this many bytes out.reserve(size); match self { Self::Commit(commit) => { commit.encode_to(&mut out)?; } Self::Tree(items) => { for item in items { item.encode_to(&mut out)?; } } Self::Blob(data) => { out.extend_from_slice(data); } } debug_assert_eq!(out.len(), size); let mut e = ZlibEncoder::new(Vec::new(), Compression::default()); e.write_all(&out)?; let compressed_data = e.finish()?; original_out.extend_from_slice(&compressed_data); Ok(()) } #[must_use] pub fn uncompressed_size(&self) -> usize { match self { Self::Commit(commit) => commit.size(), Self::Tree(items) => items.iter().map(TreeItem::size).sum(), Self::Blob(data) => data.len(), } } // wen const generics for RustCrypto? :-( pub fn hash( &self, ) -> Result<GenericArray<u8, <Sha1 as FixedOutputDirty>::OutputSize>, anyhow::Error> { let size = self.uncompressed_size(); let file_prefix = match self { Self::Commit(_) => "commit", Self::Tree(_) => "tree", Self::Blob(_) => "blob", }; let size_len = itoa::Buffer::new().format(size).len(); let mut out = BytesMut::with_capacity(file_prefix.len() + " ".len() + size_len + "\n".len() + size); write!(out, "{} {}\0", file_prefix, size)?; match self { Self::Commit(commit) => { commit.encode_to(&mut out)?; } Self::Tree(items) => { for item in items { item.encode_to(&mut out)?; } } Self::Blob(blob) => { out.extend_from_slice(blob); } } Ok(sha1::Sha1::digest(&out)) } }
+ " +0000".len() }
random_line_split