public void LoadTable(CompoundTable table, int shard) { Shard shard2; if (_shards.TryGetValue(shard, out shard2)) throw new ArgumentNullException("shard"); _shards.Add(shard, shard2 = new Shard("Shard: " + shard.ToString())); LoadTable(table, shard2); }
private int Transaction(Shard s, TransactionAction action, int parameterA, int parameterB) { try { return action(parameterA, parameterB, s.random); } finally { s.spinLock.Unlock(); } }
public ShardedRandom(int shardCount, int seed) { shards = new Shard[shardCount]; for (int i = 0; i < shardCount; i++) { unchecked { shards[i] = new Shard(seed + i); } } }
/// <summary> /// Constructs the storage representation from client side objects. /// </summary> /// <param name="id">Identify of mapping.</param> /// <param name="s">Shard being converted.</param> /// <param name="minValue">Min key value.</param> /// <param name="maxValue">Max key value.</param> /// <param name="status">Mapping status.</param> internal DefaultStoreMapping( Guid id, Shard s, byte[] minValue, byte[] maxValue, int status) { this.Id = id; this.ShardMapId = s.ShardMapId; this.MinValue = minValue; this.MaxValue = maxValue; this.Status = status; this.LockOwnerId = default(Guid); this.StoreShard = s.StoreShard; }
public void DeleteShardVersionMismatch() { ShardMapManager smm = ShardMapManagerFactory.GetSqlShardMapManager( Globals.ShardMapManagerConnectionString, ShardMapManagerLoadPolicy.Lazy); ShardMap sm = smm.GetShardMap(ShardMapTests.s_defaultShardMapName); Assert.IsNotNull(sm); ShardLocation sl = new ShardLocation(Globals.ShardMapManagerTestsDatasourceName, ShardMapTests.s_shardedDBs[0]); Shard sNew = sm.CreateShard(sl); // Update shard to increment version ShardUpdate su = new ShardUpdate(); su.Status = ShardStatus.Offline; Shard sUpdated = sm.UpdateShard(sNew, su); bool removeFailed = false; try { sm.DeleteShard(sNew); } catch (ShardManagementException sme) { Assert.AreEqual(ShardManagementErrorCategory.ShardMap, sme.ErrorCategory); Assert.AreEqual(ShardManagementErrorCode.ShardVersionMismatch, sme.ErrorCode); removeFailed = true; } Assert.IsTrue(removeFailed); }
//------------------------------------------------------------------------Gateway messages parsing private static async void Gateway_OnMessageCreated(object sender, MessageEventArgs e) { Shard shard = e.Shard; DiscordMessage message = e.Message; if (message.Author == shard.User) { // Ignore messages created by our bot. return; } if (message.ChannelId.Id.ToString() == ProgHelpers.channelid)//Prevent DM abuse, only react to messages sent on a set channel. { //-----------------------------------------------------------------------------------------INFO - VALMIS V1 if (message.Content == "!sniperiinoinfo" || message.Content == "!si") { ITextChannel textChannel = (ITextChannel)shard.Cache.Channels.Get(message.ChannelId); try { // Reply to the user who posted "!info". await textChannel.CreateMessage(new DiscordMessageDetails() .SetEmbed(new DiscordEmbedBuilder() .SetTitle($"kitsun8's Sniperiino") .SetFooter(ProgHelpers.version) .SetColor(DiscordColor.FromHexadecimal(0xff9933)) .AddField(ProgHelpers.txtdeveloper + " ", "kitsun8#4567", false) .AddField(ProgHelpers.txtpurpose + " ", ProgHelpers.txtpurpose2, false) .AddField(ProgHelpers.txtcommands + " ", "!sniperiinoinfo/si", false) )); Console.WriteLine($"!sniperiinoinfo - " + message.Author.Username + "-" + message.Author.Id + " --- " + DateTime.Now); } catch (Exception) { Console.WriteLine($"!sniperiinoinfo - EX -" + message.Author.Username + "-" + message.Author.Id + " --- " + DateTime.Now); } } } }
public void CreateShardNullLocation() { ShardMapManager smm = ShardMapManagerFactory.GetSqlShardMapManager( Globals.ShardMapManagerConnectionString, ShardMapManagerLoadPolicy.Lazy); ShardMap sm = smm.GetShardMap(ShardMapTests.s_defaultShardMapName); Assert.IsNotNull(sm); bool addFailed = false; try { ShardLocation sl = new ShardLocation("", ""); Shard sNew = sm.CreateShard(sl); } catch (ArgumentException) { addFailed = true; } Assert.IsTrue(addFailed); }
public static async Task Start() { Settings.Load(); Log.Taexify(); DiscordBotUserToken token = new DiscordBotUserToken(Settings.Sunbae.Token); DiscordWebSocketApplication app = new DiscordWebSocketApplication(token); Shard shard = app.ShardManager.CreateSingleShard(); await shard.StartAsync(CancellationToken.None); shard.Gateway.OnMessageCreated += CommandParser.ProcessCommand; shard.Gateway.OnMessageCreated += ProcessMessage; CommandParser.SetPrefix("."); // Commands CommandFactory.RegisterCommand("ping", new PingCommand()); while (shard.IsRunning) { await Task.Delay(1000); } }
private async void Gateway_OnMessageCreated(object sender, MessageEventArgs e) { Shard shard = e.Shard; DiscordMessage message = e.Message; if (message.Author.Id == shard.UserId) { // Ignore messages created by our bot. return; } if (message.Content == "ping") { try { // Reply to the user who posted "!ping". await http.CreateMessage(message.ChannelId, $"<@!{message.Author.Id}> Pong!"); } catch (DiscordHttpApiException) { } } }
public override bool Invoke() { if (!receivingFromOwnBreak) { receivingFromOwnBreak = true; return(true); } Debug.Log("Invoke MoveAboutSigil"); Shard s = FindShard(); if (s is null) { Debug.Log("Couldn't find Shard for instruction :("); } Vector3 center = new Vector3(x.Value, y.Value, z.Value); Vector3 centerline = s.Position() - center; Debug.Log(s.Position()); Debug.Log(centerline); if (axis.Value == 0) { centerline = Quaternion.Euler(amount.Value, 0, 0) * centerline; } else if (axis.Value == 1) { centerline = Quaternion.Euler(0, amount.Value, 0) * centerline; } else if (axis.Value == 2) { centerline = Quaternion.Euler(0, 0, amount.Value) * centerline; } Debug.Log(centerline); s.Move(center + centerline); Debug.Log("Moving shard to " + s.transform.Find("Model").position.ToString()); return(false); }
public override void RunCommand(Shard shard, ITextChannel channel, string[] commandParams) { if (commandParams.Length < 3) { SendHelpMessage(channel); return; } DiscordUser dUser = DiscordUtil.DiscordUserFromName(shard, commandParams[1]); if (dUser == null) { DiscordUtil.SendMessage(channel, "Unable to find user: "******"Invalid rank!"); return; } User user = JfsPing.UserManager.UserFromDiscordUser(dUser); JfsPing.UserManager.SetUserRank(user, rank); DiscordUtil.SendMessage(channel, "Set rank for " + commandParams[1] + " to " + rank); }
public virtual void Damage(AttackDetails attackDetails) { lastDamageTime = Time.time; currentHealth -= attackDetails.damageAmount; currentStunResistance -= attackDetails.stunDamageAmount; DamageHop(attackDetails.damageKnockbackSpeed); Instantiate(entityData.hitParticle, aliveGO.transform.position, Quaternion.Euler(0f, 0f, Random.Range(0f, 360f))); if (attackDetails.position.x > aliveGO.transform.position.x) { lastDamageDirection = -1; } else { lastDamageDirection = 1; } if (currentStunResistance <= 0) { isStunned = true; } if (currentHealth <= 0) { GameObject s = Instantiate(shard, aliveGO.transform.position, Quaternion.identity) as GameObject; Shard shardObject = s.GetComponent <Shard>(); shardObject.expPoints = entityData.ExpPoints; isDead = true; } }
public async Task <ValidatorDuty> GetValidatorDutyAsync(BlsPublicKey validatorPublicKey, Epoch epoch) { if (!_storeProvider.TryGetStore(out IStore? retrievedStore)) { throw new Exception("Beacon chain is currently syncing or waiting for genesis."); } IStore store = retrievedStore !; Hash32 head = await _forkChoice.GetHeadAsync(store); if (!store.TryGetBlockState(head, out BeaconState? headState)) { throw new Exception($"Head state {head} not found."); } Epoch currentEpoch = _beaconStateAccessor.GetCurrentEpoch(headState !); Epoch nextEpoch = currentEpoch + Epoch.One; if (epoch == Epoch.None) { epoch = currentEpoch; } else if (epoch > nextEpoch) { throw new ArgumentOutOfRangeException(nameof(epoch), epoch, $"Duties cannot look ahead more than the next epoch {nextEpoch}."); } TimeParameters timeParameters = _timeParameterOptions.CurrentValue; Slot startSlot = _beaconChainUtility.ComputeStartSlotOfEpoch(epoch); Slot endSlot = startSlot + new Slot(timeParameters.SlotsPerEpoch); Slot attestationSlot = Slot.None; CommitteeIndex attestationCommitteeIndex = CommitteeIndex.None; Slot blockProposalSlot = Slot.None; if (epoch == nextEpoch) { // Clone for next or current, so that it can be safely mutated (transitioned forward) BeaconState state = BeaconState.Clone(headState !); _beaconStateTransition.ProcessSlots(state, startSlot); // Check base state ValidatorIndex validatorIndex = CheckValidatorIndex(state, validatorPublicKey); CheckStateDuty(state, validatorIndex, ref attestationSlot, ref attestationCommitteeIndex, ref blockProposalSlot); // Check future states CheckFutureSlots(state, endSlot, validatorIndex, ref attestationSlot, ref attestationCommitteeIndex, ref blockProposalSlot); } else if (epoch == currentEpoch) { // Take block slot and roots before cloning (for historical checks) IReadOnlyList <Hash32> historicalBlockRoots = headState !.BlockRoots; Slot fromSlot = headState !.Slot; BeaconState state = BeaconState.Clone(headState !); // Check base state ValidatorIndex validatorIndex = CheckValidatorIndex(state, validatorPublicKey); CheckStateDuty(state, validatorIndex, ref attestationSlot, ref attestationCommitteeIndex, ref blockProposalSlot); // Check future states CheckFutureSlots(state, endSlot, validatorIndex, ref attestationSlot, ref attestationCommitteeIndex, ref blockProposalSlot); // Check historical states if (startSlot < fromSlot && (attestationSlot == Slot.None || blockProposalSlot == Slot.None)) { CheckHistoricalSlots(store, historicalBlockRoots, fromSlot, startSlot, validatorIndex, ref attestationSlot, ref attestationCommitteeIndex, ref blockProposalSlot); } } else { Hash32 endRoot = _forkChoice.GetAncestor(store, head, endSlot - Slot.One); if (!store.TryGetBlockState(endRoot, out BeaconState? endState)) { throw new Exception($"State {endRoot} for slot {endSlot} not found."); } BeaconState state = endState !; // Check base state ValidatorIndex validatorIndex = CheckValidatorIndex(state, validatorPublicKey); CheckStateDuty(state, validatorIndex, ref attestationSlot, ref attestationCommitteeIndex, ref blockProposalSlot); // Check historical states IReadOnlyList <Hash32> historicalBlockRoots = state.BlockRoots; Slot fromSlot = state.Slot; if (attestationSlot == Slot.None || blockProposalSlot == Slot.None) { CheckHistoricalSlots(store, historicalBlockRoots, fromSlot, startSlot, validatorIndex, ref attestationSlot, ref attestationCommitteeIndex, ref blockProposalSlot); } } // HACK: Shards were removed from Phase 0, but analogy is committee index, so use for initial testing. Shard attestationShard = new Shard((ulong)attestationCommitteeIndex); ValidatorDuty validatorDuty = new ValidatorDuty(validatorPublicKey, attestationSlot, attestationShard, blockProposalSlot); return(validatorDuty); }
public static SszElement ToSszBasicElement(this Shard item) { return(new SszBasicElement((ulong)item)); }
public static void InitRunes() { #region Precision Runes Precision = new Runes("Precision"); Precision.keystones.Add(new Rune("Press the Attack", Resources.Press_The_Attack)); Precision.keystones.Add(new Rune("Lethal Tempo", Resources.Lethal_Tempo)); Precision.keystones.Add(new Rune("Fleet Footwork", Resources.Fleet_Footwork)); Precision.keystones.Add(new Rune("Conqueror", Resources.Conquerer)); Precision.firstRow.Add(new Rune("Overheal", Resources.Overheal)); Precision.firstRow.Add(new Rune("Triumph", Resources.Triumph)); Precision.firstRow.Add(new Rune("Presence of Mind", Resources.Presence_of_Mind)); Precision.secondRow.Add(new Rune("Legend: Alacrity", Resources.Legend_Alacrity)); Precision.secondRow.Add(new Rune("Legend: Tenacity", Resources.Legend_Tenacity)); Precision.secondRow.Add(new Rune("Legend: Bloodline", Resources.Legend_Bloodline)); Precision.thirdRow.Add(new Rune("Coup de Grace", Resources.Coup_de_Grace)); Precision.thirdRow.Add(new Rune("Cut Down", Resources.Cut_Down)); Precision.thirdRow.Add(new Rune("Last Stand", Resources.Last_Stand)); Precision.Register(); #endregion #region Domination Runes Domination = new Runes("Domination"); Domination.keystones.Add(new Rune("Electrocute", Resources.Electrocute)); Domination.keystones.Add(new Rune("Predator", Resources.Predator)); Domination.keystones.Add(new Rune("Dark Harvest", Resources.Dark_Harvest)); Domination.keystones.Add(new Rune("Hail of Blades", Resources.Hail_of_Blades)); Domination.firstRow.Add(new Rune("Cheap Shot", Resources.Cheap_Shot)); Domination.firstRow.Add(new Rune("Taste of Blood", Resources.Taste_of_Blood)); Domination.firstRow.Add(new Rune("Sudden Impact", Resources.Sudden_Impact)); Domination.secondRow.Add(new Rune("Zombie Ward", Resources.Zombie_Ward)); Domination.secondRow.Add(new Rune("Ghost Poro", Resources.Ghost_Poro)); Domination.secondRow.Add(new Rune("Eyeball Collection", Resources.Eyeball_Collection)); Domination.thirdRow.Add(new Rune("Ravenous Hunter", Resources.Ravenous_Hunter)); Domination.thirdRow.Add(new Rune("Ingenious Hunter", Resources.Ingenious_Hunter)); Domination.thirdRow.Add(new Rune("Relentless Hunter", Resources.Relentless_Hunter)); Domination.thirdRow.Add(new Rune("Ultimate Hunter", Resources.Ultimate_Hunter)); Domination.Register(); #endregion #region Sorcery Runes Sorcery = new Runes("Sorcery"); Sorcery.keystones.Add(new Rune("Summon Aery", Resources.Summon_Aery)); Sorcery.keystones.Add(new Rune("Arcane Comet", Resources.Arcane_Comet)); Sorcery.keystones.Add(new Rune("Phase Rush", Resources.Phase_Rush)); Sorcery.firstRow.Add(new Rune("Nullifying Orb", Resources.Nullifying_Orb)); Sorcery.firstRow.Add(new Rune("Manaflow Band", Resources.Manaflow_Band)); Sorcery.firstRow.Add(new Rune("Nimbus Cloak", Resources.Nimbus_Cloak)); Sorcery.secondRow.Add(new Rune("Transcendence", Resources.Transcendence)); Sorcery.secondRow.Add(new Rune("Celerity", Resources.Celerity)); Sorcery.secondRow.Add(new Rune("Absolute Focus", Resources.Absolute_Focus)); Sorcery.thirdRow.Add(new Rune("Scorch", Resources.Scorch)); Sorcery.thirdRow.Add(new Rune("Waterwalking", Resources.Waterwalking)); Sorcery.thirdRow.Add(new Rune("Gathering Storm", Resources.Gathering_Storm)); Sorcery.Register(); #endregion #region Resolve Runes Resolve = new Runes("Resolve"); Resolve.keystones.Add(new Rune("Grasp of the Undying", Resources.Grasp_of_the_Undying)); Resolve.keystones.Add(new Rune("Aftershock", Resources.Aftershock)); Resolve.keystones.Add(new Rune("Guardian", Resources.Guardian)); Resolve.firstRow.Add(new Rune("Demolish", Resources.Demolish)); Resolve.firstRow.Add(new Rune("Font of Life", Resources.Font_of_Life)); Resolve.firstRow.Add(new Rune("Shield Bash", Resources.Shield_Bash)); Resolve.secondRow.Add(new Rune("Conditioning", Resources.Conditioning)); Resolve.secondRow.Add(new Rune("Second Wind", Resources.Second_Wind)); Resolve.secondRow.Add(new Rune("Bone Plating", Resources.Bone_Plating)); Resolve.thirdRow.Add(new Rune("Overgrowth", Resources.Overgrowth)); Resolve.thirdRow.Add(new Rune("Revitalize", Resources.Revitalize)); Resolve.thirdRow.Add(new Rune("Unflinching", Resources.Unflinching)); Resolve.Register(); #endregion #region Inspiration Runes Inspiration = new Runes("Inspiration"); Inspiration.keystones.Add(new Rune("Glacial Augment", Resources.Glacial_Augment_Alt)); Inspiration.keystones.Add(new Rune("Kleptomancy", Resources.Kleptomancy)); Inspiration.keystones.Add(new Rune("Unsealed Spellbook", Resources.Unsealed_Spellbook)); Inspiration.firstRow.Add(new Rune("Hextech Flashtraption", Resources.Hextech_Flashtraption)); Inspiration.firstRow.Add(new Rune("Magical Footwear", Resources.Magical_Footwear)); Inspiration.firstRow.Add(new Rune("Perfect Timing", Resources.Perfect_Timing)); Inspiration.secondRow.Add(new Rune("Future's Market", Resources.Future_s_Market)); Inspiration.secondRow.Add(new Rune("Minion Dematerializer", Resources.Minion_Dematerializer)); Inspiration.secondRow.Add(new Rune("Biscuit Delivery", Resources.Biscuit_Delivery)); Inspiration.thirdRow.Add(new Rune("Cosmic Insight", Resources.Cosmic_Insight)); Inspiration.thirdRow.Add(new Rune("Approach Velocity", Resources.Approach_Velocity)); Inspiration.thirdRow.Add(new Rune("Time Warp Tonic", Resources.Time_Warp_Tonic)); Inspiration.Register(); #endregion #region Shards Shard Adaptive_Forge = new Shard("Adaptive Force", Resources.Adaptive_Force); Adaptive_Forge.Register(); Shard Attack_Speed = new Shard("Attack Speed", Resources.Attack_Speed); Attack_Speed.Register(); Shard Cooldown_Reduction = new Shard("Cooldown Reduction", Resources.Cooldown_Reduction); Cooldown_Reduction.Register(); Shard Armor = new Shard("Armor", Resources.Armor); Armor.Register(); Shard Magic_Resist = new Shard("Magic Resist", Resources.Magic_Resistance); Magic_Resist.Register(); Shard Health = new Shard("Health", Resources.Health); Health.Register(); #endregion }
private EntityStarted EntityStartedToProto(Shard.EntityStarted entityStarted) { return EntityStarted.CreateBuilder().SetEntityId(entityStarted.EntityId).Build(); }
public void DateGetPointMappingsForRange() { ShardMapManager smm = ShardMapManagerFactory.GetSqlShardMapManager( Globals.ShardMapManagerConnectionString, ShardMapManagerLoadPolicy.Lazy); ListShardMap <DateTime> lsm = smm.GetListShardMap <DateTime>(DateTimeShardMapperTests.s_listShardMapName); Assert.IsNotNull(lsm); Shard s1 = lsm.CreateShard(new ShardLocation(Globals.ShardMapManagerTestsDatasourceName, DateTimeShardMapperTests.s_shardedDBs[0])); Assert.IsNotNull(s1); Shard s2 = lsm.CreateShard(new ShardLocation(Globals.ShardMapManagerTestsDatasourceName, DateTimeShardMapperTests.s_shardedDBs[1])); Assert.IsNotNull(s2); DateTime val1 = DateTime.Now.Subtract(TimeSpan.FromMinutes(10)); PointMapping <DateTime> p1 = lsm.CreatePointMapping(val1, s1); Assert.IsNotNull(p1); DateTime val2 = DateTime.Now.Subtract(TimeSpan.FromMinutes(20)); PointMapping <DateTime> p2 = lsm.CreatePointMapping(val2, s1); Assert.IsNotNull(p2); DateTime val3 = DateTime.Now.Subtract(TimeSpan.FromMinutes(30)); PointMapping <DateTime> p3 = lsm.CreatePointMapping(val3, s2); Assert.IsNotNull(p2); // Get all mappings in shard map. int count = 0; IEnumerable <PointMapping <DateTime> > allMappings = lsm.GetMappings(); using (IEnumerator <PointMapping <DateTime> > mEnum = allMappings.GetEnumerator()) { while (mEnum.MoveNext()) { count++; } } Assert.AreEqual(3, count); // Get all mappings in specified range. Range <DateTime> wantedRange = new Range <DateTime>(val3.AddMinutes(-5), val3.AddMinutes(15)); count = 0; IEnumerable <PointMapping <DateTime> > mappingsInRange = lsm.GetMappings(wantedRange); using (IEnumerator <PointMapping <DateTime> > mEnum = mappingsInRange.GetEnumerator()) { while (mEnum.MoveNext()) { count++; } } Assert.AreEqual(2, count); // Get all mappings for a shard. count = 0; IEnumerable <PointMapping <DateTime> > mappingsForShard = lsm.GetMappings(s1); using (IEnumerator <PointMapping <DateTime> > mEnum = mappingsForShard.GetEnumerator()) { while (mEnum.MoveNext()) { count++; } } Assert.AreEqual(2, count); // Get all mappings in specified range for a particular shard. count = 0; IEnumerable <PointMapping <DateTime> > mappingsInRangeForShard = lsm.GetMappings(wantedRange, s1); using (IEnumerator <PointMapping <DateTime> > mEnum = mappingsInRangeForShard.GetEnumerator()) { while (mEnum.MoveNext()) { count++; } } Assert.AreEqual(1, count); }
public async Task Handle(Shard shard, MessageReactionAddEvent evt) { await TryHandleProxyMessageReactions(evt); }
public async Task <ValidatorDuty> GetValidatorDutyAsync(BlsPublicKey validatorPublicKey, Epoch epoch) { Root head = await _forkChoice.GetHeadAsync(_store).ConfigureAwait(false); BeaconState headState = await _store.GetBlockStateAsync(head).ConfigureAwait(false); Epoch currentEpoch = _beaconStateAccessor.GetCurrentEpoch(headState); Epoch nextEpoch = currentEpoch + Epoch.One; if (epoch == Epoch.None) { epoch = currentEpoch; } else if (epoch > nextEpoch) { throw new ArgumentOutOfRangeException(nameof(epoch), epoch, $"Duties cannot look ahead more than the next epoch {nextEpoch}."); } TimeParameters timeParameters = _timeParameterOptions.CurrentValue; Slot startSlot = _beaconChainUtility.ComputeStartSlotOfEpoch(epoch); Slot endSlot = startSlot + new Slot(timeParameters.SlotsPerEpoch); Duty duty = new Duty() { AttestationSlot = Slot.None, AttestationCommitteeIndex = CommitteeIndex.None, BlockProposalSlot = Slot.None }; if (epoch == nextEpoch) { // Clone for next or current, so that it can be safely mutated (transitioned forward) BeaconState state = BeaconState.Clone(headState); _beaconStateTransition.ProcessSlots(state, startSlot); // Check base state ValidatorIndex validatorIndex = CheckValidatorIndex(state, validatorPublicKey); duty = CheckStateDuty(state, validatorIndex, duty); // Check future states duty = CheckFutureSlots(state, endSlot, validatorIndex, duty); } else if (epoch == currentEpoch) { // Take block slot and roots before cloning (for historical checks) IReadOnlyList <Root> historicalBlockRoots = headState.BlockRoots; Slot fromSlot = headState.Slot; BeaconState state = BeaconState.Clone(headState); // Check base state ValidatorIndex validatorIndex = CheckValidatorIndex(state, validatorPublicKey); duty = CheckStateDuty(state, validatorIndex, duty); // Check future states duty = CheckFutureSlots(state, endSlot, validatorIndex, duty); // Check historical states if (startSlot < fromSlot && (duty.AttestationSlot == Slot.None || duty.BlockProposalSlot == Slot.None)) { duty = await CheckHistoricalSlotsAsync(_store, historicalBlockRoots, fromSlot, startSlot, validatorIndex, duty).ConfigureAwait(false); } } else { Root endRoot = await _forkChoice.GetAncestorAsync(_store, head, endSlot - Slot.One); BeaconState state = await _store.GetBlockStateAsync(endRoot).ConfigureAwait(false); // Check base state ValidatorIndex validatorIndex = CheckValidatorIndex(state, validatorPublicKey); duty = CheckStateDuty(state, validatorIndex, duty); // Check historical states IReadOnlyList <Root> historicalBlockRoots = state.BlockRoots; if (duty.AttestationSlot == Slot.None || duty.BlockProposalSlot == Slot.None) { Slot fromSlot = state.Slot; duty = await CheckHistoricalSlotsAsync(_store, historicalBlockRoots, fromSlot, startSlot, validatorIndex, duty).ConfigureAwait(false); } } // HACK: Shards were removed from Phase 0, but analogy is committee index, so use for initial testing. Shard attestationShard = new Shard((ulong)duty.AttestationCommitteeIndex); ValidatorDuty validatorDuty = new ValidatorDuty(validatorPublicKey, duty.AttestationSlot, attestationShard, duty.BlockProposalSlot); return(validatorDuty); }
public void DeleteShardAbortGSMDoAndLSMUndo() { bool shouldThrow = true; IStoreOperationFactory sof = new StubStoreOperationFactory() { CallBase = true, CreateRemoveShardOperationShardMapManagerIStoreShardMapIStoreShard = (_smm, _sm, _s) => { StubRemoveShardOperation op = new StubRemoveShardOperation(_smm, _sm, _s); op.CallBase = true; op.DoGlobalPostLocalExecuteIStoreTransactionScope = (ts) => { if (shouldThrow) { throw new StoreException("", ShardMapFaultHandlingTests.TransientSqlException); } else { // Call the base function, hack for this behavior is to save current operation, set current to null, restore current operation. var original = op.DoGlobalPostLocalExecuteIStoreTransactionScope; op.DoGlobalPostLocalExecuteIStoreTransactionScope = null; try { return(op.DoGlobalPostLocalExecute(ts)); } finally { op.DoGlobalPostLocalExecuteIStoreTransactionScope = original; } } }; op.UndoLocalSourceExecuteIStoreTransactionScope = (ts) => { if (shouldThrow) { throw new StoreException("", ShardMapFaultHandlingTests.TransientSqlException); } else { // Call the base function, hack for this behavior is to save current operation, set current to null, restore current operation. var original = op.UndoLocalSourceExecuteIStoreTransactionScope; op.UndoLocalSourceExecuteIStoreTransactionScope = null; try { return(op.UndoLocalSourceExecute(ts)); } finally { op.UndoLocalSourceExecuteIStoreTransactionScope = original; } } }; return(op); } }; ShardMapManager smm = new ShardMapManager( new SqlShardMapManagerCredentials(Globals.ShardMapManagerConnectionString), new SqlStoreConnectionFactory(), sof, new CacheStore(), ShardMapManagerLoadPolicy.Lazy, new RetryPolicy(1, TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero), RetryBehavior.DefaultRetryBehavior); ShardMap sm = smm.GetShardMap(ShardMapTests.s_defaultShardMapName); Assert.IsNotNull(sm); ShardLocation sl = new ShardLocation(Globals.ShardMapManagerTestsDatasourceName, ShardMapTests.s_shardedDBs[0]); Shard sNew = sm.CreateShard(sl); Assert.IsNotNull(sNew); bool storeOperationFailed = false; try { sm.DeleteShard(sNew); } catch (ShardManagementException sme) { Assert.AreEqual(ShardManagementErrorCategory.ShardMap, sme.ErrorCategory); Assert.AreEqual(ShardManagementErrorCode.StorageOperationFailure, sme.ErrorCode); storeOperationFailed = true; } Assert.IsTrue(storeOperationFailed); // verify that the shard exists in store. Shard sValidate = sm.GetShard(sl); Assert.IsNotNull(sValidate); // Obtain the pending operations. var pendingOperations = ShardMapperTests.GetPendingStoreOperations(); Assert.AreEqual(pendingOperations.Count(), 1); shouldThrow = false; storeOperationFailed = false; try { sm.DeleteShard(sNew); } catch (ShardManagementException) { storeOperationFailed = true; } Assert.IsFalse(storeOperationFailed); Assert.AreEqual(0, sm.GetShards().Count()); }
private void UnloadTable(Shard shard) { }
public abstract void RunCommand(Shard shard, ITextChannel channel, string[] commandParams); //0 is command name
private CompoundTable GetTable(Shard shard) { return null; }
private void LoadTable(CompoundTable table, Shard shard) { }
private EntityState EntityStateToProto(Shard.ShardState entityState) { return EntityState.CreateBuilder().AddRangeEntities(entityState.Entries).Build(); }
public void AddShard(Shard s) { Debug.Log("addded shard"); ShardsAcquired.Add(s); }
public override void RunCommand(Shard shard, ITextChannel channel, string[] commandParams) { DiscordUtil.SendMessage(channel, Response); }
private string FilePath(Shard shard) => Path.Combine(DataTypePath(shard.UserId, shard.DataType), shard.TimeStamp.ToString("o").Replace(':', ';').Replace('.', ','));
// [DataRow(42uL, "0xab48aa2cc6f4a0bb63b5d67be54ac3aed10326dda304c5aeb9e942b40d6e7610478377680ab90e092ef1895e62786008", 0uL, 5uL, 1uL, null)] // [DataRow(42uL, "0x8aea7d8eb22063bcfe882e2b7efc0b3713e1a48dd8343bed523b1ab4546114be84d00f896d33c605d1f67456e8e2ed93", 0uL, 5uL, 1uL, null)] // [DataRow(42uL, "0x89db41a6183c2fe47cf54d1e00c3cfaae53df634a32cccd5cf0c0a73e95ee0450fc3d060bb6878780fbf5f30d9e29aac", 0uL, 5uL, 1uL, null)] // [DataRow(42uL, "0xb783a70a1cf9f53e7d2ddf386bea81a947e5360c5f1e0bf004fceedb2073e4dd180ef3d2d91bee7b1c5a88d1afd11c49", 0uL, 5uL, 1uL, null)] // [DataRow(42uL, "0x8fe55d12257709ae842f8594f9a0a40de3d38dabdf82b21a60baac927e52ed00c5fd42f4c905410eacdaf8f8a9952490", 0uL, 5uL, 1uL, null)] // [DataRow(42uL, "0x95906ec0660892c205634e21ad540cbe0b6f7729d101d5c4639b864dea09be7f42a4252c675d46dd90a2661b3a94e8ca", 0uL, 5uL, 1uL, null)] public async Task ValidatorDutyAtSpecificTimeDuplicateProposal(ulong targetTime, string publicKey, ulong epoch, ulong attestationSlot, ulong attestationShard, ulong?blockProposalSlot) { // NOTE: Current algorithm for GetBeaconProposerIndex() sometimes allocates multiple proposal slots in an epoch, e.g. above index 23 gets slot 2 and 6 // It could be an error in the algorithm (need to check; domain type could be wrong), or due to the pre-shard algorithm. // The algorithm before shards were removed was different, so maybe ignore for now, implement phase 1 (with shards), and worry about it then. // This test for now will simply detect if things unintentionally change. // The implementation of GetValidatorDuties will always return the first assigned slot in an epoch. // This means it is consistent whether run before or after the first slot. // Arrange IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true); testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>()); ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); // Get genesis store initialise MemoryStoreProvider with the state IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); // Move forward time TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; for (ulong timeSinceGenesis = 1; timeSinceGenesis <= targetTime; timeSinceGenesis++) { ulong time = state.GenesisTime + timeSinceGenesis; await forkChoice.OnTickAsync(store, time); if (timeSinceGenesis % timeParameters.SecondsPerSlot == 0) { BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero); SignedBeaconBlock signedBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block); await forkChoice.OnBlockAsync(store, signedBlock); } } Console.WriteLine(""); Console.WriteLine("***** State advanced to slot {0}, time {1}, ready to start tests *****", state.Slot, store.Time); Console.WriteLine(""); // Act ValidatorAssignments validatorAssignments = testServiceProvider.GetService <ValidatorAssignments>(); BlsPublicKey validatorPublicKey = new BlsPublicKey(publicKey); Epoch targetEpoch = new Epoch(epoch); ValidatorDuty validatorDuty = await validatorAssignments.GetValidatorDutyAsync(validatorPublicKey, targetEpoch); Console.WriteLine("Validator {0}, epoch {1}: attestation slot {2}, shard {3}, proposal slot {4}", validatorPublicKey, targetEpoch, validatorDuty.AttestationSlot, (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot); // Assert validatorDuty.ValidatorPublicKey.ShouldBe(validatorPublicKey); Slot? expectedBlockProposalSlot = (Slot?)blockProposalSlot; Slot expectedAttestationSlot = new Slot(attestationSlot); Shard expectedAttestationShard = new Shard(attestationShard); validatorDuty.BlockProposalSlot.ShouldBe(expectedBlockProposalSlot); validatorDuty.AttestationSlot.ShouldBe(expectedAttestationSlot); validatorDuty.AttestationShard.ShouldBe(expectedAttestationShard); }
public override void RunCommand(Shard shard, ITextChannel channel, string[] commandParams) { JfsPing.UserManager.ReloadUsers(); DiscordUtil.SendMessage(channel, "Reloaded Users!"); }
public ActionResult Create(Shard shard) { return null; }
private ShardStats ShardStatsToProto(Shard.ShardStats o) { return ShardStats.CreateBuilder().SetShard(o.ShardId).SetEntityCount(o.EntityCount).Build(); }
public void CreateShardAbortGSM() { int retryCount = 0; EventHandler <RetryingEventArgs> eventHandler = (sender, arg) => { retryCount++; }; ShardMapManager smm = new ShardMapManager( new SqlShardMapManagerCredentials(Globals.ShardMapManagerConnectionString), new SqlStoreConnectionFactory(), new StubStoreOperationFactory() { CallBase = true, CreateAddShardOperationShardMapManagerIStoreShardMapIStoreShard = (_smm, _sm, _s) => new NTimeFailingAddShardOperation(10, _smm, _sm, _s) }, new CacheStore(), ShardMapManagerLoadPolicy.Lazy, new RetryPolicy(5, TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero), RetryBehavior.DefaultRetryBehavior); ShardMap sm = smm.GetShardMap(ShardMapTests.s_defaultShardMapName); Assert.IsNotNull(sm); ShardLocation sl = new ShardLocation(Globals.ShardMapManagerTestsDatasourceName, ShardMapTests.s_shardedDBs[0]); bool storeOperationFailed = false; smm.ShardMapManagerRetrying += eventHandler; try { Shard sNew = sm.CreateShard(sl); Assert.IsNotNull(sNew); } catch (ShardManagementException sme) { Assert.AreEqual(ShardManagementErrorCategory.ShardMap, sme.ErrorCategory); Assert.AreEqual(ShardManagementErrorCode.StorageOperationFailure, sme.ErrorCode); storeOperationFailed = true; } smm.ShardMapManagerRetrying -= eventHandler; Assert.AreEqual(5, retryCount); Assert.IsTrue(storeOperationFailed); // verify that shard map does not have any shards. int count = 0; IEnumerable <Shard> sList = sm.GetShards(); using (IEnumerator <Shard> sEnum = sList.GetEnumerator()) { while (sEnum.MoveNext()) { count++; } } Assert.AreEqual(0, count); }
public LogContext(long member_no) { shard_id_ = Shard.GetShardId(member_no); }
private Task InitCommands() { Command <TUser> newCommand = null; // !global newCommand = new Command <TUser>("global"); newCommand.Type = CommandType.Standard; newCommand.Description = "Display all teh numbers."; newCommand.RequiredPermissions = PermissionType.OwnerOnly; newCommand.OnExecute += async e => { StringBuilder shards = new StringBuilder(); GlobalContext dbContext = GlobalContext.Create(this.DbConfig.GetDbConnectionString()); Shard globalCount = new Shard(); foreach (Shard shard in dbContext.Shards) { globalCount.ServerCount += shard.ServerCount; globalCount.UserCount += shard.UserCount; globalCount.MemoryUsed += shard.MemoryUsed; globalCount.ThreadsActive += shard.ThreadsActive; globalCount.MessagesTotal += shard.MessagesTotal; globalCount.MessagesPerMinute += shard.MessagesPerMinute; globalCount.OperationsRan += shard.OperationsRan; globalCount.OperationsActive += shard.OperationsActive; globalCount.Disconnects += shard.Disconnects; shards.AppendLine(shard.GetStatsString()); } string message = "Server Status: <http://status.botwinder.info>\n\n" + $"Global Servers: `{globalCount.ServerCount}`\n" + $"Global Members `{globalCount.UserCount}`\n" + $"Global Allocated data Memory: `{globalCount.MemoryUsed} MB`\n" + $"Global Threads: `{globalCount.ThreadsActive}`\n" + $"Global Messages received: `{globalCount.MessagesTotal}`\n" + $"Global Messages per minute: `{globalCount.MessagesPerMinute}`\n" + $"Global Operations ran: `{globalCount.OperationsRan}`\n" + $"Global Operations active: `{globalCount.OperationsActive}`\n" + $"Global Disconnects: `{globalCount.Disconnects}`\n" + $"\n**Shards: `{dbContext.Shards.Count()}`**\n\n" + $"{shards.ToString()}"; await SendMessageToChannel(e.Channel, message); }; this.Commands.Add(newCommand.Id, newCommand); // !getServer newCommand = new Command <TUser>("getServer"); newCommand.Type = CommandType.Standard; newCommand.Description = "Display some info about specific server with id/name, or owners id/username."; newCommand.RequiredPermissions = PermissionType.OwnerOnly; newCommand.OnExecute += async e => { if (string.IsNullOrEmpty(e.TrimmedMessage)) { await SendMessageToChannel(e.Channel, "Requires parameters."); return; } guid id; guid.TryParse(e.TrimmedMessage, out id); StringBuilder response = new StringBuilder(); IEnumerable <ServerStats> foundServers = null; if (!(foundServers = ServerContext.Create(this.DbConfig.GetDbConnectionString()).ServerStats.Where(s => s.ServerId == id || s.OwnerId == id || s.ServerName.ToLower().Contains($"{e.TrimmedMessage.ToLower()}") || s.OwnerName.ToLower().Contains($"{e.TrimmedMessage.ToLower()}") )).Any()) { await SendMessageToChannel(e.Channel, "Server not found."); return; } if (foundServers.Count() > 5) { response.AppendLine("__**Found more than 5 servers!**__\n"); } foreach (ServerStats server in foundServers.Take(5)) { response.AppendLine(server.ToString()); response.AppendLine(); } await SendMessageToChannel(e.Channel, response.ToString()); }; this.Commands.Add(newCommand.Id, newCommand); // !getInvite newCommand = new Command <TUser>("getInvite"); newCommand.Type = CommandType.Standard; newCommand.Description = "Get an invite url with serverid."; newCommand.RequiredPermissions = PermissionType.OwnerOnly; newCommand.OnExecute += async e => { guid id; ServerConfig foundServer = null; if (string.IsNullOrEmpty(e.TrimmedMessage) || !guid.TryParse(e.TrimmedMessage, out id) || (foundServer = ServerContext.Create(this.DbConfig.GetDbConnectionString()).ServerConfigurations.FirstOrDefault(s => s.ServerId == id)) == null) { await SendMessageToChannel(e.Channel, "Server not found."); return; } if (string.IsNullOrEmpty(foundServer.InviteUrl)) { await SendMessageToChannel(e.Channel, "I don't have permissions to create this InviteUrl."); return; } await SendMessageToChannel(e.Channel, foundServer.InviteUrl); }; this.Commands.Add(newCommand.Id, newCommand); // !maintenance newCommand = new Command <TUser>("maintenance"); newCommand.Type = CommandType.Standard; newCommand.Description = "Performe maintenance"; newCommand.RequiredPermissions = PermissionType.OwnerOnly; newCommand.OnExecute += async e => { await SendMessageToChannel(e.Channel, "Okay, this may take a while..."); await LogMaintenanceAndExit(); }; this.Commands.Add(newCommand.Id, newCommand); // !restart newCommand = new Command <TUser>("restart"); newCommand.Type = CommandType.Standard; newCommand.Description = "Shut down the bot."; newCommand.RequiredPermissions = PermissionType.OwnerOnly; newCommand.OnExecute += async e => { await SendMessageToChannel(e.Channel, "bai"); await Task.Delay(1000); Environment.Exit(0); }; this.Commands.Add(newCommand.Id, newCommand); this.Commands.Add("shutdown", newCommand.CreateAlias("shutdown")); // !getExceptions newCommand = new Command <TUser>("getExceptions"); newCommand.Type = CommandType.Standard; newCommand.Description = "Get a list of exceptions."; newCommand.RequiredPermissions = PermissionType.OwnerOnly; newCommand.OnExecute += async e => { StringBuilder response = new StringBuilder(); if (string.IsNullOrEmpty(e.TrimmedMessage) || !int.TryParse(e.TrimmedMessage, out int n) || n <= 0) { n = 5; } GlobalContext dbContext = GlobalContext.Create(this.DbConfig.GetDbConnectionString()); foreach (ExceptionEntry exception in dbContext.Exceptions.Skip(Math.Max(0, dbContext.Exceptions.Count() - n))) { response.AppendLine(exception.GetMessage()); } string responseString = response.ToString(); if (string.IsNullOrWhiteSpace(responseString)) { responseString = "I did not record any errors :stuck_out_tongue:"; } await SendMessageToChannel(e.Channel, responseString); }; this.Commands.Add(newCommand.Id, newCommand); // !getException newCommand = new Command <TUser>("getException"); newCommand.Type = CommandType.Standard; newCommand.Description = "Get an exception stack for specific ID."; newCommand.RequiredPermissions = PermissionType.OwnerOnly; newCommand.OnExecute += async e => { string responseString = "I couldn't find that exception."; ExceptionEntry exception = null; GlobalContext dbContext = GlobalContext.Create(this.DbConfig.GetDbConnectionString()); if (!string.IsNullOrEmpty(e.TrimmedMessage) && int.TryParse(e.TrimmedMessage, out int id) && (exception = dbContext.Exceptions.FirstOrDefault(ex => ex.Id == id)) != null) { responseString = exception.GetStack(); } await SendMessageToChannel(e.Channel, responseString); }; this.Commands.Add(newCommand.Id, newCommand); // !blacklist newCommand = new Command <TUser>("blacklist"); newCommand.Type = CommandType.Standard; newCommand.Description = "Add or remove an ID to or from the blacklist."; newCommand.RequiredPermissions = PermissionType.OwnerOnly; newCommand.OnExecute += async e => { guid id = 0; string responseString = "Invalid parameters."; if (e.MessageArgs == null || e.MessageArgs.Length < 2 || !guid.TryParse(e.MessageArgs[1], out id)) { if (!e.Message.MentionedUsers.Any()) { await SendMessageToChannel(e.Channel, responseString); return; } id = e.Message.MentionedUsers.First().Id; } GlobalContext dbContext = GlobalContext.Create(this.DbConfig.GetDbConnectionString()); ServerStats server = ServerContext.Create(this.DbConfig.GetDbConnectionString()).ServerStats .FirstOrDefault(s => s.ServerId == id || s.OwnerId == id); switch (e.MessageArgs[0]) { case "add": if (dbContext.Blacklist.Any(b => b.Id == id)) { responseString = "That ID is already blacklisted."; break; } dbContext.Blacklist.Add(new BlacklistEntry() { Id = id }); dbContext.SaveChanges(); responseString = server == null ? "Done." : server.ServerId == id ? $"I'll be leaving `{server.OwnerName}`'s server `{server.ServerName}` shortly." : $"All of `{server.OwnerName}`'s servers are now blacklisted."; break; case "remove": BlacklistEntry entry = dbContext.Blacklist.FirstOrDefault(b => b.Id == id); if (entry == null) { responseString = "That ID was not blacklisted."; break; } dbContext.Blacklist.Remove(entry); dbContext.SaveChanges(); responseString = server == null ? "Done." : server.ServerId == id ? $"Entry for `{server.OwnerName}`'s server `{server.ServerName}` was removed from the balcklist." : $"Entries for all `{server.OwnerName}`'s servers were removed from the blacklist."; break; default: responseString = "Invalid keyword."; break; } await SendMessageToChannel(e.Channel, responseString); }; this.Commands.Add(newCommand.Id, newCommand); // !subscriber newCommand = new Command <TUser>("subscriber"); newCommand.Type = CommandType.Standard; newCommand.Description = "Add or remove an ID to or from the subscribers, use with optional bonus or premium parameter."; newCommand.RequiredPermissions = PermissionType.OwnerOnly; newCommand.OnExecute += async e => { guid id = 0; string responseString = "Invalid parameters."; if (e.MessageArgs == null || e.MessageArgs.Length < 2 || !guid.TryParse(e.MessageArgs[1], out id)) { if (!e.Message.MentionedUsers.Any()) { await SendMessageToChannel(e.Channel, responseString); return; } id = e.Message.MentionedUsers.First().Id; } GlobalContext dbContext = GlobalContext.Create(this.DbConfig.GetDbConnectionString()); Subscriber subscriber = dbContext.Subscribers.FirstOrDefault(s => s.UserId == id); switch (e.MessageArgs[0]) //Nope - mentioned users above mean that there is a parameter. { case "add": if (subscriber == null) { dbContext.Subscribers.Add(subscriber = new Subscriber() { UserId = id }); } for (int i = 2; i < e.MessageArgs.Length; i++) { subscriber.HasBonus = subscriber.HasBonus || e.MessageArgs[i] == "bonus"; subscriber.IsPremium = subscriber.IsPremium || e.MessageArgs[i] == "premium"; } dbContext.SaveChanges(); responseString = "Done."; break; case "remove": if (subscriber == null) { responseString = "That ID was not a subscriber."; break; } responseString = "Done."; if (e.MessageArgs.Length < 3) { dbContext.Subscribers.Remove(subscriber); break; } for (int i = 2; i < e.MessageArgs.Length; i++) { subscriber.HasBonus = subscriber.HasBonus && e.MessageArgs[i] != "bonus"; subscriber.IsPremium = subscriber.IsPremium && e.MessageArgs[i] != "premium"; } dbContext.SaveChanges(); break; default: responseString = "Invalid keyword."; break; } await SendMessageToChannel(e.Channel, responseString); }; this.Commands.Add(newCommand.Id, newCommand); // !partner newCommand = new Command <TUser>("partner"); newCommand.Type = CommandType.Standard; newCommand.Description = "Add or remove an ID to or from the partners, use with optional premium parameter."; newCommand.RequiredPermissions = PermissionType.OwnerOnly; newCommand.OnExecute += async e => { guid id = 0; string responseString = "Invalid parameters."; if (e.MessageArgs == null || e.MessageArgs.Length < 2 || !guid.TryParse(e.MessageArgs[1], out id)) { if (!e.Message.MentionedUsers.Any()) { await SendMessageToChannel(e.Channel, responseString); return; } id = e.Message.MentionedUsers.First().Id; } GlobalContext dbContext = GlobalContext.Create(this.DbConfig.GetDbConnectionString()); PartneredServer partner = dbContext.PartneredServers.FirstOrDefault(s => s.ServerId == id); switch (e.MessageArgs[0]) //Nope - mentioned users above mean that there is a parameter. { case "add": if (partner == null) { dbContext.PartneredServers.Add(partner = new PartneredServer() { ServerId = id }); } if (e.MessageArgs.Length > 2) { partner.IsPremium = partner.IsPremium || e.MessageArgs[2] == "premium"; } dbContext.SaveChanges(); responseString = "Done."; break; case "remove": if (partner == null) { responseString = "That ID was not a partner."; break; } responseString = "Done."; if (e.MessageArgs.Length < 3) { dbContext.PartneredServers.Remove(partner); break; } if (e.MessageArgs.Length > 2) { partner.IsPremium = partner.IsPremium && e.MessageArgs[2] != "premium"; } dbContext.SaveChanges(); break; default: responseString = "Invalid keyword."; break; } await SendMessageToChannel(e.Channel, responseString); }; this.Commands.Add(newCommand.Id, newCommand); // !operations newCommand = new Command <TUser>("operations"); newCommand.Type = CommandType.Standard; newCommand.Description = "Display info about all queued or running operations on your server."; newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin; newCommand.OnExecute += async e => { StringBuilder response = new StringBuilder(); bool allOperations = IsGlobalAdmin(e.Message.Author.Id); response.AppendLine($"Total operations in the queue: `{this.CurrentOperations.Count}`"); if (allOperations) { response.AppendLine($"Currently allocated data Memory: `{(GC.GetTotalMemory(false) / 1000000f):#0.00} MB`"); } response.AppendLine(); lock (this.OperationsLock) { foreach (Operation <TUser> op in this.CurrentOperations) { if (!allOperations && op.CommandArgs.Server.Id != e.Server.Id) { continue; } response.AppendLine(op.ToString()); if (allOperations) { response.AppendLine($"Server: `{op.CommandArgs.Server.Guild.Name}`\n" + $"ServerID: `{op.CommandArgs.Server.Id}`\n" + $"Allocated DataMemory: `{op.AllocatedMemoryStarted:#0.00} MB`\n"); } } } string responseString = response.ToString(); if (string.IsNullOrEmpty(responseString)) { responseString = "There are no operations running."; } await SendMessageToChannel(e.Channel, responseString); }; this.Commands.Add(newCommand.Id, newCommand); // !cancel newCommand = new Command <TUser>("cancel"); newCommand.Type = CommandType.Standard; newCommand.Description = "Cancel queued or running operation - use in the same channel, and with the name of the command as parameter. (nuke, archive, etc...)"; newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin; newCommand.OnExecute += async e => { string responseString = "Operation not found."; Operation <TUser> operation = null; if (!string.IsNullOrEmpty(e.TrimmedMessage) && (operation = this.CurrentOperations.FirstOrDefault( op => op.CommandArgs.Channel.Id == e.Channel.Id && op.CommandArgs.Command.Id == e.TrimmedMessage)) != null) { responseString = "Operation canceled:\n\n" + operation.ToString(); } await SendMessageToChannel(e.Channel, responseString); }; this.Commands.Add(newCommand.Id, newCommand); // !say newCommand = new Command <TUser>("say"); newCommand.Type = CommandType.Standard; newCommand.Description = "Make the bot say something!"; newCommand.RequiredPermissions = PermissionType.SubModerator; newCommand.DeleteRequest = true; newCommand.IsBonusCommand = true; newCommand.OnExecute += async e => { if (string.IsNullOrWhiteSpace(e.TrimmedMessage)) { return; } await SendMessageToChannel(e.Channel, e.TrimmedMessage); }; this.Commands.Add(newCommand.Id, newCommand); // !ping newCommand = new Command <TUser>("ping"); newCommand.Type = CommandType.Standard; newCommand.Description = "Measure how long does it take to receive a message and handle it as a command."; newCommand.RequiredPermissions = PermissionType.Everyone; newCommand.OnExecute += async e => { TimeSpan time = DateTime.UtcNow - Utils.GetTimeFromId(e.Message.Id); string responseString = "`" + time.TotalMilliseconds.ToString("#00") + "`ms"; await SendMessageToChannel(e.Channel, responseString); }; this.Commands.Add(newCommand.Id, newCommand); // !help newCommand = new Command <TUser>("help"); newCommand.Type = CommandType.Standard; newCommand.Description = "PMs a list of Custom Commands for the server if used without a parameter. Use with a parameter to search for specific commands."; newCommand.RequiredPermissions = PermissionType.Everyone; newCommand.OnExecute += async e => { StringBuilder response = new StringBuilder("Please refer to the website documentation for the full list of features and commands: <http://botwinder.info/docs>\n\n"); StringBuilder commandStrings = new StringBuilder(); bool isSpecific = !string.IsNullOrWhiteSpace(e.TrimmedMessage); string prefix = e.Server.Config.CommandPrefix; List <string> includedCommandIds = new List <string>(); int count = 0; void AddCustomAlias(string commandId) { List <CustomAlias> aliases = e.Server.CustomAliases.Values.Where(a => a.CommandId == commandId).ToList(); int aliasCount = aliases.Count; if (aliasCount > 0) { commandStrings.Append(aliasCount == 1 ? " **-** Custom Alias: " : " **-** Custom Aliases: "); for (int i = 0; i < aliasCount; i++) { commandStrings.Append((i == 0 ? "`" : i == aliasCount - 1 ? " and `" : ", `") + prefix + aliases[i].Alias + "`"); } } commandStrings.AppendLine(); } void AddCommand(Command <TUser> cmd) { commandStrings.AppendLine($"\n```diff\n{(cmd.CanExecute(this, e.Server, e.Channel, e.Message.Author as SocketGuildUser) ? "+" : "-")}" + $" {prefix}{cmd.Id}```" + $" **-** {cmd.Description}"); if (cmd.Aliases != null && cmd.Aliases.Any()) { int aliasCount = cmd.Aliases.Count; commandStrings.Append(aliasCount == 1 ? " **-** Alias: " : " **-** Aliases: "); for (int i = 0; i < aliasCount; i++) { commandStrings.Append((i == 0 ? "`" : i == aliasCount - 1 ? " and `" : ", `") + prefix + cmd.Aliases[i] + "`"); } commandStrings.AppendLine(); } AddCustomAlias(cmd.Id); } void AddCustomCommand(CustomCommand cmd) { commandStrings.AppendLine($"\n```diff\n{(cmd.CanExecute(this, e.Server, e.Channel, e.Message.Author as SocketGuildUser) ? "+" : "-")}" + $" {prefix}{cmd.CommandId}```" + $" **-** {cmd.Description}"); AddCustomAlias(cmd.CommandId); } if (isSpecific) { string expression = e.TrimmedMessage.Replace(" ", "|") + ")\\w*"; if (e.MessageArgs.Length > 1) { expression += "(" + expression; } Regex regex = new Regex($"\\w*({expression}", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(10f)); foreach (Command <TUser> cmd in e.Server.Commands.Values) { if (!cmd.IsHidden && cmd.RequiredPermissions != PermissionType.OwnerOnly && regex.Match(cmd.Id).Success) { Command <TUser> command = cmd; if (cmd.IsAlias && e.Server.Commands.ContainsKey(cmd.ParentId)) { command = e.Server.Commands[cmd.ParentId]; } if (includedCommandIds.Contains(command.Id)) { continue; } if (++count > 5) { break; } AddCommand(cmd); } } foreach (CustomCommand cmd in e.Server.CustomCommands.Values) { if (regex.Match(cmd.CommandId).Success) //Chances are that it's gonna fail more often. { if (includedCommandIds.Contains(cmd.CommandId)) { continue; } if (++count > 5) { break; } AddCustomCommand(cmd); } } foreach (CustomAlias alias in e.Server.CustomAliases.Values) { if (regex.Match(alias.Alias).Success) //Chances are that it's gonna fail more often. { if (includedCommandIds.Contains(alias.CommandId)) { continue; } if (++count > 5) { break; } if (e.Server.Commands.ContainsKey(alias.CommandId)) { AddCommand(e.Server.Commands[alias.CommandId]); } else if (e.Server.CustomCommands.ContainsKey(alias.CommandId)) { AddCustomCommand(e.Server.CustomCommands[alias.CommandId]); } } } if (count == 0) { response.AppendLine("I did not find any commands matching your search expression."); } else { if (count > 5) { response.AppendLine("I found too many commands matching your search expression. **Here are the first five:**"); } response.Append(commandStrings.ToString()); } } else //Not specific - PM CustomCommands. { foreach (CustomCommand cmd in e.Server.CustomCommands.Values) { if (includedCommandIds.Contains(cmd.CommandId)) { continue; } if (++count > 5) { break; } AddCustomCommand(cmd); } response.AppendLine("I've PMed you the Custom Commands for this server."); await e.Message.Author.SendMessageSafe(commandStrings.ToString()); } await SendMessageToChannel(e.Channel, response.ToString()); }; this.Commands.Add(newCommand.Id, newCommand); /* * // !command * newCommand = new Command<TUser>("command"); * newCommand.Type = CommandType.Standard; * newCommand.Description = ""; * newCommand.RequiredPermissions = PermissionType.OwnerOnly; * newCommand.OnExecute += async e => { * string responseString = ""; * await SendMessageToChannel(e.Channel, responseString); * }; * this.Commands.Add(newCommand.Id, newCommand); * */ return(Task.CompletedTask); }
public LogContext(Session session) { shard_id_ = Shard.GetShardId(session.member_no); }
public async Task FutureEpochValidatorDuty() { // Arrange IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true); testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>()); ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); // Get genesis store initialise MemoryStoreProvider with the state IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); // Move forward time TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; ulong time = state.GenesisTime + 1; ulong nextSlotTime = state.GenesisTime + timeParameters.SecondsPerSlot; // half way through epoch 4 ulong futureEpoch = 4uL; ulong slots = futureEpoch * timeParameters.SlotsPerEpoch + timeParameters.SlotsPerEpoch / 2; for (ulong slot = 1; slot < slots; slot++) { while (time < nextSlotTime) { await forkChoice.OnTickAsync(store, time); time++; } await forkChoice.OnTickAsync(store, time); time++; // Hash32 head = await forkChoice.GetHeadAsync(store); // store.TryGetBlockState(head, out BeaconState headState); BeaconState headState = state; BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, headState, BlsSignature.Zero); SignedBeaconBlock signedBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, headState, block); await forkChoice.OnBlockAsync(store, signedBlock); nextSlotTime = nextSlotTime + timeParameters.SecondsPerSlot; } // halfway through slot ulong futureTime = nextSlotTime + timeParameters.SecondsPerSlot / 2; while (time < futureTime) { await forkChoice.OnTickAsync(store, time); time++; } Console.WriteLine(""); Console.WriteLine("***** State advanced to epoch {0}, slot {1}, time {2}, ready to start tests *****", futureEpoch, state.Slot, store.Time); Console.WriteLine(""); List <object?[]> data = FutureEpochValidatorDutyData().ToList(); for (int dataIndex = 0; dataIndex < data.Count; dataIndex++) { object?[] dataRow = data[dataIndex]; string publicKey = (string)dataRow[0] !; ulong epoch = (ulong)dataRow[1] !; bool success = (bool)dataRow[2] !; ulong? attestationSlot = (ulong?)dataRow[3] !; ulong attestationShard = (ulong)dataRow[4] !; ulong? blockProposalSlot = (ulong?)dataRow[5]; Console.WriteLine("** Test {0}, public key {1}, epoch {2}", dataIndex, publicKey, epoch); // Act ValidatorAssignments validatorAssignments = testServiceProvider.GetService <ValidatorAssignments>(); BlsPublicKey validatorPublicKey = new BlsPublicKey(publicKey); Epoch targetEpoch = new Epoch(epoch); // failure expected if (!success) { Should.Throw <Exception>(async() => { ValidatorDuty validatorDuty = await validatorAssignments.GetValidatorDutyAsync(validatorPublicKey, targetEpoch); Console.WriteLine( "Validator {0}, epoch {1}: attestation slot {2}, shard {3}, proposal slot {4}", validatorPublicKey, targetEpoch, validatorDuty.AttestationSlot, (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot); }, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); continue; } ValidatorDuty validatorDuty = await validatorAssignments.GetValidatorDutyAsync(validatorPublicKey, targetEpoch); Console.WriteLine("Validator {0}, epoch {1}: attestation slot {2}, shard {3}, proposal slot {4}", validatorPublicKey, targetEpoch, validatorDuty.AttestationSlot, (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot); // Assert validatorDuty.ValidatorPublicKey.ShouldBe(validatorPublicKey, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); Slot? expectedBlockProposalSlot = (Slot?)blockProposalSlot; Slot? expectedAttestationSlot = (Slot?)attestationSlot; Shard expectedAttestationShard = new Shard(attestationShard); validatorDuty.BlockProposalSlot.ShouldBe(expectedBlockProposalSlot, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); validatorDuty.AttestationSlot.ShouldBe(expectedAttestationSlot, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); validatorDuty.AttestationShard.ShouldBe(expectedAttestationShard, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); } }
private CompoundTable GetTable(Shard shard) { return(null); }
public static void ShardMapManagerLoadTestsInitialize(TestContext testContext) { // Clear all connection pools. SqlConnection.ClearAllPools(); using (SqlConnection conn = new SqlConnection(Globals.ShardMapManagerTestConnectionString)) { conn.Open(); // Create ShardMapManager database using (SqlCommand cmd = new SqlCommand( string.Format(Globals.CreateDatabaseQuery, Globals.ShardMapManagerDatabaseName), conn)) { cmd.ExecuteNonQuery(); } // Create shard databases for (int i = 0; i < ShardMapManagerLoadTests.s_shardedDBs.Length; i++) { using (SqlCommand cmd = new SqlCommand( string.Format(Globals.CreateDatabaseQuery, ShardMapManagerLoadTests.s_shardedDBs[i]), conn)) { cmd.ExecuteNonQuery(); } } // cleanup for deadlock monitoring foreach (string q in s_deadlockDetectionCleanupQueries) { using (SqlCommand cmd = new SqlCommand(q, conn)) { try { cmd.ExecuteNonQuery(); } catch (SqlException) { } } } // setup for deadlock monitoring foreach (string q in s_deadlockDetectionSetupQueries) { using (SqlCommand cmd = new SqlCommand(q, conn)) { try { cmd.ExecuteNonQuery(); } catch (SqlException) { } } } } // Create shard map manager. ShardMapManagerFactory.CreateSqlShardMapManager( Globals.ShardMapManagerConnectionString, ShardMapManagerCreateMode.ReplaceExisting); // Create list shard map. ShardMapManager smm = ShardMapManagerFactory.GetSqlShardMapManager( Globals.ShardMapManagerConnectionString, ShardMapManagerLoadPolicy.Lazy); ListShardMap <int> lsm = smm.CreateListShardMap <int>(ShardMapManagerLoadTests.s_listShardMapName); Assert.IsNotNull(lsm); // Create range shard map. RangeShardMap <int> rsm = smm.CreateRangeShardMap <int>(ShardMapManagerLoadTests.s_rangeShardMapName); Assert.IsNotNull(rsm); // Add 'InitialShardCount' shards to list and range shard map. for (int i = 0; i < ShardMapManagerLoadTests.InitialShardCount; i++) { ShardCreationInfo si = new ShardCreationInfo( new ShardLocation(Globals.ShardMapManagerTestsDatasourceName, ShardMapManagerLoadTests.s_shardedDBs[i]), ShardStatus.Online); Shard sList = lsm.CreateShard(si); Assert.IsNotNull(sList); Shard sRange = rsm.CreateShard(si); Assert.IsNotNull(sRange); } // Initialize retry policy s_retryPolicy = new RetryPolicy <SqlAzureTransientErrorDetectionStrategy>( new ExponentialBackoff(5, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(100))); }