cirrus 0.3.0

An ergonomic Rust HTTP client for the Salesforce REST API.
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! Bulk API 2.0 — async, CSV-driven ingest and query operations.
//!
//! Two flavors live under `/services/data/{version}/jobs/`:
//!
//! - **Ingest** (`/jobs/ingest`) — create / update / upsert / delete /
//!   hardDelete records in batches of up to 150 MB / 10k+ records per
//!   job. The caller drives the job through `Open` → `UploadComplete` →
//!   `InProgress` → `JobComplete` / `Failed` / `Aborted`. Reach via
//!   [`BulkHandler::ingest`].
//! - **Query** (`/jobs/query`) — async SOQL execution that streams
//!   results as CSV with cursor-based pagination. Reach via
//!   [`BulkHandler::query`].
//!
//! # CSV transport
//!
//! Bulk 2.0 is the only Salesforce REST surface that uses `text/csv`
//! bodies (not JSON). Upload and result-fetch methods take/return
//! [`bytes::Bytes`] rather than typed bodies so callers can stream large
//! payloads without forcing buffer copies. CSV parsing/encoding is the
//! caller's responsibility — pick whichever crate fits the use case
//! (`csv`, `polars`, etc.).
//!
//! # Polling is on the caller
//!
//! The SDK exposes the building blocks (create, upload, close, get,
//! results, delete) but does *not* automate polling. Salesforce ingest
//! jobs can take seconds (small batches) or hours (millions of records);
//! the right poll cadence depends entirely on payload size and the
//! caller's latency vs. quota trade-offs. Build a polling loop with the
//! interval that fits the workload.

use crate::Cirrus;
use crate::error::CirrusResult;
use crate::response::{BulkIngestJob, BulkOperation, BulkQueryJob, BulkQueryResults};
use serde::Serialize;

const CSV_CONTENT_TYPE: &str = "text/csv";
const CSV_ACCEPT: &str = "text/csv";
const SFORCE_LOCATOR: &str = "Sforce-Locator";
const SFORCE_NUM_RECORDS: &str = "Sforce-NumberOfRecords";

impl Cirrus {
    /// Returns a handler for Bulk API 2.0 (`/services/data/{api_version}/jobs/...`).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use cirrus::{Cirrus, auth::StaticTokenAuth};
    /// # use std::sync::Arc;
    /// use cirrus::{BulkIngestSpec, BulkOperation};
    /// # async fn example() -> Result<(), cirrus::CirrusError> {
    /// # let auth = Arc::new(StaticTokenAuth::new("tok", "https://x.my.salesforce.com"));
    /// # let sf = Cirrus::builder().auth(auth).build()?;
    /// let bulk = sf.bulk();
    /// let ingest = bulk.ingest();
    /// let spec = BulkIngestSpec {
    ///     object: "Account".into(),
    ///     operation: BulkOperation::Insert,
    ///     external_id_field_name: None,
    ///     line_ending: None,
    ///     column_delimiter: None,
    ///     assignment_rule_id: None,
    /// };
    /// let job = ingest.create(&spec).await?;
    /// ingest.upload(&job.id, cirrus::Bytes::from("Name\nAcme\n")).await?;
    /// ingest.close(&job.id).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn bulk(&self) -> BulkHandler<'_> {
        BulkHandler { client: self }
    }
}

/// Top-level Bulk API 2.0 handler. Returned by [`Cirrus::bulk`].
#[derive(Debug)]
pub struct BulkHandler<'a> {
    client: &'a Cirrus,
}

impl BulkHandler<'_> {
    /// Returns a sub-handler for ingest (CRUD-style) bulk jobs under
    /// `/jobs/ingest`.
    pub fn ingest(&self) -> BulkIngestHandler<'_> {
        BulkIngestHandler {
            client: self.client,
        }
    }

    /// Returns a sub-handler for SOQL query bulk jobs under `/jobs/query`.
    pub fn query(&self) -> BulkQueryHandler<'_> {
        BulkQueryHandler {
            client: self.client,
        }
    }
}

