SOFTWARE AND DATA ENGINEERING
Linear Types Assume Convergence
## Introduction Linear types are types whose values must be used exactly once, in all branches a program can take. To be “used” here means “used by some operation”, for example by passing, returning, storing, or destroying the value. This is as opposed to not being used in an operation, which in a stack language would be akin to the value being popped off the stack.1 1 To expand on this: linear types are types which in the substructural types framework allow for “exchange”, but not “weakening” or “contraction”. In a stack language, this allows linear values to be reordered, but not freely discarded or duplicated: each must be consumed exactly once. Rust’s type system is affine, which means you can’t use a value after it’s been moved, preventing classes of bugs like use-after-free. Linear types are even stricter and require that a value must be used, preventing bugs like memory leaks. In this post I will cover how to encode linear types, their interaction with various language features, and how to model these interactions in the language using effects. I’m writing this post after having had conversations about this with Jana (Hexcat). Even though I’m writing this post from my perspective, I did not arrive at the insights in this post on my own. Thank you Jana! ## RAII counts as use For a while the intuition for how to add linear types to Rust was as a form of extra-strict
#[must_use] which required that a type must never be dropped. This was painful because if accepted, it would break common operations like branching and reassignment. Rust relies heavily on destructors, and forbidding them means we’re now fighting the language. rust rust let x = Foo {}; if cond { consume(x); } // Error: x is dropped in the `else` branch Copy My most important contribution to progressing linear types for Rust has been the insight that RAII counts as a valid “use”. Linear types in literature1 don’t stipulate by which method they should be used. They only require that values are never yeeted out of memory without being used as part of some operation. And there is no reason why Drop::drop couldn’t be that operation. 1 “Literature” meaning the chapter on substructural types in “Advanced Topics in Types and Programming Languages”. rust rust let x = Foo {}; if cond { consume(x); } // Ok, destructor called in the `else` branch Copy If this isn’t intuitive, think about it this way: if we want to guarantee that we never leak any sockets or file descriptors, all we need to do is guarantee that their destructors are always called. We can try to do that by hand, but we might make mistakes and so we can’t fully guarantee it. Linear types give us the tools to make those guarantees as a part of the language. ## Linearity and divergence are mutually exclusive Say we have some trait Leak which when absent means: “this type is linear”. We could introduce some type Foo which has linear semantics as follows: rust rust /// When a type is `!Leak` it implements linear semantics unsafe auto trait Leak {} /// A type which has linear semantics struct Foo { .. } impl !Leak for Foo {} Copy What we now have to do is guarantee that any instance of Foo has its destructor run. The easiest way to break that guarantee is probably the following: rust rust let x = Foo {}; loop {} Copy Here we create an instance of Foo, but its destructor will never be called. That is because loop {} loops forever and never terminates. Let’s try another program that does something very similar: rust rust let x = Foo {}; std::process::exit(0); Copy Here too we never actually run the destructors of x, because the program terminates before we have a chance to run them. Its docs specifically call out that destructors won’t be run. Now on to one last program: rust rust let x = Foo {}; panic!("oh no"); Copy This program will run the destructors of x when compiled with panic=unwind, but it won’t when compiled with panic=abort. And since that option exists outside of the type system, we have to assume that panicking may not run destructors.1 1 I plan to dig into unwinding and panicking more deeply in a future post. For the purposes of this post: just assume that all functions which may panic also imply divergence. Though I suspect that we can split unwinding and divergence from panic. What all of these examples have in common is that they return the never type (!). That is because they never actually return, instead interrupting the usual flow of the program. As a rule, linear types cannot be held across operations which evaluate to !.1 1 Local control flow like return, break, and continue (and by extension ?) is also typed !, but it is fine: control is handed back to an enclosing scope, which runs destructors on the way out. The problem is only operations which never hand control back. But that’s not enough to guarantee linearity: we can emulate infinite loops via recursion too, and so we need rules for that as well. For example: rust rust fn bar() { bar() } let x = Foo {}; bar(); Copy This snippet is no different than if we called loop {} at the end. The destructor will never run, despite the return type of bar being unit (()) and not never (!). ## The divergence effect In effect systems, all of these forms of divergence are captured by the divergence effect. This is often shortened to div. Under the effect rules we’re proposing, functions which carry an explicit !div marker are guaranteed to terminate (“converge”). Using the with-notation that would look as follows: rust rust fn foo() with !div { ... } // function let x = || with !div { ... }; // closure let x = with !div { ... }; // block Copy The way this works is by restricting the set of allowed operations in a !div function to only those which the compiler can prove will terminate. Just like with const, this should be deny-by-default: all operations are disallowed unless we can prove them safe. In Rust that would mean no loop {}, and no calls to functions returning never (!). But also no recursion, even through indirection: rust rust // recursion, but with more steps fn a() { b() } fn b() { c() } fn c() { a() } a(); Copy Indirect calls through function pointers and trait objects would also be disallowed by default, unless their types carry the !div marker too (e.g. dyn Fn() with !div). Some amount of looping would still be possible, but only over provably bounded iterators. In today’s Rust, something like TrustedLen, restricted to a finite upper bound, could provide the length guarantee. In an effect-aware version of Rust, we would also require Iterator::next to be !div, since TrustedLen currently does not prohibit divergence: > The iterator must produce exactly the number of elements it reported or > diverge before reaching the end. The rule for linear types would be something like: “Values of types implementing !Leak may only be held in !div contexts”. Since !div contexts also prohibit diverging expressions like loop {} and calls to functions returning !, that then solves their interaction: | | Foo: !Leak | fn bar() -> ! | | ----------- | ------------ | --------------- | | with div | Disallowed | Allowed | | with !div | Allowed | Disallowed | This means that linear values can’t be held across, say, a server’s accept loop. Linear values can only be held within !div contexts, which themselves may be used within a loop. But as I’ve covered before: with effects around 80% of a typical program does not need to carry any effects at all, 15% may want to error or diverge, and only around 5% touches IO. ## Leak is not Forget There is also a weaker guarantee than !Leak we can provide via !Forget. !Leak guarantees a destructor is always run, but !Forget guarantees that when a type goes out of scope its destructor is run. The difference is that !Forget never actually guarantees a value will go out of scope, it only explains what will happen when it does. A different way to think of it is that !Forget prohibits a type’s lifetime from being promoted to 'static. To enable a futures-based version of thread::scope we likely can get away with only requiring !Forget. Ideally we would start with Forget and only introduce Leak later on. But since Forget: Leak, any code relaxing its bounds to ?Forget would still imply Leak. We would need to make sure that introducing Leak later doesn’t end up being a breaking change. Put together, the two traits might look something like this: rust rust /// Types whose destructor is not guaranteed to run. /// /// This is a type compatible with diverging functions. These /// are functions which may contain unbounded loops, recursion, /// and calls to operations returning `!` (never). pub unsafe auto trait Leak {} /// Types whose lifetime can be promoted to `'static`. /// /// Types implementing `Forget` may be passed to `mem::forget`, /// or placed in `Rc` or `Arc` cycles created through `UnsafeCell`. /// These types may also be held for the remainder of the /// program via `Box::leak`, `thread::spawn`, and `static`. pub unsafe auto trait Forget: Leak {} Copy ## External termination Something linear types cannot model is behavior which exists outside of the program’s boundaries. Linear types cannot guarantee destructors are run if, say, the kernel crashes, or the computer it runs on loses power. The way to improve program resiliency in those cases could be by fixing bugs in the kernel and using an uninterruptible power supply (UPS).1 1 Also particularly interesting here is durable computing. The way I think about linear types is that they work in tandem with improvements to program execution environments. A more stable kernel and a UPS are not quite as impactful if the software we run on them constantly crashes. And vice versa: running ultra-stable software on failing hardware doesn’t create a good experience either. ## Conclusion In this post I’ve explained what linear types are, how we can encode them in Rust using Drop, how they interact with the never type, and finally how we can encode the divergence effect in the language to manage the interactions between linear types and the never type. We also looked at the weaker !Forget guarantee, which may be a good first step towards full linearity. Non-divergence is not the only requirement for linear types, we also need to rule out things like mem::forget, Rc cycles, and statics. But being able to prove it certainly is an important requirement.JANARUST
CONSTRUCTION HOUSING AND REAL ESTATE
A by-based delegation notation
## Introduction In a recent lang design meeting Petrochenkov outlined a design for delegation based on a new
reuse keyword. I unfortunately had to drop off early because of a work conflict, so unfortunately I couldn’t participate in the discussion. I've been thinking a little more about delegation since. Though I like the idea of delegation and the scope at which it's applied, I feel like the reuse proposal isn't quite where it needs to be yet. Kotlin’s by keyword (“provided by”) also provides delegation, and I think it is closer to what a Rust feature should feel like: - For traits you’d use impl..for..by (“trait impl foo is provided by bar”) - For impl blocks you'd use impl..by (“inherent impl is provided by bar”) - For individual methods you’d use fn..by (“function foo is provided by bar”) Usually I try to provide some degree of analysis and detail in my posts. But I'm quite short on time, so the best I can provide is a big list of translated examples from RFC 3530 to show you what I think we could do instead. ## Forwarding a trait implementation Here we forward the Hash implementation from some inner type to the outer type. rust rust // Setup pub struct BTreeSet<T> { inner: BTreeMap<T, ()>, } // 1. Before impl<T: Hash> Hash for BTreeSet<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.inner.hash(state) } } // 2. Using the `reuse` keyword proposal from RFC 3530 impl<T: Hash> Hash for BTreeSet<T> { reuse Hash::hash { self.inner } } // 3. Using a Kotlin-inspired `by` keyword. impl<T: Hash> Hash for BTreeSet<T> by self.inner; Copy ## Forwarding to a differently named method The by spelling below assumes Self::iter can resolve through Self = &'a BTreeSet<T> to BTreeSet::iter. This assumes some amount of auto-deref working at the path level. But it’s not too bad either; perhaps something like: “Check the reference first; if it isn’t there, check the referenced type.” rust rust // Setup pub type Iter<'a, T> = btree_map::Keys<'a, T, ()>; pub struct BTreeSet<T> { inner: BTreeMap<T, ()>, } impl<T> BTreeSet<T> { pub fn iter(&self) -> Iter<'_, T> { self.inner.keys() } } // 1. Before impl<'a, T> IntoIterator for &'a BTreeSet<T> { type Item = &'a T; type IntoIter = Iter<'a, T>; fn into_iter(self) -> Iter<'a, T> { self.iter() } } // 2. Using the `reuse` keyword proposal from RFC 3530 impl<'a, T> IntoIterator for &'a BTreeSet<T> { type Item = &'a T; type IntoIter = Iter<'a, T>; reuse BTreeSet::<T>::iter as into_iter; } // 3. Using a Kotlin-inspired `by` keyword impl<'a, T> IntoIterator for &'a BTreeSet<T> { type Item = &'a T; type IntoIter = Iter<'a, T>; fn into_iter by Self::iter; } Copy ## Forwarding one inherent method Here we forward a single method from an inner type to the outer type. rust rust // Setup pub struct BTreeSet<T> { inner: BTreeMap<T, ()>, } // 1. Before impl<T> BTreeSet<T> { pub fn len(&self) -> usize { self.inner.len() } } // 2. Using the `reuse` keyword proposal from RFC 3530 impl<T> BTreeSet<T> { pub reuse BTreeMap::<T, ()>::len { self.inner } } // 3. Using a Kotlin-inspired `by` keyword impl<T> BTreeSet<T> { pub fn len by self.inner; } Copy ## Forwarding multiple inherent methods BTreeMap has 20 or so methods defined on it, but we’re only choosing to forward two of those to BTreeSet. rust rust // Setup pub struct BTreeSet<T> { inner: BTreeMap<T, ()>, } // 1. Before: expanded from the delegation example impl<T> BTreeSet<T> { pub fn len(&self) -> usize { self.inner.len() } pub fn is_empty(&self) -> bool { self.inner.is_empty() } } // 2. Using the `reuse` keyword proposal from RFC 3530 impl<T> BTreeSet<T> { pub reuse BTreeMap::<T, ()>::{len, is_empty} { self.inner } } // 3. Using a Kotlin-inspired `by` keyword impl<T> BTreeSet<T> { pub fn len by self.inner; pub fn is_empty by self.inner; } Copy ## Forwarding all inherent methods RFC 3530 states: “the path prefixes in glob delegations can only refer to traits” (ref), which means that when delegating inherent methods each method must be individually delegated. The by keyword is a bit more powerful and can batch delegate methods. This is probably a case worth looking more closely at when doing a more thorough pass. I feel like the by form is fairly unambiguous in what it should refer to here. We’re not implementing any trait, so the only thing this could refer to is all the inherent items present on BTreeSet::inner. rust rust // Setup pub struct BTreeSet<T> { inner: BTreeMap<T, ()>, } // 1. Before impl<T> BTreeSet<T> { pub fn len(&self) -> usize { self.inner.len() } pub fn is_empty(&self) -> bool { self.inner.is_empty() } pub fn clear(&mut self) { self.inner.clear() } pub fn append(&mut self, other: &mut Self) where T: Ord, { self.inner.append(&mut other.inner) } pub fn keys(&self) -> btree_map::Keys<'_, T, ()> { self.inner.keys() } pub fn values(&self) -> btree_map::Values<'_, T, ()> { self.inner.values() } // ... more forwarding methods omitted. } // 2. Using the `reuse` keyword proposal from RFC 3530 impl<T> BTreeSet<T> { pub reuse BTreeMap::<T, ()>::{ len, is_empty, clear, append, keys, values, // ... more forwarding methods omitted. } { self.inner } } // 3. Using a Kotlin-inspired `by` keyword impl<T> BTreeSet<T> by self.inner; Copy ## Renaming a forwarded method The by keyword always requires spelling out the export name and the import target, so renaming is mostly a matter of changing the export name. rust rust // Setup pub struct BTreeSet<T> { inner: BTreeMap<T, ()>, } // 1. Before impl<T> BTreeSet<T> { pub fn contains<Q>(&self, value: &Q) -> bool where T: Borrow<Q> + Ord, Q: Ord + ?Sized, { self.inner.contains_key(value) } } // 2. Using the `reuse` keyword proposal from RFC 3530 impl<T> BTreeSet<T> { pub reuse BTreeMap::<T, ()>::contains_key as contains { self.inner } } // 3. Using a Kotlin-inspired `by` keyword impl<T> BTreeSet<T> { pub fn contains by self.inner.contains_key; } Copy ## Forwarding an associated function Path traversal through fields with by uses the . notation. Method selection on Self uses regular path traversal in the form of Self::foo. This is not too different from reuse, except that we’re opting to enable the use of Self instead of always requiring fully qualified names. Though there is likely nothing preventing RFC 3530 from later adding support for that too. rust rust // Setup pub struct BTreeSet<T> { inner: BTreeMap<T, ()>, } impl<T> BTreeSet<T> { pub fn new() -> Self { Self { inner: BTreeMap::new(), } } } // 1. Before impl<T> Default for BTreeSet<T> { fn default() -> BTreeSet<T> { BTreeSet::new() } } // 2. Using the `reuse` keyword proposal from RFC 3530 impl<T> Default for BTreeSet<T> { reuse BTreeSet::<T>::new as default; } // 3. Using a Kotlin-inspired `by` keyword impl<T> Default for BTreeSet<T> { fn default by Self::new; } Copy ## Projecting multiple operands Here the delegation needs to delegate both self → self.inner and other → other.inner. The RFC spells the rules out for this, so all we really have show here is a different way of spelling the same thing. rust rust // Setup pub struct BTreeSet<T> { inner: BTreeMap<T, ()>, } // 1. Before impl<T: PartialEq> PartialEq for BTreeSet<T> { fn eq(&self, other: &BTreeSet<T>) -> bool { self.inner.eq(&other.inner) } } // 2. Using the `reuse` keyword proposal from RFC 3530 impl<T: PartialEq> PartialEq for BTreeSet<T> { reuse PartialEq::eq { self.inner } } // 3. Using a Kotlin-inspired `by` keyword impl<T: PartialEq> PartialEq for BTreeSet<T> by self.inner; Copy ## Returning the wrapper and delegating a whole trait The RFC explains why this notation automatically delegates both clone and clone_from for reuse. Again: what I’m suggesting here is basically the same thing, but using a different notation. rust rust // Setup pub struct BTreeSet<T> { inner: BTreeMap<T, ()>, } // 1. Before impl<T: Clone> Clone for BTreeSet<T> { fn clone(&self) -> Self { BTreeSet { inner: self.inner.clone(), } } fn clone_from(&mut self, source: &Self) { self.inner.clone_from(&source.inner); } } // 2. Using the `reuse` keyword proposal from RFC 3530 reuse impl<T: Clone> Clone for BTreeSet<T> { self.inner } // 3. Using a Kotlin-inspired `by` keyword impl<T: Clone> Clone for BTreeSet<T> by self.inner; Copy ## Delegating a trait while overriding one method The by variant omits type Item because it forwards the delegate's Iterator::Item unchanged. rust rust // Setup struct Wrapper<I> { inner: I, } // 1. Before impl<I: Iterator> Iterator for Wrapper<I> { type Item = I::Item; fn next(&mut self) -> Option<Self::Item> { self.inner.next() } fn size_hint(&self) -> (usize, Option<usize>) { (0, None) } fn count(self) -> usize { self.inner.count() } // Other forwarding methods omitted. } // 2. Using the `reuse` keyword proposal from RFC 3530 impl<I: Iterator> Iterator for Wrapper<I> { type Item = I::Item; reuse Iterator::* { self.inner } fn size_hint(&self) -> (usize, Option<usize>) { (0, None) } } // 3. Using a Kotlin-inspired `by` keyword impl<I: Iterator> Iterator for Wrapper<I> by self.inner { fn size_hint(&self) -> (usize, Option<usize>) { (0, None) } } Copy ## Choosing between multiple trait implementations This is a fun case where we have to use an additional explicit by delegation on a trait method to be able to spell out the exact path we’re selecting: <self.inner as Trait<()>>::foo is proposed syntax for qualifying the projected inner field; it is not existing Rust syntax. rust rust // Setup trait Trait<T> { fn foo(&self); } struct Inner; impl Trait<i32> for Inner { fn foo(&self) {} } impl Trait<()> for Inner { fn foo(&self) {} } struct Wrapper { inner: Inner, } // 1. Before impl<T> Trait<T> for Wrapper { fn foo(&self) { <Inner as Trait<()>>::foo(&self.inner) } } // 2. Using the `reuse` keyword proposal from RFC 3530 impl<T> Trait<T> for Wrapper { reuse <Inner as Trait<()>>::foo { self.inner } } // 3. Using a Kotlin-inspired `by` keyword impl<T> Trait<T> for Wrapper { fn foo by <self.inner as Trait<()>>::foo; } Copy ## Delegating an associated function to the inner type The by keyword can provide unambiguous lookup when delegating traits. impl Trait for Wrapper makes it clear we’re limiting our search for trait Trait. Then by providing by self.inner it’s now clear that we’re only interested in delegating to impl Trait for Inner. That makes any lookup of fn foo unambiguous. And in this case we can just delegate all methods at once, so the simple thing here does the right thing. rust rust // Setup trait Trait { fn foo() -> usize; } struct Inner; impl Trait for Inner { fn foo() -> usize { 42 } } struct Wrapper { inner: Inner, } // 1. Before impl Trait for Wrapper { fn foo() -> usize { <Inner as Trait>::foo() } } // 2. Using the `reuse` keyword proposal from RFC 3530 impl Trait for Wrapper { reuse <Inner as Trait>::foo; } // 3. Using a Kotlin-inspired `by` keyword impl Trait for Wrapper by self.inner; Copy ## Example: FlatMap The by variant omits type Item because it forwards the delegate's Iterator::Item unchanged. rust rust // Setup pub struct FlatMap<I, U, F> where I: Iterator, U: IntoIterator, F: FnMut(I::Item) -> U, { inner: Flatten<Map<I, F>>, } // 1. Before: representative forwarding methods impl<I, U, F> Iterator for FlatMap<I, U, F> where I: Iterator, U: IntoIterator, F: FnMut(I::Item) -> U, { type Item = U::Item; fn next(&mut self) -> Option<Self::Item> { self.inner.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } fn count(self) -> usize { self.inner.count() } // Other forwarding methods omitted. } // 2. Using the `reuse` keyword proposal from RFC 3530 impl<I, U, F> Iterator for FlatMap<I, U, F> where I: Iterator, U: IntoIterator, F: FnMut(I::Item) -> U, { type Item = U::Item; reuse Iterator::* { self.inner } } // 3. Using a Kotlin-inspired `by` keyword impl<I, U, F> Iterator for FlatMap<I, U, F> by self.inner where I: Iterator, U: IntoIterator, F: FnMut(I::Item) -> U; Copy ## API stability Something that seems important to account for is API stability of inner types. When delegating inherent methods with reuse there is no way to declare what the signature ought to be, making it a potential semver hazard when upgrading. With by that risk can be mitigated by allowing the full signature to be spelled out if desired: rust rust impl<T> BTreeSet<T> { pub fn len by self.inner; // shorthand pub fn len(&self) -> usize by self.inner; // full signature } Copy Using the full signature here would allow the delegation to provide an API guarantee, protecting against accidental breakage, but at the cost of being more verbose. Whether that tradeoff is one you want depends on what you’re doing. I expect the stdlib would probably always want it, but in my application code I probably wouldn’t. ## Conclusion I think what is most missing from the reuse keyword is a consistent feel with the rest of the language. One way to describe this is through edit distance, which itself translates to git diff noise. reuse feels very different from the rest of the language once you put items side by side. To enhance/zoom in on what I mean, consider what a method might look like when implemented, when defined in a trait without a body, and when delegated. Using the by keyword, we get something where each variant feels like it has a shared design language: rust rust // Using a Kotlin-inspired `by` keyword fn len(&self) -> usize { … } // impl fn len(&self) -> usize; // trait def fn len by self.inner; // delegation Copy The len method here is provided by delegating to the len method on inner. Now compare this with the reuse keyword. Delegating a function looks very different from implementing or defining it in a trait: rust rust // Using the `reuse` keyword proposal from RFC 3530 fn len(&self) -> usize { … } // impl fn len(&self) -> usize; // trait def reuse Foo::<T, ()>::len { self.inner } // delegation Copy The same happens when we look at trait impls. Delegating a trait implementation should feel similar to implementing it by hand. Here again is the by version, which fits in naturally: rust rust // Using a Kotlin-inspired `by` keyword impl Foo for Bar { … } // trait impl impl Foo for Bar by self.inner; // trait delegation Copy And the reuse version, which introduces a different item prefix: rust rust // Using the `reuse` keyword proposal from RFC 3530 impl Foo for Bar { … } // trait impl reuse impl Foo for Bar { self.inner } // trait delegation Copy Does it make sense what I'm saying? I feel like by is quite beautiful here. It makes for satisfying one-liners that feel like a natural extension to the language, and I think it’s worth considering as an alternative to reuse. It also would pair nicely with the with-notation I’ve described in previous posts, as well as existing keywords like where and for we already use in Rust. Note: I wish I had more time to work through all the rules involved here. Path disambiguation in particular would be worth spending time on. But I've got no time to spend, so I hope it's good enough at least to get the idea across. Note: I want to reiterate how useful the work in RFC 3530 has been. The hardest part of any RFC is not defining the solution, but defining the problem and scope. I want to make sure that even though we might have different ideas about some of the solutions, we are in agreement about the problems.PETROCHENKOV
CONSUMER ELECTRONICS AND ROBOTICS
LOGISTICS AND SUPPLY CHAINS
Pull Streams
This post is part of a series: - Pull Streams (current) - Rust Streams Streams are an asynchronous abstraction that allows dealing with large data sets in small chunks, pushing bottlenecks into the IO layer. This usually leads to less memory cost and increased performance, which is a very good thing. In streams, data flows from a Source, through a bunch of Through streams, into a Sink: txt
txt ┌────────┐ ┌─────────┐ ┌────────┐ │ Source │──▶│ Through │──▶│ Sink │ └────────┘ └─────────┘ └────────┘ Copy Node has shipped streams as part of its standard library since its early days. However with each release, new features, APIs and concepts were added, making the current implementation very unwieldy. In my years as a Node developer I've only met a handful of developers that felt comfortable using the current version of Node streams. In an ideal world streams would be used as much in Node as pipes are used in shell. ## Enter pull-streams pull-stream is an alternative model for streams created by Dominic Tarr. Like Node streams, it has a concept of backpressure. This means that instead of a source pushing out data as fast as it can, the consumer stream pulls data once it's ready to handle more. This leads to a program never holding more data in memory than it needs. The Node streams source is well over 1200 lines, without even accounting for dependencies. The pull-stream source is just 28 lines, which is a whopping 0.4kb minified: js js module.exports = function pull (a) { if (typeof a === 'function' && a.length === 1) { return function (read) { var args = [].slice.call(arguments) return pull.apply(null, args) } } var read = a var n = arguments.length var i = 1 if (read && typeof read.source === 'function') { read = read.source } for (; i < n; i++) { var s = arguments[i] if (typeof s === 'function') { read = s(read) } else if (s && typeof s === 'object') { s.sink(read) read = s.source } } return read } Copy Don’t be fooled by the simple exterior though, pull-stream provides the same functionality as Node streams do. With fewer lines of code there’ll be less bugs, and room to optimize every last bit of code. ## Pull-stream types In pull-streams there are 3 types of streams: source, through and sink. In order to let data flow, a source and sink must be connected. Through streams are combinations of sources and sinks, making every connection in the pipeline a source and a sink that talk to each other. Conceptually it looks like this: txt txt ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ │Source│──▶│ Sink │ ┌▶│ Sink │ ┌▶│ Sink │ └──────┘ ├──────┤ │ ├──────┤ │ └──────┘ │Source│─┘ │Source│─┘ └──────┘ └──────┘ Through Through Copy If a source and a through stream are connected they will not start emitting data until a sink is attached at the end. Likewise, if a through and sink are connected, they will not start flowing data until a source is attached at the start. This allows composition of arbitrary streams into pipelines similar to what pumpify provides for Node streams. ## Composition pull-streams use the pull() function to combine sinks and sources. Because sinks connect to sources, any number of streams can be connected. It's functional composition all the way. Duplex (through) streams are objects that have a .source and .sink properties on them. The following three methods of connecting pull-streams are equivalent: js js pull(a.source, b.sink) pull(b.source, a.sink) Copy js js b.sink(a.source) a.sink(b.source) Copy js js pull(a, b, a) Copy ## Helper functions pull-stream ships with helper functions such as asyncMap that make common interactions trivial. See the docs for available sources, sinks and throughs. Let's create a basic map-reduce pipeline using asyncMap where we asynchronously fs.stat an array of files, and gather the results in an array: js js const pull = require('pull') const fs = require('fs') const source = pull.values([ './file1', './file2', './file3' ]) const through = pull.asyncMap(fs.stat) const sink = pull.collect(function (err, array) { if (err) return console.error(err) console.log(array) }) pull(source, through, sink) Copy Because under the hood we're just composing functions, the overhead of doing this is reduced to a bare minimum. ## Error handling In Node streams errors don't propagate through .pipe() chains. It's therefore common practice to either use helper libraries or attach a .on('error') listener to every stream. Getting errors wrong is not a great feeling. In pull-streams errors are passed into the callback, which grinds the whole stream pipeline to a halt. It's again the familiar API of cb(err) for an error and cb(null, value) for success. Here's a source stream that returns a single fs.stat value: js js const fs = require('fs') function readFile (filename) { var read = false // keep track if we've executed the action return function source (end, cb) { if (end) return cb(end) // stop signal was passed, stop doing things if (read) return cb(true) // we're done with fs.stat, stop doing things fs.stat(filename, function (err, file) { if (err) return cb(err) // ohey, an error read = true // mark that we've executed the action return cb(null, file) // pass value down the pipeline }) } } Copy ## Wrapping it up And that's it. I could keep whipping out pull-stream examples, but I think we've made our point: streams are a cool idea; pull-stream is a neat implementation. If you're keen to learn more, take a look at the links below. I hope this was useful; give pull-stream a try let me know how you go! -Yosh - twitter/yoshuawuyts - github/yoshuawuyts ## See Also - pull-stream - pull-stream-examples - pull-stream/spec - pull-stream/sources - pull-stream/sinks - pull-stream/throughsCOMPUTING INFRASTRUCTURE AND TELECOMMUNICATIONS
A New Blog
Hey everyone! Welcome to my new blog. Stretch your legs. Make yourself at home. ## Why? I used to be quite active on Medium.com, but I don't think the site has been changing for the better, and want to try something new. Something that's my own. Something where I have the creative freedom to structure it however I like. So this is it. ## Is this a dat:// site? It's not. At least: not yet. Perhaps we'll get there eventually, but for now I'm happy to build a static site, and distribute it from my own server. I've always wanted to be better at managing servers, and this is a fun addition to my growing collection of things running on a single 5/euro month instance. Keeping things static means performance is reliable, and reliability is nice for hobby projects. A long story short: perhaps I'll make the jump to dat:// eventually. But not right now. ## Source You can find the source on github.com/yoshuawuyts/blog, and the server configuration on github.com/yoshuawuyts/server. The theme is Zola After Dark, but I expect it won't be long before I start tinkering with it. ## Wrapping Up Thanks for reading! I hope you visit again soon!