popsub_sdk 0.4.0

Rust client for PopSub: reconnection, durable sessions, acknowledgements and deduplication
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
//! `Admin`, the account management requests, for clients logged in as an admin.
//!
//! Each call is one request and its reply. None of them is queued while the
//! client is disconnected or resent after a reconnect, because repeating a
//! change such as `create_user` isn't safe: a call made while disconnected
//! fails with `Error::Connect`, and one whose connection drops before the
//! reply fails the same way, whether or not the server carried it out.

use popsub_protocol::{
    Access, BackupInfo, ClientMessage, RoleSpec, ServerMessage, TopicInfo, UserInfo,
};

use crate::client::Client;
use crate::error::Error;

/// The admin requests, borrowed from a `Client` with `Client::admin`.
///
/// Every call fails with `Error::Server` and `ErrorCode::Forbidden` unless
/// the client is logged in as an enabled admin.
#[derive(Debug, Clone, Copy)]
pub struct Admin<'a> {
    /// The client the requests go through.
    client: &'a Client,
}

impl<'a> Admin<'a> {
    /// Wraps a client.
    ///
    /// Args:
    ///     client: The client.
    ///
    /// Returns:
    ///     The handle.
    pub(crate) fn new(client: &'a Client) -> Self {
        Self { client }
    }

