Read-only mirror of github.com/smbcloudXYZ/smbcloud-ascapi.
Mirrored from https://github.com/smbcloudXYZ/smbcloud-ascapi.git
Synced Nov 25, 09:15 UTC
Add Play track promotion and Microsoft Store commit
asc play tracks promote copies a release from one track to another in one edit, as a staged rollout or at full reach, and reads the target back after the commit. commit_edit takes a changesNotSentForReview flag for apps with rejected changes pending. asc msstore submissions commit sends the pending submission to certification. It refuses when the expected package version is missing, treats an already committed submission as done, and waits for the status to leave CommitStarted. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Seto Elkahfi committed
Oct 28, 2026 at 19:04 UTC
0c14c7d7c338dc11ef168641b2bda82dd6bd5716
9 files changed
+586
-10
crates/cli/src/main.rs
+77
@@ -559,6 +559,26 @@ enum PlayTracksCommand {
559
#[arg(long)]
560
notes_file: Option<PathBuf>,
561
},
562
+ /// Promote a version code from one track to another, for example
563
+ /// internal to production, in one edit. A staged rollout is the default
564
+ /// shape: pass `--user-fraction 1.0` to release to everyone. With
565
+ /// `--dry-run` the edit is deleted and the planned track is printed.
566
+ Promote {
567
+ package: String,
568
+ #[arg(long)]
569
+ from: String,
570
+ #[arg(long)]
571
+ to: String,
572
+ #[arg(long)]
573
+ version_code: String,
574
+ /// Share of users to roll out to, above 0 and up to 1.0.
575
+ #[arg(long, default_value_t = 1.0)]
576
+ user_fraction: f64,
577
+ /// Commit with changesNotSentForReview, for apps that have rejected
578
+ /// changes pending.
579
+ #[arg(long)]
580
+ changes_not_sent_for_review: bool,
581
+ },
582
}
583
584
#[derive(Subcommand)]
@@ -597,6 +617,19 @@ enum MsStoreSubmissionsCommand {
617
#[arg(long)]
618
submission_id: Option<String>,
619
},
620
+ /// Send the pending submission to certification, then wait for the
621
+ /// status to leave CommitStarted. A submission already committed is a
622
+ /// no-op. With `--dry-run` the plan is printed and nothing is sent.
623
+ Commit {
624
+ #[arg(long)]
625
+ product_id: Option<String>,
626
+ /// Refuse unless a shipping package has this version, e.g. 1.3.2.0.
627
+ #[arg(long)]
628
+ expect_package_version: Option<String>,
629
+ /// How long to wait for the status to leave CommitStarted.
630
+ #[arg(long, default_value_t = 120)]
631
+ wait_seconds: u64,
632
+ },
633
}
634
635
#[derive(Subcommand)]
@@ -1045,6 +1078,25 @@ async fn run_msstore(
1078
.await
1079
.map_err(fail)?,
1080
),
1081
+ MsStoreSubmissionsCommand::Commit {
1082
+ product_id,
1083
+ expect_package_version,
1084
+ wait_seconds,
1085
+ } => {
1086
+ let result = msstore::commit_pending(
1087
+ &client,
1088
+ product_id.as_deref(),
1089
+ expect_package_version.as_deref(),
1090
+ wait_seconds,
1091
+ dry_run,
1092
+ )
1093
+ .await
1094
+ .map_err(fail)?;
1095
+ if result.dry_run {
1096
+ println!("# dry run: nothing was committed; plan:");
1097
+ }
1098
+ print_json(&result)
1099
+ }
1100
MsStoreSubmissionsCommand::Get {
1101
product_id,
1102
submission_id,
@@ -1220,6 +1272,31 @@ async fn run_play(
1272
}
1273
print_json(&result)
1274
}
1275
+ PlayTracksCommand::Promote {
1276
+ package,
1277
+ from,
1278
+ to,
1279
+ version_code,
1280
+ user_fraction,
1281
+ changes_not_sent_for_review,
1282
+ } => {
1283
+ let result = play::promote_track(
1284
+ &client,
1285
+ &package,
1286
+ &from,
1287
+ &to,
1288
+ &version_code,
1289
+ user_fraction,
1290
+ changes_not_sent_for_review,
1291
+ dry_run,
1292
+ )
1293
+ .await
1294
+ .map_err(fail)?;
1295
+ if result.dry_run {
1296
+ println!("# dry run: the edit was deleted; target track as it would be:");
1297
+ }
1298
+ print_json(&result)
1299
+ }
1300
},
1301
}
1302
}
crates/frontend/src/msstore.rs
+164
-2
@@ -4,8 +4,8 @@
4
//! to reuse it, never replace it: the pending submission may already hold the
5
//! uploaded package, so listing text is written into that one. Only when none
6
//! exists is a submission created (cloned from the last published one). A
7
-//! submission that is being processed or certified is never touched, and
8
-//! nothing here commits a submission to certification.
7
+//! submission that is being processed or certified is never touched. Only
8
+//! [`commit_pending`] sends a submission to certification.
9
10
use std::path::Path;
11
@@ -371,10 +371,172 @@ async fn write_and_verify(
371
Ok((changes, Some(after)))
372
}
373
374
+/// Statuses at or past the commit: the Store already has the submission, so a
375
+/// second commit would be refused.
376
+const PAST_COMMIT: [&str; 4] = ["CommitStarted", "PreProcessing", "Certification", "Release"];
377
+
378
+/// True when the submission has been committed, so committing again is a
379
+/// no-op.
380
+pub fn is_past_commit(status: &str) -> bool {
381
+ PAST_COMMIT.contains(&status)
382
+}
383
+
384
+/// Versions of the packages that will ship: every entry of
385
+/// `applicationPackages[]` whose `fileStatus` is not `PendingDelete`.
386
+pub fn package_versions(submission: &Value) -> Vec<String> {
387
+ submission
388
+ .get("applicationPackages")
389
+ .and_then(Value::as_array)
390
+ .map(|packages| {
391
+ packages
392
+ .iter()
393
+ .filter(|p| str_at(p, "/fileStatus") != Some("PendingDelete"))
394
+ .filter_map(|p| str_at(p, "/version").map(str::to_string))
395
+ .collect()
396
+ })
397
+ .unwrap_or_default()
398
+}
399
+
400
+/// The error messages of a status record, for a `...Failed` status.
401
+fn status_errors(status: &Value) -> Vec<String> {
402
+ status
403
+ .pointer("/statusDetails/errors")
404
+ .and_then(Value::as_array)
405
+ .map(|errors| {
406
+ errors
407
+ .iter()
408
+ .map(|e| {
409
+ let code = str_at(e, "/code").unwrap_or("");
410
+ let details = str_at(e, "/details").unwrap_or("");
411
+ format!("{code}: {details}")
412
+ })
413
+ .collect()
414
+ })
415
+ .unwrap_or_default()
416
+}
417
+
418
+#[derive(Debug, Serialize)]
419
+#[serde(rename_all = "camelCase")]
420
+pub struct Committed {
421
+ pub dry_run: bool,
422
+ /// The submission was already past the commit, so nothing was sent.
423
+ pub noop: bool,
424
+ pub submission_id: String,
425
+ pub package_versions: Vec<String>,
426
+ /// The status before this call.
427
+ pub status_before: String,
428
+ /// The status after the commit and the wait. `None` on a dry run or no-op.
429
+ pub status_after: Option<String>,
430
+}
431
+
432
+/// Commit the pending submission to certification.
433
+///
434
+/// Fails closed before writing when there is no pending submission or, with
435
+/// `expect_package_version`, when no shipping package has that version. A
436
+/// submission already committed is a no-op. After the commit the status is
437
+/// polled until it leaves `CommitStarted` or `wait_seconds` runs out; a status
438
+/// ending in `Failed` is an error carrying the status details.
439
+pub async fn commit_pending(
440
+ client: &MsStoreClient,
441
+ product_id: Option<&str>,
442
+ expect_package_version: Option<&str>,
443
+ wait_seconds: u64,
444
+ dry_run: bool,
445
+) -> Result<Committed, String> {
446
+ let product_id = product(client, product_id);
447
+ let app = client.get_app(product_id).await.map_err(err)?;
448
+ let id = str_at(&app, "/pendingApplicationSubmission/id")
449
+ .ok_or("the app has no pending submission to commit")?
450
+ .to_string();
451
+ let submission = client.get_submission(product_id, &id).await.map_err(err)?;
452
+ let versions = package_versions(&submission);
453
+ if let Some(expected) = expect_package_version {
454
+ if !versions.iter().any(|v| v == expected) {
455
+ return Err(format!(
456
+ "submission {id} carries package versions [{}], not {expected}; nothing was committed",
457
+ versions.join(", ")
458
+ ));
459
+ }
460
+ }
461
+ let status = client
462
+ .submission_status(product_id, &id)
463
+ .await
464
+ .map_err(err)?;
465
+ let before = str_at(&status, "/status").unwrap_or("").to_string();
466
+ let result = |noop, after| Committed {
467
+ dry_run,
468
+ noop,
469
+ submission_id: id.clone(),
470
+ package_versions: versions.clone(),
471
+ status_before: before.clone(),
472
+ status_after: after,
473
+ };
474
+ if is_past_commit(&before) {
475
+ return Ok(result(true, None));
476
+ }
477
+ if dry_run {
478
+ return Ok(result(false, None));
479
+ }
480
+ client
481
+ .commit_submission(product_id, &id)
482
+ .await
483
+ .map_err(err)?;
484
+
485
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(wait_seconds);
486
+ loop {
487
+ let status = client
488
+ .submission_status(product_id, &id)
489
+ .await
490
+ .map_err(err)?;
491
+ let current = str_at(&status, "/status").unwrap_or("").to_string();
492
+ if current.ends_with("Failed") {
493
+ return Err(format!(
494
+ "submission {id} is {current}: {}",
495
+ status_errors(&status).join("; ")
496
+ ));
497
+ }
498
+ if current != "CommitStarted" || std::time::Instant::now() >= deadline {
499
+ return Ok(result(false, Some(current)));
500
+ }
501
+ tokio::time::sleep(std::time::Duration::from_secs(3)).await;
502
+ }
503
+}
504
+
505
#[cfg(test)]
506
mod tests {
507
use super::*;
508
509
+ fn submission() -> Value {
510
+ serde_json::json!({"applicationPackages": [
511
+ {"fileName": "a.msix", "version": "1.3.1.0", "fileStatus": "PendingDelete"},
512
+ {"fileName": "b.msix", "version": "1.3.2.0", "fileStatus": "Uploaded"},
513
+ {"fileName": "c.msix", "version": "1.3.2.0"}
514
+ ]})
515
+ }
516
+
517
+ #[test]
518
+ fn package_versions_skip_packages_pending_delete() {
519
+ assert_eq!(package_versions(&submission()), vec!["1.3.2.0", "1.3.2.0"]);
520
+ assert!(package_versions(&serde_json::json!({})).is_empty());
521
+ }
522
+
523
+ #[test]
524
+ fn only_committed_statuses_are_past_commit() {
525
+ for s in ["CommitStarted", "PreProcessing", "Certification", "Release"] {
526
+ assert!(is_past_commit(s));
527
+ }
528
+ for s in ["PendingCommit", "CommitFailed", ""] {
529
+ assert!(!is_past_commit(s));
530
+ }
531
+ }
532
+
533
+ #[test]
534
+ fn failed_statuses_list_their_errors() {
535
+ let status = serde_json::json!({"status": "CommitFailed", "statusDetails": {"errors": [
536
+ {"code": "InvalidState", "details": "bad package"}]}});
537
+ assert_eq!(status_errors(&status), vec!["InvalidState: bad package"]);
538
+ }
539
+
540
#[test]
541
fn locked_statuses_cover_the_in_flight_states() {
542
for s in ["CommitStarted", "PreProcessing", "Certification"] {
crates/frontend/src/play.rs
+96
-3
@@ -59,12 +59,15 @@ fn err(error: impl std::fmt::Display) -> String {
59
/// the edit and returns the first error. A macro rather than a function so the
60
/// body can borrow from the caller's scope.
61
macro_rules! in_edit {
62
- ($client:expr, $package:expr, $commit:expr, |$c:ident, $id:ident| $body:expr) => {{
62
+ ($client:expr, $package:expr, $commit:expr, |$c:ident, $id:ident| $body:expr) => {
63
+ in_edit!($client, $package, $commit, false, |$c, $id| $body)
64
+ };
65
+ ($client:expr, $package:expr, $commit:expr, $unsent:expr, |$c:ident, $id:ident| $body:expr) => {{
66
let $c: &PlayClient = $client;
67
let edit = $c.insert_edit($package).await.map_err(err)?;
68
let $id: &str = edit.id.as_str();
69
let outcome: Result<_, String> = $body.await;
67
- finish($c, $package, $id, $commit, outcome).await
70
+ finish($c, $package, $id, $commit, $unsent, outcome).await
71
}};
72
}
73
@@ -73,13 +76,17 @@ async fn finish<T>(
76
package: &str,
77
edit_id: &str,
78
commit: bool,
79
+ changes_not_sent_for_review: bool,
80
outcome: Result<T, String>,
81
) -> Result<T, String> {
82
let outcome = match outcome {
83
Ok(value) if commit => {
84
async {
85
client.validate_edit(package, edit_id).await.map_err(err)?;
82
- client.commit_edit(package, edit_id).await.map_err(err)?;
86
+ client
87
+ .commit_edit(package, edit_id, changes_not_sent_for_review)
88
+ .await
89
+ .map_err(err)?;
90
Ok(value)
91
}
92
.await
@@ -365,6 +372,92 @@ pub async fn set_track_notes(
372
Ok(NotesSet { dry_run, track })
373
}
374
375
+#[derive(Debug, Serialize)]
376
+#[serde(rename_all = "camelCase")]
377
+pub struct Promoted {
378
+ pub dry_run: bool,
379
+ /// The target already held the code at this status and fraction.
380
+ pub noop: bool,
381
+ /// The source track as read.
382
+ pub from: Track,
383
+ /// The target track as it will be (dry run or no-op) or is (read back
384
+ /// after commit).
385
+ pub to: Track,
386
+}
387
+
388
+/// Promote `version_code` from one track to another inside one edit: get both
389
+/// tracks, plan, update the target, validate and commit. A dry run deletes the
390
+/// edit. After the commit the target is read back and compared.
391
+#[allow(clippy::too_many_arguments)]
392
+pub async fn promote_track(
393
+ client: &PlayClient,
394
+ package: &str,
395
+ from_track: &str,
396
+ to_track: &str,
397
+ version_code: &str,
398
+ user_fraction: f64,
399
+ changes_not_sent_for_review: bool,
400
+ dry_run: bool,
401
+) -> Result<Promoted, String> {
402
+ if from_track == to_track {
403
+ return Err("--from and --to are the same track".to_string());
404
+ }
405
+ let (from, plan) = in_edit!(
406
+ client,
407
+ package,
408
+ !dry_run,
409
+ changes_not_sent_for_review,
410
+ |c, id| {
411
+ Box::pin(async move {
412
+ let source = c.get_track(package, id, from_track).await.map_err(err)?;
413
+ let target = c.get_track(package, id, to_track).await.map_err(err)?;
414
+ let plan = target.promote_from(&source, version_code, user_fraction)?;
415
+ if !dry_run && !plan.noop {
416
+ c.update_track(package, id, &plan.target)
417
+ .await
418
+ .map_err(err)?;
419
+ }
420
+ Ok((source, plan))
421
+ })
422
+ }
423
+ )?;
424
+ if dry_run || plan.noop {
425
+ return Ok(Promoted {
426
+ dry_run,
427
+ noop: plan.noop,
428
+ from,
429
+ to: plan.target,
430
+ });
431
+ }
432
+ let stored = read_track(client, package, to_track).await?;
433
+ let full = user_fraction >= 1.0;
434
+ let landed = stored
435
+ .releases
436
+ .iter()
437
+ .filter(|r| r.version_codes.iter().any(|c| c == version_code))
438
+ .any(|r| {
439
+ if full {
440
+ r.status.as_deref() == Some("completed")
441
+ } else {
442
+ r.status.as_deref() == Some("inProgress")
443
+ && r.user_fraction
444
+ .is_some_and(|f| (f - user_fraction).abs() < 1e-9)
445
+ }
446
+ });
447
+ if !landed {
448
+ return Err(format!(
449
+ "committed, but {to_track} does not show version code {version_code} at the \
450
+ requested status and fraction"
451
+ ));
452
+ }
453
+ Ok(Promoted {
454
+ dry_run,
455
+ noop: false,
456
+ from,
457
+ to: stored,
458
+ })
459
+}
460
+
461
#[cfg(test)]
462
mod tests {
463
use super::*;
crates/msstore/README.md
+3
-1
@@ -17,4 +17,6 @@ let app = client.get_app(&product).await?;
17
18
Submissions are kept as `serde_json::Value`. Only the listing keys are
19
replaced, so packages, pricing and everything else round-trip untouched.
20
-Committing a submission to certification is deliberately not implemented.
20
+`MsStoreClient::commit_submission` sends the pending submission to
21
+certification; `asc msstore submissions commit` wraps it with a check of the
22
+uploaded package version and a wait for the status to leave `CommitStarted`.
crates/msstore/src/client.rs
+15
@@ -106,6 +106,17 @@ impl MsStoreClient {
106
.await
107
}
108
109
+ /// Commit the submission to certification:
110
+ /// `POST /v1.0/my/applications/{id}/submissions/{sid}/commit`.
111
+ pub async fn commit_submission(&self, product_id: &str, submission_id: &str) -> Result<Value> {
112
+ self.send(
113
+ Method::POST,
114
+ &app_path(product_id, &format!("/submissions/{submission_id}/commit")),
115
+ None,
116
+ )
117
+ .await
118
+ }
119
+
120
pub async fn delete_submission(&self, product_id: &str, submission_id: &str) -> Result<()> {
121
self.send(
122
Method::DELETE,
@@ -132,5 +143,9 @@ mod tests {
143
app_path("9P69", "/submissions/123/status"),
144
"/v1.0/my/applications/9P69/submissions/123/status"
145
);
146
+ assert_eq!(
147
+ app_path("9P69", "/submissions/123/commit"),
148
+ "/v1.0/my/applications/9P69/submissions/123/commit"
149
+ );
150
}
151
}
crates/msstore/src/lib.rs
+2
-1
@@ -5,7 +5,8 @@
5
//! and search terms. Authentication is Entra client credentials, cached until
6
//! shortly before the token expires. Submissions travel as
7
//! [`serde_json::Value`] so only the listing keys are touched and everything
8
-//! else round-trips. Committing a submission is not implemented.
8
+//! else round-trips. A submission is sent to certification with
9
+//! [`MsStoreClient::commit_submission`].
10
11
pub mod auth;
12
pub mod client;
crates/play/src/client.rs
+15
-2
@@ -123,8 +123,21 @@ impl PlayClient {
123
Ok(())
124
}
125
126
- pub async fn commit_edit(&self, package: &str, edit_id: &str) -> Result<()> {
127
- let path = edits_path(package, &format!("/{edit_id}:commit"));
126
+ /// Commit the edit. `changes_not_sent_for_review` is for apps with
127
+ /// rejected changes pending: Play then publishes without sending them
128
+ /// for review again.
129
+ pub async fn commit_edit(
130
+ &self,
131
+ package: &str,
132
+ edit_id: &str,
133
+ changes_not_sent_for_review: bool,
134
+ ) -> Result<()> {
135
+ let query = if changes_not_sent_for_review {
136
+ "?changesNotSentForReview=true"
137
+ } else {
138
+ ""
139
+ };
140
+ let path = edits_path(package, &format!("/{edit_id}:commit{query}"));
141
self.send(
142
Method::POST,
143
&path,
crates/play/src/lib.rs
+1
-1
@@ -22,4 +22,4 @@ pub use listing::{
22
Listing, ListingFields, FULL_DESCRIPTION_MAX_LEN, RELEASE_NOTES_MAX_LEN,
23
SHORT_DESCRIPTION_MAX_LEN, TITLE_MAX_LEN,
24
};
25
-pub use track::{LocalizedText, Track, TrackRelease};
25
+pub use track::{LocalizedText, PromotePlan, Track, TrackRelease};
crates/play/src/track.rs
+213
@@ -24,6 +24,10 @@ pub struct TrackRelease {
24
pub release_notes: Vec<LocalizedText>,
25
#[serde(default, skip_serializing_if = "Option::is_none")]
26
pub country_targeting: Option<serde_json::Value>,
27
+ /// Release fields this crate does not model, kept so an update sends
28
+ /// them back unchanged.
29
+ #[serde(flatten)]
30
+ pub extra: serde_json::Map<String, serde_json::Value>,
31
}
32
33
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -33,7 +37,108 @@ pub struct Track {
37
pub releases: Vec<TrackRelease>,
38
}
39
40
+/// What a promotion changes on the target track.
41
+#[derive(Debug, Clone, Serialize)]
42
+pub struct PromotePlan {
43
+ /// The target already holds the code at the requested status and
44
+ /// fraction, so there is nothing to write.
45
+ pub noop: bool,
46
+ /// The target track as it will be after the promotion.
47
+ pub target: Track,
48
+}
49
+
50
+const FRACTION_EPSILON: f64 = 1e-9;
51
+
52
impl Track {
53
+ /// Plan promoting `version_code` from `source` onto this (target) track.
54
+ ///
55
+ /// The new release copies the source release's name, version codes and
56
+ /// release notes. It is `inProgress` at `user_fraction` below 1.0 and
57
+ /// `completed` at 1.0. Any `inProgress` or `draft` release on the target
58
+ /// is replaced; `completed` releases stay, because Play needs the one
59
+ /// serving users during a staged rollout. A target already holding the
60
+ /// code at the same status and fraction is a no-op, a higher fraction
61
+ /// updates it, and a lower one is an error.
62
+ pub fn promote_from(
63
+ &self,
64
+ source: &Track,
65
+ version_code: &str,
66
+ user_fraction: f64,
67
+ ) -> std::result::Result<PromotePlan, String> {
68
+ if !(user_fraction > 0.0 && user_fraction <= 1.0) {
69
+ return Err(format!("user fraction {user_fraction} is outside (0, 1]"));
70
+ }
71
+ let from = source
72
+ .releases
73
+ .iter()
74
+ .find(|r| r.version_codes.iter().any(|c| c == version_code))
75
+ .ok_or_else(|| {
76
+ format!(
77
+ "no release on track {} carries version code {version_code}",
78
+ source.track
79
+ )
80
+ })?;
81
+ let full = user_fraction >= 1.0;
82
+ let release = TrackRelease {
83
+ name: from.name.clone(),
84
+ version_codes: from.version_codes.clone(),
85
+ status: Some(if full { "completed" } else { "inProgress" }.to_string()),
86
+ user_fraction: (!full).then_some(user_fraction),
87
+ release_notes: from.release_notes.clone(),
88
+ country_targeting: None,
89
+ extra: Default::default(),
90
+ };
91
+
92
+ if let Some(held) = self
93
+ .releases
94
+ .iter()
95
+ .find(|r| r.version_codes.iter().any(|c| c == version_code))
96
+ {
97
+ let held_full = held.status.as_deref() == Some("completed");
98
+ let held_fraction = if held_full {
99
+ 1.0
100
+ } else {
101
+ held.user_fraction.unwrap_or(0.0)
102
+ };
103
+ let rolling = matches!(
104
+ held.status.as_deref(),
105
+ Some("inProgress") | Some("completed")
106
+ );
107
+ if rolling {
108
+ if (held_fraction - user_fraction).abs() < FRACTION_EPSILON {
109
+ return Ok(PromotePlan {
110
+ noop: true,
111
+ target: self.clone(),
112
+ });
113
+ }
114
+ if user_fraction < held_fraction {
115
+ return Err(format!(
116
+ "track {} already serves version code {version_code} to {held_fraction}; a rollout cannot be lowered to {user_fraction}",
117
+ self.track
118
+ ));
119
+ }
120
+ }
121
+ }
122
+
123
+ let mut releases: Vec<TrackRelease> = self
124
+ .releases
125
+ .iter()
126
+ .filter(|r| {
127
+ !matches!(r.status.as_deref(), Some("inProgress") | Some("draft"))
128
+ && !r.version_codes.iter().any(|c| c == version_code)
129
+ })
130
+ .cloned()
131
+ .collect();
132
+ releases.insert(0, release);
133
+ Ok(PromotePlan {
134
+ noop: false,
135
+ target: Track {
136
+ track: self.track.clone(),
137
+ releases,
138
+ },
139
+ })
140
+ }
141
+
142
/// Set `locale`'s release notes on the release carrying `version_code`,
143
/// replacing any existing note for that language. Returns an error if no
144
/// release carries the code, or the text is over Play's limit.
@@ -114,4 +219,112 @@ mod tests {
219
assert_eq!(value["releases"][0]["status"], "draft");
220
assert_eq!(value["releases"][0]["name"], "1.2.0");
221
}
222
+
223
+ fn source() -> Track {
224
+ serde_json::from_str(
225
+ r#"{"track":"internal","releases":[{"name":"1.3.1","versionCodes":["131"],
226
+ "status":"completed","releaseNotes":[{"language":"en-US","text":"new"}]}]}"#,
227
+ )
228
+ .unwrap()
229
+ }
230
+
231
+ fn production(release: &str) -> Track {
232
+ serde_json::from_str(&format!(
233
+ r#"{{"track":"production","releases":[{release}]}}"#
234
+ ))
235
+ .unwrap()
236
+ }
237
+
238
+ const LIVE: &str = r#"{"name":"1.3.0","versionCodes":["130"],"status":"completed",
239
+ "countryTargeting":{"includeRestOfWorld":true},"inAppUpdatePriority":3}"#;
240
+
241
+ #[test]
242
+ fn promoting_adds_a_staged_release_and_keeps_the_live_one() {
243
+ let plan = production(LIVE)
244
+ .promote_from(&source(), "131", 0.2)
245
+ .unwrap();
246
+ assert!(!plan.noop);
247
+ let r = &plan.target.releases;
248
+ assert_eq!(r.len(), 2);
249
+ assert_eq!(r[0].status.as_deref(), Some("inProgress"));
250
+ assert_eq!(r[0].user_fraction, Some(0.2));
251
+ assert_eq!(r[0].name.as_deref(), Some("1.3.1"));
252
+ assert_eq!(r[0].release_notes[0].text, "new");
253
+ assert_eq!(r[1].status.as_deref(), Some("completed"));
254
+ }
255
+
256
+ #[test]
257
+ fn the_same_code_at_the_same_fraction_is_a_noop() {
258
+ let held =
259
+ r#"{"name":"1.3.1","versionCodes":["131"],"status":"inProgress","userFraction":0.2}"#;
260
+ let plan = production(held)
261
+ .promote_from(&source(), "131", 0.2)
262
+ .unwrap();
263
+ assert!(plan.noop);
264
+ }
265
+
266
+ #[test]
267
+ fn a_higher_fraction_updates_the_rollout() {
268
+ let held =
269
+ r#"{"name":"1.3.1","versionCodes":["131"],"status":"inProgress","userFraction":0.2}"#;
270
+ let plan = production(held)
271
+ .promote_from(&source(), "131", 0.5)
272
+ .unwrap();
273
+ assert!(!plan.noop);
274
+ assert_eq!(plan.target.releases.len(), 1);
275
+ assert_eq!(plan.target.releases[0].user_fraction, Some(0.5));
276
+ }
277
+
278
+ #[test]
279
+ fn a_lower_fraction_is_an_error() {
280
+ let held =
281
+ r#"{"name":"1.3.1","versionCodes":["131"],"status":"inProgress","userFraction":0.5}"#;
282
+ assert!(production(held)
283
+ .promote_from(&source(), "131", 0.2)
284
+ .is_err());
285
+ }
286
+
287
+ #[test]
288
+ fn a_fraction_of_one_completes_the_release() {
289
+ let plan = production(LIVE)
290
+ .promote_from(&source(), "131", 1.0)
291
+ .unwrap();
292
+ let first = &plan.target.releases[0];
293
+ assert_eq!(first.status.as_deref(), Some("completed"));
294
+ assert_eq!(first.user_fraction, None);
295
+ }
296
+
297
+ #[test]
298
+ fn a_draft_on_the_target_is_replaced() {
299
+ let draft = r#"{"name":"old","versionCodes":["129"],"status":"draft"}"#;
300
+ let t = production(&format!("{LIVE},{draft}"));
301
+ let plan = t.promote_from(&source(), "131", 0.2).unwrap();
302
+ assert_eq!(plan.target.releases.len(), 2);
303
+ assert!(plan
304
+ .target
305
+ .releases
306
+ .iter()
307
+ .all(|r| r.name.as_deref() != Some("old")));
308
+ }
309
+
310
+ #[test]
311
+ fn an_unknown_code_or_bad_fraction_is_an_error() {
312
+ let t = production(LIVE);
313
+ assert!(t.promote_from(&source(), "999", 0.2).is_err());
314
+ assert!(t.promote_from(&source(), "131", 0.0).is_err());
315
+ assert!(t.promote_from(&source(), "131", 1.5).is_err());
316
+ }
317
+
318
+ #[test]
319
+ fn unknown_fields_on_kept_releases_survive() {
320
+ let plan = production(LIVE)
321
+ .promote_from(&source(), "131", 0.2)
322
+ .unwrap();
323
+ let value = serde_json::to_value(&plan.target).unwrap();
324
+ assert_eq!(value["releases"][1]["inAppUpdatePriority"], 3);
325
+ assert_eq!(
326
+ value["releases"][1]["countryTargeting"]["includeRestOfWorld"],
327
+ true
328
+ );
329
+ }
330
}