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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
use crate::{types::*, Error, UserCache};
use reqwest::{
    header::{HeaderMap, HeaderValue},
    Response,
};
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value;
use std::sync::{Arc, RwLock};

const DEFAULT_ENDPOINT: &str = "https://zenkit.com/api/v1";
const API_TOKEN_ENV_VAR: &str = "ZENKIT_API_TOKEN";

/// Zenkit http/API client
#[derive(Debug)]
pub struct ApiClient {
    client: reqwest::Client,
    url_prefix: String, // url prefix
    ratelimit: Option<u32>,
    ratelimit_remaining: Option<u32>,
    /// cache of workspaces, loaded with get_all_workspaces_and_ids
    workspaces: RwLock<Vec<Arc<WorkspaceData>>>,
    /// cache of lists
    lists: RwLock<Vec<Arc<ListInfo>>>,
}

/// Initialization parameters for Zenkit Api client
/// ```rust
/// use zenkit::{init_api,ApiConfig};
/// let api = init_api(ApiConfig::default()).unwrap();
/// ```
pub struct ApiConfig {
    /// Secret API Token. Default value is from environment: ZENKIT_API_TOKEN
    pub token: String,
    /// HTTPS endpoint. Defaults to "https://zenkit.com/api/v1"
    pub endpoint: String,
}

impl Default for ApiConfig {
    fn default() -> Self {
        Self {
            endpoint: String::from(DEFAULT_ENDPOINT),
            token: std::env::var(API_TOKEN_ENV_VAR).ok().unwrap_or_default(),
        }
    }
}

// generate user-agent header value from package version in the form "zenkit rs x.y.z"
fn user_agent_header() -> HeaderValue {
    let agent = &format!(
        "{} rs {}",
        env!("CARGO_PKG_NAME"),
        env!("CARGO_PKG_VERSION")
    );
    HeaderValue::from_str(agent).unwrap_or_else(|_| HeaderValue::from_static("zenkit_rust"))
}

impl ApiClient {
    /// Constructs a new ApiClient.
    /// Because there are some functions that use the "global" get_api(),
    /// most users should use [init_api] instead of this constructor.
    /// Error if token is non-ascii
    pub(crate) fn new(config: ApiConfig) -> Result<Self, Error> {
        use reqwest::header::{CONTENT_TYPE, USER_AGENT};
        if config.token.is_empty() {
            let env_is_set = match std::env::var(API_TOKEN_ENV_VAR) {
                Ok(s) => !s.is_empty(),
                Err(_) => false,
            };
            let msg = match env_is_set {
                false => format!(
                    "Missing API token. Do you need to set the environment variable '{}'?",
                    API_TOKEN_ENV_VAR
                ),
                true => "Missing API token. The token is needed as a parameter to ApiClient::new()"
                    .to_string(),
                // couldn't tell if env is set
            };
            return Err(Error::MissingAPIToken(msg));
        }
        let mut headers = HeaderMap::new();
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
        headers.insert(USER_AGENT, user_agent_header());
        headers.insert(
            "Zenkit-API-Key",
            HeaderValue::from_str(&config.token)
                .map_err(|_| Error::Other("token has non-ascii chars".to_string()))?,
        );
        let client = reqwest::Client::builder()
            .default_headers(headers)
            .build()?;

        Ok(Self {
            client,
            url_prefix: config.endpoint,
            ratelimit: None,
            ratelimit_remaining: None,
            workspaces: RwLock::new(Vec::new()),
            lists: RwLock::new(Vec::new()),
        })
    }

    /// Returns the rate limit returned on the most recent api call
    /// Not yet implemented
    pub fn get_rate_limit(&self) -> Option<u32> {
        self.ratelimit
    }

    /// Returns the rate limit remaining on the most recent api call
    /// Not yet implemented
    pub fn get_rate_limit_remaining(&self) -> Option<u32> {
        self.ratelimit_remaining
    }

