public async Task RunAsyncWithMessage()
        {
            var state = Substitute.For<IReliableStateManager>();
            var queueName = Guid.NewGuid().ToString();
            var queue = Substitute.For<IReliableQueue<object>>();
            var msg = new ConditionalValue<object>(false, null);

            var tx = Substitute.For<ITransaction>();
            //state.GetOrAddAsync<IReliableQueue<object>>(queueName).Returns(queue);
            //state.CreateTransaction().Returns(tx);
            queue.TryDequeueAsync(tx).Returns(msg);
            var processor = Substitute.For<IProcessor<object>>();

            var ds = new FakeDequeueService(state, queueName, processor);

            var ct = new CancellationTokenSource();

            using (var t = new Timer(new TimerCallback((object obj) => { ct.Cancel(); }), null, 3, Timeout.Infinite))
            {
                await ds.RunTest(ct.Token);
            }

            //await state.Received().GetOrAddAsync<IReliableQueue<object>>(queueName);
            //state.Received().CreateTransaction();
            await tx.Received(0).CommitAsync();
            await queue.Received().TryDequeueAsync(tx);
            await processor.Received(0).Process(Arg.Any<object>());
            await tx.Received(0).CommitAsync();
            Assert.Inconclusive();
        }
        public async Task <Product> GetProduct(Guid productId)
        {
            var products = await StateManager.GetOrAddAsync <IReliableDictionary <Guid, Product> >("products");

            using (var tx = StateManager.CreateTransaction())
            {
                ConditionalValue <Product> product = await products.TryGetValueAsync(tx, productId);

                return(product.HasValue ? product.Value : null);
            }
        }
        public async Task <Tuple <CountyRecord, string> > GetInfoAndNameAsync()
        {
            ConditionalValue <DoctorActorState> doctorActorStateResult = await this.StateManager.TryGetStateAsync <DoctorActorState>("DoctorActorState");

            if (doctorActorStateResult.HasValue)
            {
                return(new Tuple <CountyRecord, string>(doctorActorStateResult.Value.CountyInfo, doctorActorStateResult.Value.Name));
            }

            throw new ArgumentException(string.Format("No actor state in actor {0}", this.Id));
        }
Пример #4
0
        public async Task <Quote> Get(Guid id)
        {
            var quotes = await _stateManager.GetOrAddAsync <IReliableDictionary <Guid, Quote> >("quotes");

            using (var tx = _stateManager.CreateTransaction())
            {
                ConditionalValue <Quote> quote = await quotes.TryGetValueAsync(tx, id);

                return(quote.HasValue ? quote.Value : null);
            }
        }
        private async Task GenerateHealthDataAsync()
        {
            ConditionalValue <BandActorState> BandActorStateResult = await this.StateManager.TryGetStateAsync <BandActorState>("BandActorState");

            if (BandActorStateResult.HasValue)
            {
                BandActorStateResult.Value.AddHeartRateRecord(new HeartRateRecord((float)this.random.NextDouble()));
                await this.StateManager.SetStateAsync <BandActorState>("BandActorState", BandActorStateResult.Value);
            }
            return;
        }
Пример #6
0
        public async Task <PolicyArtifact> GetPolicyQuoteById(Guid id)
        {
            var policies = await _stateManager.GetOrAddAsync <IReliableDictionary <Guid, PolicyArtifact> >("policyquotes");

            using (var tx = _stateManager.CreateTransaction())
            {
                ConditionalValue <PolicyArtifact> product = await policies.TryGetValueAsync(tx, id);

                return(product.HasValue ? product.Value : null);
            }
        }
        public async Task <Guid> GetAssociatedDoctorAsync()
        {
            ConditionalValue <Guid> DoctorInfoResult = await this.StateManager.TryGetStateAsync <Guid>("DoctorId");

            if (DoctorInfoResult.HasValue)
            {
                return(DoctorInfoResult.Value);
            }

            throw new ArgumentException(string.Format("No band actor state {0}|{1}", this.Id, this.Id.Kind));
        }
