Example #1
0
        public ScheduledOperation Schedule(TimeSpan interval, Fiber fiber, Action operation)
        {
            var scheduled = new ScheduledOperationExecuterImpl(GetScheduledTime(interval), fiber, operation);
            Schedule(scheduled);

            return scheduled;
        }
Example #2
0
		protected TestInstance()
		{
			_fiber = new SynchronousFiber();

			UpdateValueChannel = new ConsumerChannel<UpdateValue>(_fiber, HandleUpdateValue);
			PreviousValues = new List<PreviousValue>();
		}
        /// <summary>
        /// Creates a PollingFileSystemEventProducer
        /// </summary>		
        /// <param name="directory">The directory to watch</param>
        /// <param name="channel">The channel where events should be sent</param>
        /// <param name="scheduler">Event scheduler</param>
        /// <param name="fiber">Fiber to schedule on</param>
        /// <param name="checkInterval">The maximal time between events or polls on a given file</param>
        /// <param name="checkSubDirectory">Indicates if subdirectorys will be checked or ignored</param>
        public PollingFileSystemEventProducer(string directory, UntypedChannel channel, [NotNull] Scheduler scheduler, Fiber fiber,
            TimeSpan checkInterval, bool checkSubDirectory)
        {
            if (scheduler == null)
                throw new ArgumentNullException("scheduler");

            _directory = directory;
            _channel = channel;
            _fiber = fiber;
            _hashes = new Dictionary<string, Guid>();
            _scheduler = scheduler;
            _checkInterval = checkInterval;

            _scheduledAction = scheduler.Schedule(3.Seconds(), _fiber, HashFileSystem);

            var myChannel = new ChannelAdapter();

            _connection = myChannel.Connect(connectionConfigurator =>
                {
                    connectionConfigurator.AddConsumerOf<FileSystemChanged>().UsingConsumer(HandleFileSystemChangedAndCreated);
                    connectionConfigurator.AddConsumerOf<FileSystemCreated>().UsingConsumer(HandleFileSystemChangedAndCreated);
                    connectionConfigurator.AddConsumerOf<FileSystemRenamed>().UsingConsumer(HandleFileSystemRenamed);
                    connectionConfigurator.AddConsumerOf<FileSystemDeleted>().UsingConsumer(HandleFileSystemDeleted);
                });

            _fileSystemEventProducer = new FileSystemEventProducer(directory, myChannel, checkSubDirectory);
        }
Example #4
0
		public void Adding_a_request_message()
		{
			_fiber = new SynchronousFiber();
			_engine = new DynamicRoutingEngine(_fiber);

			_engine.Request(new A(), new ShuntChannel());
		}
		public PeerSubscriptionCache(Fiber fiber, Scheduler scheduler, SubscriptionObserver observer)
		{
			_observer = observer;
			_fiber = fiber;
			_scheduler = scheduler;
			_endpoints = new Dictionary<Uri, EndpointSubscriptionCache>();
		}
Example #6
0
			public MyConsumer(Fiber fiber)
			{
				_fiber = fiber;

				Called = new Stact.Future<MyCommand>();
				CommandChannel = new ConsumerChannel<MyCommand>(_fiber, HandleMyCommand);
			}
		public EndpointSubscriptionCache(Fiber fiber, Scheduler scheduler, SubscriptionObserver observer)
		{
			_fiber = fiber;
			_scheduler = scheduler;
			_observer = observer;
			_messageSubscriptions = new Dictionary<string, EndpointSubscription>();
		}
 internal override CodeBase Fiber(Fiber visitedObject)
 {
     var data = visitedObject.FiberItems;
     var newItems = new FiberItem[data.Length];
     var index = data.Length - 1;
     newItems[index] = data[index].Visit(this);
     return Fiber(visitedObject, null, newItems);
 }
 public EndpointSubscriptionCache(Fiber fiber, Scheduler scheduler, SubscriptionObserver observer)
 {
     _fiber = fiber;
     _scheduler = scheduler;
     _observer = observer;
     _messageSubscriptions =
         new DictionaryCache<SubscriptionKey, EndpointSubscription>(
             key => new EndpointSubscription(_fiber, _scheduler, key.MessageName, key.CorrelationId, _observer));
 }
