scim-server 0.5.3

A comprehensive SCIM 2.0 server library for Rust with multi-tenant support and type-safe operations
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
//! Conditional operations helper trait for SCIM resources.
//!
//! This module provides reusable functionality for implementing version-based optimistic
//! concurrency control in SCIM ResourceProvider implementations. It handles version
//! computation, conflict detection, and conditional operation patterns.
//!
//! # Optimistic Concurrency Control
//!
//! This implementation follows SCIM and HTTP ETag patterns for:
//! - Version-based conditional updates and deletes
//! - Conflict detection and resolution
//! - Version computation using content hashing
//! - ConditionalResult handling for operation outcomes
//!
//! # Usage
//!
//! ```rust,no_run
//! use scim_server::resource::version::{RawVersion, ConditionalResult};
//!
//! // ConditionalOperations provides methods like conditional_update_resource
//! // that prevent lost updates through optimistic locking
//! let expected_version = RawVersion::from_hash("abc123");
//!
//! // The trait automatically implements conditional operations
//! // for any type that implements ResourceProvider
//! ```

use crate::providers::ResourceProvider;
use crate::resource::RequestContext;
use crate::resource::version::{ConditionalResult, RawVersion, VersionConflict};
use crate::resource::versioned::VersionedResource;
use serde_json::Value;
use std::future::Future;

/// Trait providing version-based conditional operations for SCIM resources.
///
/// This trait extends ResourceProvider with optimistic concurrency control capabilities
/// including conditional updates, deletes, and version management. Most implementers
/// can use the default implementations which provide standard conditional operation patterns.
pub trait ConditionalOperations: ResourceProvider {
    /// Perform a conditional update operation.
    ///
    /// Updates a resource only if the current version matches the expected version,
    /// preventing lost updates in concurrent scenarios. Uses optimistic locking
    /// based on resource content versioning.
    ///
    /// # Arguments
    /// * `resource_type` - The type of resource to update
    /// * `id` - The unique identifier of the resource
    /// * `data` - The updated resource data
    /// * `expected_version` - The version the client expects (for conflict detection)
    /// * `context` - Request context containing tenant information
    ///
    /// # Returns
    /// * `Success(VersionedResource)` - Update succeeded with new resource and version
    /// * `VersionMismatch(VersionConflict)` - Resource was modified by another client
    /// * `NotFound` - Resource doesn't exist
    ///
    /// # Example
    /// ```rust,no_run
    /// use scim_server::resource::version::{RawVersion, ConditionalResult};
    /// use serde_json::json;
    ///
    /// let expected_version = RawVersion::from_hash("abc123");
    /// let update_data = json!({"userName": "newname", "active": false});
    ///
    /// // ConditionalOperations automatically available on ResourceProvider implementations
    /// // match provider.conditional_update_resource("Users", "123", update_data, &expected_version, &context).await? {
    /// //     ConditionalResult::Success(versioned) => println!("Update successful"),
    /// //     ConditionalResult::VersionMismatch(conflict) => println!("Conflict detected"),
    /// //     ConditionalResult::NotFound => println!("Resource not found"),
    /// // }
    /// ```
    fn conditional_update_resource(
        &self,
        resource_type: &str,
        id: &str,
        data: Value,
        expected_version: &RawVersion,
        context: &RequestContext,
    ) -> impl Future<Output = Result<ConditionalResult<VersionedResource>, Self::Error>> + Send
    where
        Self: Sync,
    {
        async move {
            // Get current resource
            match self.get_resource(resource_type, id, context).await? {
                Some(current_resource) => {
                    // Create versioned resource to get current version
                    let versioned_current = current_resource;
                    let current_version = versioned_current.version();

                    // Check if versions match
                    if current_version != expected_version {
                        return Ok(ConditionalResult::VersionMismatch(
                            VersionConflict::standard_message(
                                expected_version.clone(),
                                current_version.clone(),
                            ),
                        ));
                    }

                    // Version matches, proceed with update
                    match self
                        .update_resource(resource_type, id, data, None, context)
                        .await
                    {
                        Ok(updated_resource) => {
                            let versioned_result = updated_resource;
                            Ok(ConditionalResult::Success(versioned_result))
                        }
                        Err(e) => Err(e),
                    }
                }
                None => Ok(ConditionalResult::NotFound),
            }
        }
    }