    /// Check response for http errors and deserialize to requested object type.
    /// This is called on every response returned from the api client
    async fn json<T: DeserializeOwned>(&self, resp: Response) -> Result<T, Error> {
        //
        // see if api gave us pushback for rate limit
        //   if so, store them internally; otherwise, set None for those fields
        // Since self is not mut, we would need to store these in a Cell
        // match resp.headers.get("x-ratelimit-limit")
        // match resp.headers.get("x-ratelimit-remaining")
        // match resp.headers.get("x-ratelimit-reset") // time when api ok to use again
        //
        let status = &resp.status();
        let bytes = resp.bytes().await?;
        if !status.is_success() {
            // attempt to parse response as Zenkit error
            if let Ok(err_res) = serde_json::from_slice::<ErrorResult>(&bytes) {
                //   should we use error message in lookup table, i.e.:
                //       if let Some(message) = crate::lookup_error(err_res.error.code) ...
                //   - no, if the error provided is more descriptive
                //   - yes, if the error provided is in a different language
                //   For now, just use the message provided
                return Err(Error::ApiError(status.as_u16(), Some(err_res.error)));
            }
            return Err(Error::Other(format!(
                "Server returned status {}:{}",
                status.as_u16(),
                String::from_utf8_lossy(bytes.as_ref())
            )));
        }
        match serde_json::from_slice(&bytes) {
            Ok(obj) => Ok(obj),
            Err(e) => {
                eprintln!(
                    "Error deserializing result {}. data:\n{}",
                    e.to_string(),
                    String::from_utf8_lossy(&bytes)
                );
                Err(e.into())
            }
        }
    }

    /// Returns users in workspace. This method caches the user list so subsequent
    /// calls for the same workspace use the in-memory list.
    pub async fn get_users(&self, workspace_id: ID) -> Result<Vec<Arc<User>>, Error> {
        let ws_cache_read = self.workspaces.read()?;
        let wd = match ws_cache_read
            .iter()
            .find(|w| w.workspace.id == workspace_id)
        {
            Some(w) => w,
            None => {
                return Err(Error::Other(format!(
                    "get_workspace_users: invalid workspace_id '{}'",
                    workspace_id
                )))
            }
        };
        let wd2 = wd.clone();
        // drop to avoid holding lock across await. Cost is a very small chance of duplicate
        // fetches but gain is preventing delay of other uses of workspace list.
        drop(ws_cache_read);
        Ok(wd2.users().await?)
    }

    /// Returns users in the workspace. Bypasses cache and uses zenkit api directly.
    /// See also get_users.
    pub async fn get_users_raw(&self, workspace_id: ID) -> Result<Vec<User>, Error> {
        let url = format!("{}/workspaces/{}/users", self.url_prefix, workspace_id);
        let resp = self.client.get(&url).send().await?;
        self.json(resp).await
    }

    /// Find first user matching predicate
    pub async fn find_user<P>(
        &self,
        workspace_id: ID,
        predicate: P,
    ) -> Result<Option<Arc<User>>, Error>
    where
        P: Fn(&Arc<User>) -> bool,
    {
        let ws_cache_read = self.workspaces.read()?;
        let wd = match ws_cache_read
            .iter()
            .find(|w| w.workspace.id == workspace_id)
        {
            Some(w) => w,
            None => {
                return Err(Error::Other(format!(
                    "get_workspace_users: invalid workspace_id '{}'",
                    workspace_id
                )))
            }
        };
        let wd2 = wd.clone();
        drop(ws_cache_read);
        Ok(wd2.find_user(predicate).await?)
    }

    /// Finds the user id for the name. Name parameter can be display name, full name, or uuid.
    /// String matching is case-insensitive. Return value is Some(id) if found,
    /// None if no match, or Err if there was a network problem getting the user list.
    pub async fn get_user_id(&self, workspace_id: ID, name: &str) -> Result<Option<ID>, Error> {
        let lc_name = name.to_lowercase();
        let id = self
            .find_user(workspace_id, |u| {
                u.display_name.to_lowercase() == lc_name
                    || u.full_name.to_lowercase() == lc_name
                    || u.uuid == lc_name
            })
            .await?
            .map(|u| u.id);
        Ok(id)
    }

    /// get accesses for the user
    pub async fn get_user_accesses(&self) -> Result<Vec<Access>, Error> {
        let resp = self
            .client
            .get(&format!("{}/users/me/access", self.url_prefix))
            .send()
            .await?;
        self.json(resp).await
    }

    /// Returns shared accesses for user
    pub async fn get_shared_accesses<A: Into<AllId>>(
        &self,
        user_allid: A,
    ) -> Result<SharedAccesses, Error> {
        let url = format!(
            "{}/users/me/matching-access/{}",
            self.url_prefix,
            user_allid.into()
        );
        let resp = self.client.get(&url).send().await?;
        self.json(resp).await
    }

    /// returns schema fields of list
    pub async fn get_list_elements<A: Into<AllId>>(
        &self,
        list_allid: A,
    ) -> Result<Vec<Element>, Error> {
        let url = format!("{}/lists/{}/elements", self.url_prefix, list_allid.into());
        let resp = self.client.get(&url).send().await?;
        self.json(resp).await
    }

