Skip to main content

docs_encryption/
docs_encryption.rs

1//! Documentation examples for Encryption page.
2//!
3//! Run with: cargo run --example docs_encryption
4
5use s2_sdk::{
6    S2,
7    types::{
8        AppendInput, AppendRecord, AppendRecordBatch, BasinConfig, BasinName, BasinReconfiguration,
9        CreateBasinInput, CreateStreamInput, DeleteStreamInput, EncryptionAlgorithm, ReadFrom,
10        ReadInput, ReadLimits, ReadStart, ReadStop, ReconfigureBasinInput, S2Config, StreamName,
11    },
12};
13
14#[tokio::main]
15async fn main() -> Result<(), Box<dyn std::error::Error>> {
16    let access_token = std::env::var("S2_ACCESS_TOKEN")?;
17    let basin_name: BasinName = std::env::var("S2_BASIN")?.parse()?;
18    let stream_name: StreamName = format!(
19        "docs-encryption-{}",
20        std::time::SystemTime::now()
21            .duration_since(std::time::UNIX_EPOCH)?
22            .as_millis()
23    )
24    .parse()?;
25
26    let client = S2::new(S2Config::new(access_token))?;
27
28    // ANCHOR: basin-cipher
29    client
30        .create_basin(
31            CreateBasinInput::new(basin_name.clone())
32                .with_config(BasinConfig::new().with_stream_cipher(EncryptionAlgorithm::Aegis256)),
33        )
34        .await?;
35
36    client
37        .reconfigure_basin(ReconfigureBasinInput::new(
38            basin_name.clone(),
39            BasinReconfiguration::new().with_stream_cipher(EncryptionAlgorithm::Aes256Gcm),
40        ))
41        .await?;
42    // ANCHOR_END: basin-cipher
43
44    let basin = client.basin(basin_name.clone());
45    basin
46        .create_stream(CreateStreamInput::new(stream_name.clone()))
47        .await?;
48
49    // ANCHOR: append-read
50    let stream = basin
51        .stream(stream_name.clone())
52        .with_encryption_key(std::env::var("S2_ENCRYPTION_KEY")?.parse()?);
53
54    stream
55        .append(AppendInput::new(AppendRecordBatch::try_from_iter([
56            AppendRecord::new("top secret")?,
57        ])?))
58        .await?;
59
60    let batch = stream
61        .read(
62            ReadInput::new()
63                .with_start(ReadStart::new().with_from(ReadFrom::SeqNum(0)))
64                .with_stop(ReadStop::new().with_limits(ReadLimits::new().with_count(10))),
65        )
66        .await?;
67    // ANCHOR_END: append-read
68
69    println!("Read {} encrypted record(s)", batch.records.len());
70
71    basin
72        .delete_stream(DeleteStreamInput::new(stream_name))
73        .await?;
74
75    Ok(())
76}