private ReactInstanceManager(
            string jsBundleFile,
            string jsMainModuleName,
            IReadOnlyList<IReactPackage> packages,
            bool useDeveloperSupport,
            LifecycleState initialLifecycleState,
            UIImplementationProvider uiImplementationProvider,
            Action<Exception> nativeModuleCallExceptionHandler)
        {
            if (packages == null)
                throw new ArgumentNullException(nameof(packages));
            if (uiImplementationProvider == null)
                throw new ArgumentNullException(nameof(uiImplementationProvider));

            _jsBundleFile = jsBundleFile;
            _jsMainModuleName = jsMainModuleName;
            _packages = packages;

            _useDeveloperSupport = useDeveloperSupport;
            _devSupportManager = _useDeveloperSupport
                ? (IDevSupportManager)new DevSupportManager(
                    new ReactInstanceDevCommandsHandler(this),
                    _jsBundleFile,
                    _jsMainModuleName)
                : new DisabledDevSupportManager();

            _lifecycleState = initialLifecycleState;
            _uiImplementationProvider = uiImplementationProvider;
            _nativeModuleCallExceptionHandler = nativeModuleCallExceptionHandler;
        }
Пример #2
0
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                Utils.SafeExecute(() => this.runtimeClient.Dispose());
                this.state = LifecycleState.Disposed;
            }

            GC.SuppressFinalize(this);
        }
        void RunSystem()
        {
            if (state != LifecycleState.StartingUp)
            {
                throw new Exception("Invalid lifecycle state");
            }

            state = LifecycleState.Running;
            Builder.cruise.OnExiting += new CoordinatorCruise.ExitingHandler(ShutDownSystem);
            Builder.cruise.Run(); // app exits when this call completes
        }
Пример #4
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="cause">TBD</param>
        /// <param name="message">TBD</param>
        public override void AroundPostRestart(Exception cause, object message)
        {
            var s = _state.Remove(Self);
            if (s != null)
            {
                _subscriber = UntypedSubscriber.ToTyped<T>(s.Subscriber);
                _demand = s.Demand;
                _lifecycleState = s.LifecycleState;
            }

            base.AroundPostRestart(cause, message);
        }
 /// <summary>
 /// Internally stops service.
 /// </summary>
 /// <returns>A task representing stopping procedure.</returns>
 private async Task StopInternal()
 {
     try
     {
         this.LifecycleState = LifecycleState.Stopping;
         await this.DoStop();
     }
     finally
     {
         this.LifecycleState = LifecycleState.Stopped;
     }
 }
        /*============================================================================*/
        /* Internal Functions                                                         */
        /*============================================================================*/

        internal void SetCurrentState(LifecycleState state)
        {
            if (_state == state)
            {
                return;
            }
            _state = state;
            if (_STATE_CHANGE != null)
            {
                _STATE_CHANGE();
            }
        }
Пример #7
0
        public void beforeHandlerError_reverts_state()
        {
            LifecycleState expected = lifecycle.state;

            lifecycle.ERROR += delegate(Exception error){
            };
            transition.FromStates(LifecycleState.UNINITIALIZED)
            .ToStates(LifecycleState.INITIALIZING, LifecycleState.ACTIVE)
            .AddBeforeHandler(delegate(object message, HandlerAsyncCallback callback) {
                callback("There was a problem");
            }).Enter();
            Assert.That(lifecycle.state, Is.EqualTo(expected));
        }
Пример #8
0
        public void On(LifecycleState state, Func <Task> action)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            if (CurrentState >= state)
            {
                throw new InvalidOperationException();
            }

            pipeline[state].Enqueue(action);
        }
