/// <summary>
 /// Constructs the step, using the specified transport to send the messages
 /// </summary>
 public SendOutgoingMessageStep(ITransport transport, IRebusLoggerFactory rebusLoggerFactory)
 {
     if (transport == null) throw new ArgumentNullException(nameof(transport));
     if (rebusLoggerFactory == null) throw new ArgumentNullException(nameof(rebusLoggerFactory));
     _transport = transport;
     _log = rebusLoggerFactory.GetCurrentClassLogger();
 }
Example #2
0
        public static void CreateQueue(Action<ITransportEndpoint> action)
        {
            var name = new TransportEndpointAddress(Guid.NewGuid().ToString());
            
            var managers = new ITransport[]
            {
                new MsmqTransport(),
                new InMemoryTransport(),
                new InMemorySynchronousTransport()
            };

            foreach (var manager in managers)
            {
                try
                {
                    manager.CreateEndpoint(name);
                    var queue = manager.OpenEndpoint(name);
                    action(queue);
                }
                finally
                {
                    manager.DeleteEndpoint(name);
                }
            }
        }
Example #3
0
        internal ITransport Open(string hostname, ITransport transport)
        {
            ProtocolHeader myHeader = this.Start(hostname, transport);

            ProtocolHeader theirHeader = Reader.ReadHeader(transport);
            Trace.WriteLine(TraceLevel.Frame, "RECV AMQP {0}", theirHeader);
            this.OnHeader(myHeader, theirHeader);

            SaslCode code = SaslCode.SysTemp;
            while (true)
            {
                ByteBuffer buffer = Reader.ReadFrameBuffer(transport, new byte[4], uint.MaxValue);
                if (buffer == null)
                {
                    throw new ObjectDisposedException(transport.GetType().Name);
                }

                if (!this.OnFrame(transport, buffer, out code))
                {
                    break;
                }
            }

            if (code != SaslCode.Ok)
            {
                throw new AmqpException(ErrorCode.UnauthorizedAccess,
                    Fx.Format(SRAmqp.SaslNegoFailed, code));
            }

            return this.UpgradeTransport(transport);
        }
 public ElasticClientFactory(
     IConnectionSettingsValues settings = null,
     IConnection connection = null,
     ITransport transport = null,
     INestSerializer serializer = null) {
     this.CreateClient(settings, connection, transport, serializer);
 }
 public BusClient(ITransport transport, ISubscriptionKeyResolver keyResolver, IConfigurationContext configurationContext)
 {
     this.transport = transport;
     this.keyResolver = keyResolver;
     this.transport.InitializeForPublishing();
     this.configurationContext = configurationContext;
 }
Example #6
0
 public MessageHandler(IKernel kernel, ITransport transport, ISerializer serializer, TimeoutManager timeoutManager)
 {
     m_kernel = kernel;
     m_transport = transport;
     m_serializer = serializer;
     m_timeoutManager = timeoutManager;
 }
Example #7
0
        public void Run()
        {
            // Create an in-memory TransactionalTransport and point it to the AuditQ
            // Serialize data into the database.

            string auditQueue = ConfigurationManager.AppSettings["AuditQueue"];
            string machineName = Environment.MachineName;

            // Make sure that the queue being monitored, exists!
            if (!MessageQueue.Exists(MsmqUtilities.GetFullPathWithoutPrefix(auditQueue)))
            {
                // The error queue being monitored must be local to this endpoint
                throw new Exception(string.Format("The audit queue {0} being monitored must be local to this endpoint and must exist. Make sure a transactional queue by the specified name exists. The audit queue to be monitored is specified in the app.config", auditQueue));
            }

            // Create an in-memory transport with the same configuration as that of the current endpoint.
            AuditMessageQueueTransport = new TransactionalTransport()
            {
                IsTransactional = CurrentEndpointTransport.IsTransactional,
                MaxRetries = CurrentEndpointTransport.MaxRetries,
                IsolationLevel = CurrentEndpointTransport.IsolationLevel,
                MessageReceiver = new MsmqMessageReceiver(),
                NumberOfWorkerThreads = CurrentEndpointTransport.NumberOfWorkerThreads,
                TransactionTimeout = CurrentEndpointTransport.TransactionTimeout,
                FailureManager = CurrentEndpointTransport.FailureManager
            };

            AuditMessageQueueTransport.Start(new Address(auditQueue, machineName));
            AuditMessageQueueTransport.TransportMessageReceived += new EventHandler<TransportMessageReceivedEventArgs>(AuditMessageQueueTransport_TransportMessageReceived);
        }
Example #8
0
 public void SetUp()
 {              
     mockRepository = new MockRepository();
     mainTransport = mockRepository.StrictMultiMock<ITransport>();
     mainTransport.Replay();
     retryingTransport = new RetryingTransport(new SilentLogger(), mainTransport, retryCount, retryDelay);
 }
        public void Run()
        {
            if (!RoutingConfig.IsConfiguredAsMasterNode)
                return;

            controlTransport = new TransactionalTransport
            {
                IsTransactional = true,
                FailureManager = MessageFailureManager,
                MessageReceiver = new MsmqMessageReceiver(),
                MaxRetries = 1,
                NumberOfWorkerThreads = NumberOfWorkerThreads,
            };

            controlTransport.TransportMessageReceived +=
                (obj, ev) =>
                {
                    var transportMessage = ev.Message;

                    if (!transportMessage.Headers.ContainsKey(Headers.ControlMessage))
                        return;

                    HandleControlMessage(transportMessage);
                };

            var bus = Configure.Instance.Builder.Build<IStartableBus>();
            bus.Started += (obj, ev) => controlTransport.Start(ControlQueue);
        }
Example #10
0
        public virtual async Task ConnectAsync(string hostname, int port, bool ssl, bool validateCertificate)
        {
            try
            {
                Host = hostname;
                Port = port;
                Ssl = ssl;

#if WINDOWS_PHONE
                _Connection = new WindowsNetSockets(hostname, port, ssl);
#else
                _Connection = new SystemNetTransport(hostname, port, ssl, validateCertificate);
#endif
                _Stream = new BufferedReadStream(await _Connection.ConnectAsync());

                OnConnected(await GetResponseAsync());

                IsConnected = true;
            }
            catch (Exception)
            {
                IsConnected = false;
                Utilities.TryDispose(_Stream);
                throw;
            }
        }
 // For send/receive
 private TransportAsyncWorker(ITransport transport, OperationType operation, byte[] buffer, int offset, int size, AsyncCallback callback, object state)
     : this(transport, operation, callback, state)
 {
     _buffer = buffer;
     _offset = offset;
     _size = size;
 }