    /// Returns a single list item
    pub async fn get_entry<L: Into<AllId>, E: Into<AllId>>(
        &self,
        list_allid: L,
        entry_allid: E,
    ) -> Result<Entry, Error> {
        let url = format!(
            "{}/lists/{}/entries/{}",
            self.url_prefix,
            list_allid.into(),
            entry_allid.into()
        );
        let resp = self.client.get(&url).send().await?;
        self.json(resp).await
    }

    /// Returns items from list (possibly filtered/sorted), with pagination
    /// Parameter may be id or uuid. To use name lookup, use get_list_info.
    /// See also get_list_entries_for_view
    pub async fn get_list_entries<A: Into<AllId>>(
        &self,
        list_allid: A,
        params: &GetEntriesRequest,
    ) -> Result<Vec<Entry>, Error> {
        let url = format!(
            "{}/lists/{}/entries/filter",
            self.url_prefix,
            list_allid.into()
        );
        let resp = self.client.post(&url).json(&params).send().await?;
        self.json(resp).await
    }

    /// Returns list items sorted by last update (asc or desc), with pagination
    /// Set 'sort' to Some(column-name, direction), e.g., Some("updated_at", Desc)
    pub async fn get_list_entries_sorted<A: Into<AllId>>(
        &self,
        list_allid: A,
        sort: Option<(&str, SortDirection)>,
        limit: usize, // number to return per call (or 0 for no limit)
        skip: usize,  // number to skip
    ) -> Result<Vec<Entry>, Error> {
        let order_by = if let Some((sort_field, sort_dir)) = sort {
            vec![OrderBy {
                column: Some(String::from(sort_field)),
                direction: sort_dir,
            }]
        } else {
            Vec::new()
        };
        let q = GetEntriesRequest {
            limit,
            skip,
            order_by,
            ..Default::default()
        };
        Ok(self.get_list_entries(list_allid, &q).await?)
    }

    /// Returns items from list - with filter and optional group-by
    /// Compared to get_list_entries, this fn allows optional grouping, and optionally can return deprecated
    /// items, and doesn't allow sorting.
    pub async fn get_list_entries_for_view(
        &self,
        list_id: ID,
        params: &GetEntriesViewRequest,
    ) -> Result<GetEntriesViewResponse, Error> {
        let url = format!("{}/lists/{}/entries/filter/list", self.url_prefix, list_id);
        let resp = self.client.post(&url).json(params).send().await?;
        self.json(resp).await
    }

    /// Update checklists
    pub async fn update_checklists<L: Into<AllId>, E: Into<AllId>>(
        &self,
        list_allid: L,
        entry_allid: E,
        checklists: Vec<Checklist>,
    ) -> Result<(), Error> {
        let url = format!(
            "{}/lists/{}/entries/{}/checklists",
            self.url_prefix,
            list_allid.into(),
            entry_allid.into()
        );
        let data = UpdateChecklistParam { checklists };
        let resp = self.client.put(&url).json(&data).send().await?;
        self.json(resp).await
    }

    /// Delete a list entry
    pub async fn delete_entry<L: Into<AllId>, E: Into<AllId>>(
        &self,
        list_allid: L,
        entry_allid: E,
    ) -> Result<DeleteListEntryResponse, Error> {
        let url = format!(
            "{}/lists/{}/deprecated-entries/{}",
            self.url_prefix,
            list_allid.into(),
            entry_allid.into()
        );
        let resp = self.client.delete(&url).send().await?;
        self.json(resp).await
    }

    // Returns true if workspaces have been loaded
    fn have_workspaces(&self) -> Result<bool, Error> {
        let ws_cache = self.workspaces.read()?;
        Ok(!ws_cache.is_empty())
    }

    fn get_cached_list(&self, list_allid: &str) -> Result<Arc<ListInfo>, Error> {
        let list_cache = self.lists.read()?;
        let li = match list_cache.iter().find(|li| li.has_id(list_allid)) {
            Some(li) => li.clone(),
            None => return Err(Error::Other(format!("Invalid list '{}'", list_allid))),
        };
        Ok(li)
    }

    fn get_cached_workspace_allid(&self, ws_id: &str) -> Result<Arc<WorkspaceData>, Error> {
        // first check previously loaded
        let ws_cache = self.workspaces.read()?;
        let wd = match ws_cache.iter().find(|wd| wd.workspace.has_id(ws_id)) {
            Some(w) => w.clone(),
            None => return Err(Error::Other(format!("Invalid workspace_id '{}'", ws_id))),
        };
        Ok(wd)
    }

