Skip to main content

suno_core/
client.rs

1//! The Suno API client: lists the library behind the [`Http`](crate::Http) port.
2
3use std::collections::{BTreeSet, HashMap};
4use std::sync::Mutex;
5use std::time::Instant;
6
7use futures_util::stream::{self, StreamExt};
8
9use crate::auth::ClerkAuth;
10use crate::backoff::{backoff_delay, retry_after};
11use crate::clock::Clock;
12use crate::consts::{
13    API_MAX_RETRIES, BILLING_INFO_PATH, CLIP_PARENT_PATH, FEED_INITIAL_RATE, FEED_V3_PATH,
14    GET_SONGS_BY_IDS_PATH, GET_SONGS_CHUNK, MAX_PAGES, PLAYLIST_ME_PATH, PLAYLIST_PATH,
15    SUNO_API_BASE_URL,
16};
17use crate::error::{Error, Result};
18use crate::http::{Http, HttpRequest, Method};
19use crate::limiter::{AdaptiveLimiter, retry_after_delay};
20use crate::lyrics::AlignedLyrics;
21use crate::model::{BillingInfo, Clip, Playlist, Stem};
22use crate::wire::{
23    feed_v3_body, parse_aligned_lyrics, parse_billing_info, parse_clip, parse_feed_v3,
24    parse_playlist_clips, parse_playlists, parse_songs_batch, parse_stem_page_count,
25    parse_stems_page, parse_wav_url,
26};
27
28/// A client for the Suno library API, owning the account's [`ClerkAuth`].
29///
30/// Holds the [`Clock`] so [`api_request`](Self::api_request) can back off on a
31/// `429` or transient failure, and an [`AdaptiveLimiter`] that paces reactively:
32/// it waits nowhere until a `429`, then halves the rate and ramps it back on
33/// sustained success.
34pub struct SunoClient<C> {
35    auth: ClerkAuth,
36    clock: C,
37    limiter: Mutex<AdaptiveLimiter>,
38}
39
40impl<C: Clock> SunoClient<C> {
41    /// Create a client from a fresh or already-authenticated [`ClerkAuth`].
42    pub fn new(auth: ClerkAuth, clock: C) -> Self {
43        Self {
44            auth,
45            clock,
46            limiter: Mutex::new(AdaptiveLimiter::new(FEED_INITIAL_RATE)),
47        }
48    }
49
50    /// Borrow the underlying authenticator.
51    pub fn auth(&self) -> &ClerkAuth {
52        &self.auth
53    }
54
55    /// The adaptive limiter's current requests-per-second rate, for tests.
56    #[cfg(test)]
57    pub(crate) fn limiter_rate(&self) -> f64 {
58        self.limiter.lock().unwrap().rate()
59    }
60
61    /// List clips across the whole library, or only liked clips.
62    ///
63    /// Walks the cursor-paginated `POST /api/feed/v3` feed, hard-capped at
64    /// [`MAX_PAGES`], truncating to `limit` when set.
65    ///
66    /// The `complete` flag is `true` only when paging ended on a server-reported
67    /// `has_more == false`; any other stop (missing `has_more`, no usable cursor,
68    /// `limit`, [`MAX_PAGES`], transport error) yields `false` so the caller
69    /// never treats a truncated listing as authoritative for deletion.
70    /// `any_filtered` is `true` when the downloadable filter dropped any clip,
71    /// which likewise denies deletion authority since it may have hidden a
72    /// manifest-tracked clip.
73    pub async fn list_clips(
74        &self,
75        http: &impl Http,
76        liked: bool,
77        limit: Option<usize>,
78    ) -> Result<(Vec<Clip>, bool, bool)> {
79        let mut clips = Vec::new();
80        let mut cursor: Option<String> = None;
81        let mut complete = false;
82        let mut any_filtered = false;
83        for _ in 0..MAX_PAGES {
84            let body = feed_v3_body(liked, cursor.as_deref());
85            let response = self
86                .api_send_retrying(http, Method::Post, FEED_V3_PATH, body)
87                .await?;
88            let page = parse_feed_v3(&response)?;
89            clips.extend(page.clips);
90            any_filtered |= page.any_filtered;
91            match page.has_more {
92                Some(false) => {
93                    complete = true;
94                    break;
95                }
96                Some(true) => match page.next_cursor {
97                    Some(next) => cursor = Some(next),
98                    None => break,
99                },
100                None => break,
101            }
102            if limit.is_some_and(|n| clips.len() >= n) {
103                break;
104            }
105        }
106        if let Some(n) = limit {
107            clips.truncate(n);
108        }
109        Ok((clips, complete, any_filtered))
110    }
111
112    /// Fetch one clip by ID.
113    ///
114    /// Tries the dedicated `/api/clip/{id}` endpoint first, then falls back to
115    /// scanning the library feed if that endpoint yields no matching clip.
116    pub async fn get_clip(&self, http: &impl Http, id: &str) -> Result<Clip> {
117        if let Some(clip) = self.try_get_clip(http, id).await? {
118            return Ok(clip);
119        }
120        self.find_in_feed(http, id).await
121    }
122
123    /// Ask Suno to render a clip to lossless WAV (server-side, asynchronous).
124    pub async fn request_wav(&self, http: &impl Http, id: &str) -> Result<()> {
125        let path = format!("/api/gen/{id}/convert_wav/");
126        self.api_request(http, Method::Post, &path, Vec::new())
127            .await?;
128        Ok(())
129    }
130
131    /// Read the rendered WAV URL for a clip, or `None` while it is not ready.
132    ///
133    /// A `404` maps to `None` (not yet rendered), and it skips the shared retry
134    /// so the caller's poll loop owns that budget.
135    pub async fn wav_url(&self, http: &impl Http, id: &str) -> Result<Option<String>> {
136        let path = format!("/api/gen/{id}/wav_file/");
137        let body = match self.api_get(http, &path).await {
138            Ok(body) => body,
139            Err(Error::NotFound(_)) => return Ok(None),
140            Err(err) => return Err(err),
141        };
142        parse_wav_url(&body)
143    }
144
145    /// Fetch a clip's word- and line-level aligned (synced) lyrics.
146    ///
147    /// The trailing slash on `.../aligned_lyrics/v2/` is required. An
148    /// instrumental or un-alignable clip returns `200` with empty arrays, and a
149    /// `404` is treated the same way, so an absent alignment is "no synced
150    /// lyrics" rather than a run failure.
151    pub async fn aligned_lyrics(&self, http: &impl Http, id: &str) -> Result<AlignedLyrics> {
152        let path = format!("/api/gen/{id}/aligned_lyrics/v2/");
153        match self.api_get_retrying(http, &path).await {
154            Ok(body) => Ok(parse_aligned_lyrics(&body)),
155            Err(Error::NotFound(_)) => Ok(AlignedLyrics::default()),
156            Err(err) => Err(err),
157        }
158    }
159
160    /// Fetch specific clips by id, batch-first with a per-id fallback.
161    ///
162    /// Used by lineage resolution to gap-fill ancestors absent from a normal
163    /// listing, including trashed ones. Ids are fetched in one batch via
164    /// [`get_songs_by_ids`](Self::get_songs_by_ids); any the batch omits fall
165    /// back to one `GET /api/clip/{id}` each, bounded by `concurrency`, attempted
166    /// once, with a `404` skipped. A `429` while batching propagates rather than
167    /// fanning out into per-id requests.
168    ///
169    /// No downloadability filter is applied: an ancestor may be an infill or
170    /// context artefact the walk must still traverse, so these clips are for
171    /// resolution only and must never be treated as download candidates. Ids are
172    /// deduplicated in order and the result preserves that order, matched by id.
173    pub async fn get_clips_by_ids(
174        &self,
175        http: &impl Http,
176        ids: &[&str],
177        concurrency: usize,
178    ) -> Result<Vec<Clip>> {
179        let ordered = dedup_nonempty(ids);
180        let mut found: HashMap<&str, Clip> = self
181            .get_songs_by_ids(http, &ordered)
182            .await?
183            .into_iter()
184            .filter_map(|clip| {
185                ordered
186                    .iter()
187                    .find(|id| **id == clip.id)
188                    .map(|id| (*id, clip))
189            })
190            .collect();
191        let omitted: Vec<&str> = ordered
192            .iter()
193            .copied()
194            .filter(|id| !found.contains_key(id))
195            .collect();
196        if !omitted.is_empty() {
197            for clip in self
198                .fetch_clips_individually(http, &omitted, concurrency)
199                .await?
200            {
201                if let Some(id) = ordered.iter().copied().find(|id| *id == clip.id) {
202                    found.insert(id, clip);
203                }
204            }
205        }
206        Ok(ordered.iter().filter_map(|id| found.remove(id)).collect())
207    }
208
209    /// Batch-fetch clips by id via `GET /api/clips/get_songs_by_ids?ids=…&ids=…`.
210    ///
211    /// The pure batch primitive: deduplicated ids are split into
212    /// [`GET_SONGS_CHUNK`] chunks and matched back by id, preserving input order.
213    /// Ids the batch does not return are left for the caller to fill.
214    ///
215    /// The endpoint is undocumented and may be unavailable: a chunk it cannot
216    /// serve (any `4xx`/`5xx`, transport failure, or unexpected body) yields
217    /// nothing for that chunk rather than erroring, so an outage degrades rather
218    /// than breaks. A `429` rides the retry and then propagates rather than
219    /// fanning out into per-id requests; an auth failure likewise propagates.
220    pub async fn get_songs_by_ids(&self, http: &impl Http, ids: &[&str]) -> Result<Vec<Clip>> {
221        let ordered = dedup_nonempty(ids);
222        let mut found: HashMap<&str, Clip> = HashMap::new();
223        for chunk in ordered.chunks(GET_SONGS_CHUNK) {
224            let query = chunk
225                .iter()
226                .map(|id| format!("ids={id}"))
227                .collect::<Vec<_>>()
228                .join("&");
229            let path = format!("{GET_SONGS_BY_IDS_PATH}?{query}");
230            let clips = match self.api_get_retrying(http, &path).await {
231                Ok(body) => parse_songs_batch(&body).unwrap_or_default(),
232                Err(err @ (Error::RateLimited { .. } | Error::Auth(_))) => return Err(err),
233                Err(_) => Vec::new(),
234            };
235            for clip in clips {
236                if let Some(id) = chunk.iter().copied().find(|id| *id == clip.id) {
237                    found.insert(id, clip);
238                }
239            }
240        }
241        Ok(ordered.iter().filter_map(|id| found.remove(id)).collect())
242    }
243
244    /// The per-id `GET /api/clip/{id}` fallback for
245    /// [`get_clips_by_ids`](Self::get_clips_by_ids), with bounded concurrency.
246    /// Returns any clip (trashed or artefact) unfiltered; a `404` is skipped and
247    /// input order is preserved.
248    async fn fetch_clips_individually(
249        &self,
250        http: &impl Http,
251        ids: &[&str],
252        concurrency: usize,
253    ) -> Result<Vec<Clip>> {
254        let limit = concurrency.max(1);
255        let fetched = stream::iter(ids.iter().copied())
256            .map(|id| async move {
257                let path = format!("/api/clip/{id}");
258                match self.api_get_retrying(http, &path).await {
259                    Ok(body) => Ok(parse_clip(&body)),
260                    Err(Error::NotFound(_)) => Ok(None),
261                    Err(err) => Err(err),
262                }
263            })
264            .buffered(limit)
265            .collect::<Vec<_>>()
266            .await;
267        let mut clips = Vec::new();
268        for item in fetched {
269            if let Some(clip) = item? {
270                clips.push(clip);
271            }
272        }
273        Ok(clips)
274    }
275
276    /// Fetch a clip's immediate parent, or `None` when the clip is a root.
277    ///
278    /// A root's parent comes back as `200` with a bodiless, id-less clip (not a
279    /// `404`); [`parse_clip`] gates on a non-empty id so that maps to `Ok(None)`.
280    /// The `404` arm is a fallback for the alternative encoding. Any other
281    /// failure propagates rather than being mistaken for a root.
282    pub async fn get_clip_parent(&self, http: &impl Http, id: &str) -> Result<Option<Clip>> {
283        let path = format!("{CLIP_PARENT_PATH}?clip_id={id}");
284        match self.api_get_retrying(http, &path).await {
285            Ok(body) => Ok(parse_clip(&body)),
286            Err(Error::NotFound(_)) => Ok(None),
287            Err(err) => Err(err),
288        }
289    }
290
291    /// List the account's own playlists, paging `/api/playlist/me`.
292    ///
293    /// Trashed and share-list playlists are excluded by query. Paging stops on
294    /// the first empty page, is hard-capped at [`MAX_PAGES`], and de-duplicates
295    /// by id so a server that ignores the page parameter cannot loop or inflate
296    /// the set.
297    ///
298    /// A hard failure propagates: the caller then refuses every playlist
299    /// deletion this run, so a dropped fetch can never remove a `.m3u8`.
300    pub async fn get_playlists(&self, http: &impl Http) -> Result<Vec<Playlist>> {
301        let mut playlists = Vec::new();
302        let mut seen = BTreeSet::new();
303        for page in 1..=MAX_PAGES {
304            let path =
305                format!("{PLAYLIST_ME_PATH}?page={page}&show_trashed=false&show_sharelist=false");
306            let body = self.api_get_retrying(http, &path).await?;
307            let page_playlists = parse_playlists(&body)?;
308            if page_playlists.is_empty() {
309                break;
310            }
311            for playlist in page_playlists {
312                if seen.insert(playlist.id.clone()) {
313                    playlists.push(playlist);
314                }
315            }
316        }
317        Ok(playlists)
318    }
319
320    /// Fetch one playlist's clips in Suno order via `/api/playlist/{id}/`.
321    ///
322    /// `playlist_clips[]` is already ordered with trashed members excluded, so
323    /// order is preserved and no downloadability filter is applied. Only clips
324    /// with a non-empty id are kept.
325    ///
326    /// The returned `bool` is a completeness signal for deletion authority:
327    /// `true` only when `num_total_results` is present, equals the raw count, and
328    /// no member was dropped for a missing id. A short or id-missing page returns
329    /// `false`, so a Mirror playlist under `library = "off"` is never
330    /// authoritative unless its whole member set was seen.
331    pub async fn get_playlist_clips(
332        &self,
333        http: &impl Http,
334        id: &str,
335    ) -> Result<(Vec<Clip>, bool)> {
336        let path = format!("{PLAYLIST_PATH}{id}/");
337        let body = self.api_get_retrying(http, &path).await?;
338        parse_playlist_clips(&body)
339    }
340
341    /// Read the authenticated account's billing information.
342    pub async fn get_billing_info(&self, http: &impl Http) -> Result<BillingInfo> {
343        let body = self.api_get_retrying(http, BILLING_INFO_PATH).await?;
344        parse_billing_info(&body)
345    }
346
347    /// List a clip's already-separated stems (free, read-only).
348    ///
349    /// Pages `GET /api/clip/{id}/stems/pages` then `.../stems?page=P` (0-indexed).
350    /// This endpoint only reads: it never spends credits or triggers separation,
351    /// so it is safe on the bulk mirror path. Call only when the clip's
352    /// `has_stem` is true.
353    ///
354    /// The `complete` flag is `true` only when the page count came back and every
355    /// page drained after at least one stem was seen. An empty listing
356    /// (`pages == 0` or a `400`/`404` on the page-count endpoint), a transport
357    /// failure, a partial drain, or a count above [`MAX_PAGES`] all yield
358    /// `false`, so the caller KEEPS existing local stems rather than reading the
359    /// absence as "no stems".
360    pub async fn list_stems(&self, http: &impl Http, clip_id: &str) -> Result<(Vec<Stem>, bool)> {
361        let declared = self.stem_page_count(http, clip_id).await?;
362        // Zero pages is Suno's "no stems" answer: indeterminate, never an
363        // authoritative empty.
364        if declared == 0 {
365            return Ok((Vec::new(), false));
366        }
367        let pages = declared.min(MAX_PAGES);
368        let mut stems: Vec<Stem> = Vec::new();
369        for page in 0..pages {
370            // Pages are 0-indexed; no trailing slash before the query (unlike
371            // `.../stems/pages`).
372            let path = format!("/api/clip/{clip_id}/stems?page={page}");
373            // A page error mid-enumeration is indeterminate: surface it so the
374            // caller keeps existing stems rather than reading a partial drain as
375            // authoritative.
376            let body = self.api_get_retrying(http, &path).await?;
377            stems.extend(parse_stems_page(&body));
378        }
379        dedupe_stems(&mut stems);
380        let complete = !stems.is_empty() && declared <= MAX_PAGES;
381        Ok((stems, complete))
382    }
383
384    /// Read the stems page count from `GET /api/clip/{id}/stems/pages`.
385    ///
386    /// A clip with no stems answers `400`/`404`; both map to `0` (indeterminate,
387    /// never an authoritative empty). Any other error propagates so the caller
388    /// keeps the stems as unknown.
389    async fn stem_page_count(&self, http: &impl Http, clip_id: &str) -> Result<u32> {
390        let path = format!("/api/clip/{clip_id}/stems/pages");
391        match self.api_get_retrying(http, &path).await {
392            Ok(body) => Ok(parse_stem_page_count(&body)),
393            Err(err) if is_invalid_page_error(&err) => Ok(0),
394            Err(Error::NotFound(_)) => Ok(0),
395            Err(err) => Err(err),
396        }
397    }
398
399    /// Try the dedicated clip endpoint, returning `None` when it is missing or
400    /// returns a body that does not yield the requested clip.
401    async fn try_get_clip(&self, http: &impl Http, id: &str) -> Result<Option<Clip>> {
402        let path = format!("/api/clip/{id}");
403        match self.api_get_retrying(http, &path).await {
404            Ok(body) => Ok(parse_clip(&body).filter(|clip| clip.id == id)),
405            Err(Error::NotFound(_)) => Ok(None),
406            Err(err) => Err(err),
407        }
408    }
409
410    /// Locate a clip by scanning the library feed.
411    async fn find_in_feed(&self, http: &impl Http, id: &str) -> Result<Clip> {
412        let (clips, _complete, _) = self.list_clips(http, false, None).await?;
413        clips
414            .into_iter()
415            .find(|clip| clip.id == id)
416            .ok_or_else(|| Error::Api(format!("clip {id} not found in the library")))
417    }
418
419    /// Perform an authenticated GET, refreshing the JWT once on a 401/403.
420    async fn api_get(&self, http: &impl Http, path: &str) -> Result<Vec<u8>> {
421        self.api_request(http, Method::Get, path, Vec::new()).await
422    }
423
424    /// A retrying GET: [`api_send_retrying`](Self::api_send_retrying) with no body.
425    async fn api_get_retrying(&self, http: &impl Http, path: &str) -> Result<Vec<u8>> {
426        self.api_send_retrying(http, Method::Get, path, Vec::new())
427            .await
428    }
429
430    /// Like [`api_request`](Self::api_request) but paces through the adaptive
431    /// rate limiter and backs off via the [`Clock`] on a `429` or transient
432    /// failure, up to [`API_MAX_RETRIES`] times. Each attempt reconstructs the
433    /// request, so a throttled feed page re-POSTs the same cursor rather than
434    /// skipping ahead.
435    ///
436    /// Pacing lives at this single per-request layer so it composes with any
437    /// paged walk. The WAV render flow instead uses the plain
438    /// [`api_get`](Self::api_get) so the executor owns that retry budget.
439    async fn api_send_retrying(
440        &self,
441        http: &impl Http,
442        method: Method,
443        path: &str,
444        body: Vec<u8>,
445    ) -> Result<Vec<u8>> {
446        let pace = self.limiter.lock().unwrap().pace(Instant::now());
447        if !pace.is_zero() {
448            self.clock.sleep(pace).await;
449        }
450        let mut retries = 0;
451        loop {
452            match self.api_request(http, method, path, body.clone()).await {
453                Ok(response) => return Ok(response),
454                Err(Error::RateLimited { retry_after }) if retries < API_MAX_RETRIES => {
455                    self.clock.sleep(retry_after_delay(retry_after)).await;
456                    retries += 1;
457                }
458                Err(Error::Connection(_)) if retries < API_MAX_RETRIES => {
459                    self.clock.sleep(backoff_delay(retries, None)).await;
460                    retries += 1;
461                }
462                Err(err) => return Err(err),
463            }
464        }
465    }
466
467    /// Perform an authenticated request, refreshing the JWT once on a 401/403.
468    ///
469    /// `body` is sent only by the adapter when non-empty, so a GET or a bodyless
470    /// POST reaches the network unchanged.
471    async fn api_request(
472        &self,
473        http: &impl Http,
474        method: Method,
475        path: &str,
476        body: Vec<u8>,
477    ) -> Result<Vec<u8>> {
478        // Crate-wide POST allow-list: every mutating request funnels through
479        // here, so a destructive or credit-spending endpoint can never be sent.
480        // GETs are free and unrestricted.
481        if method == Method::Post && !post_path_allowed(path) {
482            return Err(Error::Refused(format!(
483                "POST to {path} is not on the allow-list"
484            )));
485        }
486        let url = format!("{SUNO_API_BASE_URL}{path}");
487        let mut auth_refreshed = false;
488        loop {
489            let jwt = self.auth.ensure_jwt(self.clock.now_unix(), http).await?;
490            let mut request = match method {
491                Method::Get => HttpRequest::get(url.clone()),
492                Method::Post => HttpRequest::post(url.clone(), body.clone()),
493            };
494            request
495                .headers
496                .push(("Authorization".to_string(), format!("Bearer {jwt}")));
497            let response = http
498                .send(request)
499                .await
500                .map_err(|err| Error::Connection(err.to_string()))?;
501            match response.status {
502                200..=299 => {
503                    self.limiter.lock().unwrap().on_success();
504                    return Ok(response.body);
505                }
506                401 | 403 if !auth_refreshed => {
507                    self.auth.invalidate_jwt();
508                    auth_refreshed = true;
509                }
510                401 | 403 => {
511                    return Err(Error::Auth(format!(
512                        "Suno API auth failed with status {}",
513                        response.status
514                    )));
515                }
516                429 => {
517                    self.limiter.lock().unwrap().on_rate_limit();
518                    return Err(Error::RateLimited {
519                        retry_after: retry_after(&response),
520                    });
521                }
522                400 => {
523                    let preview: String = String::from_utf8_lossy(&response.body)
524                        .chars()
525                        .take(200)
526                        .collect();
527                    return Err(Error::BadRequest(format!(
528                        "Suno API returned 400: {preview}"
529                    )));
530                }
531                404 => {
532                    return Err(Error::NotFound(format!("Suno API returned 404: {path}")));
533                }
534                status => {
535                    let preview: String = String::from_utf8_lossy(&response.body)
536                        .chars()
537                        .take(200)
538                        .collect();
539                    return Err(Error::Api(format!("Suno API returned {status}: {preview}")));
540                }
541            }
542        }
543    }
544}
545
546/// Whether a Suno API path may be the target of a POST (the crate-wide POST
547/// allow-list), deliberately narrow so a mutating request only ever reaches a
548/// vetted endpoint: the library feed ([`FEED_V3_PATH`]) and the per-clip WAV
549/// render (`…/convert_wav/`). Any credit-spending endpoint is deliberately
550/// absent; GETs are never gated.
551fn post_path_allowed(path: &str) -> bool {
552    if path == FEED_V3_PATH {
553        return true;
554    }
555    if let Some(rest) = path.strip_prefix("/api/gen/")
556        && let Some(id) = rest.strip_suffix("/convert_wav/")
557    {
558        return is_single_id_segment(id);
559    }
560    false
561}
562
563/// Whether `segment` is a single, non-empty path id segment: no slash, no query,
564/// and no `..` traversal, so an allow-list match can never be smuggled past by a
565/// crafted path.
566fn is_single_id_segment(segment: &str) -> bool {
567    !segment.is_empty()
568        && !segment.contains('/')
569        && !segment.contains('?')
570        && !segment.contains("..")
571}
572
573/// Whether an error is Suno's "no stems" answer (a `400`) on the page-count
574/// endpoint, distinguished from a transient `5xx` so a server error is never
575/// mistaken for "no stems".
576fn is_invalid_page_error(err: &Error) -> bool {
577    matches!(err, Error::BadRequest(_))
578}
579
580/// Drop stems that repeat across pages, keeping the first occurrence of each
581/// download URL so a paged listing counts a stem once.
582fn dedupe_stems(stems: &mut Vec<Stem>) {
583    let mut seen = BTreeSet::new();
584    stems.retain(|stem| seen.insert(stem.url.clone()));
585}
586
587/// Deduplicate ids in first-seen order, dropping empties. Shared by the by-id
588/// fetch paths so the batch, the fallback, and the returned order all agree.
589fn dedup_nonempty<'a>(ids: &[&'a str]) -> Vec<&'a str> {
590    let mut seen: BTreeSet<&str> = BTreeSet::new();
591    ids.iter()
592        .copied()
593        .filter(|id| !id.is_empty() && seen.insert(id))
594        .collect()
595}
596
597#[cfg(test)]
598mod tests;