public async Task <U> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken) { _logger.LogDebug("FindByNameAsync({0})", normalizedUserName); try { CallSettings callSettings = CallSettings.FromCancellationToken(cancellationToken); using (var transaction = await _datastore.BeginTransactionAsync( callSettings)) { var indexEntity = await transaction.LookupAsync( _nnindexKeyFactory.CreateKey(normalizedUserName), callSettings); if (null == indexEntity) { return(null); } return(EntityToUser(await transaction.LookupAsync( (Key)indexEntity[USER_KEY], callSettings))); } } catch (Grpc.Core.RpcException e) when(e.Status.StatusCode == StatusCode.NotFound) { return(null); } }
public async Task <T> InsertAsync <T>(T entity) where T : class { CommitResponse resp; using (DatastoreTransaction transaction = await _db.BeginTransactionAsync()) { var e = ToEntity(entity); transaction.Insert(e); resp = await transaction.CommitAsync(); } return(entity); }
public async Task <User> Create(User user) { using (DatastoreTransaction transaction = await _db.BeginTransactionAsync()) { var entity = user.ToEntity(); entity.Key = _db.CreateKeyFactory("User").CreateIncompleteKey(); transaction.Insert(entity); await transaction.CommitAsync(); user.Id = entity.Key.ToId(); } return(user); }
public async Task <Role> Create(Role role) { using (DatastoreTransaction transaction = await _db.BeginTransactionAsync()) { var entity = role.ToEntity(); entity.Key = _db.CreateKeyFactory("Spot").CreateIncompleteKey(); transaction.Insert(entity); await transaction.CommitAsync(); role.Id = entity.Key.ToId(); } return(role); }
public async Task <Spot> Create(Spot spot) { using (DatastoreTransaction transaction = await _db.BeginTransactionAsync()) { var entity = spot.ToEntity(); entity.Key = _db.CreateKeyFactory("Spot").CreateIncompleteKey(); transaction.Insert(entity); await transaction.CommitAsync(); spot.Id = entity.Key.ToId(); } return(spot); }
private async Task CondenseOldCounters(IEnumerable <string> keyNames, CallSettings callSettings) { var keys = keyNames.Select((keyName) => _keyFactory.CreateKey(keyName)); long sum = 0; using (var transaction = await _datastore.BeginTransactionAsync()) { var entities = (await transaction.LookupAsync(keys, callSettings)) .Where(e => e != null); if (entities.Count() < 2) { return; // Nothing to condense. } foreach (Entity entity in entities) { sum += (long)entity[COUNT]; } Entity first = entities.First(); first[COUNT] = sum; first[COUNT].ExcludeFromIndexes = true; first[TIMESTAMP] = DateTime.UtcNow; transaction.Update(first); transaction.Delete(entities.Skip(1)); await transaction.CommitAsync(); } }
protected override async Task <IImmutableList <Exception> > WriteMessagesAsync(IEnumerable <AtomicWrite> messages) { var writes = messages as IList <AtomicWrite> ?? messages.ToList(); IList <Entity> entities = new List <Entity>(writes.Count); using (var tr = await _db.BeginTransactionAsync()) { foreach (var w in writes) { var rootEntity = await GetOrCreateRootEntity(w.PersistenceId, w.HighestSequenceNr); foreach (var p in (IEnumerable <IPersistentRepresentation>)w.Payload) { var entity = new Entity { Key = EntityKey(p.PersistenceId, p.SequenceNr), [JournalFields.SequenceNr] = p.SequenceNr, [JournalFields.Manifest] = p.Manifest, [JournalFields.WriterGuid] = p.WriterGuid, [JournalFields.Payload] = new Value { BlobValue = ByteString.CopyFrom(Serialize(p)), ExcludeFromIndexes = true } }; entities.Add(entity); } //update SeqNr on root object tr.Upsert(rootEntity); } tr.Upsert(entities); tr.Commit(); } return(await Task.FromResult((IImmutableList <Exception>) null)); // all good }
public async Task SetFighterVoteAsync(string id) { var key = _keyFactory.CreateKey(id); var fighter = await _db.LookupAsync(key); if (fighter == null) { return; } fighter["vote"] = fighter.Properties["vote"].IntegerValue + 1; using (var transaction = await _db.BeginTransactionAsync()) { transaction.Update(fighter); await transaction.CommitAsync(); } }
protected override async Task SaveAsync(SnapshotMetadata metadata, object snapshot) { var rootEntity = SnapshotToEntity(metadata, snapshot); var snapshotEntity = new Entity(rootEntity); using (var tr = await _db.BeginTransactionAsync()) { rootEntity.Key = RootKey(metadata.PersistenceId); snapshotEntity.Key = EntityKey(metadata.PersistenceId, metadata.SequenceNr); tr.Upsert(rootEntity, snapshotEntity); tr.Commit(); } }
protected async Task <bool> Insert <T>(T item) { try { var keyFactory = _db.CreateKeyFactory(_kind.GetDescription()); using var tran = await _db.BeginTransactionAsync(); var entityToInsert = new Entity { Key = keyFactory.CreateIncompleteKey() }; tran.Insert(MapToEntity(entityToInsert, item)); return((await tran.CommitAsync()).IndexUpdates > 0); } catch (Exception ex) { var exceptionMsg = $"{GetType().FullName}.Insert experienced a {ex.GetType()}"; _logger.LogError(ex, exceptionMsg); throw new Exception(exceptionMsg, ex); } }
public async Task RollbackAsync() { string projectId = _fixture.ProjectId; string namespaceId = _fixture.NamespaceId; // Snippet: RollbackAsync(*) DatastoreDb db = DatastoreDb.Create(projectId, namespaceId); KeyFactory keyFactory = db.CreateKeyFactory("message"); // Dispose automatically rolls back an uncommitted transaction synchronously. // To roll back asynchronously, bool committed = false; DatastoreTransaction transaction = await db.BeginTransactionAsync(); try { Entity message = new Entity { Key = keyFactory.CreateIncompleteKey(), ["text"] = "Hello", }; // This adds the entity to a collection in memory: nothing // is sent to the server. db.Insert(message); // Attempt to commit the transaction asynchronously. await transaction.CommitAsync(); committed = true; } finally { if (!committed) { // Roll back asynchronously if anything failed. await transaction.RollbackAsync(); } } // End snippet }
/// <summary> /// The main loop of a Task that periodically cleans up expired sessions. /// Never returns. /// </summary> private async Task SweepTaskMain() { var random = System.Security.Cryptography.RandomNumberGenerator.Create(); var randomByte = new byte[1]; while (true) { random.GetBytes(randomByte); // Not a perfect distrubution, but fine for our limited purposes. int randomMinute = randomByte[0] % 60; _log.DebugFormat("Delaying {0} minutes before checking sweep lock.", randomMinute); await Task.Delay(TimeSpan.FromMinutes(randomMinute)); // Use a lock to make sure no clients are sweeping at the same time, or // sweeping more often than once per hour. try { using (var transaction = await _datastore.BeginTransactionAsync(_callSettings)) { const string SWEEP_BEGIN_DATE = "beginDate", SWEEPER = "sweeper", SWEEP_LOCK_KIND = "SweepLock"; var key = _datastore.CreateKeyFactory(SWEEP_LOCK_KIND).CreateKey(1); Entity sweepLock = await transaction.LookupAsync(key, _callSettings) ?? new Entity() { Key = key }; bool sweep = true; try { sweep = DateTime.UtcNow - ((DateTime)sweepLock[SWEEP_BEGIN_DATE]) > TimeSpan.FromHours(1); } catch (Exception e) { _log.Error("Error reading sweep begin date.", e); } if (!sweep) { _log.Debug("Not yet time to sweep."); continue; } sweepLock[SWEEP_BEGIN_DATE] = DateTime.UtcNow; sweepLock[SWEEPER] = Environment.MachineName; transaction.Upsert(sweepLock); await transaction.CommitAsync(_callSettings); } } catch (Exception e) { _log.Error("Error acquiring sweep lock.", e); continue; } try { _log.Info("Beginning sweep."); // Find old sessions to clean up var now = DateTime.UtcNow; var query = new Query(SESSION_LOCK_KIND) { Filter = Filter.LessThan(EXPIRES, now), Projection = { "__key__" } }; foreach (Entity lockEntity in _datastore.RunQueryLazily(query)) { try { using (var transaction = _datastore.BeginTransaction(_callSettings)) { var sessionLock = SessionLockFromEntity(transaction.Lookup(lockEntity.Key, _callSettings)); if (sessionLock == null || sessionLock.ExpirationDate > now) { continue; } transaction.Delete(lockEntity.Key, _sessionKeyFactory.CreateKey(lockEntity.Key.Path.First().Name)); transaction.Commit(_callSettings); } } catch (Exception e) { _log.Error("Failed to delete session.", e); } } _log.Info("Done sweep."); } catch (Exception e) { _log.Error("Failed to query expired sessions.", e); } } }