1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use std::convert::TryInto;
use std::io::BufRead;
use std::mem::replace;
use std::str;
use std::thread::{scope, spawn, JoinHandle, ScopedJoinHandle};

use crossbeam::channel::bounded;
use log::*;

use anyhow::{anyhow, Result};
use quick_xml::events::attributes::Attributes;
use quick_xml::events::Event;
use quick_xml::Reader;

use crate::io::object::{ChunkWriter, ThreadObjectWriter, UnchunkWriter};
use crate::io::ObjectWriter;
use crate::tsv::split_first;
use crate::util::logging::{measure_and_recv, measure_and_send, meter_bar};
use crate::util::StringAccumulator;

use super::record::*;

const CHUNK_LINES: usize = 5000;
const CHUNK_BUFFER_SIZE: usize = 20;

#[derive(Debug, Default)]
struct Codes {
    tag: i16,
    ind1: Code,
    ind2: Code,
}

impl From<Codes> for Field {
    fn from(c: Codes) -> Field {
        Field {
            tag: c.tag,
            ind1: c.ind1,
            ind2: c.ind2,
            subfields: Vec::new(),
        }
    }
}

/// Read MARC records from XML.
pub fn scan_records<R, W>(reader: R, output: &mut W) -> Result<usize>
where
    R: BufRead,
    W: ObjectWriter<MARCRecord>,
{
    let mut reader = Reader::from_reader(reader);
    let mut nrecs = 0;
    let mut buffer = Vec::with_capacity(4096);
    loop {
        match reader.read_event_into(&mut buffer)? {
            Event::Start(ref e) => {
                let name = e.local_name();
                match name.into_inner() {
                    b"record" => {
                        let rec = read_record(&mut reader)?;
                        output.write_object(rec)?;
                        nrecs += 1;
                    }
                    _ => (),
                }
            }
            Event::Eof => return Ok(nrecs),
            _ => (),
        }
    }
}

/// Read MARC records from delimited XML.
///
/// This reader parses the XML in parallel, since XML parsing is typically
/// the bottleneck for MARC scanning.
pub fn scan_records_delim<R, W>(reader: R, output: &mut W) -> Result<usize>
where
    R: BufRead + Send + 'static,
    W: ObjectWriter<MARCRecord> + Sync + Send,
{
    let lines = reader.lines();

    let output = ChunkWriter::new(output);
    let fill = meter_bar(CHUNK_BUFFER_SIZE, "input chunks");

    let nrecs: Result<usize> = scope(|outer| {
        // scoped thread writer to support parallel writing
        let output = ThreadObjectWriter::wrap(output)
            .with_name("marc records")
            .with_capacity(CHUNK_BUFFER_SIZE)
            .spawn_scoped(outer);
        // receivers & senders for chunks of lines
        let (chunk_tx, chunk_rx) = bounded(CHUNK_BUFFER_SIZE);

        // background thread getting lines
        info!("spawning reader thread");
        let fpb = fill.clone();
        let bg_read: JoinHandle<Result<usize>> = spawn(move || {
            let mut accum = Vec::with_capacity(CHUNK_LINES);
            let mut nlines = 0usize;
            for line in lines {
                let line = line?;
                let (_id, payload) = split_first(&line).ok_or_else(|| anyhow!("invalid line"))?;
                nlines += 1;
                accum.push(payload.to_owned());
                if accum.len() >= CHUNK_LINES {
                    let chunk = replace(&mut accum, Vec::with_capacity(CHUNK_LINES));
                    measure_and_send(&chunk_tx, chunk, &fpb).expect("channel send failure");
                }
            }
            if accum.len() > 0 {
                chunk_tx.send(accum).expect("channel send failure");
            }
            Ok(nlines)
        });

        let nrecs: Result<usize> = scope(|inner| {
            // how many workers to use? let's count the active threads
            //
            // 1. decompression
            // 2. parse lines
            // 3. serialize MARC records
            // 4. write Parquet file
            //
            // That leaves the remaining proessors to be used for parsing XML.
            let nthreads = 4;
            let mut workers: Vec<ScopedJoinHandle<'_, Result<usize>>> =
                Vec::with_capacity(nthreads as usize);
            info!("spawning {} parser threads", nthreads);
            for i in 0..nthreads {
                debug!("spawning parser thread {}", i + 1);
                let rx = chunk_rx.clone();
                let out = output.satellite();
                let out = UnchunkWriter::with_size(out, CHUNK_LINES);
                let fill = fill.clone();
                workers.push(inner.spawn(move || {
                    let mut out = out;
                    let mut nrecs = 0;
                    while let Some(chunk) = measure_and_recv(&rx, &fill) {
                        for line in chunk {
                            let res = parse_record(&line)?;
                            out.write_object(res)?;
                            nrecs += 1;
                        }
                    }
                    out.finish()?;
                    Ok(nrecs)
                }));
            }

            let mut nrecs = 0;
            for h in workers {
                nrecs += h.join().map_err(std::panic::resume_unwind)??;
            }
            Ok(nrecs)
        });
        let nrecs = nrecs?;

        bg_read.join().map_err(std::panic::resume_unwind)??;
        output.finish()?;
        Ok(nrecs)
    });
    let nrecs = nrecs?;

    info!("processed {} records", nrecs);
    Ok(nrecs)
}