Example #10
0
		public Auction(Fiber fiber, Inbox inbox, Guid id)
		{
			Id = id;
			_inbox = inbox;
			_fiber = fiber;

			AskChannel = new SelectiveConsumerChannel<Request<Ask>>(_fiber, HandleAsk);
			EndChannel = new ConsumerChannel<End>(_fiber, x => { _ended = true; });
		}
Example #11
0
		public Auction(Inbox inbox, Fiber fiber, Scheduler scheduler)
		{
			_currentBid = 1.00m;

			scheduler.Schedule(60000, fiber, () =>
			{
				inbox.Send(new EndAuction());
			});

			inbox.Loop(loop =>
			{
				loop.Receive<Request<AuctionStatus>>(request =>
				{
					request.Respond(new AuctionStatusImpl
					{
						CurrentBid = _currentBid,
						IsOpen = _open,
					});
				});

				loop.Receive<Request<PlaceBid>>(request =>
				{
					if (request.Body.MaximumBid <= _currentBid)
					{
						request.Respond(new OutBidImpl
						{
							CurrentBid = _currentBid
						});
					}
					else
					{
						_currentBid = request.Body.MaximumBid;
						request.Respond(new BidAcceptedImpl
						{
							CurrentBid = _currentBid
						});
						if (_highBidder != null)
						{
							_highBidder.Send(new OutBidImpl
							{
								CurrentBid = _currentBid
							});
						}
						_highBidder = request.ResponseChannel;
					}

					loop.Continue();
				});

				loop.Receive<EndAuction>(msg =>
				{
					_open = false;
//					_highBidder.Send(new YouWin());
				});
			});
		}
        public BusSubscriptionRepository(Uri busUri, SubscriptionStorage storage)
        {
            string uri = busUri.AbsoluteUri;
            if (busUri.Query.Length > 0)
                uri = uri.Replace(busUri.Query, "");

            _busUri = new Uri(uri);
            _storage = storage;
            _fiber = new PoolFiber();
        }
Example #13
0
        public void ReadsCorrectValue()
        {
            Fiber fiber = new Fiber();
            int random = new Random().Next();

            Task<int> result = fiber.Enqueue(() => random, false);
            result.Wait();

            Assert.AreEqual(result.Result, random);
        }
Example #14
0
        public PeerHandler(Fiber fiber, Scheduler scheduler, Inbox inbox, SubscriptionObserver observer)
        {
            _observer = observer;
            _endpointSubscriptionCache = new EndpointSubscriptionCache(fiber, scheduler, observer);

            inbox.Receive<InitializePeerHandler>(init =>
                {
                    _peerId = init.PeerId;
                    _peerUri = init.PeerUri;
                });
        }
Example #15
0
        public SuperviseService(HostSettings settings, ServiceBuilderFactory serviceBuilderFactory)
        {
            _settings = settings;
            _serviceBuilderFactory = serviceBuilderFactory;
            _serviceAvailability = new List<ServiceAvailability>();

            _fiber = new PoolFiber();
            _scheduler = new TimerScheduler(new PoolFiber());

            _commandHandlers = CreateCommandHandlers();
        }
        public InProcessKlingerScheduleServer(EnvironmentValidatorRepository repository, TimeSpan schedulerDelay,
                                              TimeSpan schedulerInterval)
        {
            EventChannel = new ChannelAdapter();

            _fiber = new PoolFiber();
            _scheduler = new TimerScheduler(_fiber);
            _repository = repository;
            _schedulerDelay = schedulerDelay;
            _schedulerInterval = schedulerInterval;
        }
		public EndpointSubscription(Fiber fiber, Scheduler scheduler, string messageName,
		                            SubscriptionObserver observer)
		{
			_fiber = fiber;
			_scheduler = scheduler;
			_messageName = messageName;
			_observer = observer;

			_ids = new Dictionary<Guid, PeerSubscription>();

			_subscriptionId = Guid.Empty;
		}
