aurabase 0.1.1

Official Rust SDK for Aurabase: high-performance open-source Backend-as-a-Service (BaaS)
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
use aurabase::{create_client, types::SignUpRequest};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;
use std::time::Duration;

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
struct Todo {
    #[serde(skip_serializing_if = "Option::is_none")]
    id: Option<uuid::Uuid>,
    title: String,
    completed: bool,
    owner_id: String,
}

#[derive(Deserialize)]
struct SmokeConfig {
    project_uuid: String,
    anon_key: String,
    service_key: String,
}

fn get_smoke_config() -> Option<SmokeConfig> {
    let path = Path::new("../.smoke/last-run.json");
    if path.exists() {
        let content = fs::read_to_string(path).ok()?;
        serde_json::from_str(&content).ok()
    } else {
        None
    }
}

/// URL DU PROJET (`https://<slug>.<apex>`) — le SDK ne porte plus d'identifiant de projet :
/// c'est l'hôte qui désigne le tenant, et la passerelle qui injecte le `project_id`
/// (`aura-gateway/src/middleware/project_subdomain.rs`). `http://localhost:8080` ne désigne
/// aucun projet : sans cette variable, il n'y a rien à tester. Même convention que le SDK JS
/// (`AURA_E2E_URL`, `aurabase-js/packages/aurabase/tests/readme-smoke-e2e.test.ts`).
fn e2e_url() -> Option<String> {
    std::env::var("AURA_E2E_URL").ok().filter(|u| !u.is_empty())
}