    /// Perform a conditional delete operation.
    ///
    /// Deletes a resource only if the current version matches the expected version,
    /// preventing accidental deletion of modified resources.
    ///
    /// # Arguments
    /// * `resource_type` - The type of resource to delete
    /// * `id` - The unique identifier of the resource
    /// * `expected_version` - The version the client expects (for conflict detection)
    /// * `context` - Request context containing tenant information
    ///
    /// # Returns
    /// * `Success(())` - Delete succeeded
    /// * `VersionMismatch(VersionConflict)` - Resource was modified by another client
    /// * `NotFound` - Resource doesn't exist
    fn conditional_delete_resource(
        &self,
        resource_type: &str,
        id: &str,
        expected_version: &RawVersion,
        context: &RequestContext,
    ) -> impl Future<Output = Result<ConditionalResult<()>, Self::Error>> + Send
    where
        Self: Sync,
    {
        async move {
            // Get current resource
            match self.get_resource(resource_type, id, context).await? {
                Some(current_resource) => {
                    // Create versioned resource to get current version
                    let versioned_current = current_resource;
                    let current_version = versioned_current.version();

                    // Check if versions match
                    if current_version != expected_version {
                        return Ok(ConditionalResult::VersionMismatch(
                            VersionConflict::standard_message(
                                expected_version.clone(),
                                current_version.clone(),
                            ),
                        ));
                    }

                    // Version matches, proceed with delete
                    match self.delete_resource(resource_type, id, None, context).await {
                        Ok(_) => Ok(ConditionalResult::Success(())),
                        Err(e) => Err(e),
                    }
                }
                None => Ok(ConditionalResult::NotFound),
            }
        }
    }

    /// Perform a conditional PATCH operation.
    ///
    /// Applies PATCH operations to a resource only if the current version matches
    /// the expected version, combining version control with incremental updates.
    ///
    /// # Arguments
    /// * `resource_type` - The type of resource to patch
    /// * `id` - The unique identifier of the resource
    /// * `patch_request` - The PATCH operations to apply
    /// * `expected_version` - The version the client expects (for conflict detection)
    /// * `context` - Request context containing tenant information
    ///
    /// # Returns
    /// * `Success(VersionedResource)` - PATCH succeeded with updated resource and version
    /// * `VersionMismatch(VersionConflict)` - Resource was modified by another client
    /// * `NotFound` - Resource doesn't exist
    fn conditional_patch_resource(
        &self,
        resource_type: &str,
        id: &str,
        patch_request: &Value,
        expected_version: &RawVersion,
        context: &RequestContext,
    ) -> impl Future<Output = Result<ConditionalResult<VersionedResource>, Self::Error>> + Send
    where
        Self: Sync,
    {
        async move {
            // Get current resource
            match self.get_resource(resource_type, id, context).await? {
                Some(current_resource) => {
                    // Create versioned resource to get current version
                    let versioned_current = current_resource;
                    let current_version = versioned_current.version();

                    // Check if versions match
                    if current_version != expected_version {
                        return Ok(ConditionalResult::VersionMismatch(
                            VersionConflict::standard_message(
                                expected_version.clone(),
                                current_version.clone(),
                            ),
                        ));
                    }

                    // Version matches, proceed with patch
                    match self
                        .patch_resource(resource_type, id, patch_request, None, context)
                        .await
                    {
                        Ok(patched_resource) => {
                            let versioned_result = patched_resource;
                            Ok(ConditionalResult::Success(versioned_result))
                        }
                        Err(e) => Err(e),
                    }
                }
                None => Ok(ConditionalResult::NotFound),
            }
        }
    }

    /// Get a resource with its version information.
    ///
    /// Retrieves a resource wrapped in a VersionedResource container that includes
    /// both the resource data and its computed version for use in conditional operations.
    ///
    /// # Arguments
    /// * `resource_type` - The type of resource to retrieve
    /// * `id` - The unique identifier of the resource
    /// * `context` - Request context containing tenant information
    ///
    /// # Returns
    /// The versioned resource if found, None if not found
    ///
    /// # Example
    /// ```rust,no_run
    /// // ConditionalOperations provides get_versioned_resource for getting resources with version info
    /// // if let Some(versioned_resource) = provider.get_versioned_resource("Users", "123", &context).await? {
    /// //     let current_version = versioned_resource.version().clone();
    /// //     // Use current_version for subsequent conditional operations
    /// // }
    /// ```
    fn get_versioned_resource(
        &self,
        resource_type: &str,
        id: &str,
        context: &RequestContext,
    ) -> impl Future<Output = Result<Option<VersionedResource>, Self::Error>> + Send
    where
        Self: Sync,
    {
        async move {
            match self.get_resource(resource_type, id, context).await? {
                Some(versioned_resource) => Ok(Some(versioned_resource)),
                None => Ok(None),
            }
        }
    }

