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
// 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.

use std::any::Any;
use std::fs::OpenOptions;
use std::rc::Rc;

use differential_dataflow::{Collection, Hashable};

use itertools::repeat_n;
use timely::dataflow::channels::pact::Exchange;
use timely::dataflow::operators::generic::Operator;
use timely::dataflow::Scope;
use tracing::error;

use dataflow_types::sinks::{AvroOcfSinkConnector, SinkDesc};
use expr::GlobalId;
use interchange::avro::{encode_datums_as_avro, AvroSchemaGenerator};
use repr::{Diff, RelationDesc, Row, Timestamp};

use crate::render::sinks::SinkRender;

use super::SinkBaseMetrics;

impl<G> SinkRender<G> for AvroOcfSinkConnector
where
    G: Scope<Timestamp = Timestamp>,
{
    fn uses_keys(&self) -> bool {
        false
    }

    fn get_key_indices(&self) -> Option<&[usize]> {
        None
    }

    fn get_relation_key_indices(&self) -> Option<&[usize]> {
        None
    }

    fn render_continuous_sink(
        &self,
        _compute_state: &mut crate::render::ComputeState,
        _sink: &SinkDesc,
        sink_id: GlobalId,
        sinked_collection: Collection<G, (Option<Row>, Option<Row>), Diff>,
        _metrics: &SinkBaseMetrics,
    ) -> Option<Rc<dyn Any>>
    where
        G: Scope<Timestamp = Timestamp>,
    {
        avro_ocf(
            sinked_collection,
            sink_id,
            self.clone(),
            self.value_desc.clone(),
        );

        // no sink token
        None
    }
}

fn avro_ocf<G>(
    collection: Collection<G, (Option<Row>, Option<Row>)>,
    id: GlobalId,
    connector: AvroOcfSinkConnector,
    desc: RelationDesc,
) where
    G: Scope<Timestamp = Timestamp>,
{
    let collection = collection.map(|(k, v)| {
        assert!(k.is_none(), "Avro OCF sinks must not have keys");
        let v = v.expect("Avro OCF sinks must have values");
        v
    });
    let (schema, columns) = {
        let schema_generator = AvroSchemaGenerator::new(None, None, None, desc, false);
        let schema = schema_generator.value_writer_schema().clone();
        let columns = schema_generator.value_columns().to_vec();
        (schema, columns)
    };

    let mut vector = vec![];
    let mut avro_writer = None;

    // We want exactly one worker to write to the single output file
    let hashed_id = id.hashed();

    collection.inner.sink(
        Exchange::new(move |_| hashed_id),
        &format!("avro-ocf-{}", id),
        move |input| {
            input.for_each(|_, rows| {
                rows.swap(&mut vector);

                let mut fallible = || -> Result<(), String> {
                    let avro_writer = match avro_writer.as_mut() {
                        Some(v) => v,
                        None => {
                            let file = OpenOptions::new()
                                .append(true)
                                .open(&connector.path)
                                .map_err(|e| {
                                    format!("creating avro ocf file writer for sink failed: {}", e)
                                })?;
                            avro_writer.get_or_insert(mz_avro::Writer::new(schema.clone(), file))
                        }
                    };

                    for (v, _time, diff) in vector.drain(..) {
                        let value = encode_datums_as_avro(v.iter(), &columns);
                        assert!(diff > 0, "can't sink negative multiplicities");
                        for value in repeat_n(value, diff as usize) {
                            avro_writer
                                .append(value)
                                .map_err(|e| format!("appending to avro ocf failed: {}", e))?;
                        }
                    }
                    avro_writer
                        .flush()
                        .map_err(|e| format!("flushing bytes to avro ocf failed: {}", e))?;
                    Ok(())
                };

                if let Err(e) = fallible() {
                    error!("{}", e);
                }
            })
        },
    )
}