speice.io/assets/js/71d18034.1efabbf9.js

1 line
18 KiB
JavaScript

"use strict";(self.webpackChunkspeice_io=self.webpackChunkspeice_io||[]).push([["4558"],{20010:function(e,t,n){n.r(t),n.d(t,{assets:function(){return d},contentTitle:function(){return i},default:function(){return p},frontMatter:function(){return o},metadata:function(){return a},toc:function(){return c}});var a=n(9098),r=n(85893),s=n(50065);let o={slug:"2018/01/captains-cookbook-part-2",title:"Captain's Cookbook: Practical usage",date:new Date("2018-01-16T13:00:00.000Z"),authors:["bspeice"],tags:[]},i=void 0,d={authorsImageUrls:[void 0]},c=[{value:"Attempt 1: Move the reference",id:"attempt-1-move-the-reference",level:2},{value:"Attempt 2: Put the <code>Reader</code> in a <code>Box</code>",id:"attempt-2-put-the-reader-in-a-box",level:2},{value:"Attempt 3: The <code>TypedReader</code>",id:"attempt-3-the-typedreader",level:2}];function h(e){let t={a:"a",blockquote:"blockquote",code:"code",em:"em",h2:"h2",li:"li",ol:"ol",p:"p",pre:"pre",...(0,s.a)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(t.p,{children:"A look at more practical usages of Cap'N Proto"}),"\n",(0,r.jsxs)(t.p,{children:[(0,r.jsx)(t.a,{href:"/2018/01/captains-cookbook-part-1",children:"Part 1"})," of this series took a look at a basic starting project\nwith Cap'N Proto. In this section, we're going to take the (admittedly basic) schema and look at how we can add a pretty\nbasic feature - sending Cap'N Proto messages between threads. It's nothing complex, but I want to make sure that there's\nsome documentation surrounding practical usage of the library."]}),"\n",(0,r.jsxs)(t.p,{children:["As a quick refresher, we build a Cap'N Proto message and go through the serialization/deserialization steps\n",(0,r.jsx)(t.a,{href:"https://github.com/bspeice/capnp_cookbook_1/blob/master/src/main.rs",children:"here"}),". Our current example is going to build on\nthe code we wrote there; after the deserialization step, we'll try and send the ",(0,r.jsx)(t.code,{children:"point_reader"})," to a separate thread\nfor verification."]}),"\n",(0,r.jsxs)(t.p,{children:["I'm going to walk through the attempts as I made them and my thinking throughout.\nIf you want to skip to the final project, check out the code available ",(0,r.jsx)(t.a,{href:"https://github.com/bspeice/capnp_cookbook_2",children:"here"})]}),"\n",(0,r.jsx)(t.h2,{id:"attempt-1-move-the-reference",children:"Attempt 1: Move the reference"}),"\n",(0,r.jsx)(t.p,{children:"As a first attempt, we're going to try and let Rust move the reference. Our code will look something like:"}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-rust",children:"fn main() {\n\n // ...assume that we own a `buffer: Vec<u8>` containing the binary message content from\n // somewhere else\n\n let deserialized = capnp::serialize::read_message(\n &mut buffer.as_slice(),\n capnp::message::ReaderOptions::new()\n ).unwrap();\n\n let point_reader = deserialized.get_root::<point_capnp::point::Reader>().unwrap();\n\n // By using `point_reader` inside the new thread, we're hoping that Rust can\n // safely move the reference and invalidate the original thread's usage.\n // Since the original thread doesn't use `point_reader` again, this should\n // be safe, right?\n let handle = std::thread:spawn(move || {\n\n assert_eq!(point_reader.get_x(), 12);\n\n assert_eq!(point_reader.get_y(), 14);\n });\n\n handle.join().unwrap()\n}\n"})}),"\n",(0,r.jsx)(t.p,{children:"Well, the Rust compiler doesn't really like this. We get four distinct errors back:"}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{children:"error[E0277]: the trait bound `*const u8: std::marker::Send` is not satisfied in `[closure@src/main.rs:31:37: 36:6 point_reader:point_capnp::point::Reader<'_>]` \n --\x3e src/main.rs:31:18 \n | \n31 | let handle = std::thread::spawn(move || { \n | ^^^^^^^^^^^^^^^^^^ `*const u8` cannot be sent between threads safely \n | \n\nerror[E0277]: the trait bound `*const capnp::private::layout::WirePointer: std::marker::Send` is not satisfied in `[closure@src/main.rs:31:37: 36:6 point_reader:point_capnp::point::Reader<'_>]` \n --\x3e src/main.rs:31:18 \n | \n31 | let handle = std::thread::spawn(move || { \n | ^^^^^^^^^^^^^^^^^^ `*const capnp::private::layout::WirePointer` cannot be sent between threads safely \n | \n\nerror[E0277]: the trait bound `capnp::private::arena::ReaderArena: std::marker::Sync` is not satisfied \n --\x3e src/main.rs:31:18 \n | \n31 | let handle = std::thread::spawn(move || { \n | ^^^^^^^^^^^^^^^^^^ `capnp::private::arena::ReaderArena` cannot be shared between threads safely \n | \n\nerror[E0277]: the trait bound `*const std::vec::Vec<std::option::Option<std::boxed::Box<capnp::private::capability::ClientHook + 'static>>>: std::marker::Send` is not satisfied in `[closure@src/main.rs:31:37: 36:6 point_reader:point_capnp::point::Reader<'_>]` \n --\x3e src/main.rs:31:18 \n | \n31 | let handle = std::thread::spawn(move || { \n | ^^^^^^^^^^^^^^^^^^ `*const std::vec::Vec<std::option::Option<std::boxed::Box<capnp::private::capability::ClientHook + 'static>>>` cannot be sent between threads safely \n | \n\nerror: aborting due to 4 previous errors\n"})}),"\n",(0,r.jsxs)(t.p,{children:["Note, I've removed the help text for brevity, but suffice to say that these errors are intimidating.\nPay attention to the text that keeps on getting repeated though: ",(0,r.jsx)(t.code,{children:"XYZ cannot be sent between threads safely"}),"."]}),"\n",(0,r.jsxs)(t.p,{children:["This is a bit frustrating: we own the ",(0,r.jsx)(t.code,{children:"buffer"})," from which all the content was derived, and we don't have any\nunsafe accesses in our code. We guarantee that we wait for the child thread to stop first, so there's no possibility\nof the pointer becoming invalid because the original thread exits before the child thread does. So why is Rust\npreventing us from doing something that really should be legal?"]}),"\n",(0,r.jsxs)(t.p,{children:["This is what is known as ",(0,r.jsx)(t.a,{href:"https://doc.rust-lang.org/1.8.0/book/references-and-borrowing.html",children:"fighting the borrow checker"}),".\nLet our crusade begin."]}),"\n",(0,r.jsxs)(t.h2,{id:"attempt-2-put-the-reader-in-a-box",children:["Attempt 2: Put the ",(0,r.jsx)(t.code,{children:"Reader"})," in a ",(0,r.jsx)(t.code,{children:"Box"})]}),"\n",(0,r.jsxs)(t.p,{children:["The ",(0,r.jsx)(t.a,{href:"https://doc.rust-lang.org/std/boxed/struct.Box.html",children:(0,r.jsx)(t.code,{children:"Box"})})," type allows us to convert a pointer we have\n(in our case the ",(0,r.jsx)(t.code,{children:"point_reader"}),') into an "owned" value, which should be easier to send across threads.\nOur next attempt looks something like this:']}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-rust",children:"fn main() {\n\n // ...assume that we own a `buffer: Vec<u8>` containing the binary message content\n // from somewhere else\n\n let deserialized = capnp::serialize::read_message(\n &mut buffer.as_slice(),\n capnp::message::ReaderOptions::new()\n ).unwrap();\n\n let point_reader = deserialized.get_root::<point_capnp::point::Reader>().unwrap();\n\n let boxed_reader = Box::new(point_reader);\n\n // Now that the reader is `Box`ed, we've proven ownership, and Rust can\n // move the ownership to the new thread, right?\n let handle = std::thread::spawn(move || {\n\n assert_eq!(boxed_reader.get_x(), 12);\n\n assert_eq!(boxed_reader.get_y(), 14);\n });\n\n handle.join().unwrap();\n}\n"})}),"\n",(0,r.jsx)(t.p,{children:"Spoiler alert: still doesn't work. Same errors still show up."}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{children:"error[E0277]: the trait bound `*const u8: std::marker::Send` is not satisfied in `point_capnp::point::Reader<'_>` \n --\x3e src/main.rs:33:18 \n | \n33 | let handle = std::thread::spawn(move || { \n | ^^^^^^^^^^^^^^^^^^ `*const u8` cannot be sent between threads safely \n | \n\nerror[E0277]: the trait bound `*const capnp::private::layout::WirePointer: std::marker::Send` is not satisfied in `point_capnp::point::Reader<'_>` \n --\x3e src/main.rs:33:18 \n | \n33 | let handle = std::thread::spawn(move || { \n | ^^^^^^^^^^^^^^^^^^ `*const capnp::private::layout::WirePointer` cannot be sent between threads safely \n | \n\nerror[E0277]: the trait bound `capnp::private::arena::ReaderArena: std::marker::Sync` is not satisfied \n --\x3e src/main.rs:33:18 \n | \n33 | let handle = std::thread::spawn(move || { \n | ^^^^^^^^^^^^^^^^^^ `capnp::private::arena::ReaderArena` cannot be shared between threads safely \n | \n\nerror[E0277]: the trait bound `*const std::vec::Vec<std::option::Option<std::boxed::Box<capnp::private::capability::ClientHook + 'static>>>: std::marker::Send` is not satisfied in `point_capnp::point::Reader<'_>` \n --\x3e src/main.rs:33:18 \n | \n33 | let handle = std::thread::spawn(move || { \n | ^^^^^^^^^^^^^^^^^^ `*const std::vec::Vec<std::option::Option<std::boxed::Box<capnp::private::capability::ClientHook + 'static>>>` cannot be sent between threads safely \n | \n\nerror: aborting due to 4 previous errors\n"})}),"\n",(0,r.jsxs)(t.p,{children:["Let's be a little bit smarter about the exceptions this time though. What is that\n",(0,r.jsx)(t.a,{href:"https://doc.rust-lang.org/std/marker/trait.Send.html",children:(0,r.jsx)(t.code,{children:"std::marker::Send"})})," thing the compiler keeps telling us about?"]}),"\n",(0,r.jsxs)(t.p,{children:["The documentation is pretty clear; ",(0,r.jsx)(t.code,{children:"Send"})," is used to denote:"]}),"\n",(0,r.jsxs)(t.blockquote,{children:["\n",(0,r.jsx)(t.p,{children:"Types that can be transferred across thread boundaries."}),"\n"]}),"\n",(0,r.jsx)(t.p,{children:"In our case, we are seeing the error messages for two reasons:"}),"\n",(0,r.jsxs)(t.ol,{children:["\n",(0,r.jsxs)(t.li,{children:["\n",(0,r.jsxs)(t.p,{children:["Pointers (",(0,r.jsx)(t.code,{children:"*const u8"}),") are not safe to send across thread boundaries. While we're nice in our code\nmaking sure that we wait on the child thread to finish before closing down, the Rust compiler can't make\nthat assumption, and so complains that we're not using this in a safe manner."]}),"\n"]}),"\n",(0,r.jsxs)(t.li,{children:["\n",(0,r.jsxs)(t.p,{children:["The ",(0,r.jsx)(t.code,{children:"point_capnp::point::Reader"})," type is itself not safe to send across threads because it doesn't\nimplement the ",(0,r.jsx)(t.code,{children:"Send"})," trait. Which is to say, the things that make up a ",(0,r.jsx)(t.code,{children:"Reader"})," are themselves not thread-safe,\nso the ",(0,r.jsx)(t.code,{children:"Reader"})," is also not thread-safe."]}),"\n"]}),"\n"]}),"\n",(0,r.jsx)(t.p,{children:"So, how are we to actually transfer a parsed Cap'N Proto message between threads?"}),"\n",(0,r.jsxs)(t.h2,{id:"attempt-3-the-typedreader",children:["Attempt 3: The ",(0,r.jsx)(t.code,{children:"TypedReader"})]}),"\n",(0,r.jsxs)(t.p,{children:["The ",(0,r.jsx)(t.code,{children:"TypedReader"})," is a new API implemented in the Cap'N Proto ",(0,r.jsx)(t.a,{href:"https://crates.io/crates/capnp/0.8.14",children:"Rust code"}),".\nWe're interested in it here for two reasons:"]}),"\n",(0,r.jsxs)(t.ol,{children:["\n",(0,r.jsxs)(t.li,{children:["\n",(0,r.jsxs)(t.p,{children:["It allows us to define an object where the ",(0,r.jsx)(t.em,{children:"object"})," owns the underlying data. In previous attempts,\nthe current context owned the data, but the ",(0,r.jsx)(t.code,{children:"Reader"})," itself had no such control."]}),"\n"]}),"\n",(0,r.jsxs)(t.li,{children:["\n",(0,r.jsxs)(t.p,{children:["We can compose the ",(0,r.jsx)(t.code,{children:"TypedReader"})," using objects that are safe to ",(0,r.jsx)(t.code,{children:"Send"})," across threads, guaranteeing\nthat we can transfer parsed messages across threads."]}),"\n"]}),"\n"]}),"\n",(0,r.jsxs)(t.p,{children:["The actual type info for the ",(0,r.jsx)(t.a,{href:"https://github.com/capnproto/capnproto-rust/blob/f0efc35d7e9bd8f97ca4fdeb7c57fd7ea348e303/src/message.rs#L181",children:(0,r.jsx)(t.code,{children:"TypedReader"})}),"\nis a bit complex. And to be honest, I'm still really not sure what the whole point of the\n",(0,r.jsx)(t.a,{href:"https://doc.rust-lang.org/std/marker/struct.PhantomData.html",children:(0,r.jsx)(t.code,{children:"PhantomData"})})," thing is either.\nMy impression is that it lets us enforce type safety when we know what the underlying Cap'N Proto\nmessage represents. That is, technically the only thing we're storing is the untyped binary message;\n",(0,r.jsx)(t.code,{children:"PhantomData"})," just enforces the principle that the binary represents some specific object that has been parsed."]}),"\n",(0,r.jsx)(t.p,{children:"Either way, we can carefully construct something which is safe to move between threads:"}),"\n",(0,r.jsx)(t.pre,{children:(0,r.jsx)(t.code,{className:"language-rust",children:"fn main() {\n\n // ...assume that we own a `buffer: Vec<u8>` containing the binary message content from somewhere else\n\n let deserialized = capnp::serialize::read_message(\n &mut buffer.as_slice(),\n capnp::message::ReaderOptions::new()\n ).unwrap();\n\n let point_reader: capnp::message::TypedReader<capnp::serialize::OwnedSegments, point_capnp::point::Owned> =\n capnp::message::TypedReader::new(deserialized);\n\n // Because the point_reader is now working with OwnedSegments (which are owned vectors) and an Owned message\n // (which is 'static lifetime), this is now safe\n let handle = std::thread::spawn(move || {\n\n // The point_reader owns its data, and we use .get() to retrieve the actual point_capnp::point::Reader\n // object from it\n let point_root = point_reader.get().unwrap();\n\n assert_eq!(point_root.get_x(), 12);\n\n assert_eq!(point_root.get_y(), 14);\n });\n\n handle.join().unwrap();\n}\n"})}),"\n",(0,r.jsxs)(t.p,{children:["And while we've left Rust to do the dirty work of actually moving the ",(0,r.jsx)(t.code,{children:"point_reader"})," into the new thread,\nwe could also use things like ",(0,r.jsxs)(t.a,{href:"https://doc.rust-lang.org/std/sync/mpsc/index.html",children:[(0,r.jsx)(t.code,{children:"mpsc"})," channels"]})," to achieve a similar effect."]}),"\n",(0,r.jsx)(t.p,{children:"So now we're able to define basic Cap'N Proto messages, and send them all around our programs."})]})}function p(e={}){let{wrapper:t}={...(0,s.a)(),...e.components};return t?(0,r.jsx)(t,{...e,children:(0,r.jsx)(h,{...e})}):h(e)}},50065:function(e,t,n){n.d(t,{Z:function(){return i},a:function(){return o}});var a=n(67294);let r={},s=a.createContext(r);function o(e){let t=a.useContext(s);return a.useMemo(function(){return"function"==typeof e?e(t):{...t,...e}},[t,e])}function i(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(r):e.components||r:o(e.components),a.createElement(s.Provider,{value:t},e.children)}},9098:function(e){e.exports=JSON.parse('{"permalink":"/2018/01/captains-cookbook-part-2","source":"@site/blog/2018-01-16-captains-cookbook-part-2/index.mdx","title":"Captain\'s Cookbook: Practical usage","description":"A look at more practical usages of Cap\'N Proto","date":"2018-01-16T13:00:00.000Z","tags":[],"readingTime":6.51,"hasTruncateMarker":true,"authors":[{"name":"Bradlee Speice","socials":{"github":"https://github.com/bspeice"},"key":"bspeice","page":null}],"frontMatter":{"slug":"2018/01/captains-cookbook-part-2","title":"Captain\'s Cookbook: Practical usage","date":"2018-01-16T13:00:00.000Z","authors":["bspeice"],"tags":[]},"unlisted":false,"lastUpdatedAt":1731201811000,"prevItem":{"title":"Hello!","permalink":"/2018/05/hello"},"nextItem":{"title":"Captain\'s Cookbook: Project setup","permalink":"/2018/01/captains-cookbook-part-1"}}')}}]);