/// Handler for Bulk 2.0 ingest jobs (`/jobs/ingest`).
///
/// Typical lifecycle for a single job:
///
/// 1. [`create`](Self::create) — `POST /jobs/ingest` with an operation
///    and target sObject; Salesforce returns a job in `Open` state.
/// 2. [`upload`](Self::upload) — `PUT /jobs/ingest/{id}/batches` with
///    CSV bytes. Salesforce returns 201 with no body.
/// 3. [`close`](Self::close) — `PATCH /jobs/ingest/{id}` with
///    `{"state": "UploadComplete"}`. Tells Salesforce to start
///    processing; cannot upload more data after this.
/// 4. Poll [`get`](Self::get) until `state` is `JobComplete`, `Failed`,
///    or `Aborted`.
/// 5. Fetch results: [`successful_results`](Self::successful_results) /
///    [`failed_results`](Self::failed_results) /
///    [`unprocessed_records`](Self::unprocessed_records). Each returns
///    raw CSV bytes.
/// 6. [`delete`](Self::delete) — `DELETE /jobs/ingest/{id}` once
///    you've consumed the results.
///
/// [`abort`](Self::abort) cancels a job mid-flight if needed.
#[derive(Debug)]
pub struct BulkIngestHandler<'a> {
    client: &'a Cirrus,
}

impl BulkIngestHandler<'_> {
    /// Creates a new ingest job. Salesforce returns the job in `Open`
    /// state with a `content_url` indicating where to upload data.
    ///
    /// Calls `POST /services/data/{api_version}/jobs/ingest`.
    pub async fn create(&self, spec: &BulkIngestSpec) -> CirrusResult<BulkIngestJob> {
        self.client.post("jobs/ingest", spec).await
    }

    /// Uploads CSV record data for a job. The job must be in `Open` state.
    /// Salesforce returns 201 with no body on success.
    ///
    /// Calls `PUT /services/data/{api_version}/jobs/ingest/{job_id}/batches`
    /// with `Content-Type: text/csv`.
    pub async fn upload(&self, job_id: &str, csv: bytes::Bytes) -> CirrusResult<()> {
        let path = self
            .client
            .versioned_segments(&["jobs", "ingest", job_id, "batches"])?;
        self.client
            .send_with_body(reqwest::Method::PUT, &path, csv, CSV_CONTENT_TYPE)
            .await
    }

    /// Marks a job as ready for processing by transitioning its state to
    /// `UploadComplete`. Returns the updated job metadata.
    ///
    /// Calls `PATCH /services/data/{api_version}/jobs/ingest/{job_id}`
    /// with `{"state": "UploadComplete"}`.
    pub async fn close(&self, job_id: &str) -> CirrusResult<BulkIngestJob> {
        self.patch_state(job_id, "UploadComplete").await
    }

    /// Aborts a job. Records already processed remain committed —
    /// Salesforce does *not* roll back. Returns the updated metadata.
    ///
    /// Calls `PATCH /services/data/{api_version}/jobs/ingest/{job_id}`
    /// with `{"state": "Aborted"}`.
    pub async fn abort(&self, job_id: &str) -> CirrusResult<BulkIngestJob> {
        self.patch_state(job_id, "Aborted").await
    }

    /// Fetches the current state and metadata for a job.
    ///
    /// Calls `GET /services/data/{api_version}/jobs/ingest/{job_id}`.
    pub async fn get(&self, job_id: &str) -> CirrusResult<BulkIngestJob> {
        let path = self
            .client
            .versioned_segments(&["jobs", "ingest", job_id])?;
        self.client
            .send_at::<_, (), ()>(reqwest::Method::GET, &path, None, None)
            .await
    }

    /// Deletes a job. Only valid when the job is in `JobComplete`,
    /// `Aborted`, or `Failed` state. Returns 204 on success.
    ///
    /// Calls `DELETE /services/data/{api_version}/jobs/ingest/{job_id}`.
    pub async fn delete(&self, job_id: &str) -> CirrusResult<()> {
        let path = self
            .client
            .versioned_segments(&["jobs", "ingest", job_id])?;
        self.client
            .send_at::<(), (), ()>(reqwest::Method::DELETE, &path, None, None)
            .await
    }

    /// Returns CSV bytes for records that succeeded. Each row carries
    /// the original input fields plus `sf__Id` (Salesforce ID of the
    /// affected record) and `sf__Created` (`true` if the record was
    /// created as part of this upsert/insert).
    ///
    /// Calls
    /// `GET /services/data/{api_version}/jobs/ingest/{job_id}/successfulResults/`.
    pub async fn successful_results(&self, job_id: &str) -> CirrusResult<bytes::Bytes> {
        self.fetch_csv_results(job_id, "successfulResults").await
    }

    /// Returns CSV bytes for records that failed validation/save. Each
    /// row carries the original input fields plus `sf__Error` (the
    /// human-readable error) and `sf__Id` (empty for failed creates).
    ///
    /// Calls
    /// `GET /services/data/{api_version}/jobs/ingest/{job_id}/failedResults/`.
    pub async fn failed_results(&self, job_id: &str) -> CirrusResult<bytes::Bytes> {
        self.fetch_csv_results(job_id, "failedResults").await
    }

    /// Returns CSV bytes for records that were never attempted (e.g.
    /// the job was aborted before reaching them).
    ///
    /// Calls
    /// `GET /services/data/{api_version}/jobs/ingest/{job_id}/unprocessedrecords/`.
    pub async fn unprocessed_records(&self, job_id: &str) -> CirrusResult<bytes::Bytes> {
        self.fetch_csv_results(job_id, "unprocessedrecords").await
    }

    async fn patch_state(&self, job_id: &str, new_state: &str) -> CirrusResult<BulkIngestJob> {
        let path = self
            .client
            .versioned_segments(&["jobs", "ingest", job_id])?;
        let body = StatePatch { state: new_state };
        self.client
            .send_at::<_, (), _>(reqwest::Method::PATCH, &path, None, Some(&body))
            .await
    }

    async fn fetch_csv_results(&self, job_id: &str, kind: &str) -> CirrusResult<bytes::Bytes> {
        let path = self
            .client
            .versioned_segments(&["jobs", "ingest", job_id, kind])?;
        let (_, bytes) = self
            .client
            .fetch_raw(reqwest::Method::GET, &path, CSV_ACCEPT, None)
            .await?;
        Ok(bytes)
    }
}