/// Parse a single MARC record from an XML string.
pub fn parse_record<S: AsRef<str>>(xml: S) -> Result<MARCRecord> {
    let mut parse = Reader::from_str(xml.as_ref());
    read_record(&mut parse)
}

/// Read a single MARC record from an XML reader.
#[inline(never)] // make profiling a little easier, this fn isn't worth inlining
fn read_record<B: BufRead>(rdr: &mut Reader<B>) -> Result<MARCRecord> {
    let mut buf = Vec::new();
    let mut content = StringAccumulator::new();
    let mut record = MARCRecord {
        leader: String::new(),
        control: Vec::new(),
        fields: Vec::new(),
    };
    let mut field = Field::default();
    let mut tag = 0;
    let mut sf_code = Code::default();
    loop {
        match rdr.read_event_into(&mut buf)? {
            Event::Start(ref e) => {
                let name = e.local_name();
                match name.into_inner() {
                    b"record" => (),
                    b"leader" => {
                        content.activate();
                    }
                    b"controlfield" => {
                        tag = read_tag_attr(e.attributes())?;
                        content.activate();
                    }
                    b"datafield" => {
                        let codes = read_code_attrs(e.attributes())?;
                        field = codes.into();
                    }
                    b"subfield" => {
                        sf_code = read_sf_code_attr(e.attributes())?;
                        content.activate();
                    }
                    _ => (),
                }
            }
            Event::End(ref e) => {
                let name = e.local_name();
                match name.into_inner() {
                    b"leader" => {
                        record.leader = content.finish().to_owned();
                    }
                    b"controlfield" => record.control.push(ControlField {
                        tag: tag.try_into()?,
                        content: content.finish().to_owned(),
                    }),
                    b"subfield" => field.subfields.push(Subfield {
                        code: sf_code,
                        content: content.finish().to_owned(),
                    }),
                    b"datafield" => {
                        record.fields.push(field);
                        field = Field::default();
                    }
                    b"record" => return Ok(record),
                    _ => (),
                }
            }
            Event::Text(e) => {
                let t = e.unescape()?;
                content.add_slice(t);
            }
            Event::Eof => break,
            _ => (),
        }
    }
    Err(anyhow!("could not parse record"))
}

/// Read the tag attribute from a tag.
fn read_tag_attr(attrs: Attributes<'_>) -> Result<i16> {
    for ar in attrs {
        let a = ar?;
        if a.key.into_inner() == b"tag" {
            let tag = a.unescape_value()?;
            return Ok(tag.parse()?);
        }
    }

    Err(anyhow!("no tag attribute found"))
}

/// Read code attributes from a tag.
fn read_code_attrs(attrs: Attributes<'_>) -> Result<Codes> {
    let mut tag = 0;
    let mut ind1 = Code::default();
    let mut ind2 = Code::default();

    for ar in attrs {
        let a = ar?;
        let v = a.unescape_value()?;
        match a.key.into_inner() {
            b"tag" => tag = v.parse()?,
            b"ind1" => ind1 = v.as_bytes()[0].into(),
            b"ind2" => ind2 = v.as_bytes()[0].into(),
            _ => (),
        }
    }

    if tag == 0 {
        Err(anyhow!("no tag attribute found"))
    } else {
        Ok(Codes { tag, ind1, ind2 })
    }
}

/// Read the subfield code attriute from a tag
fn read_sf_code_attr(attrs: Attributes<'_>) -> Result<Code> {
    for ar in attrs {
        let a = ar?;
        if a.key.into_inner() == b"code" {
            let code = a.unescape_value()?;
            return Ok(code.as_bytes()[0].into());
        }
    }

    Err(anyhow!("no code found"))
}