Repository navigation
Expand file tree
/
Copy pathhost.rs
More file actions
318 lines (300 loc) · 11.2 KB
/
Copy pathhost.rs
File metadata and controls
318 lines (300 loc) · 11.2 KB
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
//! Statically registered, typed host operations and explicit local `PostgreSQL` grants.
use crate::error::{Error, Result};
use crate::value::{Type, Value, ValueKind};
use serde::Serialize;
use std::fmt;
use std::time::{Duration, Instant};
use tokio::runtime::Runtime;
use tokio::task::JoinHandle;
use tokio_postgres::{Client, Config, NoTls, config::Host};
#[derive(Debug)]
pub(crate) struct Operation {
pub arguments: Vec<Type>,
pub result: Type,
pub capability: &'static str,
}
pub(crate) fn operation(name: &str) -> Option<Operation> {
let arguments = match name {
"postgres_version" => vec![],
"postgres_echo" => vec![Type::Text],
_ => return None,
};
Some(Operation {
arguments,
result: Type::Text,
capability: "PostgresRead",
})
}
#[derive(Debug, Serialize)]
pub(crate) struct OperationContract {
name: &'static str,
arguments: Vec<String>,
result: String,
capability: &'static str,
maximum_output_bytes: usize,
deadline_milliseconds: u64,
transaction: &'static str,
replay: &'static str,
cancellation: &'static str,
failure: &'static str,
}
pub(crate) fn contracts() -> Vec<OperationContract> {
["postgres_version", "postgres_echo"].into_iter().filter_map(|name| {
operation(name).map(|operation| OperationContract {
name,
arguments: operation.arguments.iter().map(ToString::to_string).collect(),
result: operation.result.to_string(),
capability: operation.capability,
maximum_output_bytes: crate::MAX_SOURCE_BYTES,
deadline_milliseconds: 5000,
transaction: "outside application transactions; read-only statement",
replay: "no automatic replay",
cancellation: "timeout drops the read future, aborts and joins its connection driver; no rollback claim",
failure: "denied grant, invalid shape, budget failure, or redacted PostgreSQL failure",
})
}).collect()
}
pub(crate) struct HostRuntime {
postgres: Client,
driver: JoinHandle<std::result::Result<(), tokio_postgres::Error>>,
runtime: Runtime,
closed: bool,
relational: bool,
deadline: Instant,
}
impl fmt::Debug for HostRuntime {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("HostRuntime")
.field("closed", &self.closed)
.finish_non_exhaustive()
}
}
impl HostRuntime {
pub fn connect(configuration: &str) -> Result<Self> {
if tokio::runtime::Handle::try_current().is_ok() {
return Err(Error::Input(
"call synchronous project evaluation outside an async runtime".into(),
));
}
Self::connect_inner(configuration, true)
}
// Called only from owned synchronous work, including a bounded spawn_blocking
// task. That context may have a Tokio Handle but is not a runtime worker.
pub(crate) fn connect_worker(configuration: &str) -> Result<Self> {
Self::connect_inner(configuration, false)
}
fn connect_inner(configuration: &str, read_only: bool) -> Result<Self> {
crate::budget::check()?;
if configuration.len() > 16_384 {
return Err(Error::Limit("PostgreSQL configuration"));
}
let mut config: Config = configuration
.parse()
.map_err(|_| Error::Input("invalid PostgreSQL configuration".into()))?;
if config.get_hosts().len() != 1
|| config
.get_hosts()
.iter()
.any(|host| !matches!(host, Host::Unix(_)))
|| !config.get_hostaddrs().is_empty()
{
return Err(Error::Input("W1 PostgreSQL grants require one explicit local Unix socket; remote/TLS connections are not implemented".into()));
}
let connection_timeout = crate::budget::remaining(Duration::from_secs(5))?;
config.connect_timeout(connection_timeout);
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
let (postgres,driver)=runtime.block_on(async {
let (postgres,connection)=tokio::time::timeout(connection_timeout,config.connect(NoTls)).await
.map_err(|_|Error::Limit("PostgreSQL connection deadline"))?.map_err(|_|failure())?;
let driver=tokio::spawn(connection);
let settings=if read_only { "SET statement_timeout = '5s'; SET lock_timeout = '2s'; SET default_transaction_read_only = on;" }
else { "SET statement_timeout = '5s'; SET lock_timeout = '2s'; SET idle_in_transaction_session_timeout = '10s'; SET search_path = pg_catalog;" };
let setup=tokio::time::timeout(crate::budget::remaining(Duration::from_secs(5))?,postgres.batch_execute(settings)).await;
if !matches!(setup,Ok(Ok(()))) {
driver.abort();
let _driver_result=driver.await;
return Err(failure());
}
Ok((postgres,driver))
})?;
Ok(Self {
postgres,
driver,
runtime,
closed: false,
relational: false,
deadline: crate::budget::clamp(Instant::now() + Duration::from_secs(10)),
})
}
pub(crate) fn check_deadline(&self) -> Result<()> {
crate::budget::check()?;
if self.closed || Instant::now() >= self.deadline {
return Err(Error::Limit("PostgreSQL request deadline"));
}
Ok(())
}
pub(crate) fn query(
&mut self,
sql: &str,
parameters: &[&(dyn tokio_postgres::types::ToSql + Sync)],
) -> Result<Vec<tokio_postgres::Row>> {
self.query_inner(sql, parameters, self.relational)
}
pub(crate) fn relational_query(
&mut self,
sql: &str,
parameters: &[&(dyn tokio_postgres::types::ToSql + Sync)],
) -> Result<Vec<tokio_postgres::Row>> {
self.query_inner(sql, parameters, true)
}
fn query_inner(
&mut self,
sql: &str,
parameters: &[&(dyn tokio_postgres::types::ToSql + Sync)],
classified: bool,
) -> Result<Vec<tokio_postgres::Row>> {
self.check_deadline()?;
let duration = self
.deadline
.saturating_duration_since(Instant::now())
.min(Duration::from_secs(5));
if let Ok(value) = self.runtime.block_on(async {
tokio::time::timeout(duration, self.postgres.query(sql, parameters)).await
}) {
value.map_err(|e| {
if classified {
relational_error(&e)
} else {
failure()
}
})
} else {
self.cancel();
Err(Error::Limit("PostgreSQL operation deadline"))
}
}
pub(crate) fn batch(&mut self, sql: &str) -> Result<()> {
self.batch_inner(sql, self.relational)
}
pub(crate) fn relational_batch(&mut self, sql: &str) -> Result<()> {
self.batch_inner(sql, true)
}
fn batch_inner(&mut self, sql: &str, classified: bool) -> Result<()> {
self.check_deadline()?;
let duration = self
.deadline
.saturating_duration_since(Instant::now())
.min(Duration::from_secs(5));
if let Ok(value) = self.runtime.block_on(async {
tokio::time::timeout(duration, self.postgres.batch_execute(sql)).await
}) {
value.map_err(|e| {
if classified {
relational_error(&e)
} else {
failure()
}
})
} else {
self.cancel();
Err(Error::Limit("PostgreSQL operation deadline"))
}
}
pub fn call(&mut self, name: &str, arguments: &[Value]) -> Result<Value> {
let operation = operation(name).ok_or(Error::Denied)?;
if self.closed {
return Err(failure());
}
if operation.arguments.len() != arguments.len()
|| !arguments
.iter()
.zip(&operation.arguments)
.all(|(value, ty)| value.fits(ty))
{
return Err(Error::Input(
"host operation argument shape does not match its checked signature".into(),
));
}
if arguments.iter().any(
|value| matches!(&value.0,ValueKind::Text(text) if text.len()>crate::MAX_SOURCE_BYTES),
) {
return Err(Error::Limit("host operation input"));
}
let timeout = crate::budget::remaining(Duration::from_secs(5))?;
let result = self.runtime.block_on(async {
tokio::time::timeout(timeout, async {
match (name, arguments) {
("postgres_version", []) => self
.postgres
.query_one("SELECT pg_catalog.current_setting('server_version')", &[])
.await
.map_err(|_| failure()),
("postgres_echo", [Value(ValueKind::Text(text))]) => self
.postgres
.query_one("SELECT $1::text", &[text])
.await
.map_err(|_| failure()),
_ => Err(Error::Denied),
}
})
.await
});
let row = if let Ok(result) = result {
result?
} else {
self.cancel();
return Err(Error::Limit("host operation deadline"));
};
let text: String = row.try_get(0).map_err(|_| failure())?;
if text.len() > crate::MAX_SOURCE_BYTES {
return Err(Error::Limit("host operation output"));
}
Ok(Value(ValueKind::Text(text)))
}
pub(crate) fn enable_relational(&mut self) {
self.relational = true;
}
pub(crate) fn reset_deadline(&mut self) {
self.deadline = crate::budget::clamp(Instant::now() + Duration::from_secs(10));
}
pub(crate) fn healthy(&self) -> bool {
!self.closed && !self.postgres.is_closed()
}
fn cancel(&mut self) {
// Cancellation is cleanup, not a new request attempt. Keep the lease
// owned until cancellation has been attempted and its driver is joined.
let token = self.postgres.cancel_token();
let _canceled = self.runtime.block_on(async {
tokio::time::timeout(crate::budget::cleanup_timeout(), token.cancel_query(NoTls)).await
});
self.close();
}
pub(crate) fn close(&mut self) {
if !self.closed {
self.closed = true;
self.driver.abort();
let driver = &mut self.driver;
self.runtime.block_on(async {
let _driver_result = driver.await;
});
}
}
}
impl Drop for HostRuntime {
fn drop(&mut self) {
self.close();
}
}
fn failure() -> Error {
Error::Postgres
}
fn relational_error(e: &tokio_postgres::Error) -> Error {
match e.code().map(tokio_postgres::error::SqlState::code) {
Some("40001" | "40P01") => Error::Conflict,
Some("23502" | "23503" | "23505" | "23514") => Error::Denied,
_ => Error::Postgres,
}
}