public async Task <Guid> CreateAsync(string type, CancellationToken cancellationToken) { var myTypeDictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <string, bool> >(ACTOR_TYPE_COLLECTION); var myDictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <Guid, string> >(ACTOR_COLLECTION); ActorId key = ActorId.CreateRandom(); // register actor if type doesn't exist using (ITransaction tx = this.StateManager.CreateTransaction()) { if (!await myTypeDictionary.ContainsKeyAsync(tx, type)) { ActorRuntime.RegisterActorAsync <SampleActor.SampleActor>( (context, actorType) => new ActorService(context, actorType)).GetAwaiter().GetResult(); await myTypeDictionary.TryAddAsync(tx, type, true); } } // Create actor ActorProxy.Create <ISampleActor>(key, $"fabric:/Default.Main/{type}ActorService"); // Add to collection using (ITransaction tx = this.StateManager.CreateTransaction()) { await myDictionary.AddAsync(tx, key.GetGuidId(), type, TimeSpan.FromMilliseconds(ACTOR_CREATION_TIMEOUT * 1000), cancellationToken); await tx.CommitAsync(); } return(key.GetGuidId()); }
public Task ReceiveReminderAsync(string reminderName, byte[] state, TimeSpan dueTime, TimeSpan period) { ActorEventSource.Current.Message($"Actor {actorId} recieved reminder {reminderName}."); var ev = GetEvent <IWakeupCallEvents>(); ev.WakeupCall(Encoding.ASCII.GetString(state), actorId.GetGuidId()); return(Task.CompletedTask); }
async Task <bool> ITankGameSession.StartRound(ActorId aUserId) { try { GameSessionState state = await this.GetStateAsync <GameSessionState>(); List <Task> tasks = new List <Task>(); int currentuserround = 0; foreach (TankSessionMemberItem i in state.Players) { tasks.Add(i.TankId.Proxy <ITank>().ResetAsync()); if (i.UserId == aUserId) { i.CurrentRound++; currentuserround = i.CurrentRound; } } await Task.WhenAll(tasks); await this.SetStateAsync(state); //And notify StartRoundResponse srr = new StartRoundResponse(); srr.RoundNum = currentuserround; srr.Status = HttpStatusCode.OK; srr.UserId = aUserId.GetGuidId(); foreach (TankSessionMemberItem i in state.Players) { GateResponse gr = new GateResponse((int)RequestProcessorEnum.StartRound, (int)HttpStatusCode.OK, i.UserId.GetGuidId(), srr.Serialize()); await i.UserId.Proxy <IUser>().SendGateResponseAsync(gr); } bool OnSameRound = true; for (int i = 0; i < state.Players.Count - 1; i++) { if (state.Players[i].CurrentRound != state.Players[i + 1].CurrentRound) { OnSameRound = false; } } if (OnSameRound) { BeginRounResponse brr = new BeginRounResponse(this.Id.GetGuidId(), currentuserround); brr.Status = HttpStatusCode.OK; foreach (TankSessionMemberItem i in state.Players) { GateResponse gr = new GateResponse((int)RequestProcessorEnum.BeginRound, (int)HttpStatusCode.OK, i.UserId.GetGuidId(), brr.Serialize()); await i.UserId.Proxy <IUser>().SendGateResponseAsync(gr); } } return(true); } catch (Exception E) { this.Log(E); return(false); } }
public static void Write(this BinaryWriter writer, ActorId actorId) { if (actorId == null) { writer.WriteNullPrefixByte(); return; } writer.WriteNotNullPrefixByte(); writer.Write((byte)actorId.Kind); switch (actorId.Kind) { case ActorIdKind.Long: writer.Write(actorId.GetLongId()); break; case ActorIdKind.Guid: writer.Write(actorId.GetGuidId()); break; case ActorIdKind.String: writer.Write(actorId.GetStringId()); break; default: ReleaseAssert.Failfast("The ActorIdKind value {0} is invalid", actorId.Kind); break; } }
async Task ITankGameSession.NotifyPosition(ActorId TankId, float x, float y, float z, float r) { try { GameSessionState state = await this.GetStateAsync <GameSessionState>(); List <Task> notes = new List <Task>(); TankPosistionResponse resp = new TankPosistionResponse(TankId.GetGuidId(), x, y, z, r); string serialized = resp.Serialize(); List <ActorId> TargetUids = state.Players.Select(p => p.UserId).Distinct().ToList(); foreach (TankSessionMemberItem i in state.Players) { if (i.TankId != TankId) { GateResponse gr = new GateResponse((int)RequestProcessorEnum.TankPosition, (int)HttpStatusCode.OK, i.UserId.GetGuidId(), serialized); await i.UserId.Proxy <IUser>().SendGateResponseAsync(gr); } } } catch (Exception E) { this.Log(E); } }
async void IKitchenEvents.CookingCompleted(ActorId actorId, KitchenOrder order) { await SetOrderStateAsync(OrderState.Cooked); var kitchenActor = new KitchenActorProxy().CreateActor(actorId.GetGuidId()); await kitchenActor.UnsubscribeAsync <IKitchenEvents>(this); }
public async Task <PipelineRunnerActorDocument> CreateNewSiteRegistrationAsync(ActorId id, byte[] model, CancellationToken token) { var doc = new PipelineRunnerActorDocument { Id = id.GetGuidId(), Data = model }; await SaveDocumentAsync(id, new DocumentWrapper { Document = doc }, token); return(doc); }
async void IOrderEvents.OrderStateChanged(ActorId orderActorId, OrderState state) { var list = await GetTableOrderContracts(CancellationToken.None); var foundOrder = list.FirstOrDefault(o => o.OrderId == orderActorId.GetGuidId()); if (foundOrder != null) { foundOrder.State = state.ToString(); await StateManager.AddOrUpdateStateAsync(ListName, list, (key, value) => list, CancellationToken.None); } }
async void IOrderEvents.OrderServed(ActorId orderActorId, Guid dishId) { var list = await GetTableOrderContracts(CancellationToken.None); var foundOrder = list.FirstOrDefault(o => o.OrderId == orderActorId.GetGuidId()); if (foundOrder != null) { foundOrder.ServedAt = DateTime.Now; await StateManager.AddOrUpdateStateAsync(ListName, list, (key, value) => list, CancellationToken.None); } }
public async Task <IResponse> Process(IRequest request) { try { LoginUserRequest lr = request as LoginUserRequest; LoginUserResponse response = new LoginUserResponse(); if (!string.IsNullOrEmpty(lr.UserName) && !string.IsNullOrEmpty(lr.Password)) { //Compute actor id for user name ActorId userid = lr.UserName.ToLowerInvariant().ToMD5GuidActorId(); var userproxy = userid.Proxy <IUser>(); bool exists = await userproxy.isCreatedAsync(); //Note: change to NOT create actors later, possible vector if (exists) { var loginproxy = userid.Proxy <ILogin>(); if (await loginproxy.ValidatePassword(lr.Password)) { response.UserId = userid.GetGuidId(); response.Status = System.Net.HttpStatusCode.OK; } else { response.UserId = Guid.Empty; response.Status = System.Net.HttpStatusCode.Forbidden; } } else { //Already exists response.UserId = Guid.Empty; response.Status = System.Net.HttpStatusCode.NotFound; } return(response); } else { response.UserId = Guid.Empty; response.Status = System.Net.HttpStatusCode.BadRequest; } return(response); } catch (Exception E) { E.Log(); ErrorResponse errorresponse = new ErrorResponse(E.Message); return(errorresponse); } }
private static async Task VerifyActors( HealthIndexCalculator hic, ActorId bandActorId, string doctorName, CountyRecord randomCountyRecord, BandInfo bandActorInfo, IDoctorActor docActor, IBandActor bandActor) { while (true) { BandDataViewModel view = await bandActor.GetBandDataAsync(); if (view.PersonName == bandActorInfo.PersonName) { if (view.CountyInfo == bandActorInfo.CountyInfo) { if (view.DoctorId == bandActorInfo.DoctorId) { if (view.PersonId == bandActorId.GetGuidId()) { if (hic.ComputeIndex(bandActorInfo.HealthIndex) == view.HealthIndex) { break; } else { await bandActor.NewAsync(bandActorInfo); await Task.Delay(100); } } } } } } while (true) { Tuple <CountyRecord, string> info = await docActor.GetInfoAndNameAsync(); if (info.Item2 == String.Format("Dr. {0}", doctorName) && info.Item1 == randomCountyRecord) { break; } else { await docActor.NewAsync(doctorName, randomCountyRecord); await Task.Delay(100); } } }
public async Task <IResponse> Process(IRequest request) { try { CreateUserRequest uer = request as CreateUserRequest; CreateUserResponse response = new CreateUserResponse(); if (!string.IsNullOrEmpty(uer.UserName) && !string.IsNullOrEmpty(uer.Password)) { //Compute actor id for user name ActorId userid = uer.UserName.ToLowerInvariant().ToMD5GuidActorId(); var userproxy = userid.Proxy <IUser>(); bool exists = await userproxy.isCreatedAsync(); //Note: change to NOT create actors later, possible vector if (!exists) { bool result = await userproxy.CreateUserAsync(uer.UserName, uer.Password, false); response.Sucessful = true; response.UserId = userid.GetGuidId(); response.Status = System.Net.HttpStatusCode.OK; } else { //Already exists response.Sucessful = false; response.UserId = Guid.Empty; response.Status = System.Net.HttpStatusCode.Forbidden; } return(response); } else { response.Sucessful = false; response.UserId = Guid.Empty; response.Status = System.Net.HttpStatusCode.BadRequest; } return(response); } catch (Exception E) { E.Log(); ErrorResponse errorresponse = new ErrorResponse(E.Message); return(errorresponse); } }
async Task <bool> ITankGameSession.TakeDamage(ActorId TankID, float amount) { try { bool isDead = false; float newHealth = 0.0f; GameSessionState state = await this.GetStateAsync <GameSessionState>(); foreach (TankSessionMemberItem i in state.Players) { if (i.TankId == TankID) { newHealth = await(i.TankId.Proxy <ITank>().TakeDamageAsync(amount)); if (newHealth <= 0) { isDead = true; } } } await this.SetStateAsync(state); //Notify clients TakeDamageResponse tdr = new TakeDamageResponse(); tdr.Status = System.Net.HttpStatusCode.OK; tdr.TankGameSessionId = this.Id.GetGuidId(); tdr.TankId = TankID.GetGuidId(); tdr.Health = newHealth; tdr.isDead = isDead; List <Task> tasks = new List <Task>(); foreach (TankSessionMemberItem i in state.Players) { GateResponse gr = new GateResponse((int)RequestProcessorEnum.TakeDamage, (int)HttpStatusCode.OK, i.UserId.GetGuidId(), tdr.Serialize()); tasks.Add(i.UserId.Proxy <IUser>().SendGateResponseAsync(gr)); } await Task.WhenAll(tasks); //End notify clients return(isDead); } catch (Exception E) { this.Log(E); return(false); } }
public TransactionId(ActorId actorId) { switch (actorId.Kind) { case ActorIdKind.Long: this.kind = ActorIdKind.Long; this.longId = actorId.GetLongId(); break; case ActorIdKind.Guid: this.kind = ActorIdKind.Long; this.guidId = actorId.GetGuidId(); break; case ActorIdKind.String: this.kind = ActorIdKind.Long; this.stringId = actorId.GetStringId(); break; default: throw new InvalidOperationException($"he ActorIdKind value {(object)this.kind} is invalid"); } }
internal static string GetStorageKey(this ActorId actorId) { switch (actorId.Kind) { case ActorIdKind.Long: return(string.Format(CultureInfo.InvariantCulture, "{0}_{1}", actorId.Kind.ToString(), actorId.GetLongId())); case ActorIdKind.Guid: return(string.Format(CultureInfo.InvariantCulture, "{0}_{1}", actorId.Kind.ToString(), actorId.GetGuidId())); case ActorIdKind.String: return(string.Format(CultureInfo.InvariantCulture, "{0}_{1}", actorId.Kind.ToString(), actorId.GetStringId())); default: return(null); } }
public async Task EveryBuildSubscription() { var channel = new Channel { Name = "channel", Classification = "class" }; var build = new Build { Branch = "source.branch", Repository = "source.repo", BuildNumber = "build.number", Commit = "sha", DateProduced = DateTimeOffset.UtcNow.AddDays(-1) }; var location = "https://repo.feed/index.json"; var newAsset = new Asset { Name = "source.asset", Version = "1.0.1", Locations = new List <AssetLocation> { new AssetLocation { Location = location, Type = LocationType.NugetFeed } } }; var newBuild = new Build { Branch = "source.branch", Repository = "source.repo", BuildNumber = "build.number.2", Commit = "sha2", DateProduced = DateTimeOffset.UtcNow, Assets = new List <Asset> { newAsset } }; var buildChannels = new[] { new BuildChannel { Build = build, Channel = channel }, new BuildChannel { Build = newBuild, Channel = channel } }; var subscription = new Subscription { Channel = channel, SourceRepository = "source.repo", TargetRepository = "target.repo", TargetBranch = "target.branch", Enabled = true, PolicyObject = new SubscriptionPolicy { MergePolicies = null, UpdateFrequency = UpdateFrequency.EveryBuild }, LastAppliedBuild = build }; var repoInstallation = new Repository { RepositoryName = "target.repo", InstallationId = 1 }; await Context.BuildChannels.AddRangeAsync(buildChannels); await Context.Subscriptions.AddAsync(subscription); await Context.Repositories.AddAsync(repoInstallation); await Context.SaveChangesAsync(); SubscriptionActor.Setup(s => s.UpdateAsync(newBuild.Id)).Returns(Task.CompletedTask); var updater = ActivatorUtilities.CreateInstance <DependencyUpdater>(Scope.ServiceProvider); await updater.UpdateDependenciesAsync(newBuild.Id, channel.Id); ActorId.GetGuidId().Should().Be(subscription.Id); }
private static async Task VerifyActors( HealthIndexCalculator hic, ActorId bandActorId, string doctorName, CountyRecord randomCountyRecord, BandInfo bandActorInfo, IDoctorActor docActor, IBandActor bandActor, CancellationToken ct) { ServiceEventSource.Current.Message("Verifying Actor {0}", bandActorId); bool bandVerified = false; bool doctorVerified = false; int bandErrorCount = 0; int doctorErrorCount = 0; while (!ct.IsCancellationRequested && !bandVerified && !doctorVerified) { await Task.Delay(100); if (!bandVerified) { try { BandDataViewModel view = await bandActor.GetBandDataAsync(); if (view.PersonName == bandActorInfo.PersonName) { if (view.CountyInfo == bandActorInfo.CountyInfo) { if (view.DoctorId == bandActorInfo.DoctorId) { if (view.PersonId == bandActorId.GetGuidId()) { if (view.HealthIndexValue == bandActorInfo.HealthIndex) { bandVerified = true; ServiceEventSource.Current.Message("Band actor verified."); } else { await bandActor.NewAsync(bandActorInfo); } } } } } } catch (Exception e) { bandErrorCount++; ServiceEventSource.Current.Message("Exception Count {0} verifying band actor, retrying. {1}", bandErrorCount, e); } } else { ServiceEventSource.Current.Message("band already verified, skipping"); } if (!doctorVerified) { try { Tuple <CountyRecord, string> info = await docActor.GetInfoAndNameAsync(); if (info.Item2 == String.Format("Dr. {0}", doctorName) && info.Item1 == randomCountyRecord) { doctorVerified = true; ServiceEventSource.Current.Message("Doctor actor verified."); } else { await docActor.NewAsync(doctorName, randomCountyRecord); } } catch (Exception e) { doctorErrorCount++; ServiceEventSource.Current.Message("Exception Count {0} verifying doctor actor, retrying. {1}", doctorErrorCount, e); } } else { ServiceEventSource.Current.Message("doctor already verified, skipping"); } } }
private async Task <Guid> CreateConsumerAsync(string appApiLicenseCode) { byte[] selfieBytes = GetImageBytes("christina.png"); string selfieBase64 = Convert.ToBase64String(selfieBytes); CryptoRandom random = new CryptoRandom(); int age = random.Next(22, 115); SmartRequest <PlayerRegisterRequest> req = new SmartRequest <PlayerRegisterRequest> { CreatedOn = DateTimeOffset.UtcNow, Latitude = 34.072846D, Longitude = -84.190285D, Data = new PlayerRegisterRequest { CountryCode = "US", LanguageCode = "en-US", SelfieBase64 = selfieBase64, Data = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("age", age.ToString()) } } , Uuid = $"{Guid.NewGuid()}" }; Guid correlationRefId = Guid.NewGuid(); Uri requestUri = GetFullUri("api/v3/player/registration"); HttpRequestMessage httpreq = new HttpRequestMessage(HttpMethod.Post, requestUri); httpreq.Headers.Add("lazlo-apilicensecode", appApiLicenseCode); httpreq.Headers.Add("lazlo-correlationrefId", correlationRefId.ToString()); string json = JsonConvert.SerializeObject(req); httpreq.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); HttpResponseMessage message = await _HttpClient.SendAsync(httpreq).ConfigureAwait(false); string responseJson = await message.Content.ReadAsStringAsync().ConfigureAwait(false); if (message.IsSuccessStatusCode) { if (age < 18) { throw new CorrelationException("Allowed to register a player under 18") { CorrelationRefId = correlationRefId }; } var statusResponse = JsonConvert.DeserializeObject <SmartResponse <ConsumerRegisterResponse> >(responseJson); ActorId consumerActorId = new ActorId(Guid.NewGuid()); IConsumerSimulationActor consumerActor = ActorProxy.Create <IConsumerSimulationActor>(consumerActorId, ConsumerServiceUri); await consumerActor.InitializeAsync( appApiLicenseCode, statusResponse.Data.ConsumerLicenseCode).ConfigureAwait(false); return(consumerActorId.GetGuidId()); } else { throw new Exception("Create player failed"); } }