-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathobject_writer.rs
180 lines (147 loc) · 5.64 KB
/
object_writer.rs
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
// 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 std::pin::Pin;
use std::task::{Context, Poll};
use arrow_array::Array;
use object_store::{path::Path, MultipartId};
use pin_project::pin_project;
use prost::Message;
use tokio::io::{AsyncWrite, AsyncWriteExt};
use crate::encodings::plain::PlainEncoder;
use crate::format::{ProtoStruct, MAGIC, MAJOR_VERSION, MINOR_VERSION};
use crate::io::ObjectStore;
use crate::Result;
/// AsyncWrite with the capability to tell the position the data is written.
///
#[pin_project]
pub struct ObjectWriter {
store: ObjectStore,
// TODO: wrap writer with a BufWriter.
#[pin]
writer: Box<dyn AsyncWrite + Unpin + Send>,
multipart_id: MultipartId,
cursor: usize,
}
impl ObjectWriter {
pub async fn new(object_store: &ObjectStore, path: &Path) -> Result<Self> {
let (multipart_id, writer) = object_store.inner.put_multipart(path).await?;
Ok(Self {
store: object_store.clone(),
writer,
multipart_id,
cursor: 0,
})
}
/// Tell the current position (file size).
pub fn tell(&self) -> usize {
self.cursor
}
/// Write a protobuf message to the object, and returns the file position of the protobuf.
pub async fn write_protobuf(&mut self, msg: &impl Message) -> Result<usize> {
let offset = self.tell();
let len = msg.encoded_len();
self.write_u32_le(len as u32).await?;
self.write_all(&msg.encode_to_vec()).await?;
Ok(offset)
}
pub async fn write_struct<'b, M: Message + From<&'b T>, T: ProtoStruct<Proto = M> + 'b>(
&mut self,
obj: &'b T,
) -> Result<usize> {
let msg: M = M::from(obj);
self.write_protobuf(&msg).await
}
/// Write an array using plain encoding.
///
/// Returns the file position if success.
pub async fn write_plain_encoded_array(&mut self, array: &dyn Array) -> Result<usize> {
let mut encoder = PlainEncoder::new(self, array.data_type());
encoder.encode(&[array]).await
}
/// Write magics to the tail of a file before closing the file.
pub async fn write_magics(&mut self, pos: usize) -> Result<()> {
self.write_i64_le(pos as i64).await?;
self.write_i16_le(MAJOR_VERSION).await?;
self.write_i16_le(MINOR_VERSION).await?;
self.write_all(MAGIC).await?;
Ok(())
}
pub async fn shutdown(&mut self) -> Result<()> {
Ok(self.writer.shutdown().await?)
}
}
impl AsyncWrite for ObjectWriter {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
let mut this = self.project();
this.writer.as_mut().poll_write(cx, buf).map_ok(|n| {
*this.cursor += n;
n
})
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
self.project().writer.as_mut().poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
self.project().writer.as_mut().poll_shutdown(cx)
}
}
#[cfg(test)]
mod tests {
use object_store::path::Path;
use tokio::io::AsyncWriteExt;
use crate::format::Metadata;
use crate::io::object_reader::{read_struct, CloudObjectReader};
use crate::io::ObjectStore;
use super::*;
#[tokio::test]
async fn test_write() {
let store = ObjectStore::new(":memory:").await.unwrap();
let mut object_writer = ObjectWriter::new(&store, &Path::from("/foo"))
.await
.unwrap();
assert_eq!(object_writer.tell(), 0);
let mut buf = Vec::<u8>::new();
buf.resize(256, 0);
assert_eq!(object_writer.write(buf.as_slice()).await.unwrap(), 256);
assert_eq!(object_writer.tell(), 256);
assert_eq!(object_writer.write(buf.as_slice()).await.unwrap(), 256);
assert_eq!(object_writer.tell(), 512);
assert_eq!(object_writer.write(buf.as_slice()).await.unwrap(), 256);
assert_eq!(object_writer.tell(), 256 * 3);
object_writer.shutdown().await.unwrap();
}
#[tokio::test]
async fn test_write_proto_structs() {
let store = ObjectStore::new(":memory:").await.unwrap();
let path = Path::from("/foo");
let mut object_writer = ObjectWriter::new(&store, &path).await.unwrap();
assert_eq!(object_writer.tell(), 0);
let mut metadata = Metadata::default();
metadata.manifest_position = Some(100);
metadata.batch_offsets.extend([1, 2, 3, 4]);
let pos = object_writer.write_struct(&metadata).await.unwrap();
assert_eq!(pos, 0);
object_writer.shutdown().await.unwrap();
let object_reader = CloudObjectReader::new(&store, path, 1024).unwrap();
let actual: Metadata = read_struct(&object_reader, pos).await.unwrap();
assert_eq!(metadata, actual);
}
}