Пример #9
0
 private void MoveToBackgroundLifecycleState()
 {
     lock (_lifecycleStateLock)
     {
         if (_currentReactContext != null)
         {
             if (_lifecycleState == LifecycleState.Resumed)
             {
                 _currentReactContext.OnEnteredBackground();
                 _lifecycleState = LifecycleState.Background;
             }
         }
     }
 }
 private static EventTestCase Success(
     LifecycleState initialState,
     TriggerEvent trigger,
     LifecycleState expectedAfterTransition,
     params IEvent[] expectedHandlerExecutions
     )
 {
     return(new SuccessCase {
         InitialState = initialState,
         Trigger = trigger,
         ExpectedStateAfterTransition = expectedAfterTransition,
         ExpectedHandlerExecutions = expectedHandlerExecutions
     });
 }
            protected void SetLifecycleStateTo(LifecycleState state)
            {
                var operations = new ScreenLifecycleOperations(Aggregator, Screen);

                if (state == LifecycleState.Created)
                {
                    return;
                }

                operations.Initialize();

                if (state == LifecycleState.Initialized)
                {
                    return;
                }

                operations.Activate();

                if (state == LifecycleState.Activated)
                {
                    return;
                }

                operations.Deactivate();

                if (state == LifecycleState.Deactivated)
                {
                    return;
                }

                operations.Close();

                if (state == LifecycleState.Closed)
                {
                    return;
                }

                if (state == LifecycleState.ExceptionOccured)
                {
                    Aggregator.Publish(
                        ScreenEvents.LifecycleExceptionOccured,
                        new ScreenEventArgs(Screen)
                        );
                }
                else
                {
                    throw new NotSupportedException();
                }
            }
Пример #12
0
        /// <summary>
        /// Creation of the View object
        /// </summary>
        public virtual void onCreate(ScreenInfo screenInfo)
        {
            State = LifecycleState.CREATE;

            Debug.WriteLine("Creating the view : " + screenInfo.Name);

            if (screenInfo != null)
            {
                this.ScreenInfo = screenInfo;
            }
            else
            {
                throw new Exception();
            }
        }
Пример #13
0
        private void DefineTransition <TArgs>(
            LifecycleState from,
            LifecycleState to,
            ScreenLifecycleEvent <TArgs> on,
            Action <EventPublication> action,
            Func <EventPublication, bool> condition = null
            ) where TArgs : ScreenEventArgs
        {
            condition = condition ?? AlwaysTrueCondition;

            Func <EventPublication, bool> c = on != null ?
                                              pub => pub.Event == on && condition(pub) :
                                              condition;

            _sm.DefineTransition(from, to, c, action);
        }
Пример #14
0
        private async Task Stop(bool gracefully)
        {
            if (this.IsDisposing)
            {
                return;
            }
            this.applicationLifetime?.StopApplication();
            using (await this.initLock.LockAsync().ConfigureAwait(false))
            {
                if (this.state == LifecycleState.Disposed)
                {
                    return;
                }
                try
                {
                    this.state = LifecycleState.Disposing;
                    CancellationToken canceled = CancellationToken.None;
                    if (!gracefully)
                    {
                        var cts = new CancellationTokenSource();
                        cts.Cancel();
                        canceled = cts.Token;
                    }

                    await this.clusterClientLifecycle.OnStop(canceled);

                    if (gracefully)
                    {
                        Utils.SafeExecute(() => (this.runtimeClient as OutsideRuntimeClient)?.Disconnect());
                    }

                    Utils.SafeExecute(() => (this.runtimeClient as OutsideRuntimeClient)?.Reset(gracefully));
                    this.Dispose(true);
                }
                finally
                {
                    // If disposal failed, the system is in an invalid state.
                    if (this.state == LifecycleState.Disposing)
                    {
                        this.state = LifecycleState.Invalid;
                    }
                }
            }

            this.applicationLifetime?.NotifyStopped();
        }
