A Cosmos DB database contains two containers, ContainerA and ContainerB. Stored procedures (SPs) are being created for both containers with the same ID and body.
The consistency level for Cosmos DB is set to strong. ContainerA does not have any SPs, while ContainerB contains several. An attempt to create the same SP in ContainerA leads to various errors.
When trying to read the SP with a particular ID, the following error is received:
Response status code does not indicate success: NotFound (404);
code : NotFound
message : Message: {"Errors":["Resource Not Found."]}
When attempting to create the SP with a particular ID, the error encountered is:
Response status code does not indicate success: Conflict (409);
code : Conflict
message : Message: {"Errors":["Resource with specified id, name, or unique index already exists."]}
After receiving the conflict error, an attempt is made to replace the existing SP by waiting for some time for propagation, but the following error is returned:
Response status code does not indicate success: NotFound (404);
code : NotFound
message : Entity with the specified id does not exist in the system.
Creating SPs directly in the Azure portal's Data Explorer results in:
Error while creating stored procedure spProductUpsert:
Message: {"code":"NotFound","message":"Entity with the specified id does not exist in the system."}
The questions are:
- How can the issues of transitioning from Not Found to Conflict (and vice versa) be resolved?
- How can the same SPs with the same ID be created in ContainerA?
private async Task<StoredProcedureProperties> GetOrCreateStoreProcedure(string embeddedResourcePath, string spId, CosmosClient documentClient, Container collection)
{
try
{
string body;
using (StreamReader sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedResourcePath), Encoding.UTF8))
{
body = sr.ReadToEnd();
}
try
{
return await collection.Scripts.ReadStoredProcedureAsync(spId);
}
catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
try
{
return await collection.Scripts.CreateStoredProcedureAsync(new StoredProcedureProperties { Id = spId, Body = body });
}
catch (CosmosException exception) when (exception.StatusCode == HttpStatusCode.Conflict)
{
await Task.Delay(2000); //wait 2 sec
return await collection.Scripts.ReplaceStoredProcedureAsync(new StoredProcedureProperties { Id = spId, Body = body });
}
}
}
catch (Exception ex)
{
throw ex;
}
}