rustsf 0.1.1

Salesforce SDK for Rust, supports the latest API version 68.0, (Winter 2026)
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
//! # Salesforce Metadata API
//!
//! Metadata API enables you to deploy metadata to Salesforce,
//! this includes destructive deployments
//!
//! ## Supported Endpoints:
//! - **/services/data/vXX.X/metadata/deployRequest**, for deployments, status checks, and cancellation
//!
//! ## Supported Methods:
//! - [deploy](crate::metadata_api::MetadataApi#method.deploy), for sending deployments to the Salesforce queue
//! - [status](crate::metadata_api::MetadataApi#method.status), reports on the status of a deployment
//! - [cancel](crate::metadata_api::MetadataApi#method.cancel), cancelles a running or queued deployment
//!
//! # Notes
//! You can deploy or retrieve up to 10,000 files at once. The maximum size of the deployed or
//! retrieved .zip file is 39 MB. If the files are uncompressed in an unzipped folder,
//! the size limit is 600 MB or 629,145,600 bytes.
//! The size limit in bytes is calculated as 600 x 1024 x 1024.
//!
//! # See
//! <https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_rest_deploy.htm>
//!
use crate::client::Client;
use crate::errors::Error;
use crate::metadata_api::metadata_retriever::MetadataRetriever;
use crate::metadata_api::responses::async_result::AsyncResult;
use crate::metadata_api::responses::cancel_request::CancelRequest;
use crate::metadata_api::responses::check_retrieve_status_response::CheckRetrieveStatusResponse;
use crate::metadata_api::responses::deploy_response::DeployResponse;
use crate::rest_api::responses::error_response::ErrorResponse;
use log::{debug, trace};
use metadata_deployer::MetadataDeployer;
use reqwest::{Response, multipart};
use rustsf_auth::SalesforceCredentials;
use serde::de::DeserializeOwned;
use std::collections::HashMap;

pub mod metadata_deployer;
pub mod metadata_retriever;
pub mod responses;

const METADATA_NAMESPACE: &str = "http://soap.sforce.com/2006/04/metadata";
const ENVELOPE_NAMESPACE: &str = "http://schemas.xmlsoap.org/soap/envelope/";

/// A `MetadataApi` that represents the core component for interacting with a Metadata API.
///
/// The Metadata API offers two styles: file-based calls (`deploy`/`retrieve`,
/// which take a zip and run asynchronously) and CRUD-based calls, which act on
/// components directly and return synchronously. This client covers the latter.
///
/// It exists because some operations have no equivalent elsewhere — notably
/// deleting a `CustomField`, which the Tooling API does not support at all
/// (that object exposes only Query/GET/POST/PATCH).
///
/// Unlike the REST clients this speaks SOAP, since the Metadata API has no REST
/// binding for these calls.
pub struct MetadataApi {
	client: Client,
}

impl MetadataApi {
	/// Creates a new instance of `MetadataApi`.
	///
	/// # Parameters
	/// - `client`: An instance of the `Client` struct that will be used to interact with the metadata API.
	///
	/// # Returns
	/// A new `MetadataApi` object initialized with the provided `client`.
	///
	/// # Example
	/// ```rust
	/// use rustsf::{Client, Credentials, MetadataApi};
	///
	/// #[tokio::main]
	/// async fn main() {
	///     let client= Client::new(Credentials::new()).await?;
	///     // Authentication logic...
	///
	///     let mut api = MetadataApi::new(client);
	///
	///     // ... add your logic here...
	///
	/// }
	/// ```
	pub async fn new(credentials: SalesforceCredentials) -> Result<Self, Error> {
		Ok(Self {
			client: Client::new(credentials).await?,
		})
	}

	/// Cancels a deployment request with the specified `deploy_request_id`.
	///
	/// # Arguments
	/// * `deploy_request_id` - The unique identifier of the deployment request to be canceled.
	///
	/// # Returns
	/// * `Result<DeployResponse, Error>` - Returns `DeployResponse` on success, or an `Error` on a HTTP failure.
	///
	/// # Errors
	/// This function will return an error in the following cases:
	/// * If the client's base version path retrieval fails.
	/// * If the HTTP PATCH request fails or receives an invalid response.
	/// * If the JSON response cannot be parsed correctly.
	///
	/// # Example
	/// ```rust
	/// use rustsf::{Client, Credentials, MetadataApi};
	///
	/// #[tokio::main]
	/// async fn main() {
	///     let client= Client::new(Credentials::new()).await?;
	///     // Authentication logic...
	///
	///     let mut api = MetadataApi::new(client);
	///
	///     let mut request = api.new_deployment_request();
	///     // ... add your logic here to add things to the deployment
	///     let response = api.deploy(request).await?;
	///
	///     // Cancel the deployment
	///     let response = api.cancel(response.get_deploy_request_id()).await?;
	///     println!("Cancel response {:?}", response);
	/// }
	/// ```
	pub async fn cancel(&self, deploy_request_id: &str) -> Result<DeployResponse, Error> {
		let url = format!(
			"{}/metadata/deployRequest/{}",
			self.client.services_data_version_path(),
			deploy_request_id,
		);
		let response = self.client.patch(&url, CancelRequest::new(), &HashMap::new()).await?;
		handle_json_response(response).await
	}

