cirrus-metadata 0.1.0

Salesforce Metadata API (SOAP) client for the Cirrus SDK.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
//! Wiremock-backed tests for the file-based deploy/retrieve handlers.
//!
//! Each test pins down one operation's wire shape:
//!
//! - the SOAP request body Salesforce should see, and
//! - the response envelope shape we parse into typed results.
//!
//! Response fixtures are modeled after the documented examples in the
//! Metadata API Developer Guide; field coverage is deliberately
//! generous so we exercise as much of the typed envelope surface as
//! possible.

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use bytes::Bytes;
use cirrus_metadata::auth::StaticTokenAuth;
use cirrus_metadata::{
    DeployOptions, DeployStatus, MetadataClient, MetadataError, MetadataType, PackageManifest,
    RetrieveRequest, RetrieveStatus, RetryPolicy, TestLevel, WaitConfig,
};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use wiremock::matchers::{body_string_contains, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

// -- Helpers -----------------------------------------------------------------

fn xml_response(body: &str) -> ResponseTemplate {
    ResponseTemplate::new(200)
        .insert_header("content-type", "text/xml; charset=UTF-8")
        .set_body_string(body.to_string())
}

fn client_against(server: &MockServer) -> MetadataClient {
    let auth = Arc::new(StaticTokenAuth::new("tok", server.uri()));
    MetadataClient::builder()
        .auth(auth)
        .retry_policy(RetryPolicy {
            base_delay: Duration::from_millis(1),
            max_delay: Duration::from_millis(5),
            jitter: false,
            ..RetryPolicy::default()
        })
        .build()
        .unwrap()
}

// -- deploy ------------------------------------------------------------------

#[tokio::test]
async fn deploy_sends_zip_base64_and_returns_async_result() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/services/Soap/m/66.0"))
        // Base64 of "PKzip" is "UEt6aXA=" — assert the bytes were
        // base64-encoded before going on the wire.
        .and(body_string_contains("<met:ZipFile>UEt6aXA="))
        .and(body_string_contains("<met:checkOnly>true</met:checkOnly>"))
        .and(body_string_contains(
            "<met:testLevel>RunLocalTests</met:testLevel>",
        ))
        .respond_with(xml_response(
            r#"<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <deployResponse xmlns="http://soap.sforce.com/2006/04/metadata">
      <result>
        <done>false</done>
        <id>0Af00000abcDEF</id>
        <state>Queued</state>
      </result>
    </deployResponse>
  </soapenv:Body>
</soapenv:Envelope>"#,
        ))
        .mount(&server)
        .await;

    let md = client_against(&server);
    let opts = DeployOptions {
        check_only: Some(true),
        test_level: Some(TestLevel::RunLocalTests),
        ..Default::default()
    };
    let result = md.deploy(Bytes::from_static(b"PKzip"), opts).await.unwrap();
    assert_eq!(result.id, "0Af00000abcDEF");
    assert!(!result.done);
}

// -- check_deploy_status -----------------------------------------------------

#[tokio::test]
async fn check_deploy_status_parses_full_deploy_result() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(body_string_contains("<met:checkDeployStatus>"))
        .and(body_string_contains(
            "<met:asyncProcessId>0Af00000abcDEF</met:asyncProcessId>",
        ))
        .and(body_string_contains(
            "<met:includeDetails>true</met:includeDetails>",
        ))
        .respond_with(xml_response(
            r#"<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <checkDeployStatusResponse xmlns="http://soap.sforce.com/2006/04/metadata">
      <result>
        <id>0Af00000abcDEF</id>
        <done>true</done>
        <success>true</success>
        <status>Succeeded</status>
        <checkOnly>false</checkOnly>
        <ignoreWarnings>false</ignoreWarnings>
        <rollbackOnError>true</rollbackOnError>
        <runTestsEnabled>true</runTestsEnabled>
        <numberComponentsDeployed>10</numberComponentsDeployed>
        <numberComponentsTotal>10</numberComponentsTotal>
        <numberComponentErrors>0</numberComponentErrors>
        <numberTestsCompleted>5</numberTestsCompleted>
        <numberTestsTotal>5</numberTestsTotal>
        <numberTestErrors>0</numberTestErrors>
        <createdBy>005xx00000abcde</createdBy>
        <createdByName>Stephanie</createdByName>
        <createdDate>2026-05-28T10:00:00.000Z</createdDate>
        <startDate>2026-05-28T10:00:05.000Z</startDate>
        <completedDate>2026-05-28T10:01:00.000Z</completedDate>
        <details>
          <componentSuccesses>
            <componentType>ApexClass</componentType>
            <fullName>Foo</fullName>
            <fileName>classes/Foo.cls</fileName>
            <success>true</success>
            <changed>false</changed>
            <created>true</created>
            <deleted>false</deleted>
          </componentSuccesses>
          <runTestResult>
            <numTestsRun>5</numTestsRun>
            <numFailures>0</numFailures>
            <totalTime>1234.5</totalTime>
          </runTestResult>
        </details>
      </result>
    </checkDeployStatusResponse>
  </soapenv:Body>
</soapenv:Envelope>"#,
        ))
        .mount(&server)
        .await;

    let md = client_against(&server);
    let result = md
        .check_deploy_status("0Af00000abcDEF", true)
        .await
        .unwrap();
    assert!(result.done);
    assert!(result.success);
    assert_eq!(result.status, Some(DeployStatus::Succeeded));
    assert_eq!(result.number_components_deployed, 10);
    let details = result.details.unwrap();
    assert_eq!(details.component_successes.len(), 1);
    assert_eq!(details.component_successes[0].full_name, Some("Foo".into()));
    let test_result = details.run_test_result.unwrap();
    assert_eq!(test_result.num_tests_run, 5);
    assert_eq!(test_result.total_time, 1234.5);
}