    /// Creates an account.
    ///
    /// Args:
    ///     username: Its name.
    ///     password: Its password.
    ///     role: What it may do.
    ///
    /// Returns:
    ///     The new account.
    ///
    /// Raises:
    ///     Error::Server: `user_exists`, `bad_request` for an invalid name,
    ///         password or pattern, or `forbidden`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    pub async fn create_user(
        &self,
        username: impl Into<String>,
        password: impl Into<String>,
        role: RoleSpec,
    ) -> Result<UserInfo, Error> {
        self.user(ClientMessage::CreateUser {
            username: username.into(),
            password: password.into(),
            role,
        })
        .await
    }

    /// Reads an account.
    ///
    /// Args:
    ///     username: The account.
    ///
    /// Returns:
    ///     The account.
    ///
    /// Raises:
    ///     Error::Server: `user_not_found` or `forbidden`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    pub async fn get_user(&self, username: impl Into<String>) -> Result<UserInfo, Error> {
        self.user(ClientMessage::GetUser {
            username: username.into(),
        })
        .await
    }

    /// Lists every account, sorted by name.
    ///
    /// Returns:
    ///     The accounts.
    ///
    /// Raises:
    ///     Error::Server: `forbidden`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    ///     Error::Protocol: When the server answers with something else.
    pub async fn list_users(&self) -> Result<Vec<UserInfo>, Error> {
        match self.client.request(ClientMessage::ListUsers {}).await? {
            ServerMessage::Users { users } => Ok(users),
            other => Err(Error::Protocol(format!("{other:?}"))),
        }
    }

    /// Replaces an account's role. Live subscriptions the new role doesn't
    /// allow are ended.
    ///
    /// Args:
    ///     username: The account.
    ///     role: Its new role.
    ///
    /// Returns:
    ///     The account as it now stands.
    ///
    /// Raises:
    ///     Error::Server: `user_not_found`, `bad_request` for an invalid
    ///         pattern or for demoting the last enabled admin, or `forbidden`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    pub async fn set_role(
        &self,
        username: impl Into<String>,
        role: RoleSpec,
    ) -> Result<UserInfo, Error> {
        self.user(ClientMessage::SetRole {
            username: username.into(),
            role,
        })
        .await
    }

    /// Grants an account a topic pattern, replacing any grant it already
    /// has for exactly that pattern.
    ///
    /// Args:
    ///     username: The account.
    ///     pattern: The topic pattern.
    ///     access: What it allows.
    ///
    /// Returns:
    ///     The account as it now stands.
    ///
    /// Raises:
    ///     Error::Server: `user_not_found`, `bad_request` (an invalid
    ///         pattern, an admin account, or publishing for a readonly one),
    ///         or `forbidden`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    pub async fn grant(
        &self,
        username: impl Into<String>,
        pattern: impl Into<String>,
        access: Access,
    ) -> Result<UserInfo, Error> {
        self.user(ClientMessage::Grant {
            username: username.into(),
            pattern: pattern.into(),
            access,
        })
        .await
    }

    /// Removes one of an account's grants. Live subscriptions that are no
    /// longer allowed are ended.
    ///
    /// Args:
    ///     username: The account.
    ///     pattern: The pattern, exactly as granted.
    ///
    /// Returns:
    ///     The account as it now stands.
    ///
    /// Raises:
    ///     Error::Server: `user_not_found`, `bad_request` when the account
    ///         has no such grant, or `forbidden`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    pub async fn revoke(
        &self,
        username: impl Into<String>,
        pattern: impl Into<String>,
    ) -> Result<UserInfo, Error> {
        self.user(ClientMessage::Revoke {
            username: username.into(),
            pattern: pattern.into(),
        })
        .await
    }

    /// Sets an account's password. Tokens issued before it are cancelled,
    /// and the account's connections are closed so they log in again.
    ///
    /// Args:
    ///     username: The account.
    ///     password: The new password.
    ///
    /// Returns:
    ///     The account.
    ///
    /// Raises:
    ///     Error::Server: `user_not_found`, `bad_request` for a password
    ///         that is too short or too long, or `forbidden`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    pub async fn set_password(
        &self,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Result<UserInfo, Error> {
        self.user(ClientMessage::SetPassword {
            username: username.into(),
            password: password.into(),
        })
        .await
    }

    /// Enables or disables an account. Disabling closes its connections
    /// with `CloseCode::AccountDisabled` and refuses its logins and tokens.
    ///
    /// Args:
    ///     username: The account.
    ///     enabled: Whether it may log in.
    ///
    /// Returns:
    ///     The account as it now stands.
    ///
    /// Raises:
    ///     Error::Server: `user_not_found`, `bad_request` for disabling the
    ///         last enabled admin, or `forbidden`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    pub async fn set_enabled(
        &self,
        username: impl Into<String>,
        enabled: bool,
    ) -> Result<UserInfo, Error> {
        self.user(ClientMessage::SetEnabled {
            username: username.into(),
            enabled,
        })
        .await
    }

    /// Deletes an account and closes its connections with
    /// `CloseCode::AccountDisabled`.
    ///
    /// Args:
    ///     username: The account.
    ///
    /// Raises:
    ///     Error::Server: `user_not_found`, `bad_request` for the last
    ///         enabled admin, or `forbidden`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    ///     Error::Protocol: When the server answers with something else.
    pub async fn delete_user(&self, username: impl Into<String>) -> Result<(), Error> {
        let username = username.into();
        match self
            .client
            .request(ClientMessage::DeleteUser { username })
            .await?
        {
            ServerMessage::UserDeleted { .. } => Ok(()),
            other => Err(Error::Protocol(format!("{other:?}"))),
        }
    }

    /// Lists every topic that has a log, sorted by name.
    ///
    /// Returns:
    ///     The topics, with their bounds, record counts and live subscribers.
    ///
    /// Raises:
    ///     Error::Server: `forbidden`, or `storage_unavailable`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    ///     Error::Protocol: When the server answers with something else.
    pub async fn list_topics(&self) -> Result<Vec<TopicInfo>, Error> {
        match self.client.request(ClientMessage::ListTopics {}).await? {
            ServerMessage::Topics { topics } => Ok(topics),
            other => Err(Error::Protocol(format!("{other:?}"))),
        }
    }

    /// Describes one topic.
    ///
    /// Args:
    ///     topic: The topic.
    ///
    /// Returns:
    ///     Its bounds, record count and live subscribers.
    ///
    /// Raises:
    ///     Error::Server: `topic_not_found`, `forbidden`, or `storage_unavailable`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    ///     Error::Protocol: When the server answers with something else.
    pub async fn get_topic(&self, topic: impl Into<String>) -> Result<TopicInfo, Error> {
        self.topic(ClientMessage::GetTopic {
            topic: topic.into(),
        })
        .await
    }

    /// Removes every record a topic holds. Its numbering carries on, and
    /// subscribers that hadn't caught up are told their history was truncated.
    ///
    /// Args:
    ///     topic: The topic.
    ///
    /// Returns:
    ///     The topic afterwards.
    ///
    /// Raises:
    ///     Error::Server: `topic_not_found`, `forbidden`, or `storage_unavailable`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    ///     Error::Protocol: When the server answers with something else.
    pub async fn purge_topic(&self, topic: impl Into<String>) -> Result<TopicInfo, Error> {
        self.topic(ClientMessage::PurgeTopic {
            topic: topic.into(),
        })
        .await
    }

    /// Asks the server to back itself up while it keeps running: its topic
    /// logs, sessions and accounts, into a new directory under its
    /// `storage.backup_path`.
    ///
    /// The reply comes when the copy is finished, which for a large store
    /// can take longer than the default `ClientConfig::request_timeout`;
    /// give the client a longer one for backups.
    ///
    /// Args:
    ///     name: The backup's directory name, or `None` for the current time
    ///         in UTC, such as `20261127T101500Z`.
    ///
    /// Returns:
    ///     The backup's name, where it is on the server, and what it holds.
    ///
    /// Raises:
    ///     Error::Server: `bad_request` for an invalid name, `backup_exists`,
    ///         `backup_unsupported` for the `memory` backend,
    ///         `storage_unavailable` when another backup is running or a file
    ///         can't be written, or `forbidden`.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    ///     Error::Protocol: When the server answers with something else.
    pub async fn backup(&self, name: Option<String>) -> Result<BackupInfo, Error> {
        match self.client.request(ClientMessage::Backup { name }).await? {
            ServerMessage::BackupCreated { backup } => Ok(backup),
            other => Err(Error::Protocol(format!("{other:?}"))),
        }
    }

    /// Sends a request answered by a `topic_info` frame.
    ///
    /// Args:
    ///     message: The request.
    ///
    /// Returns:
    ///     The topic in the reply.
    ///
    /// Raises:
    ///     Error::Server: When the server refused it.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    ///     Error::Protocol: When the server answers with something else.
    async fn topic(&self, message: ClientMessage) -> Result<TopicInfo, Error> {
        match self.client.request(message).await? {
            ServerMessage::TopicInfo { topic } => Ok(topic),
            other => Err(Error::Protocol(format!("{other:?}"))),
        }
    }

    /// Sends a request answered by a `user` frame.
    ///
    /// Args:
    ///     message: The request.
    ///
    /// Returns:
    ///     The account in the reply.
    ///
    /// Raises:
    ///     Error::Server: When the server refused it.
    ///     Error::Connect: When disconnected, or the connection dropped first.
    ///     Error::Timeout: When no reply arrived in time.
    ///     Error::Closed: When the client has stopped.
    ///     Error::Protocol: When the server answers with something else.
    async fn user(&self, message: ClientMessage) -> Result<UserInfo, Error> {
        match self.client.request(message).await? {
            ServerMessage::User { user } => Ok(user),
            other => Err(Error::Protocol(format!("{other:?}"))),
        }
    }
}