Пример #15
0
        /// <inheritdoc />
        public async Task Connect()
        {
            this.ThrowIfDisposedOrAlreadyInitialized();
            using (await this.initLock.LockAsync().ConfigureAwait(false))
            {
                this.ThrowIfDisposedOrAlreadyInitialized();
                if (this.state == LifecycleState.Starting)
                {
                    throw new InvalidOperationException("A prior connection attempt failed. This instance must be disposed.");
                }

                this.state = LifecycleState.Starting;
                await this.runtimeClient.Start().ConfigureAwait(false);

                this.state = LifecycleState.Started;
            }
        }
        private void SetLifecycleStateAccordingTo(LifecycleEvent lifecycleEvent)
        {
            switch (lifecycleEvent)
            {
            case LifecycleEvent.ViewDidLoad:
                CurrentState = LifecycleState.Loaded;
                break;

            case LifecycleEvent.ViewDidAppear:
                CurrentState = LifecycleState.Appeared;
                break;

            case LifecycleEvent.ViewDidDisappear:
                CurrentState = LifecycleState.Disappeared;
                break;
            }
        }
        private void MoveToResumedLifecycleState(bool force)
        {
            lock (_lifecycleStateLock)
            {
                if (_currentReactContext != null)
                {
                    // We currently don't have an OnCreate callback so we call OnResume for both transitions
                    if (force ||
                        _lifecycleState == LifecycleState.BeforeResume ||
                        _lifecycleState == LifecycleState.BeforeCreate)
                    {
                        _currentReactContext.OnResume();
                    }
                }

                _lifecycleState = LifecycleState.Resumed;
            }
        }
Пример #18
0
        /// <inheritdoc />
        void IDisposable.Dispose()
        {
            if (this.IsDisposing)
            {
                return;
            }

            this.AbortAsync().GetAwaiter().GetResult();

            // Only dispose the service container if this client owns the application lifetime.
            // If the lifetime isn't owned by this client, then the owner is responsible for disposing the container.
            if (this.applicationLifetime is object)
            {
                (this.ServiceProvider as IDisposable)?.Dispose();
            }

            this.state = LifecycleState.Disposed;
        }
Пример #19
0
 private void MoveToBeforeCreateLifecycleState()
 {
     lock (_lifecycleStateLock)
     {
         if (_currentReactContext != null)
         {
             if (_lifecycleState == LifecycleState.Resumed)
             {
                 _currentReactContext.OnSuspend();
                 _lifecycleState = LifecycleState.BeforeResume;
             }
             if (_lifecycleState == LifecycleState.BeforeResume)
             {
                 _currentReactContext.OnDestroy();
             }
         }
     }
 }
        internal ReactInstanceManager(
            string jsBundleFile,
            string jsMainModuleName,
            IReadOnlyList <IReactPackage> packages,
            bool useDeveloperSupport,
            LifecycleState initialLifecycleState,
            UIImplementationProvider uiImplementationProvider,
            Func <IJavaScriptExecutor> javaScriptExecutorFactory,
            Action <Exception> nativeModuleCallExceptionHandler,
            bool lazyViewManagersEnabled)
        {
            RnLog.Info(ReactConstants.RNW, $"ReactInstanceManager: constructor");

            if (packages == null)
            {
                throw new ArgumentNullException(nameof(packages));
            }
            if (uiImplementationProvider == null)
            {
                throw new ArgumentNullException(nameof(uiImplementationProvider));
            }
            if (javaScriptExecutorFactory == null)
            {
                throw new ArgumentNullException(nameof(javaScriptExecutorFactory));
            }

            _jsBundleFile     = jsBundleFile;
            _jsMainModuleName = jsMainModuleName;
            _packages         = packages;

            _useDeveloperSupport = useDeveloperSupport;
            _devSupportManager   = _useDeveloperSupport
                ? (IDevSupportManager) new DevSupportManager(
                new ReactInstanceDevCommandsHandler(this),
                _jsBundleFile == null,
                _jsMainModuleName)
                : new DisabledDevSupportManager();

            _lifecycleStateMachine            = new LifecycleStateMachine(initialLifecycleState);
            _uiImplementationProvider         = uiImplementationProvider;
            _javaScriptExecutorFactory        = javaScriptExecutorFactory;
            _nativeModuleCallExceptionHandler = nativeModuleCallExceptionHandler;
            _lazyViewManagersEnabled          = lazyViewManagersEnabled;
        }
        /// <summary>
        /// Starts this instance of a service.
        /// </summary>
        /// <returns>A task representing starting procedure.</returns>
        public virtual async Task Start()
        {
            if (this.LifecycleState == LifecycleState.Started)
            {
                return;
            }

            await this._semaphore.WaitAsync();

            if (this.LifecycleState == LifecycleState.Started)
            {
                return;
            }

            this.LifecycleState = LifecycleState.Starting;

            try
            {
                await this.DoStart();

                this.LifecycleState = LifecycleState.Started;
            }
            catch (Exception startException)
            {
                if (this.ShouldStopOn(startException))
                {
                    try
                    {
                        await this.StopInternal();
                    }
                    catch (Exception stopException)
                    {
                        throw new AggregateException(startException, stopException);
                    }
                }

                throw;
            }
            finally
            {
                this._semaphore.Release();
            }
        }
        /// <summary>
        /// Called when the application is suspended.
        /// </summary>
        public void OnSuspend()
        {
            DispatcherHelpers.AssertOnDispatcher();

            _lifecycleState           = LifecycleState.BeforeResume;
            _defaultBackButtonHandler = null;

            if (_useDeveloperSupport)
            {
                _devSupportManager.IsEnabled = false;
            }

            var currentReactContext = _currentReactContext;

            if (currentReactContext != null)
            {
                _currentReactContext.OnSuspend();
            }
        }