/// Handler for Bulk 2.0 query jobs (`/jobs/query`).
///
/// Lifecycle for a single query job:
///
/// 1. [`create`](Self::create) — `POST /jobs/query` with a SOQL string
///    and operation (`Query` or `QueryAll`); Salesforce returns a job
///    that progresses straight to `UploadComplete` (no upload step).
/// 2. Poll [`get`](Self::get) until `state` is `JobComplete`,
///    `Failed`, or `Aborted`.
/// 3. Drain results via [`results`](Self::results), passing
///    [`BulkQueryResults::locator`] back as the cursor on subsequent
///    calls until it returns `None`.
/// 4. [`delete`](Self::delete) when done.
#[derive(Debug)]
pub struct BulkQueryHandler<'a> {
    client: &'a Cirrus,
}

impl BulkQueryHandler<'_> {
    /// Creates a new query job.
    ///
    /// Calls `POST /services/data/{api_version}/jobs/query`.
    pub async fn create(&self, spec: &BulkQuerySpec) -> CirrusResult<BulkQueryJob> {
        self.client.post("jobs/query", spec).await
    }

    /// Fetches the current state and metadata for a query job.
    ///
    /// Calls `GET /services/data/{api_version}/jobs/query/{job_id}`.
    pub async fn get(&self, job_id: &str) -> CirrusResult<BulkQueryJob> {
        let path = self.client.versioned_segments(&["jobs", "query", job_id])?;
        self.client
            .send_at::<_, (), ()>(reqwest::Method::GET, &path, None, None)
            .await
    }

    /// Aborts a running query job.
    ///
    /// Calls `PATCH /services/data/{api_version}/jobs/query/{job_id}`
    /// with `{"state": "Aborted"}`.
    pub async fn abort(&self, job_id: &str) -> CirrusResult<BulkQueryJob> {
        let path = self.client.versioned_segments(&["jobs", "query", job_id])?;
        let body = StatePatch { state: "Aborted" };
        self.client
            .send_at::<_, (), _>(reqwest::Method::PATCH, &path, None, Some(&body))
            .await
    }

    /// Fetches one page of query results as CSV plus the cursor for
    /// the next page.
    ///
    /// `locator` is the cursor returned by a previous
    /// [`BulkQueryResults::locator`]. Pass `None` for the first page.
    /// `max_records` caps the number of rows in this page (Salesforce
    /// caps the absolute maximum at 50,000 per request).
    ///
    /// Calls
    /// `GET /services/data/{api_version}/jobs/query/{job_id}/results`
    /// with optional `?locator=&maxRecords=` query parameters.
    pub async fn results(
        &self,
        job_id: &str,
        locator: Option<&str>,
        max_records: Option<u32>,
    ) -> CirrusResult<BulkQueryResults> {
        let path = self
            .client
            .versioned_segments(&["jobs", "query", job_id, "results"])?;
        let max_records_str = max_records.map(|n| n.to_string());
        let mut query: Vec<(&str, &str)> = Vec::with_capacity(2);
        if let Some(loc) = locator {
            query.push(("locator", loc));
        }
        if let Some(ref n) = max_records_str {
            query.push(("maxRecords", n.as_str()));
        }
        let query_slice = if query.is_empty() {
            None
        } else {
            Some(query.as_slice())
        };
        let (headers, csv) = self
            .client
            .fetch_raw(reqwest::Method::GET, &path, CSV_ACCEPT, query_slice)
            .await?;
        Ok(BulkQueryResults {
            csv,
            locator: header_string(&headers, SFORCE_LOCATOR).filter(|s| s != "null"),
            number_of_records: header_string(&headers, SFORCE_NUM_RECORDS)
                .and_then(|s| s.parse().ok()),
        })
    }

    /// Deletes a query job. Only valid when the job is in `JobComplete`,
    /// `Aborted`, or `Failed` state.
    ///
    /// Calls `DELETE /services/data/{api_version}/jobs/query/{job_id}`.
    pub async fn delete(&self, job_id: &str) -> CirrusResult<()> {
        let path = self.client.versioned_segments(&["jobs", "query", job_id])?;
        self.client
            .send_at::<(), (), ()>(reqwest::Method::DELETE, &path, None, None)
            .await
    }
}