#[tokio::test]
async fn check_deploy_status_parses_failure_details() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .respond_with(xml_response(
            r#"<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <checkDeployStatusResponse xmlns="http://soap.sforce.com/2006/04/metadata">
      <result>
        <id>0Af00000bad</id>
        <done>true</done>
        <success>false</success>
        <status>Failed</status>
        <numberComponentErrors>2</numberComponentErrors>
        <details>
          <componentFailures>
            <componentType>ApexClass</componentType>
            <fullName>BrokenClass</fullName>
            <fileName>classes/BrokenClass.cls</fileName>
            <success>false</success>
            <problem>Unexpected token 'foo'</problem>
            <problemType>Error</problemType>
            <lineNumber>42</lineNumber>
            <columnNumber>13</columnNumber>
          </componentFailures>
          <componentFailures>
            <componentType>ApexClass</componentType>
            <fullName>BrokenTwo</fullName>
            <fileName>classes/BrokenTwo.cls</fileName>
            <success>false</success>
            <problem>Method does not exist</problem>
            <problemType>Error</problemType>
          </componentFailures>
        </details>
      </result>
    </checkDeployStatusResponse>
  </soapenv:Body>
</soapenv:Envelope>"#,
        ))
        .mount(&server)
        .await;

    let md = client_against(&server);
    let result = md.check_deploy_status("0Af00000bad", true).await.unwrap();
    assert!(!result.success);
    assert_eq!(result.status, Some(DeployStatus::Failed));
    let details = result.details.unwrap();
    assert_eq!(details.component_failures.len(), 2);
    let first = &details.component_failures[0];
    assert_eq!(first.full_name, Some("BrokenClass".into()));
    assert_eq!(first.problem, Some("Unexpected token 'foo'".into()));
    assert_eq!(first.line_number, Some(42));
    assert_eq!(first.column_number, Some(13));
}

// -- cancel_deploy -----------------------------------------------------------

#[tokio::test]
async fn cancel_deploy_round_trip() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(body_string_contains("<met:cancelDeploy>"))
        .and(body_string_contains(
            "<met:asyncProcessId>0Af00000abc</met:asyncProcessId>",
        ))
        .respond_with(xml_response(
            r#"<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <cancelDeployResponse xmlns="http://soap.sforce.com/2006/04/metadata">
      <result>
        <id>0Af00000abc</id>
        <done>true</done>
      </result>
    </cancelDeployResponse>
  </soapenv:Body>
</soapenv:Envelope>"#,
        ))
        .mount(&server)
        .await;

    let md = client_against(&server);
    let result = md.cancel_deploy("0Af00000abc").await.unwrap();
    assert_eq!(result.id, "0Af00000abc");
    assert!(result.done);
}

// -- deploy_recent_validation ------------------------------------------------

#[tokio::test]
async fn deploy_recent_validation_returns_new_deploy_id() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(body_string_contains("<met:deployRecentValidation>"))
        .and(body_string_contains(
            "<met:validationId>0Af00000valid</met:validationId>",
        ))
        .respond_with(xml_response(
            r#"<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <deployRecentValidationResponse xmlns="http://soap.sforce.com/2006/04/metadata">
      <result>0Af00000NEWdep</result>
    </deployRecentValidationResponse>
  </soapenv:Body>
</soapenv:Envelope>"#,
        ))
        .mount(&server)
        .await;

    let md = client_against(&server);
    let new_id = md.deploy_recent_validation("0Af00000valid").await.unwrap();
    assert_eq!(new_id, "0Af00000NEWdep");
}

