How to use Stop method of Microsoft.Coyote.Actors.ActorExecutionContext class

Best Coyote code snippet using Microsoft.Coyote.Actors.ActorExecutionContext.Stop

ActorExecutionContext.cs

Source:ActorExecutionContext.cs Github

copy

Full Screen

...665 public void RegisterLog(IActorRuntimeLog log) => this.LogWriter.RegisterLog(log);666 /// <inheritdoc/>667 public void RemoveLog(IActorRuntimeLog log) => this.LogWriter.RemoveLog(log);668 /// <inheritdoc/>669 public void Stop() => this.Scheduler.ForceStop();670 /// <summary>671 /// Disposes runtime resources.672 /// </summary>673 protected virtual void Dispose(bool disposing)674 {675 if (disposing)676 {677 this.ActorMap.Clear();678 }679 }680 /// <inheritdoc/>681 public void Dispose()682 {683 this.Dispose(true);684 GC.SuppressFinalize(this);685 }686 /// <summary>687 /// The mocked execution context of an actor program.688 /// </summary>689 internal sealed class Mock : ActorExecutionContext690 {691 /// <summary>692 /// Map that stores all unique names and their corresponding actor ids.693 /// </summary>694 private readonly ConcurrentDictionary<string, ActorId> NameValueToActorId;695 /// <summary>696 /// Map of program counters used for state-caching to distinguish697 /// scheduling from non-deterministic choices.698 /// </summary>699 private readonly ConcurrentDictionary<ActorId, int> ProgramCounterMap;700 /// <summary>701 /// If true, the actor execution is controlled, else false.702 /// </summary>703 internal override bool IsExecutionControlled => true;704 /// <summary>705 /// Initializes a new instance of the <see cref="Mock"/> class.706 /// </summary>707 internal Mock(Configuration configuration, CoyoteRuntime runtime, OperationScheduler scheduler,708 SpecificationEngine specificationEngine, IRandomValueGenerator valueGenerator, LogWriter logWriter)709 : base(configuration, runtime, scheduler, specificationEngine, valueGenerator, logWriter)710 {711 this.NameValueToActorId = new ConcurrentDictionary<string, ActorId>();712 this.ProgramCounterMap = new ConcurrentDictionary<ActorId, int>();713 }714 /// <inheritdoc/>715 public override ActorId CreateActorIdFromName(Type type, string name)716 {717 // It is important that all actor ids use the monotonically incrementing718 // value as the id during testing, and not the unique name.719 return this.NameValueToActorId.GetOrAdd(name, key => this.CreateActorId(type, key));720 }721 /// <inheritdoc/>722 public override ActorId CreateActor(Type type, Event initialEvent = null, EventGroup eventGroup = null) =>723 this.CreateActor(null, type, null, initialEvent, eventGroup);724 /// <inheritdoc/>725 public override ActorId CreateActor(Type type, string name, Event initialEvent = null, EventGroup eventGroup = null) =>726 this.CreateActor(null, type, name, initialEvent, eventGroup);727 /// <inheritdoc/>728 public override ActorId CreateActor(ActorId id, Type type, Event initialEvent = null, EventGroup eventGroup = null)729 {730 this.Assert(id != null, "Cannot create an actor using a null actor id.");731 return this.CreateActor(id, type, null, initialEvent, eventGroup);732 }733 /// <inheritdoc/>734 public override Task<ActorId> CreateActorAndExecuteAsync(Type type, Event initialEvent = null, EventGroup eventGroup = null) =>735 this.CreateActorAndExecuteAsync(null, type, null, initialEvent, eventGroup);736 /// <inheritdoc/>737 public override Task<ActorId> CreateActorAndExecuteAsync(Type type, string name, Event initialEvent = null, EventGroup eventGroup = null) =>738 this.CreateActorAndExecuteAsync(null, type, name, initialEvent, eventGroup);739 /// <inheritdoc/>740 public override Task<ActorId> CreateActorAndExecuteAsync(ActorId id, Type type, Event initialEvent = null, EventGroup eventGroup = null)741 {742 this.Assert(id != null, "Cannot create an actor using a null actor id.");743 return this.CreateActorAndExecuteAsync(id, type, null, initialEvent, eventGroup);744 }745 /// <summary>746 /// Creates a new actor of the specified <see cref="Type"/> and name, using the specified747 /// unbound actor id, and passes the specified optional <see cref="Event"/>. This event748 /// can only be used to access its payload, and cannot be handled.749 /// </summary>750 internal ActorId CreateActor(ActorId id, Type type, string name, Event initialEvent = null, EventGroup eventGroup = null)751 {752 var creatorOp = this.Scheduler.GetExecutingOperation<ActorOperation>();753 return this.CreateActor(id, type, name, initialEvent, creatorOp?.Actor, eventGroup);754 }755 /// <summary>756 /// Creates a new <see cref="Actor"/> of the specified <see cref="Type"/>.757 /// </summary>758 internal override ActorId CreateActor(ActorId id, Type type, string name, Event initialEvent, Actor creator, EventGroup eventGroup)759 {760 this.AssertExpectedCallerActor(creator, "CreateActor");761 Actor actor = this.CreateActor(id, type, name, creator, eventGroup);762 this.RunActorEventHandler(actor, initialEvent, true, null);763 return actor.Id;764 }765 /// <summary>766 /// Creates a new actor of the specified <see cref="Type"/> and name, using the specified767 /// unbound actor id, and passes the specified optional <see cref="Event"/>. This event768 /// can only be used to access its payload, and cannot be handled. The method returns only769 /// when the actor is initialized and the <see cref="Event"/> (if any) is handled.770 /// </summary>771 internal Task<ActorId> CreateActorAndExecuteAsync(ActorId id, Type type, string name, Event initialEvent = null,772 EventGroup eventGroup = null)773 {774 var creatorOp = this.Scheduler.GetExecutingOperation<ActorOperation>();775 return this.CreateActorAndExecuteAsync(id, type, name, initialEvent, creatorOp?.Actor, eventGroup);776 }777 /// <summary>778 /// Creates a new <see cref="Actor"/> of the specified <see cref="Type"/>. The method779 /// returns only when the actor is initialized and the <see cref="Event"/> (if any)780 /// is handled.781 /// </summary>782 internal override async Task<ActorId> CreateActorAndExecuteAsync(ActorId id, Type type, string name, Event initialEvent,783 Actor creator, EventGroup eventGroup)784 {785 this.AssertExpectedCallerActor(creator, "CreateActorAndExecuteAsync");786 this.Assert(creator != null, "Only an actor can call 'CreateActorAndExecuteAsync': avoid calling " +787 "it directly from the test method; instead call it through a test driver actor.");788 Actor actor = this.CreateActor(id, type, name, creator, eventGroup);789 this.RunActorEventHandler(actor, initialEvent, true, creator);790 // Wait until the actor reaches quiescence.791 await creator.ReceiveEventAsync(typeof(QuiescentEvent), rev => (rev as QuiescentEvent).ActorId == actor.Id);792 return await Task.FromResult(actor.Id);793 }794 /// <summary>795 /// Creates a new <see cref="Actor"/> of the specified <see cref="Type"/>.796 /// </summary>797 internal override Actor CreateActor(ActorId id, Type type, string name, Actor creator, EventGroup eventGroup)798 {799 this.Assert(type.IsSubclassOf(typeof(Actor)), "Type '{0}' is not an actor.", type.FullName);800 // Using ulong.MaxValue because a Create operation cannot specify801 // the id of its target, because the id does not exist yet.802 this.Scheduler.ScheduleNextOperation(AsyncOperationType.Create);803 this.ResetProgramCounter(creator);804 if (id is null)805 {806 id = this.CreateActorId(type, name);807 }808 else809 {810 this.Assert(id.Runtime is null || id.Runtime == this, "Unbound actor id '{0}' was created by another runtime.", id.Value);811 this.Assert(id.Type == type.FullName, "Cannot bind actor id '{0}' of type '{1}' to an actor of type '{2}'.",812 id.Value, id.Type, type.FullName);813 id.Bind(this);814 }815 // If a group was not provided, inherit the current event group from the creator (if any).816 if (eventGroup is null && creator != null)817 {818 eventGroup = creator.EventGroup;819 }820 Actor actor = ActorFactory.Create(type);821 ActorOperation op = new ActorOperation(id.Value, id.Name, actor, this.Scheduler);822 IEventQueue eventQueue = new MockEventQueue(actor);823 actor.Configure(this, id, op, eventQueue, eventGroup);824 actor.SetupEventHandlers();825 if (this.Configuration.ReportActivityCoverage)826 {827 actor.ReportActivityCoverage(this.CoverageInfo);828 }829 bool result = this.Scheduler.RegisterOperation(op);830 this.Assert(result, "Actor id '{0}' is used by an existing or previously halted actor.", id.Value);831 if (actor is StateMachine)832 {833 this.LogWriter.LogCreateStateMachine(id, creator?.Id.Name, creator?.Id.Type);834 }835 else836 {837 this.LogWriter.LogCreateActor(id, creator?.Id.Name, creator?.Id.Type);838 }839 return actor;840 }841 /// <inheritdoc/>842 public override void SendEvent(ActorId targetId, Event initialEvent, EventGroup eventGroup = default, SendOptions options = null)843 {844 var senderOp = this.Scheduler.GetExecutingOperation<ActorOperation>();845 this.SendEvent(targetId, initialEvent, senderOp?.Actor, eventGroup, options);846 }847 /// <inheritdoc/>848 public override Task<bool> SendEventAndExecuteAsync(ActorId targetId, Event initialEvent,849 EventGroup eventGroup = null, SendOptions options = null)850 {851 var senderOp = this.Scheduler.GetExecutingOperation<ActorOperation>();852 return this.SendEventAndExecuteAsync(targetId, initialEvent, senderOp?.Actor, eventGroup, options);853 }854 /// <summary>855 /// Sends an asynchronous <see cref="Event"/> to an actor.856 /// </summary>857 internal override void SendEvent(ActorId targetId, Event e, Actor sender, EventGroup eventGroup, SendOptions options)858 {859 if (e is null)860 {861 string message = sender != null ?862 string.Format("{0} is sending a null event.", sender.Id.ToString()) :863 "Cannot send a null event.";864 this.Assert(false, message);865 }866 if (sender != null)867 {868 this.Assert(targetId != null, "{0} is sending event {1} to a null actor.", sender.Id, e);869 }870 else871 {872 this.Assert(targetId != null, "Cannot send event {1} to a null actor.", e);873 }874 this.AssertExpectedCallerActor(sender, "SendEvent");875 EnqueueStatus enqueueStatus = this.EnqueueEvent(targetId, e, sender, eventGroup, options, out Actor target);876 if (enqueueStatus is EnqueueStatus.EventHandlerNotRunning)877 {878 this.RunActorEventHandler(target, null, false, null);879 }880 }881 /// <summary>882 /// Sends an asynchronous <see cref="Event"/> to an actor. Returns immediately if the target was883 /// already running. Otherwise blocks until the target handles the event and reaches quiescense.884 /// </summary>885 internal override async Task<bool> SendEventAndExecuteAsync(ActorId targetId, Event e, Actor sender,886 EventGroup eventGroup, SendOptions options)887 {888 this.Assert(sender is StateMachine, "Only an actor can call 'SendEventAndExecuteAsync': avoid " +889 "calling it directly from the test method; instead call it through a test driver actor.");890 this.Assert(e != null, "{0} is sending a null event.", sender.Id);891 this.Assert(targetId != null, "{0} is sending event {1} to a null actor.", sender.Id, e);892 this.AssertExpectedCallerActor(sender, "SendEventAndExecuteAsync");893 EnqueueStatus enqueueStatus = this.EnqueueEvent(targetId, e, sender, eventGroup, options, out Actor target);894 if (enqueueStatus is EnqueueStatus.EventHandlerNotRunning)895 {896 this.RunActorEventHandler(target, null, false, sender as StateMachine);897 // Wait until the actor reaches quiescence.898 await (sender as StateMachine).ReceiveEventAsync(typeof(QuiescentEvent), rev => (rev as QuiescentEvent).ActorId == targetId);899 return true;900 }901 // EnqueueStatus.EventHandlerNotRunning is not returned by EnqueueEvent902 // (even when the actor was previously inactive) when the event e requires903 // no action by the actor (i.e., it implicitly handles the event).904 return enqueueStatus is EnqueueStatus.Dropped || enqueueStatus is EnqueueStatus.NextEventUnavailable;905 }906 /// <summary>907 /// Enqueues an event to the actor with the specified id.908 /// </summary>909 private EnqueueStatus EnqueueEvent(ActorId targetId, Event e, Actor sender, EventGroup eventGroup,910 SendOptions options, out Actor target)911 {912 target = this.Scheduler.GetOperationWithId<ActorOperation>(targetId.Value)?.Actor;913 this.Assert(target != null,914 "Cannot send event '{0}' to actor id '{1}' that is not bound to an actor instance.",915 e.GetType().FullName, targetId.Value);916 this.Scheduler.ScheduleNextOperation(AsyncOperationType.Send);917 this.ResetProgramCounter(sender as StateMachine);918 // If no group is provided we default to passing along the group from the sender.919 if (eventGroup is null && sender != null)920 {921 eventGroup = sender.EventGroup;922 }923 if (target.IsHalted)924 {925 Guid groupId = eventGroup is null ? Guid.Empty : eventGroup.Id;926 this.LogWriter.LogSendEvent(targetId, sender?.Id.Name, sender?.Id.Type,927 (sender as StateMachine)?.CurrentStateName ?? default, e, groupId, isTargetHalted: true);928 this.Assert(options is null || !options.MustHandle,929 "A must-handle event '{0}' was sent to {1} which has halted.", e.GetType().FullName, targetId);930 this.HandleDroppedEvent(e, targetId);931 return EnqueueStatus.Dropped;932 }933 EnqueueStatus enqueueStatus = this.EnqueueEvent(target, e, sender, eventGroup, options);934 if (enqueueStatus == EnqueueStatus.Dropped)935 {936 this.HandleDroppedEvent(e, targetId);937 }938 return enqueueStatus;939 }940 /// <summary>941 /// Enqueues an event to the actor with the specified id.942 /// </summary>943 private EnqueueStatus EnqueueEvent(Actor actor, Event e, Actor sender, EventGroup eventGroup, SendOptions options)944 {945 EventOriginInfo originInfo;946 string stateName = null;947 if (sender is StateMachine senderStateMachine)948 {949 originInfo = new EventOriginInfo(sender.Id, senderStateMachine.GetType().FullName,950 NameResolver.GetStateNameForLogging(senderStateMachine.CurrentState));951 stateName = senderStateMachine.CurrentStateName;952 }953 else if (sender is Actor senderActor)954 {955 originInfo = new EventOriginInfo(sender.Id, senderActor.GetType().FullName, string.Empty);956 }957 else958 {959 // Message comes from the environment.960 originInfo = new EventOriginInfo(null, "Env", "Env");961 }962 EventInfo eventInfo = new EventInfo(e, originInfo)963 {964 MustHandle = options?.MustHandle ?? false,965 Assert = options?.Assert ?? -1966 };967 Guid opId = eventGroup is null ? Guid.Empty : eventGroup.Id;968 this.LogWriter.LogSendEvent(actor.Id, sender?.Id.Name, sender?.Id.Type, stateName,969 e, opId, isTargetHalted: false);970 return actor.Enqueue(e, eventGroup, eventInfo);971 }972 /// <summary>973 /// Runs a new asynchronous event handler for the specified actor.974 /// This is a fire and forget invocation.975 /// </summary>976 /// <param name="actor">The actor that executes this event handler.</param>977 /// <param name="initialEvent">Optional event for initializing the actor.</param>978 /// <param name="isFresh">If true, then this is a new actor.</param>979 /// <param name="syncCaller">Caller actor that is blocked for quiscence.</param>980 private void RunActorEventHandler(Actor actor, Event initialEvent, bool isFresh, Actor syncCaller)981 {982 var op = actor.Operation;983 Task task = new Task(async () =>984 {985 try986 {987 // Update the current asynchronous control flow with this runtime instance,988 // allowing future retrieval in the same asynchronous call stack.989 CoyoteRuntime.AssignAsyncControlFlowRuntime(this.Runtime);990 this.Scheduler.StartOperation(op);991 if (isFresh)992 {993 await actor.InitializeAsync(initialEvent);994 }995 await actor.RunEventHandlerAsync();996 if (syncCaller != null)997 {998 this.EnqueueEvent(syncCaller, new QuiescentEvent(actor.Id), actor, actor.CurrentEventGroup, null);999 }1000 if (!actor.IsHalted)1001 {1002 this.ResetProgramCounter(actor);1003 }1004 IODebug.WriteLine("<ScheduleDebug> Completed operation {0} on task '{1}'.", actor.Id, Task.CurrentId);1005 op.OnCompleted();1006 // The actor is inactive or halted, schedule the next enabled operation.1007 this.Scheduler.ScheduleNextOperation(AsyncOperationType.Stop);1008 }1009 catch (Exception ex)1010 {1011 this.ProcessUnhandledExceptionInOperation(op, ex);1012 }1013 });1014 task.Start();1015 this.Scheduler.WaitOperationStart(op);1016 }1017 /// <summary>1018 /// Creates a new timer that sends a <see cref="TimerElapsedEvent"/> to its owner actor.1019 /// </summary>1020 internal override IActorTimer CreateActorTimer(TimerInfo info, Actor owner)1021 {...