Пример #23
0
        private void MoveToBackgroundLifecycleState()
        {
            lock (_lifecycleStateLock)
            {
                if (_currentReactContext != null)
                {
                    if (_lifecycleState == LifecycleState.Foreground)
                    {
                        _currentReactContext.OnEnteredBackground();
                    }
                    else if (_lifecycleState == LifecycleState.Suspended ||
                             _lifecycleState == LifecycleState.BeforeCreate)
                    {
                        _currentReactContext.OnResume();
                    }
                }

                _lifecycleState = LifecycleState.Background;
            }
        }
Пример #24
0
        /// <inheritdoc />
        public async Task Connect(Func <Exception, Task <bool> > retryFilter = null)
        {
            this.ThrowIfDisposedOrAlreadyInitialized();
            using (await this.initLock.LockAsync().ConfigureAwait(false))
            {
                this.ThrowIfDisposedOrAlreadyInitialized();
                if (this.state == LifecycleState.Starting)
                {
                    throw new InvalidOperationException("A prior connection attempt failed. This instance must be disposed.");
                }

                this.state = LifecycleState.Starting;
                if (this.runtimeClient is OutsideRuntimeClient orc)
                {
                    await orc.Start(retryFilter).ConfigureAwait(false);
                }
                await this.clusterClientLifecycle.OnStart().ConfigureAwait(false);

                this.state = LifecycleState.Started;
            }
        }
        private ReactInstanceManager(
            string jsBundleFile,
            string jsMainModuleName,
            IReadOnlyList <IReactPackage> packages,
            bool useDeveloperSupport,
            LifecycleState initialLifecycleState,
            UIImplementationProvider uiImplementationProvider,
            Func <IJavaScriptExecutor> javaScriptExecutorFactory,
            Action <Exception> nativeModuleCallExceptionHandler)
        {
            if (packages == null)
            {
                throw new ArgumentNullException(nameof(packages));
            }
            if (uiImplementationProvider == null)
            {
                throw new ArgumentNullException(nameof(uiImplementationProvider));
            }
            if (javaScriptExecutorFactory == null)
            {
                throw new ArgumentNullException(nameof(javaScriptExecutorFactory));
            }

            _jsBundleFile     = jsBundleFile;
            _jsMainModuleName = jsMainModuleName;
            _packages         = packages;

            _useDeveloperSupport = useDeveloperSupport;
            _devSupportManager   = _useDeveloperSupport
                ? (IDevSupportManager) new DevSupportManager(
                new ReactInstanceDevCommandsHandler(this),
                _jsBundleFile,
                _jsMainModuleName)
                : new DisabledDevSupportManager();

            _lifecycleState                   = initialLifecycleState;
            _uiImplementationProvider         = uiImplementationProvider;
            _javaScriptExecutorFactory        = javaScriptExecutorFactory;
            _nativeModuleCallExceptionHandler = nativeModuleCallExceptionHandler;
        }