    /// Create a resource with version information.
    ///
    /// Creates a new resource and returns it wrapped in a VersionedResource container
    /// with its initial computed version for immediate use in conditional operations.
    ///
    /// # Arguments
    /// * `resource_type` - The type of resource to create
    /// * `data` - The resource data as JSON
    /// * `context` - Request context containing tenant information
    ///
    /// # Returns
    /// The newly created versioned resource
    ///
    /// # Example
    /// ```rust,no_run
    /// use serde_json::json;
    ///
    /// let user_data = json!({"userName": "john.doe", "active": true});
    /// // ConditionalOperations provides create_versioned_resource for creating resources with version info
    /// // let versioned_user = provider.create_versioned_resource("Users", user_data, &context).await?;
    /// // let initial_version = versioned_user.version().clone();
    /// ```
    fn create_versioned_resource(
        &self,
        resource_type: &str,
        data: Value,
        context: &RequestContext,
    ) -> impl Future<Output = Result<VersionedResource, Self::Error>> + Send
    where
        Self: Sync,
    {
        async move {
            let versioned_resource = self.create_resource(resource_type, data, context).await?;
            Ok(versioned_resource)
        }
    }

    /// Check if a resource version matches the expected version.
    ///
    /// Utility method for comparing resource versions without performing operations,
    /// useful for validation or pre-flight checks.
    ///
    /// # Arguments
    /// * `resource_type` - The type of resource to check
    /// * `id` - The unique identifier of the resource
    /// * `expected_version` - The version to compare against
    /// * `context` - Request context containing tenant information
    ///
    /// # Returns
    /// * `Some(true)` - Resource exists and version matches
    /// * `Some(false)` - Resource exists but version doesn't match
    /// * `None` - Resource doesn't exist
    fn check_resource_version(
        &self,
        resource_type: &str,
        id: &str,
        expected_version: &RawVersion,
        context: &RequestContext,
    ) -> impl Future<Output = Result<Option<bool>, Self::Error>> + Send
    where
        Self: Sync,
    {
        async move {
            match self.get_resource(resource_type, id, context).await? {
                Some(versioned_resource) => {
                    Ok(Some(versioned_resource.version() == expected_version))
                }
                None => Ok(None),
            }
        }
    }

    /// Get the current version of a resource without retrieving the full resource.
    ///
    /// Optimized method for retrieving just the version information, useful for
    /// version checks without the overhead of full resource retrieval.
    ///
    /// # Arguments
    /// * `resource_type` - The type of resource to check
    /// * `id` - The unique identifier of the resource
    /// * `context` - Request context containing tenant information
    ///
    /// # Returns
    /// The current version if the resource exists, None if not found
    ///
    /// # Default Implementation
    /// The default implementation retrieves the full resource and computes the version.
    /// Implementers may override this for more efficient version-only retrieval.
    fn get_resource_version(
        &self,
        resource_type: &str,
        id: &str,
        context: &RequestContext,
    ) -> impl Future<Output = Result<Option<RawVersion>, Self::Error>> + Send
    where
        Self: Sync,
    {
        async move {
            match self.get_resource(resource_type, id, context).await? {
                Some(versioned_resource) => Ok(Some(versioned_resource.version().clone())),
                None => Ok(None),
            }
        }
    }

    /// Validate that a version is in the expected format.
    ///
    /// Checks that a version string or RawVersion follows expected patterns,
    /// useful for input validation before conditional operations.
    ///
    /// # Arguments
    /// * `version` - The version to validate
    ///
    /// # Returns
    /// `true` if the version format is acceptable
    fn is_valid_version(&self, version: &RawVersion) -> bool {
        // Basic validation - version should not be empty
        !version.as_str().trim().is_empty()
    }

    /// Create a version conflict error with standard messaging.
    ///
    /// Helper method for creating consistent version conflict errors across
    /// conditional operations.
    ///
    /// # Arguments
    /// * `expected` - The version the client expected
    /// * `current` - The actual current version on the server
    /// * `resource_info` - Optional additional context about the resource
    ///
    /// # Returns
    /// A VersionConflict with appropriate error messaging
    fn create_version_conflict(
        &self,
        expected: RawVersion,
        current: RawVersion,
        resource_info: Option<&str>,
    ) -> VersionConflict {
        let message = match resource_info {
            Some(info) => format!(
                "Resource {} was modified by another client. Expected version {}, current version {}",
                info,
                expected.as_str(),
                current.as_str()
            ),
            None => format!(
                "Resource was modified by another client. Expected version {}, current version {}",
                expected.as_str(),
                current.as_str()
            ),
        };
        VersionConflict::new(expected, current, message)
    }
}

/// Default implementation for any ResourceProvider
impl<T: ResourceProvider> ConditionalOperations for T {}