fauna-api 1.0.787

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
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
use std::ops::Deref;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::authentification::{CredentialsOrApiKey, Profile};
use crate::error::Result;
use crate::http::{client, encode, ok};
use crate::shared::server::{
    Authorization, Hooks as ServerHooks, Presence, Room, connect as connect_server,
};
use crate::tickets::{optional, parse_date};

/// What a member may do: `read` sees the state, `write` can also set it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    #[default]
    Read,
    Write,
}

/// Who is in a room: everyone in a group, directly or through a nested group, or
/// one person by email. A person's room takes groups its owner is in; a group's
/// room takes groups nested inside it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Member {
    Group { group: String, role: Role },
    Email { email: String, role: Role },
}

/// A live room a person or a group owns. Everyone in it sees `state` change live.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LiveRoom {
    pub id: String,
    pub name: String,

    /// The group that owns it; `None` when a person does.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,

    pub members: Vec<Member>,

    /// Any JSON, up to 256 KB, always set whole. Fauna never reads it.
    pub state: Value,
    /// Goes up by one with every state change.
    pub version: u64,

    pub created: DateTime<Utc>,
    pub updated: DateTime<Utc>,
}

impl LiveRoom {
    pub fn from_json(json: &Value) -> LiveRoom {
        LiveRoom {
            id: json["id"].as_str().unwrap_or_default().to_string(),
            name: json["name"].as_str().unwrap_or_default().to_string(),
            group: optional(&json["group"]),
            members: serde_json::from_value(json["members"].clone()).unwrap_or_default(),
            state: json["state"].clone(),
            version: json["version"].as_u64().unwrap_or_default(),
            created: parse_date(&json["created"]).unwrap_or_default(),
            updated: parse_date(&json["updated"]).unwrap_or_default(),
        }
    }
}

/// What `create` takes. Every field is optional.
#[derive(Debug, Clone, Default, Serialize)]
pub struct Draft {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// A group you are a direct admin of, to own the room. Without it, you own it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub members: Option<Vec<Member>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<Value>,
}

/// One of a room's groups someone is in: `through` is the group's own id when
/// they are directly in it, else the nested group they come in through.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PersonGroup {
    pub id: String,
    pub through: String,
}

impl PersonGroup {
    pub fn from_json(json: &Value) -> PersonGroup {
        PersonGroup {
            id: json["id"].as_str().unwrap_or_default().to_string(),
            through: json["through"].as_str().unwrap_or_default().to_string(),
        }
    }
}

/// Someone in a room: their profile, and each of the room's groups they're in.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Person {
    pub profile: Profile,
    pub groups: Vec<PersonGroup>,
}

impl Person {
    pub fn from_json(json: &Value) -> Person {
        Person {
            profile: Profile::from_json(&json["profile"]).unwrap_or_default(),
            groups: json["groups"]
                .as_array()
                .map(|groups| groups.iter().map(PersonGroup::from_json).collect())
                .unwrap_or_default(),
        }
    }
}

/// Room hooks, plus `on_state` whenever someone changes the state. Every method
/// defaults to a no-op.
pub trait Hooks: ServerHooks {
    fn on_state(&self, _room: &StateRoom, _state: &Value, _version: u64) {}
}

impl Hooks for () {}

/// Make a live room. You own it, also when you sign with an API key, or with
/// `draft.group`, that group does: you must be its direct admin. Everyone in an
/// owner group reads its room, and its admins manage it. Only the owner changes
/// who is in it or deletes it.
pub async fn create(authorization: &CredentialsOrApiKey, draft: &Draft) -> Result<LiveRoom> {
    let response = client()
        .post(format!("{}/rooms", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(draft)
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(LiveRoom::from_json(&json))
}

/// A room you own or are a member of, with its state.
pub async fn get(authorization: &CredentialsOrApiKey, id: &str) -> Result<LiveRoom> {
    let response = client()
        .get(format!("{}/rooms/{}", crate::get_url(), encode(id)))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(LiveRoom::from_json(&json))
}

/// Everyone in a room: everyone in its groups (and its owner group), directly or
/// through a nested group, and its email members. Anyone who can read the room.
pub async fn people(authorization: &CredentialsOrApiKey, id: &str) -> Result<Vec<Person>> {
    let response = client()
        .get(format!("{}/rooms/{}/people", crate::get_url(), encode(id)))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    let rows: Vec<Value> = ok(response).await?.json().await?;
    Ok(rows.iter().map(Person::from_json).collect())
}

/// Replace who is in a room. Its owner only: the person, or for a group's room,
/// that group's admins.
pub async fn set_members(
    authorization: &CredentialsOrApiKey,
    id: &str,
    members: &[Member],
) -> Result<LiveRoom> {
    let response = client()
        .put(format!("{}/rooms/{}/members", crate::get_url(), encode(id)))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(&json!({ "members": members }))
        .send()
        .await?;
    let json: Value = ok(response).await?.json().await?;
    Ok(LiveRoom::from_json(&json))
}

/// Replace a room's state; everyone in it sees the change. The owner (for a
/// group's room, that group's admins) and writers only. With `if_version`, it
/// writes only while the room is still at that version. Resolves to the new
/// version.
pub async fn set_state(
    authorization: &CredentialsOrApiKey,
    id: &str,
    state: &Value,
    if_version: Option<u64>,
) -> Result<u64> {
    let response = client()
        .put(format!("{}/rooms/{}/state", crate::get_url(), encode(id)))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(&json!({ "state": state, "ifVersion": if_version }))
        .send()
        .await?;
    let body: Value = ok(response).await?.json().await?;
    Ok(body["version"].as_u64().unwrap_or_default())
}

/// Delete a room; everyone in it is disconnected. Its owner only: the person, or
/// for a group's room, that group's admins.
pub async fn remove(authorization: &CredentialsOrApiKey, id: &str) -> Result<()> {
    let response = client()
        .delete(format!("{}/rooms/{}", crate::get_url(), encode(id)))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    ok(response).await?;
    Ok(())
}

#[derive(Default)]
struct Snapshot {
    name: String,
    state: Value,
    version: u64,
    role: Role,
}

/// A live room you are in: its state, kept current, and who else is here.
#[derive(Clone)]
pub struct StateRoom {
    room: Room,
    snapshot: Arc<Mutex<Snapshot>>,
}

impl Deref for StateRoom {
    type Target = Room;
    fn deref(&self) -> &Room {
        &self.room
    }
}

struct StateHooks {
    snapshot: Arc<Mutex<Snapshot>>,
    user: Arc<dyn Hooks>,
}

impl StateHooks {
    fn room(&self, room: &Room) -> StateRoom {
        StateRoom {
            room: room.clone(),
            snapshot: self.snapshot.clone(),
        }
    }
}

impl ServerHooks for StateHooks {
    fn create_room(&self, room: &Room, state: &Value) {
        self.user.create_room(room, state);
    }

    fn create_presence(&self, room: &Room, presence: &Presence) {
        self.user.create_presence(room, presence);
    }

    fn remove_presence(&self, room: &Room, presence: &Presence) {
        self.user.remove_presence(room, presence);
    }

    fn on_connection(&self, room: &Room, state: &Value) {
        self.room(room).hydrate(state);
        self.user.on_connection(room, state);
    }

    fn on_event(&self, room: &Room, packet: &Value) -> bool {
        let live = self.room(room);
        let handled = live.handle_event(packet);
        if handled {
            self.user.on_state(&live, &live.state(), live.version());
        }
        self.user.on_event(room, packet) || handled
    }

    fn on_presence(&self, room: &Room) {
        self.user.on_presence(room);
    }

    fn on_closed(&self, room: &Room, reason: Option<&str>) {
        self.user.on_closed(room, reason);
    }
}

impl StateRoom {
    fn snapshot(&self) -> MutexGuard<'_, Snapshot> {
        self.snapshot.lock().unwrap_or_else(PoisonError::into_inner)
    }

    pub fn name(&self) -> String {
        self.snapshot().name.clone()
    }

    pub fn state(&self) -> Value {
        self.snapshot().state.clone()
    }

    pub fn version(&self) -> u64 {
        self.snapshot().version
    }

    /// What you may do here. The owner writes.
    pub fn role(&self) -> Role {
        self.snapshot().role
    }

    pub fn hydrate(&self, snapshot: &Value) {
        if !snapshot.is_object() {
            return;
        }
        let mut current = self.snapshot();
        current.name = snapshot["name"].as_str().unwrap_or_default().to_string();
        current.state = snapshot["state"].clone();
        current.version = snapshot["version"].as_u64().unwrap_or_default();
        current.role = if snapshot["role"] == "write" {
            Role::Write
        } else {
            Role::Read
        };
    }

    pub fn handle_event(&self, packet: &Value) -> bool {
        if packet["event"] != "state" {
            return false;
        }
        let mut current = self.snapshot();
        current.state = packet["data"]["state"].clone();
        if let Some(version) = packet["data"]["version"].as_u64() {
            current.version = version;
        }
        true
    }

    /// Replace the state for everyone here. Writers only; with `if_version`, only
    /// while the room is at that version.
    pub fn set_state(&self, state: &Value, if_version: Option<u64>) {
        self.post(&json!({
            "event": "set-state",
            "data": { "state": state, "ifVersion": if_version },
        }));
    }

    pub async fn connect(
        authorization: &CredentialsOrApiKey,
        target_id: &str,
        hooks: Option<Arc<dyn Hooks>>,
    ) -> Result<(StateRoom, Presence)> {
        let snapshot = Arc::new(Mutex::new(Snapshot::default()));
        let me = connect_server(
            Authorization::Server {
                authorization: authorization.clone(),
                server: format!("fauna:live:{target_id}"),
                group: None,
            },
            &format!("{}/rooms/live", crate::get_url()),
            Arc::new(StateHooks {
                snapshot: snapshot.clone(),
                user: hooks.unwrap_or_else(|| Arc::new(())),
            }),
        )
        .await?;
        let room = StateRoom {
            room: me.room().clone(),
            snapshot,
        };
        Ok((room, me))
    }
}