forked from Cohedrin/rust-postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopy_in.rs
228 lines (209 loc) · 7 KB
/
copy_in.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
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
use futures::sink;
use futures::sync::mpsc;
use futures::{Async, AsyncSink, Future, Poll, Sink, Stream};
use postgres_protocol::message::backend::Message;
use postgres_protocol::message::frontend;
use state_machine_future::RentToOwn;
use std::error::Error as StdError;
use proto::client::{Client, PendingRequest};
use proto::statement::Statement;
use Error;
pub enum CopyMessage {
Data(Vec<u8>),
Done,
}
pub struct CopyInReceiver {
receiver: mpsc::Receiver<CopyMessage>,
done: bool,
}
impl CopyInReceiver {
pub fn new(receiver: mpsc::Receiver<CopyMessage>) -> CopyInReceiver {
CopyInReceiver {
receiver,
done: false,
}
}
}
impl Stream for CopyInReceiver {
type Item = Vec<u8>;
type Error = ();
fn poll(&mut self) -> Poll<Option<Vec<u8>>, ()> {
if self.done {
return Ok(Async::Ready(None));
}
match self.receiver.poll()? {
Async::Ready(Some(CopyMessage::Data(buf))) => Ok(Async::Ready(Some(buf))),
Async::Ready(Some(CopyMessage::Done)) => {
self.done = true;
let mut buf = vec![];
frontend::copy_done(&mut buf);
frontend::sync(&mut buf);
Ok(Async::Ready(Some(buf)))
}
Async::Ready(None) => {
self.done = true;
let mut buf = vec![];
frontend::copy_fail("", &mut buf).unwrap();
frontend::sync(&mut buf);
Ok(Async::Ready(Some(buf)))
}
Async::NotReady => Ok(Async::NotReady),
}
}
}
#[derive(StateMachineFuture)]
pub enum CopyIn<S>
where
S: Stream,
S::Item: AsRef<[u8]>,
S::Error: Into<Box<StdError + Sync + Send>>,
{
#[state_machine_future(start, transitions(ReadCopyInResponse))]
Start {
client: Client,
request: PendingRequest,
statement: Statement,
stream: S,
sender: mpsc::Sender<CopyMessage>,
},
#[state_machine_future(transitions(WriteCopyData))]
ReadCopyInResponse {
stream: S,
sender: mpsc::Sender<CopyMessage>,
receiver: mpsc::Receiver<Message>,
},
#[state_machine_future(transitions(WriteCopyDone))]
WriteCopyData {
stream: S,
pending_message: Option<CopyMessage>,
sender: mpsc::Sender<CopyMessage>,
receiver: mpsc::Receiver<Message>,
},
#[state_machine_future(transitions(ReadCommandComplete))]
WriteCopyDone {
future: sink::Send<mpsc::Sender<CopyMessage>>,
receiver: mpsc::Receiver<Message>,
},
#[state_machine_future(transitions(Finished))]
ReadCommandComplete { receiver: mpsc::Receiver<Message> },
#[state_machine_future(ready)]
Finished(u64),
#[state_machine_future(error)]
Failed(Error),
}
impl<S> PollCopyIn<S> for CopyIn<S>
where
S: Stream,
S::Item: AsRef<[u8]>,
S::Error: Into<Box<StdError + Sync + Send>>,
{
fn poll_start<'a>(state: &'a mut RentToOwn<'a, Start<S>>) -> Poll<AfterStart<S>, Error> {
let state = state.take();
let receiver = state.client.send(state.request)?;
// the statement can drop after this point, since its close will queue up after the copy
transition!(ReadCopyInResponse {
stream: state.stream,
sender: state.sender,
receiver
})
}
fn poll_read_copy_in_response<'a>(
state: &'a mut RentToOwn<'a, ReadCopyInResponse<S>>,
) -> Poll<AfterReadCopyInResponse<S>, Error> {
loop {
let message = try_ready_receive!(state.receiver.poll());
match message {
Some(Message::BindComplete) => {}
Some(Message::CopyInResponse(_)) => {
let state = state.take();
transition!(WriteCopyData {
stream: state.stream,
pending_message: None,
sender: state.sender,
receiver: state.receiver
})
}
Some(Message::ErrorResponse(body)) => return Err(Error::db(body)),
Some(_) => return Err(Error::unexpected_message()),
None => return Err(Error::closed()),
}
}
}
fn poll_write_copy_data<'a>(
state: &'a mut RentToOwn<'a, WriteCopyData<S>>,
) -> Poll<AfterWriteCopyData, Error> {
loop {
let message = match state.pending_message.take() {
Some(message) => message,
None => match try_ready!(state.stream.poll().map_err(Error::copy_in_stream)) {
Some(data) => {
let mut buf = vec![];
frontend::copy_data(data.as_ref(), &mut buf).map_err(Error::encode)?;
CopyMessage::Data(buf)
}
None => {
let state = state.take();
transition!(WriteCopyDone {
future: state.sender.send(CopyMessage::Done),
receiver: state.receiver
})
}
},
};
match state.sender.start_send(message) {
Ok(AsyncSink::Ready) => {}
Ok(AsyncSink::NotReady(message)) => {
state.pending_message = Some(message);
return Ok(Async::NotReady);
}
Err(_) => return Err(Error::closed()),
}
}
}
fn poll_write_copy_done<'a>(
state: &'a mut RentToOwn<'a, WriteCopyDone>,
) -> Poll<AfterWriteCopyDone, Error> {
try_ready!(state.future.poll().map_err(|_| Error::closed()));
let state = state.take();
transition!(ReadCommandComplete {
receiver: state.receiver
})
}
fn poll_read_command_complete<'a>(
state: &'a mut RentToOwn<'a, ReadCommandComplete>,
) -> Poll<AfterReadCommandComplete, Error> {
let message = try_ready_receive!(state.receiver.poll());
match message {
Some(Message::CommandComplete(body)) => {
let rows = body
.tag()
.map_err(Error::parse)?
.rsplit(' ')
.next()
.unwrap()
.parse()
.unwrap_or(0);
transition!(Finished(rows))
}
Some(Message::ErrorResponse(body)) => Err(Error::db(body)),
Some(_) => Err(Error::unexpected_message()),
None => Err(Error::closed()),
}
}
}
impl<S> CopyInFuture<S>
where
S: Stream,
S::Item: AsRef<[u8]>,
S::Error: Into<Box<StdError + Sync + Send>>,
{
pub fn new(
client: Client,
request: PendingRequest,
statement: Statement,
stream: S,
sender: mpsc::Sender<CopyMessage>,
) -> CopyInFuture<S> {
CopyIn::start(client, request, statement, stream, sender)
}
}