Пример #26
0
        private void MoveToForegroundLifecycleState()
        {
            lock (_lifecycleStateLock)
            {
                if (_currentReactContext != null)
                {
                    // We currently don't have an OnCreate callback so we call OnResume for both transitions
                    if (_lifecycleState == LifecycleState.Suspended ||
                        _lifecycleState == LifecycleState.BeforeCreate)
                    {
                        _currentReactContext.OnResume();
                        _currentReactContext.OnLeavingBackground();
                    }
                    else if (_lifecycleState == LifecycleState.Background)
                    {
                        _currentReactContext.OnLeavingBackground();
                    }
                }

                _lifecycleState = LifecycleState.Foreground;
            }
        }
Пример #27
0
 /// <summary>
 /// <para>
 /// Complete the stream. After that you are not allowed to
 /// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>.
 /// </para>
 /// <para>
 /// After signalling completion the Actor will then stop itself as it has completed the protocol.
 /// When <see cref="OnComplete"/> is called before any <see cref="ISubscriber{T}"/> has had the chance to subscribe
 /// to this <see cref="ActorPublisher{T}"/> the completion signal (and therefore stopping of the Actor as well)
 /// will be delayed until such <see cref="ISubscriber{T}"/> arrives.
 /// </para>
 /// </summary>
 public void OnCompleteThenStop()
 {
     switch (_lifecycleState)
     {
         case LifecycleState.Active:
         case LifecycleState.PreSubscriber:
             _lifecycleState = LifecycleState.CompleteThenStop;
             _onError = null;
             if (_subscriber != null)
             {
                 // otherwise onComplete will be called when the subscription arrives
                 try
                 {
                     ReactiveStreamsCompliance.TryOnComplete(_subscriber);
                 }
                 finally
                 {
                     Context.Stop(Self);
                 }
             }
             break;
         default: OnComplete(); break;
     }
 }
Пример #28
0
 public LifecycleEvent(LifecycleState state)
 {
     _state = state;
 }
		/*============================================================================*/
		/* Internal Functions                                                         */
		/*============================================================================*/

		internal void SetCurrentState(LifecycleState state)
		{
			if (_state == state)
				return;
			_state = state;
			if (_STATE_CHANGE != null)
				_STATE_CHANGE ();
		}
		/**
		 * The states that this transition applies
		 * @param transitionState The state that the target is put into during the transition
		 * @param finalState The state that the target is put into after the transition
		 * @return
		 */
		public LifecycleTransition ToStates(LifecycleState transitionState, LifecycleState finalState)
		{
			_transitionState = transitionState;
			_finalState = finalState;
			return this;
		}
		private void SetState(LifecycleState state)
		{
//			state && _lifecycle.SetCurrentState(state);
			_lifecycle.SetCurrentState(state);
		}
        /// <summary>
        /// Called when the application is suspended.
        /// </summary>
        public void OnSuspend()
        {
            DispatcherHelpers.AssertOnDispatcher();

            _lifecycleState = LifecycleState.BeforeResume;
            _defaultBackButtonHandler = null;

            if (_useDeveloperSupport)
            {
                _devSupportManager.IsEnabled = false;
            }

            var currentReactContext = _currentReactContext;
            if (currentReactContext != null)
            {
                _currentReactContext.OnSuspend();
            }
        }
 void StartupSystem()
 {
     state = LifecycleState.StartingUp;
     Builder.startup.Run();
 }
Пример #34
0
 /// <summary>
 /// TBD
 /// </summary>
 /// <param name="subscriber">TBD</param>
 /// <param name="demand">TBD</param>
 /// <param name="lifecycleState">TBD</param>
 public State(IUntypedSubscriber subscriber, long demand, LifecycleState lifecycleState)
 {
     Subscriber     = subscriber;
     Demand         = demand;
     LifecycleState = lifecycleState;
 }
