Skip to main content

canton_token/
scan.rs

1//! Splice Scan's HTTP API, asked directly or through a validator's scan-proxy.
2//!
3//! Scan is the service each Super Validator runs to publish what the DSO
4//! decided and what happened on the network: the DSO party, the Amulet rules,
5//! the mining rounds, traffic balances, the update history, snapshots of the
6//! active contracts. The paths and payloads here come from Splice's OpenAPI
7//! documents, `scan.yaml` and `scan-proxy.yaml` (vendored under
8//! `testdata/openapi/`), and the methods are named after what they return.
9//!
10//! # Two ways in
11//!
12//! - [`ScanClient::new`] asks a Scan itself, at `<scan>/api/scan`. It serves
13//!   everything here.
14//! - [`ScanClient::through_validator`] asks a validator's scan-proxy, at
15//!   `<validator>/api/validator`. The validator reads from several Super
16//!   Validators' Scans and answers when enough of them agree, and it
17//!   authenticates every request, so this route needs a token
18//!   ([`with_token`](ScanClient::with_token),
19//!   [`with_token_source`](ScanClient::with_token_source)). It serves the
20//!   part of the API a wallet or an application backend needs, not the
21//!   traffic, history and snapshot-page reads, which are refused before
22//!   anything is sent; of the snapshot reads it serves only
23//!   [`holdings_summary`](ScanClient::holdings_summary).
24//!
25//! A Scan asked directly is one Super Validator's word. This client does not
26//! compare several Scans; the scan-proxy is the route that does.
27//!
28//! # Why an application needs it
29//!
30//! Some choices take contracts the DSO owns: the `AmuletRules`, the open
31//! mining round, a provider's `FeaturedAppRight`. Creating a
32//! `TransferPreapproval` is one such choice. The submitting party does not
33//! see those contracts, so they are passed as disclosed contracts, and Scan
34//! is where they are published. [`ScanClient::amulet_rules`] and
35//! [`ScanClient::latest_open_mining_round`] return them with
36//! [`disclosed`](ContractWithState::disclosed), which is what a submission
37//! attaches. [`ScanClient::featured_app_right`] returns its contract without
38//! a synchronizer: disclose it on the rules' one, with
39//! [`ScanContract::disclosed`].
40//!
41//! # Splice versions
42//!
43//! Written against the documents of Splice 0.10.3. On an older Scan or
44//! validator: [`dso`](ScanClient::dso) falls back to the `/v0/dso` every
45//! release serves; the two snapshot page reads
46//! ([`acs_snapshot`](ScanClient::acs_snapshot),
47//! [`holdings_state`](ScanClient::holdings_state)) need Splice 0.7.5, which
48//! is where their `/v2` paths appeared;
49//! [`holdings_summary`](ScanClient::holdings_summary) needs 0.6.3. Everything
50//! else is served by Splice 0.6.0 and later.
51//!
52//! # Stability
53//!
54//! Splice tags each Scan endpoint `external` or `internal`. The external ones
55//! are its public API. The internal ones may change in any Splice release,
56//! and two of them are the only source of a contract an application may
57//! need: [`featured_app_right`](ScanClient::featured_app_right) and
58//! [`transfer_preapproval_by_party`](ScanClient::transfer_preapproval_by_party).
59//! Asked of a Scan directly, these are refused unless the client was built
60//! with [`with_internal_endpoints`](ScanClient::with_internal_endpoints),
61//! which is the caller accepting that. Through a validator's scan-proxy they
62//! are part of the proxy's own API and need no opt-in.
63//!
64//! [`amulet_rules`](ScanClient::amulet_rules) needs no opt-in either way:
65//! the external API publishes the rules with the rest of the DSO's contracts,
66//! and that is where a Scan is asked for them. With the opt-in it asks the
67//! internal endpoint, which returns the one contract and nothing else.
68//!
69//! Contract payloads, choice arguments and results stay JSON
70//! ([`serde_json::Value`]): they are Daml values of whatever template the
71//! contract has, in the compact encoding the Ledger JSON API uses.
72
73use std::collections::BTreeMap;
74use std::time::Duration;
75
76use base64::Engine as _;
77use canton_core::{Auth, Error, Result, TokenSource};
78use canton_daml::Timestamp;
79use canton_proto::com::daml::ledger::api::v2 as pb;
80use serde::{Deserialize, Serialize};
81use serde_json::Value;
82
83use crate::registry::{
84    ErrorResponse, MAX_RESPONSE_BYTES, check_segments, parse_base_url, read_body_from,
85    read_error_body, transport_error, truncate,
86};
87
88/// How Scan is named in an error.
89const SCAN: &str = "Scan";
90
91/// How long to wait on a Scan that accepts the connection and then says
92/// nothing. `reqwest`'s own default is unbounded.
93const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
94
95/// The most contracts a history or snapshot page may ask for.
96const MAX_PAGE_SIZE: u32 = 1000;
97
98/// Where the client's base URL points.
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100enum Route {
101    /// A Scan: `<scan>/api/scan`, paths `/<version>/…`.
102    Scan,
103    /// A validator: `<validator>/api/validator`, paths
104    /// `/<version>/scan-proxy/…`.
105    ScanProxy,
106}
107
108/// A client for one Scan, or for one validator's scan-proxy.
109#[derive(Clone, Debug)]
110pub struct ScanClient {
111    base: reqwest::Url,
112    http: reqwest::Client,
113    auth: Auth,
114    route: Route,
115    internal_endpoints: bool,
116}
117
118/// A contract as Scan publishes it.
119#[derive(Clone, Debug, Deserialize)]
120#[non_exhaustive]
121pub struct ScanContract {
122    /// `<package id>:<Module>:<Entity>`.
123    pub template_id: String,
124    /// The contract id.
125    pub contract_id: String,
126    /// The contract's arguments, as Daml JSON.
127    pub payload: Value,
128    /// The created-event blob, base64 as JSON requires. This is what a
129    /// participant needs to accept the contract as disclosed.
130    pub created_event_blob: String,
131    /// When the contract was created.
132    pub created_at: String,
133}
134
135/// A contract and the synchronizer it is assigned to.
136#[derive(Clone, Debug, Deserialize)]
137#[non_exhaustive]
138pub struct ContractWithState {
139    /// The contract.
140    pub contract: ScanContract,
141    /// The synchronizer the contract is assigned to. `None` while it is
142    /// being reassigned from one synchronizer to another.
143    #[serde(rename = "domain_id", default)]
144    pub synchronizer_id: Option<String>,
145}
146
147impl ScanContract {
148    /// The contract as a disclosed contract for a gRPC submission, on
149    /// `synchronizer_id`.
150    ///
151    /// # Errors
152    /// [`Error::UnexpectedResponse`] if the template id is not
153    /// `<package>:<Module>:<Entity>` or the blob is not base64.
154    pub fn disclosed(&self, synchronizer_id: &str) -> Result<pb::DisclosedContract> {
155        let created_event_blob = base64::engine::general_purpose::STANDARD
156            .decode(&self.created_event_blob)
157            .map_err(|e| {
158                Error::UnexpectedResponse(format!(
159                    "Scan published contract `{}` with a created-event blob that is not \
160                     base64: {e}",
161                    self.contract_id
162                ))
163            })?;
164        Ok(pb::DisclosedContract {
165            template_id: Some(identifier(&self.template_id)?),
166            contract_id: self.contract_id.clone(),
167            created_event_blob,
168            synchronizer_id: synchronizer_id.to_string(),
169        })
170    }
171
172    /// The contract as a disclosed contract for the JSON Ledger API, which
173    /// takes the blob as the base64 Scan already sent.
174    #[must_use]
175    pub fn disclosed_json(&self, synchronizer_id: &str) -> Value {
176        serde_json::json!({
177            "templateId": self.template_id,
178            "contractId": self.contract_id,
179            "createdEventBlob": self.created_event_blob,
180            "synchronizerId": synchronizer_id,
181        })
182    }
183}
184
185impl ContractWithState {
186    /// The contract as a disclosed contract for a gRPC submission, on the
187    /// synchronizer it is assigned to.
188    ///
189    /// # Errors
190    /// As [`ScanContract::disclosed`], plus [`Error::Connection`], which is
191    /// retriable, if the contract is between synchronizers and so has none to
192    /// be disclosed on. That passes in seconds.
193    pub fn disclosed(&self) -> Result<pb::DisclosedContract> {
194        self.contract.disclosed(self.assigned()?)
195    }
196
197    /// The contract as a disclosed contract for the JSON Ledger API.
198    ///
199    /// # Errors
200    /// [`Error::Connection`] if the contract is between synchronizers.
201    pub fn disclosed_json(&self) -> Result<Value> {
202        Ok(self.contract.disclosed_json(self.assigned()?))
203    }
204
205    fn assigned(&self) -> Result<&str> {
206        self.synchronizer_id.as_deref().ok_or_else(|| {
207            Error::Connection(format!(
208                "contract `{}` is being reassigned between synchronizers, so there is none to \
209                 disclose it on yet; retry shortly",
210                self.contract.contract_id
211            ))
212        })
213    }
214}
215
216/// `<package>:<Module>:<Entity>` as the Ledger API's three fields. A module
217/// name has dots and never colons, so exactly three parts is the only
218/// well-formed shape.
219fn identifier(template_id: &str) -> Result<pb::Identifier> {
220    let mut parts = template_id.split(':');
221    match (parts.next(), parts.next(), parts.next(), parts.next()) {
222        (Some(package_id), Some(module_name), Some(entity_name), None)
223            if !package_id.is_empty() && !module_name.is_empty() && !entity_name.is_empty() =>
224        {
225            Ok(pb::Identifier {
226                package_id: package_id.to_string(),
227                module_name: module_name.to_string(),
228                entity_name: entity_name.to_string(),
229            })
230        }
231        _ => Err(Error::UnexpectedResponse(format!(
232            "Scan published a contract with template id `{template_id}`, which is not \
233             `<package>:<Module>:<Entity>`"
234        ))),
235    }
236}
237
238/// What the DSO is and the contracts that say how it runs.
239#[derive(Clone, Debug, Deserialize)]
240#[non_exhaustive]
241pub struct DsoInfo {
242    /// The party that represents the DSO as a whole.
243    pub dso_party_id: String,
244    /// How many Super Validators must agree for a vote to pass.
245    pub voting_threshold: u32,
246    /// The `OpenMiningRound` with the highest round number. It may not have
247    /// opened yet: see [`MiningRounds::latest_open`] for the one to use.
248    pub latest_mining_round: ContractWithState,
249    /// The `AmuletRules` contract.
250    pub amulet_rules: ContractWithState,
251    /// The `DsoRules` contract.
252    pub dso_rules: ContractWithState,
253    /// One `SvNodeState` contract per Super Validator in the DSO rules.
254    pub sv_node_states: Vec<ContractWithState>,
255    /// The round the network started from, where Scan reports it.
256    #[serde(default)]
257    pub initial_round: Option<String>,
258}
259
260/// The Scans the Super Validators run for one synchronizer.
261#[derive(Clone, Debug, Deserialize)]
262#[non_exhaustive]
263pub struct SynchronizerScans {
264    /// The synchronizer.
265    #[serde(rename = "domainId")]
266    pub synchronizer_id: String,
267    /// Its Scans.
268    pub scans: Vec<ScanInfo>,
269}
270
271/// One Super Validator's Scan.
272#[derive(Clone, Debug, Deserialize)]
273#[serde(rename_all = "camelCase")]
274#[non_exhaustive]
275pub struct ScanInfo {
276    /// The Scan's public URL, without `/api/scan`.
277    pub public_url: String,
278    /// The Super Validator that runs it.
279    pub sv_name: String,
280}
281
282/// The mining rounds that rewards can be registered in, and the ones whose
283/// rewards are being computed.
284#[derive(Clone, Debug)]
285#[non_exhaustive]
286pub struct MiningRounds {
287    /// `OpenMiningRound` contracts. Several are open at once, and the newest
288    /// may not have reached its opening time.
289    pub open: Vec<ContractWithState>,
290    /// `IssuingMiningRound` contracts.
291    pub issuing: Vec<ContractWithState>,
292}
293
294/// The two fields of an `OpenMiningRound` that decide whether it is the one
295/// to use.
296#[derive(Deserialize)]
297struct OpenRound {
298    round: Round,
299    #[serde(rename = "opensAt")]
300    opens_at: Timestamp,
301}
302
303#[derive(Deserialize)]
304struct Round {
305    #[serde(deserialize_with = "int64")]
306    number: i64,
307}
308
309/// A Daml `Int` in JSON: a string, since a JSON number cannot hold every
310/// `i64`, though a number is accepted too.
311fn int64<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<i64, D::Error> {
312    #[derive(Deserialize)]
313    #[serde(untagged)]
314    enum Int {
315        Text(String),
316        Number(i64),
317    }
318    match Int::deserialize(deserializer)? {
319        Int::Text(text) => text.parse().map_err(serde::de::Error::custom),
320        Int::Number(number) => Ok(number),
321    }
322}
323
324impl MiningRounds {
325    /// The open round to pass to a choice at `now`: of the rounds whose
326    /// opening time has come, the one with the highest number.
327    ///
328    /// This is the round Splice's own applications pick
329    /// (`selectLatestOpenMiningRound`). The round with the lowest number is
330    /// open too, but it is the next to be archived, and a transaction built
331    /// on it fails if the archival lands first.
332    ///
333    /// # Errors
334    /// [`Error::UnexpectedResponse`] if a round's payload has no `round` or
335    /// `opensAt`, and [`Error::Connection`], which is retriable, if no round
336    /// has opened yet.
337    pub fn latest_open(&self, now: Timestamp) -> Result<&ContractWithState> {
338        let mut latest: Option<(i64, &ContractWithState)> = None;
339        for round in &self.open {
340            let fields: OpenRound = serde_json::from_value(round.contract.payload.clone())
341                .map_err(|e| {
342                    Error::UnexpectedResponse(format!(
343                        "Scan published open mining round `{}` with a payload that is not an \
344                         OpenMiningRound: {e}",
345                        round.contract.contract_id
346                    ))
347                })?;
348            if fields.opens_at > now {
349                continue;
350            }
351            if latest.is_none_or(|(number, _)| fields.round.number > number) {
352                latest = Some((fields.round.number, round));
353            }
354        }
355        latest.map(|(_, round)| round).ok_or_else(|| {
356            Error::Connection(format!(
357                "none of the {} open mining rounds Scan published has reached its opening time; \
358                 retry shortly",
359                self.open.len()
360            ))
361        })
362    }
363}
364
365/// How much traffic a member has bought and used on a synchronizer.
366#[derive(Clone, Copy, Debug, PartialEq, Eq)]
367#[non_exhaustive]
368pub struct TrafficStatus {
369    /// Bytes of extra traffic the member has consumed, as the sequencers
370    /// account it.
371    pub total_consumed: i64,
372    /// Bytes of extra traffic the member may consume in total, as the
373    /// sequencers account it.
374    pub total_limit: i64,
375    /// Bytes of extra traffic the member has purchased, as the DSO records
376    /// it. The limit catches up with this once the purchase is processed.
377    pub total_purchased: i64,
378}
379
380/// An entry in the Amulet Name Service.
381#[derive(Clone, Debug, Deserialize)]
382#[non_exhaustive]
383pub struct AnsEntry {
384    /// The entry's contract, where it has one. Entries the DSO defines for
385    /// itself and the Super Validators have none.
386    #[serde(default)]
387    pub contract_id: Option<String>,
388    /// The party the name belongs to.
389    pub user: String,
390    /// The name.
391    pub name: String,
392    /// The URL the owner gave.
393    pub url: String,
394    /// The description the owner gave.
395    pub description: String,
396    /// When the entry expires, where it does.
397    #[serde(default)]
398    pub expires_at: Option<String>,
399}
400
401/// A point in Scan's history: everything up to and including it has been
402/// read. Pass it back to read on from there.
403#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
404pub struct HistoryPosition {
405    /// The migration the record time belongs to. Record times start over
406    /// after a hard synchronizer migration, so one alone does not order
407    /// history.
408    #[serde(rename = "after_migration_id")]
409    pub migration_id: i64,
410    /// The record time.
411    #[serde(rename = "after_record_time")]
412    pub record_time: String,
413}
414
415/// One entry of the update history.
416#[derive(Clone, Debug)]
417#[non_exhaustive]
418pub enum ScanUpdate {
419    /// A transaction.
420    Transaction(ScanTransaction),
421    /// A contract leaving one synchronizer or arriving on another.
422    Reassignment(ScanReassignment),
423}
424
425impl ScanUpdate {
426    /// Where this update is in history, to read on from.
427    #[must_use]
428    pub fn position(&self) -> HistoryPosition {
429        match self {
430            Self::Transaction(transaction) => HistoryPosition {
431                migration_id: transaction.migration_id,
432                record_time: transaction.record_time.clone(),
433            },
434            Self::Reassignment(reassignment) => HistoryPosition {
435                migration_id: match &reassignment.event {
436                    ReassignmentEvent::Assignment(assignment) => assignment.migration_id,
437                    ReassignmentEvent::Unassignment(unassignment) => unassignment.migration_id,
438                },
439                record_time: reassignment.record_time.clone(),
440            },
441        }
442    }
443
444    /// The update id.
445    #[must_use]
446    pub fn update_id(&self) -> &str {
447        match self {
448            Self::Transaction(transaction) => &transaction.update_id,
449            Self::Reassignment(reassignment) => &reassignment.update_id,
450        }
451    }
452}
453
454/// The API gives the two kinds of update no tag to tell them by: a
455/// transaction is the one with events, a reassignment the one with an event.
456impl<'de> Deserialize<'de> for ScanUpdate {
457    fn deserialize<D: serde::Deserializer<'de>>(
458        deserializer: D,
459    ) -> std::result::Result<Self, D::Error> {
460        use serde::de::Error as _;
461        let value = Value::deserialize(deserializer)?;
462        if value.get("events_by_id").is_some() {
463            serde_json::from_value(value)
464                .map(Self::Transaction)
465                .map_err(D::Error::custom)
466        } else if value.get("event").is_some() {
467            serde_json::from_value(value)
468                .map(Self::Reassignment)
469                .map_err(D::Error::custom)
470        } else {
471            Err(D::Error::custom(
472                "an update with neither `events_by_id` (a transaction) nor `event` (a \
473                 reassignment)",
474            ))
475        }
476    }
477}
478
479/// A transaction in the update history.
480#[derive(Clone, Debug, Deserialize)]
481#[non_exhaustive]
482pub struct ScanTransaction {
483    /// The update id.
484    pub update_id: String,
485    /// The migration the transaction was recorded in.
486    pub migration_id: i64,
487    /// The workflow id the submitter gave, empty when it gave none.
488    pub workflow_id: String,
489    /// When the sequencer recorded it.
490    pub record_time: String,
491    /// The synchronizer it was sequenced on.
492    pub synchronizer_id: String,
493    /// The ledger effective time.
494    pub effective_at: String,
495    /// The ids of the root events, in execution order.
496    pub root_event_ids: Vec<String>,
497    /// Every event of the transaction by its id.
498    pub events_by_id: BTreeMap<String, ScanEvent>,
499    /// The hash an external party signed, for an externally signed
500    /// transaction.
501    #[serde(default)]
502    pub external_transaction_hash: Option<String>,
503}
504
505/// An event of a transaction.
506#[derive(Clone, Debug, Deserialize)]
507#[serde(tag = "event_type")]
508#[non_exhaustive]
509pub enum ScanEvent {
510    /// A contract was created.
511    #[serde(rename = "created_event")]
512    Created(ScanCreatedEvent),
513    /// A choice was exercised.
514    #[serde(rename = "exercised_event")]
515    Exercised(ScanExercisedEvent),
516}
517
518/// A contract's creation.
519#[derive(Clone, Debug, Deserialize)]
520#[non_exhaustive]
521pub struct ScanCreatedEvent {
522    /// The event id.
523    pub event_id: String,
524    /// The contract id.
525    pub contract_id: String,
526    /// `<package id>:<Module>:<Entity>`.
527    pub template_id: String,
528    /// The name of the package the template is in.
529    pub package_name: String,
530    /// The contract's arguments, as Daml JSON.
531    pub create_arguments: Value,
532    /// When the contract was created.
533    pub created_at: String,
534    /// The contract's signatories.
535    pub signatories: Vec<String>,
536    /// The contract's observers.
537    pub observers: Vec<String>,
538}
539
540/// A choice exercised on a contract.
541#[derive(Clone, Debug, Deserialize)]
542#[non_exhaustive]
543pub struct ScanExercisedEvent {
544    /// The event id.
545    pub event_id: String,
546    /// The contract the choice was exercised on.
547    pub contract_id: String,
548    /// `<package id>:<Module>:<Entity>`.
549    pub template_id: String,
550    /// The name of the package the template is in.
551    pub package_name: String,
552    /// The choice.
553    pub choice: String,
554    /// The choice's argument, as Daml JSON.
555    pub choice_argument: Value,
556    /// The ids of the events the choice caused, in execution order.
557    pub child_event_ids: Vec<String>,
558    /// What the choice returned, as Daml JSON.
559    pub exercise_result: Value,
560    /// Whether the choice archived the contract.
561    pub consuming: bool,
562    /// The parties that exercised it.
563    pub acting_parties: Vec<String>,
564    /// The interface the choice was exercised through, where it was.
565    #[serde(default)]
566    pub interface_id: Option<String>,
567}
568
569/// A contract leaving one synchronizer or arriving on another.
570#[derive(Clone, Debug, Deserialize)]
571#[non_exhaustive]
572pub struct ScanReassignment {
573    /// The update id.
574    pub update_id: String,
575    /// The offset on the Scan's own participant. It means nothing to another
576    /// participant.
577    pub offset: String,
578    /// When the sequencer recorded it.
579    pub record_time: String,
580    /// Which half of the reassignment this is.
581    pub event: ReassignmentEvent,
582}
583
584/// The two halves of a reassignment.
585#[derive(Clone, Debug)]
586#[non_exhaustive]
587pub enum ReassignmentEvent {
588    /// The contract arrived on the target synchronizer.
589    Assignment(ScanAssignment),
590    /// The contract left the source synchronizer.
591    Unassignment(ScanUnassignment),
592}
593
594/// As [`ScanUpdate`]: untagged in the API, and told apart by the one field
595/// each has that the other does not.
596impl<'de> Deserialize<'de> for ReassignmentEvent {
597    fn deserialize<D: serde::Deserializer<'de>>(
598        deserializer: D,
599    ) -> std::result::Result<Self, D::Error> {
600        use serde::de::Error as _;
601        let value = Value::deserialize(deserializer)?;
602        if value.get("created_event").is_some() {
603            serde_json::from_value(value)
604                .map(Self::Assignment)
605                .map_err(D::Error::custom)
606        } else if value.get("contract_id").is_some() {
607            serde_json::from_value(value)
608                .map(Self::Unassignment)
609                .map_err(D::Error::custom)
610        } else {
611            Err(D::Error::custom(
612                "a reassignment event with neither `created_event` (an assignment) nor \
613                 `contract_id` (an unassignment)",
614            ))
615        }
616    }
617}
618
619/// A contract arriving on a synchronizer.
620#[derive(Clone, Debug, Deserialize)]
621#[non_exhaustive]
622pub struct ScanAssignment {
623    /// The party that submitted the reassignment.
624    pub submitter: String,
625    /// The synchronizer the contract left.
626    pub source_synchronizer: String,
627    /// The synchronizer it arrived on.
628    pub target_synchronizer: String,
629    /// The migration it was recorded in.
630    pub migration_id: i64,
631    /// The id that ties this half to the unassignment.
632    pub unassign_id: String,
633    /// The contract, as created on the target synchronizer.
634    pub created_event: ScanCreatedEvent,
635    /// How many times the contract has been reassigned.
636    pub reassignment_counter: i64,
637}
638
639/// A contract leaving a synchronizer.
640#[derive(Clone, Debug, Deserialize)]
641#[non_exhaustive]
642pub struct ScanUnassignment {
643    /// The party that submitted the reassignment.
644    pub submitter: String,
645    /// The synchronizer the contract left.
646    pub source_synchronizer: String,
647    /// The migration it was recorded in.
648    pub migration_id: i64,
649    /// The synchronizer it is going to.
650    pub target_synchronizer: String,
651    /// The id that ties this half to the assignment.
652    pub unassign_id: String,
653    /// How many times the contract has been reassigned.
654    pub reassignment_counter: i64,
655    /// The contract.
656    pub contract_id: String,
657}
658
659/// One entry of the event history: an update, the mediator's verdict on it,
660/// or both.
661#[derive(Clone, Debug, Deserialize)]
662#[non_exhaustive]
663pub struct ScanEventItem {
664    /// The update, where Scan's participant saw it. A transaction the
665    /// mediator rejected has a verdict and no update.
666    #[serde(default)]
667    pub update: Option<ScanUpdate>,
668    /// The mediator's verdict, as Scan publishes it.
669    #[serde(default)]
670    pub verdict: Option<Value>,
671    /// The traffic the update cost, where Scan reports it.
672    #[serde(default)]
673    pub traffic_summary: Option<Value>,
674    /// The application activity records the update produced, where Scan
675    /// reports them.
676    #[serde(default)]
677    pub app_activity_records: Option<Value>,
678    /// The asset activity records the update produced, where Scan reports
679    /// them.
680    #[serde(default)]
681    pub asset_activity_records: Option<Value>,
682    /// The application provider the submission was made through, where Scan
683    /// reports one.
684    #[serde(default)]
685    pub submitting_app_provider: Option<String>,
686}
687
688impl ScanEventItem {
689    /// Where this entry is in history, to read on from: the update's
690    /// position, or the verdict's where there is no update, as for a
691    /// transaction the mediator rejected. `None` only for an entry with
692    /// neither, or a verdict without its migration and record time.
693    #[must_use]
694    pub fn position(&self) -> Option<HistoryPosition> {
695        if let Some(update) = &self.update {
696            return Some(update.position());
697        }
698        let verdict = self.verdict.as_ref()?;
699        Some(HistoryPosition {
700            migration_id: verdict.get("migration_id")?.as_i64()?,
701            record_time: verdict.get("record_time")?.as_str()?.to_string(),
702        })
703    }
704}
705
706/// Which snapshot of the active contracts to read, and which part of it.
707///
708/// Scan takes a snapshot every few hours.
709/// [`ScanClient::acs_snapshot_timestamp`] gives the record time of the one
710/// before a moment; [`at_or_before`](Self::at_or_before) lets Scan find it
711/// instead.
712#[derive(Clone, Debug)]
713pub struct SnapshotRequest {
714    migration_id: i64,
715    record_time: String,
716    at_or_before: bool,
717    after: Option<String>,
718    page_size: u32,
719    parties: Vec<String>,
720    templates: Vec<String>,
721}
722
723impl SnapshotRequest {
724    /// The snapshot taken at exactly `record_time` in `migration_id`.
725    pub fn at(migration_id: i64, record_time: impl Into<String>) -> Self {
726        Self {
727            migration_id,
728            record_time: record_time.into(),
729            at_or_before: false,
730            after: None,
731            page_size: 100,
732            parties: Vec::new(),
733            templates: Vec::new(),
734        }
735    }
736
737    /// Take the most recent snapshot at or before the record time, where the
738    /// default is to require one at exactly that time.
739    #[must_use]
740    pub fn at_or_before(mut self) -> Self {
741        self.at_or_before = true;
742        self
743    }
744
745    /// How many contracts a page holds. Defaults to 100; Scan allows 1000.
746    #[must_use]
747    pub fn with_page_size(mut self, page_size: u32) -> Self {
748        self.page_size = page_size;
749        self
750    }
751
752    /// Read the page after the one that returned this token.
753    #[must_use]
754    pub fn after(mut self, next_page_token: impl Into<String>) -> Self {
755        self.after = Some(next_page_token.into());
756        self
757    }
758
759    /// Only contracts these parties are stakeholders of. For the holdings
760    /// reads these are the owners, and at least one is required.
761    #[must_use]
762    pub fn for_parties<I, S>(mut self, parties: I) -> Self
763    where
764        I: IntoIterator<Item = S>,
765        S: Into<String>,
766    {
767        self.parties = parties.into_iter().map(Into::into).collect();
768        self
769    }
770
771    /// Only contracts of these templates, each as
772    /// `<package name>:<Module>:<Entity>`. Ignored by the holdings reads.
773    #[must_use]
774    pub fn for_templates<I, S>(mut self, templates: I) -> Self
775    where
776        I: IntoIterator<Item = S>,
777        S: Into<String>,
778    {
779        self.templates = templates.into_iter().map(Into::into).collect();
780        self
781    }
782
783    fn record_time_match(&self) -> &'static str {
784        if self.at_or_before {
785            "at_or_before"
786        } else {
787            "exact"
788        }
789    }
790
791    fn owners(&self, read: &str) -> Result<&[String]> {
792        if self.parties.is_empty() {
793            return Err(Error::InvalidRequest(format!(
794                "{read} needs at least one owner party (SnapshotRequest::for_parties)"
795            )));
796        }
797        Ok(&self.parties)
798    }
799}
800
801/// A page of a snapshot of the active contracts.
802#[derive(Clone, Debug, Deserialize)]
803#[non_exhaustive]
804pub struct AcsSnapshot {
805    /// The record time of the snapshot that was read.
806    pub record_time: String,
807    /// The migration it belongs to.
808    pub migration_id: i64,
809    /// The contracts on this page.
810    pub created_events: Vec<ActiveContract>,
811    /// The token for the next page, absent on the last one.
812    #[serde(default)]
813    pub next_page_token: Option<String>,
814}
815
816/// A contract in a snapshot.
817#[derive(Clone, Debug, Deserialize)]
818#[non_exhaustive]
819pub struct ActiveContract {
820    /// The update that created it, where Scan reports it.
821    #[serde(default)]
822    pub created_in_update_id: Option<String>,
823    /// The contract id.
824    pub contract_id: String,
825    /// `<package id>:<Module>:<Entity>`.
826    pub template_id: String,
827    /// The name of the package the template is in.
828    pub package_name: String,
829    /// The contract's arguments, as Daml JSON.
830    pub create_arguments: Value,
831    /// When the contract was created.
832    pub created_at: String,
833    /// The contract's signatories.
834    pub signatories: Vec<String>,
835    /// The contract's observers.
836    pub observers: Vec<String>,
837}
838
839/// What some parties held at a snapshot.
840#[derive(Clone, Debug, Deserialize)]
841#[non_exhaustive]
842pub struct HoldingsSummaries {
843    /// The record time of the snapshot that was read.
844    pub record_time: String,
845    /// The migration it belongs to.
846    pub migration_id: i64,
847    /// One summary per owner that held anything.
848    pub summaries: Vec<HoldingsSummary>,
849}
850
851/// What one party held at a snapshot. Amounts are decimal strings, as Daml
852/// JSON writes a `Decimal`.
853#[derive(Clone, Debug, Deserialize)]
854#[non_exhaustive]
855pub struct HoldingsSummary {
856    /// The owner.
857    pub party_id: String,
858    /// The Amulet the party could spend.
859    pub total_unlocked_coin: String,
860    /// The Amulet locked in its name.
861    pub total_locked_coin: String,
862    /// Both together.
863    pub total_coin_holdings: String,
864}
865
866impl ScanClient {
867    /// A client for the Scan served at `base_url`, which ends in `/api/scan`.
868    ///
869    /// # Errors
870    /// [`Error::InvalidRequest`] if `base_url` is not a URL, or an HTTP client
871    /// cannot be built.
872    pub fn new(base_url: &str) -> Result<Self> {
873        Self::with_http_client(base_url, default_http_client()?)
874    }
875
876    /// [`new`](Self::new) with an HTTP client the caller has configured:
877    /// timeouts, proxies, a custom TLS root store. Configure it with
878    /// `reqwest::redirect::Policy::none()`, as [`new`](Self::new) does: what
879    /// Scan answers goes into commands the caller signs, so it must come from
880    /// the Scan the caller named and not from wherever a 3xx points.
881    ///
882    /// # Errors
883    /// [`Error::InvalidRequest`] if `base_url` is not a URL.
884    pub fn with_http_client(base_url: &str, http: reqwest::Client) -> Result<Self> {
885        Self::build(base_url, http, Route::Scan)
886    }
887
888    /// A client for the scan-proxy of the validator served at `base_url`,
889    /// which ends in `/api/validator`.
890    ///
891    /// The proxy authenticates every request: give the client a token with
892    /// [`with_token`](Self::with_token) or
893    /// [`with_token_source`](Self::with_token_source).
894    ///
895    /// # Errors
896    /// [`Error::InvalidRequest`] if `base_url` is not a URL, or an HTTP client
897    /// cannot be built.
898    pub fn through_validator(base_url: &str) -> Result<Self> {
899        Self::through_validator_with_http_client(base_url, default_http_client()?)
900    }
901
902    /// [`through_validator`](Self::through_validator) with an HTTP client the
903    /// caller has configured. See [`with_http_client`](Self::with_http_client).
904    ///
905    /// # Errors
906    /// [`Error::InvalidRequest`] if `base_url` is not a URL.
907    pub fn through_validator_with_http_client(
908        base_url: &str,
909        http: reqwest::Client,
910    ) -> Result<Self> {
911        Self::build(base_url, http, Route::ScanProxy)
912    }
913
914    fn build(base_url: &str, http: reqwest::Client, route: Route) -> Result<Self> {
915        let base = parse_base_url(base_url, "Scan")?;
916        Ok(Self {
917            base,
918            http,
919            auth: Auth::None,
920            route,
921            internal_endpoints: false,
922        })
923    }
924
925    /// Send a bearer token with every request. A validator's scan-proxy
926    /// requires one; a Scan does not.
927    #[must_use]
928    pub fn with_token(mut self, token: impl Into<String>) -> Self {
929        self.auth = Auth::Static(token.into());
930        self
931    }
932
933    /// Send a bearer token from a source that refreshes it, such as
934    /// `canton_auth::TokenProvider`.
935    #[must_use]
936    pub fn with_token_source(mut self, source: impl TokenSource + 'static) -> Self {
937        self.auth = Auth::Dynamic(std::sync::Arc::new(source));
938        self
939    }
940
941    /// Allow the calls that reach endpoints Splice tags `internal` when the
942    /// client asks a Scan directly:
943    /// [`featured_app_right`](Self::featured_app_right) and
944    /// [`transfer_preapproval_by_party`](Self::transfer_preapproval_by_party),
945    /// and the lighter of the two ways to read
946    /// [`amulet_rules`](Self::amulet_rules).
947    ///
948    /// Splice may change an internal endpoint in any release, and these
949    /// methods change with it. Through a validator's scan-proxy the same
950    /// calls are part of the proxy's API, and this is not needed.
951    #[must_use]
952    pub fn with_internal_endpoints(mut self) -> Self {
953        self.internal_endpoints = true;
954        self
955    }
956
957    /// Build a URL from an API version and path segments, under the
958    /// scan-proxy prefix where the client goes through a validator. Every
959    /// segment is percent-encoded, so a party or a name cannot change which
960    /// resource is addressed, and a segment that is empty, `.` or `..` is
961    /// refused: URL parsing resolves those away, so `featured_app_right("..")`
962    /// asked for the list of every right and read it as "not featured".
963    fn url(&self, version: &str, segments: &[&str]) -> Result<reqwest::Url> {
964        check_segments(&[version])?;
965        check_segments(segments)?;
966        let mut url = self.base.clone();
967        {
968            let mut path = url.path_segments_mut().map_err(|()| {
969                Error::InvalidRequest("the Scan URL cannot have a path".to_string())
970            })?;
971            path.pop_if_empty().push(version);
972            if self.route == Route::ScanProxy {
973                path.push("scan-proxy");
974            }
975            path.extend(segments);
976        }
977        Ok(url)
978    }
979
980    /// Refuse a read the validator's scan-proxy does not serve.
981    fn scan_only(&self, read: &str) -> Result<()> {
982        if self.route == Route::ScanProxy {
983            return Err(Error::InvalidRequest(format!(
984                "a validator's scan-proxy does not serve {read}; ask a Scan for it \
985                 (ScanClient::new)"
986            )));
987        }
988        Ok(())
989    }
990
991    /// Refuse an internal endpoint of a Scan the caller did not opt into.
992    fn internal(&self, read: &str) -> Result<()> {
993        if self.route == Route::Scan && !self.internal_endpoints {
994            return Err(Error::InvalidRequest(format!(
995                "{read} is an endpoint Scan tags internal, which Splice may change in any \
996                 release; opt in with ScanClient::with_internal_endpoints(), or go through a \
997                 validator's scan-proxy (ScanClient::through_validator), which serves it as \
998                 part of its API"
999            )));
1000        }
1001        Ok(())
1002    }
1003
1004    /// The party that represents the DSO.
1005    ///
1006    /// # Errors
1007    /// As any HTTP call, plus [`Error::UnexpectedResponse`] on a body that is
1008    /// not what Splice specifies.
1009    pub async fn dso_party_id(&self) -> Result<String> {
1010        #[derive(Deserialize)]
1011        struct Reply {
1012            dso_party_id: String,
1013        }
1014        let reply: Reply = self.get(self.url("v0", &["dso-party-id"])?).await?;
1015        Ok(reply.dso_party_id)
1016    }
1017
1018    /// The DSO: its party, its voting threshold, and the contracts that hold
1019    /// its rules.
1020    ///
1021    /// Asked at `/v1/dso`, which Splice 0.10 added. A Scan or a validator
1022    /// older than that answers `404` there and serves `/v0/dso`, which
1023    /// carries the same contracts, so that is asked next.
1024    ///
1025    /// # Errors
1026    /// As [`dso_party_id`](Self::dso_party_id).
1027    pub async fn dso(&self) -> Result<DsoInfo> {
1028        match self.get(self.url("v1", &["dso"])?).await {
1029            Err(Error::Http { status: 404, .. }) => self.get(self.url("v0", &["dso"])?).await,
1030            answer => answer,
1031        }
1032    }
1033
1034    /// Every Super Validator's Scan, per synchronizer.
1035    ///
1036    /// # Errors
1037    /// As [`dso_party_id`](Self::dso_party_id), and
1038    /// [`Error::InvalidRequest`] through a validator's scan-proxy, which does
1039    /// not serve it.
1040    pub async fn scans(&self) -> Result<Vec<SynchronizerScans>> {
1041        #[derive(Deserialize)]
1042        struct Reply {
1043            scans: Vec<SynchronizerScans>,
1044        }
1045        self.scan_only("the list of Scans")?;
1046        let reply: Reply = self.get(self.url("v0", &["scans"])?).await?;
1047        Ok(reply.scans)
1048    }
1049
1050    /// The open and the issuing mining rounds.
1051    ///
1052    /// # Errors
1053    /// As [`dso_party_id`](Self::dso_party_id).
1054    pub async fn open_and_issuing_mining_rounds(&self) -> Result<MiningRounds> {
1055        // A Scan answers with only the rounds the caller does not say it has
1056        // cached, keyed by contract id; the proxy answers with them all.
1057        #[derive(Serialize)]
1058        struct Cached {
1059            cached_open_mining_round_contract_ids: [String; 0],
1060            cached_issuing_round_contract_ids: [String; 0],
1061        }
1062        #[derive(Deserialize)]
1063        struct MaybeCached {
1064            #[serde(default)]
1065            contract: Option<ScanContract>,
1066            #[serde(default)]
1067            domain_id: Option<String>,
1068        }
1069        #[derive(Deserialize)]
1070        struct FromScan {
1071            open_mining_rounds: BTreeMap<String, MaybeCached>,
1072            issuing_mining_rounds: BTreeMap<String, MaybeCached>,
1073        }
1074        #[derive(Deserialize)]
1075        struct FromProxy {
1076            open_mining_rounds: Vec<ContractWithState>,
1077            issuing_mining_rounds: Vec<ContractWithState>,
1078        }
1079        fn all(rounds: BTreeMap<String, MaybeCached>) -> Result<Vec<ContractWithState>> {
1080            rounds
1081                .into_iter()
1082                .map(|(contract_id, round)| {
1083                    let contract = round.contract.ok_or_else(|| {
1084                        Error::UnexpectedResponse(format!(
1085                            "Scan left out mining round `{contract_id}` as cached, where this \
1086                             client told it nothing was"
1087                        ))
1088                    })?;
1089                    Ok(ContractWithState {
1090                        contract,
1091                        synchronizer_id: round.domain_id,
1092                    })
1093                })
1094                .collect()
1095        }
1096
1097        let url = self.url("v0", &["open-and-issuing-mining-rounds"])?;
1098        match self.route {
1099            Route::Scan => {
1100                let reply: FromScan = self
1101                    .post(
1102                        url,
1103                        &Cached {
1104                            cached_open_mining_round_contract_ids: [],
1105                            cached_issuing_round_contract_ids: [],
1106                        },
1107                    )
1108                    .await?;
1109                Ok(MiningRounds {
1110                    open: all(reply.open_mining_rounds)?,
1111                    issuing: all(reply.issuing_mining_rounds)?,
1112                })
1113            }
1114            Route::ScanProxy => {
1115                let reply: FromProxy = self.get(url).await?;
1116                Ok(MiningRounds {
1117                    open: reply.open_mining_rounds,
1118                    issuing: reply.issuing_mining_rounds,
1119                })
1120            }
1121        }
1122    }
1123
1124    /// The open mining round to pass to a choice now: see
1125    /// [`MiningRounds::latest_open`].
1126    ///
1127    /// # Errors
1128    /// As [`open_and_issuing_mining_rounds`](Self::open_and_issuing_mining_rounds)
1129    /// and [`MiningRounds::latest_open`].
1130    pub async fn latest_open_mining_round(&self) -> Result<ContractWithState> {
1131        let rounds = self.open_and_issuing_mining_rounds().await?;
1132        let now = std::time::SystemTime::now()
1133            .duration_since(std::time::UNIX_EPOCH)
1134            .ok()
1135            .and_then(|since| i64::try_from(since.as_micros()).ok())
1136            .ok_or_else(|| {
1137                Error::InvalidRequest("the system clock is not a time after 1970".to_string())
1138            })?;
1139        rounds.latest_open(Timestamp(now)).cloned()
1140    }
1141
1142    /// The closed mining rounds that have not been archived yet.
1143    ///
1144    /// # Errors
1145    /// As [`scans`](Self::scans).
1146    pub async fn closed_rounds(&self) -> Result<Vec<ScanContract>> {
1147        #[derive(Deserialize)]
1148        struct Reply {
1149            rounds: Vec<ScanContract>,
1150        }
1151        self.scan_only("the closed mining rounds")?;
1152        let reply: Reply = self.get(self.url("v0", &["closed-rounds"])?).await?;
1153        Ok(reply.rounds)
1154    }
1155
1156    /// The `AmuletRules` contract.
1157    ///
1158    /// A Scan publishes it twice: with the rest of the DSO's contracts in the
1159    /// external API ([`dso`](Self::dso)), and alone at an internal endpoint.
1160    /// The external one is asked, unless the client opted into the internal
1161    /// endpoints ([`with_internal_endpoints`](Self::with_internal_endpoints)),
1162    /// whose reply is the one contract. A validator's scan-proxy serves it as
1163    /// part of its own API.
1164    ///
1165    /// # Errors
1166    /// As [`dso_party_id`](Self::dso_party_id).
1167    pub async fn amulet_rules(&self) -> Result<ContractWithState> {
1168        #[derive(Deserialize)]
1169        struct MaybeCached {
1170            #[serde(default)]
1171            contract: Option<ScanContract>,
1172            #[serde(default)]
1173            domain_id: Option<String>,
1174        }
1175        #[derive(Deserialize)]
1176        struct FromScan {
1177            amulet_rules_update: MaybeCached,
1178        }
1179        #[derive(Deserialize)]
1180        struct FromProxy {
1181            amulet_rules: ContractWithState,
1182        }
1183        if self.route == Route::Scan && !self.internal_endpoints {
1184            return Ok(self.dso().await?.amulet_rules);
1185        }
1186        let url = self.url("v0", &["amulet-rules"])?;
1187        match self.route {
1188            Route::Scan => {
1189                // The body names the contract the caller has cached, so that
1190                // Scan can leave it out. None is named here.
1191                let reply: FromScan = self.post(url, &serde_json::json!({})).await?;
1192                let contract = reply.amulet_rules_update.contract.ok_or_else(|| {
1193                    Error::UnexpectedResponse(
1194                        "Scan left out the Amulet rules as cached, where this client told it \
1195                         nothing was"
1196                            .to_string(),
1197                    )
1198                })?;
1199                Ok(ContractWithState {
1200                    contract,
1201                    synchronizer_id: reply.amulet_rules_update.domain_id,
1202                })
1203            }
1204            Route::ScanProxy => {
1205                let reply: FromProxy = self.get(url).await?;
1206                Ok(reply.amulet_rules)
1207            }
1208        }
1209    }
1210
1211    /// A provider's `FeaturedAppRight` contract, or `None` if the provider is
1212    /// not a featured application.
1213    ///
1214    /// The contract comes without a synchronizer: disclose it on the one the
1215    /// Amulet rules are on ([`ScanContract::disclosed`]).
1216    ///
1217    /// On a Scan this is an internal endpoint: see
1218    /// [`with_internal_endpoints`](Self::with_internal_endpoints).
1219    ///
1220    /// # Errors
1221    /// As [`dso_party_id`](Self::dso_party_id), and
1222    /// [`Error::InvalidRequest`] on a Scan without the opt-in.
1223    pub async fn featured_app_right(&self, provider: &str) -> Result<Option<ScanContract>> {
1224        #[derive(Deserialize)]
1225        struct Reply {
1226            #[serde(default)]
1227            featured_app_right: Option<ScanContract>,
1228        }
1229        self.internal("a featured application right")?;
1230        let reply: Reply = self
1231            .get(self.url("v0", &["featured-apps", provider])?)
1232            .await?;
1233        Ok(reply.featured_app_right)
1234    }
1235
1236    /// The `TransferPreapproval` contract that lets `party` receive Amulet
1237    /// without accepting each transfer, or `None` if it has none.
1238    ///
1239    /// On a Scan this is an internal endpoint: see
1240    /// [`with_internal_endpoints`](Self::with_internal_endpoints).
1241    ///
1242    /// # Errors
1243    /// As [`featured_app_right`](Self::featured_app_right).
1244    pub async fn transfer_preapproval_by_party(
1245        &self,
1246        party: &str,
1247    ) -> Result<Option<ContractWithState>> {
1248        #[derive(Deserialize)]
1249        struct Reply {
1250            transfer_preapproval: ContractWithState,
1251        }
1252        self.internal("a transfer preapproval")?;
1253        let url = self.url("v0", &["transfer-preapprovals", "by-party", party])?;
1254        let reply: Option<Reply> = self.get_optional(url).await?;
1255        Ok(reply.map(|reply| reply.transfer_preapproval))
1256    }
1257
1258    /// How much traffic `member` has bought and used on a synchronizer. A
1259    /// member is a participant or a mediator, by its id (`PAR::…`, `MED::…`).
1260    ///
1261    /// # Errors
1262    /// As [`scans`](Self::scans).
1263    pub async fn member_traffic_status(
1264        &self,
1265        synchronizer_id: &str,
1266        member_id: &str,
1267    ) -> Result<TrafficStatus> {
1268        #[derive(Deserialize)]
1269        struct Reply {
1270            traffic_status: Status,
1271        }
1272        #[derive(Deserialize)]
1273        struct Status {
1274            actual: Actual,
1275            target: Target,
1276        }
1277        #[derive(Deserialize)]
1278        struct Actual {
1279            total_consumed: i64,
1280            total_limit: i64,
1281        }
1282        #[derive(Deserialize)]
1283        struct Target {
1284            total_purchased: i64,
1285        }
1286        self.scan_only("a member's traffic status")?;
1287        let url = self.url(
1288            "v0",
1289            &[
1290                "domains",
1291                synchronizer_id,
1292                "members",
1293                member_id,
1294                "traffic-status",
1295            ],
1296        )?;
1297        let reply: Reply = self.get(url).await?;
1298        Ok(TrafficStatus {
1299            total_consumed: reply.traffic_status.actual.total_consumed,
1300            total_limit: reply.traffic_status.actual.total_limit,
1301            total_purchased: reply.traffic_status.target.total_purchased,
1302        })
1303    }
1304
1305    /// The Amulet Name Service entry of `party`, or `None` if it has none.
1306    ///
1307    /// # Errors
1308    /// As [`dso_party_id`](Self::dso_party_id).
1309    pub async fn ans_entry_by_party(&self, party: &str) -> Result<Option<AnsEntry>> {
1310        self.ans_entry(&["ans-entries", "by-party", party]).await
1311    }
1312
1313    /// The Amulet Name Service entry for `name`, or `None` if there is none.
1314    ///
1315    /// # Errors
1316    /// As [`dso_party_id`](Self::dso_party_id).
1317    pub async fn ans_entry_by_name(&self, name: &str) -> Result<Option<AnsEntry>> {
1318        self.ans_entry(&["ans-entries", "by-name", name]).await
1319    }
1320
1321    async fn ans_entry(&self, segments: &[&str]) -> Result<Option<AnsEntry>> {
1322        #[derive(Deserialize)]
1323        struct Reply {
1324            entry: AnsEntry,
1325        }
1326        let reply: Option<Reply> = self.get_optional(self.url("v0", segments)?).await?;
1327        Ok(reply.map(|reply| reply.entry))
1328    }
1329
1330    /// Up to `page_size` unexpired Amulet Name Service entries, those whose
1331    /// name starts with `name_prefix` where one is given.
1332    ///
1333    /// # Errors
1334    /// As [`dso_party_id`](Self::dso_party_id).
1335    pub async fn ans_entries(
1336        &self,
1337        name_prefix: Option<&str>,
1338        page_size: u32,
1339    ) -> Result<Vec<AnsEntry>> {
1340        #[derive(Deserialize)]
1341        struct Reply {
1342            entries: Vec<AnsEntry>,
1343        }
1344        let mut url = self.url("v0", &["ans-entries"])?;
1345        {
1346            let mut query = url.query_pairs_mut();
1347            if let Some(name_prefix) = name_prefix {
1348                query.append_pair("name_prefix", name_prefix);
1349            }
1350            query.append_pair("page_size", &page_size.to_string());
1351        }
1352        let reply: Reply = self.get(url).await?;
1353        Ok(reply.entries)
1354    }
1355
1356    /// Up to `page_size` updates after `after`, oldest first, or from the
1357    /// beginning of history where `after` is `None`.
1358    ///
1359    /// The last update's [`position`](ScanUpdate::position) is the `after` of
1360    /// the next page, and fewer than `page_size` updates means the end of
1361    /// what Scan has so far. Every Scan returns the same updates in the same
1362    /// order.
1363    ///
1364    /// # Errors
1365    /// As [`scans`](Self::scans).
1366    pub async fn updates(
1367        &self,
1368        after: Option<&HistoryPosition>,
1369        page_size: u32,
1370    ) -> Result<Vec<ScanUpdate>> {
1371        #[derive(Deserialize)]
1372        struct Reply {
1373            transactions: Vec<ScanUpdate>,
1374        }
1375        self.scan_only("the update history")?;
1376        let reply: Reply = self
1377            .post(
1378                self.url("v2", &["updates"])?,
1379                &history_request(after, page_size)?,
1380            )
1381            .await?;
1382        Ok(reply.transactions)
1383    }
1384
1385    /// The update with this id, or `None` if Scan has none.
1386    ///
1387    /// # Errors
1388    /// As [`scans`](Self::scans).
1389    pub async fn update(&self, update_id: &str) -> Result<Option<ScanUpdate>> {
1390        self.scan_only("an update")?;
1391        self.get_optional(self.url("v2", &["updates", update_id])?)
1392            .await
1393    }
1394
1395    /// Up to `page_size` entries of the event history after `after`: each
1396    /// update with the mediator's verdict on it. Paged as
1397    /// [`updates`](Self::updates), from the last entry's
1398    /// [`position`](ScanEventItem::position), which an entry has also when it
1399    /// is a verdict with no update.
1400    ///
1401    /// # Errors
1402    /// As [`scans`](Self::scans).
1403    pub async fn events(
1404        &self,
1405        after: Option<&HistoryPosition>,
1406        page_size: u32,
1407    ) -> Result<Vec<ScanEventItem>> {
1408        #[derive(Deserialize)]
1409        struct Reply {
1410            events: Vec<ScanEventItem>,
1411        }
1412        self.scan_only("the event history")?;
1413        let reply: Reply = self
1414            .post(
1415                self.url("v0", &["events"])?,
1416                &history_request(after, page_size)?,
1417            )
1418            .await?;
1419        Ok(reply.events)
1420    }
1421
1422    /// The record time of the most recent snapshot of the active contracts
1423    /// taken before `before` (an RFC 3339 time) in `migration_id`, or `None`
1424    /// if there is none.
1425    ///
1426    /// # Errors
1427    /// As [`scans`](Self::scans).
1428    pub async fn acs_snapshot_timestamp(
1429        &self,
1430        before: &str,
1431        migration_id: i64,
1432    ) -> Result<Option<String>> {
1433        #[derive(Deserialize)]
1434        struct Reply {
1435            record_time: String,
1436        }
1437        self.scan_only("the snapshot times")?;
1438        let mut url = self.url("v0", &["state", "acs", "snapshot-timestamp"])?;
1439        url.query_pairs_mut()
1440            .append_pair("before", before)
1441            .append_pair("migration_id", &migration_id.to_string());
1442        let reply: Option<Reply> = self.get_optional(url).await?;
1443        Ok(reply.map(|reply| reply.record_time))
1444    }
1445
1446    /// A page of a snapshot of the active contracts.
1447    ///
1448    /// Splice 0.7.5 and later: an older Scan has no `/v2/state/acs` and
1449    /// answers `404`.
1450    ///
1451    /// # Errors
1452    /// As [`scans`](Self::scans), and [`Error::InvalidRequest`] for a page
1453    /// size Scan does not allow.
1454    pub async fn acs_snapshot(&self, request: &SnapshotRequest) -> Result<AcsSnapshot> {
1455        self.scan_only("the snapshots of the active contracts")?;
1456        let mut body = serde_json::json!({
1457            "migration_id": request.migration_id,
1458            "record_time": request.record_time,
1459            "record_time_match": request.record_time_match(),
1460            "page_size": page_size(request.page_size)?,
1461        });
1462        if let Some(after) = &request.after {
1463            set(&mut body, "after", Value::from(after.as_str()));
1464        }
1465        if !request.parties.is_empty() {
1466            set(&mut body, "party_ids", Value::from(request.parties.clone()));
1467        }
1468        if !request.templates.is_empty() {
1469            set(
1470                &mut body,
1471                "templates",
1472                Value::from(request.templates.clone()),
1473            );
1474        }
1475        self.post(self.url("v2", &["state", "acs"])?, &body).await
1476    }
1477
1478    /// A page of the Amulet and locked Amulet contracts the request's parties
1479    /// owned at a snapshot. Splice 0.7.5 and later, as
1480    /// [`acs_snapshot`](Self::acs_snapshot).
1481    ///
1482    /// # Errors
1483    /// As [`acs_snapshot`](Self::acs_snapshot), and
1484    /// [`Error::InvalidRequest`] if the request names no party.
1485    pub async fn holdings_state(&self, request: &SnapshotRequest) -> Result<AcsSnapshot> {
1486        self.scan_only("the holdings at a snapshot")?;
1487        let mut body = serde_json::json!({
1488            "migration_id": request.migration_id,
1489            "record_time": request.record_time,
1490            "record_time_match": request.record_time_match(),
1491            "page_size": page_size(request.page_size)?,
1492            "owner_party_ids": request.owners("a holdings read")?,
1493        });
1494        if let Some(after) = &request.after {
1495            set(&mut body, "after", Value::from(after.as_str()));
1496        }
1497        self.post(self.url("v2", &["holdings", "state"])?, &body)
1498            .await
1499    }
1500
1501    /// The Amulet totals the request's parties held at a snapshot. The page
1502    /// size, page token and templates of the request are not used. Splice
1503    /// 0.6.3 and later.
1504    ///
1505    /// # Errors
1506    /// As [`dso_party_id`](Self::dso_party_id), and
1507    /// [`Error::InvalidRequest`] if the request names no party.
1508    pub async fn holdings_summary(&self, request: &SnapshotRequest) -> Result<HoldingsSummaries> {
1509        let body = serde_json::json!({
1510            "migration_id": request.migration_id,
1511            "record_time": request.record_time,
1512            "record_time_match": request.record_time_match(),
1513            "owner_party_ids": request.owners("a holdings summary")?,
1514        });
1515        self.post(self.url("v1", &["holdings", "summary"])?, &body)
1516            .await
1517    }
1518
1519    /// `GET` a path this client has no method for, and return the JSON as it
1520    /// came. `version` is the first path segment (`v0`, `v1`, …).
1521    ///
1522    /// For the rest of Splice's API: the same transport as every other call
1523    /// here (the token, no redirects, a bounded reply, encoded segments) and
1524    /// nothing checked about what comes back. Through a validator the path is
1525    /// taken under its `scan-proxy` prefix.
1526    ///
1527    /// # Errors
1528    /// As any HTTP call.
1529    pub async fn get_json(
1530        &self,
1531        version: &str,
1532        segments: &[&str],
1533        query: &[(&str, &str)],
1534    ) -> Result<Value> {
1535        let mut url = self.url(version, segments)?;
1536        if !query.is_empty() {
1537            url.query_pairs_mut().extend_pairs(query);
1538        }
1539        self.get(url).await
1540    }
1541
1542    /// `POST` a JSON body to a path this client has no method for, and return
1543    /// the JSON as it came. See [`get_json`](Self::get_json).
1544    ///
1545    /// # Errors
1546    /// As any HTTP call.
1547    pub async fn post_json(&self, version: &str, segments: &[&str], body: &Value) -> Result<Value> {
1548        self.post(self.url(version, segments)?, body).await
1549    }
1550
1551    /// Send a request with the bearer token, when one is configured.
1552    async fn send(&self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> {
1553        let request = match self.auth.bearer().await? {
1554            Some(token) => request.bearer_auth(token),
1555            None => request,
1556        };
1557        request.send().await.map_err(|e| transport_error(e, SCAN))
1558    }
1559
1560    async fn get<T: serde::de::DeserializeOwned>(&self, url: reqwest::Url) -> Result<T> {
1561        let response = self.send(self.http.get(url.clone())).await?;
1562        decode(response, url.as_str()).await
1563    }
1564
1565    async fn post<T: serde::de::DeserializeOwned>(
1566        &self,
1567        url: reqwest::Url,
1568        body: &(impl Serialize + ?Sized),
1569    ) -> Result<T> {
1570        let response = self.send(self.http.post(url.clone()).json(body)).await?;
1571        decode(response, url.as_str()).await
1572    }
1573
1574    /// A `GET` whose `404` is an answer: there is no such entry.
1575    ///
1576    /// Only when Scan is the one answering. A `404` whose body is not JSON did
1577    /// not come from a Scan handler: it is a base URL one path component off,
1578    /// or a gateway in front of one, and reporting that as "no such entry"
1579    /// would be a steady, quiet `None` where every other call fails loudly.
1580    async fn get_optional<T: serde::de::DeserializeOwned>(
1581        &self,
1582        url: reqwest::Url,
1583    ) -> Result<Option<T>> {
1584        let response = self.send(self.http.get(url.clone())).await?;
1585        if response.status() == reqwest::StatusCode::NOT_FOUND {
1586            let body = read_error_body(response, url.as_str(), SCAN).await?;
1587            let trimmed = body.trim();
1588            if serde_json::from_str::<ErrorResponse>(trimmed).is_ok() {
1589                return Ok(None);
1590            }
1591            tracing::warn!(%url, "a 404 that is not Scan's own — check the base URL");
1592            return Err(Error::http_at(404, truncate(trimmed), url.as_str()));
1593        }
1594        Ok(Some(decode(response, url.as_str()).await?))
1595    }
1596}
1597
1598/// The HTTP client every [`ScanClient`] starts from: a deadline, and no
1599/// redirects.
1600fn default_http_client() -> Result<reqwest::Client> {
1601    reqwest::Client::builder()
1602        .timeout(DEFAULT_TIMEOUT)
1603        .redirect(reqwest::redirect::Policy::none())
1604        .build()
1605        .map_err(|e| Error::InvalidRequest(format!("cannot build an HTTP client: {e}")))
1606}
1607
1608fn page_size(page_size: u32) -> Result<u32> {
1609    if page_size == 0 || page_size > MAX_PAGE_SIZE {
1610        return Err(Error::InvalidRequest(format!(
1611            "a page of {page_size} is not one Scan serves: it takes 1 to {MAX_PAGE_SIZE}"
1612        )));
1613    }
1614    Ok(page_size)
1615}
1616
1617/// Set a field of a JSON object built on the line above. `object[key] = …`
1618/// does the same and panics when `object` is not an object.
1619fn set(object: &mut Value, key: &str, value: Value) {
1620    if let Some(fields) = object.as_object_mut() {
1621        fields.insert(key.to_string(), value);
1622    }
1623}
1624
1625/// The body of a history read: where to read on from, and how much.
1626fn history_request(after: Option<&HistoryPosition>, size: u32) -> Result<Value> {
1627    let mut body = serde_json::json!({ "page_size": page_size(size)? });
1628    if let Some(after) = after {
1629        let after = serde_json::to_value(after).map_err(|e| {
1630            Error::InvalidRequest(format!("a history position that is not JSON: {e}"))
1631        })?;
1632        set(&mut body, "after", after);
1633    }
1634    Ok(body)
1635}
1636
1637/// One place where a non-success status becomes an error and a body becomes a
1638/// value, so every call reports failure the same way.
1639async fn decode<T: serde::de::DeserializeOwned>(
1640    response: reqwest::Response,
1641    url: &str,
1642) -> Result<T> {
1643    let status = response.status();
1644    let body = if status.is_success() {
1645        read_body_from(response, MAX_RESPONSE_BYTES, url, SCAN).await?
1646    } else {
1647        read_error_body(response, url, SCAN).await?
1648    };
1649    if !status.is_success() {
1650        // Splice's error body is `{"error": "…"}`; anything else is passed
1651        // through. The body stays the body, since the shared error model
1652        // reads it; the URL is in the log line.
1653        tracing::warn!(%url, status = status.as_u16(), "Scan answered with an error");
1654        let message = serde_json::from_str::<ErrorResponse>(&body)
1655            .map(|e| e.error)
1656            .unwrap_or(body);
1657        return Err(Error::http_at(status.as_u16(), truncate(&message), url));
1658    }
1659    serde_json::from_str(&body).map_err(|e| {
1660        Error::UnexpectedResponse(format!(
1661            "{url} returned a body this does not understand: {e}"
1662        ))
1663    })
1664}
1665
1666#[cfg(test)]
1667#[allow(clippy::unwrap_used, clippy::expect_used)]
1668mod tests {
1669    use super::*;
1670
1671    fn contract(contract_id: &str, payload: Value) -> ContractWithState {
1672        ContractWithState {
1673            contract: ScanContract {
1674                template_id: "pkg:Splice.Round:OpenMiningRound".to_string(),
1675                contract_id: contract_id.to_string(),
1676                payload,
1677                created_event_blob: base64::engine::general_purpose::STANDARD.encode([1, 2, 3]),
1678                created_at: "2026-11-26T10:00:00Z".to_string(),
1679            },
1680            synchronizer_id: Some("global-domain::1220aa".to_string()),
1681        }
1682    }
1683
1684    fn round(number: i64, opens_at: &str) -> ContractWithState {
1685        contract(
1686            &format!("00round{number}"),
1687            serde_json::json!({
1688                "round": { "number": number.to_string() },
1689                "opensAt": opens_at,
1690                "targetClosesAt": "2026-11-26T12:00:00Z",
1691            }),
1692        )
1693    }
1694
1695    fn at(time: &str) -> Timestamp {
1696        serde_json::from_value(Value::from(time)).unwrap()
1697    }
1698
1699    /// Several rounds are open at once and the newest has usually not reached
1700    /// its opening time. The one to use is the highest that has: the lowest
1701    /// is archived next, and the one above the highest is not usable yet.
1702    #[test]
1703    fn the_latest_open_round_is_the_highest_one_whose_opening_time_has_come() {
1704        let rounds = MiningRounds {
1705            open: vec![
1706                round(11, "2026-11-26T10:10:00.000000Z"),
1707                round(10, "2026-11-26T10:00:00.000000Z"),
1708                round(12, "2026-11-26T10:20:00.000000Z"),
1709            ],
1710            issuing: Vec::new(),
1711        };
1712        let pick = |now: &str| {
1713            rounds
1714                .latest_open(at(now))
1715                .map(|round| round.contract.contract_id.clone())
1716        };
1717        assert_eq!(pick("2026-11-26T10:15:00Z").unwrap(), "00round11");
1718        assert_eq!(pick("2026-11-26T10:05:00Z").unwrap(), "00round10");
1719        // The opening time itself counts as open.
1720        assert_eq!(pick("2026-11-26T10:20:00Z").unwrap(), "00round12");
1721        assert_eq!(pick("2026-11-27T00:00:00Z").unwrap(), "00round12");
1722
1723        // Before any round opens there is none, and that passes by itself.
1724        let error = pick("2026-11-26T09:00:00Z").unwrap_err();
1725        assert!(error.is_retriable(), "{error:?}");
1726        assert!(
1727            error.to_string().contains("3 open mining rounds"),
1728            "{error}"
1729        );
1730    }
1731
1732    /// A round number is a Daml `Int`, which JSON writes as a string, and
1733    /// compares as a number: round 9 is before round 10.
1734    #[test]
1735    fn round_numbers_compare_as_numbers_whether_written_as_text_or_not() {
1736        let mut as_number = round(9, "2026-11-26T09:50:00Z");
1737        as_number.contract.payload["round"]["number"] = Value::from(9);
1738        let rounds = MiningRounds {
1739            open: vec![round(10, "2026-11-26T10:00:00Z"), as_number],
1740            issuing: Vec::new(),
1741        };
1742        let latest = rounds.latest_open(at("2026-11-26T11:00:00Z")).unwrap();
1743        assert_eq!(latest.contract.contract_id, "00round10");
1744    }
1745
1746    #[test]
1747    fn a_round_that_is_not_an_open_mining_round_is_an_unexpected_response() {
1748        let rounds = MiningRounds {
1749            open: vec![contract("00odd", serde_json::json!({ "round": {} }))],
1750            issuing: Vec::new(),
1751        };
1752        let error = rounds.latest_open(at("2026-11-26T11:00:00Z")).unwrap_err();
1753        assert!(matches!(error, Error::UnexpectedResponse(_)), "{error:?}");
1754        assert!(error.to_string().contains("00odd"), "{error}");
1755    }
1756
1757    /// gRPC takes the blob as bytes and the JSON API as the base64 Scan sent,
1758    /// and both name the synchronizer the contract is on.
1759    #[test]
1760    fn a_contract_is_disclosed_as_bytes_for_grpc_and_base64_for_json() {
1761        let rules = contract("00rules", serde_json::json!({}));
1762        let disclosed = rules.disclosed().unwrap();
1763        assert_eq!(disclosed.contract_id, "00rules");
1764        assert_eq!(disclosed.created_event_blob, [1, 2, 3]);
1765        assert_eq!(disclosed.synchronizer_id, "global-domain::1220aa");
1766        let template = disclosed.template_id.unwrap();
1767        assert_eq!(
1768            (
1769                template.package_id.as_str(),
1770                template.module_name.as_str(),
1771                template.entity_name.as_str()
1772            ),
1773            ("pkg", "Splice.Round", "OpenMiningRound")
1774        );
1775
1776        let json = rules.disclosed_json().unwrap();
1777        assert_eq!(json["createdEventBlob"], "AQID");
1778        assert_eq!(json["synchronizerId"], "global-domain::1220aa");
1779        assert_eq!(json["templateId"], "pkg:Splice.Round:OpenMiningRound");
1780    }
1781
1782    #[test]
1783    fn a_contract_that_cannot_be_disclosed_says_why() {
1784        let mut in_transit = contract("00moving", serde_json::json!({}));
1785        in_transit.synchronizer_id = None;
1786        let error = in_transit.disclosed().unwrap_err();
1787        assert!(error.is_retriable(), "{error:?}");
1788        assert!(in_transit.disclosed_json().is_err());
1789
1790        for template_id in ["pkg:Module", "pkg:Module:Entity:Extra", "::", ""] {
1791            let mut odd = contract("00odd", serde_json::json!({}));
1792            odd.contract.template_id = template_id.to_string();
1793            let error = odd.disclosed().unwrap_err();
1794            assert!(matches!(error, Error::UnexpectedResponse(_)), "{error:?}");
1795        }
1796
1797        let mut odd = contract("00blob", serde_json::json!({}));
1798        odd.contract.created_event_blob = "not base64!!".to_string();
1799        let error = odd.disclosed().unwrap_err();
1800        assert!(error.to_string().contains("00blob"), "{error}");
1801    }
1802
1803    /// The two kinds of update carry no tag: a transaction is the one with
1804    /// events, a reassignment the one with an event.
1805    #[test]
1806    fn updates_are_told_apart_by_their_fields() {
1807        let transaction: ScanUpdate = serde_json::from_value(serde_json::json!({
1808            "update_id": "1220tx",
1809            "migration_id": 4,
1810            "workflow_id": "",
1811            "record_time": "2026-11-26T10:00:00.000000Z",
1812            "synchronizer_id": "global-domain::1220aa",
1813            "effective_at": "2026-11-26T09:59:59.000000Z",
1814            "root_event_ids": ["1220tx:0"],
1815            "events_by_id": {
1816                "1220tx:0": {
1817                    "event_type": "exercised_event",
1818                    "event_id": "1220tx:0",
1819                    "contract_id": "00rules",
1820                    "template_id": "pkg:Splice.AmuletRules:AmuletRules",
1821                    "package_name": "splice-amulet",
1822                    "choice": "AmuletRules_Transfer",
1823                    "choice_argument": {},
1824                    "child_event_ids": ["1220tx:1"],
1825                    "exercise_result": {},
1826                    "consuming": false,
1827                    "acting_parties": ["alice::1220"],
1828                },
1829                "1220tx:1": {
1830                    "event_type": "created_event",
1831                    "event_id": "1220tx:1",
1832                    "contract_id": "00amulet",
1833                    "template_id": "pkg:Splice.Amulet:Amulet",
1834                    "package_name": "splice-amulet",
1835                    "create_arguments": { "owner": "bob::1220" },
1836                    "created_at": "2026-11-26T09:59:59.000000Z",
1837                    "signatories": ["DSO::1220"],
1838                    "observers": [],
1839                },
1840            },
1841        }))
1842        .unwrap();
1843        assert_eq!(transaction.update_id(), "1220tx");
1844        assert_eq!(
1845            transaction.position(),
1846            HistoryPosition {
1847                migration_id: 4,
1848                record_time: "2026-11-26T10:00:00.000000Z".to_string(),
1849            }
1850        );
1851        let ScanUpdate::Transaction(transaction) = transaction else {
1852            panic!("a transaction");
1853        };
1854        assert!(matches!(
1855            transaction.events_by_id["1220tx:0"],
1856            ScanEvent::Exercised(_)
1857        ));
1858        assert!(matches!(
1859            transaction.events_by_id["1220tx:1"],
1860            ScanEvent::Created(_)
1861        ));
1862
1863        let unassigned: ScanUpdate = serde_json::from_value(serde_json::json!({
1864            "update_id": "1220out",
1865            "offset": "000a",
1866            "record_time": "2026-11-26T10:01:00.000000Z",
1867            "event": {
1868                "submitter": "alice::1220",
1869                "source_synchronizer": "one::1220",
1870                "target_synchronizer": "two::1220",
1871                "migration_id": 5,
1872                "unassign_id": "u1",
1873                "reassignment_counter": 1,
1874                "contract_id": "00moving",
1875            },
1876        }))
1877        .unwrap();
1878        assert_eq!(unassigned.position().migration_id, 5);
1879        assert!(matches!(
1880            unassigned,
1881            ScanUpdate::Reassignment(ScanReassignment {
1882                event: ReassignmentEvent::Unassignment(_),
1883                ..
1884            })
1885        ));
1886
1887        let neither = serde_json::from_value::<ScanUpdate>(serde_json::json!({
1888            "update_id": "1220odd",
1889        }))
1890        .unwrap_err();
1891        assert!(neither.to_string().contains("events_by_id"), "{neither}");
1892    }
1893
1894    /// The last entry of an event page is what the next page is read from,
1895    /// and it can be a verdict with no update: a transaction the mediator
1896    /// rejected. Its position comes from the verdict then.
1897    #[test]
1898    fn an_event_entry_has_a_position_with_or_without_an_update() {
1899        let rejected: ScanEventItem = serde_json::from_value(serde_json::json!({
1900            "update": null,
1901            "verdict": {
1902                "update_id": "1220rejected",
1903                "migration_id": 4,
1904                "domain_id": "global-domain::1220aa",
1905                "record_time": "2026-11-26T10:02:00.000000Z",
1906                "finalization_time": "2026-11-26T10:02:01.000000Z",
1907                "submitting_parties": ["alice::1220"],
1908                "submitting_participant_uid": "participant::1220",
1909                "verdict_result": "VERDICT_RESULT_REJECTED",
1910                "mediator_group": 0,
1911                "transaction_views": { "views": [], "root_views": [] },
1912            },
1913            "asset_activity_records": [],
1914            "submitting_app_provider": "provider::1220",
1915        }))
1916        .unwrap();
1917        assert!(rejected.update.is_none());
1918        assert_eq!(
1919            rejected.position(),
1920            Some(HistoryPosition {
1921                migration_id: 4,
1922                record_time: "2026-11-26T10:02:00.000000Z".to_string(),
1923            })
1924        );
1925        assert_eq!(
1926            rejected.submitting_app_provider.as_deref(),
1927            Some("provider::1220")
1928        );
1929        assert!(rejected.asset_activity_records.is_some());
1930
1931        let empty: ScanEventItem = serde_json::from_value(serde_json::json!({})).unwrap();
1932        assert_eq!(empty.position(), None);
1933    }
1934
1935    /// A path argument that URL parsing would resolve away is refused before
1936    /// anything is sent, on either route.
1937    #[tokio::test]
1938    async fn a_dot_or_empty_path_segment_is_refused_before_sending() {
1939        let direct = ScanClient::new("http://127.0.0.1:1/api/scan")
1940            .unwrap()
1941            .with_internal_endpoints();
1942        let proxy = ScanClient::through_validator("http://127.0.0.1:1/api/validator").unwrap();
1943        for client in [direct, proxy] {
1944            // URL parsing drops tab, CR and LF, so `.\t` was `.` and `.\t.`
1945            // was `..` by the time the request went out.
1946            for id in ["..", ".", "", ".\t", ".\t.", "..\r", "\n.."] {
1947                let error = client.featured_app_right(id).await.unwrap_err();
1948                assert!(
1949                    matches!(error, Error::InvalidRequest(_)),
1950                    "{id:?}: {error:?}"
1951                );
1952                let error = client.ans_entry_by_party(id).await.unwrap_err();
1953                assert!(
1954                    matches!(error, Error::InvalidRequest(_)),
1955                    "{id:?}: {error:?}"
1956                );
1957            }
1958            // The API version is a segment like the others.
1959            for version in ["", ".", "..", ".\t."] {
1960                assert!(
1961                    matches!(client.url(version, &["dso"]), Err(Error::InvalidRequest(_))),
1962                    "{version:?}"
1963                );
1964            }
1965        }
1966    }
1967
1968    /// A base URL with a query or a fragment is refused on either route, and
1969    /// a trailing backslash is trimmed like a slash.
1970    #[test]
1971    fn the_base_url_has_no_query_or_fragment_and_is_trimmed() {
1972        for base in [
1973            "https://s.example/api/scan?apikey=abc",
1974            "https://s.example/api/scan#x",
1975        ] {
1976            assert!(
1977                matches!(ScanClient::new(base), Err(Error::InvalidRequest(_))),
1978                "{base}"
1979            );
1980            assert!(
1981                matches!(
1982                    ScanClient::through_validator(base),
1983                    Err(Error::InvalidRequest(_))
1984                ),
1985                "{base}"
1986            );
1987        }
1988        let client = ScanClient::new(r"https://s.example/api/scan\").unwrap();
1989        assert_eq!(
1990            client.url("v0", &["dso"]).unwrap().as_str(),
1991            "https://s.example/api/scan/v0/dso"
1992        );
1993    }
1994
1995    /// The position serializes as the `after` object the history reads take.
1996    #[test]
1997    fn a_history_position_is_the_after_of_the_next_page() {
1998        let after = HistoryPosition {
1999            migration_id: 4,
2000            record_time: "2026-11-26T10:00:00.000000Z".to_string(),
2001        };
2002        assert_eq!(
2003            history_request(Some(&after), 50).unwrap(),
2004            serde_json::json!({
2005                "page_size": 50,
2006                "after": {
2007                    "after_migration_id": 4,
2008                    "after_record_time": "2026-11-26T10:00:00.000000Z",
2009                },
2010            })
2011        );
2012        assert_eq!(
2013            history_request(None, 1).unwrap(),
2014            serde_json::json!({ "page_size": 1 })
2015        );
2016        for size in [0, 1001] {
2017            let error = history_request(None, size).unwrap_err();
2018            assert!(matches!(error, Error::InvalidRequest(_)), "{error:?}");
2019        }
2020    }
2021}