Example #12
0
 public TransportWrapper(ITransport transport)
 {
     if (transport == null)
         throw new ArgumentNullException("transport");
     _transport = transport;
     _serviceManager = new ServiceManager<TransportWrapper>("SendGrid Service", "Email Services");
 }
Example #13
0
 public Dictionary<string, string> ExecuteOperation(ITransport transport)
 {
     //Defines a new Dictonary which is capable of storing indexed string values with a string index.
     Dictionary<string, string> result;
     //Writes the request header
     HeaderParams param = WriteHeader(transport, STATS_REQUEST);
     transport.Flush();
     ReadHeaderAndValidate(transport, param);
     //reads the number of statistic details sent from server
     int numberOfStats = transport.ReadVInt();
     if (logger.IsTraceEnabled)
         logger.Trace("Number of Stats : " + numberOfStats);
     result = new Dictionary<string, string>();
     //reads all statistics and add them to the 'result' dictionary
     for (int i = 0; i < numberOfStats; i++)
     {
         String statName = transport.ReadString();
         if (logger.IsTraceEnabled)
             logger.Trace("Stat Name Recieved : " + statName);
         String statValue = transport.ReadString();
         if (logger.IsTraceEnabled)
             logger.Trace("Stat ValueRecieved : " + statName);
         result.Add(statName, statValue);
     }
     return result;
 }
Example #14
0
 protected virtual void OnResumed(ITransport sender)
 {
     if(this.resumedHandler != null)
     {
         this.resumedHandler(sender);
     }
 }
Example #15
0
        public static void Test(ITransport t, IQueueStrategy strategy,
            Endpoint queueEndpoint, Action<Message> send, Func<MessageEnumerator>
            enumer)
        {
            Guid id = Guid.NewGuid();
            var serializer = new XmlMessageSerializer(new
                                                          DefaultReflection(), new DefaultKernel());

            var subscriptionStorage = new MsmqSubscriptionStorage(new
                                                                      DefaultReflection(),
                                                                  serializer,
                                                                  queueEndpoint.Uri,
                                                                  new
                                                                      EndpointRouter(),
                                                                  strategy);
            subscriptionStorage.Initialize();

            var wait = new ManualResetEvent(false);

            subscriptionStorage.SubscriptionChanged += () => wait.Set();

            t.AdministrativeMessageArrived +=
                subscriptionStorage.HandleAdministrativeMessage;

            Message msg = new MessageBuilder
                (serializer).GenerateMsmqMessageFromMessageBatch(new
                                                                     AddInstanceSubscription
                {
                    Endpoint = queueEndpoint.Uri.ToString(),
                    InstanceSubscriptionKey = id,
                    Type = typeof (TestMessage2).FullName,
                });
            send(msg);

            wait.WaitOne();

            msg = new MessageBuilder
                (serializer).GenerateMsmqMessageFromMessageBatch(new
                                                                     RemoveInstanceSubscription
                {
                    Endpoint = queueEndpoint.Uri.ToString(),
                    InstanceSubscriptionKey = id,
                    Type = typeof (TestMessage2).FullName,
                });

            wait.Reset();

            send(msg);

            wait.WaitOne();

            IEnumerable<Uri> uris = subscriptionStorage
                .GetSubscriptionsFor(typeof (TestMessage2));
            Assert.Equal(0, uris.Count());

            int count = 0;
            MessageEnumerator copy = enumer();
            while (copy.MoveNext()) count++;
            Assert.Equal(0, count);
        }
Example #16
0
 /// <summary>
 /// Constructs the step, using the given transport and settings
 /// </summary>
 public SimpleRetryStrategyStep(ITransport transport, SimpleRetryStrategySettings simpleRetryStrategySettings, IErrorTracker errorTracker, IRebusLoggerFactory rebusLoggerFactory)
 {
     _transport = transport;
     _simpleRetryStrategySettings = simpleRetryStrategySettings;
     _errorTracker = errorTracker;
     _log = rebusLoggerFactory.GetCurrentClassLogger();
 }
Example #17
0
 protected virtual void OnInterrupted(ITransport sender)
 {
     if(this.interruptedHandler != null)
     {
         this.interruptedHandler(sender);
     }
 }
Example #18
0
 protected override void OnCommand(ITransport sender, Command command)
 {
     if ( command.IsWireFormatInfo )
     {
         WireFormatInfo info = (WireFormatInfo)command;
         try
         {
             if (!info.Valid)
             {
                 throw new IOException("Remote wire format magic is invalid");
             }
             wireInfoSentDownLatch.await(negotiateTimeout);
             wireFormat.RenegotiateWireFormat(info);
         }
         catch (Exception e)
         {
             OnException(this, e);
         }
         finally
         {
             readyCountDownLatch.countDown();
         }
     }
     this.commandHandler(sender, command);
 }
Example #19
0
 public void Init(ITransport transport)
 {
     transport.MessageSerializationException += Transport_OnMessageSerializationException;
     transport.MessageProcessingFailure += Transport_OnMessageProcessingFailure;
     transport.MessageProcessingCompleted += Transport_OnMessageProcessingCompleted;
     transport.MessageArrived += Transport_OnMessageArrived;
 }
        public void Run()
        {
            if (!Configure.Instance.DistributorConfiguredToRunOnThisEndpoint())
                return;

            controlTransport = new TransactionalTransport
            {
                IsTransactional = true,
                FailureManager = MessageFailureManager,
                MessageReceiver = new MsmqMessageReceiver(),
                MaxRetries = 5,
                NumberOfWorkerThreads = NumberOfWorkerThreads,
            };

            controlTransport.TransportMessageReceived +=
                (obj, ev) =>
                {
                    var transportMessage = ev.Message;

                    if (!transportMessage.IsControlMessage())
                        return;

                    HandleControlMessage(transportMessage);
                };

            controlTransport.Start(ControlQueue);
        }