Пример #8
0
        public async Task <Product> GetProduct(int productId)
        {
            Logger.Debug("GetProduct: #{0}", productId);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                ConditionalValue <Product> item = await this.productsCollection.TryGetValueAsync(tx, productId);

                return(item.HasValue ? item.Value : null);
            }
        }
Пример #9
0
        private async Task <IList <Movie> > GetMovieFromCache(string searchTerm)
        {
            var movieReliableDictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <string, IList <Movie> > >("SearchCache");

            using (var tx = this.StateManager.CreateTransaction())
            {
                ConditionalValue <IList <Movie> > movieList = await movieReliableDictionary.TryGetValueAsync(tx, searchTerm);

                return(movieList.HasValue ? movieList.Value : null);
            }
        }
        /// <summary>
        /// This method saves the description (eventString) and timestamp of the recentmost induced fault as
        /// a ChaosEntry in a Reliable Dictionary
        /// </summary>
        /// <param name="eventString"></param>
        /// <returns>A task to await on</returns>
        private async Task StoreEventAsync(string eventString)
        {
            ServiceEventSource.Current.ServiceMessage(this, "ChaosTest: {0}", eventString);

            IReliableDictionary <string, long> eventCount =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <string, long> >(StringResource.EventCountKey);

            IReliableDictionary <string, DateTime> startTime =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <string, DateTime> >(StringResource.StartTimeKey);

            IReliableDictionary <long, ChaosEntry> savedEvents =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <long, ChaosEntry> >(StringResource.SavedEventsKey);


            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                if (!await startTime.ContainsKeyAsync(tx, StringResource.StartTimeKey))
                {
                    await startTime.AddAsync(tx, StringResource.StartTimeKey, DateTime.UtcNow);
                }

                if (!await eventCount.ContainsKeyAsync(tx, StringResource.EventCountKey))
                {
                    await eventCount.AddAsync(tx, StringResource.EventCountKey, 0);
                }

                ConditionalValue <long> result =
                    await eventCount.TryGetValueAsync(tx, StringResource.EventCountKey, LockMode.Update);

                if (result.HasValue)
                {
                    long currentCount = result.Value;

                    // If we have HistoryLength number of events, we make room for new events by removing oldest ones,
                    // always keeping HistoryLength number of recentmost events on the show on the webpage.
                    if (currentCount > Constants.HistoryLength - 1)
                    {
                        await savedEvents.TryRemoveAsync(tx, currentCount - Constants.HistoryLength + 1);
                    }

                    ChaosEntry chaosEntry = new ChaosEntry
                    {
                        Record    = eventString,
                        TimeStamp = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)
                    };

                    await savedEvents.AddAsync(tx, ++currentCount, chaosEntry);

                    await eventCount.SetAsync(tx, StringResource.EventCountKey, currentCount);

                    await tx.CommitAsync();
                }
            }
        }
Пример #11
0
        public async Task <User> GetUser(Guid userId)
        {
            var users = await _stateManager.GetOrAddAsync <IReliableDictionary <Guid, Login> >("users");

            using (var tx = _stateManager.CreateTransaction())
            {
                ConditionalValue <Login> user = await users.TryGetValueAsync(tx, userId);

                return(user.HasValue ? user.Value.User : null);
            }
        }
        public Task <ConditionalValue <TValue> > TryRemoveAsync(ITransaction tx, TKey key)
        {
            TValue value;
            var    result = new ConditionalValue <TValue>(_state.TryRemove(key, out value), value);

            if (result.HasValue)
            {
                OnDictionaryChanged(new NotifyDictionaryItemRemovedEventArgs <TKey, TValue>(tx, key));
            }
            return(Task.FromResult(result));
        }
Пример #13
0
        public async Task <Game> GetGame(string gameId)
        {
            var games = await _stateManager.GetOrAddAsync <IReliableDictionary <string, Game> >("Games");

            using (var tx = _stateManager.CreateTransaction())
            {
                ConditionalValue <Game> game = await games.TryGetValueAsync(tx, gameId);

                return(game.HasValue ? game.Value : null);
            }
        }
