encore-dev 2.0.0-beta.21

Rust SDK for Encore applications
Documentation
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! ClickHouse databases through a real runtime and server: declaring,
//! querying, inserting, parameters, access levels and errors.
//!
//! Skipped unless `ENCORE_CLICKHOUSE_TEST_URL` names a server user that may
//! create databases, users and roles:
//!
//! ```sh
//! ENCORE_CLICKHOUSE_TEST_URL=http://default:pw@127.0.0.1:18123 \
//!     cargo test -p encore-dev --test clickhouse
//! ```
//!
//! What it creates on the server is prefixed `ch_rs_`, and dropped at the end.

use std::collections::BTreeMap;
use std::future::{Future, IntoFuture};

use chrono::{DateTime, NaiveDate, Utc};
use encore::storage::clickhouse::{Database, DatabaseRef, Error, Row, RowStream, Value};
use encore_runtimecfg::pb;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

const DB: &str = "ch_rs_db";

static EVENTS: Database = Database::new("events").migrations("./migrations");
static NAMED: Database = Database::named("events");
static READER: DatabaseRef = EVENTS.read();

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Kind {
    Click,
    View,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Event {
    id: u64,
    kind: Kind,
    at: DateTime<Utc>,
    day: NaiveDate,
    user: Uuid,
    tags: Vec<String>,
    score: Option<f64>,
    price: String,
    attrs: BTreeMap<String, u32>,
}

fn event(id: u64, kind: Kind) -> Event {
    Event {
        id,
        kind,
        at: DateTime::from_timestamp(1_700_000_000 + id as i64, 123_456_000).unwrap(),
        day: NaiveDate::from_ymd_opt(2024, 2, 29).unwrap(),
        user: Uuid::from_u128(u128::from(id)),
        tags: vec![format!("t{id}")],
        score: id.is_multiple_of(2).then_some(id as f64 / 2.0),
        price: format!("{id}.50"),
        attrs: BTreeMap::from([("n".to_string(), id as u32)]),
    }
}

/// The server, and its superuser's credentials: from
/// `ENCORE_CLICKHOUSE_TEST_URL`.
struct Server {
    base: reqwest::Url,
    user: String,
    password: String,
}

fn server() -> Option<Server> {
    let raw = std::env::var("ENCORE_CLICKHOUSE_TEST_URL").ok()?;
    let mut base = reqwest::Url::parse(&raw).expect("ENCORE_CLICKHOUSE_TEST_URL is not a URL");
    let user = base.username().to_string();
    let password = base.password().unwrap_or_default().to_string();
    base.set_username("").unwrap();
    base.set_password(None).unwrap();
    Some(Server {
        base,
        user,
        password,
    })
}

/// Runs `sql` on the server as `user`, in `database` if given, and returns
/// the response's body.
async fn run_as(
    s: &Server,
    user: &str,
    password: &str,
    database: Option<&str>,
    sql: &str,
) -> Result<String, String> {
    let mut url = s.base.clone();
    if let Some(db) = database {
        url.query_pairs_mut().append_pair("database", db);
    }
    let resp = reqwest::Client::new()
        .post(url)
        .header("X-ClickHouse-User", user)
        .header("X-ClickHouse-Key", password)
        .body(sql.to_string())
        .send()
        .await
        .map_err(|e| e.to_string())?;
    let ok = resp.status().is_success();
    let body = resp.text().await.map_err(|e| e.to_string())?;
    if ok {
        Ok(body)
    } else {
        Err(body)
    }
}

async fn admin(s: &Server, sql: &str) {
    run_as(s, &s.user, &s.password, None, sql)
        .await
        .unwrap_or_else(|e| panic!("{sql}: {e}"));
}

/// The database and a user per access level, each holding a role with the
/// level's grants, as Encore's hierarchy has it.
async fn setup(s: &Server) {
    teardown(s).await;
    for sql in [
        format!("CREATE DATABASE {DB}"),
        "CREATE ROLE ch_rs_r, ch_rs_w, ch_rs_a".to_string(),
        format!("GRANT SELECT, SHOW ON {DB}.* TO ch_rs_r"),
        format!("GRANT INSERT, ALTER UPDATE, ALTER DELETE ON {DB}.* TO ch_rs_w"),
        "GRANT ch_rs_r TO ch_rs_w".to_string(),
        format!("GRANT ALL ON {DB}.* TO ch_rs_a"),
        "CREATE USER ch_rs_reader IDENTIFIED BY 'r'".to_string(),
        "CREATE USER ch_rs_writer IDENTIFIED BY 'w'".to_string(),
        "CREATE USER ch_rs_admin IDENTIFIED BY 'a'".to_string(),
        "GRANT ch_rs_r TO ch_rs_reader".to_string(),
        "GRANT ch_rs_w TO ch_rs_writer".to_string(),
        "GRANT ch_rs_a TO ch_rs_admin".to_string(),
    ] {
        admin(s, &sql).await;
    }
}

async fn teardown(s: &Server) {
    for sql in [
        format!("DROP DATABASE IF EXISTS {DB} SYNC"),
        "DROP USER IF EXISTS ch_rs_reader, ch_rs_writer, ch_rs_admin".to_string(),
        "DROP ROLE IF EXISTS ch_rs_r, ch_rs_w, ch_rs_a".to_string(),
    ] {
        admin(s, &sql).await;
    }
}

/// Points the runtime at the server before anything starts it: the database
/// `events` is `ch_rs_db`, with a user per level.
fn runtime_config(s: &Server) {
    let user = |rid: &str, name: &str, pw: &str| pb::ClickHouseUser {
        rid: rid.into(),
        username: name.into(),
        password: Some(pb::SecretData {
            source: Some(pb::secret_data::Source::Embedded(pw.as_bytes().to_vec())),
            ..Default::default()
        }),
        client_cert_rid: None,
    };
    let cfg = pb::RuntimeConfig {
        environment: Some(pb::Environment {
            app_id: "app".into(),
            env_name: "local".into(),
            ..Default::default()
        }),
        deployment: Some(pb::Deployment {
            hosted_services: vec![pb::HostedService {
                name: "svc".into(),
                ..Default::default()
            }],
            ..Default::default()
        }),
        infra: Some(pb::Infrastructure {
            resources: Some(pb::infrastructure::Resources {
                clickhouse_clusters: vec![pb::ClickHouseCluster {
                    rid: "cluster".into(),
                    servers: vec![pb::ClickHouseServer {
                        rid: "server".into(),
                        url: s.base.to_string(),
                        kind: pb::ServerKind::Primary as i32,
                        tls_config: None,
                    }],
                    databases: vec![pb::ClickHouseDatabase {
                        rid: "db".into(),
                        encore_name: "events".into(),
                        cloud_name: DB.into(),
                        read_user_rid: "u:read".into(),
                        write_user_rid: "u:write".into(),
                        admin_user_rid: "u:admin".into(),
                        max_connections: 0,
                        service_roles: Default::default(),
                    }],
                }],
                ..Default::default()
            }),
            credentials: Some(pb::infrastructure::Credentials {
                clickhouse_users: vec![
                    user("u:read", "ch_rs_reader", "r"),
                    user("u:write", "ch_rs_writer", "w"),
                    user("u:admin", "ch_rs_admin", "a"),
                ],
                ..Default::default()
            }),
        }),
        ..Default::default()
    };
    // Before the runtime reads the environment: this binary's only test.
    std::env::set_var(
        "ENCORE_RUNTIME_CONFIG",
        encore_runtimecfg::encoding::encode_env_value(&cfg),
    );
}

fn assert_send<F: Future + Send>(_: F) {}

/// The calls' futures are `Send`, so a multi-threaded server can hold them.
#[test]
fn calls_are_send() {
    // Never polled: only the types are checked, and no runtime starts.
    let rows = [event(1, Kind::Click)];
    assert_send(EVENTS.query("SELECT 1").fetch_all::<u8>());
    assert_send(READER.query("SELECT 1").fetch::<Row>());
    assert_send(EVENTS.exec("SELECT 1").param("x", 1).into_future());
    assert_send(EVENTS.insert("events", &rows).into_future());
    fn stream_is_send<T: Send>() {}
    stream_is_send::<RowStream<Event>>();
}

#[tokio::test(flavor = "multi_thread")]
async fn queries_inserts_and_access_levels() {
    let Some(s) = server() else {
        eprintln!("ENCORE_CLICKHOUSE_TEST_URL is unset: skipped");
        return;
    };
    setup(&s).await;
    runtime_config(&s);

    // The schema is the admin's.
    let create = "CREATE TABLE events (
        id UInt64, kind Enum8('click' = 1, 'view' = 2), at DateTime64(6, 'UTC'), day Date,
        user UUID, tags Array(String), score Nullable(Float64), price Decimal(10, 2),
        attrs Map(String, UInt32), note String DEFAULT 'none'
    ) ENGINE = MergeTree ORDER BY id";
    let err = EVENTS.write().exec(create).await.unwrap_err();
    assert!(
        matches!(&err, Error::Server { name, .. } if name == "ACCESS_DENIED"),
        "{err:?}"
    );
    EVENTS.admin().exec(create).await.expect("create the table");

    // Inserts.
    let events: Vec<Event> = (1..=4)
        .map(|id| {
            event(
                id,
                if id.is_multiple_of(2) {
                    Kind::View
                } else {
                    Kind::Click
                },
            )
        })
        .collect();
    let result = EVENTS.insert("events", &events).await.expect("insert");
    assert_eq!(result.rows_written, 4);
    assert!(!result.query_id.is_empty());
    let empty: [Event; 0] = [];
    assert_eq!(
        EVENTS.insert("events", &empty).await.unwrap().rows_written,
        0
    );

    // Rows read back by column name.
    let all: Vec<Event> = READER
        .query("SELECT * EXCEPT (note) FROM events ORDER BY id")
        .fetch_all()
        .await
        .expect("read the events");
    assert_eq!(all, events);
    let clicks: Vec<(u64, String)> = NAMED
        .read()
        .query("SELECT id, note FROM events WHERE kind = {kind:String} ORDER BY id")
        .param("kind", "click")
        .fetch_all()
        .await
        .unwrap();
    // A column the rows don't have gets its default.
    assert_eq!(clicks, [(1, "none".into()), (3, "none".into())]);

    // One row, or none.
    let count: u64 = READER
        .query("SELECT count() FROM events")
        .setting("max_execution_time", "30")
        .fetch_one()
        .await
        .unwrap();
    assert_eq!(count, 4);
    let none: Option<Event> = READER
        .query("SELECT * EXCEPT (note) FROM events WHERE id = {id:UInt64}")
        .param("id", 99u64)
        .fetch_optional()
        .await
        .unwrap();
    assert_eq!(none, None);
    let err = READER
        .query("SELECT id FROM events WHERE id = 99")
        .fetch_one::<u64>()
        .await
        .unwrap_err();
    assert_eq!(err, Error::NoRows);
    let err = READER
        .query("SELECT id FROM events")
        .fetch_optional::<u64>()
        .await
        .unwrap_err();
    assert_eq!(err, Error::TooManyRows);

    // Streaming, as `Row`s, with a query id of our own.
    let mut rows = READER
        .query("SELECT id, kind FROM events ORDER BY id")
        .query_id("ch_rs_stream")
        .fetch::<Row>()
        .await
        .unwrap();
    assert_eq!(rows.query_id(), "ch_rs_stream");
    let names: Vec<_> = rows.columns().iter().map(|c| c.name.as_str()).collect();
    assert_eq!(names, ["id", "kind"]);
    let first = rows.next().await.unwrap().unwrap();
    assert_eq!(first.get::<u64>("id"), 1);
    assert_eq!(first.get::<Kind>("kind"), Kind::Click);
    assert_eq!(first.values()[1], Value::Enum("click".into()));
    // Dropped before the last row: the query stops.
    drop(rows);

    // Parameters of each kind, read back as the server parsed them.
    let at = DateTime::from_timestamp(1_700_000_000, 654_321_000).unwrap();
    let user = Uuid::from_u128(42);
    #[derive(Debug, Deserialize, PartialEq)]
    struct Echo {
        a: Vec<u16>,
        s: String,
        b: Vec<u8>,
        at: DateTime<Utc>,
        day: NaiveDate,
        user: Uuid,
        m: BTreeMap<String, i64>,
        n: Option<i32>,
        d: f64,
        f: f64,
        ok: bool,
        tab: String,
    }
    let echo: Echo = READER
        .query(
            "SELECT {a:Array(UInt16)} AS a, {s:String} AS s, {b:String} AS b, \
             {at:DateTime64(6, 'UTC')} AS at, {day:Date} AS day, {user:UUID} AS user, \
             {m:Map(String, Int64)} AS m, {n:Nullable(Int32)} AS n, \
             {d:Decimal(10, 3)} AS d, {f:Float64} AS f, {ok:Bool} AS ok, \
             {tab:String} AS tab",
        )
        .param("a", vec![1u16, 2])
        .param("s", "it's")
        .param("b", vec![0x61u8, 0x62])
        .param("at", at)
        .param("day", NaiveDate::from_ymd_opt(1999, 12, 31).unwrap())
        .param("user", user)
        .param("m", BTreeMap::from([("k", -1i64)]))
        .param("n", None::<i32>)
        .param("d", Value::Decimal("1.250".into()))
        .param("f", 0.5f64)
        .param("ok", true)
        .param("tab", "a\tb\nc\\")
        .fetch_one()
        .await
        .expect("echo the parameters");
    assert_eq!(
        echo,
        Echo {
            a: vec![1, 2],
            s: "it's".into(),
            b: b"ab".to_vec(),
            at,
            day: NaiveDate::from_ymd_opt(1999, 12, 31).unwrap(),
            user,
            m: BTreeMap::from([("k".to_string(), -1)]),
            n: None,
            d: 1.25,
            f: 0.5,
            ok: true,
            tab: "a\tb\nc\\".into(),
        }
    );

    // Statements.
    let result = EVENTS
        .exec("ALTER TABLE events DELETE WHERE id = {id:UInt64}")
        .param("id", 4u64)
        .setting("mutations_sync", "1")
        .await
        .expect("delete");
    assert!(!result.query_id.is_empty());
    let count: u64 = READER
        .query("SELECT count() FROM events")
        .fetch_one()
        .await
        .unwrap();
    assert_eq!(count, 3);

    // A read handle can't write, nor a write handle change the schema.
    let err = READER.insert("events", &events[..1]).await.unwrap_err();
    assert!(
        matches!(&err, Error::Server { name, .. } if name == "ACCESS_DENIED"),
        "{err:?}"
    );
    let err = READER
        .exec("ALTER TABLE events DELETE WHERE 1")
        .await
        .unwrap_err();
    assert!(matches!(&err, Error::Server { .. }), "{err:?}");
    let err = EVENTS
        .write()
        .exec("TRUNCATE TABLE events")
        .await
        .unwrap_err();
    assert!(matches!(&err, Error::Server { .. }), "{err:?}");

    // The server's errors, with their code and name.
    let err = READER
        .query("SELECT * FROM nope")
        .fetch_all::<Row>()
        .await
        .unwrap_err();
    assert_eq!(err.code(), Some(60), "{err:?}");
    assert!(matches!(&err, Error::Server { name, .. } if name == "UNKNOWN_TABLE"));
    let err = READER
        .query("SELECT 1")
        .setting("no_such_setting", "1")
        .fetch_all::<Row>()
        .await
        .unwrap_err();
    assert!(matches!(&err, Error::Server { .. }), "{err:?}");
    // A row that doesn't fit the type asked for.
    let err = READER
        .query("SELECT 300 AS n")
        .fetch_one::<u8>()
        .await
        .unwrap_err();
    assert!(
        matches!(&err, Error::Decode(m) if m.contains("\"n\"")),
        "{err:?}"
    );
    // A row to insert that isn't a struct or map.
    let err = EVENTS.insert("events", &[1, 2]).await.unwrap_err();
    assert!(matches!(&err, Error::InvalidArgument(_)), "{err:?}");

    // Connection strings, each with its level's user.
    for (conn, user) in [
        (EVENTS.connection_string(), "ch_rs_writer"),
        (READER.connection_string(), "ch_rs_reader"),
        (EVENTS.admin().connection_string(), "ch_rs_admin"),
    ] {
        let conn = reqwest::Url::parse(&conn.unwrap()).unwrap();
        assert_eq!(conn.username(), user);
        assert_eq!(conn.path(), format!("/{DB}"));
        let me = run_as(
            &s,
            conn.username(),
            conn.password().unwrap(),
            Some(&conn.path()[1..]),
            "SELECT currentUser()",
        )
        .await
        .unwrap();
        assert_eq!(me.trim(), user);
    }

    teardown(&s).await;
}