Example #21
0
        internal bool OnFrame(ITransport transport, ByteBuffer buffer, out SaslCode code)
        {
            ushort channel;
            DescribedList command;
            Frame.GetFrame(buffer, out channel, out command);
            Trace.WriteLine(TraceLevel.Frame, "RECV {0}", command);

            bool shouldContinue = true;
            if (command.Descriptor.Code == Codec.SaslOutcome.Code)
            {
                code = ((SaslOutcome)command).Code;
                shouldContinue = false;
            }
            else
            {
                code = SaslCode.Ok;
                DescribedList response = this.OnCommand(command);
                if (response != null)
                {
                    this.SendCommand(transport, response);
                    shouldContinue = response.Descriptor.Code != Codec.SaslOutcome.Code;
                }
            }

            return shouldContinue;
        }
        public void Init()
        {
            endpointTransport = Configure.Instance.Builder.Build<ITransport>();
            endpointTransport.FinishedMessageProcessing += (x, y) => SendReadyMessage(false);

            var bus = Configure.Instance.Builder.Build<IStartableBus>();
            bus.Started += (x, y) =>
                                {
                                    SendReadyMessage(true);
                                    controlTransport.Start(ControlQueue);
                                };

            endpointBus = Configure.Instance.Builder.Build<IBus>();

            controlTransport = new TransactionalTransport
                            {
                                IsTransactional = true,
                                FailureManager = Configure.Instance.Builder.Build<IManageMessageFailures>(),
                                MessageReceiver = new MsmqMessageReceiver(),
                                MaxRetries = 1,
                                NumberOfWorkerThreads = NumberOfWorkerThreads
                            };

            var serializer = Configure.Instance.Builder.Build<IMessageSerializer>();

            controlTransport.TransportMessageReceived +=
                (obj, ev) =>
                    {
                        var messages = serializer.Deserialize(new MemoryStream(ev.Message.Body));
                        foreach (var msg in messages)
                            if (msg is ReadyMessage)
                                Handle(msg as ReadyMessage, ev.Message.ReturnAddress);
                    };
        }
        /// <summary>
        /// Creates the worker factory
        /// </summary>
        public ThreadPoolWorkerFactory(ITransport transport, IRebusLoggerFactory rebusLoggerFactory, IPipeline pipeline, IPipelineInvoker pipelineInvoker, Options options, Func<RebusBus> busGetter, BusLifetimeEvents busLifetimeEvents, ISyncBackoffStrategy backoffStrategy)
        {
            if (transport == null) throw new ArgumentNullException(nameof(transport));
            if (rebusLoggerFactory == null) throw new ArgumentNullException(nameof(rebusLoggerFactory));
            if (pipeline == null) throw new ArgumentNullException(nameof(pipeline));
            if (pipelineInvoker == null) throw new ArgumentNullException(nameof(pipelineInvoker));
            if (options == null) throw new ArgumentNullException(nameof(options));
            if (busGetter == null) throw new ArgumentNullException(nameof(busGetter));
            if (busLifetimeEvents == null) throw new ArgumentNullException(nameof(busLifetimeEvents));
            if (backoffStrategy == null) throw new ArgumentNullException(nameof(backoffStrategy));
            _transport = transport;
            _rebusLoggerFactory = rebusLoggerFactory;
            _pipeline = pipeline;
            _pipelineInvoker = pipelineInvoker;
            _options = options;
            _busGetter = busGetter;
            _backoffStrategy = backoffStrategy;
            _parallelOperationsManager = new ParallelOperationsManager(options.MaxParallelism);
            _log = _rebusLoggerFactory.GetCurrentClassLogger();

            if (_options.MaxParallelism < 1)
            {
                throw new ArgumentException($"Max parallelism is {_options.MaxParallelism} which is an invalid value");
            }

            if (options.WorkerShutdownTimeout < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException($"Cannot use '{options.WorkerShutdownTimeout}' as worker shutdown timeout as it");
            }

            busLifetimeEvents.WorkersStopped += WaitForContinuationsToFinish;
        }
Example #24
0
 public DockingViewManager(ITransport transport, IAdapter adapter, IScheduler scheduler, LocalScheduler dispatcher)
 {
     _transport = transport;
     _adapter = adapter;
     _scheduler = scheduler;
     _dispatcher = dispatcher;
 }
        public ChinookNotificationForwarder(IBus bus, IChinookTransportFactory transportFactory)
        {
            _bus = bus;
            _transport = transportFactory.GetTransport();

            _transport.TransportMessageReceived += TransportMessageReceived;
        }
 protected AbstractInterceptor(ITransport transport, IKernel kernel, ISerializer serializer, TimeoutManager timeoutManager)
 {
     m_transport = transport;
     m_kernel = kernel;
     m_serializer = serializer;
     m_timeoutManager = timeoutManager;
 }
 public SendService(IDatabaseAccess databaseAccess)
 {
     _deliveryRepository = databaseAccess.Repository<Delivery>();
     _sendGridMessage = new SendGridMessage();
     _sendGridMessage.From = new MailAddress(ConfigurationManager.AppSettings["SendFrom"]);
     _transport = new Web(ConfigurationManager.AppSettings["SendGridkey"]);
 }
Example #28
0
 public CachedTransport(string email, ITransport innerTranport)
 {
     userCacheService = new CacheService(email);
     commonCacheService = new CacheService();
     this.innerTranport = innerTranport;
     this.innerTranport.Throttled += instance_Throttled;
 }
 public static IAsyncTransport GetWrapper(ITransport transport)
 {
     // determine whether transport supports async operations and construct wrapper if not
     return transport is IAsyncTransport
         ? (IAsyncTransport)transport
         : new TransportAsyncWrapper(transport);
 }
 public DurationTraderViewModelController(ITransport transport, IAdapter adapter, IScheduler scheduler, LocalScheduler dispatcher)
 {
     transport.GetTradingObservables()
         .SubscribeOn(scheduler)
         .ObserveOn(dispatcher)
         .Subscribe(fSet => adapter.updater(fSet, ViewModel));
 }
        private async Task WorkerAsync(
            ConcurrentQueue <SentryEvent> queue,
            SentryOptions options,
            ITransport transport,
            SemaphoreSlim queuedEventSemaphore,
            CancellationToken cancellation)
        {
            var shutdownTimeout   = new CancellationTokenSource();
            var shutdownRequested = false;

            try
            {
                while (!shutdownTimeout.IsCancellationRequested)
                {
                    // If the cancellation was signaled,
                    // set the latest we can keep reading off of the queue (while there's still stuff to read)
                    // No longer synchronized with queuedEventSemaphore (Enqueue will throw object disposed),
                    // run until the end of the queue or shutdownTimeout
                    if (!shutdownRequested)
                    {
                        try
                        {
                            await queuedEventSemaphore.WaitAsync(cancellation).ConfigureAwait(false);
                        }
                        // Cancellation requested, scheduled shutdown but continue in case there are more items
                        catch (OperationCanceledException)
                        {
                            if (options.ShutdownTimeout == TimeSpan.Zero)
                            {
                                options.DiagnosticLogger?.LogDebug(
                                    "Exiting immediately due to 0 shutdown timeout. #{0} in queue.", queue.Count);
                                return;
                            }
                            else
                            {
                                options.DiagnosticLogger?.LogDebug(
                                    "Shutdown scheduled. Stopping by: {0}. #{1} in queue.", options.ShutdownTimeout,
                                    queue.Count);
                                shutdownTimeout.CancelAfter(options.ShutdownTimeout);
                            }

                            shutdownRequested = true;
                        }
                    }

                    if (queue.TryPeek(out var @event)) // Work with the event while it's in the queue
                    {
                        try
                        {
                            var task = transport.CaptureEventAsync(@event, shutdownTimeout.Token);
                            options.DiagnosticLogger?.LogDebug("Event {0} in-flight to Sentry. #{1} in queue.", @event.EventId, queue.Count);
                            await task.ConfigureAwait(false);
                        }
                        catch (OperationCanceledException)
                        {
                            options.DiagnosticLogger?.LogInfo("Shutdown token triggered. Time to exit. #{0} in queue.",
                                                              queue.Count);
                            return;
                        }
                        catch (Exception exception)
                        {
                            options.DiagnosticLogger?.LogError("Error while processing event {1}: {0}. #{2} in queue.",
                                                               exception, @event.EventId, queue.Count);
                        }
                        finally
                        {
                            queue.TryDequeue(out _);
                            Interlocked.Decrement(ref _currentItems);
                            OnFlushObjectReceived?.Invoke(@event, EventArgs.Empty);
                        }
                    }
                    else
                    {
                        Debug.Assert(shutdownRequested);
                        options.DiagnosticLogger?.LogInfo("Exiting the worker with an empty queue.");

                        // Empty queue. Exit.
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                options.DiagnosticLogger?.LogFatal("Exception in the background worker.", e);
                throw;
            }
            finally
            {
                queuedEventSemaphore.Dispose();
            }
        }
 internal ITransport UpgradeTransportInternal(ITransport transport)
 {
     return(this.UpgradeTransport(transport));
 }
Example #33
0
 internal void OnTransportException(ITransport source, Exception cause)
 {
     this.OnException(cause);
 }
Example #34
0
        /// <summary>
        /// Handle incoming commands
        /// </summary>
        /// <param name="commandTransport">An ITransport</param>
        /// <param name="command">A  Command</param>
        protected void OnCommand(ITransport commandTransport, Command command)
        {
            if (command.IsMessageDispatch)
            {
                WaitForTransportInterruptionProcessingToComplete();
                DispatchMessage((MessageDispatch)command);
            }
            else if (command.IsKeepAliveInfo)
            {
                OnKeepAliveCommand(commandTransport, (KeepAliveInfo)command);
            }
            else if (command.IsWireFormatInfo)
            {
                this.brokerWireFormatInfo = (WireFormatInfo)command;
            }
            else if (command.IsBrokerInfo)
            {
                this.brokerInfo = (BrokerInfo)command;
                this.brokerInfoReceived.countDown();
            }
            else if (command.IsShutdownInfo)
            {
                // Only terminate the connection if the transport we use is not fault
                // tolerant otherwise we let the transport deal with the broker closing
                // our connection and deal with IOException if it is sent to use.
                if (!closing.Value && !closed.Value && this.transport != null && !this.transport.IsFaultTolerant)
                {
                    OnException(new NMSException("Broker closed this connection via Shutdown command."));
                }
            }
            else if (command.IsProducerAck)
            {
                ProducerAck ack = (ProducerAck)command as ProducerAck;
                if (ack.ProducerId != null)
                {
                    MessageProducer producer = producers[ack.ProducerId] as MessageProducer;
                    if (producer != null)
                    {
                        if (Tracer.IsDebugEnabled)
                        {
                            Tracer.DebugFormat("Connection[{0}]: Received a new ProducerAck -> ",
                                               this.ConnectionId, ack);
                        }

                        producer.OnProducerAck(ack);
                    }
                }
            }
            else if (command.IsConnectionError)
            {
                if (!closing.Value && !closed.Value)
                {
                    ConnectionError connectionError = (ConnectionError)command;
                    BrokerError     brokerError     = connectionError.Exception;
                    string          message         = "Broker connection error.";
                    string          cause           = "";

                    if (null != brokerError)
                    {
                        message = brokerError.Message;
                        if (null != brokerError.Cause)
                        {
                            cause = brokerError.Cause.Message;
                        }
                    }

                    Tracer.ErrorFormat("Connection[{0}]: ConnectionError: " + message + " : " + cause, this.ConnectionId);
                    OnAsyncException(new NMSConnectionException(message, cause));
                }
            }
            else
            {
                Tracer.ErrorFormat("Connection[{0}]: Unknown command: " + command, this.ConnectionId);
            }
        }
Example #35
0
        public void Close()
        {
            if (!this.closed.Value && !transportFailed.Value)
            {
                this.Stop();
            }

            lock (myLock)
            {
                if (this.closed.Value)
                {
                    return;
                }

                try
                {
                    Tracer.InfoFormat("Connection[{0}]: Closing Connection Now.", this.ConnectionId);
                    this.closing.Value = true;

                    if (this.advisoryConsumer != null)
                    {
                        this.advisoryConsumer.Dispose();
                        this.advisoryConsumer = null;
                    }

                    lock (sessions.SyncRoot)
                    {
                        foreach (Session session in sessions)
                        {
                            session.Shutdown();
                        }
                    }
                    sessions.Clear();

                    if (this.tempDests.Count > 0)
                    {
                        // Make a copy of the destinations to delete, because the act of deleting
                        // them will modify the collection.
                        ActiveMQTempDestination[] tempDestsToDelete = new ActiveMQTempDestination[this.tempDests.Count];

                        this.tempDests.Values.CopyTo(tempDestsToDelete, 0);
                        foreach (ActiveMQTempDestination dest in tempDestsToDelete)
                        {
                            dest.Delete();
                        }
                    }

                    // Connected is true only when we've successfully sent our ConnectionInfo
                    // to the broker, so if we haven't announced ourselves there's no need to
                    // inform the broker of a remove, and if the transport is failed, why bother.
                    if (connected.Value && !transportFailed.Value)
                    {
                        DisposeOf(ConnectionId);
                        ShutdownInfo shutdowninfo = new ShutdownInfo();
                        transport.Oneway(shutdowninfo);
                    }

                    executor.Shutdown();

                    Tracer.DebugFormat("Connection[{0}]: Disposing of the Transport.", this.ConnectionId);
                    transport.Dispose();
                }
                catch (Exception ex)
                {
                    Tracer.ErrorFormat("Connection[{0}]: Error during connection close: {1}", ConnectionId, ex);
                }
                finally
                {
                    if (executor != null)
                    {
                        executor.Shutdown();
                    }

                    this.transport       = null;
                    this.closed.Value    = true;
                    this.connected.Value = false;
                    this.closing.Value   = false;
                }
            }
        }
Example #36
0
 /// <summary>
 /// Constructs the step
 /// </summary>
 public OutgoingAuditingStep(AuditingHelper auditingHelper, ITransport transport)
 {
     _auditingHelper = auditingHelper;
     _transport      = transport;
 }
Example #37
0
 public static ITransport UseRedisAttachments(this ITransport transport, IConnectionMultiplexer multiplexer, RedisConfiguration configuration)
 {
     transport.UseMiddleware(new AttachmentMiddleware(new RedisAttachmentProvider(multiplexer, configuration)));
     return(transport);
 }
Example #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DriverVcs"/> class.
 /// </summary>
 /// <param name="configRepository">The repository configuration.</param>
 /// <param name="io">The input/output instance.</param>
 /// <param name="config">The config instance.</param>
 /// <param name="transport">The remote transport instance.</param>
 /// <param name="process">The process instance.</param>
 protected DriverVcs(ConfigRepositoryVcs configRepository, IIO io, Config config, ITransport transport = null, IProcessExecutor process = null)
 {
     cacheInfomartion = new Dictionary <string, ConfigBucket>();
     ConfigRepository = configRepository;
     Config           = config;
     IO             = io;
     Process        = process ?? new BucketProcessExecutor(io);
     Uri            = configRepository.Uri;
     this.transport = transport ?? new TransportHttp(io, config);
 }
Example #39
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Cyan;
            Aviation aviation = new Aviation();
            Cargo    cargo    = new Cargo();
            Military military = new Military();
            Pasanger pasanger = new Pasanger();
            Ty134    ty134    = new Ty134();
            Boing    boing    = new Boing();

            cargo.addInfo();
            Console.WriteLine('\n');
            military.addInfo();
            Console.WriteLine('\n');
            pasanger.addInfo();
            Console.WriteLine('\n');

            Console.ForegroundColor = ConsoleColor.Magenta;
            aviation.Type();
            cargo.Type();
            military.Type();
            pasanger.Type();
            ty134.Type();
            boing.Type();
            Console.WriteLine('\n');

            Console.ForegroundColor = ConsoleColor.White;
            bool fly = pasanger is Aviation;

            if (fly)
            {
                Aviation confOne = (Aviation)pasanger;
                confOne.Type();
            }

            Console.ForegroundColor = ConsoleColor.Red;
            ITransport confTwo   = military as ITransport;
            ITrans     confThree = cargo as ITrans;

            if (confTwo != null)
            {
                confTwo.Info();
            }

            if (confThree != null)
            {
                confThree.Info("fsfe");
            }



            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine(cargo.ToString());

            Console.ForegroundColor = ConsoleColor.Green;
            Transport obj = pasanger as Transport;//можно ли преобразовать

            Console.WriteLine(obj.GetType());

            Console.ForegroundColor = ConsoleColor.Yellow;
            if (military is Transport)//преднадлежит
            {
                Console.WriteLine(true + "\n");
            }

            Console.ForegroundColor = ConsoleColor.Magenta;
            Transport[] mas = { cargo, military, pasanger };
            foreach (Transport x in mas)
            {
                Console.WriteLine(Printer.iAmPrinting(x));
            }

            Console.ReadKey();
        }
 public BackgroundWorker(
     ITransport transport,
     SentryOptions options)
     : this(transport, options, null, null)
 {
 }
Example #41
0
        /// <summary>
        /// Constructs the in-mem error tracker with the configured number of delivery attempts as the MAX
        /// </summary>
        public InMemErrorTracker(SimpleRetryStrategySettings simpleRetryStrategySettings, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory, ITransport transport, IRebusTime rebusTime)
        {
            if (rebusLoggerFactory == null)
            {
                throw new ArgumentNullException(nameof(rebusLoggerFactory));
            }
            if (asyncTaskFactory == null)
            {
                throw new ArgumentNullException(nameof(asyncTaskFactory));
            }

            _simpleRetryStrategySettings = simpleRetryStrategySettings ?? throw new ArgumentNullException(nameof(simpleRetryStrategySettings));
            _transport = transport ?? throw new ArgumentNullException(nameof(transport));
            _rebusTime = rebusTime ?? throw new ArgumentNullException(nameof(rebusTime));

            _log = rebusLoggerFactory.GetLogger <InMemErrorTracker>();

            _cleanupOldTrackedErrorsTask = asyncTaskFactory.Create(
                BackgroundTaskName,
                CleanupOldTrackedErrors,
                interval: TimeSpan.FromSeconds(10)
                );
        }
Example #42
0
 /// <summary>
 /// <para>Initializes the routes.</para>
 /// </summary>
 /// <returns>The transport.</returns>
 private void InitializeRoutes(ITransport transport)
 {
     this.Files   = new FilesRoutes(transport);
     this.Sharing = new SharingRoutes(transport);
     this.Users   = new UsersRoutes(transport);
 }
Example #43
0
 protected override ITransport UpgradeTransport(ITransport transport)
 {
     return(transport);
 }
Example #44
0
 public CambionConfiguration()
 {
     Transport  = new TransportConfiguration(this, a => _transport = a);
     Serializer = new SerializerConfiguration(this, a => _serializer = a);
 }
Example #45
0
        /// <summary>
        /// Receives an object from a transport.
        /// </summary>
        /// <param name="objectId"></param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to send notice of cancellation.</param>
        /// <param name="remoteTransport">The transport to receive from.</param>
        /// <param name="localTransport">Leave null to use the default cache.</param>
        /// <param name="onProgressAction">Action invoked on progress iterations.</param>
        /// <param name="onErrorAction">Action invoked on internal errors.</param>
        /// <param name="onTotalChildrenCountKnown">Action invoked once the total count of objects is known.</param>
        /// <returns></returns>
        public static async Task <Base> Receive(string objectId, CancellationToken cancellationToken, ITransport remoteTransport = null, ITransport localTransport = null, Action <ConcurrentDictionary <string, int> > onProgressAction = null, Action <string, Exception> onErrorAction = null, Action <int> onTotalChildrenCountKnown = null)
        {
            Log.AddBreadcrumb("Receive");

            var(serializer, settings) = GetSerializerInstance();

            var localProgressDict      = new ConcurrentDictionary <string, int>();
            var internalProgressAction = GetInternalProgressAction(localProgressDict, onProgressAction);

            localTransport = localTransport != null ? localTransport : new SQLiteTransport();
            localTransport.OnErrorAction     = onErrorAction;
            localTransport.OnProgressAction  = internalProgressAction;
            localTransport.CancellationToken = cancellationToken;

            serializer.ReadTransport     = localTransport;
            serializer.OnProgressAction  = internalProgressAction;
            serializer.OnErrorAction     = onErrorAction;
            serializer.CancellationToken = cancellationToken;

            // First we try and get the object from the local transport. If it's there, we assume all its children are there, and proceed with deserialisation.
            // This assumption is hard-wired into the SDK. Read below.
            var objString = localTransport.GetObject(objectId);

            if (objString != null)
            {
                // Shoot out the total children count
                var partial = JsonConvert.DeserializeObject <Placeholder>(objString);
                if (partial.__closure != null)
                {
                    onTotalChildrenCountKnown?.Invoke(partial.__closure.Count);
                }

                return(JsonConvert.DeserializeObject <Base>(objString, settings));
            }
            else if (remoteTransport == null)
            {
                Log.CaptureAndThrow(new SpeckleException($"Could not find specified object using the local transport, and you didn't provide a fallback remote from which to pull it."), SentryLevel.Error);
            }

            // If we've reached this stage, it means that we didn't get a local transport hit on our object, so we will proceed to get it from the provided remote transport.
            // This is done by copying itself and all its children from the remote transport into the local one.
            remoteTransport.OnErrorAction     = onErrorAction;
            remoteTransport.OnProgressAction  = internalProgressAction;
            remoteTransport.CancellationToken = cancellationToken;

            Log.AddBreadcrumb("RemoteHit");
            objString = await remoteTransport.CopyObjectAndChildren(objectId, localTransport, onTotalChildrenCountKnown);

            // Wait for the local transport to finish "writing" - in this case, it signifies that the remote transport has done pushing copying objects into it. (TODO: I can see some scenarios where latency can screw things up, and we should rather wait on the remote transport).
            await localTransport.WriteComplete();

            // Proceed to deserialise the object, now safely knowing that all its children are present in the local (fast) transport.
            return(JsonConvert.DeserializeObject <Base>(objString, settings));

            // Summary:
            // Basically, receiving an object (and all its subchildren) operates with two transports, one that is potentially slow, and one that is fast.
            // The fast transport ("localTransport") is used syncronously inside the deserialisation routine to get the value of nested references and set them. The slow transport ("remoteTransport") is used to get the raw data and populate the local transport with all necessary data for a successful deserialisation of the object.
            // Note: if properly implemented, there is no hard distinction between what is a local or remote transport; it's still just a transport. So, for example, if you want to receive an object without actually writing it first to a local transport, you can just pass a Server/S3 transport as a local transport.
            // This is not reccommended, but shows what you can do. Another tidbit: the local transport does not need to be disk-bound; it can easily be an in memory transport. In memory transports are the fastest ones, but they're of limited use for more
        }
Example #46
0
 public LoggingTransport(ITransport next)
     : base(next)
 {
 }
Example #47
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="transport">The message transport to use. The backend will dispose it when it gets disposed.</param>
 /// <param name="configuration">The configuration.</param>
 /// <param name="logger">The logger to use.</param>
 public GossipBackend(ITransport transport, GossipConfiguration configuration, ILogger logger = null)
     : this(transport, configuration, null, logger)
 {
 }
Example #48
0
        bool StartMove(Creature creature)
        {
            if (path == null || path.Empty())
            {
                return(false);
            }

            if (Stopped())
            {
                return(true);
            }

            bool transportPath = creature.GetTransport() != null;

            if (isArrivalDone)
            {
                if ((currentNode == path.Count - 1) && !repeating) // If that's our last waypoint
                {
                    float x = path[(int)currentNode].x;
                    float y = path[(int)currentNode].y;
                    float z = path[(int)currentNode].z;
                    float o = path[(int)currentNode].orientation;

                    if (!transportPath)
                    {
                        creature.SetHomePosition(x, y, z, o);
                    }
                    else
                    {
                        Transport trans = creature.GetTransport();
                        if (trans)
                        {
                            o -= trans.GetOrientation();
                            creature.SetTransportHomePosition(x, y, z, o);
                            trans.CalculatePassengerPosition(ref x, ref y, ref z, ref o);
                            creature.SetHomePosition(x, y, z, o);
                        }
                        else
                        {
                            transportPath = false;
                        }
                        // else if (vehicle) - this should never happen, vehicle offsets are const
                    }

                    creature.GetMotionMaster().Initialize();
                    return(false);
                }

                currentNode = (uint)((currentNode + 1) % path.Count);
            }

            WaypointData node = path.LookupByIndex((int)currentNode);

            isArrivalDone = false;

            creature.AddUnitState(UnitState.RoamingMove);

            MoveSplineInit init          = new MoveSplineInit(creature);
            Position       formationDest = new Position(node.x, node.y, node.z);

            //! If creature is on transport, we assume waypoints set in DB are already transport offsets
            if (transportPath)
            {
                init.DisableTransportPathTransformations();
                ITransport trans = creature.GetDirectTransport();
                if (trans != null)
                {
                    trans.CalculatePassengerPosition(ref formationDest.posX, ref formationDest.posY, ref formationDest.posZ, ref formationDest.Orientation);
                }
            }

            init.MoveTo(formationDest.posX, formationDest.posY, formationDest.posZ);

            //! Accepts angles such as 0.00001 and -0.00001, 0 must be ignored, default value in waypoint table
            if (node.orientation != 0 && node.delay != 0)
            {
                init.SetFacing(formationDest.Orientation);
            }

            switch (node.movetype)
            {
            case WaypointMoveType.Land:
                init.SetAnimation(AnimType.ToGround);
                break;

            case WaypointMoveType.Takeoff:
                init.SetAnimation(AnimType.ToFly);
                break;

            case WaypointMoveType.Run:
                init.SetWalk(false);
                break;

            case WaypointMoveType.Walk:
                init.SetWalk(true);
                break;
            }

            init.Launch();

            //Call for creature group update
            if (creature.GetFormation() != null && creature.GetFormation().getLeader() == creature)
            {
                creature.SetWalk(node.movetype != WaypointMoveType.Run);
                creature.GetFormation().LeaderMoveTo(formationDest.posX, formationDest.posY, formationDest.posZ);
            }

            return(true);
        }
Example #49
0
 protected virtual void OnException(ITransport sender, Exception command)
 {
     this.exceptionHandler(sender, command);
 }
Example #50
0
 /// <summary>
 /// Receives an object from a transport.
 /// </summary>
 /// <param name="objectId"></param>
 /// <param name="remoteTransport">The transport to receive from.</param>
 /// <param name="localTransport">Leave null to use the default cache.</param>
 /// <param name="onProgressAction">Action invoked on progress iterations.</param>
 /// <param name="onErrorAction">Action invoked on internal errors.</param>
 /// <param name="onTotalChildrenCountKnown">Action invoked once the total count of objects is known.</param>
 /// <returns></returns>
 public static Task <Base> Receive(string objectId, ITransport remoteTransport = null, ITransport localTransport = null, Action <ConcurrentDictionary <string, int> > onProgressAction = null, Action <string, Exception> onErrorAction = null, Action <int> onTotalChildrenCountKnown = null)
 {
     return(Receive(
                objectId,
                CancellationToken.None,
                remoteTransport,
                localTransport,
                onProgressAction,
                onErrorAction,
                onTotalChildrenCountKnown
                ));
 }
Example #51
0
 public static IBus CreateAndStartInMemoryBus(this BusFactory busFactory, TestPeerDirectory directory, ITransport transport)
 {
     return(busFactory.WithConfiguration("in-memory-bus", "Memory")
            .ConfigureContainer(cfg =>
     {
         cfg.ForSingletonOf <IPeerDirectory>().Use(directory);
         cfg.ForSingletonOf <ITransport>().Use(transport);
     }).CreateAndStartBus());
 }
Example #52
0
 public OnlineProtocol(ITransport transport)
 {
     this.transport = transport;
 }
Example #53
0
 public DelayOperationsTransportDecorator(ITransport transport)
 {
     _transport = transport;
 }
Example #54
0
 protected virtual void OnCommand(ITransport sender, Command command)
 {
     this.commandHandler(sender, command);
 }
Example #55
0
        private ITransport CreateTransport(I2PRouterInfo ri)
        {
            ITransport transport = null;

            try
            {
                I2PRouterAddress ra_ntcp = null;
                var ntcpaddr             = ri.Adresses.Where(a => (a.TransportStyle == "NTCP") &&
                                                             a.Options.Contains("host") &&
                                                             a.Options.Contains("port") &&
                                                             (RouterContext.Inst.UseIpV6 || a.Options["host"].Contains('.')));
                var a1 = ntcpaddr.Where(a => GetAddressFamiliy(a, "host") == System.Net.Sockets.AddressFamily.InterNetwork);
                if (a1.Any())
                {
                    ra_ntcp = a1.Random();
                }
                else
                {
                    a1 = ntcpaddr.Where(a => Dns.GetHostEntry(a.Options["host"]).AddressList.
                                        Any(aa => aa.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork));
                    if (a1.Any())
                    {
                        ra_ntcp = a1.Random();
                    }
                }

                I2PRouterAddress ra_ssu = null;
                var ssuaddr             = ri.Adresses.Where(a => (a.TransportStyle == "SSU") && a.Options.Contains("key"));
                a1 = ssuaddr.Where(a => GetAddressFamiliy(a, "host") == System.Net.Sockets.AddressFamily.InterNetwork ||
                                   GetAddressFamiliy(a, "ihost0") == System.Net.Sockets.AddressFamily.InterNetwork);
                if (a1.Any())
                {
                    ra_ssu = a1.Random();
                }
                else
                {
                    a1 = ntcpaddr.Where(a => Dns.GetHostEntry(a.Options["host"]).AddressList.
                                        Any(aa => aa.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork));
                    if (a1.Any())
                    {
                        ra_ssu = a1.Random();
                    }
                    else
                    {
                        a1 = ntcpaddr.Where(a => Dns.GetHostEntry(a.Options["ihost0"]).AddressList.
                                            Any(aa => aa.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork));
                        if (a1.Any())
                        {
                            ra_ssu = a1.Random();
                        }
                    }
                }

                I2PRouterAddress ra;

                //if ( ra_ntcp != null ) ra = ra_ntcp; else ra = ra_ssu;
                if (ra_ssu != null)
                {
                    ra = ra_ssu;
                }
                else
                {
                    ra = ra_ntcp;
                }

                if (ra == null)
                {
                    DebugUtils.LogDebug(() =>
                                        string.Format("TransportProvider: CreateTransport: No usable address found for {0}!", ri.Identity.IdentHash.Id32Short));
                    return(null);
                }

                switch (ra.TransportStyle.ToString())
                {
                case "SSU":
                    transport = SsuHost.AddSession(ra, ri.Identity);
                    break;

                case "NTCP":
                    transport = new NTCPClientOutgoing(ra, ri.Identity);
                    break;

                default:
                    throw new NotImplementedException();
                }

                DebugUtils.LogDebug(() =>
                                    string.Format("TransportProvider: Creating new {0} transport {2} to {1}",
                                                  ra.TransportStyle, ri.Identity.IdentHash.Id32Short, transport.DebugId));

                AddTransport(transport, ri.Identity.IdentHash);
                transport.Connect();

                var dstore = new DatabaseStoreMessage(RouterContext.Inst.MyRouterInfo);
                transport.Send(dstore);
            }
            catch (Exception ex)
            {
#if LOG_ALL_TRANSPORT
                DebugUtils.Log(ex);
                DebugUtils.Log("TransportProvider: CreateTransport stack trace: " + System.Environment.StackTrace);
#else
                DebugUtils.LogDebug(() => "TransportProvider: Exception [" + ex.GetType().ToString() + "] '" + ex.Message + "' to " +
                                    ri.Identity.IdentHash.Id32Short + ".");
#endif
                if (transport != null)
                {
                    Remove(transport);
                }
                throw;
            }

            return(transport);
        }
Example #56
0
        /// <summary>
        /// Handles all requests for <see cref="PersistentConnection"/>s.
        /// </summary>
        /// <param name="context">The <see cref="HostContext"/> for the current request.</param>
        /// <returns>A <see cref="Task"/> that completes when the <see cref="PersistentConnection"/> pipeline is complete.</returns>
        /// <exception cref="T:System.InvalidOperationException">
        /// Thrown if connection wasn't initialized.
        /// Thrown if the transport wasn't specified.
        /// Thrown if the connection id wasn't specified.
        /// </exception>
        public virtual Task ProcessRequestAsync(HostContext context)
        {
            if (!_initialized)
            {
                throw new InvalidOperationException("Connection not initialized.");
            }

            if (IsNegotiationRequest(context.Request))
            {
                return(ProcessNegotiationRequest(context));
            }

            _transport = GetTransport(context);

            if (_transport == null)
            {
                throw new InvalidOperationException("Protocol error: Unknown transport.");
            }

            string connectionId = _transport.ConnectionId;

            // If there's no connection id then this is a bad request
            if (String.IsNullOrEmpty(connectionId))
            {
                throw new InvalidOperationException("Protocol error: Missing connection id.");
            }

            var groups = new List <string>(_transport.Groups);

            Connection connection = CreateConnection(connectionId, groups, context.Request);

            Connection = connection;
            Groups     = new GroupManager(connection, DefaultSignal);

            _transport.TransportConnected = () =>
            {
                var command = new ServerCommand
                {
                    Type  = ServerCommandType.RemoveConnection,
                    Value = connectionId
                };

                return(_serverMessageHandler.SendCommand(command));
            };

            _transport.Connected = () =>
            {
                return(OnConnectedAsync(context.Request, connectionId));
            };

            _transport.Reconnected = () =>
            {
                return(OnReconnectedAsync(context.Request, groups, connectionId));
            };

            _transport.Received = data =>
            {
                return(OnReceivedAsync(context.Request, connectionId, data));
            };

            _transport.Error = OnErrorAsync;

            _transport.Disconnected = () =>
            {
                return(OnDisconnectAsync(connectionId));
            };

            return(_transport.ProcessRequest(connection) ?? TaskAsyncHelper.Empty);
        }
Example #57
0
 public void HandleIncomingTransport(ITransport transport)
 {
     Provider.HandleTransport(transport);
 }
Example #58
0
        private static bool Send(I2PIdentHash dest, I2NPMessage data, int reclvl)
        {
            ITransport transp = null;

            try
            {
                if (dest == RouterContext.Inst.MyRouterIdentity.IdentHash)
                {
                    DebugUtils.LogDebug(() => "TransportProvider: Loopback " + data.ToString());
                    TransportProvider.Inst.DistributeIncomingMessage(null, data.Header16);
                    return(true);
                }

                if (TransportProvider.Inst.CurrentlyUnknownRouters.Contains(dest))
                {
                    TransportProvider.Inst.CurrentlyUnknownRouters.Add(dest, data);
                    return(true);
                }

                transp = TransportProvider.Inst.GetEstablishedTransport(dest, false);
                if (transp != null)
                {
                    transp.Send(data);
                    return(true);
                }

                if (NetDb.Inst.Contains(dest))
                {
                    transp = TransportProvider.Inst.GetTransport(dest);
                    if (transp == null)
                    {
                        throw new ArgumentException("Unable to contact " + dest.ToString());
                    }
                    transp.Send(data);
                }
                else
                {
                    if (TransportProvider.Inst.CurrentlyUnresolvableRouters.Contains(dest))
                    {
                        throw new ArgumentException("Unable to resolve " + dest.ToString());
                    }

                    TransportProvider.Inst.CurrentlyUnknownRouters.Add(dest, data);
                }
            }
            catch (FailedToConnectException ex)
            {
                if (transp != null)
                {
                    TransportProvider.Inst.Remove(transp);
                }

                if (dest != null && NetDb.Inst != null)
                {
                    NetDb.Inst.Statistics.FailedToConnect(dest);
                }
                DebugUtils.LogDebug(() => "TransportProvider.Send: " + (transp == null ? "<>" : transp.DebugId) +
                                    " Exception " + ex.GetType().ToString() + ", " + ex.Message);

                throw;
            }
            catch (EndOfStreamEncounteredException ex)
            {
                TransportProvider.Inst.Remove(transp);

                DebugUtils.LogDebug(() => "TransportProvider.Send: Connection " + (transp == null ? "<>" : transp.DebugId) +
                                    " closed exception: " + ex.GetType().ToString() + ", " + ex.Message);

                if (reclvl > 1 || !Send(dest, data, reclvl + 1))
                {
                    DebugUtils.LogDebug(() => "TransportProvider.Send: Recconnection failed to " + dest.Id32Short + ", reclvl: " + reclvl.ToString() + ".");
                    throw;
                }
            }
            catch (RouterUnresolvableException ex)
            {
                if (dest != null)
                {
                    NetDb.Inst.Statistics.DestinationInformationFaulty(dest);
                }
                DebugUtils.LogDebug(() => "TransportProvider.Send: Unresolvable router: " + ex.Message);

                throw;
            }
            catch (Exception ex)
            {
                if (transp != null)
                {
                    TransportProvider.Inst.Remove(transp);
                }

                if (dest != null)
                {
                    NetDb.Inst.Statistics.DestinationInformationFaulty(dest);
                }
                DebugUtils.LogDebug(() => "TransportProvider.Send: Exception " + ex.GetType().ToString() + ", " + ex.Message);

                throw;
            }
            return(true);
        }
Example #59
0
 public IntroducerOfTransportInstability(ITransport innerTransport, int failFactor)
 {
     _innerTransport = innerTransport;
     _failFactor     = failFactor;
 }
Example #60
0
        /// <summary>
        /// Called from the HTTPManager's OnUpdate function every frame. It's main function is to send out heartbeat messages.
        /// </summary>
        void IHeartbeat.OnHeartbeatUpdate(TimeSpan dif)
        {
            switch (State)
            {
            case States.Opening:
                if (DateTime.UtcNow - ConnectionStarted >= Options.Timeout)
                {
                    (this as IManager).EmitError(SocketIOErrors.Internal, "Connection timed out!");
                    (this as IManager).EmitEvent("connect_error");
                    (this as IManager).EmitEvent("connect_timeout");
                    (this as IManager).TryToReconnect();
                }

                break;

            case States.Reconnecting:
                if (ReconnectAt != DateTime.MinValue && DateTime.UtcNow >= ReconnectAt)
                {
                    (this as IManager).EmitEvent("reconnect_attempt");
                    (this as IManager).EmitEvent("reconnecting");

                    Open();
                }
                break;

            case States.Open:
                ITransport trans = null;

                // Select transport to use
                if (Transport != null && Transport.State == TransportStates.Open)
                {
                    trans = Transport;
                }

                // not yet open?
                if (trans == null || trans.State != TransportStates.Open)
                {
                    return;
                }

                // Start to poll the server for events
                trans.Poll();

                // Start to send out unsent packets
                SendOfflinePackets();

                // First time we reached this point. Set the LastHeartbeat to the current time, 'cause we are just opened.
                if (LastHeartbeat == DateTime.MinValue)
                {
                    LastHeartbeat = DateTime.UtcNow;
                    return;
                }

                // It's time to send out a ping event to the server
                if (DateTime.UtcNow - LastHeartbeat > Handshake.PingInterval)
                {
                    (this as IManager).SendPacket(new Packet(TransportEventTypes.Ping, SocketIOEventTypes.Unknown, "/", string.Empty));

                    LastHeartbeat = DateTime.UtcNow;
                }

                // No pong event received in the given time, we are disconnected.
                if (DateTime.UtcNow - LastPongReceived > Handshake.PingTimeout)
                {
                    (this as IManager).TryToReconnect();
                }

                break;     // case States.Open:
            }
        }