Пример #14
0
        /// <summary>
        ///     移除缓存键。
        /// </summary>
        /// <param name="key">缓存键。</param>
        public async Task RemoveTeacherSmartCacheAsync(string key)
        {
            ConditionalValue <CacheWrapper <Teacher> > result = await StateManager.TryGetStateAsync <CacheWrapper <Teacher> >(key);

            if (!result.HasValue)
            {
                return;
            }

            await StateManager.RemoveStateAsync(key);
        }
        public async Task <int> GetTransactionsPerSecondAsync()
        {
            var state = await this.StateManager.GetOrAddAsync <IReliableDictionary <string, int> >("state");

            using (var tx = this.StateManager.CreateTransaction())
            {
                ConditionalValue <int> tps = await state.TryGetValueAsync(tx, "tps");

                return(tps.HasValue ? tps.Value : 100);
            }
        }
        public async Task <Processor> Delete([FromUri] string ProcessorName)
        {
            string[] validationErrors = Processor.ValidateProcessName(ProcessorName);
            if (null != validationErrors)
            {
                Utils.ThrowHttpError(validationErrors);
            }


            Processor existing;

            using (ITransaction tx = this.Svc.StateManager.CreateTransaction())
            {
                // do we have it?
                ConditionalValue <Processor> cResults = await this.Svc.ProcessorStateStore.TryGetValueAsync(tx, ProcessorName);

                if (!cResults.HasValue)
                {
                    Utils.ThrowHttpError(string.Format("Processor with the name {0} does not exists", ProcessorName));
                }

                existing = cResults.Value;


                if (existing.IsOkToDelete())
                {
                    Utils.ThrowHttpError(
                        string.Format("Processor with the name {0} not valid for this operation", ProcessorName, existing.ProcessorStatusString));
                }

                existing.ProcessorStatus |= ProcessorStatus.PendingDelete;
                existing = await this.Svc.ProcessorStateStore.AddOrUpdateAsync(
                    tx,
                    existing.Name,
                    existing,
                    (name, proc) =>
                {
                    proc.SafeUpdate(existing);
                    return(proc);
                });

                // delete it
                await
                this.Svc.ProcessorOperationsQueue.EnqueueAsync(
                    tx,
                    new ProcessorOperation()
                {
                    OperationType = ProcessorOperationType.Delete, ProcessorName = ProcessorName
                });

                await tx.CommitAsync();
            }
            return(existing);
        }
Пример #17
0
        private async Task <bool> BackupCallbackAsync(BackupInfo backupInfo, CancellationToken cancellationToken)
        {
            ServiceEventSource.Current.ServiceMessage(Context, "Inside backup callback for replica {0}|{1}", this.Context.PartitionId, this.Context.ReplicaId);
            long totalBackupCount;

            IReliableDictionary <string, long> backupCountDictionary =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <string, long> >(BackupCountDictionaryName);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                ConditionalValue <long> value = await backupCountDictionary.TryGetValueAsync(tx, "backupCount");

                if (!value.HasValue)
                {
                    totalBackupCount = 0;
                }
                else
                {
                    totalBackupCount = value.Value;
                }

                await backupCountDictionary.SetAsync(tx, "backupCount", ++totalBackupCount);

                await tx.CommitAsync();
            }

            ServiceEventSource.Current.Message("Backup count dictionary updated, total backup count is {0}", totalBackupCount);

            try
            {
                ServiceEventSource.Current.ServiceMessage(Context, "Archiving backup");
                await this.backupManager.ArchiveBackupAsync(backupInfo, cancellationToken);

                ServiceEventSource.Current.ServiceMessage(Context, "Backup archived");
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceMessage(Context, "Archive of backup failed: Source: {0} Exception: {1}", backupInfo.Directory, e.Message);
            }

            try
            {
                ServiceEventSource.Current.ServiceMessage(Context, "Deleting backups");
                await this.backupManager.DeleteBackupsAsync(cancellationToken);

                ServiceEventSource.Current.ServiceMessage(Context, "Backups deleted");
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceMessage(Context, "Delete of backup failed: Exception: {1}", e.Message);
            }

            return(true);
        }