    // Returns workspace from cache, or error if there was no match for id
    // Expects that get_all_workspaces_and_lists has been called previously
    fn get_cached_workspace(&self, ws_id: ID) -> Result<Arc<WorkspaceData>, Error> {
        let ws_cache_read = self.workspaces.read()?;
        let wd = match ws_cache_read.iter().find(|w| w.workspace.id == ws_id) {
            Some(w) => w.clone(),
            None => return Err(Error::Other(format!("Invalid workspace_id '{}'", ws_id))),
        };
        Ok(wd)
    }

    /// Loads all workspaces and lists that the current user can access.
    ///
    /// Performance notes:
    /// - Repeaded calls return cached data.
    pub async fn get_all_workspaces_and_lists(&self) -> Result<Vec<Arc<Workspace>>, Error> {
        if !self.have_workspaces()? {
            let resp = self
                .client
                .get(&format!("{}/users/me/workspacesWithLists", self.url_prefix))
                .send()
                .await?;
            let ws_list: Vec<Workspace> = self.json(resp).await?;
            let mut ws_cache_write = self.workspaces.write()?;
            ws_cache_write.append(
                &mut ws_list
                    .into_iter()
                    .map(|w| Arc::new(WorkspaceData::new(w)))
                    .collect(),
            );
            // drop write lock
        }
        let ws_cache = self.workspaces.read()?;
        Ok(ws_cache.iter().map(|wd| wd.workspace.clone()).collect())
    }

    /// Returns the workspace. `ws_id` may be ID, UUID, or title.
    ///
    /// Performance notes:
    /// - If ID or UUID are known, those are preferred over title due to a potential
    ///   performance benefit.
    /// - If you expect to call this for more than one workspace during a single app session,
    ///   it is almost always more efficient to call get_all_workspaces_and_lists first,
    ///   so that all workspaces are fetched with a single hit to Zenkit servers.
    /// - If called more than once for the same workspace id (or an alternate
    ///   identifier of a previously-loaded workspace), a cached value is returned.
    /// - If get_all_workspaces_and_lists has been called previously, this function
    ///   returns cached data and does not incur additional Zenkit server hits if
    ///   ws_id is valid.
    /// - Non-matching parameters are more expensive, performance-wise. If the name
    ///   does not match cached workspaces, an additional query will always be performed.
    pub async fn get_workspace(&self, ws_id: &str) -> Result<Arc<Workspace>, Error> {
        // first check previously loaded
        if let Ok(wd) = self.get_cached_workspace_allid(ws_id) {
            return Ok(wd.workspace.clone());
        }

        // if ws_id is an int or uuid, we can get just one using the call below.
        // If it's a workspace title, we need to get all since api doesn't support get-by-name.
        if ws_id.parse::<i64>().is_ok() || crate::util::is_uuid(ws_id) {
            let url = format!("{}/workspaces/{}", self.url_prefix, ws_id);
            let resp = self.client.get(&url).send().await?;
            let ws_data = WorkspaceData::new(self.json(resp).await?);
            let mut cache_write = self.workspaces.write()?;
            let ws_copy = ws_data.workspace.clone();
            cache_write.push(Arc::new(ws_data));
            return Ok(ws_copy);
        }

        // load & cache all workspaces
        for w in self.get_all_workspaces_and_lists().await?.iter() {
            if w.has_id(ws_id) {
                return Ok(w.clone());
            }
        }
        Err(Error::Other(format!("Workspace '{}' not found", ws_id)))
    }

    /// Retrieves a list, with field definitions.
    /// list_name parameter can be string name, id, or uuid
    pub async fn get_list_info(
        &self,
        workspace_id: ID,
        list_allid: &'_ str,
    ) -> Result<Arc<ListInfo>, Error> {
        // first try list cache
        if let Ok(li) = self.get_cached_list(list_allid) {
            return Ok(li);
        }

        // list_info not cached
        // first get its containing workspace, then load fields
        let wd = match self.get_cached_workspace(workspace_id) {
            Ok(wd) => wd.workspace.clone(),
            Err(_) => {
                // wasn't cached, try to load it, or fail if invalid id
                self.get_workspace(&workspace_id.to_string()).await?
            }
        };

        let list = match wd.lists.iter().find(|l| l.has_id(list_allid)) {
            Some(list) => list.clone(),
            None => {
                return Err(Error::Other(format!(
                    "get_list_info: invalid list '{}' in workspace '{}' ({})",
                    list_allid, wd.name, workspace_id
                )))
            }
        };
        // load fields
        let fields = self.get_list_elements(list.id).await?;

        let info = Arc::new(ListInfo::new(list, fields));
        let mut list_cache_write = self.lists.write()?;
        list_cache_write.push(info.clone());
        Ok(info)
    }

