/// <summary>
        /// Creates <paramref name="parallelCount"/> write sessions simultaneously over
        /// <paramref name="iterations"/> number of iterations.
        /// </summary>
        private async Task CreateReleaseWriteSessions(
            SessionPool pool,
            SpannerClient client,
            int iterations,
            int parallelCount)
        {
            // We yield to increase contention among parallel tasks that are kicked off.
            // This increases the amount of work they are doing on another thread.
            await Task.Yield();

            for (var i = 0; i < iterations; i++)
            {
                var readWriteOptions = new TransactionOptions {
                    ReadWrite = new TransactionOptions.Types.ReadWrite()
                };
                var writeSessions = await Task.WhenAll(
                    DuplicateTaskAsync(() => CreateSessionAsync(pool, client, readWriteOptions), parallelCount));

                await Task.Delay(TimeSpan.FromMilliseconds(10));

                foreach (var session in writeSessions)
                {
                    var transaction = await TransactionPool.BeginPooledTransactionAsync(client, session, readWriteOptions);

                    await TransactionPool.CommitAsync(transaction, session, new Mutation[0], SpannerOptions.Instance.Timeout, CancellationToken.None);

                    pool.ReleaseToPool(client, session);
                }
            }
        }
        /// <summary>
        /// Creates <paramref name="parallelCount"/> read sessions simultaneously over
        /// <paramref name="iterations"/> number of iterations.
        /// </summary>
        private async Task CreateReleaseReadSessions(
            SessionPool pool,
            SpannerClient client,
            int iterations,
            int parallelCount)
        {
            // We yield to increase contention among parallel tasks that are kicked off.
            // This increases the amount of work they are doing on another thread.
            await Task.Yield();

            for (var i = 0; i < iterations; i++)
            {
                var readOptions = new TransactionOptions {
                    ReadOnly = new TransactionOptions.Types.ReadOnly()
                };
                var readSessions = await Task.WhenAll(
                    DuplicateTaskAsync(() => CreateSessionAsync(pool, client, readOptions), parallelCount));

                await Task.Delay(TimeSpan.FromMilliseconds(10));

                foreach (var session in readSessions)
                {
                    pool.ReleaseToPool(client, session);
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 转发扫水结果到客户端
        /// </summary>
        /// <param name="sessionId">发送端</param>
        /// <param name="content">扫水结果</param>
        /// <returns></returns>
        public static MQActionVoidResult CollectCompletedToClient(string sessionId, CollectResult content)
        {
            var session = SessionPool.GetClientsGroup(ClientTypeEnum.Client);

            if (session != null)
            {
                foreach (var item in session)
                {
                    if (item.Key == content.ClientSessionID)
                    {
                        MQRouterSendQueue.PushCollectCompleted(item.Key, content);
                        break;
                    }
                }

                return(new MQActionVoidResult()
                {
                    IsOK = true
                });
            }
            else
            {
                return(new MQActionVoidResult()
                {
                    IsOK = false, ErrorMsg = "未找到出货客户端"
                });
            }
        }
        public async Task MaxActiveViolation_WaitOnResourcesExhausted_Blocks()
        {
            using (var pool = new SessionPool())
            {
                pool.Options.WaitOnResourcesExhausted = true;
                pool.Options.MaximumActiveSessions    = 2;

                var client   = new FakeClient();
                var session1 = await CreateSessionAsync(pool, client);

                var session2 = await CreateSessionAsync(pool, client);

                var createTask = CreateSessionAsync(pool, client);

                await Task.WhenAll(createTask, ReleaseAfterDelay(session1));

                Assert.Same(session1, await createTask);

                async Task ReleaseAfterDelay(Session session)
                {
                    await Task.Delay(TimeSpan.FromMilliseconds(10));

                    pool.ReleaseToPool(client, session);
                }
            }
        }
            public void ShouldLogInUseAndAvailableSessionIds()
            {
                var mockLogger = new Mock <ILogger>();
                var mock       = new Mock <IPooledSession>();

                mock.Setup(x => x.IsHealthy).Returns(true);
                var id            = Guid.NewGuid();
                var inUseSessions = new Dictionary <Guid, IPooledSession>();

                inUseSessions.Add(id, mock.Object);

                var sessions = new Queue <IPooledSession>();
                var mock1    = new Mock <IPooledSession>();

                mock1.Setup(x => x.IsHealthy).Returns(true);

                sessions.Enqueue(mock1.Object);

                var pool = new SessionPool(sessions, inUseSessions, logger: mockLogger.Object);

                pool.Dispose();

                mockLogger.Verify(x => x.Info(It.Is <string>(actual => actual.StartsWith("Disposing In Use"))),
                                  Times.Once);
                mockLogger.Verify(x => x.Info(It.Is <string>(actual => actual.StartsWith("Disposing Available"))),
                                  Times.Once);
            }
            public void ShouldNotExceedIdleLimit()
            {
                var mock = new Mock <IConnection>();

                mock.Setup(x => x.IsOpen).Returns(true);

                var config = new Config {
                    MaxIdleSessionPoolSize = 2
                };
                var pool = new SessionPool(TestUri, AuthTokens.None, null, config, mock.Object);

                var sessions = new List <ISession>();

                for (var i = 0; i < 4; i++)
                {
                    sessions.Add(pool.GetSession());
                    pool.NumberOfAvailableSessions.Should().BeLessOrEqualTo(2);
                }

                foreach (var session in sessions)
                {
                    session.Dispose();
                    pool.NumberOfAvailableSessions.Should().BeLessOrEqualTo(2);
                }

                pool.NumberOfAvailableSessions.Should().Be(2);
            }
            public void ShouldReuseHealthySessionWhenHealthySessionInQueue()
            {
                var sessions    = new Queue <IPooledSession>();
                var healthyMock = new Mock <IPooledSession>();

                healthyMock.Setup(x => x.IsHealthy).Returns(true);
                var unhealthyMock = new Mock <IPooledSession>();

                unhealthyMock.Setup(x => x.IsHealthy).Returns(false);

                sessions.Enqueue(unhealthyMock.Object);
                sessions.Enqueue(healthyMock.Object);
                var pool = new SessionPool(sessions, null);

                pool.NumberOfAvailableSessions.Should().Be(2);
                pool.NumberOfInUseSessions.Should().Be(0);

                var session = pool.GetSession();

                pool.NumberOfAvailableSessions.Should().Be(0);
                pool.NumberOfInUseSessions.Should().Be(1);
                unhealthyMock.Verify(x => x.Reset(), Times.Never);
                unhealthyMock.Verify(x => x.Close(), Times.Once);
                healthyMock.Verify(x => x.Reset(), Times.Once);
                session.Should().Be(healthyMock.Object);
            }
            public void ShouldReleaseAll()
            {
                var mock = new Mock <IPooledSession>();

                mock.Setup(x => x.IsHealthy).Returns(true);
                var id            = Guid.NewGuid();
                var inUseSessions = new Dictionary <Guid, IPooledSession>();

                inUseSessions.Add(id, mock.Object);

                var sessions = new Queue <IPooledSession>();
                var mock1    = new Mock <IPooledSession>();

                mock1.Setup(x => x.IsHealthy).Returns(true);

                sessions.Enqueue(mock1.Object);

                var pool = new SessionPool(sessions, inUseSessions);

                pool.NumberOfAvailableSessions.Should().Be(1);
                pool.NumberOfInUseSessions.Should().Be(1);

                pool.Dispose();

                pool.NumberOfAvailableSessions.Should().Be(0);
                pool.NumberOfInUseSessions.Should().Be(0);
            }
            public void ShouldCreateNewSessionWhenQueueOnlyContainsUnhealthySessions()
            {
                var mock          = new Mock <IConnection>();
                var sessions      = new Queue <IPooledSession>();
                var unhealthyId   = Guid.NewGuid();
                var unhealthyMock = new Mock <IPooledSession>();

                unhealthyMock.Setup(x => x.IsHealthy).Returns(false);
                unhealthyMock.Setup(x => x.Id).Returns(unhealthyId);

                sessions.Enqueue(unhealthyMock.Object);
                var pool = new SessionPool(sessions, null, mock.Object);

                pool.NumberOfAvailableSessions.Should().Be(1);
                pool.NumberOfInUseSessions.Should().Be(0);

                var session = pool.GetSession();

                pool.NumberOfAvailableSessions.Should().Be(0);
                pool.NumberOfInUseSessions.Should().Be(1);
                unhealthyMock.Verify(x => x.Reset(), Times.Never);
                unhealthyMock.Verify(x => x.Close(), Times.Once);

                session.Should().NotBeNull();
                ((IPooledSession)session).Id.Should().NotBe(unhealthyId);
            }
Exemplo n.º 10
0
        private void Accept(SaeaAwaiter awaiter, SocketError socketError)
        {
            if (socketError == SocketError.Success)
            {
                var acceptedSocket = awaiter.Saea.AcceptSocket;
                var session        = SessionPool.Take();
                session.Attach(acceptedSocket);
                this.TcpSocketSaeaSessions.Add(session);
                this.CompletetionNotify?.Invoke(TcpSocketCompletionNotify.OnConnected, session);

                session.StartProcess();
            }
            else
            {
                LogHelper.WriteLog("server_accept-fail");
            }

            if (!this._isRuning)
            {
                return;
            }

            awaiter.Saea.AcceptSocket = null;
            SaeaExHelper.AcceptAsync(_listener, awaiter, Accept);
        }
        public void ConnectToServer(IPEndPoint ipEndPoint)
        {
            Socket socket  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var    awaiter = HandlerSaeaPool.Take();

            awaiter.Saea.RemoteEndPoint = ipEndPoint;

            SaeaExHelper.ConnectAsync(socket, awaiter, (a, e) =>
            {
                HandlerSaeaPool.Return(a);
                var session = SessionPool.Take();
                if (e != SocketError.Success)
                {
                    LogHelper.WriteLog("client_connect-error");
                    CompletetionNotify?.Invoke(TcpSessionNotify.OnClosed, session);
                    SessionPool.Return(session);
                    return;
                }
                TcpSocketSaeaSessions.Add(session);

                session.Attach(socket);
                CompletetionNotify?.Invoke(TcpSessionNotify.OnConnected, session);
                session.StartProcess();
            });
        }
Exemplo n.º 12
0
            private static TargetedSessionPool CreatePool(bool acquireSessionsImmediately)
            {
                var client = new SessionTestingSpannerClient();

                client.Scheduler.RealTimeTimeout = TimeSpan.FromSeconds(15);
                // Fixed session pool options so we can hard-code values without worrying about the defaults changing
                var options = new SessionPoolOptions
                {
                    IdleSessionRefreshDelay         = TimeSpan.FromMinutes(15),
                    MaintenanceLoopDelay            = TimeSpan.FromSeconds(0),   // Disable automatic pool maintenance
                    PoolEvictionDelay               = TimeSpan.FromMinutes(100), // Deliberately not a multiple of 15
                    SessionEvictionJitter           = RetrySettings.NoJitter,
                    SessionRefreshJitter            = RetrySettings.NoJitter,
                    MaximumActiveSessions           = 100,
                    MaximumConcurrentSessionCreates = 20,
                    CreateSessionMaximumBatchSize   = 5,
                    MinimumPooledSessions           = 10,
                    Timeout = TimeSpan.FromSeconds(60),
                    WaitOnResourcesExhausted = ResourcesExhaustedBehavior.Block,
                    WriteSessionsFraction    = 0.2
                };
                var parent = new SessionPool(client, options);

                return(new TargetedSessionPool(parent, s_databaseName, acquireSessionsImmediately));
            }
Exemplo n.º 13
0
        public async Task GetStatisticsSnapshot_MultipleDatabases()
        {
            var client  = new SessionTestingSpannerClient();
            var options = new SessionPoolOptions
            {
                MinimumPooledSessions = 10,
            };
            var sessionPool      = new SessionPool(client, options);
            var acquisitionTask1 = sessionPool.AcquireSessionAsync(s_sampleDatabaseName, new TransactionOptions(), default);
            var acquisitionTask2 = sessionPool.AcquireSessionAsync(s_sampleDatabaseName2, new TransactionOptions(), default);

            // Wait a little in real time because session creation tasks
            // are started in a controlled fire and forget manner.
            // Let's give time for stats to be updated.
            await Task.Delay(TimeSpan.FromMilliseconds(250));

            var stats = sessionPool.GetStatisticsSnapshot();

            Assert.Equal(2, stats.PerDatabaseStatistics.Count);
            Assert.Equal(2, stats.TotalActiveSessionCount);
            Assert.Equal(0, stats.TotalReadPoolCount);
            // We've asked for 2 sessions, and the databases "know" they need 10 in the pool (each), so
            // there will be 22 in-flight requests in total.
            Assert.Equal(22, stats.TotalInFlightCreationCount);

            Assert.Contains(stats.PerDatabaseStatistics, s => s.DatabaseName == s_sampleDatabaseName);
            Assert.Contains(stats.PerDatabaseStatistics, s => s.DatabaseName == s_sampleDatabaseName2);

            // xUnit waits until tasks registered in its synchronization context have completed before considering the
            // test itself complete, so we need to let the pool complete the acquisition tasks.
            await client.Scheduler.RunAsync(TimeSpan.FromMinutes(2));
        }
Exemplo n.º 14
0
            public static SessionInfo From(ISocketClient socketClient, SessionPool sessionPool)
            {
                var session = new Session(socketClient);
                var proxy   = new SessionProxy(session, sessionPool);

                return(new SessionInfo(session, proxy));
            }
Exemplo n.º 15
0
 public TransferPromptListAction(TransferPromptModel model, TransferPromptController controller,
                                 SessionPool source, SessionPool destination, TransferItem directory, Transfer transfer, TransferItemCache cache)
     : base(
         controller, source, destination,
         new InnerTransferPromptListWorker(model, controller, transfer, directory, cache))
 {
 }
        /// <summary>
        /// Creates <paramref name="parallelCount"/> read sessions simultaneously over
        /// <paramref name="iterations"/> number of iterations.
        /// </summary>
        private async Task CreateReleaseReadSessions(
            SessionPool pool,
            SpannerClient client,
            int iterations,
            int parallelCount)
        {
            // We yield to increase contention among parallel tasks that are kicked off.
            // This increases the amount of work they are doing on another thread.
            await Task.Yield();

            for (var i = 0; i < iterations; i++)
            {
                var readOptions = new TransactionOptions {
                    ReadOnly = new TransactionOptions.Types.ReadOnly()
                };
                var readSessions = await Task.WhenAll(
                    DuplicateTaskAsync(
                        () =>
                        pool.CreateSessionFromPoolAsync(
                            client, s_defaultName.ProjectId,
                            s_defaultName.InstanceId, s_defaultName.DatabaseId, readOptions,
                            CancellationToken.None),
                        parallelCount))
                                   .ConfigureAwait(false);

                await Task.Delay(TimeSpan.FromMilliseconds(10)).ConfigureAwait(false);

                foreach (var session in readSessions)
                {
                    pool.ReleaseToPool(client, session);
                }
            }
        }
Exemplo n.º 17
0
        public async Task MaxActiveViolationThrows()
        {
            using (var pool = new SessionPool())
            {
                pool.Options.WaitOnResourcesExhausted = false;
                pool.Options.MaximumActiveSessions    = 2;
                var exceptionThrown = false;

                var client = CreateMockClient();
                await pool.CreateSessionFromPoolAsync(
                    client.Object, s_defaultName.ProjectId,
                    s_defaultName.InstanceId, s_defaultName.DatabaseId, null, CancellationToken.None)
                .ConfigureAwait(false);

                await pool.CreateSessionFromPoolAsync(
                    client.Object, s_defaultName.ProjectId,
                    s_defaultName.InstanceId, s_defaultName.DatabaseId, null, CancellationToken.None)
                .ConfigureAwait(false);

                try
                {
                    await pool.CreateSessionFromPoolAsync(
                        client.Object, s_defaultName.ProjectId,
                        s_defaultName.InstanceId, s_defaultName.DatabaseId, null, CancellationToken.None)
                    .ConfigureAwait(false);
                }
                catch (RpcException e)
                {
                    Assert.Equal(StatusCode.ResourceExhausted, e.Status.StatusCode);
                    exceptionThrown = true;
                }

                Assert.True(exceptionThrown);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// 投注端退出了,注销资源,通知他的控盘端下线
        /// </summary>
        public static void RemoveBetServer(Session session)
        {
            if (AvailableBetServers.ContainsKey(session.ClientId))
            {
                int value;
                AvailableBetServers.TryRemove(session.ClientId, out value);
            }

            // 通知该服务端影响到的一批客户端下线
            var allClients = SessionPool.GetClientsGroup(ClientTypeEnum.Client);

            if (allClients.Count == 0)
            {
                return;
            }
            var clientIds = allClients.Keys.ToArray();

            foreach (var clientId in clientIds)
            {
                if (allClients[clientId].BetServerId == session.ClientId)
                {
                    MQRouterSendQueue.PushBetServerClose(clientId);
                }
            }
        }
Exemplo n.º 19
0
        public async Task MaxPoolSizeNotViolated()
        {
            using (var pool = new SessionPool())
            {
                pool.Options.MaximumPooledSessions = 2;

                var client   = CreateMockClient();
                var sessions = await Task.WhenAll(
                    pool.CreateSessionFromPoolAsync(
                        client.Object, s_defaultName.ProjectId,
                        s_defaultName.InstanceId, s_defaultName.DatabaseId, null, CancellationToken.None),
                    pool.CreateSessionFromPoolAsync(
                        client.Object, s_defaultName.ProjectId,
                        s_defaultName.InstanceId, s_defaultName.DatabaseId, null, CancellationToken.None),
                    pool.CreateSessionFromPoolAsync(
                        client.Object, s_defaultName.ProjectId,
                        s_defaultName.InstanceId, s_defaultName.DatabaseId, null, CancellationToken.None))
                               .ConfigureAwait(false);

                pool.ReleaseToPool(client.Object, sessions[0]);
                pool.ReleaseToPool(client.Object, sessions[1]);
                pool.ReleaseToPool(client.Object, sessions[2]);

                Assert.Equal(
                    2, pool.GetPoolSize(
                        client.Object, s_defaultName.ProjectId,
                        s_defaultName.InstanceId, s_defaultName.DatabaseId));
            }
        }
Exemplo n.º 20
0
        public async Task ClientsHaveDifferentPools()
        {
            using (var pool = new SessionPool())
            {
                var client1 = CreateMockClient();
                var client2 = CreateMockClient();

                var session = await pool.CreateSessionFromPoolAsync(
                    client1.Object, s_defaultName.ProjectId,
                    s_defaultName.InstanceId, s_defaultName.DatabaseId, null, CancellationToken.None)
                              .ConfigureAwait(false);

                pool.ReleaseToPool(client1.Object, session);

                var session2 = await pool.CreateSessionFromPoolAsync(
                    client2.Object, s_defaultName.ProjectId,
                    s_defaultName.InstanceId, s_defaultName.DatabaseId, null, CancellationToken.None)
                               .ConfigureAwait(false);

                Assert.NotSame(session, session2);
                Assert.Equal(2, _createdSessions.Count);
                Assert.Equal(1, _createdSessions[client1].Count);
                Assert.Equal(1, _createdSessions[client2].Count);
            }
        }
Exemplo n.º 21
0
        public async Task MaxActiveViolationBlocks()
        {
            using (var pool = new SessionPool())
            {
                pool.Options.WaitOnResourcesExhausted = true;
                pool.Options.MaximumActiveSessions    = 2;

                var client   = CreateMockClient();
                var session1 = await pool.CreateSessionFromPoolAsync(
                    client.Object, s_defaultName.ProjectId,
                    s_defaultName.InstanceId, s_defaultName.DatabaseId, null, CancellationToken.None)
                               .ConfigureAwait(false);

                await pool.CreateSessionFromPoolAsync(
                    client.Object, s_defaultName.ProjectId,
                    s_defaultName.InstanceId, s_defaultName.DatabaseId, null, CancellationToken.None)
                .ConfigureAwait(false);

                async Task ReleaseTask()
                {
                    await Task.Delay(TimeSpan.FromMilliseconds(10));

                    pool.ReleaseToPool(client.Object, session1);
                }

                var createTask = pool.CreateSessionFromPoolAsync(
                    client.Object, s_defaultName.ProjectId,
                    s_defaultName.InstanceId, s_defaultName.DatabaseId, null, CancellationToken.None);

                await Task.WhenAll(createTask, ReleaseTask()).ConfigureAwait(false);

                Assert.Same(session1, createTask.ResultWithUnwrappedExceptions());
            }
        }
Exemplo n.º 22
0
 private CommandController(WindowController parent, SessionPool session, ICommandView view)
 {
     View            = view;
     _parent         = parent;
     _session        = session;
     View.SendEvent += View_SendEvent;
 }
Exemplo n.º 23
0
        void LockConflict(SessionBase sharedReadSession)
        {
            string      host        = null;
            Random      r           = new Random(5);
            SessionPool sessionPool = new SessionPool(3, () => new ServerClientSession(systemDir, host, 2000, false));

            try
            {
                int         iCounter   = 0;
                int         sessionId1 = -1;
                SessionBase session1   = null;
                for (int i = 0; i < 50; i++)
                {
                    try
                    {
                        session1 = sessionPool.GetSession(out sessionId1);
                        session1.BeginUpdate();
                        Dokument Doc_A = new Dokument();
                        Doc_A.Name = "Test A";
                        session1.Persist(Doc_A);
                        Console.WriteLine(Doc_A.ToString());
                        int         sessionId2 = -1;
                        SessionBase session2   = null;
                        try
                        {
                            session2 = sessionPool.GetSession(out sessionId2);
                            session2.BeginUpdate();
                            Dokument Doc_B = new Dokument();
                            Doc_B.Name = "Test_B";
                            session2.Persist(Doc_B);
                            Console.WriteLine(Doc_B.ToString());
                            session2.Commit();
                        }
                        finally
                        {
                            sessionPool.FreeSession(sessionId2, session2);
                        }
                        session1.Commit();
                        sharedReadSession.ForceDatabaseCacheValidation();
                        session1.BeginRead();
                        ulong ct = session1.AllObjects <Dokument>(false).Count;
                        Console.WriteLine("Number of Dokument found by normal session: " + ct);
                        session1.Commit();
                        ct = sharedReadSession.AllObjects <Dokument>(false).Count;
                        Console.WriteLine("Number of Dokument found by shared read session: " + ct);
                    }
                    finally
                    {
                        sessionPool.FreeSession(sessionId1, session1);
                    }
                    iCounter++;
                    Console.WriteLine(" -> " + iCounter.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
Exemplo n.º 24
0
 public SessionProxy(
     Session session,
     SessionPool pool)
 {
     _pool    = pool;
     _session = session;
 }
Exemplo n.º 25
0
        /// <summary>
        /// 客户端注销
        /// </summary>
        /// <param name="session"></param>
        /// <param name="oldUserName"></param>
        public static void RemoveClients(Session session, string oldUserName = null)
        {
            string betServerId = session.BetServerId;

            if (string.IsNullOrEmpty(betServerId) || SessionPool.GetByClientId(betServerId, ClientTypeEnum.Bet) == null)
            {
                return;
            }

            //// 通知投注端清理投注账号的资源
            //List<WebsiteAccountDetail> websiteAccounts =
            //    WebsiteAccountService.Instance.GetAccountListByMemberId(session);
            //if (websiteAccounts != null && websiteAccounts.Count > 0)
            //{
            //    foreach (var account in websiteAccounts)
            //    {
            //        MQRouterSendQueue.QuitOut(betServerId, new WebsiteAccountContract()
            //        {
            //            WebsiteEnum = account.WebsiteEnum,
            //            UserName = account.UserName
            //        });
            //    }
            //}

            // 释放一个控盘端可用额
            if (AvailableBetServers.ContainsKey(betServerId))
            {
                AvailableBetServers[betServerId] -= 1;
            }
        }
 internal TcpSocketSaeaFullBased(
     TcpSocketConfigurationBase configuration,
     SaeaAwaiterPool handlerSaeaPool,
     SessionPool sessionPool,
     NotifyEventHandler <TcpSessionNotify, TcpSocketSaeaSession> notifyEventHandler,
     TcpSocketSaeaEngineBased agent)
     : base(notifyEventHandler, configuration, handlerSaeaPool, sessionPool, agent)
     => CompletedBuffer = new byte[configuration.ReceiveBufferSize];
Exemplo n.º 27
0
 public FilterAction(TransferPromptModel model, TransferPromptController controller,
                     SessionPool source, SessionPool destination,
                     Transfer transfer, TransferAction action, TransferItemCache cache)
     : base(
         controller, source,
         new InnerTransferPromptFilterWorker(model, controller, transfer, action, cache))
 {
 }
Exemplo n.º 28
0
 public GeneratedSerializerTests()
 {
     this.serviceProvider = new ServiceCollection()
                            .AddHagar(hagar => hagar.AddAssembly(typeof(GeneratedSerializerTests).Assembly))
                            .BuildServiceProvider();
     this.codecProvider = this.serviceProvider.GetRequiredService <ITypedCodecProvider>();
     this.sessionPool   = this.serviceProvider.GetRequiredService <SessionPool>();
 }
Exemplo n.º 29
0
 private static bool CheckForSessionExpiredError(this RpcException rpcException, Func <Session> sessionFunc)
 {
     if (rpcException.IsSessionExpiredError())
     {
         SessionPool.MarkSessionExpired(sessionFunc());
     }
     return(false);
 }
Exemplo n.º 30
0
 public void Dispose()
 {
     if (null != sessionPool)
     {
         sessionPool.Dispose();
         sessionPool = null;
     }
 }
Exemplo n.º 31
0
        private void Initialize()
        {
            _bufferManager = new GrowingByteBufferManager(_configuration.InitialPooledBufferCount, _configuration.ReceiveBufferSize);

            _acceptSaeaPool = new SaeaPool(16, 32,
                () =>
                {
                    var saea = new SaeaAwaitable();
                    return saea;
                },
                (saea) =>
                {
                    try
                    {
                        saea.Saea.AcceptSocket = null;
                        saea.Saea.SetBuffer(0, 0);
                        saea.Saea.RemoteEndPoint = null;
                        saea.Saea.SocketFlags = SocketFlags.None;
                    }
                    catch (Exception ex)
                    {
//                        _log.Error(ex.Message, ex);
                    }
                });
            _handleSaeaPool = new SaeaPool(1024, int.MaxValue,
                () =>
                {
                    var saea = new SaeaAwaitable();
                    return saea;
                },
                (saea) =>
                {
                    try
                    {
                        saea.Saea.AcceptSocket = null;
                        saea.Saea.SetBuffer(EmptyArray, 0, 0);
                        saea.Saea.RemoteEndPoint = null;
                        saea.Saea.SocketFlags = SocketFlags.None;
                    }
                    catch (Exception ex)
                    {
//                        _log.Error(ex.Message, ex);
                    }
                });
            _sessionPool = new SessionPool(1024, int.MaxValue,
                () =>
                {
                    var session = new TcpSocketSaeaSession(_configuration, _bufferManager, _handleSaeaPool, _dispatcher, this);
                    return session;
                },
                (session) =>
                {
                    try
                    {
                        session.Clear();
                    }
                    catch (Exception ex)
                    {
//                        _log.Error(ex.Message, ex);
                    }
                });
        }
Exemplo n.º 32
0
 void LockConflict(SessionBase sharedReadSession)
 {
   string host = null;
   Random r = new Random(5);
   SessionPool sessionPool = new SessionPool(3, () => new ServerClientSession(systemDir, host, 2000, false));
   try
   {
     int iCounter = 0;
     int sessionId1 = -1;
     SessionBase session1 = null;
     for (int i = 0; i < 50; i++)
     {
       try
       {
         session1 = sessionPool.GetSession(out sessionId1);
         session1.BeginUpdate();
         Dokument Doc_A = new Dokument();
         Doc_A.Name = "Test A";
         session1.Persist(Doc_A);
         Console.WriteLine(Doc_A.ToString());
         int sessionId2 = -1;
         SessionBase session2 = null;
         try
         {
           session2 = sessionPool.GetSession(out sessionId2);
           session2.BeginUpdate();
           Dokument Doc_B = new Dokument();
           Doc_B.Name = "Test_B";
           session2.Persist(Doc_B);
           Console.WriteLine(Doc_B.ToString());
           session2.Commit();
         }
         finally
         {
           sessionPool.FreeSession(sessionId2, session2);
         }
         session1.Commit();
         sharedReadSession.ForceDatabaseCacheValidation();
         session1.BeginRead();
         ulong ct = session1.AllObjects<Dokument>(false).Count;
         Console.WriteLine("Number of Dokument found by normal session: " + ct);
         session1.Commit();
         ct = sharedReadSession.AllObjects<Dokument>(false).Count;
         Console.WriteLine("Number of Dokument found by shared read session: " + ct);
       }
       finally
       {
         sessionPool.FreeSession(sessionId1, session1);
       }
       iCounter++;
       Console.WriteLine(" -> " + iCounter.ToString());
     }
   }
   catch (Exception ex)
   {
     Console.WriteLine(ex.Message);
     throw;
   }
 }