Full Screen

Full Screen

Actor.cs

Source:Actor.cs Github

copy

Full Screen

...233 /// <summary>234 /// Starts a timer that sends a <see cref="TimerElapsedEvent"/> to this actor after the235 /// specified due time. The timer accepts an optional payload to be used during timeout.236 /// The timer is automatically disposed after it timeouts. To manually stop and dispose237 /// the timer, invoke the <see cref="StopTimer"/> method.238 /// </summary>239 /// <remarks>240 /// See <see href="/coyote/advanced-topics/actors/timers">Using timers in actors</see> for more information.241 /// </remarks>242 /// <param name="startDelay">The amount of time to wait before sending the timeout event.</param>243 /// <param name="customEvent">Optional custom event to raise instead of the default TimerElapsedEvent.</param>244 /// <returns>Handle that contains information about the timer.</returns>245 protected TimerInfo StartTimer(TimeSpan startDelay, TimerElapsedEvent customEvent = null)246 {247 // The specified due time and period must be valid.248 this.Assert(startDelay.TotalMilliseconds >= 0, "{0} registered a timer with a negative due time.", this.Id);249 return this.RegisterTimer(startDelay, Timeout.InfiniteTimeSpan, customEvent);250 }251 /// <summary>252 /// Starts a periodic timer that sends a <see cref="TimerElapsedEvent"/> to this actor after253 /// the specified due time, and then repeats after each specified period. The timer accepts254 /// an optional payload to be used during timeout. The timer can be stopped by invoking the255 /// <see cref="StopTimer"/> method.256 /// </summary>257 /// <remarks>258 /// See <see href="/coyote/advanced-topics/actors/timers">Using timers in actors</see> for more information.259 /// </remarks>260 /// <param name="startDelay">The amount of time to wait before sending the first timeout event.</param>261 /// <param name="period">The time interval between timeout events.</param>262 /// <param name="customEvent">Optional custom event to raise instead of the default TimerElapsedEvent.</param>263 /// <returns>Handle that contains information about the timer.</returns>264 protected TimerInfo StartPeriodicTimer(TimeSpan startDelay, TimeSpan period, TimerElapsedEvent customEvent = null)265 {266 // The specified due time and period must be valid.267 this.Assert(startDelay.TotalMilliseconds >= 0, "{0} registered a periodic timer with a negative due time.", this.Id);268 this.Assert(period.TotalMilliseconds >= 0, "{0} registered a periodic timer with a negative period.", this.Id);269 return this.RegisterTimer(startDelay, period, customEvent);270 }271 /// <summary>272 /// Stops and disposes the specified timer.273 /// </summary>274 /// <remarks>275 /// See <see href="/coyote/advanced-topics/actors/timers">Using timers in actors</see> for more information.276 /// </remarks>277 /// <param name="info">Handle that contains information about the timer.</param>278 protected void StopTimer(TimerInfo info)279 {280 this.Assert(info.OwnerId == this.Id, "{0} is not allowed to dispose timer '{1}', which is owned by {2}.",281 this.Id, info, info.OwnerId);282 this.UnregisterTimer(info);283 }284 /// <summary>285 /// Returns a nondeterministic boolean choice, that can be286 /// controlled during analysis or testing.287 /// </summary>288 /// <returns>The controlled nondeterministic choice.</returns>289 protected bool RandomBoolean() => this.Context.GetNondeterministicBooleanChoice(2, this.Id.Name, this.Id.Type);290 /// <summary>291 /// Returns a nondeterministic boolean choice, that can be292 /// controlled during analysis or testing. The value is used293 /// to generate a number in the range [0..maxValue), where 0294 /// triggers true.295 /// </summary>296 /// <param name="maxValue">The max value.</param>297 /// <returns>The controlled nondeterministic choice.</returns>298 protected bool RandomBoolean(int maxValue) =>299 this.Context.GetNondeterministicBooleanChoice(maxValue, this.Id.Name, this.Id.Type);300 /// <summary>301 /// Returns a nondeterministic integer, that can be controlled during302 /// analysis or testing. The value is used to generate an integer in303 /// the range [0..maxValue).304 /// </summary>305 /// <param name="maxValue">The max value.</param>306 /// <returns>The controlled nondeterministic integer.</returns>307 protected int RandomInteger(int maxValue) =>308 this.Context.GetNondeterministicIntegerChoice(maxValue, this.Id.Name, this.Id.Type);309 /// <summary>310 /// Invokes the specified monitor with the specified <see cref="Event"/>.311 /// </summary>312 /// <typeparam name="T">Type of the monitor.</typeparam>313 /// <param name="e">Event to send to the monitor.</param>314 protected void Monitor<T>(Event e) => this.Monitor(typeof(T), e);315 /// <summary>316 /// Invokes the specified monitor with the specified event.317 /// </summary>318 /// <param name="type">Type of the monitor.</param>319 /// <param name="e">The event to send.</param>320 protected void Monitor(Type type, Event e)321 {322 this.Assert(e != null, "{0} is sending a null event.", this.Id);323 this.Context.InvokeMonitor(type, e, this.Id.Name, this.Id.Type, this.CurrentStateName);324 }325 /// <summary>326 /// Checks if the assertion holds, and if not, throws an <see cref="AssertionFailureException"/> exception.327 /// </summary>328 protected void Assert(bool predicate) => this.Context.Assert(predicate);329 /// <summary>330 /// Checks if the assertion holds, and if not, throws an <see cref="AssertionFailureException"/> exception.331 /// </summary>332 protected void Assert(bool predicate, string s, object arg0) => this.Context.Assert(predicate, s, arg0);333 /// <summary>334 /// Checks if the assertion holds, and if not, throws an <see cref="AssertionFailureException"/> exception.335 /// </summary>336 protected void Assert(bool predicate, string s, object arg0, object arg1) =>337 this.Context.Assert(predicate, s, arg0, arg1);338 /// <summary>339 /// Checks if the assertion holds, and if not, throws an <see cref="AssertionFailureException"/> exception.340 /// </summary>341 protected void Assert(bool predicate, string s, object arg0, object arg1, object arg2) =>342 this.Context.Assert(predicate, s, arg0, arg1, arg2);343 /// <summary>344 /// Checks if the assertion holds, and if not, throws an <see cref="AssertionFailureException"/> exception.345 /// </summary>346 protected void Assert(bool predicate, string s, params object[] args) =>347 this.Context.Assert(predicate, s, args);348 /// <summary>349 /// Raises a <see cref='HaltEvent'/> to halt the actor at the end of the current action.350 /// </summary>351 protected void RaiseHaltEvent()352 {353 this.Assert(this.CurrentStatus is Status.Active, "{0} invoked Halt while halting.", this.Id);354 this.CurrentStatus = Status.Halting;355 }356 /// <summary>357 /// Asynchronous callback that is invoked when the actor is initialized with an optional event.358 /// </summary>359 /// <param name="initialEvent">Optional event used for initialization.</param>360 /// <returns>Task that represents the asynchronous operation.</returns>361 protected virtual Task OnInitializeAsync(Event initialEvent) => Task.CompletedTask;362 /// <summary>363 /// Asynchronous callback that is invoked when the actor successfully dequeues an event from its inbox.364 /// This method is not called when the dequeue happens via a receive statement.365 /// </summary>366 /// <param name="e">The event that was dequeued.</param>367 protected virtual Task OnEventDequeuedAsync(Event e) => Task.CompletedTask;368 /// <summary>369 /// Callback that is invoked when the actor ignores an event and removes it from its inbox.370 /// </summary>371 /// <param name="e">The event that was ignored.</param>372 protected virtual void OnEventIgnored(Event e)373 {374 }375 /// <summary>376 /// Callback that is invoked when the actor defers dequeing an event from its inbox.377 /// </summary>378 /// <param name="e">The event that was deferred.</param>379 protected virtual void OnEventDeferred(Event e)380 {381 }382 /// <summary>383 /// Asynchronous callback that is invoked when the actor finishes handling a dequeued event, unless384 /// the handler of the dequeued event caused the actor to halt (either normally or due to an exception).385 /// The actor will either become idle or dequeue the next event from its inbox.386 /// </summary>387 /// <param name="e">The event that was handled.</param>388 protected virtual Task OnEventHandledAsync(Event e) => Task.CompletedTask;389 /// <summary>390 /// Asynchronous callback that is invoked when the actor receives an event that it is not391 /// prepared to handle. The callback is invoked first, after which the actor will necessarily392 /// throw an <see cref="UnhandledEventException"/>.393 /// </summary>394 /// <param name="e">The event that was unhandled.</param>395 /// <param name="state">The state when the event was dequeued.</param>396 protected virtual Task OnEventUnhandledAsync(Event e, string state) => Task.CompletedTask;397 /// <summary>398 /// Asynchronous callback that is invoked when the actor handles an exception.399 /// </summary>400 /// <param name="ex">The exception thrown by the actor.</param>401 /// <param name="e">The event being handled when the exception was thrown.</param>402 /// <returns>The action that the runtime should take.</returns>403 protected virtual Task OnExceptionHandledAsync(Exception ex, Event e) => Task.CompletedTask;404 /// <summary>405 /// Asynchronous callback that is invoked when the actor halts.406 /// </summary>407 /// <param name="e">The event being handled when the actor halted.</param>408 /// <returns>Task that represents the asynchronous operation.</returns>409 protected virtual Task OnHaltAsync(Event e) => Task.CompletedTask;410 /// <summary>411 /// Enqueues the specified event and its metadata.412 /// </summary>413 internal EnqueueStatus Enqueue(Event e, EventGroup eventGroup, EventInfo info)414 {415 if (this.CurrentStatus is Status.Halted)416 {417 return EnqueueStatus.Dropped;418 }419 return this.Inbox.Enqueue(e, eventGroup, info);420 }421 /// <summary>422 /// Runs the event handler. The handler terminates if there is no next423 /// event to process or if the actor has halted.424 /// </summary>425 internal async Task RunEventHandlerAsync()426 {427 bool isFreshDequeue = true;428 Event lastDequeuedEvent = null;429 while (this.CurrentStatus != Status.Halted && this.Context.IsRunning)430 {431 (DequeueStatus status, Event e, EventGroup eventGroup, EventInfo info) = this.Inbox.Dequeue();432 if (eventGroup != null)433 {434 this.EventGroup = eventGroup;435 }436 if (status is DequeueStatus.Success)437 {438 // Notify the runtime for a new event to handle. This is only used439 // during bug-finding and operation bounding, because the runtime440 // has to schedule an actor when a new operation is dequeued.441 this.Context.LogDequeuedEvent(this, e, info, isFreshDequeue);442 await this.InvokeUserCallbackAsync(UserCallbackType.OnEventDequeued, e);443 lastDequeuedEvent = e;444 }445 else if (status is DequeueStatus.Raised)446 {447 // Only supported by types (e.g. StateMachine) that allow448 // the user to explicitly raise events.449 this.Context.LogHandleRaisedEvent(this, e);450 }451 else if (status is DequeueStatus.Default)452 {453 this.Context.LogWriter.LogDefaultEventHandler(this.Id, this.CurrentStateName);454 // If the default event was dequeued, then notify the runtime.455 // This is only used during bug-finding, because the runtime must456 // instrument a scheduling point between default event handlers.457 this.Context.LogDefaultEventDequeued(this);458 }459 else if (status is DequeueStatus.NotAvailable)460 {461 // Terminate the handler as there is no event available.462 break;463 }464 if (e is TimerElapsedEvent timeoutEvent &&465 timeoutEvent.Info.Period.TotalMilliseconds < 0)466 {467 // If the timer is not periodic, then dispose it.468 this.UnregisterTimer(timeoutEvent.Info);469 }470 if (this.CurrentStatus is Status.Active)471 {472 // Handles the next event, if the actor is not halted.473 await this.HandleEventAsync(e);474 }475 if (!this.Inbox.IsEventRaised && lastDequeuedEvent != null && this.CurrentStatus != Status.Halted)476 {477 // Inform the user that the actor handled the dequeued event.478 await this.InvokeUserCallbackAsync(UserCallbackType.OnEventHandled, lastDequeuedEvent);479 lastDequeuedEvent = null;480 }481 if (this.CurrentStatus is Status.Halting)482 {483 // If the current status is halting, then halt the actor.484 await this.HaltAsync(e);485 }486 isFreshDequeue = false;487 }488 }489 /// <summary>490 /// Handles the specified <see cref="Event"/>.491 /// </summary>492 private protected virtual async Task HandleEventAsync(Event e)493 {494 if (this.ActionMap.TryGetValue(e.GetType(), out CachedDelegate cachedAction) ||495 this.ActionMap.TryGetValue(typeof(WildCardEvent), out cachedAction))496 {497 this.Context.LogInvokedAction(this, cachedAction.MethodInfo, null, null);498 await this.InvokeActionAsync(cachedAction, e);499 }500 else if (e is HaltEvent)501 {502 // If it is the halt event, then change the actor status to halting.503 this.CurrentStatus = Status.Halting;504 }505 else506 {507 await this.InvokeUserCallbackAsync(UserCallbackType.OnEventUnhandled, e);508 if (this.CurrentStatus is Status.Active)509 {510 // If the event cannot be handled then report an error, else halt gracefully.511 var ex = new UnhandledEventException(e, default, "Unhandled Event");512 bool isHalting = this.OnUnhandledEventExceptionHandler(ex, e);513 this.Assert(isHalting, "{0} received event '{1}' that cannot be handled.",514 this.Id, e.GetType().FullName);515 }516 }517 }518 /// <summary>519 /// Invokes the specified action delegate.520 /// </summary>521 private protected async Task InvokeActionAsync(CachedDelegate cachedAction, Event e)522 {523 try524 {525 if (cachedAction.IsAsync)526 {527 Task task = null;528 if (cachedAction.Handler is Func<Event, Task> taskFuncWithEvent)529 {530 task = taskFuncWithEvent(e);531 }532 else if (cachedAction.Handler is Func<Task> taskFunc)533 {534 task = taskFunc();535 }536 this.OnWaitTask(task, cachedAction.MethodInfo.Name);537 await task;538 }539 else if (cachedAction.Handler is Action<Event> actionWithEvent)540 {541 actionWithEvent(e);542 }543 else if (cachedAction.Handler is Action action)544 {545 action();546 }547 }548 catch (Exception ex) when (this.OnExceptionHandler(ex, cachedAction.MethodInfo.Name, e))549 {550 // User handled the exception.551 await this.OnExceptionHandledAsync(ex, e);552 }553 catch (Exception ex) when (!cachedAction.IsAsync && this.InvokeOnFailureExceptionFilter(cachedAction, ex))554 {555 // Use an exception filter to call OnFailure before the stack556 // has been unwound. If the exception filter does not fail-fast,557 // it returns false to process the exception normally.558 }559 catch (Exception ex)560 {561 await this.TryHandleActionInvocationExceptionAsync(ex, cachedAction.MethodInfo.Name);562 }563 }564 /// <summary>565 /// Invokes the specified event handler user callback.566 /// </summary>567 private protected async Task InvokeUserCallbackAsync(string callbackType, Event e, string currentState = default)568 {569 try570 {571 Task task = null;572 if (callbackType is UserCallbackType.OnInitialize)573 {574 task = this.OnInitializeAsync(e);575 }576 else if (callbackType is UserCallbackType.OnEventDequeued)577 {578 task = this.OnEventDequeuedAsync(e);579 }580 else if (callbackType is UserCallbackType.OnEventHandled)581 {582 task = this.OnEventHandledAsync(e);583 }584 else if (callbackType is UserCallbackType.OnEventUnhandled)585 {586 task = this.OnEventUnhandledAsync(e, currentState);587 }588 this.OnWaitTask(task, callbackType);589 await task;590 }591 catch (Exception ex) when (this.OnExceptionHandler(ex, callbackType, e))592 {593 // User handled the exception.594 await this.OnExceptionHandledAsync(ex, e);595 }596 catch (Exception ex)597 {598 // Reports the unhandled exception.599 await this.TryHandleActionInvocationExceptionAsync(ex, callbackType);600 }601 }602 /// <summary>603 /// An exception filter that calls <see cref="CoyoteRuntime.OnFailure"/>,604 /// which can choose to fast-fail the app to get a full dump.605 /// </summary>606 /// <param name="action">The action being executed when the failure occurred.</param>607 /// <param name="ex">The exception being tested.</param>608 private protected bool InvokeOnFailureExceptionFilter(CachedDelegate action, Exception ex)609 {610 // This is called within the exception filter so the stack has not yet been unwound.611 // If the call does not fail-fast, return false to process the exception normally.612 this.Context.RaiseOnFailureEvent(new ActionExceptionFilterException(action.MethodInfo.Name, ex));613 return false;614 }615 /// <summary>616 /// Tries to handle an exception thrown during an action invocation.617 /// </summary>618 private protected Task TryHandleActionInvocationExceptionAsync(Exception ex, string actionName)619 {620 Exception innerException = ex;621 while (innerException is TargetInvocationException)622 {623 innerException = innerException.InnerException;624 }625 if (innerException is AggregateException)626 {627 innerException = innerException.InnerException;628 }629 if (innerException is ExecutionCanceledException || innerException is TaskSchedulerException)630 {631 this.CurrentStatus = Status.Halted;632 Debug.WriteLine($"<Exception> {innerException.GetType().Name} was thrown from {this.Id}.");633 }634 else635 {636 // Reports the unhandled exception.637 this.ReportUnhandledException(innerException, actionName);638 }639 return Task.CompletedTask;640 }641 /// <summary>642 /// Checks if the specified event is ignored.643 /// </summary>644 internal virtual bool IsEventIgnored(Event e) =>645 e is TimerElapsedEvent timeoutEvent && !this.Timers.ContainsKey(timeoutEvent.Info);646 /// <summary>647 /// Checks if the specified event is deferred.648 /// </summary>649 internal virtual bool IsEventDeferred(Event e) => false;650 /// <summary>651 /// Checks if there is a default handler installed.652 /// </summary>653 internal virtual bool IsDefaultHandlerInstalled() => false;654 /// <summary>655 /// Returns the hashed state of this actor.656 /// </summary>657 internal virtual int GetHashedState()658 {659 unchecked660 {661 var hash = 19;662 hash = (hash * 31) + this.GetType().GetHashCode();663 hash = (hash * 31) + this.Id.Value.GetHashCode();664 hash = (hash * 31) + this.IsHalted.GetHashCode();665 hash = (hash * 31) + this.IsEventHandlerRunning.GetHashCode();666 hash = (hash * 31) + this.Context.GetActorProgramCounter(this.Id);667 hash = (hash * 31) + this.Inbox.GetCachedState();668 // Adds the user-defined hashed state.669 hash = (hash * 31) + this.HashedState;670 return hash;671 }672 }673 /// <summary>674 /// Returns the hashed state of this actor.675 /// </summary>676 internal virtual int GetHashedState(string abstractionLevel)677 {678 unchecked679 {680 int hash = 37;681 if (abstractionLevel is "default")682 {683 hash = (hash * 397) + this.GetType().GetHashCode();684 hash = (hash * 397) + this.IsHalted.GetHashCode();685 hash = (hash * 31) + this.Id.Value.GetHashCode();686 hash = (hash * 397) + this.IsEventHandlerRunning.GetHashCode();687 hash = (hash * 397) + this.Context.GetActorProgramCounter(this.Id);688 hash = (hash * 397) + this.Inbox.GetCachedState();689 }690 else if (abstractionLevel is "inboxonly")691 {692 hash = (hash * 397) + this.Inbox.GetCachedState();693 }694 else if (abstractionLevel is "custom")695 {696 hash = (hash * 397) + this.Inbox.GetCachedState();697 if (this.HashedState != 0)698 {699 // Adds the user-defined hashed machine state.700 hash = (hash * 397) + this.HashedState;701 }702 }703 else if (abstractionLevel is "custom-only")704 {705 if (this.HashedState != 0)706 {707 // Adds the user-defined hashed machine state.708 hash = (hash * 397) + this.HashedState;709 }710 }711 return hash;712 }713 }714 /// <summary>715 /// Registers a new timer using the specified configuration.716 /// </summary>717 private protected TimerInfo RegisterTimer(TimeSpan dueTime, TimeSpan period, TimerElapsedEvent customEvent)718 {719 var info = new TimerInfo(this.Id, dueTime, period, customEvent);720 var timer = this.Context.CreateActorTimer(info, this);721 this.Context.LogWriter.LogCreateTimer(info);722 this.Timers.Add(info, timer);723 return info;724 }725 /// <summary>726 /// Unregisters the specified timer.727 /// </summary>728 private protected void UnregisterTimer(TimerInfo info)729 {730 if (!this.Timers.TryGetValue(info, out IActorTimer timer))731 {732 this.Assert(info.OwnerId == this.Id, "Timer '{0}' is already disposed.", info);733 }734 this.Context.LogWriter.LogStopTimer(info);735 this.Timers.Remove(info);736 using (timer)737 {738 // sometimes timer can be null.739 }740 }741 /// <summary>742 /// Extracts user declarations and sets up the event handlers.743 /// </summary>744 internal virtual void SetupEventHandlers()745 {746 if (!ActionCache.ContainsKey(this.GetType()))747 {748 Stack<Type> actorTypes = new Stack<Type>();...

