1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
use std::{
    borrow::Cow,
    thread::{spawn, JoinHandle, Scope, ScopedJoinHandle},
};

use anyhow::Result;
use crossbeam::channel::{bounded, Receiver, Sender};
use indicatif::ProgressBar;

use crate::util::logging::{measure_and_recv, measure_and_send, meter_bar};

use super::ObjectWriter;

enum WorkHandle<'scope> {
    Static(JoinHandle<Result<usize>>),
    Scoped(ScopedJoinHandle<'scope, Result<usize>>),
}

fn ferry<T, W>(recv: Receiver<T>, writer: W, pb: ProgressBar) -> Result<usize>
where
    T: Send + Sync + 'static,
    W: ObjectWriter<T>,
{
    let mut writer = writer; // move writer into thread

    while let Some(obj) = measure_and_recv(&recv, &pb) {
        writer.write_object(obj)?;
    }

    pb.finish_and_clear();
    writer.finish()
}

pub struct ThreadObjectWriterBuilder<W> {
    writer: W,
    name: String,
    capacity: usize,
}

/// Write objects in a background thread.
pub struct ThreadObjectWriter<'scope, T>
where
    T: Send + Sync + 'static,
{
    sender: Sender<T>,
    handle: WorkHandle<'scope>,
    meter: ProgressBar,
}

impl<'scope, T> ThreadObjectWriter<'scope, T>
where
    T: Send + Sync + 'scope,
{
    pub fn wrap<W>(writer: W) -> ThreadObjectWriterBuilder<W>
    where
        W: ObjectWriter<T> + Send + Sync + 'scope,
    {
        ThreadObjectWriterBuilder {
            writer,
            name: "unnamed".into(),
            capacity: 100,
        }
    }
}

impl<W> ThreadObjectWriterBuilder<W> {
    /// Set the channel capacity for this thread writer.  Defaults to 100.
    pub fn with_capacity(self, cap: usize) -> Self {
        ThreadObjectWriterBuilder {
            capacity: cap,
            ..self
        }
    }

    /// Set a name for this thread writer for debugging.
    pub fn with_name<S: Into<Cow<'static, str>>>(self, name: S) -> Self {
        let name: Cow<'static, str> = name.into();
        ThreadObjectWriterBuilder {
            name: name.to_string(),
            ..self
        }
    }

    /// Spawn the thread writer.
    pub fn spawn_scoped<'scope, 'env, T>(
        self,
        scope: &'scope Scope<'scope, 'env>,
    ) -> ThreadObjectWriter<'scope, T>
    where
        W: ObjectWriter<T> + Send + Sync + 'scope,
        T: Send + Sync + 'scope,
    {
        let (sender, receiver) = bounded(self.capacity);
        let pb = meter_bar(self.capacity, &format!("{} buffer", self.name));

        let rpb = pb.clone();
        let h = scope.spawn(move || ferry(receiver, self.writer, rpb));

        ThreadObjectWriter {
            meter: pb,
            sender,
            handle: WorkHandle::Scoped(h),
        }
    }
}

impl<W> ThreadObjectWriterBuilder<W> {
    /// Spawn the thread writer.
    pub fn spawn<T>(self) -> ThreadObjectWriter<'static, T>
    where
        W: ObjectWriter<T> + Send + Sync + 'static,
        T: Send + Sync + 'static,
    {
        let (sender, receiver) = bounded(self.capacity);
        let pb = meter_bar(self.capacity, &format!("{} buffer", self.name));

        let rpb = pb.clone();
        let h = spawn(move || ferry(receiver, self.writer, rpb));

        ThreadObjectWriter {
            meter: pb,
            sender,
            handle: WorkHandle::Static(h),
        }
    }
}

impl<'scope, T: Send + Sync + 'scope> ThreadObjectWriter<'scope, T> {
    /// Create a satellite writer that writes to the same backend as this
    /// writer.
    ///
    /// Satellites can be used to enable multiple data-generating threads to
    /// write to the same thread writer, turning it into a multi-producer,
    /// single-consumer writing pipeline.  Satellite writers should be finished,
    /// and closing them does not finish the original thread writer (it still
    /// needs to have [ObjectWriter::finish] called, typically after all
    /// satellites are done, but it calling [ObjectWriter::finish] while
    /// satellites are still active will wait until the satellites have finished
    /// and closed their connections to the consumer thread).
    ///
    /// Satellites hold a reference to the original thread writer, to discourage
    /// keeping them alive after the thread writer has been finished.  They
    /// work best with [std::thread::scope]:
    ///
    /// ```rust,ignore
    /// let writer = ThreadWriter::new(writer);
    /// scope(|s| {
    ///     for i in 0..NTHREADS {
    ///         let out = writer.satellite();
    ///         s.spawn(move || {
    ///             // process and write to out
    ///             out.finish().expect("closing writer failed");
    ///         })
    ///     }
    /// })
    /// ```
    pub fn satellite<'a>(&'a self) -> ThreadWriterSatellite<'a, 'scope, T>
    where
        'scope: 'a,
    {
        ThreadWriterSatellite::create(self)
    }
}

impl<'scope, T: Send + Sync + 'static> ObjectWriter<T> for ThreadObjectWriter<'scope, T> {
    fn write_object(&mut self, object: T) -> Result<()> {
        measure_and_send(&self.sender, object, &self.meter)?;
        Ok(())
    }

    fn finish(self) -> Result<usize> {
        // dropping the sender will cause the consumer to hang up.
        drop(self.sender);
        // wait for the consumer to finish before we consider the writer closed.
        let res = match self.handle {
            WorkHandle::Static(h) => h.join().map_err(std::panic::resume_unwind)?,
            WorkHandle::Scoped(h) => h.join().map_err(std::panic::resume_unwind)?,
        };
        res
    }
}

/// Child writer to allow objects to be written to a threaded writer from multiple
/// threads, allowing parallel feeding of data.  It takes a **reference** to the
/// original thread writer, so it needs to be used with [std::thread::scope]. The
/// original writer still needs to be closed, and this design ensures that the
/// original cannot be closed until all the children are finished.
#[derive(Clone)]
pub struct ThreadWriterSatellite<'a, 'scope, T>
where
    T: Send + Sync + 'static,
    'scope: 'a,
{
    delegate: &'a ThreadObjectWriter<'scope, T>,
    sender: Sender<T>,
}

impl<'a, 'scope, T> ThreadWriterSatellite<'a, 'scope, T>
where
    T: Send + Sync + 'static,
    'scope: 'a,
{
    /// Create a new thread child writer.
    fn create(delegate: &'a ThreadObjectWriter<'scope, T>) -> ThreadWriterSatellite<'a, 'scope, T> {
        ThreadWriterSatellite {
            delegate,
            sender: delegate.sender.clone(),
        }
    }
}

impl<'a, 'scope, T> ObjectWriter<T> for ThreadWriterSatellite<'a, 'scope, T>
where
    T: Send + Sync + 'static,
    'scope: 'a,
{
    fn write_object(&mut self, object: T) -> Result<()> {
        measure_and_send(&self.sender, object, &self.delegate.meter)?;
        Ok(())
    }

    fn finish(self) -> Result<usize> {
        // do nothing, dropping the writer will close the sender
        Ok(0)
    }
}