	/// Asynchronously deploys metadata to the server using the given `MetadataRequest`.
	///
	/// # Parameters
	/// - `request`: The `MetadataRequest` containing the deployment options and the zipped files to be deployed.
	///
	/// # Returns
	/// This function returns a `Result` containing:
	/// - `DeployResponse` if the HTTP request was successful, it contains the response body.
	/// - `Error` if any error occurs during the HTTP request process.
	///
	/// # Examples
	/// ```rust
	/// use rustsf::{Client, Credentials, MetadataApi};
	///
	/// #[tokio::main]
	/// async fn main() {
	///     let client= Client::new(Credentials::new()).await?;
	///     // Authentication logic...
	///
	///     let mut api = MetadataApi::new(client);
	///     let mut request = api.new_deployment_request();
	///     // ... add your logic here to add things to the deployment
	///     let response = api.deploy(request).await?;
	///     println!("Deployment response {:?}", response);
	/// }
	/// ```
	///
	/// # Notes
	/// - The deployed zip file must be named `deploy.zip`.
	/// - Make sure the server's base version path is correctly configured in the `self.client`.
	///
	/// # See
	/// <https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_rest_deploy.htm>
	pub async fn deploy(&self, request: MetadataDeployer) -> Result<DeployResponse, Error> {
		// create the form
		let form = multipart::Form::new()
			.part(
				"json",
				multipart::Part::bytes(request.get_deploy_request_json()?.into_bytes()).mime_str("application/json")?,
			)
			.part(
				"zipfile",
				multipart::Part::bytes(request.get_zip_file()?)
					.file_name("deploy.zip")
					.mime_str("application/zip")?,
			);

		// Send request
		let url = format!("{}/metadata/deployRequest", self.client.services_data_version_path());
		let response = self
			.client
			.post_multipart(
				&url,
				&HashMap::new(),
				form,
			)
			.await?;
		handle_json_response(response).await
	}

	/// Creates a new `MetadataRequest` instance using the current client's configuration
	/// This instance is used to build and execute metadata deployment requests.
	///
	/// # Returns
	/// A `MetadataRequest` object initialized with the underlying client's settings.
	///
	/// # Examples
	/// ```rust
	/// use rustsf::{Client, Credentials, MetadataApi};
	///
	/// #[tokio::main]
	/// async fn main() {
	///     let client= Client::new(Credentials::new()).await?;
	///     // Authentication logic...
	///
	///     let mut api = MetadataApi::new(client);
	///
	///     let mut request = api.new_deployment_request();
	///     // ... add your logic here to all things to the deployment
	///     // e.g. request.add(....)?;
	///     let response = api.deploy(deployer).await?;
	/// }
	/// ```
	///
	/// # See
	/// <https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_rest_deploy.htm>
	pub fn new_deployment_request(&self) -> MetadataDeployer {
		MetadataDeployer::new()
	}

	pub fn new_retrieval_request(&self) -> MetadataRetriever {
		MetadataRetriever::new()
	}

	pub async fn retrieve(&self, request: MetadataRetriever) -> Result<AsyncResult, Error> {
		let body = format!(
			r#"<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="{}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="{}">
  <soapenv:Header><SessionHeader><sessionId>{}</sessionId></SessionHeader></soapenv:Header>
  <soapenv:Body>
    <retrieve>
      <retrieveRequest>
        <apiVersion>{}</apiVersion>
        <unpackaged>{}</unpackaged>
      </retrieveRequest>
    </retrieve>
  </soapenv:Body>
</soapenv:Envelope>"#,
			ENVELOPE_NAMESPACE,
			METADATA_NAMESPACE,
			escape_xml(self.client.access_token().await?),
			crate::client::DEFAULT_API_VERSION,
			request.get_package(),
		);

		let response = self.client.post_soap("retrieve", body).await?;

		let xml = response.text().await?;
		trace!("Soap Metadata API retrieve response: {}", xml);

		Ok(AsyncResult::from_xml(&xml)?)
	}

	pub async fn retrieve_status(&self, id: &str) -> Result<CheckRetrieveStatusResponse, Error> {
		let body = format!(
			r#"<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="{}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="{}">
  <soapenv:Header><SessionHeader><sessionId>{}</sessionId></SessionHeader></soapenv:Header>
  <soapenv:Body>
      <checkRetrieveStatus>
        <id>{}</id>
        <includeZip>true</includeZip>
      </checkRetrieveStatus>
  </soapenv:Body>
</soapenv:Envelope>"#,
			ENVELOPE_NAMESPACE,
			METADATA_NAMESPACE,
			escape_xml(self.client.access_token().await?),
			id,
		);

		let response = self.client.post_soap("retrieve", body).await?;

		let xml = response.text().await?;

		trace!("Soap Metadata API retrieve status response: {}", xml);

		Ok(CheckRetrieveStatusResponse::from_xml(&xml)?)
	}