Example #18
0
		public WcfChannelHost(Fiber fiber, UntypedChannel output, Uri serviceUri, string pipeName)
		{
			_serviceUri = serviceUri;

			var channel = new DeserializeMessageEnvelopeChannel<WcfMessageEnvelope>(fiber, new FastTextSerializer(), output);

			_service = new WcfChannelService<WcfMessageEnvelope>(channel);

			_serviceHost = new ConfigurationFreeServiceHost(_service, _serviceUri);
			_serviceHost.AddServiceEndpoint(typeof(WcfChannel<WcfMessageEnvelope>), new NetNamedPipeBinding(), pipeName);
			_serviceHost.Open();
		}
Example #19
0
		public BufferedChunkWriter(Fiber fiber, Scheduler scheduler, ChunkWriter output, int bufferLengthInBytes)
		{
			_waitAfterMinFlush = 10.Milliseconds();
			_fiber = fiber;
			_scheduler = scheduler;
			_output = output;

			_inputBuffer = new Chunk(bufferLengthInBytes);
			_outputBuffer = new Chunk(bufferLengthInBytes);

			_minFlushLength = bufferLengthInBytes/2;
		}
Example #20
0
        public PeerCache(Fiber fiber, Scheduler scheduler, SubscriptionObserver observer, Guid clientId,
                         Uri controlUri)
        {
            _peers = new DictionaryCache<Uri, ActorRef>();
            _peerUri = controlUri;
            _fiber = fiber;
            _scheduler = scheduler;
            _peerIds = new DictionaryCache<Guid, Uri>();

            _peerHandlerFactory = ActorFactory.Create((f, s, i) => new PeerHandler(f, s, i, observer));

            // create a peer for our local client
            WithPeer(clientId, controlUri, x => { }, true);
        }
Example #21
0
        public AuctionActor(Fiber fiber, FiberScheduler scheduler, DateTime expiresAt, decimal openingBid, decimal bidIncrement)
        {
            _fiber = fiber;
            _scheduler = scheduler;
            _expiresAt = expiresAt;
            _openingBid = openingBid;
            _bidIncrement = bidIncrement;
            _highestBid = openingBid - bidIncrement;

            BidChannel = new ConsumerChannel<Bid>(_fiber, ReceiveBid);
            AskChannel = new ConsumerChannel<Ask>(_fiber, ReceiveAsk);

            scheduler.Schedule(expiresAt.ToUniversalTime() - SystemUtil.UtcNow, _fiber, EndAuction);
        }
Example #22
0
        public void ScheduleFinishesOnTime()
        {
            bool? state = false;

            Fiber fiber = new Fiber();
            TimeSpan waitTime = TimeSpan.FromMilliseconds(250);
            DateTime startTime = DateTime.Now;

            Task t = fiber.Schedule(() =>
            {
                state = true;
            }, waitTime, false);

            t.Wait();

            Assert.IsTrue(DateTime.Now - startTime > waitTime);
            Assert.IsTrue(state.Value);
        }
Example #23
0
        public ScheduledOperation Schedule(TimeSpan interval, TimeSpan periodicInterval, Fiber fiber, Action operation)
        {
            ScheduledOperationExecuterImpl scheduled = null;
            scheduled = new ScheduledOperationExecuterImpl(GetScheduledTime(interval), fiber, () =>
                {
                    try
                    {
                        operation();
                    }
                    catch
                    {
                    }
                    finally
                    {
                        scheduled.ScheduledAt = GetScheduledTime(periodicInterval);
                        Schedule(scheduled);
                    }
                });
            Schedule(scheduled);

            return scheduled;
        }
