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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use anyhow::{anyhow, ensure};
use csv::{ReaderBuilder, StringRecord, Writer};
use std::cmp;
use std::convert::TryFrom;
use teaclave_types::{FunctionArguments, FunctionRuntime};

// Input data should be sorted by the specified index column.
const IN_DATA1: &str = "input_data1";
const IN_DATA2: &str = "input_data2";
// fusion output data
const OUT_RESULT: &str = "output_result";

#[derive(Default)]
pub struct OrderedSetJoin;

#[derive(serde::Deserialize)]
pub struct OrderedSetJoinArguments {
    // Start from 0.
    left_column: usize,
    right_column: usize,
    ascending: bool,
    // If it is set to true, drop the selected column of all files from the results.
    // If it is set to false, only keep the selected column of the first file.
    drop: bool,
}

impl TryFrom<FunctionArguments> for OrderedSetJoinArguments {
    type Error = anyhow::Error;

    fn try_from(arguments: FunctionArguments) -> Result<Self, Self::Error> {
        use anyhow::Context;
        serde_json::from_str(&arguments.into_string()).context("Cannot deserialize arguments")
    }
}

impl OrderedSetJoin {
    pub const NAME: &'static str = "builtin-ordered-set-join";

    pub fn new() -> Self {
        Default::default()
    }

    pub fn run(
        &self,
        arguments: FunctionArguments,
        runtime: FunctionRuntime,
    ) -> anyhow::Result<String> {
        let args = OrderedSetJoinArguments::try_from(arguments)?;
        let mut rdr1 = ReaderBuilder::new()
            .has_headers(false)
            .from_reader(runtime.open_input(IN_DATA1)?);
        let mut rdr2 = ReaderBuilder::new()
            .has_headers(false)
            .from_reader(runtime.open_input(IN_DATA2)?);
        let mut wtr = Writer::from_writer(runtime.create_output(OUT_RESULT)?);

        let mut record1 = StringRecord::new();
        let mut record2 = StringRecord::new();
        let mut count = 0;
        ensure!(rdr1.read_record(&mut record1)?, "input1 is empty");
        ensure!(rdr2.read_record(&mut record2)?, "input2 is empty");

        loop {
            let fields1 = record1
                .get(args.left_column)
                .ok_or_else(|| anyhow!("invalid index"))?;
            let fields2 = record2
                .get(args.right_column)
                .ok_or_else(|| anyhow!("invalid index"))?;
            let order = &fields1.cmp(fields2);

            match order {
                cmp::Ordering::Equal => {
                    let new_record1 = if args.drop {
                        drop_column(&record1, args.left_column)
                    } else {
                        record1.clone()
                    };
                    let new_record2 = drop_column(&record2, args.right_column);
                    wtr.write_record(new_record1.iter().chain(&new_record2))?;
                    count += 1;
                    if !rdr1.read_record(&mut record1)? || !rdr2.read_record(&mut record2)? {
                        break;
                    }
                }
                cmp::Ordering::Less => {
                    if args.ascending {
                        if !rdr1.read_record(&mut record1)? {
                            break;
                        }
                    } else if !rdr2.read_record(&mut record2)? {
                        break;
                    }
                }
                cmp::Ordering::Greater => {
                    if args.ascending {
                        if !rdr2.read_record(&mut record2)? {
                            break;
                        }
                    } else if !rdr1.read_record(&mut record1)? {
                        break;
                    }
                }
            }
        }

        Ok(format!("{} records", count))
    }
}

pub fn drop_column(column: &StringRecord, index: usize) -> StringRecord {
    StringRecord::from(
        column
            .iter()
            .enumerate()
            .filter_map(|(i, e)| if i != index { Some(e) } else { None })
            .collect::<Vec<_>>(),
    )
}

#[cfg(feature = "enclave_unit_test")]
pub mod tests {
    use super::*;
    use serde_json::json;
    use std::path::Path;
    use std::untrusted::fs;
    use teaclave_crypto::*;
    use teaclave_runtime::*;
    use teaclave_test_utils::*;
    use teaclave_types::*;

    pub fn run_tests() -> bool {
        run_tests!(test_ordered_set_join)
    }

    fn test_ordered_set_join() {
        let arguments = FunctionArguments::from_json(json!({
            "left_column": 0,
            "right_column": 0,
            "ascending":true,
            "drop":true
        }))
        .unwrap();

        let base = Path::new("fixtures/functions/ordered_set_join");

        let user1_input = base.join("join0.csv");
        let output = base.join("output_join.csv");

        let user2_input = base.join("join1.csv");

        let input_files = StagedFiles::new(hashmap!(
            IN_DATA1 =>
            StagedFileInfo::new(&user1_input, TeaclaveFile128Key::random(), FileAuthTag::mock()),
            IN_DATA2 =>
            StagedFileInfo::new(&user2_input, TeaclaveFile128Key::random(), FileAuthTag::mock()),
        ));

        let output_files = StagedFiles::new(hashmap!(
            OUT_RESULT =>
            StagedFileInfo::new(&output, TeaclaveFile128Key::random(), FileAuthTag::mock()),
        ));

        let runtime = Box::new(RawIoRuntime::new(input_files, output_files));
        let summary = OrderedSetJoin::new().run(arguments, runtime).unwrap();
        assert_eq!("120 records".to_string(), summary);

        let expected_output = "fixtures/functions/gbdt_training/train.txt";
        let result = fs::read_to_string(&output).unwrap();
        let expected = fs::read_to_string(expected_output).unwrap();
        assert_eq!(result.trim(), expected.trim());
    }
}