	/// Retrieves the status of a deployment request.
	///
	/// # Parameters
	/// - `deploy_request_id`: The unique identifier of the deployment request for which the status is being queried.
	/// - `include_details`: A boolean indicating whether additional details about
	///   the deployment request should be included in the response.
	///
	/// # Returns
	/// - On success, returns a `DeployResponse` object containing the status and
	///   optional details of the deployment request.
	/// - Returns an `Error` in case of a HTTP failure, such as a network issue or if the
	///   deployment request ID is invalid.
	///
	/// # Errors
	/// - This function propagates errors from underlying HTTP or JSON handling.
	/// - Returns an error if there are issues with the request parameters or
	///   response deserialization.
	///
	/// # Example
	/// ```rust
	/// use rustsf::{Client, Credentials, MetadataApi};
	///
	/// #[tokio::main]
	/// async fn main() {
	///     let client= Client::new(Credentials::new()).await?;
	///     // Authentication logic...
	///
	///     let mut api = MetadataApi::new(client);
	///
	///     let mut request = api.new_deployment_request();
	///     // ... add your logic here to add things to the deployment
	///     let response = api.deploy(request).await?;
	///
	///     // Cancel the deployment
	///     let response = api.status(response.get_deploy_request_id(), true).await?;
	///     println!("Status response {:?}", response);
	/// }
	/// ```
	///
	/// # Notes
	/// - The `include_details` parameter, when set to `true`, appends an additional
	///   query parameter to the HTTP request (`includeDetails=true`) to ask the
	///   server for more detailed data.
	/// - The function makes use of the `handle_json_response` helper function to
	///   process the JSON response returned by the server.
	///
	/// # Dependencies
	/// This function requires the following:
	/// - `self.client`: An HTTP client that supports asynchronous operations.
	/// - `self.client.base_version_path()`: A method that provides the base path for
	///   the API endpoint.
	/// - `handle_json_response`: An asynchronous function that processes the
	///   JSON-formatted response from the server.
	pub async fn deploy_status(&self, deploy_request_id: &str, include_details: bool) -> Result<DeployResponse, Error> {
		let mut params: Vec<(String, String)> = vec![];
		if include_details {
			params.push(("includeDetails".to_string(), "true".to_string()));
		}

		let response = self
			.client
			.get_json(
				format!(
					"{}/metadata/deployRequest/{}",
					self.client.services_data_version_path(),
					deploy_request_id
				),
				&params,
				&HashMap::new(),
			)
			.await?;

		handle_json_response(response).await
	}
}

async fn handle_json_response<T: DeserializeOwned>(response: Response) -> Result<T, Error> {
	if response.status().is_success() {
		Ok(response.json().await?)
	} else {
		let errors: Vec<ErrorResponse> = response.json().await?;
		Err(Error::Salesforce(errors))
	}
}

/*async fn handle_raw_response(response: Response) -> Result<String, Error> {
	if response.status().is_success() {
		Ok(response.text().await?)
	} else {
		let errors: Vec<ErrorResponse> = response.json().await?;
		Err(Error::Salesforce(errors))
	}
}*/

fn generate_package_xml(version: &str, elements: &HashMap<String, Vec<String>>) -> String {
	let header = r#"<?xml version="1.0" encoding="UTF-8"?>
    <Package xmlns="http://soap.sforce.com/2006/04/metadata">"#;
	let footer = format!("  <version>{}</version>\n</Package>", version);

	let mut metadata_type = "".to_string();
	for (metadata, objects) in elements {
		let members = objects
			.iter()
			.map(|object| format!("        <members>{}</members>", object))
			.collect::<Vec<String>>()
			.join("\n");

		metadata_type.push_str(
			format!(
				"<types>\n{}\n        <name>{}</name>\n    </types>\n",
				members, metadata
			)
			.as_str(),
		);
	}
	format!("{}\n{}\n{}", header, metadata_type, footer)
}

fn add_file_to_package(package: &mut HashMap<String, Vec<String>>, metadata_type: &str, file_name: &str) {
	// Add the file to the deployment package
	let package_file_name = file_name.split(".").next().unwrap().to_string(); // fixme remove unwrap
	debug!("Adding package file: {}", package_file_name);
	package
		.entry(metadata_type.to_string())
		.or_insert_with(Vec::new)
		.push(package_file_name);
}

pub struct Deployment {}

fn escape_xml<S: AsRef<str>>(value: S) -> String {
	value
		.as_ref()
		.replace('&', "&amp;")
		.replace('<', "&lt;")
		.replace('>', "&gt;")
		.replace('"', "&quot;")
		.replace('\'', "&apos;")
}