// -- retrieve ----------------------------------------------------------------

#[tokio::test]
async fn retrieve_sends_unpackaged_manifest_and_returns_async_result() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(body_string_contains("<met:retrieve>"))
        .and(body_string_contains("<met:RetrieveRequest>"))
        .and(body_string_contains(
            "<met:apiVersion>66.0</met:apiVersion>",
        ))
        .and(body_string_contains("<met:members>MyClass</met:members>"))
        .and(body_string_contains("<met:name>ApexClass</met:name>"))
        .respond_with(xml_response(
            r#"<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <retrieveResponse xmlns="http://soap.sforce.com/2006/04/metadata">
      <result>
        <done>false</done>
        <id>09S00000retrId</id>
        <state>Queued</state>
      </result>
    </retrieveResponse>
  </soapenv:Body>
</soapenv:Envelope>"#,
        ))
        .mount(&server)
        .await;

    let md = client_against(&server);
    let req = RetrieveRequest {
        api_version: "66.0".into(),
        single_package: true,
        unpackaged: Some(PackageManifest::new("66.0").add(MetadataType::APEX_CLASS, ["MyClass"])),
        ..Default::default()
    };
    let result = md.retrieve(req).await.unwrap();
    assert_eq!(result.id, "09S00000retrId");
}

// -- check_retrieve_status ---------------------------------------------------

#[tokio::test]
async fn check_retrieve_status_decodes_zip_bytes() {
    let server = MockServer::start().await;

    // Base64 of "PKfakezipbytes" — stand-in for an actual zip.
    let zip_b64 = "UEtmYWtlemlwYnl0ZXM=";

    Mock::given(method("POST"))
        .and(body_string_contains("<met:checkRetrieveStatus>"))
        .and(body_string_contains(
            "<met:includeZip>true</met:includeZip>",
        ))
        .respond_with(xml_response(&format!(
            r#"<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <checkRetrieveStatusResponse xmlns="http://soap.sforce.com/2006/04/metadata">
      <result>
        <id>09S00000retrId</id>
        <done>true</done>
        <success>true</success>
        <status>Succeeded</status>
        <fileProperties>
          <createdById>005xx0000</createdById>
          <createdByName>Stephanie</createdByName>
          <createdDate>2026-05-28T10:00:00.000Z</createdDate>
          <fileName>unpackaged/classes/MyClass.cls</fileName>
          <fullName>MyClass</fullName>
          <id>01p00000abc</id>
          <lastModifiedById>005xx0000</lastModifiedById>
          <lastModifiedByName>Stephanie</lastModifiedByName>
          <lastModifiedDate>2026-05-28T10:00:00.000Z</lastModifiedDate>
          <type>ApexClass</type>
        </fileProperties>
        <zipFile>{zip_b64}</zipFile>
      </result>
    </checkRetrieveStatusResponse>
  </soapenv:Body>
</soapenv:Envelope>"#
        )))
        .mount(&server)
        .await;

    let md = client_against(&server);
    let result = md
        .check_retrieve_status("09S00000retrId", true)
        .await
        .unwrap();
    assert!(result.done);
    assert!(result.success);
    assert_eq!(result.status, Some(RetrieveStatus::Succeeded));
    assert_eq!(result.file_properties.len(), 1);
    assert_eq!(result.file_properties[0].full_name, "MyClass");
    assert_eq!(
        result.file_properties[0].type_name,
        Some("ApexClass".into())
    );
    let zip = result.zip_bytes().unwrap().unwrap();
    assert_eq!(&zip[..], b"PKfakezipbytes");
}

// -- wait_for_deploy ---------------------------------------------------------