Пример #18
0
        /// <summary>
        ///     Registers an entity as observable for a given topic.
        ///     This method is called by a management service or actor.
        /// </summary>
        /// <param name="topic">The topic.</param>
        /// <returns>The asynchronous result of the operation.</returns>
        public async Task RegisterObservableActorAsync(string topic)
        {
            EntityId id = await this.GetEntityIdAsync();

            if (id == null)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(topic))
            {
                throw new ArgumentException($"The {nameof(topic)} parameter cannot be null.", nameof(topic));
            }
            ConditionalValue <Dictionary <Uri, ObserverInfo> > topicState = await this.StateManager.TryGetStateAsync <Dictionary <Uri, ObserverInfo> >(topic);

            if (topicState.HasValue)
            {
                throw new ArgumentException($"{id} is already an observable for Topic=[{topic}]");
            }
            for (int k = 1; k <= ConfigurationHelper.MaxQueryRetryCount; k++)
            {
                try
                {
                    IRegistryService registryService = ServiceProxy.Create <IRegistryService>(
                        ConfigurationHelper.RegistryServiceUri,
                        new ServicePartitionKey(PartitionResolver.Resolve(topic, ConfigurationHelper.RegistryServicePartitionCount)));
                    await registryService.RegisterObservableAsync(topic, id);

                    ActorEventSource.Current.Message($"Observable successfully registered.\r\n[Observable]: {id}\r\n[Publication]: Topic=[{topic}].");
                    await this.StateManager.SetStateAsync(topic, new Dictionary <Uri, ObserverInfo>());

                    return;
                }
                catch (FabricTransientException ex)
                {
                    ActorEventSource.Current.Error(ex);
                }
                catch (AggregateException ex)
                {
                    foreach (Exception e in ex.InnerExceptions)
                    {
                        ActorEventSource.Current.Error(e);
                    }
                    throw;
                }
                catch (Exception ex)
                {
                    ActorEventSource.Current.Error(ex);
                    throw;
                }
                await Task.Delay(ConfigurationHelper.BackoffQueryDelay);
            }
            throw new TimeoutException(Constants.RetryTimeoutExhausted);
        }
Пример #19
0
        public virtual async Task <TValue> GetAsync(TKey key, Func <TKey, Task <TValue> > factory)
        {
            ConditionalValue <TValue> result = default;

            try
            {
                result = await TryGetValueAsync(key);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString(), ex);
            }

            if (result.HasValue)
            {
                return(result.Value);
            }

            using (await SemaphoreSlim.LockAsync())
            {
                try
                {
                    result = await TryGetValueAsync(key);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.ToString(), ex);
                }

                if (result.HasValue)
                {
                    return(result.Value);
                }

                var generatedValue = await factory(key);

                if (IsDefaultValue(generatedValue))
                {
                    return(generatedValue);
                }

                try
                {
                    await SetAsync(key, generatedValue);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.ToString(), ex);
                }

                return(generatedValue);
            }
        }