#[tokio::test]
async fn test_e2e_prod_flow() {
    let config = match get_smoke_config() {
        Some(c) => c,
        None => {
            println!("Skipping E2E test: .smoke/last-run.json not found");
            return;
        }
    };

    let base_url = match e2e_url() {
        Some(u) => u,
        None => {
            println!(
                "Skipping E2E test: AURA_E2E_URL absente — l'URL du projet \
                 (https://<slug>.<apex>) est désormais la seule désignation du tenant"
            );
            return;
        }
    };

    println!("Starting E2E test for project: {}", config.project_uuid);

    // ─── Instanciation du client ───
    let client = create_client(&base_url, &config.anon_key, None);

    // ─── Étape 1 : Auth (Sign Up & Sign In) ───
    let test_id = uuid::Uuid::new_v4().to_string()[..8].to_string();
    let email = format!("e2e-user-{}@aurabase.cloud", test_id);
    let password = "E2EUserPass123!".to_string();

    println!("Signing up user: {}", email);
    let signup_res = client
        .auth()
        .sign_up(SignUpRequest {
            email: email.clone(),
            password: password.clone(),
            captcha_token: None,
        })
        .await
        .expect("Signup failed");

    println!("Signup response: {:?}", signup_res);

    let user = match signup_res.data {
        Some(aurabase::types::LoginResponse::TokenPair(ref tp)) => tp.user.clone(),
        _ => panic!(
            "Expected TokenPair in signup response, got: {:?}",
            signup_res
        ),
    };

    let user_id = user.id.clone();
    println!("User signed up with ID: {}", user_id);

    // Connexion avec mot de passe
    println!("Signing in user: {}", email);
    let login_res = client
        .auth()
        .sign_in_with_password(aurabase::types::SignInRequest {
            email: email.clone(),
            password: password.clone(),
            captcha_token: None,
        })
        .await
        .expect("Login failed");

    println!("Login response: {:?}", login_res);
    assert!(login_res.data.is_some());
    println!("Login successful!");

    // ─── Étape 2 : Database & RLS ───
    // Insertion de données sous l'identité de l'utilisateur connecté
    let todo_item = Todo {
        id: None,
        title: "Test E2E SDK Rust".to_string(),
        completed: false,
        owner_id: user_id.clone(),
    };

    println!("Inserting todo item...");
    let insert_res = client
        .db()
        .from::<Todo>("todos")
        .insert(todo_item.clone())
        .execute()
        .await
        .expect("Insert failed");

    let inserted_todos = insert_res.data.expect("No data returned on insert");
    assert!(!inserted_todos.is_empty(), "Inserted todos array is empty");
    let inserted_todo = &inserted_todos[0];
    let inserted_id = inserted_todo.id.expect("No ID generated for todo");
    println!("Inserted todo with ID: {}", inserted_id);

    // Lecture sous l'identité de l'utilisateur connecté (doit voir son todo)
    println!("Reading todos (authenticated)...");
    let read_res = client
        .db()
        .from::<Todo>("todos")
        .select("*")
        .eq("owner_id", &user_id)
        .execute()
        .await
        .expect("Read failed");

    let todos = read_res.data.expect("No data returned on read");
    assert!(!todos.is_empty());
    assert_eq!(todos[0].title, "Test E2E SDK Rust");
    println!("Authenticated read verified!");

    // Lecture anonyme (doit être vide en raison de la RLS)
    let anon_client = create_client(&base_url, &config.anon_key, None);

    println!("Reading todos (anonymous)...");
    let anon_read_res = anon_client
        .db()
        .from::<Todo>("todos")
        .select("*")
        .execute()
        .await
        .expect("Anonymous read failed");

    let anon_todos = anon_read_res.data.expect("No data returned on anon read");
    assert!(
        anon_todos.is_empty(),
        "Anon should not be able to read private data"
    );
    println!("Anonymous RLS isolation verified!");

    // Mise à jour de la ligne
    println!("Updating todo item...");
    let mut updated_todo_info = inserted_todo.clone();
    updated_todo_info.completed = true;

    let update_res = client
        .db()
        .from::<Todo>("todos")
        .update(&inserted_id.to_string(), updated_todo_info)
        .execute()
        .await
        .expect("Update failed");

    let updated_todos = update_res.data.expect("No data returned on update");
    assert!(!updated_todos.is_empty());
    let updated_todo = &updated_todos[0];
    assert!(updated_todo.completed);
    println!("Todo updated successfully!");

    // Suppression
    println!("Deleting todo item...");
    let delete_res = client
        .db()
        .from::<serde_json::Value>("todos")
        .delete(&inserted_id.to_string())
        .execute()
        .await
        .expect("Delete failed");

    assert!(delete_res.error.is_none());
    println!("Todo deleted successfully!");

    // ─── Étape 3 : Storage ───
    let bucket_name = format!("e2e-bucket-{}", test_id);
    // Utilisons le service_key client pour la gestion de bucket
    let admin_client = create_client(&base_url, &config.service_key, None);

    println!("Creating storage bucket: {}", bucket_name);
    let create_bucket_res = admin_client
        .storage()
        .create_bucket(&bucket_name, Some(true), None, None)
        .await
        .expect("Create bucket failed");

    assert_eq!(
        create_bucket_res.data.expect("No bucket returned").name,
        bucket_name
    );
    println!("Storage bucket created!");

    // Upload de fichier
    let file_content = b"Contenu du fichier E2E Rust".to_vec();
    let file_path = "rust_test.txt";
    println!("Uploading file...");
    let upload_res = client
        .storage()
        .upload(&bucket_name, file_path, file_content.clone(), None)
        .await
        .expect("Upload failed");

    let upload_data = upload_res.data.expect("No data returned on upload");
    let uploaded_key = upload_data.key.clone();
    println!("File uploaded successfully with key: {}", uploaded_key);

    // Extraction de la clé relative (sans le nom du bucket en préfixe)
    let object_path = match uploaded_key.find('/') {
        Some(idx) => &uploaded_key[idx + 1..],
        None => &uploaded_key,
    };
    println!("File relative path: {}", object_path);

    // Download de fichier
    println!("Downloading file...");
    let download_res = client
        .storage()
        .download(&bucket_name, object_path)
        .await
        .expect("Download failed");

    if let Some(ref err) = download_res.error {
        panic!("Download returned error: {:?}", err);
    }
    let downloaded_content = download_res.data.expect("No data returned on download");
    assert_eq!(downloaded_content, file_content);
    println!("File download verified!");

    // Liste des fichiers
    println!("Listing files in bucket...");
    let list_res = client
        .storage()
        .list(&bucket_name, None, None, None)
        .await
        .expect("List files failed");

    let files = list_res.data.expect("No files returned");
    assert!(!files.is_empty());
    assert_eq!(files[0].name, uploaded_key);
    println!("File listing verified!");

    // Suppression de fichier
    println!("Removing file...");
    client
        .storage()
        .remove(&bucket_name, vec![object_path.to_string()])
        .await
        .expect("Remove file failed");
    println!("File removed!");

    // Suppression de bucket
    println!("Deleting bucket...");
    admin_client
        .storage()
        .delete_bucket(&bucket_name)
        .await
        .expect("Delete bucket failed");
    println!("Storage bucket deleted!");

    // ─── Étape 4 : Edge Functions (WASM) ───
    println!("Reading hash.wasm...");
    let wasm_path = Path::new("../scripts/functions/wasm/hash.wasm");
    let wasm_bytes = fs::read(wasm_path).expect("Failed to read hash.wasm");
    use base64::Engine;
    let wasm_b64 = base64::engine::general_purpose::STANDARD.encode(&wasm_bytes);

    println!("Creating Edge Function 'hash-fn'...");
    let build_fn_client = reqwest::Client::new();
    let create_fn_url = format!("http://localhost:8080/v1/functions/{}", config.project_uuid);
    let create_fn_payload = serde_json::json!({
        "name": "hash-fn",
        "runtime": "wasm",
        "code": wasm_b64,
        "env_vars": {}
    });

    let create_fn_res = build_fn_client
        .post(&create_fn_url)
        .header("apikey", &config.service_key)
        .json(&create_fn_payload)
        .send()
        .await
        .expect("Failed to send create function request");

    let create_status = create_fn_res.status();
    let create_res_text = create_fn_res.text().await.unwrap_or_default();
    assert!(
        create_status.is_success(),
        "Failed to create Edge Function: {} - {}",
        create_status,
        create_res_text
    );
    println!("Edge Function 'hash-fn' created successfully!");

    // Attendre la propagation ou l'initialisation
    tokio::time::sleep(Duration::from_secs(2)).await;

    println!("Invoking Edge Function 'hash-fn'...");
    let func_res = client
        .functions()
        .invoke::<serde_json::Value>(
            "hash-fn",
            Some(aurabase::services::functions::InvokeOptions {
                body: Some(serde_json::json!("hello world")),
                ..Default::default()
            }),
        )
        .await
        .expect("Function invocation failed");

    if let Some(ref err) = func_res.error {
        panic!("Edge Function invocation returned error: {:?}", err);
    }
    let data_val = func_res.data.expect("No data returned from function");
    let body_val = data_val
        .get("body")
        .expect("No body field in InvokeResponse");
    let hash_val = body_val.get("hash").and_then(|v| v.as_str()).unwrap_or("");
    println!("WASM Edge Function response hash: {}", hash_val);
    assert_eq!(hash_val, "0xfc16783b");

    // Suppression de la fonction
    println!("Deleting Edge Function 'hash-fn'...");
    let delete_fn_url = format!(
        "http://localhost:8080/v1/functions/{}/hash-fn",
        config.project_uuid
    );
    let delete_fn_res = build_fn_client
        .delete(&delete_fn_url)
        .header("apikey", &config.service_key)
        .send()
        .await
        .expect("Failed to send delete function request");
    assert!(
        delete_fn_res.status().is_success(),
        "Failed to delete Edge Function"
    );
    println!("Edge Function 'hash-fn' deleted successfully!");

    // ─── Étape 5 : Realtime (WebSocket) ───
    println!("Testing Realtime connection...");
    let realtime = client.realtime();

    let channel = realtime.channel("public:todos", None);

    // S'abonner
    println!("Subscribing to channel public:todos...");
    realtime
        .subscribe_channel(channel)
        .await
        .expect("Subscription failed");

    // Attendre la connexion
    let mut state_rx = realtime.on_state_change();
    let mut connected = false;
    for _ in 0..10 {
        if realtime.connection_state() == aurabase::ConnectionState::Connected {
            connected = true;
            break;
        }
        if let Ok(state) = tokio::time::timeout(Duration::from_millis(500), state_rx.recv()).await {
            if state.ok() == Some(aurabase::ConnectionState::Connected) {
                connected = true;
                break;
            }
        }
    }

    if connected {
        println!("Realtime connected successfully!");
    } else {
        println!("Warning: Realtime did not reach connected state in time.");
    }

    println!("=== E2E Test Completed Successfully! [OK] ===");
}