/// Request body for [`BulkIngestHandler::create`].
///
/// `content_type` is fixed to `"CSV"` server-side (the only supported
/// value) and is not exposed here. Salesforce defaults `column_delimiter`
/// to `Comma` and `line_ending` to `LF` when omitted.
#[derive(Debug, Clone, Serialize)]
pub struct BulkIngestSpec {
    /// API name of the target sObject (e.g. `"Account"`).
    pub object: String,
    /// Operation kind — must be one of the ingest values: `Insert`,
    /// `Update`, `Upsert`, `Delete`, `HardDelete`. Query/QueryAll on a
    /// `BulkIngestSpec` will produce a server-side error.
    pub operation: BulkOperation,
    /// External ID field name. Required when `operation` is `Upsert`,
    /// must be `None` for the other operations.
    #[serde(
        rename = "externalIdFieldName",
        skip_serializing_if = "Option::is_none"
    )]
    pub external_id_field_name: Option<String>,
    /// CSV line ending. Defaults server-side to `LF` when `None`.
    #[serde(rename = "lineEnding", skip_serializing_if = "Option::is_none")]
    pub line_ending: Option<crate::response::BulkLineEnding>,
    /// CSV column delimiter. Defaults server-side to `Comma` when `None`.
    #[serde(rename = "columnDelimiter", skip_serializing_if = "Option::is_none")]
    pub column_delimiter: Option<crate::response::BulkColumnDelimiter>,
    /// Optional assignment-rule ID (Lead/Case routing).
    #[serde(rename = "assignmentRuleId", skip_serializing_if = "Option::is_none")]
    pub assignment_rule_id: Option<String>,
}