    /// Clears workspace cache
    pub fn clear_workspace_cache(&self) -> Result<(), Error> {
        let mut ws_cache_write = self.workspaces.write()?;
        ws_cache_write.clear();
        Ok(())
    }

    /// Clears ListInfo cache. Note: ListInfo cache contains field definitions, not items.
    pub fn clear_list_cache(&self) -> Result<(), Error> {
        let mut list_cache_write = self.lists.write()?;
        list_cache_write.clear();
        Ok(())
    }

    /// Creates a new list entry
    pub async fn create_entry(&self, list_id: ID, val: Value) -> Result<Entry, Error> {
        let url = format!("{}/lists/{}/entries", self.url_prefix, list_id);
        let resp = self.client.post(&url).json(&val).send().await?;
        self.json(resp).await
    }

    /// Creates a new webhook
    pub async fn create_webhook(&self, webhook: &NewWebhook) -> Result<Webhook, Error> {
        let url = format!("{}/webhooks", self.url_prefix);
        let resp = self.client.post(&url).json(&webhook).send().await?;
        self.json(resp).await
    }

    /// Deletes webhook
    pub async fn delete_webhook(&self, webhook_id: ID) -> Result<Webhook, Error> {
        let url = format!("{}/webhooks/{}", self.url_prefix, webhook_id);
        let resp = self.client.delete(&url).send().await?;
        self.json(resp).await
    }

    /// List webhooks created by the current user
    pub async fn get_webhooks(&self) -> Result<Vec<Webhook>, Error> {
        // found this undocumented api by trial-and-error.
        // .. tried /webooks and /workspaces/ID/webhooks before finding /users/me/webhooks
        let url = format!("{}/users/me/webhooks", self.url_prefix);
        let resp = self.client.get(&url).send().await?;
        self.json(resp).await
    }

    /// Updates list field-value
    pub async fn update_entry(
        &self,
        list_id: ID,
        entry_id: ID,
        val: Value,
    ) -> Result<Entry, Error> {
        let url = format!("{}/lists/{}/entries/{}", self.url_prefix, list_id, entry_id);
        let resp = self.client.put(&url).json(&val).send().await?;
        self.json(resp).await
    }

    /// Creates a new list Comment
    pub async fn create_list_comment(
        &self,
        list_id: ID,
        comment: &NewComment,
    ) -> Result<Activity, Error> {
        let url = format!("{}/users/me/lists/{}/activities", self.url_prefix, list_id);
        let resp = self.client.post(&url).json(&comment).send().await?;
        self.json(resp).await
    }

    /// Creates a new list entry Comment
    pub async fn create_entry_comment(
        &self,
        list_id: ID,
        entry_id: ID,
        comment: &NewComment,
    ) -> Result<Activity, Error> {
        let url = format!(
            "{}/users/me/lists/{}/entries/{}/activities",
            self.url_prefix, list_id, entry_id
        );
        let resp = self.client.post(&url).json(&comment).send().await?;
        self.json(resp).await
    }
}

// used internally for updateChecklists api
#[derive(Serialize, Debug)]
struct UpdateChecklistParam {
    checklists: Vec<Checklist>,
}

#[derive(Debug)]
struct WorkspaceData {
    workspace: Arc<Workspace>,
    user_cache: RwLock<UserCache>,
}

impl WorkspaceData {
    fn new(w: Workspace) -> Self {
        Self {
            workspace: Arc::new(w),
            user_cache: Default::default(),
        }
    }

    /// Returns user cache; loads users if cache has not been initialized,
    /// or if force_reload is true
    pub async fn ensure_user_cache(&self, force_reload: bool) -> Result<(), Error> {
        let mut write = self.user_cache.write()?;
        if write.is_empty() || force_reload {
            write.replace_all(
                crate::get_api()?
                    .get_users_raw(self.workspace.id)
                    .await?
                    .into_iter()
                    .map(Arc::new)
                    .collect(),
            );
        }
        Ok(())
    }

    /// Returns list of users in workspace
    pub async fn users(&self) -> Result<Vec<Arc<User>>, Error> {
        self.ensure_user_cache(false).await?;
        let read = self.user_cache.read()?;
        Ok(read.users())
    }

    /// Find first user matching predicate
    pub async fn find_user<P>(&self, predicate: P) -> Result<Option<Arc<User>>, Error>
    where
        P: Fn(&Arc<User>) -> bool,
    {
        self.ensure_user_cache(false).await?;
        let read = self.user_cache.read()?;
        Ok(read.find_user(predicate))
    }
}