Пример #20
0
        protected override async Task OnActivateAsync()
        {
            try
            {
                // Initialize States
                await this.StateManager.TryAddStateAsync(QueueState, new Queue <Payload>());

                ConditionalValue <Device> result = await this.StateManager.TryGetStateAsync <Device>(MetadataState);

                if (!result.HasValue)
                {
                    // The device id is a string with the following format: device<number>
                    string deviceIdAsString = this.Id.ToString();
                    long   deviceId;
                    long.TryParse(deviceIdAsString.Substring(6), out deviceId);

                    Device metadata = new Device
                    {
                        DeviceId     = deviceId,
                        Name         = deviceIdAsString,
                        MinThreshold = MinThresholdDefault,
                        MaxThreshold = MaxThresholdDefault,
                        Model        = Unknown,
                        Type         = Unknown,
                        Manufacturer = Unknown,
                        City         = Unknown,
                        Country      = Unknown
                    };
                    await this.StateManager.TryAddStateAsync(MetadataState, metadata);
                }

                // Create EventHubClient
                this.CreateEventHubClient();
            }
            catch (Exception ex)
            {
                // Trace exception as ETW event
                ActorEventSource.Current.Error(ex);

                // Trace exception using Application Insights
                Program.TelemetryClient.TrackException(
                    ex,
                    new Dictionary <string, string>
                {
                    { "ActorType", "DeviceActor" },
                    { "ActorId", this.Id.ToString() },
                    { "ServiceName", this.ActorService.Context.ServiceName.ToString() },
                    { "Partition", this.ActorService.Context.PartitionId.ToString() },
                    { "Node", this.ActorService.Context.NodeContext.NodeName }
                });
            }
        }
Пример #21
0
        protected override async Task OnActivateAsync()
        {
            ConditionalValue <RestockRequestActorState> state = await this.StateManager.TryGetStateAsync <RestockRequestActorState>(ActorStatePropertyName);

            if (!state.HasValue)
            {
                await this.StateManager.SetStateAsync <RestockRequestActorState>(ActorStatePropertyName, new RestockRequestActorState());

                ActorEventSource.Current.ActorMessage(this, "RestockRequestActor: State initialized");
            }

            return;
        }