/// Request body for [`BulkQueryHandler::create`].
///
/// Note that Salesforce caps a single bulk query at 60 minutes of
/// processing — for larger result sets, partition the SOQL with `WHERE`
/// clauses and run multiple jobs.
#[derive(Debug, Clone, Serialize)]
pub struct BulkQuerySpec {
    /// SOQL to execute.
    pub query: String,
    /// `Query` for active records only, `QueryAll` to include
    /// soft-deleted and archived records.
    pub operation: BulkOperation,
    /// CSV line ending. Defaults server-side to `LF` when `None`.
    #[serde(rename = "lineEnding", skip_serializing_if = "Option::is_none")]
    pub line_ending: Option<crate::response::BulkLineEnding>,
    /// CSV column delimiter. Defaults server-side to `Comma` when `None`.
    #[serde(rename = "columnDelimiter", skip_serializing_if = "Option::is_none")]
    pub column_delimiter: Option<crate::response::BulkColumnDelimiter>,
}

#[derive(Serialize)]
struct StatePatch<'a> {
    state: &'a str,
}

fn header_string(headers: &reqwest::header::HeaderMap, name: &str) -> Option<String> {
    headers
        .get(name)
        .and_then(|v| v.to_str().ok())
        .map(str::to_owned)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use crate::auth::StaticTokenAuth;
    use crate::response::{BulkColumnDelimiter, BulkJobState, BulkLineEnding};
    use serde_json::json;
    use std::sync::Arc;
    use wiremock::matchers::{body_json, header, method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn fixture(uri: String) -> Cirrus {
        let auth = Arc::new(StaticTokenAuth::new("tok", uri));
        Cirrus::builder().auth(auth).build().unwrap()
    }

    fn ingest_job_response(id: &str, state: &str) -> serde_json::Value {
        json!({
            "id": id,
            "operation": "insert",
            "object": "Account",
            "createdById": "005xx",
            "createdDate": "2024-01-01T00:00:00.000+0000",
            "systemModstamp": "2024-01-01T00:00:00.000+0000",
            "state": state,
            "concurrencyMode": "Parallel",
            "contentType": "CSV",
            "apiVersion": 60.0,
            "lineEnding": "LF",
            "columnDelimiter": "COMMA",
            "jobType": "V2Ingest"
        })
    }

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

        Mock::given(method("POST"))
            .and(path("/services/data/v66.0/jobs/ingest"))
            .and(header("authorization", "Bearer tok"))
            .and(body_json(json!({
                "object": "Account",
                "operation": "insert"
            })))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(ingest_job_response("750xx", "Open")),
            )
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        let job = sf
            .bulk()
            .ingest()
            .create(&BulkIngestSpec {
                object: "Account".into(),
                operation: BulkOperation::Insert,
                external_id_field_name: None,
                line_ending: None,
                column_delimiter: None,
                assignment_rule_id: None,
            })
            .await
            .unwrap();
        assert_eq!(job.id, "750xx");
        assert_eq!(job.state, BulkJobState::Open);
    }

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

        Mock::given(method("POST"))
            .and(path("/services/data/v66.0/jobs/ingest"))
            .and(body_json(json!({
                "object": "Account",
                "operation": "upsert",
                "externalIdFieldName": "External_Id__c",
                "lineEnding": "CRLF",
                "columnDelimiter": "TAB"
            })))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(ingest_job_response("750xx", "Open")),
            )
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        sf.bulk()
            .ingest()
            .create(&BulkIngestSpec {
                object: "Account".into(),
                operation: BulkOperation::Upsert,
                external_id_field_name: Some("External_Id__c".into()),
                line_ending: Some(BulkLineEnding::CRLF),
                column_delimiter: Some(BulkColumnDelimiter::Tab),
                assignment_rule_id: None,
            })
            .await
            .unwrap();
    }

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

        Mock::given(method("PUT"))
            .and(path("/services/data/v66.0/jobs/ingest/750xx/batches"))
            .and(header("content-type", "text/csv"))
            .and(header("authorization", "Bearer tok"))
            .respond_with(ResponseTemplate::new(201))
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        let csv = bytes::Bytes::from_static(b"Name\nAcme\nGlobex\n");
        sf.bulk().ingest().upload("750xx", csv).await.unwrap();
    }

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

        Mock::given(method("PATCH"))
            .and(path("/services/data/v66.0/jobs/ingest/750xx"))
            .and(body_json(json!({"state": "UploadComplete"})))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(ingest_job_response("750xx", "UploadComplete")),
            )
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        let job = sf.bulk().ingest().close("750xx").await.unwrap();
        assert_eq!(job.state, BulkJobState::UploadComplete);
    }

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

        Mock::given(method("PATCH"))
            .and(path("/services/data/v66.0/jobs/ingest/750xx"))
            .and(body_json(json!({"state": "Aborted"})))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(ingest_job_response("750xx", "Aborted")),
            )
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        let job = sf.bulk().ingest().abort("750xx").await.unwrap();
        assert_eq!(job.state, BulkJobState::Aborted);
    }

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

        let mut completed = ingest_job_response("750xx", "JobComplete");
        completed["numberRecordsProcessed"] = json!(100);
        completed["numberRecordsFailed"] = json!(2);
        completed["totalProcessingTime"] = json!(2349);

        Mock::given(method("GET"))
            .and(path("/services/data/v66.0/jobs/ingest/750xx"))
            .respond_with(ResponseTemplate::new(200).set_body_json(completed))
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        let job = sf.bulk().ingest().get("750xx").await.unwrap();
        assert_eq!(job.state, BulkJobState::JobComplete);
        assert_eq!(job.number_records_processed, Some(100));
        assert_eq!(job.number_records_failed, Some(2));
    }

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

        Mock::given(method("DELETE"))
            .and(path("/services/data/v66.0/jobs/ingest/750xx"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        sf.bulk().ingest().delete("750xx").await.unwrap();
    }

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

        let csv = "sf__Id,sf__Created,Name\n001xx,true,Acme\n";
        Mock::given(method("GET"))
            .and(path(
                "/services/data/v66.0/jobs/ingest/750xx/successfulResults",
            ))
            .and(header("accept", "text/csv"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string(csv)
                    .insert_header("content-type", "text/csv"),
            )
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        let bytes = sf
            .bulk()
            .ingest()
            .successful_results("750xx")
            .await
            .unwrap();
        assert_eq!(&bytes[..], csv.as_bytes());
    }

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

        let csv = "sf__Id,sf__Error,Name\n,REQUIRED_FIELD_MISSING:Name,\n";
        Mock::given(method("GET"))
            .and(path("/services/data/v66.0/jobs/ingest/750xx/failedResults"))
            .respond_with(ResponseTemplate::new(200).set_body_string(csv))
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        let bytes = sf.bulk().ingest().failed_results("750xx").await.unwrap();
        assert!(bytes.starts_with(b"sf__Id,sf__Error"));
    }

    #[tokio::test]
    async fn ingest_results_path_404_surfaces_as_api_error() {
        // Wrong job id: Salesforce returns 400 with the standard error array.
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/services/data/v66.0/jobs/ingest/missing/successfulResults",
            ))
            .respond_with(ResponseTemplate::new(400).set_body_json(json!([{
                "message": "InvalidJob: Bulk API job missing not found",
                "errorCode": "INVALIDJOBSTATE"
            }])))
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        let err = sf
            .bulk()
            .ingest()
            .successful_results("missing")
            .await
            .unwrap_err();
        match err {
            crate::CirrusError::Api { status, errors, .. } => {
                assert_eq!(status, 400);
                assert_eq!(errors[0].error_code, "INVALIDJOBSTATE");
            }
            other => panic!("expected Api error, got {other:?}"),
        }
    }

    fn query_job_response(id: &str, state: &str) -> serde_json::Value {
        // Mirrors the documented query-job CREATE response — see
        // api_asynch query_create_job. Salesforce parses the SOQL,
        // surfaces `object`, and never echoes the original `query`
        // string. `jobType` is absent until the GET endpoint, so we
        // omit it here too — tests for GET shape live in response.rs.
        json!({
            "id": id,
            "operation": "query",
            "state": state,
            "object": "Account",
            "createdById": "005xx",
            "createdDate": "2024-01-01T00:00:00.000+0000",
            "systemModstamp": "2024-01-01T00:00:00.000+0000",
            "concurrencyMode": "Parallel",
            "contentType": "CSV",
            "apiVersion": 60.0,
            "lineEnding": "LF",
            "columnDelimiter": "COMMA"
        })
    }

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

        Mock::given(method("POST"))
            .and(path("/services/data/v66.0/jobs/query"))
            .and(body_json(json!({
                "query": "SELECT Id, Name FROM Account",
                "operation": "query"
            })))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(query_job_response("750xx", "UploadComplete")),
            )
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        let job = sf
            .bulk()
            .query()
            .create(&BulkQuerySpec {
                query: "SELECT Id, Name FROM Account".into(),
                operation: BulkOperation::Query,
                line_ending: None,
                column_delimiter: None,
            })
            .await
            .unwrap();
        assert_eq!(job.state, BulkJobState::UploadComplete);
    }

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

        let csv = "Id,Name\n001xx,Acme\n";
        Mock::given(method("GET"))
            .and(path("/services/data/v66.0/jobs/query/750xx/results"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string(csv)
                    .insert_header("Sforce-Locator", "MTAwMA")
                    .insert_header("Sforce-NumberOfRecords", "1"),
            )
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        let result = sf
            .bulk()
            .query()
            .results("750xx", None, None)
            .await
            .unwrap();
        assert_eq!(&result.csv[..], csv.as_bytes());
        assert_eq!(result.locator.as_deref(), Some("MTAwMA"));
        assert_eq!(result.number_of_records, Some(1));
    }

    #[tokio::test]
    async fn query_results_treats_null_locator_as_done() {
        // When the result set is fully drained Salesforce sends
        // Sforce-Locator: null (literal string, not absent header).
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/services/data/v66.0/jobs/query/750xx/results"))
            .and(query_param("locator", "MTAwMA"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string("")
                    .insert_header("Sforce-Locator", "null")
                    .insert_header("Sforce-NumberOfRecords", "0"),
            )
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        let result = sf
            .bulk()
            .query()
            .results("750xx", Some("MTAwMA"), None)
            .await
            .unwrap();
        assert!(result.locator.is_none());
        assert_eq!(result.number_of_records, Some(0));
    }

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

        Mock::given(method("GET"))
            .and(path("/services/data/v66.0/jobs/query/750xx/results"))
            .and(query_param("maxRecords", "10000"))
            .respond_with(ResponseTemplate::new(200).set_body_string("Id\n"))
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        sf.bulk()
            .query()
            .results("750xx", None, Some(10000))
            .await
            .unwrap();
    }

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

        Mock::given(method("PATCH"))
            .and(path("/services/data/v66.0/jobs/query/750xx"))
            .and(body_json(json!({"state": "Aborted"})))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(query_job_response("750xx", "Aborted")),
            )
            .mount(&server)
            .await;

        let sf = fixture(server.uri());
        let job = sf.bulk().query().abort("750xx").await.unwrap();
        assert_eq!(job.state, BulkJobState::Aborted);
    }
}