Example #24
0
        public void WriteExecutionOrderIsCorrect()
        {
            const int WRITE_COUNT = 10000;

            ConcurrentQueue<int?> queue = new ConcurrentQueue<int?>();

            Fiber fiber = new Fiber();

            for (int i = 0; i < WRITE_COUNT; i++)
            {
                int? x = i;
                fiber.Enqueue(() =>
                {
                    queue.Enqueue(x);
                });
            }

            while (queue.Count != WRITE_COUNT)
            {
                Thread.Sleep(0);
            }

            Assert.IsTrue(queue.Zip(Enumerable.Range(0, WRITE_COUNT), (i, j) => i == j).All(b => b));
        }
Example #25
0
        public void ReadWriteExecutionOrderIsCorrect()
        {
            int? state = 0;

            Fiber fiber = new Fiber();

            fiber.Enqueue(() =>
            {
                Thread.Sleep(100);
                Assert.AreEqual(state.Value, 0);
            }, false);

            fiber.Enqueue(() =>
            {
                state = 1;
            });

            Task finalTask = fiber.Enqueue(() =>
            {
                Assert.AreEqual(state.Value, 1);
            }, false);

            finalTask.Wait();
        }
Example #26
0
 public SocketServer(Uri uri, Fiber fiber, UntypedChannel eventChannel)
     : base(uri, fiber, eventChannel)
 {
 }
Example #27
0
 /// <summary>
 ///   Constructs a channel
 /// </summary>
 /// <param name = "fiber">The queue where consumer actions should be enqueued</param>
 /// <param name = "output">The method to call when a message is sent to the channel</param>
 /// <param name = "filter">The filter to determine if the message can be consumed</param>
 public FilterChannel(Fiber fiber, Channel <T> output, Filter <T> filter)
 {
     _fiber = fiber;
     Output = output;
     Filter = filter;
 }
        public T HandleOnFiber(Fiber fiber)
        {
            _configuredProvider = () => new SharedFiberProvider <TKey>(fiber);

            return(this as T);
        }
Example #29
0
 public InterceptorChannel(Fiber fiber, Channel <T> output, InterceptorFactory <T> interceptorFactory)
 {
     _fiber             = fiber;
     _output            = output;
     InterceptorFactory = interceptorFactory;
 }
Example #30
0
 public StatusChannel(EnvironmentValidatorRepository repo)
 {
     _repo  = repo;
     _fiber = new PoolFiber();
 }
Example #31
0
 public HttpServer(Uri uri, Fiber fiber, UntypedChannel eventChannel,
                   IEnumerable <PatternMatchConnectionHandler> connectionHandlers)
     : base(uri, fiber, eventChannel)
 {
     _connectionHandlers = connectionHandlers.ToArray();
 }
Example #32
0
 public ICancellableDispatcher GetDispatcher() => Fiber.CreateMonoThreadedFiber(_OnCreate);
Example #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Tasks.YieldableTask"/> class.
 /// </summary>
 /// <returns>
 /// The task.
 /// </returns>
 /// <param name='coroutine'>
 /// The coroutine to execute.
 /// </param>
 /// <param name='creationOptions'>
 /// Creation options.
 /// </param>
 public YieldableTask(Func <FiberInstruction> coroutine, TaskCreationOptions creationOptions) :
     base(() => InternalAction(), creationOptions)
 {
     fiber = new Fiber(coroutine);
 }
Example #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Tasks.YieldableTask"/> class.
 /// </summary>
 /// <returns>
 /// The task.
 /// </returns>
 /// <param name='coroutine'>
 /// The coroutine to execute.
 /// </param>
 public YieldableTask(Func <FiberInstruction> coroutine) :
     base(() => InternalAction())
 {
     fiber = new Fiber(coroutine);
 }
Example #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Tasks.YieldableTask"/> class.
 /// </summary>
 /// <returns>
 /// The task.
 /// </returns>
 /// <param name='instruction'>
 /// The instruction to execute.
 /// </param>
 /// <param name='cancellationToken'>
 /// Cancellation token.
 /// </param>
 /// <param name='creationOptions'>
 /// Creation options.
 /// </param>
 public YieldableTask(FiberInstruction instruction, CancellationToken cancellationToken, TaskCreationOptions creationOptions) :
     base(() => InternalAction(), cancellationToken, creationOptions)
 {
     fiber = new Fiber(() => instruction);
 }
Example #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Tasks.YieldableTask"/> class.
 /// </summary>
 /// <returns>
 /// The task.
 /// </returns>
 /// <param name='instruction'>
 /// The coroutine to execute.
 /// </param>
 public YieldableTask(FiberInstruction instruction) :
     base(() => InternalAction())
 {
     fiber = new Fiber(() => instruction);
 }
Example #37
0
 public PingActor()
 {
     _fiber = new PoolFiber();
 }
 public void Initialize(TActor instance, Fiber fiber, Scheduler scheduler, Inbox inbox)
 {
     _methods.Each(method => method.Initialize(instance, fiber, scheduler, inbox));
 }
Example #39
0
 public PongActor()
 {
     _fiber = new ThreadPoolFiber();
 }
Example #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Tasks.YieldableTask"/> class.
 /// </summary>
 /// <returns>
 /// The task.
 /// </returns>
 /// <param name='coroutine'>
 /// The coroutine to execute.
 /// </param>
 /// <param name='state'>
 /// State to pass to the function.
 /// </param>
 public YieldableTask(Func <object, FiberInstruction> coroutine, object state) :
     base(() => InternalAction())
 {
     fiber = new Fiber(coroutine, state);
 }
Example #41
0
 /// <summary>
 /// Constructs a channel
 /// </summary>
 /// <param name="fiber">The queue where consumer actions should be enqueued</param>
 /// <param name="consumer">The method to call when a message is sent to the channel</param>
 public ConsumerChannel(Fiber fiber, Consumer <T> consumer)
 {
     _fiber    = fiber;
     _consumer = consumer;
 }
Example #42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Tasks.YieldableTask"/> class.
 /// </summary>
 /// <returns>
 /// The task.
 /// </returns>
 /// <param name='coroutine'>
 /// The coroutine to execute.
 /// </param>
 /// <param name='state'>
 /// State to pass to the function.
 /// </param>
 /// <param name='cancellationToken'>
 /// Cancellation token.
 /// </param>
 /// <param name='creationOptions'>
 /// Creation options.
 /// </param>
 public YieldableTask(Func <object, FiberInstruction> coroutine, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) :
     base(() => InternalAction(), cancellationToken, creationOptions)
 {
     fiber = new Fiber(coroutine, state);
 }
 public SharedThreadFiberManager(Action <Thread> onCreate = null)
 {
     _Fiber = Fiber.CreateMonoThreadedFiber(onCreate);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Tasks.YieldableTask"/> class.
 /// </summary>
 /// <returns>
 /// The task.
 /// </returns>
 /// <param name='coroutine'>
 /// The coroutine to execute.
 /// </param>
 /// <param name='creationOptions'>
 /// Creation options.
 /// </param>
 public YieldableTask(IEnumerator coroutine, TaskCreationOptions creationOptions)
     : base(() => InternalAction(), creationOptions)
 {
     fiber = new Fiber(coroutine);
 }
Example #45
0
        /// <summary>
        /// Gets the time scaling on the routine.
        /// </summary>
        public float GetTimeScale()
        {
            Fiber fiber = GetManager().Fibers[this];

            return(fiber == null ? 1.0f : fiber.TimeScale);
        }
Example #46
0
 protected override void Activities(Fiber fiber) =>
 Emitter callExternalService(Fiber _) // Could return an inner Fiber if needed
Example #47
0
		static AnonymousActor CreateAnonymousActor(Fiber fiber, Scheduler scheduler, Inbox inbox)
		{
			return new AnonymousActor(fiber, scheduler, inbox);
		}
Example #48
0
 public AsyncCalls(ASyncToken token, Fiber fiber)
 {
     this.AsyncUser = token;
     this.fiber     = fiber;
 }
Example #49
0
 public ObjectWriterChannel(Fiber fiber, ObjectWriter writer, Action <Channel <T> > completed)
 {
     _writer    = writer;
     _fiber     = fiber;
     _completed = completed;
 }
 public InMemorySubscriptionStorage()
 {
     _subscriptions = new HashSet<PersistentSubscription>();
     _fiber = new PoolFiber();
 }
Example #51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Tasks.YieldableTask"/> class.
 /// </summary>
 /// <returns>
 /// The task.
 /// </returns>
 /// <param name='coroutine'>
 /// The coroutine to execute.
 /// </param>
 public YieldableTask(IEnumerator coroutine) :
     base(() => InternalAction())
 {
     fiber = new Fiber(coroutine);
 }
 public void AddChannel <T>(Fiber fiber, Func <Fiber, Channel <T> > channelFactory)
 {
     _connection.AddChannel(fiber, channelFactory);
 }
Example #53
0
		AnonymousActor(Fiber fiber, Scheduler scheduler, Inbox inbox)
		{
			_fiber = fiber;
			_scheduler = scheduler;
			_inbox = inbox;
		}
Example #54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Tasks.YieldableTask"/> class.
 /// </summary>
 /// <returns>
 /// The task.
 /// </returns>
 /// <param name='coroutine'>
 /// The coroutine to execute.
 /// </param>
 /// <param name='creationOptions'>
 /// Creation options.
 /// </param>
 public YieldableTask(IEnumerator coroutine, TaskCreationOptions creationOptions) :
     base(() => InternalAction(), creationOptions)
 {
     fiber = new Fiber(coroutine);
 }
Example #55
0
        public QueryActor(Fiber fiber)
        {
            _fiber = fiber;

            GetCityChannel = new ConsumerChannel<QueryInputModel>(_fiber, ProcessRequest);
        }
Example #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Tasks.YieldableTask"/> class.
 /// </summary>
 /// <returns>
 /// The task.
 /// </returns>
 /// <param name='coroutine'>
 /// The coroutine to execute.
 /// </param>
 /// <param name='cancellationToken'>
 /// Cancellation token.
 /// </param>
 public YieldableTask(IEnumerator coroutine, CancellationToken cancellationToken) :
     base(() => InternalAction(), cancellationToken)
 {
     fiber = new Fiber(coroutine);
 }
Example #57
0
 TActor CreateActorInstance(Fiber fiber, Scheduler scheduler, Inbox inbox)
 {
     return(_factory(fiber, scheduler, inbox));
 }
Example #58
0
        public void AddChannel(Fiber fiber, Func <Fiber, Channel <TChannel> > channelFactory)
        {
            Channel <TChannel> channel = channelFactory(fiber);

            _builder.AddChannel(channel);
        }
Example #59
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpicyPixel.Threading.Tasks.YieldableTask"/> class.
 /// </summary>
 /// <returns>
 /// The task.
 /// </returns>
 /// <param name='coroutine'>
 /// The coroutine to execute.
 /// </param>
 /// <param name='cancellationToken'>
 /// Cancellation token.
 /// </param>
 public YieldableTask(Func <FiberInstruction> coroutine, CancellationToken cancellationToken) :
     base(() => InternalAction(), cancellationToken)
 {
     fiber = new Fiber(coroutine);
 }
Example #60
0
 public SocketServer(Uri uri, Fiber fiber)
     : this(uri, fiber, new ShuntChannel())
 {
 }