Пример #22
0
        private async Task <TicketOrder> GetEntityStateAsync()
        {
            ConditionalValue <TicketOrder> stateResult = await this.StateManager.TryGetStateAsync <TicketOrder>(ActorStatePropertyName);

            if (stateResult.HasValue)
            {
                return(stateResult.Value);
            }
            else
            {
                return(null);
            }
        }
        public static async Task <TValue> GetValueOrDefaultAsync <TKey, TValue>(
            this IReliableDictionary <TKey, TValue> dict,
            ITransaction transaction,
            TKey key) where TKey : IComparable <TKey>, IEquatable <TKey>
        {
            ConditionalValue <TValue> maybeValue = await dict.TryGetValueAsync(transaction, key);

            if (maybeValue.HasValue)
            {
                return(maybeValue.Value);
            }

            return(default !);
Пример #24
0
        private async Task <RVSSalesActorStatus> GetOrderStatusAsync()
        {
            ConditionalValue <RVSSalesActorStatus> orderStatusResult = await this.StateManager.TryGetStateAsync <RVSSalesActorStatus>(OrderStatusPropertyName);

            if (orderStatusResult.HasValue)
            {
                return(orderStatusResult.Value);
            }
            else
            {
                return(RVSSalesActorStatus.Unknown);
            }
        }
        protected virtual async Task InitializeStateAsync()
        {
            _originalStateProperties.Clear();

            foreach (StatePropertyMetadata metadata in _statePropertyMetadata.Values)
            {
                ConditionalValue <object> stateProperty = await StateManager.TryGetStateAsync <object>(metadata.PropertyName);

                object propertyValue = stateProperty.HasValue ? stateProperty.Value : metadata.DefaultValue;
                metadata.PropertyInfo.SetValue(State, propertyValue);
                _originalStateProperties.Add(metadata.PropertyName, propertyValue);
            }
        }
Пример #26
0
        public async Task <perStoryData> GetStoryPointData(Guid storypointEntryId)
        {
            IReliableDictionary <Guid, perStoryData> storypointdata =
                await _stateManager.GetOrAddAsync <IReliableDictionary <Guid, perStoryData> >("storypointdata");


            using (ITransaction tx = _stateManager.CreateTransaction())
            {
                ConditionalValue <perStoryData> storypointEntry = await storypointdata.TryGetValueAsync(tx, storypointEntryId);

                return(storypointEntry.HasValue ? storypointEntry.Value : null);
            }
        }
        private async Task SaveHealthDataAsync(HeartRateRecord newRecord)
        {
            ConditionalValue <List <HeartRateRecord> > HeartRateRecords = await this.StateManager.TryGetStateAsync <List <HeartRateRecord> >("HeartRateRecords");

            if (HeartRateRecords.HasValue)
            {
                List <HeartRateRecord> records = HeartRateRecords.Value;
                records = records.Where(x => DateTimeOffset.UtcNow - ((DateTimeOffset)x.Timestamp).ToUniversalTime() <= this.TimeWindow).ToList();
                records.Add(newRecord);
                await this.StateManager.SetStateAsync <List <HeartRateRecord> >("HeartRateRecords", records);
            }
            return;
        }
Пример #28
0
        public async Task GetAsyncNoResult()
        {
            MetricReliableStateManager target = new MetricReliableStateManager(
                this.GetContext(),
                new JsonReliableStateSerializerResolver(),
                this.GetConfig(),
                new MockReliableStateManager());

            ConditionalValue <IReliableDictionary <int, string> > actual = await target.TryGetAsync <IReliableDictionary <int, string> >("test://dictionary");

            Assert.IsFalse(actual.HasValue);
            Assert.IsNull(actual.Value);
        }
        public async Task <ConditionalValue <T> > TryGetAsync <T>(Uri name) where T : IReliableState
        {
            using (ITransaction tx = this.stateManagerReplica.CreateTransaction())
            {
                ConditionalValue <IReliableState> result = await this.TryGetMetricReliableCollectionAsync(tx, typeof(T), name);

                await tx.CommitAsync();

                return(result.HasValue
                    ? new ConditionalValue <T>(true, (T)result.Value)
                    : await this.stateManagerReplica.TryGetAsync <T>(name));
            }
        }
Пример #30
0
        /// <summary>
        /// Metodo interno para retorna um funcionarios pelo Id.
        /// </summary>
        /// <param name="employerName">Nome do funcionario para pesquisa</param>
        /// <returns></returns>
        private async Task <EmployerEntity> GetEmployerById(Guid employerId)
        {
            var employers = await _stateManager.GetOrAddAsync <IReliableDictionary <Guid, EmployerEntity> >("employer");

            var result = new List <EmployerEntity>();

            using (var transac = _stateManager.CreateTransaction())
            {
                ConditionalValue <EmployerEntity> employer = await employers.TryGetValueAsync(transac, employerId);

                return(employer.HasValue ? employer.Value : null);
            }
        }
        public async Task <byte[]> GetCacheItemAsync(string key, string clientId, string tenantId, TimeSpan timeout, CancellationToken cancellationToken)
        {
            var metaDictionary = await _stateManager.TryGetAsync <IReliableDictionary <string, CacheEntry> >(GetMetadataDictionaryName(clientId, tenantId));

            if (!metaDictionary.HasValue)
            {
                return(null);
            }
            var dataDictionary = await _stateManager.TryGetAsync <IReliableDictionary <string, byte[]> >(GetDataDictionaryName(clientId, tenantId));

            if (!dataDictionary.HasValue)
            {
                return(null);
            }
            ConditionalValue <CacheEntry> meta;
            var  data = new ConditionalValue <byte[]>();
            bool isExpired;

            using (var transaction = _stateManager.CreateTransaction())
            {
                meta = await metaDictionary.Value.TryGetValueAsync(transaction, key, LockMode.Default, timeout, cancellationToken);

                if (!meta.HasValue)
                {
                    return(null);
                }
                isExpired = IsExpired(meta.Value);
                if (!isExpired)
                {
                    data = await dataDictionary.Value.TryGetValueAsync(transaction, key, LockMode.Default, timeout, cancellationToken);

                    if (!data.HasValue)
                    {
                        return(null);
                    }
                }
            }

            if (isExpired)
            {
                await DeleteCacheItemAsync(key, clientId, tenantId, timeout, cancellationToken);

                return(null);
            }
            else
            {
                _ = await UpdateLastAccessedAsync(key, meta.Value, metaDictionary.Value, timeout, cancellationToken);

                return(data.Value);
            }
        }