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

//! Apache Parquet encodings and utils for persist data

use std::io::{Read, Seek, Write};

use arrow2::io::parquet::read::RecordReader;
use arrow2::io::parquet::write::RowGroupIterator;
use differential_dataflow::trace::Description;
use parquet2::compression::Compression;
use parquet2::encoding::Encoding;
use parquet2::metadata::KeyValue;
use parquet2::read::read_metadata;
use parquet2::write::{write_file, Version, WriteOptions};
use timely::progress::{Antichain, Timestamp};

use crate::error::Error;
use crate::gen::persist::ProtoBatchFormat;
use crate::indexed::columnar::arrow::{
    decode_arrow_batch_kvtd, encode_arrow_batch_kvtd, SCHEMA_ARROW_KVTD,
};
use crate::indexed::columnar::ColumnarRecords;
use crate::indexed::encoding::{
    decode_trace_inline_meta, decode_unsealed_inline_meta, encode_trace_inline_meta,
    encode_unsealed_inline_meta, BlobTraceBatch, BlobUnsealedBatch,
};
use crate::storage::SeqNo;

const INLINE_METADATA_KEY: &'static str = "MZ:inline";

/// Encodes an BlobUnsealedBatch into the Parquet format.
pub fn encode_unsealed_parquet<W: Write>(
    w: &mut W,
    batch: &BlobUnsealedBatch,
) -> Result<(), Error> {
    encode_parquet_kvtd(
        w,
        encode_unsealed_inline_meta(batch, ProtoBatchFormat::ParquetKvtd),
        &batch.updates,
    )
}

/// Encodes an BlobTraceBatch into the Parquet format.
pub fn encode_trace_parquet<W: Write>(w: &mut W, batch: &BlobTraceBatch) -> Result<(), Error> {
    encode_parquet_kvtd(
        w,
        encode_trace_inline_meta(batch, ProtoBatchFormat::ParquetKvtd),
        &batch.updates,
    )
}

/// Decodes a BlobUnsealedBatch from the Parquet format.
pub fn decode_unsealed_parquet<R: Read + Seek>(r: &mut R) -> Result<BlobUnsealedBatch, Error> {
    let metadata = read_metadata(r).map_err(|err| err.to_string())?;
    let metadata = metadata
        .key_value_metadata()
        .as_ref()
        .and_then(|x| x.iter().find(|x| x.key == INLINE_METADATA_KEY));
    let (format, meta) = decode_unsealed_inline_meta(metadata.and_then(|x| x.value.as_ref()))?;

    let updates = match format {
        ProtoBatchFormat::Unknown => return Err("unknown format".into()),
        ProtoBatchFormat::ArrowKvtd => {
            return Err("ArrowKvtd format not supported in parquet".into())
        }
        ProtoBatchFormat::ParquetKvtd => decode_parquet_file_kvtd(r)?,
    };

    let ret = BlobUnsealedBatch {
        desc: SeqNo(meta.seqno_lower)..SeqNo(meta.seqno_upper),
        updates,
    };
    ret.validate()?;
    Ok(ret)
}

/// Decodes a BlobTraceBatch from the Parquet format.
pub fn decode_trace_parquet<R: Read + Seek>(r: &mut R) -> Result<BlobTraceBatch, Error> {
    let metadata = read_metadata(r).map_err(|err| err.to_string())?;
    let metadata = metadata
        .key_value_metadata()
        .as_ref()
        .and_then(|x| x.iter().find(|x| x.key == INLINE_METADATA_KEY));
    let (format, meta) = decode_trace_inline_meta(metadata.and_then(|x| x.value.as_ref()))?;

    let updates = match format {
        ProtoBatchFormat::Unknown => return Err("unknown format".into()),
        ProtoBatchFormat::ArrowKvtd => {
            return Err("ArrowKVTD format not supported in parquet".into())
        }
        ProtoBatchFormat::ParquetKvtd => decode_parquet_file_kvtd(r)?,
    };

    let ret = BlobTraceBatch {
        desc: meta.desc.map_or_else(
            || {
                Description::new(
                    Antichain::from_elem(u64::minimum()),
                    Antichain::from_elem(u64::minimum()),
                    Antichain::from_elem(u64::minimum()),
                )
            },
            |x| x.into(),
        ),
        updates,
    };
    ret.validate()?;
    Ok(ret)
}

fn encode_parquet_kvtd<W: Write>(
    w: &mut W,
    inline_base64: String,
    iter: &[ColumnarRecords],
) -> Result<(), Error> {
    let iter = iter.into_iter().map(|x| Ok(encode_arrow_batch_kvtd(x)));

    let schema = SCHEMA_ARROW_KVTD.clone();
    let options = WriteOptions {
        write_statistics: false,
        compression: Compression::Uncompressed,
        version: Version::V2,
    };
    let row_groups = RowGroupIterator::try_new(
        iter,
        &schema,
        options,
        vec![
            Encoding::Plain,
            Encoding::Plain,
            Encoding::Plain,
            Encoding::Plain,
        ],
    )?;

    let parquet_schema = row_groups.parquet_schema().clone();
    let metadata = vec![KeyValue {
        key: INLINE_METADATA_KEY.into(),
        value: Some(inline_base64),
    }];
    write_file(w, row_groups, parquet_schema, options, None, Some(metadata))
        .map_err(|err| err.to_string())?;

    Ok(())
}

fn decode_parquet_file_kvtd<R: Read + Seek>(r: &mut R) -> Result<Vec<ColumnarRecords>, Error> {
    let reader = RecordReader::try_new(r, None, None, None, None)?;

    let file_schema = reader.schema().fields().as_slice();
    // We're not trying to accept any sort of user created data, so be strict.
    if file_schema != SCHEMA_ARROW_KVTD.fields() {
        return Err(format!(
            "expected arrow schema {:?} got: {:?}",
            SCHEMA_ARROW_KVTD.fields(),
            file_schema
        )
        .into());
    }

    let mut ret = Vec::new();
    for batch in reader {
        ret.push(decode_arrow_batch_kvtd(&batch?)?);
    }
    Ok(ret)
}