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, read_body_from, read_error_body, transport_error, truncate,
85};
86
87const SCAN: &str = "Scan";
89
90const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
93
94const MAX_PAGE_SIZE: u32 = 1000;
96
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99enum Route {
100 Scan,
102 ScanProxy,
105}
106
107#[derive(Clone, Debug)]
109pub struct ScanClient {
110 base: reqwest::Url,
111 http: reqwest::Client,
112 auth: Auth,
113 route: Route,
114 internal_endpoints: bool,
115}
116
117#[derive(Clone, Debug, Deserialize)]
119#[non_exhaustive]
120pub struct ScanContract {
121 pub template_id: String,
123 pub contract_id: String,
125 pub payload: Value,
127 pub created_event_blob: String,
130 pub created_at: String,
132}
133
134#[derive(Clone, Debug, Deserialize)]
136#[non_exhaustive]
137pub struct ContractWithState {
138 pub contract: ScanContract,
140 #[serde(rename = "domain_id", default)]
143 pub synchronizer_id: Option<String>,
144}
145
146impl ScanContract {
147 pub fn disclosed(&self, synchronizer_id: &str) -> Result<pb::DisclosedContract> {
154 let created_event_blob = base64::engine::general_purpose::STANDARD
155 .decode(&self.created_event_blob)
156 .map_err(|e| {
157 Error::UnexpectedResponse(format!(
158 "Scan published contract `{}` with a created-event blob that is not \
159 base64: {e}",
160 self.contract_id
161 ))
162 })?;
163 Ok(pb::DisclosedContract {
164 template_id: Some(identifier(&self.template_id)?),
165 contract_id: self.contract_id.clone(),
166 created_event_blob,
167 synchronizer_id: synchronizer_id.to_string(),
168 })
169 }
170
171 #[must_use]
174 pub fn disclosed_json(&self, synchronizer_id: &str) -> Value {
175 serde_json::json!({
176 "templateId": self.template_id,
177 "contractId": self.contract_id,
178 "createdEventBlob": self.created_event_blob,
179 "synchronizerId": synchronizer_id,
180 })
181 }
182}
183
184impl ContractWithState {
185 pub fn disclosed(&self) -> Result<pb::DisclosedContract> {
193 self.contract.disclosed(self.assigned()?)
194 }
195
196 pub fn disclosed_json(&self) -> Result<Value> {
201 Ok(self.contract.disclosed_json(self.assigned()?))
202 }
203
204 fn assigned(&self) -> Result<&str> {
205 self.synchronizer_id.as_deref().ok_or_else(|| {
206 Error::Connection(format!(
207 "contract `{}` is being reassigned between synchronizers, so there is none to \
208 disclose it on yet; retry shortly",
209 self.contract.contract_id
210 ))
211 })
212 }
213}
214
215fn identifier(template_id: &str) -> Result<pb::Identifier> {
219 let mut parts = template_id.split(':');
220 match (parts.next(), parts.next(), parts.next(), parts.next()) {
221 (Some(package_id), Some(module_name), Some(entity_name), None)
222 if !package_id.is_empty() && !module_name.is_empty() && !entity_name.is_empty() =>
223 {
224 Ok(pb::Identifier {
225 package_id: package_id.to_string(),
226 module_name: module_name.to_string(),
227 entity_name: entity_name.to_string(),
228 })
229 }
230 _ => Err(Error::UnexpectedResponse(format!(
231 "Scan published a contract with template id `{template_id}`, which is not \
232 `<package>:<Module>:<Entity>`"
233 ))),
234 }
235}
236
237#[derive(Clone, Debug, Deserialize)]
239#[non_exhaustive]
240pub struct DsoInfo {
241 pub dso_party_id: String,
243 pub voting_threshold: u32,
245 pub latest_mining_round: ContractWithState,
248 pub amulet_rules: ContractWithState,
250 pub dso_rules: ContractWithState,
252 pub sv_node_states: Vec<ContractWithState>,
254 #[serde(default)]
256 pub initial_round: Option<String>,
257}
258
259#[derive(Clone, Debug, Deserialize)]
261#[non_exhaustive]
262pub struct SynchronizerScans {
263 #[serde(rename = "domainId")]
265 pub synchronizer_id: String,
266 pub scans: Vec<ScanInfo>,
268}
269
270#[derive(Clone, Debug, Deserialize)]
272#[serde(rename_all = "camelCase")]
273#[non_exhaustive]
274pub struct ScanInfo {
275 pub public_url: String,
277 pub sv_name: String,
279}
280
281#[derive(Clone, Debug)]
284#[non_exhaustive]
285pub struct MiningRounds {
286 pub open: Vec<ContractWithState>,
289 pub issuing: Vec<ContractWithState>,
291}
292
293#[derive(Deserialize)]
296struct OpenRound {
297 round: Round,
298 #[serde(rename = "opensAt")]
299 opens_at: Timestamp,
300}
301
302#[derive(Deserialize)]
303struct Round {
304 #[serde(deserialize_with = "int64")]
305 number: i64,
306}
307
308fn int64<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<i64, D::Error> {
311 #[derive(Deserialize)]
312 #[serde(untagged)]
313 enum Int {
314 Text(String),
315 Number(i64),
316 }
317 match Int::deserialize(deserializer)? {
318 Int::Text(text) => text.parse().map_err(serde::de::Error::custom),
319 Int::Number(number) => Ok(number),
320 }
321}
322
323impl MiningRounds {
324 pub fn latest_open(&self, now: Timestamp) -> Result<&ContractWithState> {
337 let mut latest: Option<(i64, &ContractWithState)> = None;
338 for round in &self.open {
339 let fields: OpenRound = serde_json::from_value(round.contract.payload.clone())
340 .map_err(|e| {
341 Error::UnexpectedResponse(format!(
342 "Scan published open mining round `{}` with a payload that is not an \
343 OpenMiningRound: {e}",
344 round.contract.contract_id
345 ))
346 })?;
347 if fields.opens_at > now {
348 continue;
349 }
350 if latest.is_none_or(|(number, _)| fields.round.number > number) {
351 latest = Some((fields.round.number, round));
352 }
353 }
354 latest.map(|(_, round)| round).ok_or_else(|| {
355 Error::Connection(format!(
356 "none of the {} open mining rounds Scan published has reached its opening time; \
357 retry shortly",
358 self.open.len()
359 ))
360 })
361 }
362}
363
364#[derive(Clone, Copy, Debug, PartialEq, Eq)]
366#[non_exhaustive]
367pub struct TrafficStatus {
368 pub total_consumed: i64,
371 pub total_limit: i64,
374 pub total_purchased: i64,
377}
378
379#[derive(Clone, Debug, Deserialize)]
381#[non_exhaustive]
382pub struct AnsEntry {
383 #[serde(default)]
386 pub contract_id: Option<String>,
387 pub user: String,
389 pub name: String,
391 pub url: String,
393 pub description: String,
395 #[serde(default)]
397 pub expires_at: Option<String>,
398}
399
400#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
403pub struct HistoryPosition {
404 #[serde(rename = "after_migration_id")]
408 pub migration_id: i64,
409 #[serde(rename = "after_record_time")]
411 pub record_time: String,
412}
413
414#[derive(Clone, Debug)]
416#[non_exhaustive]
417pub enum ScanUpdate {
418 Transaction(ScanTransaction),
420 Reassignment(ScanReassignment),
422}
423
424impl ScanUpdate {
425 #[must_use]
427 pub fn position(&self) -> HistoryPosition {
428 match self {
429 Self::Transaction(transaction) => HistoryPosition {
430 migration_id: transaction.migration_id,
431 record_time: transaction.record_time.clone(),
432 },
433 Self::Reassignment(reassignment) => HistoryPosition {
434 migration_id: match &reassignment.event {
435 ReassignmentEvent::Assignment(assignment) => assignment.migration_id,
436 ReassignmentEvent::Unassignment(unassignment) => unassignment.migration_id,
437 },
438 record_time: reassignment.record_time.clone(),
439 },
440 }
441 }
442
443 #[must_use]
445 pub fn update_id(&self) -> &str {
446 match self {
447 Self::Transaction(transaction) => &transaction.update_id,
448 Self::Reassignment(reassignment) => &reassignment.update_id,
449 }
450 }
451}
452
453impl<'de> Deserialize<'de> for ScanUpdate {
456 fn deserialize<D: serde::Deserializer<'de>>(
457 deserializer: D,
458 ) -> std::result::Result<Self, D::Error> {
459 use serde::de::Error as _;
460 let value = Value::deserialize(deserializer)?;
461 if value.get("events_by_id").is_some() {
462 serde_json::from_value(value)
463 .map(Self::Transaction)
464 .map_err(D::Error::custom)
465 } else if value.get("event").is_some() {
466 serde_json::from_value(value)
467 .map(Self::Reassignment)
468 .map_err(D::Error::custom)
469 } else {
470 Err(D::Error::custom(
471 "an update with neither `events_by_id` (a transaction) nor `event` (a \
472 reassignment)",
473 ))
474 }
475 }
476}
477
478#[derive(Clone, Debug, Deserialize)]
480#[non_exhaustive]
481pub struct ScanTransaction {
482 pub update_id: String,
484 pub migration_id: i64,
486 pub workflow_id: String,
488 pub record_time: String,
490 pub synchronizer_id: String,
492 pub effective_at: String,
494 pub root_event_ids: Vec<String>,
496 pub events_by_id: BTreeMap<String, ScanEvent>,
498 #[serde(default)]
501 pub external_transaction_hash: Option<String>,
502}
503
504#[derive(Clone, Debug, Deserialize)]
506#[serde(tag = "event_type")]
507#[non_exhaustive]
508pub enum ScanEvent {
509 #[serde(rename = "created_event")]
511 Created(ScanCreatedEvent),
512 #[serde(rename = "exercised_event")]
514 Exercised(ScanExercisedEvent),
515}
516
517#[derive(Clone, Debug, Deserialize)]
519#[non_exhaustive]
520pub struct ScanCreatedEvent {
521 pub event_id: String,
523 pub contract_id: String,
525 pub template_id: String,
527 pub package_name: String,
529 pub create_arguments: Value,
531 pub created_at: String,
533 pub signatories: Vec<String>,
535 pub observers: Vec<String>,
537}
538
539#[derive(Clone, Debug, Deserialize)]
541#[non_exhaustive]
542pub struct ScanExercisedEvent {
543 pub event_id: String,
545 pub contract_id: String,
547 pub template_id: String,
549 pub package_name: String,
551 pub choice: String,
553 pub choice_argument: Value,
555 pub child_event_ids: Vec<String>,
557 pub exercise_result: Value,
559 pub consuming: bool,
561 pub acting_parties: Vec<String>,
563 #[serde(default)]
565 pub interface_id: Option<String>,
566}
567
568#[derive(Clone, Debug, Deserialize)]
570#[non_exhaustive]
571pub struct ScanReassignment {
572 pub update_id: String,
574 pub offset: String,
577 pub record_time: String,
579 pub event: ReassignmentEvent,
581}
582
583#[derive(Clone, Debug)]
585#[non_exhaustive]
586pub enum ReassignmentEvent {
587 Assignment(ScanAssignment),
589 Unassignment(ScanUnassignment),
591}
592
593impl<'de> Deserialize<'de> for ReassignmentEvent {
596 fn deserialize<D: serde::Deserializer<'de>>(
597 deserializer: D,
598 ) -> std::result::Result<Self, D::Error> {
599 use serde::de::Error as _;
600 let value = Value::deserialize(deserializer)?;
601 if value.get("created_event").is_some() {
602 serde_json::from_value(value)
603 .map(Self::Assignment)
604 .map_err(D::Error::custom)
605 } else if value.get("contract_id").is_some() {
606 serde_json::from_value(value)
607 .map(Self::Unassignment)
608 .map_err(D::Error::custom)
609 } else {
610 Err(D::Error::custom(
611 "a reassignment event with neither `created_event` (an assignment) nor \
612 `contract_id` (an unassignment)",
613 ))
614 }
615 }
616}
617
618#[derive(Clone, Debug, Deserialize)]
620#[non_exhaustive]
621pub struct ScanAssignment {
622 pub submitter: String,
624 pub source_synchronizer: String,
626 pub target_synchronizer: String,
628 pub migration_id: i64,
630 pub unassign_id: String,
632 pub created_event: ScanCreatedEvent,
634 pub reassignment_counter: i64,
636}
637
638#[derive(Clone, Debug, Deserialize)]
640#[non_exhaustive]
641pub struct ScanUnassignment {
642 pub submitter: String,
644 pub source_synchronizer: String,
646 pub migration_id: i64,
648 pub target_synchronizer: String,
650 pub unassign_id: String,
652 pub reassignment_counter: i64,
654 pub contract_id: String,
656}
657
658#[derive(Clone, Debug, Deserialize)]
661#[non_exhaustive]
662pub struct ScanEventItem {
663 #[serde(default)]
666 pub update: Option<ScanUpdate>,
667 #[serde(default)]
669 pub verdict: Option<Value>,
670 #[serde(default)]
672 pub traffic_summary: Option<Value>,
673 #[serde(default)]
676 pub app_activity_records: Option<Value>,
677 #[serde(default)]
680 pub asset_activity_records: Option<Value>,
681 #[serde(default)]
684 pub submitting_app_provider: Option<String>,
685}
686
687impl ScanEventItem {
688 #[must_use]
693 pub fn position(&self) -> Option<HistoryPosition> {
694 if let Some(update) = &self.update {
695 return Some(update.position());
696 }
697 let verdict = self.verdict.as_ref()?;
698 Some(HistoryPosition {
699 migration_id: verdict.get("migration_id")?.as_i64()?,
700 record_time: verdict.get("record_time")?.as_str()?.to_string(),
701 })
702 }
703}
704
705#[derive(Clone, Debug)]
712pub struct SnapshotRequest {
713 migration_id: i64,
714 record_time: String,
715 at_or_before: bool,
716 after: Option<String>,
717 page_size: u32,
718 parties: Vec<String>,
719 templates: Vec<String>,
720}
721
722impl SnapshotRequest {
723 pub fn at(migration_id: i64, record_time: impl Into<String>) -> Self {
725 Self {
726 migration_id,
727 record_time: record_time.into(),
728 at_or_before: false,
729 after: None,
730 page_size: 100,
731 parties: Vec::new(),
732 templates: Vec::new(),
733 }
734 }
735
736 #[must_use]
739 pub fn at_or_before(mut self) -> Self {
740 self.at_or_before = true;
741 self
742 }
743
744 #[must_use]
746 pub fn with_page_size(mut self, page_size: u32) -> Self {
747 self.page_size = page_size;
748 self
749 }
750
751 #[must_use]
753 pub fn after(mut self, next_page_token: impl Into<String>) -> Self {
754 self.after = Some(next_page_token.into());
755 self
756 }
757
758 #[must_use]
761 pub fn for_parties<I, S>(mut self, parties: I) -> Self
762 where
763 I: IntoIterator<Item = S>,
764 S: Into<String>,
765 {
766 self.parties = parties.into_iter().map(Into::into).collect();
767 self
768 }
769
770 #[must_use]
773 pub fn for_templates<I, S>(mut self, templates: I) -> Self
774 where
775 I: IntoIterator<Item = S>,
776 S: Into<String>,
777 {
778 self.templates = templates.into_iter().map(Into::into).collect();
779 self
780 }
781
782 fn record_time_match(&self) -> &'static str {
783 if self.at_or_before {
784 "at_or_before"
785 } else {
786 "exact"
787 }
788 }
789
790 fn owners(&self, read: &str) -> Result<&[String]> {
791 if self.parties.is_empty() {
792 return Err(Error::InvalidRequest(format!(
793 "{read} needs at least one owner party (SnapshotRequest::for_parties)"
794 )));
795 }
796 Ok(&self.parties)
797 }
798}
799
800#[derive(Clone, Debug, Deserialize)]
802#[non_exhaustive]
803pub struct AcsSnapshot {
804 pub record_time: String,
806 pub migration_id: i64,
808 pub created_events: Vec<ActiveContract>,
810 #[serde(default)]
812 pub next_page_token: Option<String>,
813}
814
815#[derive(Clone, Debug, Deserialize)]
817#[non_exhaustive]
818pub struct ActiveContract {
819 #[serde(default)]
821 pub created_in_update_id: Option<String>,
822 pub contract_id: String,
824 pub template_id: String,
826 pub package_name: String,
828 pub create_arguments: Value,
830 pub created_at: String,
832 pub signatories: Vec<String>,
834 pub observers: Vec<String>,
836}
837
838#[derive(Clone, Debug, Deserialize)]
840#[non_exhaustive]
841pub struct HoldingsSummaries {
842 pub record_time: String,
844 pub migration_id: i64,
846 pub summaries: Vec<HoldingsSummary>,
848}
849
850#[derive(Clone, Debug, Deserialize)]
853#[non_exhaustive]
854pub struct HoldingsSummary {
855 pub party_id: String,
857 pub total_unlocked_coin: String,
859 pub total_locked_coin: String,
861 pub total_coin_holdings: String,
863}
864
865impl ScanClient {
866 pub fn new(base_url: &str) -> Result<Self> {
872 Self::with_http_client(base_url, default_http_client()?)
873 }
874
875 pub fn with_http_client(base_url: &str, http: reqwest::Client) -> Result<Self> {
884 Self::build(base_url, http, Route::Scan)
885 }
886
887 pub fn through_validator(base_url: &str) -> Result<Self> {
898 Self::through_validator_with_http_client(base_url, default_http_client()?)
899 }
900
901 pub fn through_validator_with_http_client(
907 base_url: &str,
908 http: reqwest::Client,
909 ) -> Result<Self> {
910 Self::build(base_url, http, Route::ScanProxy)
911 }
912
913 fn build(base_url: &str, http: reqwest::Client, route: Route) -> Result<Self> {
914 let normalised = format!("{}/", base_url.trim_end_matches('/'));
917 let base = reqwest::Url::parse(&normalised)
918 .map_err(|e| Error::InvalidRequest(format!("`{base_url}` is not a Scan URL: {e}")))?;
919 Ok(Self {
920 base,
921 http,
922 auth: Auth::None,
923 route,
924 internal_endpoints: false,
925 })
926 }
927
928 #[must_use]
931 pub fn with_token(mut self, token: impl Into<String>) -> Self {
932 self.auth = Auth::Static(token.into());
933 self
934 }
935
936 #[must_use]
939 pub fn with_token_source(mut self, source: impl TokenSource + 'static) -> Self {
940 self.auth = Auth::Dynamic(std::sync::Arc::new(source));
941 self
942 }
943
944 #[must_use]
955 pub fn with_internal_endpoints(mut self) -> Self {
956 self.internal_endpoints = true;
957 self
958 }
959
960 fn url(&self, version: &str, segments: &[&str]) -> Result<reqwest::Url> {
965 let mut url = self.base.clone();
966 {
967 let mut path = url.path_segments_mut().map_err(|()| {
968 Error::InvalidRequest("the Scan URL cannot have a path".to_string())
969 })?;
970 path.pop_if_empty().push(version);
971 if self.route == Route::ScanProxy {
972 path.push("scan-proxy");
973 }
974 path.extend(segments);
975 }
976 Ok(url)
977 }
978
979 fn scan_only(&self, read: &str) -> Result<()> {
981 if self.route == Route::ScanProxy {
982 return Err(Error::InvalidRequest(format!(
983 "a validator's scan-proxy does not serve {read}; ask a Scan for it \
984 (ScanClient::new)"
985 )));
986 }
987 Ok(())
988 }
989
990 fn internal(&self, read: &str) -> Result<()> {
992 if self.route == Route::Scan && !self.internal_endpoints {
993 return Err(Error::InvalidRequest(format!(
994 "{read} is an endpoint Scan tags internal, which Splice may change in any \
995 release; opt in with ScanClient::with_internal_endpoints(), or go through a \
996 validator's scan-proxy (ScanClient::through_validator), which serves it as \
997 part of its API"
998 )));
999 }
1000 Ok(())
1001 }
1002
1003 pub async fn dso_party_id(&self) -> Result<String> {
1009 #[derive(Deserialize)]
1010 struct Reply {
1011 dso_party_id: String,
1012 }
1013 let reply: Reply = self.get(self.url("v0", &["dso-party-id"])?).await?;
1014 Ok(reply.dso_party_id)
1015 }
1016
1017 pub async fn dso(&self) -> Result<DsoInfo> {
1027 match self.get(self.url("v1", &["dso"])?).await {
1028 Err(Error::Http { status: 404, .. }) => self.get(self.url("v0", &["dso"])?).await,
1029 answer => answer,
1030 }
1031 }
1032
1033 pub async fn scans(&self) -> Result<Vec<SynchronizerScans>> {
1040 #[derive(Deserialize)]
1041 struct Reply {
1042 scans: Vec<SynchronizerScans>,
1043 }
1044 self.scan_only("the list of Scans")?;
1045 let reply: Reply = self.get(self.url("v0", &["scans"])?).await?;
1046 Ok(reply.scans)
1047 }
1048
1049 pub async fn open_and_issuing_mining_rounds(&self) -> Result<MiningRounds> {
1054 #[derive(Serialize)]
1057 struct Cached {
1058 cached_open_mining_round_contract_ids: [String; 0],
1059 cached_issuing_round_contract_ids: [String; 0],
1060 }
1061 #[derive(Deserialize)]
1062 struct MaybeCached {
1063 #[serde(default)]
1064 contract: Option<ScanContract>,
1065 #[serde(default)]
1066 domain_id: Option<String>,
1067 }
1068 #[derive(Deserialize)]
1069 struct FromScan {
1070 open_mining_rounds: BTreeMap<String, MaybeCached>,
1071 issuing_mining_rounds: BTreeMap<String, MaybeCached>,
1072 }
1073 #[derive(Deserialize)]
1074 struct FromProxy {
1075 open_mining_rounds: Vec<ContractWithState>,
1076 issuing_mining_rounds: Vec<ContractWithState>,
1077 }
1078 fn all(rounds: BTreeMap<String, MaybeCached>) -> Result<Vec<ContractWithState>> {
1079 rounds
1080 .into_iter()
1081 .map(|(contract_id, round)| {
1082 let contract = round.contract.ok_or_else(|| {
1083 Error::UnexpectedResponse(format!(
1084 "Scan left out mining round `{contract_id}` as cached, where this \
1085 client told it nothing was"
1086 ))
1087 })?;
1088 Ok(ContractWithState {
1089 contract,
1090 synchronizer_id: round.domain_id,
1091 })
1092 })
1093 .collect()
1094 }
1095
1096 let url = self.url("v0", &["open-and-issuing-mining-rounds"])?;
1097 match self.route {
1098 Route::Scan => {
1099 let reply: FromScan = self
1100 .post(
1101 url,
1102 &Cached {
1103 cached_open_mining_round_contract_ids: [],
1104 cached_issuing_round_contract_ids: [],
1105 },
1106 )
1107 .await?;
1108 Ok(MiningRounds {
1109 open: all(reply.open_mining_rounds)?,
1110 issuing: all(reply.issuing_mining_rounds)?,
1111 })
1112 }
1113 Route::ScanProxy => {
1114 let reply: FromProxy = self.get(url).await?;
1115 Ok(MiningRounds {
1116 open: reply.open_mining_rounds,
1117 issuing: reply.issuing_mining_rounds,
1118 })
1119 }
1120 }
1121 }
1122
1123 pub async fn latest_open_mining_round(&self) -> Result<ContractWithState> {
1130 let rounds = self.open_and_issuing_mining_rounds().await?;
1131 let now = std::time::SystemTime::now()
1132 .duration_since(std::time::UNIX_EPOCH)
1133 .ok()
1134 .and_then(|since| i64::try_from(since.as_micros()).ok())
1135 .ok_or_else(|| {
1136 Error::InvalidRequest("the system clock is not a time after 1970".to_string())
1137 })?;
1138 rounds.latest_open(Timestamp(now)).cloned()
1139 }
1140
1141 pub async fn closed_rounds(&self) -> Result<Vec<ScanContract>> {
1146 #[derive(Deserialize)]
1147 struct Reply {
1148 rounds: Vec<ScanContract>,
1149 }
1150 self.scan_only("the closed mining rounds")?;
1151 let reply: Reply = self.get(self.url("v0", &["closed-rounds"])?).await?;
1152 Ok(reply.rounds)
1153 }
1154
1155 pub async fn amulet_rules(&self) -> Result<ContractWithState> {
1167 #[derive(Deserialize)]
1168 struct MaybeCached {
1169 #[serde(default)]
1170 contract: Option<ScanContract>,
1171 #[serde(default)]
1172 domain_id: Option<String>,
1173 }
1174 #[derive(Deserialize)]
1175 struct FromScan {
1176 amulet_rules_update: MaybeCached,
1177 }
1178 #[derive(Deserialize)]
1179 struct FromProxy {
1180 amulet_rules: ContractWithState,
1181 }
1182 if self.route == Route::Scan && !self.internal_endpoints {
1183 return Ok(self.dso().await?.amulet_rules);
1184 }
1185 let url = self.url("v0", &["amulet-rules"])?;
1186 match self.route {
1187 Route::Scan => {
1188 let reply: FromScan = self.post(url, &serde_json::json!({})).await?;
1191 let contract = reply.amulet_rules_update.contract.ok_or_else(|| {
1192 Error::UnexpectedResponse(
1193 "Scan left out the Amulet rules as cached, where this client told it \
1194 nothing was"
1195 .to_string(),
1196 )
1197 })?;
1198 Ok(ContractWithState {
1199 contract,
1200 synchronizer_id: reply.amulet_rules_update.domain_id,
1201 })
1202 }
1203 Route::ScanProxy => {
1204 let reply: FromProxy = self.get(url).await?;
1205 Ok(reply.amulet_rules)
1206 }
1207 }
1208 }
1209
1210 pub async fn featured_app_right(&self, provider: &str) -> Result<Option<ScanContract>> {
1223 #[derive(Deserialize)]
1224 struct Reply {
1225 #[serde(default)]
1226 featured_app_right: Option<ScanContract>,
1227 }
1228 self.internal("a featured application right")?;
1229 let reply: Reply = self
1230 .get(self.url("v0", &["featured-apps", provider])?)
1231 .await?;
1232 Ok(reply.featured_app_right)
1233 }
1234
1235 pub async fn transfer_preapproval_by_party(
1244 &self,
1245 party: &str,
1246 ) -> Result<Option<ContractWithState>> {
1247 #[derive(Deserialize)]
1248 struct Reply {
1249 transfer_preapproval: ContractWithState,
1250 }
1251 self.internal("a transfer preapproval")?;
1252 let url = self.url("v0", &["transfer-preapprovals", "by-party", party])?;
1253 let reply: Option<Reply> = self.get_optional(url).await?;
1254 Ok(reply.map(|reply| reply.transfer_preapproval))
1255 }
1256
1257 pub async fn member_traffic_status(
1263 &self,
1264 synchronizer_id: &str,
1265 member_id: &str,
1266 ) -> Result<TrafficStatus> {
1267 #[derive(Deserialize)]
1268 struct Reply {
1269 traffic_status: Status,
1270 }
1271 #[derive(Deserialize)]
1272 struct Status {
1273 actual: Actual,
1274 target: Target,
1275 }
1276 #[derive(Deserialize)]
1277 struct Actual {
1278 total_consumed: i64,
1279 total_limit: i64,
1280 }
1281 #[derive(Deserialize)]
1282 struct Target {
1283 total_purchased: i64,
1284 }
1285 self.scan_only("a member's traffic status")?;
1286 let url = self.url(
1287 "v0",
1288 &[
1289 "domains",
1290 synchronizer_id,
1291 "members",
1292 member_id,
1293 "traffic-status",
1294 ],
1295 )?;
1296 let reply: Reply = self.get(url).await?;
1297 Ok(TrafficStatus {
1298 total_consumed: reply.traffic_status.actual.total_consumed,
1299 total_limit: reply.traffic_status.actual.total_limit,
1300 total_purchased: reply.traffic_status.target.total_purchased,
1301 })
1302 }
1303
1304 pub async fn ans_entry_by_party(&self, party: &str) -> Result<Option<AnsEntry>> {
1309 self.ans_entry(&["ans-entries", "by-party", party]).await
1310 }
1311
1312 pub async fn ans_entry_by_name(&self, name: &str) -> Result<Option<AnsEntry>> {
1317 self.ans_entry(&["ans-entries", "by-name", name]).await
1318 }
1319
1320 async fn ans_entry(&self, segments: &[&str]) -> Result<Option<AnsEntry>> {
1321 #[derive(Deserialize)]
1322 struct Reply {
1323 entry: AnsEntry,
1324 }
1325 let reply: Option<Reply> = self.get_optional(self.url("v0", segments)?).await?;
1326 Ok(reply.map(|reply| reply.entry))
1327 }
1328
1329 pub async fn ans_entries(
1335 &self,
1336 name_prefix: Option<&str>,
1337 page_size: u32,
1338 ) -> Result<Vec<AnsEntry>> {
1339 #[derive(Deserialize)]
1340 struct Reply {
1341 entries: Vec<AnsEntry>,
1342 }
1343 let mut url = self.url("v0", &["ans-entries"])?;
1344 {
1345 let mut query = url.query_pairs_mut();
1346 if let Some(name_prefix) = name_prefix {
1347 query.append_pair("name_prefix", name_prefix);
1348 }
1349 query.append_pair("page_size", &page_size.to_string());
1350 }
1351 let reply: Reply = self.get(url).await?;
1352 Ok(reply.entries)
1353 }
1354
1355 pub async fn updates(
1366 &self,
1367 after: Option<&HistoryPosition>,
1368 page_size: u32,
1369 ) -> Result<Vec<ScanUpdate>> {
1370 #[derive(Deserialize)]
1371 struct Reply {
1372 transactions: Vec<ScanUpdate>,
1373 }
1374 self.scan_only("the update history")?;
1375 let reply: Reply = self
1376 .post(
1377 self.url("v2", &["updates"])?,
1378 &history_request(after, page_size)?,
1379 )
1380 .await?;
1381 Ok(reply.transactions)
1382 }
1383
1384 pub async fn update(&self, update_id: &str) -> Result<Option<ScanUpdate>> {
1389 self.scan_only("an update")?;
1390 self.get_optional(self.url("v2", &["updates", update_id])?)
1391 .await
1392 }
1393
1394 pub async fn events(
1403 &self,
1404 after: Option<&HistoryPosition>,
1405 page_size: u32,
1406 ) -> Result<Vec<ScanEventItem>> {
1407 #[derive(Deserialize)]
1408 struct Reply {
1409 events: Vec<ScanEventItem>,
1410 }
1411 self.scan_only("the event history")?;
1412 let reply: Reply = self
1413 .post(
1414 self.url("v0", &["events"])?,
1415 &history_request(after, page_size)?,
1416 )
1417 .await?;
1418 Ok(reply.events)
1419 }
1420
1421 pub async fn acs_snapshot_timestamp(
1428 &self,
1429 before: &str,
1430 migration_id: i64,
1431 ) -> Result<Option<String>> {
1432 #[derive(Deserialize)]
1433 struct Reply {
1434 record_time: String,
1435 }
1436 self.scan_only("the snapshot times")?;
1437 let mut url = self.url("v0", &["state", "acs", "snapshot-timestamp"])?;
1438 url.query_pairs_mut()
1439 .append_pair("before", before)
1440 .append_pair("migration_id", &migration_id.to_string());
1441 let reply: Option<Reply> = self.get_optional(url).await?;
1442 Ok(reply.map(|reply| reply.record_time))
1443 }
1444
1445 pub async fn acs_snapshot(&self, request: &SnapshotRequest) -> Result<AcsSnapshot> {
1454 self.scan_only("the snapshots of the active contracts")?;
1455 let mut body = serde_json::json!({
1456 "migration_id": request.migration_id,
1457 "record_time": request.record_time,
1458 "record_time_match": request.record_time_match(),
1459 "page_size": page_size(request.page_size)?,
1460 });
1461 if let Some(after) = &request.after {
1462 set(&mut body, "after", Value::from(after.as_str()));
1463 }
1464 if !request.parties.is_empty() {
1465 set(&mut body, "party_ids", Value::from(request.parties.clone()));
1466 }
1467 if !request.templates.is_empty() {
1468 set(
1469 &mut body,
1470 "templates",
1471 Value::from(request.templates.clone()),
1472 );
1473 }
1474 self.post(self.url("v2", &["state", "acs"])?, &body).await
1475 }
1476
1477 pub async fn holdings_state(&self, request: &SnapshotRequest) -> Result<AcsSnapshot> {
1485 self.scan_only("the holdings at a snapshot")?;
1486 let mut body = serde_json::json!({
1487 "migration_id": request.migration_id,
1488 "record_time": request.record_time,
1489 "record_time_match": request.record_time_match(),
1490 "page_size": page_size(request.page_size)?,
1491 "owner_party_ids": request.owners("a holdings read")?,
1492 });
1493 if let Some(after) = &request.after {
1494 set(&mut body, "after", Value::from(after.as_str()));
1495 }
1496 self.post(self.url("v2", &["holdings", "state"])?, &body)
1497 .await
1498 }
1499
1500 pub async fn holdings_summary(&self, request: &SnapshotRequest) -> Result<HoldingsSummaries> {
1508 let body = serde_json::json!({
1509 "migration_id": request.migration_id,
1510 "record_time": request.record_time,
1511 "record_time_match": request.record_time_match(),
1512 "owner_party_ids": request.owners("a holdings summary")?,
1513 });
1514 self.post(self.url("v1", &["holdings", "summary"])?, &body)
1515 .await
1516 }
1517
1518 pub async fn get_json(
1529 &self,
1530 version: &str,
1531 segments: &[&str],
1532 query: &[(&str, &str)],
1533 ) -> Result<Value> {
1534 let mut url = self.url(version, segments)?;
1535 if !query.is_empty() {
1536 url.query_pairs_mut().extend_pairs(query);
1537 }
1538 self.get(url).await
1539 }
1540
1541 pub async fn post_json(&self, version: &str, segments: &[&str], body: &Value) -> Result<Value> {
1547 self.post(self.url(version, segments)?, body).await
1548 }
1549
1550 async fn send(&self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> {
1552 let request = match self.auth.bearer().await? {
1553 Some(token) => request.bearer_auth(token),
1554 None => request,
1555 };
1556 request.send().await.map_err(|e| transport_error(e, SCAN))
1557 }
1558
1559 async fn get<T: serde::de::DeserializeOwned>(&self, url: reqwest::Url) -> Result<T> {
1560 let response = self.send(self.http.get(url.clone())).await?;
1561 decode(response, url.as_str()).await
1562 }
1563
1564 async fn post<T: serde::de::DeserializeOwned>(
1565 &self,
1566 url: reqwest::Url,
1567 body: &(impl Serialize + ?Sized),
1568 ) -> Result<T> {
1569 let response = self.send(self.http.post(url.clone()).json(body)).await?;
1570 decode(response, url.as_str()).await
1571 }
1572
1573 async fn get_optional<T: serde::de::DeserializeOwned>(
1580 &self,
1581 url: reqwest::Url,
1582 ) -> Result<Option<T>> {
1583 let response = self.send(self.http.get(url.clone())).await?;
1584 if response.status() == reqwest::StatusCode::NOT_FOUND {
1585 let body = read_error_body(response, url.as_str(), SCAN).await?;
1586 let trimmed = body.trim();
1587 if serde_json::from_str::<ErrorResponse>(trimmed).is_ok() {
1588 return Ok(None);
1589 }
1590 tracing::warn!(%url, "a 404 that is not Scan's own — check the base URL");
1591 return Err(Error::http_at(404, truncate(trimmed), url.as_str()));
1592 }
1593 Ok(Some(decode(response, url.as_str()).await?))
1594 }
1595}
1596
1597fn default_http_client() -> Result<reqwest::Client> {
1600 reqwest::Client::builder()
1601 .timeout(DEFAULT_TIMEOUT)
1602 .redirect(reqwest::redirect::Policy::none())
1603 .build()
1604 .map_err(|e| Error::InvalidRequest(format!("cannot build an HTTP client: {e}")))
1605}
1606
1607fn page_size(page_size: u32) -> Result<u32> {
1608 if page_size == 0 || page_size > MAX_PAGE_SIZE {
1609 return Err(Error::InvalidRequest(format!(
1610 "a page of {page_size} is not one Scan serves: it takes 1 to {MAX_PAGE_SIZE}"
1611 )));
1612 }
1613 Ok(page_size)
1614}
1615
1616fn set(object: &mut Value, key: &str, value: Value) {
1619 if let Some(fields) = object.as_object_mut() {
1620 fields.insert(key.to_string(), value);
1621 }
1622}
1623
1624fn history_request(after: Option<&HistoryPosition>, size: u32) -> Result<Value> {
1626 let mut body = serde_json::json!({ "page_size": page_size(size)? });
1627 if let Some(after) = after {
1628 let after = serde_json::to_value(after).map_err(|e| {
1629 Error::InvalidRequest(format!("a history position that is not JSON: {e}"))
1630 })?;
1631 set(&mut body, "after", after);
1632 }
1633 Ok(body)
1634}
1635
1636async fn decode<T: serde::de::DeserializeOwned>(
1639 response: reqwest::Response,
1640 url: &str,
1641) -> Result<T> {
1642 let status = response.status();
1643 let body = if status.is_success() {
1644 read_body_from(response, MAX_RESPONSE_BYTES, url, SCAN).await?
1645 } else {
1646 read_error_body(response, url, SCAN).await?
1647 };
1648 if !status.is_success() {
1649 tracing::warn!(%url, status = status.as_u16(), "Scan answered with an error");
1653 let message = serde_json::from_str::<ErrorResponse>(&body)
1654 .map(|e| e.error)
1655 .unwrap_or(body);
1656 return Err(Error::http_at(status.as_u16(), truncate(&message), url));
1657 }
1658 serde_json::from_str(&body).map_err(|e| {
1659 Error::UnexpectedResponse(format!(
1660 "{url} returned a body this does not understand: {e}"
1661 ))
1662 })
1663}
1664
1665#[cfg(test)]
1666#[allow(clippy::unwrap_used, clippy::expect_used)]
1667mod tests {
1668 use super::*;
1669
1670 fn contract(contract_id: &str, payload: Value) -> ContractWithState {
1671 ContractWithState {
1672 contract: ScanContract {
1673 template_id: "pkg:Splice.Round:OpenMiningRound".to_string(),
1674 contract_id: contract_id.to_string(),
1675 payload,
1676 created_event_blob: base64::engine::general_purpose::STANDARD.encode([1, 2, 3]),
1677 created_at: "2026-11-26T10:00:00Z".to_string(),
1678 },
1679 synchronizer_id: Some("global-domain::1220aa".to_string()),
1680 }
1681 }
1682
1683 fn round(number: i64, opens_at: &str) -> ContractWithState {
1684 contract(
1685 &format!("00round{number}"),
1686 serde_json::json!({
1687 "round": { "number": number.to_string() },
1688 "opensAt": opens_at,
1689 "targetClosesAt": "2026-11-26T12:00:00Z",
1690 }),
1691 )
1692 }
1693
1694 fn at(time: &str) -> Timestamp {
1695 serde_json::from_value(Value::from(time)).unwrap()
1696 }
1697
1698 #[test]
1702 fn the_latest_open_round_is_the_highest_one_whose_opening_time_has_come() {
1703 let rounds = MiningRounds {
1704 open: vec![
1705 round(11, "2026-11-26T10:10:00.000000Z"),
1706 round(10, "2026-11-26T10:00:00.000000Z"),
1707 round(12, "2026-11-26T10:20:00.000000Z"),
1708 ],
1709 issuing: Vec::new(),
1710 };
1711 let pick = |now: &str| {
1712 rounds
1713 .latest_open(at(now))
1714 .map(|round| round.contract.contract_id.clone())
1715 };
1716 assert_eq!(pick("2026-11-26T10:15:00Z").unwrap(), "00round11");
1717 assert_eq!(pick("2026-11-26T10:05:00Z").unwrap(), "00round10");
1718 assert_eq!(pick("2026-11-26T10:20:00Z").unwrap(), "00round12");
1720 assert_eq!(pick("2026-11-27T00:00:00Z").unwrap(), "00round12");
1721
1722 let error = pick("2026-11-26T09:00:00Z").unwrap_err();
1724 assert!(error.is_retriable(), "{error:?}");
1725 assert!(
1726 error.to_string().contains("3 open mining rounds"),
1727 "{error}"
1728 );
1729 }
1730
1731 #[test]
1734 fn round_numbers_compare_as_numbers_whether_written_as_text_or_not() {
1735 let mut as_number = round(9, "2026-11-26T09:50:00Z");
1736 as_number.contract.payload["round"]["number"] = Value::from(9);
1737 let rounds = MiningRounds {
1738 open: vec![round(10, "2026-11-26T10:00:00Z"), as_number],
1739 issuing: Vec::new(),
1740 };
1741 let latest = rounds.latest_open(at("2026-11-26T11:00:00Z")).unwrap();
1742 assert_eq!(latest.contract.contract_id, "00round10");
1743 }
1744
1745 #[test]
1746 fn a_round_that_is_not_an_open_mining_round_is_an_unexpected_response() {
1747 let rounds = MiningRounds {
1748 open: vec![contract("00odd", serde_json::json!({ "round": {} }))],
1749 issuing: Vec::new(),
1750 };
1751 let error = rounds.latest_open(at("2026-11-26T11:00:00Z")).unwrap_err();
1752 assert!(matches!(error, Error::UnexpectedResponse(_)), "{error:?}");
1753 assert!(error.to_string().contains("00odd"), "{error}");
1754 }
1755
1756 #[test]
1759 fn a_contract_is_disclosed_as_bytes_for_grpc_and_base64_for_json() {
1760 let rules = contract("00rules", serde_json::json!({}));
1761 let disclosed = rules.disclosed().unwrap();
1762 assert_eq!(disclosed.contract_id, "00rules");
1763 assert_eq!(disclosed.created_event_blob, [1, 2, 3]);
1764 assert_eq!(disclosed.synchronizer_id, "global-domain::1220aa");
1765 let template = disclosed.template_id.unwrap();
1766 assert_eq!(
1767 (
1768 template.package_id.as_str(),
1769 template.module_name.as_str(),
1770 template.entity_name.as_str()
1771 ),
1772 ("pkg", "Splice.Round", "OpenMiningRound")
1773 );
1774
1775 let json = rules.disclosed_json().unwrap();
1776 assert_eq!(json["createdEventBlob"], "AQID");
1777 assert_eq!(json["synchronizerId"], "global-domain::1220aa");
1778 assert_eq!(json["templateId"], "pkg:Splice.Round:OpenMiningRound");
1779 }
1780
1781 #[test]
1782 fn a_contract_that_cannot_be_disclosed_says_why() {
1783 let mut in_transit = contract("00moving", serde_json::json!({}));
1784 in_transit.synchronizer_id = None;
1785 let error = in_transit.disclosed().unwrap_err();
1786 assert!(error.is_retriable(), "{error:?}");
1787 assert!(in_transit.disclosed_json().is_err());
1788
1789 for template_id in ["pkg:Module", "pkg:Module:Entity:Extra", "::", ""] {
1790 let mut odd = contract("00odd", serde_json::json!({}));
1791 odd.contract.template_id = template_id.to_string();
1792 let error = odd.disclosed().unwrap_err();
1793 assert!(matches!(error, Error::UnexpectedResponse(_)), "{error:?}");
1794 }
1795
1796 let mut odd = contract("00blob", serde_json::json!({}));
1797 odd.contract.created_event_blob = "not base64!!".to_string();
1798 let error = odd.disclosed().unwrap_err();
1799 assert!(error.to_string().contains("00blob"), "{error}");
1800 }
1801
1802 #[test]
1805 fn updates_are_told_apart_by_their_fields() {
1806 let transaction: ScanUpdate = serde_json::from_value(serde_json::json!({
1807 "update_id": "1220tx",
1808 "migration_id": 4,
1809 "workflow_id": "",
1810 "record_time": "2026-11-26T10:00:00.000000Z",
1811 "synchronizer_id": "global-domain::1220aa",
1812 "effective_at": "2026-11-26T09:59:59.000000Z",
1813 "root_event_ids": ["1220tx:0"],
1814 "events_by_id": {
1815 "1220tx:0": {
1816 "event_type": "exercised_event",
1817 "event_id": "1220tx:0",
1818 "contract_id": "00rules",
1819 "template_id": "pkg:Splice.AmuletRules:AmuletRules",
1820 "package_name": "splice-amulet",
1821 "choice": "AmuletRules_Transfer",
1822 "choice_argument": {},
1823 "child_event_ids": ["1220tx:1"],
1824 "exercise_result": {},
1825 "consuming": false,
1826 "acting_parties": ["alice::1220"],
1827 },
1828 "1220tx:1": {
1829 "event_type": "created_event",
1830 "event_id": "1220tx:1",
1831 "contract_id": "00amulet",
1832 "template_id": "pkg:Splice.Amulet:Amulet",
1833 "package_name": "splice-amulet",
1834 "create_arguments": { "owner": "bob::1220" },
1835 "created_at": "2026-11-26T09:59:59.000000Z",
1836 "signatories": ["DSO::1220"],
1837 "observers": [],
1838 },
1839 },
1840 }))
1841 .unwrap();
1842 assert_eq!(transaction.update_id(), "1220tx");
1843 assert_eq!(
1844 transaction.position(),
1845 HistoryPosition {
1846 migration_id: 4,
1847 record_time: "2026-11-26T10:00:00.000000Z".to_string(),
1848 }
1849 );
1850 let ScanUpdate::Transaction(transaction) = transaction else {
1851 panic!("a transaction");
1852 };
1853 assert!(matches!(
1854 transaction.events_by_id["1220tx:0"],
1855 ScanEvent::Exercised(_)
1856 ));
1857 assert!(matches!(
1858 transaction.events_by_id["1220tx:1"],
1859 ScanEvent::Created(_)
1860 ));
1861
1862 let unassigned: ScanUpdate = serde_json::from_value(serde_json::json!({
1863 "update_id": "1220out",
1864 "offset": "000a",
1865 "record_time": "2026-11-26T10:01:00.000000Z",
1866 "event": {
1867 "submitter": "alice::1220",
1868 "source_synchronizer": "one::1220",
1869 "target_synchronizer": "two::1220",
1870 "migration_id": 5,
1871 "unassign_id": "u1",
1872 "reassignment_counter": 1,
1873 "contract_id": "00moving",
1874 },
1875 }))
1876 .unwrap();
1877 assert_eq!(unassigned.position().migration_id, 5);
1878 assert!(matches!(
1879 unassigned,
1880 ScanUpdate::Reassignment(ScanReassignment {
1881 event: ReassignmentEvent::Unassignment(_),
1882 ..
1883 })
1884 ));
1885
1886 let neither = serde_json::from_value::<ScanUpdate>(serde_json::json!({
1887 "update_id": "1220odd",
1888 }))
1889 .unwrap_err();
1890 assert!(neither.to_string().contains("events_by_id"), "{neither}");
1891 }
1892
1893 #[test]
1897 fn an_event_entry_has_a_position_with_or_without_an_update() {
1898 let rejected: ScanEventItem = serde_json::from_value(serde_json::json!({
1899 "update": null,
1900 "verdict": {
1901 "update_id": "1220rejected",
1902 "migration_id": 4,
1903 "domain_id": "global-domain::1220aa",
1904 "record_time": "2026-11-26T10:02:00.000000Z",
1905 "finalization_time": "2026-11-26T10:02:01.000000Z",
1906 "submitting_parties": ["alice::1220"],
1907 "submitting_participant_uid": "participant::1220",
1908 "verdict_result": "VERDICT_RESULT_REJECTED",
1909 "mediator_group": 0,
1910 "transaction_views": { "views": [], "root_views": [] },
1911 },
1912 "asset_activity_records": [],
1913 "submitting_app_provider": "provider::1220",
1914 }))
1915 .unwrap();
1916 assert!(rejected.update.is_none());
1917 assert_eq!(
1918 rejected.position(),
1919 Some(HistoryPosition {
1920 migration_id: 4,
1921 record_time: "2026-11-26T10:02:00.000000Z".to_string(),
1922 })
1923 );
1924 assert_eq!(
1925 rejected.submitting_app_provider.as_deref(),
1926 Some("provider::1220")
1927 );
1928 assert!(rejected.asset_activity_records.is_some());
1929
1930 let empty: ScanEventItem = serde_json::from_value(serde_json::json!({})).unwrap();
1931 assert_eq!(empty.position(), None);
1932 }
1933
1934 #[test]
1936 fn a_history_position_is_the_after_of_the_next_page() {
1937 let after = HistoryPosition {
1938 migration_id: 4,
1939 record_time: "2026-11-26T10:00:00.000000Z".to_string(),
1940 };
1941 assert_eq!(
1942 history_request(Some(&after), 50).unwrap(),
1943 serde_json::json!({
1944 "page_size": 50,
1945 "after": {
1946 "after_migration_id": 4,
1947 "after_record_time": "2026-11-26T10:00:00.000000Z",
1948 },
1949 })
1950 );
1951 assert_eq!(
1952 history_request(None, 1).unwrap(),
1953 serde_json::json!({ "page_size": 1 })
1954 );
1955 for size in [0, 1001] {
1956 let error = history_request(None, size).unwrap_err();
1957 assert!(matches!(error, Error::InvalidRequest(_)), "{error:?}");
1958 }
1959 }
1960}