#[tokio::test]
async fn wait_for_deploy_polls_until_done() {
    let server = MockServer::start().await;

    // Hand-rolled call counter so the first two polls return InProgress
    // and the third returns Succeeded. wiremock's `up_to_n_times`
    // composes awkwardly with two paired Mocks; an AtomicUsize-keyed
    // matcher keeps the test readable.
    let counter = Arc::new(AtomicUsize::new(0));

    Mock::given(method("POST"))
        .and(body_string_contains("<met:checkDeployStatus>"))
        .respond_with({
            let counter = counter.clone();
            move |_: &wiremock::Request| {
                let n = counter.fetch_add(1, Ordering::SeqCst);
                let (done, status) = if n < 2 {
                    ("false", "InProgress")
                } else {
                    ("true", "Succeeded")
                };
                ResponseTemplate::new(200)
                    .insert_header("content-type", "text/xml; charset=UTF-8")
                    .set_body_string(format!(
                        r#"<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <checkDeployStatusResponse xmlns="http://soap.sforce.com/2006/04/metadata">
      <result>
        <id>0Af00000poll</id>
        <done>{done}</done>
        <success>true</success>
        <status>{status}</status>
      </result>
    </checkDeployStatusResponse>
  </soapenv:Body>
</soapenv:Envelope>"#
                    ))
            }
        })
        .mount(&server)
        .await;

    let md = client_against(&server);
    let result = md
        .wait_for_deploy_with(
            "0Af00000poll",
            WaitConfig {
                // Keep tests fast; the helper still exercises the
                // backoff doubling and clamping.
                initial_delay: Duration::from_millis(1),
                max_delay: Duration::from_millis(5),
                total_timeout: None,
            },
        )
        .await
        .unwrap();

    assert_eq!(result.status, Some(DeployStatus::Succeeded));
    // 3 intermediate polls (InProgress, InProgress, Succeeded) plus 1
    // final include_details=true fetch once the deploy reached a
    // terminal state — the polling loop deliberately skips details on
    // intermediate iterations because the response grows with every
    // processed component on large deploys.
    assert_eq!(counter.load(Ordering::SeqCst), 4);
}

#[tokio::test]
async fn wait_for_deploy_times_out_when_never_done() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(body_string_contains("<met:checkDeployStatus>"))
        .respond_with(xml_response(
            r#"<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <checkDeployStatusResponse xmlns="http://soap.sforce.com/2006/04/metadata">
      <result>
        <id>0Af00000slow</id>
        <done>false</done>
        <status>InProgress</status>
      </result>
    </checkDeployStatusResponse>
  </soapenv:Body>
</soapenv:Envelope>"#,
        ))
        .mount(&server)
        .await;

    let md = client_against(&server);
    let err = md
        .wait_for_deploy_with(
            "0Af00000slow",
            WaitConfig {
                initial_delay: Duration::from_millis(1),
                max_delay: Duration::from_millis(2),
                total_timeout: Some(Duration::from_millis(10)),
            },
        )
        .await
        .unwrap_err();
    assert!(matches!(err, MetadataError::PollTimeout(_)));
    assert!(err.to_string().contains("timed out"));
}

// -- wait_for_retrieve -------------------------------------------------------

#[tokio::test]
async fn wait_for_retrieve_returns_final_result_with_zip() {
    let server = MockServer::start().await;
    let counter = Arc::new(AtomicUsize::new(0));

    Mock::given(method("POST"))
        .and(body_string_contains("<met:checkRetrieveStatus>"))
        .respond_with({
            let counter = counter.clone();
            move |_: &wiremock::Request| {
                let n = counter.fetch_add(1, Ordering::SeqCst);
                let body = if n == 0 {
                    r#"<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <checkRetrieveStatusResponse xmlns="http://soap.sforce.com/2006/04/metadata">
      <result>
        <id>09S00000poll</id>
        <done>false</done>
        <status>InProgress</status>
      </result>
    </checkRetrieveStatusResponse>
  </soapenv:Body>
</soapenv:Envelope>"#
                        .to_string()
                } else {
                    r#"<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <checkRetrieveStatusResponse xmlns="http://soap.sforce.com/2006/04/metadata">
      <result>
        <id>09S00000poll</id>
        <done>true</done>
        <success>true</success>
        <status>Succeeded</status>
        <zipFile>UEt6aXA=</zipFile>
      </result>
    </checkRetrieveStatusResponse>
  </soapenv:Body>
</soapenv:Envelope>"#
                        .to_string()
                };
                ResponseTemplate::new(200)
                    .insert_header("content-type", "text/xml; charset=UTF-8")
                    .set_body_string(body)
            }
        })
        .mount(&server)
        .await;

    let md = client_against(&server);
    let result = md
        .wait_for_retrieve_with(
            "09S00000poll",
            WaitConfig {
                initial_delay: Duration::from_millis(1),
                max_delay: Duration::from_millis(5),
                total_timeout: None,
            },
        )
        .await
        .unwrap();
    assert!(result.done);
    let zip = result.zip_bytes().unwrap().unwrap();
    assert_eq!(&zip[..], b"PKzip");
    assert_eq!(counter.load(Ordering::SeqCst), 2);
}