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
//! Reconciliation and post workflow operations for the Version Management client.
use super::super::{
ConflictDetection, PartialPostRow, PostResponse, ReconcileResponse, SessionId, VersionGuid,
};
use super::VersionManagementClient;
use crate::Result;
use tracing::instrument;
impl<'a> VersionManagementClient<'a> {
/// Reconciles a version against the DEFAULT version.
///
/// Reconciliation compares the current version against the DEFAULT version,
/// identifying differences and detecting conflicts based on the specified
/// conflict detection type. This is a required step before posting changes.
///
/// **Important**: Reconcile requires an exclusive write lock on the version.
/// You must have started an edit session and no read sessions can be active.
///
/// # Arguments
///
/// * `version_guid` - The GUID of the version to reconcile
/// * `session_id` - The session ID from the active edit session
/// * `abort_if_conflicts` - If `true`, abort if conflicts are detected
/// * `conflict_detection` - Type of conflict detection (ByObject or ByAttribute)
/// * `with_post` - If `true`, automatically post after successful reconcile
///
/// # Returns
///
/// Returns a [`ReconcileResponse`] with conflict information and post status.
///
/// # Errors
///
/// Returns an error if:
/// - The version doesn't exist
/// - No active edit session with matching session ID
/// - Read locks exist on the version
/// - The user doesn't have edit permissions
/// - Conflicts are detected and `abort_if_conflicts` is true
/// - Authentication fails
/// - Network error occurs
///
/// # Example
///
/// ```no_run
/// use arcgis::{
/// ArcGISClient, ClientCredentialsAuth, VersionManagementClient,
/// SessionId, ConflictDetection,
/// };
/// use uuid::Uuid;
///
/// # async fn example() -> arcgis::Result<()> {
/// # let auth = ClientCredentialsAuth::new("id".to_string(), "secret".to_string()).expect("Valid");
/// # let client = ArcGISClient::new(auth);
/// # let vm_client = VersionManagementClient::new("url", &client);
/// let version_guid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")
/// .expect("Valid UUID");
/// let session_id = SessionId::new();
///
/// // Start edit session first
/// vm_client.start_editing(version_guid.into(), session_id).await?;
///
/// // Perform edits...
///
/// // Reconcile with DEFAULT version
/// let response = vm_client.reconcile(
/// version_guid.into(),
/// session_id,
/// true, // abort if conflicts
/// ConflictDetection::ByObject,
/// false, // don't auto-post
/// ).await?;
///
/// if *response.success() {
/// if response.has_conflicts().as_ref().map_or(false, |x| *x) {
/// println!("Conflicts detected - resolve before posting");
/// } else {
/// println!("Reconcile successful, ready to post");
/// }
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self), fields(
base_url = %self.base_url,
version_guid = %version_guid,
session_id = %session_id,
abort_if_conflicts,
conflict_detection = %conflict_detection,
with_post
))]
pub async fn reconcile(
&self,
version_guid: VersionGuid,
session_id: SessionId,
abort_if_conflicts: bool,
conflict_detection: ConflictDetection,
with_post: bool,
) -> Result<ReconcileResponse> {
tracing::debug!(
version_guid = %version_guid,
session_id = %session_id,
abort_if_conflicts = abort_if_conflicts,
conflict_detection = %conflict_detection,
with_post = with_post,
"Reconciling version"
);
let url = format!("{}/versions/{}/reconcile", self.base_url, version_guid);
let abort_str = if abort_if_conflicts { "true" } else { "false" };
let with_post_str = if with_post { "true" } else { "false" };
let conflict_detection_str = conflict_detection.to_string();
tracing::debug!(url = %url, "Sending reconcile request");
let session_id_str = session_id.to_string();
let mut form = vec![
("sessionId", session_id_str.as_str()),
("abortIfConflicts", abort_str),
("conflictDetection", conflict_detection_str.as_str()),
("withPost", with_post_str),
("f", "json"),
];
// Add token if required by auth provider
let token_opt = self.client.get_token_if_required().await?;
let token_str;
if let Some(token) = token_opt {
token_str = token;
form.push(("token", token_str.as_str()));
}
let response = self.client.http().post(&url).form(&form).send().await?;
let status = response.status();
if !status.is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|e| format!("Failed to read error: {}", e));
tracing::error!(status = %status, error = %error_text, "reconcile failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let reconcile_response: ReconcileResponse = response.json().await?;
if *reconcile_response.success() {
tracing::info!(
version_guid = %version_guid,
has_conflicts = ?reconcile_response.has_conflicts(),
did_post = ?reconcile_response.did_post(),
moment = ?reconcile_response.moment(),
"Reconcile completed successfully"
);
} else {
tracing::warn!(
version_guid = %version_guid,
error = ?reconcile_response.error(),
"reconcile reported failure"
);
}
Ok(reconcile_response)
}
/// Posts changes from a version to the DEFAULT version.
///
/// Posting applies the edits made in the current version to the DEFAULT version.
/// This operation must be preceded by a successful reconcile operation with no
/// unresolved conflicts.
///
/// **Important**: The session ID must match the one used for reconcile, and the
/// DEFAULT version must not have been modified since the reconcile.
///
/// # Arguments
///
/// * `version_guid` - The GUID of the version to post
/// * `session_id` - The session ID from the active edit session (must match reconcile)
/// * `partial_rows` - Optional subset of edits to post (for partial post)
///
/// # Returns
///
/// Returns a [`PostResponse`] indicating success or failure.
///
/// # Errors
///
/// Returns an error if:
/// - The version doesn't exist
/// - No active edit session with matching session ID
/// - Reconcile was not performed first
/// - Session ID doesn't match the reconcile session
/// - DEFAULT version was modified since reconcile
/// - Unresolved conflicts exist
/// - Authentication fails
/// - Network error occurs
///
/// # Example
///
/// ```no_run
/// use arcgis::{
/// ArcGISClient, ClientCredentialsAuth, VersionManagementClient,
/// SessionId, ConflictDetection,
/// };
/// use uuid::Uuid;
///
/// # async fn example() -> arcgis::Result<()> {
/// # let auth = ClientCredentialsAuth::new("id".to_string(), "secret".to_string()).expect("Valid");
/// # let client = ArcGISClient::new(auth);
/// # let vm_client = VersionManagementClient::new("url", &client);
/// let version_guid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")
/// .expect("Valid UUID");
/// let session_id = SessionId::new();
///
/// // Start edit session
/// vm_client.start_editing(version_guid.into(), session_id).await?;
///
/// // Perform edits...
///
/// // Reconcile first
/// let reconcile_response = vm_client.reconcile(
/// version_guid.into(),
/// session_id,
/// true,
/// ConflictDetection::ByObject,
/// false,
/// ).await?;
///
/// if !reconcile_response.has_conflicts().as_ref().map_or(false, |x| *x) {
/// // No conflicts - post changes
/// let post_response = vm_client.post(
/// version_guid.into(),
/// session_id,
/// None, // post all edits
/// ).await?;
///
/// if *post_response.success() {
/// println!("Changes posted to DEFAULT successfully");
/// }
/// }
///
/// // Stop editing and save
/// vm_client.stop_editing(version_guid.into(), session_id, true).await?;
/// # Ok(())
/// # }
/// ```
///
/// # Partial Post Example
///
/// ```no_run
/// use arcgis::{ArcGISClient, ClientCredentialsAuth, VersionManagementClient, PartialPostRow};
/// # use arcgis::SessionId;
/// # use uuid::Uuid;
///
/// # async fn example() -> arcgis::Result<()> {
/// # let auth = ClientCredentialsAuth::new("id".to_string(), "secret".to_string()).expect("Valid");
/// # let client = ArcGISClient::new(auth);
/// # let vm_client = VersionManagementClient::new("url", &client);
/// # let version_guid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")
/// # .expect("Valid UUID");
/// # let session_id = SessionId::new();
/// // Post only specific features from specific layers
/// let partial_rows = vec![
/// PartialPostRow::new(0, vec![1, 2, 3]), // Layer 0, objects 1-3
/// PartialPostRow::new(1, vec![10, 20]), // Layer 1, objects 10, 20
/// ];
///
/// let response = vm_client.post(
/// version_guid.into(),
/// session_id,
/// Some(partial_rows),
/// ).await?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, partial_rows), fields(
base_url = %self.base_url,
version_guid = %version_guid,
session_id = %session_id,
partial_post = partial_rows.is_some()
))]
pub async fn post(
&self,
version_guid: VersionGuid,
session_id: SessionId,
partial_rows: Option<Vec<PartialPostRow>>,
) -> Result<PostResponse> {
tracing::debug!(
version_guid = %version_guid,
session_id = %session_id,
partial_post = partial_rows.is_some(),
"Posting changes to DEFAULT version"
);
let url = format!("{}/versions/{}/post", self.base_url, version_guid);
let mut form = vec![
("sessionId", session_id.to_string()),
("f", "json".to_string()),
];
// Serialize partial_rows if provided
let rows_json;
if let Some(rows) = partial_rows {
rows_json = serde_json::to_string(&rows)?;
form.push(("rows", rows_json));
}
tracing::debug!(url = %url, "Sending post request");
let form_refs: Vec<(&str, &str)> = form.iter().map(|(k, v)| (*k, v.as_str())).collect();
let response = self
.client
.http()
.post(&url)
.form(&form_refs)
.send()
.await?;
let status = response.status();
if !status.is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|e| format!("Failed to read error: {}", e));
tracing::error!(status = %status, error = %error_text, "post failed");
return Err(crate::Error::from(crate::ErrorKind::Api {
code: status.as_u16() as i32,
message: format!("HTTP {}: {}", status, error_text),
}));
}
let post_response: PostResponse = response.json().await?;
if *post_response.success() {
tracing::info!(
version_guid = %version_guid,
moment = ?post_response.moment(),
"Changes posted successfully"
);
} else {
tracing::warn!(
version_guid = %version_guid,
error = ?post_response.error(),
"post reported failure"
);
}
Ok(post_response)
}
}