Full Screen

Full Screen

Stop

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Actors;2using Microsoft.Coyote.SystematicTesting;3using System;4using System.Threading.Tasks;5{6 {7 static void Main(string[] args)8 {9 var configuration = Configuration.Create().WithTestingIterations(10000);10 var test = new SystematicTestingEngine(configuration);11 test.RegisterEventHandler(typeof(StartEvent), typeof(StartEventHandler));12 test.RegisterEventHandler(typeof(StopEvent), typeof(StopEventHandler));13 test.RegisterActor(typeof(Actor1));14 test.Run();15 }16 }17 {18 public TaskCompletionSource<bool> tcs;19 public StartEvent(TaskCompletionSource<bool> tcs)20 {21 this.tcs = tcs;22 }23 }24 class StopEvent : Event { }25 {26 protected override Task HandleEventAsync(Event e)27 {28 var startEvent = e as StartEvent;29 var executionContext = this.Runtime.GetActorExecutionContext(this.Actor.Id);30 executionContext.Stop();31 startEvent.tcs.SetResult(true);32 return Task.CompletedTask;33 }34 }35 {36 protected override Task HandleEventAsync(Event e)37 {38 var stopEvent = e as StopEvent;39 var executionContext = this.Runtime.GetActorExecutionContext(this.Actor.Id);40 executionContext.Stop();41 return Task.CompletedTask;42 }43 }44 {45 protected override Task OnInitializeAsync(Event initialEvent)46 {47 this.SendEvent(this.Id, new StartEvent(new TaskCompletionSource<bool>()));48 this.SendEvent(this.Id, new StopEvent());49 return Task.CompletedTask;50 }51 }52}53using Microsoft.Coyote.Actors;54using Microsoft.Coyote.SystematicTesting;55using System;56using System.Threading.Tasks;57{58 {59 static void Main(string[] args)60 {61 var configuration = Configuration.Create().WithTestingIterations(10000);62 var test = new SystematicTestingEngine(configuration);63 test.RegisterEventHandler(typeof(StartEvent), typeof(StartEventHandler));64 test.RegisterEventHandler(typeof(StopEvent), typeof(StopEventHandler));65 test.RegisterActor(typeof(Actor1));66 test.Run();67 }

Full Screen

Full Screen

Stop

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Actors;2using Microsoft.Coyote.Actors.Timers;3using System;4using System.Collections.Generic;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8{9 {10 public static void Main()11 {12 ActorExecutionContext.Stop();13 }14 }15}16using Microsoft.Coyote.Actors;17using Microsoft.Coyote.Actors.Timers;18using System;19using System.Collections.Generic;20using System.Linq;21using System.Text;22using System.Threading.Tasks;23{24 {25 public static void Main()26 {27 ActorRuntime.Stop();28 }29 }30}31using Microsoft.Coyote.Actors;32using Microsoft.Coyote.Actors.Timers;33using System;34using System.Collections.Generic;35using System.Linq;36using System.Text;37using System.Threading.Tasks;38{39 {40 public static void Main()41 {42 Actor.Stop();43 }44 }45}46using Microsoft.Coyote.Actors;47using Microsoft.Coyote.Actors.Timers;48using System;49using System.Collections.Generic;50using System.Linq;51using System.Text;52using System.Threading.Tasks;53{54 {55 public static void Main()56 {57 Actor.Stop();58 }59 }60}61using Microsoft.Coyote.Actors;62using Microsoft.Coyote.Actors.Timers;63using System;64using System.Collections.Generic;65using System.Linq;66using System.Text;67using System.Threading.Tasks;68{69 {70 public static void Main()71 {72 Actor.Stop();73 }74 }75}76using Microsoft.Coyote.Actors;77using Microsoft.Coyote.Actors.Timers;78using System;79using System.Collections.Generic;80using System.Linq;81using System.Text;

Full Screen

Full Screen

Stop

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote.Actors;4using Microsoft.Coyote.Runtime;5{6 {7 static async Task Main(string[] args)8 {9 var runtime = RuntimeFactory.Create();10 runtime.CreateActor(typeof(MyActor));11 await Task.Delay(1000);12 runtime.Stop();13 }14 }15 {16 protected override Task OnInitializeAsync(Event initialEvent)17 {18 Console.WriteLine("Hello World!");19 return Task.CompletedTask;20 }21 }22}23using System;24using System.Threading.Tasks;25using Microsoft.Coyote.Actors;26using Microsoft.Coyote.Runtime;27{28 {29 static async Task Main(string[] args)30 {31 var runtime = RuntimeFactory.Create();32 runtime.CreateActor(typeof(MyActor));33 await Task.Delay(1000);34 runtime.Stop();35 }36 }37 {38 protected override Task OnInitializeAsync(Event initialEvent)39 {40 Console.WriteLine("Hello World!");41 return Task.CompletedTask;42 }43 }44}45using System;46using System.Threading.Tasks;47using Microsoft.Coyote.Actors;48using Microsoft.Coyote.Runtime;49{50 {51 static async Task Main(string[] args)52 {53 var runtime = RuntimeFactory.Create();54 runtime.CreateActor(typeof(MyActor));55 await Task.Delay(1000);56 runtime.Stop();57 }58 }59 {60 protected override Task OnInitializeAsync(Event initialEvent)61 {62 Console.WriteLine("Hello World!");63 return Task.CompletedTask;64 }65 }66}67using System;68using System.Threading.Tasks;69using Microsoft.Coyote.Actors;70using Microsoft.Coyote.Runtime;71{72 {73 static async Task Main(string[] args)74 {75 var runtime = RuntimeFactory.Create();76 runtime.CreateActor(typeof(MyActor));77 await Task.Delay(1000);

Full Screen

Full Screen

Stop

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Coyote;4using Microsoft.Coyote.Actors;5using Microsoft.Coyote.Specifications;6using Microsoft.Coyote.Tasks;7{8 {9 static void Main(string[] args)10 {11 using (var runtime = RuntimeFactory.Create())12 {13 runtime.CreateActor(typeof(Actor1));14 runtime.SendEvent(new Event1());15 Task.Delay(5000).Wait();16 runtime.Stop();17 }18 }19 }20 {21 }22 {23 [OnEventDoAction(typeof(Event1), nameof(HandleEvent1))]24 {25 }26 void HandleEvent1()27 {28 Task.Delay(5000).Wait();29 }30 }31}32using System;33using System.Threading.Tasks;34using Microsoft.Coyote;35using Microsoft.Coyote.Actors;36using Microsoft.Coyote.Specifications;37using Microsoft.Coyote.Tasks;38{39 {40 static void Main(string[] args)41 {42 using (var runtime = RuntimeFactory.Create())43 {44 runtime.CreateActor(typeof(Actor1));45 runtime.SendEvent(new Event1());46 Task.Delay(5000).Wait();47 runtime.Stop();48 }49 }50 }51 {52 }53 {54 [OnEventDoAction(typeof(Event1), nameof(HandleEvent1))]55 {56 }57 void HandleEvent1()58 {59 Task.Delay(5000

Full Screen

Full Screen

Stop

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Actors;2using Microsoft.Coyote.Specifications;3using Microsoft.Coyote.Tasks;4using System;5using System.Threading.Tasks;6{7 {8 static void Main(string[] args)9 {10 Task task = Task.Run(async () =>11 {12 await Run();13 });14 task.Wait();15 }16 static async Task Run()17 {18 var config = Configuration.Create();19 var runtime = RuntimeFactory.Create(config);20 var actor = runtime.CreateActor(typeof(MyActor));21 runtime.SendEvent(actor, new Event1());22 runtime.SendEvent(actor, new Event2());23 runtime.SendEvent(actor, new Event3());24 runtime.SendEvent(actor, new Event4());25 await Task.Delay(1000);26 runtime.Stop();27 }28 }29 {30 [OnEventDoAction(typeof(Event1), nameof(DoAction1))]31 [OnEventDoAction(typeof(Event2), nameof(DoAction2))]32 [OnEventDoAction(typeof(Event3), nameof(DoAction3))]33 [OnEventDoAction(typeof(Event4), nameof(DoAction4))]34 [OnEventDoAction(typeof(Event5), nameof(DoAction5))]35 [OnEventDoAction(typeof(Event6), nameof(DoAction6))]36 [OnEventDoAction(typeof(Event7), nameof(DoAction7))]37 [OnEventDoAction(typeof(Event8), nameof(DoAction8))]38 [OnEventDoAction(typeof(Event9), nameof(DoAction9))]39 [OnEventDoAction(typeof(Event10), nameof(DoAction10))]40 [OnEventDoAction(typeof(Event11), nameof(DoAction11))]41 [OnEventDoAction(typeof(Event12), nameof(DoAction12))]42 [OnEventDoAction(typeof(Event13), nameof(DoAction13))]43 [OnEventDoAction(typeof(Event14), nameof(DoAction14))]44 [OnEventDoAction(typeof(Event15), nameof(DoAction15))]45 [OnEventDoAction(typeof(Event16), nameof(DoAction16))]46 [OnEventDoAction(typeof(Event17), nameof(DoAction17))]47 [OnEventDoAction(typeof(Event18), nameof(DoAction18))]48 [OnEventDoAction(typeof(Event19), nameof(DoAction19))]49 [OnEventDoAction(typeof(Event20), nameof(Do

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful