1use 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
88const SCAN: &str = "Scan";
90
91const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
94
95const MAX_PAGE_SIZE: u32 = 1000;
97
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100enum Route {
101 Scan,
103 ScanProxy,
106}
107
108#[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#[derive(Clone, Debug, Deserialize)]
120#[non_exhaustive]
121pub struct ScanContract {
122 pub template_id: String,
124 pub contract_id: String,
126 pub payload: Value,
128 pub created_event_blob: String,
131 pub created_at: String,
133}
134
135#[derive(Clone, Debug, Deserialize)]
137#[non_exhaustive]
138pub struct ContractWithState {
139 pub contract: ScanContract,
141 #[serde(rename = "domain_id", default)]
144 pub synchronizer_id: Option<String>,
145}
146
147impl ScanContract {
148 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 #[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 pub fn disclosed(&self) -> Result<pb::DisclosedContract> {
194 self.contract.disclosed(self.assigned()?)
195 }
196
197 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
216fn 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#[derive(Clone, Debug, Deserialize)]
240#[non_exhaustive]
241pub struct DsoInfo {
242 pub dso_party_id: String,
244 pub voting_threshold: u32,
246 pub latest_mining_round: ContractWithState,
249 pub amulet_rules: ContractWithState,
251 pub dso_rules: ContractWithState,
253 pub sv_node_states: Vec<ContractWithState>,
255 #[serde(default)]
257 pub initial_round: Option<String>,
258}
259
260#[derive(Clone, Debug, Deserialize)]
262#[non_exhaustive]
263pub struct SynchronizerScans {
264 #[serde(rename = "domainId")]
266 pub synchronizer_id: String,
267 pub scans: Vec<ScanInfo>,
269}
270
271#[derive(Clone, Debug, Deserialize)]
273#[serde(rename_all = "camelCase")]
274#[non_exhaustive]
275pub struct ScanInfo {
276 pub public_url: String,
278 pub sv_name: String,
280}
281
282#[derive(Clone, Debug)]
285#[non_exhaustive]
286pub struct MiningRounds {
287 pub open: Vec<ContractWithState>,
290 pub issuing: Vec<ContractWithState>,
292}
293
294#[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
309fn 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
367#[non_exhaustive]
368pub struct TrafficStatus {
369 pub total_consumed: i64,
372 pub total_limit: i64,
375 pub total_purchased: i64,
378}
379
380#[derive(Clone, Debug, Deserialize)]
382#[non_exhaustive]
383pub struct AnsEntry {
384 #[serde(default)]
387 pub contract_id: Option<String>,
388 pub user: String,
390 pub name: String,
392 pub url: String,
394 pub description: String,
396 #[serde(default)]
398 pub expires_at: Option<String>,
399}
400
401#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
404pub struct HistoryPosition {
405 #[serde(rename = "after_migration_id")]
409 pub migration_id: i64,
410 #[serde(rename = "after_record_time")]
412 pub record_time: String,
413}
414
415#[derive(Clone, Debug)]
417#[non_exhaustive]
418pub enum ScanUpdate {
419 Transaction(ScanTransaction),
421 Reassignment(ScanReassignment),
423}
424
425impl ScanUpdate {
426 #[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 #[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
454impl<'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#[derive(Clone, Debug, Deserialize)]
481#[non_exhaustive]
482pub struct ScanTransaction {
483 pub update_id: String,
485 pub migration_id: i64,
487 pub workflow_id: String,
489 pub record_time: String,
491 pub synchronizer_id: String,
493 pub effective_at: String,
495 pub root_event_ids: Vec<String>,
497 pub events_by_id: BTreeMap<String, ScanEvent>,
499 #[serde(default)]
502 pub external_transaction_hash: Option<String>,
503}
504
505#[derive(Clone, Debug, Deserialize)]
507#[serde(tag = "event_type")]
508#[non_exhaustive]
509pub enum ScanEvent {
510 #[serde(rename = "created_event")]
512 Created(ScanCreatedEvent),
513 #[serde(rename = "exercised_event")]
515 Exercised(ScanExercisedEvent),
516}
517
518#[derive(Clone, Debug, Deserialize)]
520#[non_exhaustive]
521pub struct ScanCreatedEvent {
522 pub event_id: String,
524 pub contract_id: String,
526 pub template_id: String,
528 pub package_name: String,
530 pub create_arguments: Value,
532 pub created_at: String,
534 pub signatories: Vec<String>,
536 pub observers: Vec<String>,
538}
539
540#[derive(Clone, Debug, Deserialize)]
542#[non_exhaustive]
543pub struct ScanExercisedEvent {
544 pub event_id: String,
546 pub contract_id: String,
548 pub template_id: String,
550 pub package_name: String,
552 pub choice: String,
554 pub choice_argument: Value,
556 pub child_event_ids: Vec<String>,
558 pub exercise_result: Value,
560 pub consuming: bool,
562 pub acting_parties: Vec<String>,
564 #[serde(default)]
566 pub interface_id: Option<String>,
567}
568
569#[derive(Clone, Debug, Deserialize)]
571#[non_exhaustive]
572pub struct ScanReassignment {
573 pub update_id: String,
575 pub offset: String,
578 pub record_time: String,
580 pub event: ReassignmentEvent,
582}
583
584#[derive(Clone, Debug)]
586#[non_exhaustive]
587pub enum ReassignmentEvent {
588 Assignment(ScanAssignment),
590 Unassignment(ScanUnassignment),
592}
593
594impl<'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#[derive(Clone, Debug, Deserialize)]
621#[non_exhaustive]
622pub struct ScanAssignment {
623 pub submitter: String,
625 pub source_synchronizer: String,
627 pub target_synchronizer: String,
629 pub migration_id: i64,
631 pub unassign_id: String,
633 pub created_event: ScanCreatedEvent,
635 pub reassignment_counter: i64,
637}
638
639#[derive(Clone, Debug, Deserialize)]
641#[non_exhaustive]
642pub struct ScanUnassignment {
643 pub submitter: String,
645 pub source_synchronizer: String,
647 pub migration_id: i64,
649 pub target_synchronizer: String,
651 pub unassign_id: String,
653 pub reassignment_counter: i64,
655 pub contract_id: String,
657}
658
659#[derive(Clone, Debug, Deserialize)]
662#[non_exhaustive]
663pub struct ScanEventItem {
664 #[serde(default)]
667 pub update: Option<ScanUpdate>,
668 #[serde(default)]
670 pub verdict: Option<Value>,
671 #[serde(default)]
673 pub traffic_summary: Option<Value>,
674 #[serde(default)]
677 pub app_activity_records: Option<Value>,
678 #[serde(default)]
681 pub asset_activity_records: Option<Value>,
682 #[serde(default)]
685 pub submitting_app_provider: Option<String>,
686}
687
688impl ScanEventItem {
689 #[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#[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 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 #[must_use]
740 pub fn at_or_before(mut self) -> Self {
741 self.at_or_before = true;
742 self
743 }
744
745 #[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 #[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 #[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 #[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#[derive(Clone, Debug, Deserialize)]
803#[non_exhaustive]
804pub struct AcsSnapshot {
805 pub record_time: String,
807 pub migration_id: i64,
809 pub created_events: Vec<ActiveContract>,
811 #[serde(default)]
813 pub next_page_token: Option<String>,
814}
815
816#[derive(Clone, Debug, Deserialize)]
818#[non_exhaustive]
819pub struct ActiveContract {
820 #[serde(default)]
822 pub created_in_update_id: Option<String>,
823 pub contract_id: String,
825 pub template_id: String,
827 pub package_name: String,
829 pub create_arguments: Value,
831 pub created_at: String,
833 pub signatories: Vec<String>,
835 pub observers: Vec<String>,
837}
838
839#[derive(Clone, Debug, Deserialize)]
841#[non_exhaustive]
842pub struct HoldingsSummaries {
843 pub record_time: String,
845 pub migration_id: i64,
847 pub summaries: Vec<HoldingsSummary>,
849}
850
851#[derive(Clone, Debug, Deserialize)]
854#[non_exhaustive]
855pub struct HoldingsSummary {
856 pub party_id: String,
858 pub total_unlocked_coin: String,
860 pub total_locked_coin: String,
862 pub total_coin_holdings: String,
864}
865
866impl ScanClient {
867 pub fn new(base_url: &str) -> Result<Self> {
873 Self::with_http_client(base_url, default_http_client()?)
874 }
875
876 pub fn with_http_client(base_url: &str, http: reqwest::Client) -> Result<Self> {
885 Self::build(base_url, http, Route::Scan)
886 }
887
888 pub fn through_validator(base_url: &str) -> Result<Self> {
899 Self::through_validator_with_http_client(base_url, default_http_client()?)
900 }
901
902 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 #[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 #[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 #[must_use]
952 pub fn with_internal_endpoints(mut self) -> Self {
953 self.internal_endpoints = true;
954 self
955 }
956
957 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 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 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 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 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 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 pub async fn open_and_issuing_mining_rounds(&self) -> Result<MiningRounds> {
1055 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
1598fn 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
1617fn 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
1625fn 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
1637async 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 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 #[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 assert_eq!(pick("2026-11-26T10:20:00Z").unwrap(), "00round12");
1721 assert_eq!(pick("2026-11-27T00:00:00Z").unwrap(), "00round12");
1722
1723 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 #[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 #[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 #[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 #[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 #[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 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 for version in ["", ".", "..", ".\t."] {
1960 assert!(
1961 matches!(client.url(version, &["dso"]), Err(Error::InvalidRequest(_))),
1962 "{version:?}"
1963 );
1964 }
1965 }
1966 }
1967
1968 #[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 #[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}