@@ -46,7 +46,7 @@ public class CosmosDBSessionStateProviderAsync : SessionStateStoreProviderAsyncB
4646 } ;
4747
4848 #region CosmosDB Stored Procedures
49- private const string CreateSessionStateItemSPID = "CreateSessionStateItem " ;
49+ private const string CreateSessionStateItemSPID = "CreateSessionStateItem2 " ;
5050 private const string GetStateItemSPID = "GetStateItem2" ;
5151 private const string GetStateItemExclusiveSPID = "GetStateItemExclusive" ;
5252 private const string ReleaseItemExclusiveSPID = "ReleaseItemExclusive" ;
@@ -55,7 +55,7 @@ public class CosmosDBSessionStateProviderAsync : SessionStateStoreProviderAsyncB
5555 private const string UpdateSessionStateItemSPID = "UpdateSessionStateItem" ;
5656
5757 private const string CreateSessionStateItemSP = @"
58- function CreateSessionStateItem (sessionId, timeout, lockCookie, sessionItem, uninitialized) {
58+ function CreateSessionStateItem2 (sessionId, timeout, lockCookie, sessionItem, uninitialized) {
5959 var collection = getContext().getCollection();
6060 var collectionLink = collection.getSelfLink();
6161 var response = getContext().getResponse();
@@ -74,10 +74,22 @@ function CreateSessionStateItem(sessionId, timeout, lockCookie, sessionItem, uni
7474 ttl: timeout, locked: false, sessionItem: sessionItem, uninitialized: uninitialized };
7575 collection.createDocument(collectionLink, sessionStateItem,
7676 function (err, documentCreated) {
77- if (err) {
77+ if (err)
78+ {
79+ // When creating an uninitialized item, we are doing so just to make sure it gets created.
80+ // If another request has done the same, it doesn't matter who won the race. Read/Write
81+ // locked/exclusive access is determined later via a separate GetStateItem call.
82+ if (uninitialized && err.number == 409) // message: 'Resource with specified id or name already exists.'
83+ {
84+ response.setBody({message: 'Document already exists. No need to recreate uninitialized document.', error: err});
85+ }
86+
7887 throw err;
7988 }
80- response.setBody({documentCreated: documentCreated});
89+ else
90+ {
91+ response.setBody({documentCreated: documentCreated});
92+ }
8193 });
8294 }" ;
8395
@@ -208,6 +220,7 @@ function tryGetStateItemExclusive(continuation) {
208220 doc.lockAge = 0;
209221 doc.lockCookie += 1;
210222 doc.locked = true;
223+ // CosmosDB sprocs are 'atomic' so no need to worry about a race in between the initial query and this update.
211224 var isAccepted = collection.replaceDocument(doc._self, doc,
212225 function(err, updatedDocument, responseOptions) {
213226 if (err)
0 commit comments