Пример #35
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="receive">TBD</param>
        /// <param name="message">TBD</param>
        /// <returns>TBD</returns>
        protected internal override bool AroundReceive(Receive receive, object message)
        {
            if (message is Request)
            {
                var req = (Request)message;
                if (req.IsProcessed)
                {
                    // it's an unstashed Request, demand is already handled
                    base.AroundReceive(receive, req);
                }
                else
                {
                    if (req.Count < 1)
                    {
                        if (_lifecycleState == LifecycleState.Active)
                        {
                            OnError(new ArgumentException("Number of requested elements must be positive. Rule 3.9"));
                        }
                    }
                    else
                    {
                        _demand += req.Count;
                        if (_demand < 0)
                        {
                            _demand = long.MaxValue; // long overflow: effectively unbounded
                        }
                        req.MarkProcessed();
                        base.AroundReceive(receive, message);
                    }
                }
            }
            else if (message is Subscribe <T> )
            {
                var sub        = (Subscribe <T>)message;
                var subscriber = sub.Subscriber;
                switch (_lifecycleState)
                {
                case LifecycleState.PreSubscriber:
                    _scheduledSubscriptionTimeout.Cancel();
                    _subscriber     = subscriber;
                    _lifecycleState = LifecycleState.Active;
                    ReactiveStreamsCompliance.TryOnSubscribe(subscriber, new ActorPublisherSubscription(Self));
                    break;

                case LifecycleState.ErrorEmitted:
                    if (_onError.Stop)
                    {
                        Context.Stop(Self);
                    }
                    ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance);
                    ReactiveStreamsCompliance.TryOnError(subscriber, _onError.Cause);
                    break;

                case LifecycleState.Completed:
                    ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance);
                    ReactiveStreamsCompliance.TryOnComplete(subscriber);
                    break;

                case LifecycleState.CompleteThenStop:
                    Context.Stop(Self);
                    ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance);
                    ReactiveStreamsCompliance.TryOnComplete(subscriber);
                    break;

                case LifecycleState.Active:
                case LifecycleState.Canceled:
                    if (_subscriber == subscriber)
                    {
                        ReactiveStreamsCompliance.RejectDuplicateSubscriber(subscriber);
                    }
                    else
                    {
                        ReactiveStreamsCompliance.RejectAdditionalSubscriber(subscriber, "ActorPublisher");
                    }
                    break;
                }
            }
            else if (message is Cancel)
            {
                if (_lifecycleState != LifecycleState.Canceled)
                {
                    // possible to receive again in case of stash
                    CancelSelf();
                    base.AroundReceive(receive, message);
                }
            }
            else if (message is SubscriptionTimeoutExceeded)
            {
                if (!_scheduledSubscriptionTimeout.IsCancellationRequested)
                {
                    CancelSelf();
                    base.AroundReceive(receive, message);
                }
            }
            else
            {
                return(base.AroundReceive(receive, message));
            }
            return(true);
        }
 public LifecycleEvent(LifecycleState state)
 {
     _state = state;
 }
        /// <summary>
        /// Used when the application resumes to reset the back button handling
        /// in JavaScript.
        /// </summary>
        /// <param name="onBackPressed">
        /// The action to take when back is pressed.
        /// </param>
        public void OnResume(Action onBackPressed)
        {
            if (onBackPressed == null)
                throw new ArgumentNullException(nameof(onBackPressed));

            DispatcherHelpers.AssertOnDispatcher();

            _lifecycleState = LifecycleState.Resumed;

            _defaultBackButtonHandler = onBackPressed;

            if (_useDeveloperSupport)
            {
                _devSupportManager.IsEnabled = true;
            }

            var currentReactContext = _currentReactContext;
            if (currentReactContext != null)
            {
                currentReactContext.OnResume();
            }
        }
 public LifecycleEvent(LifecycleState state)
 {
     this.state = state;
 }