Skip to content

Added if_match_etag to Item Options #2705

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 14 commits into
base: main
Choose a base branch
from

Conversation

gsa9989
Copy link

@gsa9989 gsa9989 commented Jun 13, 2025

Added if_match_etag functionality and tests for replace item, upsert item, delete item, and patch item functions. Tests have not been recorded yet, but tests added include item_replace_if_match_etag, item_upsert_if_match_etag, item_delete_if_match_etag, and item_patch_if_match_etag. All these tests include a scenario with using if_match_etag with the correct etag and an incorrect etag.

Links

https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/database-transactions-optimistic-concurrency#optimistic-concurrency-control

gsa9989 and others added 11 commits June 3, 2025 11:42
  ItemOptions-changes 41f2acf if_match_etag changes with tests
* main                b1d2f9f [origin/main] Merge pull request #1 from gsa9989/read-me-change
  read-me-change      653b308 read me change Please enter a commit message to explain why this merge is necessary,
  ItemOption-changes 41f2acf if_match_etag changes with tests
* main                b1d2f9f [origin/main] Merge pull request #1 from gsa9989/read-me-change
  read-me-change      653b308 merge upstream/main
Copy link

Thank you for your contribution @gsa9989! We will review the pull request and get back to you soon.

@github-actions github-actions bot added Community Contribution Community members are working on the issue Cosmos The azure_cosmos crate customer-reported Issues that are reported by GitHub users external to the Azure organization. labels Jun 13, 2025
@@ -17,6 +17,7 @@
* Added a function `CosmosClient::with_connection_string` to enable `CosmosClient` creation via connection string. ([#2641](https://github.com/Azure/azure-sdk-for-rust/pull/2641))
* Added support for executing limited cross-partition queries through the Gateway. See <https://learn.microsoft.com/rest/api/cosmos-db/querying-cosmosdb-resources-using-the-rest-api#queries-that-cannot-be-served-by-gateway> for more details on these limitations. ([#2577](https://github.com/Azure/azure-sdk-for-rust/pull/2577))
* Added a preview feature (behind `preview_query_engine` feature flag) to allow the Rust SDK to integrate with an external query engine for performing cross-partition queries. ([#2577](https://github.com/Azure/azure-sdk-for-rust/pull/2577))
* Added 'if_match_etag' to ItemOptions and necessary functions (tbd)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should be able to put the link to this PR in there now, right?

@@ -35,7 +35,7 @@ impl ContainerClient {
database_link: &ResourceLink,
container_id: &str,
) -> Self {
let link = database_link
let link: ResourceLink = database_link
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, this type annotation shouldn't be needed! The type of link should be apparent to the compiler from the return type of .item. You can just revert this back to how it was before :)

Copy link
Contributor

@gsa9989 please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

Copy link
Member

@analogrelay analogrelay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! A few suggestions, they're mostly not functional problems and just style/aesthetics stuff. The most critical functional thing to change is the way we're handling the response etag. We need to make sure we fail if the server doesn't return one.

As I expected, the tests are a bit repetitive, but I think duplicating logic is OK for now. We can refactor them when we have a better idea how we're testing all the different combinations of item options.

Overall a great first PR!

@@ -35,7 +35,7 @@ impl ContainerClient {
database_link: &ResourceLink,
container_id: &str,
) -> Self {
let link = database_link
let link: ResourceLink = database_link
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, this type annotation shouldn't be needed! The type of link should be apparent to the compiler from the return type of .item. You can just revert this back to how it was before :)

@@ -47,7 +47,7 @@ pub struct DeleteDatabaseOptions<'a> {
#[derive(Clone, Default)]
pub struct ItemOptions<'a> {
pub method_options: ClientMethodOptions<'a>,

pub if_match_etag: Option<Etag>,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add documentation comments to this, I'm trying to keep us up-to-date on that as we add features :).

I'll let you take a first stab at writing it, take a look at the comments for the other fields (method_options doesn't have one yet, but we'll address that later) and see what you think. Happy to help if you're not sure what to write! I'd include a link to this content on our docs site as well: https://learn.microsoft.com/azure/cosmos-db/nosql/database-transactions-optimistic-concurrency#optimistic-concurrency-control , since it describes the if-match header in detail.

Comment on lines 134 to 135
## Next steps

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You'll need to undo this change. Even though the Next Steps section itself is empty, it has nested sections (Provide feedback, for example).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This section seems to be repeated. There is a next steps section right above it with information. Is that by design?

Comment on lines 433 to 438
const ETAG: HeaderName = HeaderName::from_static("etag");
let etag = response
.headers()
.get_str(&ETAG)
.ok()
.map(|s| Etag::from(s.to_string()));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a constant in azure_core you can use, and it's already a HeaderName 🎉

I'd also change the .ok() to .expect("expected the etag to be returned"), which means you can rewrite it like this:

Suggested change
const ETAG: HeaderName = HeaderName::from_static("etag");
let etag = response
.headers()
.get_str(&ETAG)
.ok()
.map(|s| Etag::from(s.to_string()));
let etag: Etag = response
.headers()
.get_str(&azure_core::http::headers::ETAG)
.expect("expected the etag to be returned")
.into();

Using .expect means you'll unwrap the Option<String> into a String, causing a panic if the header is missing. For product code this would be bad, but in a test it's actually preferable. It's OK for test code to panic when something unexpected happens, it won't break the other tests, it'll just cause this test to fail. If for some reason the service stops returning etags, we want this test to fail, but if we're passing the Option<Etag> back in to the if_match_etag option later, then the test might continue to pass even though the behavior of the service is unexpected.

This is also a case where a type annotation (let etag: Etag) is needed because you need to tell Rust what the .into() at the end should return (any place you can write SomeType::from(some_value) you can also write the same thing like this: some_value.into(), as long as Rust can figure out what the target type is)

&item,
Some(ItemOptions {
if_match_etag: etag,
enable_content_response_on_write: false,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
enable_content_response_on_write: false,

This should be the default behavior, so let's just omit it since we're not trying to test this option in this test.

Comment on lines 458 to 459
let body = response.into_raw_body().collect_string().await?;
assert_eq!("", body);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar to the above, we're not trying to test enable_content_response_on_write behavior in this test, so let's just omit this check.

Suggested change
let body = response.into_raw_body().collect_string().await?;
assert_eq!("", body);

Comment on lines 478 to 490
match response {
Ok(_) => {
return Err(
"expected a 412 Precondition Failed error when using an incorrect ETag".into(),
);
}
Err(err) => {
assert_eq!(
Some(azure_core::http::StatusCode::PreconditionFailed),
err.http_status()
);
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is good error handling for product code, since you're properly matching on the Result<...> returned by .replace_item. But in a test, where we know that the server is supposed to return an error and the test should fail if it does not return what we expect, we can simplify this quite a bit!

Suggested change
match response {
Ok(_) => {
return Err(
"expected a 412 Precondition Failed error when using an incorrect ETag".into(),
);
}
Err(err) => {
assert_eq!(
Some(azure_core::http::StatusCode::PreconditionFailed),
err.http_status()
);
}
}
assert_eq!(
Some(azure_core::http::StatusCode::PreconditionFailed),
response.expect_err("expected the server to return an error").http_status()
);

The .expect_err method works a lot like .expect. It's just the opposite. Where .expect is used to unpack the successful return value from a Result (and panic if the Result represents an error), .expect_err unpacks the error from a Result (and panics if the Result represents a successful operation).

}

#[recorded::test]
pub async fn item_upsert_if_match_etag(context: TestContext) -> Result<(), Box<dyn Error>> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Most of the feedback from the above test applies to this one as well, so I won't repeat it all here :)

}

#[recorded::test]
pub async fn item_delete_if_match_etag(context: TestContext) -> Result<(), Box<dyn Error>> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And the same for this one

}

#[recorded::test]
pub async fn item_patch_if_match_etag(context: TestContext) -> Result<(), Box<dyn Error>> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And this one ;)

@@ -17,6 +17,7 @@
* Added a function `CosmosClient::with_connection_string` to enable `CosmosClient` creation via connection string. ([#2641](https://github.com/Azure/azure-sdk-for-rust/pull/2641))
* Added support for executing limited cross-partition queries through the Gateway. See <https://learn.microsoft.com/rest/api/cosmos-db/querying-cosmosdb-resources-using-the-rest-api#queries-that-cannot-be-served-by-gateway> for more details on these limitations. ([#2577](https://github.com/Azure/azure-sdk-for-rust/pull/2577))
* Added a preview feature (behind `preview_query_engine` feature flag) to allow the Rust SDK to integrate with an external query engine for performing cross-partition queries. ([#2577](https://github.com/Azure/azure-sdk-for-rust/pull/2577))
* Added 'if_match_etag' to ItemOptions and necessary functions ([#2705](https://github.com/Azure/azure-sdk-for-rust/pull/2705))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should go above in the unreleased section. 0.24.0 is already released. Your change would be part of the next release.


/// IfMatchEtag is used to ensure optimistic concurrency control, it helps prevent accidental overwrites and maintains data integrity.
///
/// https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/database-transactions-optimistic-concurrency#optimistic-concurrency-control
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like your PR build is failing with the same linting error I faced from adding plain URLs in comments :P

You'll likely change this comment to address Ashley's request for documentation, so when you do, putting the URL in backticks (``) should make the lint error from the build go away. Like this:

https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/database-transactions-optimistic-concurrency#optimistic-concurrency-control

Copy link

API Change Check

APIView identified API level changes in this PR and created the following API reviews

azure_data_cosmos

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Community Contribution Community members are working on the issue Cosmos The azure_cosmos crate customer-reported Issues that are reported by GitHub users external to the Azure organization.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants