Ejemplo n.º 1
0
        protected bool Index <T>(string _DefaultIndex, T data, string route, string id = "") where T : class
        {
            IndexRequest <object> req = new IndexRequest <object>(_DefaultIndex, typeof(T));

            if (!string.IsNullOrEmpty(route))
            {
                req.Routing = route;
            }
            req.Document = data;
            IndexResponse re = null;

            if (string.IsNullOrEmpty(id))
            {
                id = id_gen.CreateId().ToString();
            }
            if (!string.IsNullOrEmpty(id))
            {
                re = client.Index <T>(data, i => i.Id(id));
            }
            else
            {
                re = client.Index(req);
            }
            return(re.Result == Result.Created);
        }
Ejemplo n.º 2
0
        public void CreateId_Throws_OnTimestampWraparound()
        {
            var ts = new MockTimeSource(long.MaxValue);  // Set clock to 1 'tick' before wraparound
            var g  = new IdGenerator(0, new IdGeneratorOptions(timeSource: ts));

            Assert.IsTrue(g.CreateId() > 0);    // Should succeed;
            ts.NextTick();
            g.CreateId();                       // Should fail
        }
Ejemplo n.º 3
0
        public void CreateId_Throws_OnClockBackwards()
        {
            var ts = new MockTimeSource(100);
            var g  = new IdGenerator(0, new IdGeneratorOptions(timeSource: ts));

            g.CreateId();
            ts.PreviousTick(); // Set clock back 1 'tick', this results in the time going from "100" to "99"
            g.CreateId();
        }
Ejemplo n.º 4
0
        public void Constructor_Throws_OnTimestampWraparound()
        {
            var m  = MaskConfig.Default;
            var ts = new MockTimeSource(long.MaxValue);  // Set clock to 1 'tick' before wraparound
            var g  = new IdGenerator(0, TESTEPOCH, m, ts);

            Assert.IsTrue(g.CreateId() > 0);    // Should succeed;
            ts.NextTick();
            g.CreateId();                       // Should fail
        }
Ejemplo n.º 5
0
        public void Constructor_Throws_OnTimestampWraparound()
        {
            var mc = MaskConfig.Default;
            var ts = new MockTimeSource(mc.WraparoundDate(TESTEPOCH).AddMilliseconds(-1));  //Set clock to 1 ms before epoch
            var g  = new IdGenerator(0, TESTEPOCH, MaskConfig.Default, ts);

            Assert.IsTrue(g.CreateId() > 0); //Should succeed;
            ts.NextTick();
            g.CreateId();                    //Should fail
        }
Ejemplo n.º 6
0
        public void CreateId_Throws_OnClockBackwards()
        {
            var ts = new MockTimeSource(DateTime.UtcNow);
            var m  = MaskConfig.Default;
            var g  = new IdGenerator(0, TESTEPOCH, m, ts);

            g.CreateId();
            ts.PreviousTick(); //Set clock back 1 'tick' (ms)
            g.CreateId();
        }
Ejemplo n.º 7
0
        public void Constructor_Throws_OnTimestampWraparound()
        {
            var mc = MaskConfig.Default;
            var ts = new MockTimeSource(mc.WraparoundDate(TESTEPOCH).AddMilliseconds(-1));  //Set clock to 1 ms before epoch
            var g = new IdGenerator(0, TESTEPOCH, MaskConfig.Default, ts);

            Assert.IsTrue(g.CreateId() > 0);   //Should succeed;
            ts.NextTick();
            g.CreateId();   //Should fail
        }
Ejemplo n.º 8
0
        public void CreateId_Throws_OnClockBackwards()
        {
            var ts = new MockTimeSource(100);
            var m  = MaskConfig.Default;
            var g  = new IdGenerator(0, TESTEPOCH, m, ts);

            g.CreateId();
            ts.PreviousTick(); // Set clock back 1 'tick', this results in the time going from "100" to "99"
            g.CreateId();
        }
Ejemplo n.º 9
0
        public void Sequence_ShouldIncrease_EveryInvocation()
        {
            // We setup our generator so that the time is 0, generator id 0 and we're only left with the sequence
            // increasing each invocation of CreateId();
            var ts = new MockTimeSource(0);
            var g  = new IdGenerator(0, new IdGeneratorOptions(timeSource: ts));

            Assert.AreEqual(0, g.CreateId());
            Assert.AreEqual(1, g.CreateId());
            Assert.AreEqual(2, g.CreateId());
        }
Ejemplo n.º 10
0
        public void Sequence_ShouldIncrease_EveryInvocation()
        {
            // We setup our generator so that the time (current - epoch) results in 0, generator id 0 and we're only
            // left with the sequence increasing each invocation of CreateId();
            var ts = new MockTimeSource(TESTEPOCH);
            var m  = MaskConfig.Default;
            var g  = new IdGenerator(0, TESTEPOCH, MaskConfig.Default, ts);

            Assert.AreEqual(0, g.CreateId());
            Assert.AreEqual(1, g.CreateId());
            Assert.AreEqual(2, g.CreateId());
        }
Ejemplo n.º 11
0
        public void CreateId_Throws_OnSequenceOverflow()
        {
            var ts = new MockTimeSource();
            var g  = new IdGenerator(0, TESTEPOCH, new MaskConfig(41, 20, 2), ts);

            // We have a 2-bit sequence; generating 4 id's shouldn't be a problem
            for (int i = 0; i < 4; i++)
            {
                Assert.AreEqual(i, g.CreateId());
            }

            // However, if we invoke once more we should get an SequenceOverflowException
            g.CreateId();
        }
Ejemplo n.º 12
0
        public void Sequence_ShouldReset_EveryNewTick()
        {
            // We setup our generator so that the time is 0, generator id 0 and we're only left with the sequence
            // increasing each invocation of CreateId();
            var ts = new MockTimeSource(0);
            var g  = new IdGenerator(0, new IdGeneratorOptions(timeSource: ts));

            Assert.AreEqual(0, g.CreateId());
            Assert.AreEqual(1, g.CreateId());
            ts.NextTick();
            // Since the timestamp has increased, we should now have a much higher value (since the timestamp is
            // shifted left a number of bits (specifically GeneratorIdBits + SequenceBits)
            Assert.AreEqual((1 << (g.Options.IdStructure.GeneratorIdBits + g.Options.IdStructure.SequenceBits)) + 0, g.CreateId());
            Assert.AreEqual((1 << (g.Options.IdStructure.GeneratorIdBits + g.Options.IdStructure.SequenceBits)) + 1, g.CreateId());
        }
Ejemplo n.º 13
0
        public void CreateId_Throws_OnSequenceOverflow()
        {
            var ts = new MockTimeSource();
            var s  = new IdStructure(41, 20, 2);
            var g  = new IdGenerator(0, new IdGeneratorOptions(idStructure: s, timeSource: ts));

            // We have a 2-bit sequence; generating 4 id's shouldn't be a problem
            for (var i = 0; i < 4; i++)
            {
                Assert.AreEqual(i, g.CreateId());
            }

            // However, if we invoke once more we should get an SequenceOverflowException
            g.CreateId();
        }
Ejemplo n.º 14
0
        public async Task <GroupInviteId> Handle(AddGroupInviteCommand request,
                                                 CancellationToken cancellationToken)
        {
            var group = await _groupRepository.GetByIdAsNoTrackingAsync(request.GroupId, cancellationToken);

            if (group.OwnerId != request.InviterId)
            {
                throw new ApiException("Only owner can invite users to a group.", StatusCodes.Status403Forbidden);
            }

            if (group.UserGroups.Any(x => x.AppUserId == request.InvitedAppUserId))
            {
                throw new ApiException("User is already in a group", StatusCodes.Status409Conflict);
            }

            IdGenerator idGenerator = new IdGenerator(IdGeneratorType.GroupInvite);
            var         groupInvite = new GroupInvite
            {
                Id = new GroupInviteId(idGenerator.CreateId()),
                InvitingAppUserId = request.InviterId,
                InvitedAppUserId  = request.InvitedAppUserId,
                IsAccepted        = false,
                IsPending         = true,
                DateAdded         = DateTimeOffset.Now,
                GroupId           = request.GroupId
            };

            await _groupInviteRepository.AddAsync(groupInvite, cancellationToken);

            await _unitOfWork.SaveAsync(cancellationToken);

            return(groupInvite.Id);
        }
Ejemplo n.º 15
0
    static void Main(string[] args)
    {
        var mc = new MaskConfig(50, 0, 13);

        //Js最大值:9007199254740992
        long jsMaxValue = 9007199254740992;

        for (var i = 0; i < 2000; i++)
        {
            var gen = new IdGenerator(0, DateTime.Now.AddYears(-i), mc);
            var id  = gen.CreateId();

            if (id > jsMaxValue)
            {
                Console.WriteLine($"第{i}年: {id},超出Javascript最大数值:{jsMaxValue}");
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine($"生成器个数: {mc.MaxGenerators}");
                Console.WriteLine($"每秒每台生成Id数: {mc.MaxSequenceIds}");
                Console.WriteLine($"每秒总生成Id数: {mc.MaxGenerators * mc.MaxSequenceIds}");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"当前配置最多可用{i - 1}年哈");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine($"第{i}年: {id}");
            }
        }
        Console.WriteLine("可用超2000年");
        Console.ReadKey();
    }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            List <long> data = new List <long>();

            DateTime timeBegin = DateTime.Now;
            //var generator = new IdGenerator(0);

            var epoch     = new DateTime(2020, 7, 22, 0, 0, 0, DateTimeKind.Utc);
            var structure = new IdStructure(45, 2, 16);
            var options   = new IdGeneratorOptions(structure, new DefaultTimeSource(epoch));
            var generator = new IdGenerator(0, options);

            for (int i = 0; i < 100000000; i++)
            {
                var id = generator.CreateId();
                data.Add(id);
                //Console.WriteLine($"生成id:{id}");
            }
            DateTime timeEnd = DateTime.Now;
            TimeSpan span    = timeEnd.Subtract(timeBegin);

            data.Add(data.Last());
            Console.WriteLine($"添加一个测试数据后:{data.Count}");
            data = data.Distinct().ToList();
            Console.WriteLine($"取出重复数据后:{data.Count}");
            Console.WriteLine($"耗时:{span.TotalSeconds}");
            Console.WriteLine($"平均每秒产生:{data.Count / span.TotalSeconds}");

            Console.ReadLine();
        }
Ejemplo n.º 17
0
 public static long NewId()
 {
     lock (_lock)
     {
         return(_generator.CreateId());
     }
 }
        public void IdGeneratorOverflowShouldThrowTest()
        {
            var value = (GetMask(64 - IdGenerator.InstanceBits - IdGenerator.RegionBits - IdGenerator.ZoneBits) & long.MaxValue) + 1;
            var gen   = new IdGenerator(0, 0, 0);

            Assert.Throws <Exception>(() => gen.CreateId(value));
        }
        public void DifferentInstancesGenerateDifferentIdsTest()
        {
            var gen1 = new IdGenerator(0, 0, 0);
            var gen2 = new IdGenerator(0, 0, 1);

            Assert.NotEqual(gen1.CreateId(0u).Value, gen2.CreateId(0u).Value);
        }
Ejemplo n.º 20
0
        public void Sequence_ShouldReset_EveryNewTick()
        {
            // We setup our generator so that the time (current - epoch) results in 0, generator id 0 and we're only
            // left with the sequence increasing each invocation of CreateId();
            var ts = new MockTimeSource(TESTEPOCH);
            var m  = MaskConfig.Default;
            var g  = new IdGenerator(0, TESTEPOCH, m, ts);

            Assert.AreEqual(0, g.CreateId());
            Assert.AreEqual(1, g.CreateId());
            ts.NextTick();
            // Since the timestamp has increased, we should now have a much higher value (since the timestamp is shifted
            // left a number of bits (specifically GeneratorIdBits + SequenceBits)
            Assert.AreEqual((1 << (m.GeneratorIdBits + m.SequenceBits)) + 0, g.CreateId());
            Assert.AreEqual((1 << (m.GeneratorIdBits + m.SequenceBits)) + 1, g.CreateId());
        }
Ejemplo n.º 21
0
        public void FromId_Returns_CorrectValue()
        {
            var s     = new IdStructure(42, 8, 13);
            var epoch = new DateTimeOffset(2018, 7, 31, 14, 48, 2, TimeSpan.FromHours(2));  // Just some "random" epoch...
            var ts    = new MockTimeSource(5, TimeSpan.FromSeconds(7), epoch);              // Set clock at 5 ticks; each tick being 7 seconds...
                                                                                            // Set generator ID to 234
            var g = new IdGenerator(234, new IdGeneratorOptions(s, ts));

            // Generate a bunch of id's
            long id = 0;

            for (var i = 0; i < 35; i++)
            {
                id = g.CreateId();
            }

            var target = g.FromId(id);


            Assert.AreEqual(34, target.SequenceNumber);                                     // We generated 35 id's in the same tick, so sequence should be at 34.
            Assert.AreEqual(234, target.GeneratorId);                                       // With generator id 234
            Assert.AreEqual(epoch.Add(TimeSpan.FromSeconds(5 * 7)), target.DateTimeOffset); // And the clock was at 5 ticks, with each tick being
                                                                                            // 7 seconds (so 35 seconds from epoch)
                                                                                            // And epoch was 2018-7-31 14:48:02 +02:00...
        }
Ejemplo n.º 22
0
        public async ValueTask <bool> Send(Message message, HashSet <long> receivers)
        {
            using var context     = Context;
            message.ObjectId      = IdGenerator.CreateId();
            message.CreateUtcTime = DateTime.UtcNow;
            message.Receivers     = receivers.ToList();

            var messageBox = new MessageBox(context);

            context.BeginTran();
            try
            {
                if (!await messageBox.AddMessage(message) ||
                    !await messageBox.SendMessage(message.ObjectId, message.Receivers))
                {
                    context.RollbackTran();
                    return(false);
                }
                context.CommitTran();
                MessageSent?.Invoke(this, message);
                return(true);
            }
            catch (Exception e)
            {
                context.RollbackTran();
                throw;
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 推特Snowflake算法C#版
        /// 详情了解https://github.com/RobThree/IdGen
        /// </summary>
        /// <returns></returns>
        public static long NewId()
        {
            //如id压力增大,后续移至NetPro.Core中,apollo配置

            var generator = new IdGenerator(0);

            return(generator.CreateId());
        }
Ejemplo n.º 24
0
        public ulong GetId()
        {
            if (_isInitialised == false)
            {
                Initialise();
            }

            return((ulong)_idGenerator.CreateId());
        }
 public static long GetPassportID()
 {
     i++;
     if (i > 1000)
     {
         i = 0;
         Thread.Sleep(1);
     }
     return(PassportIDGenerator.CreateId());
 }
 public static long GetEmployerID()
 {
     i++;
     if (i > 1000)
     {
         i = 0;
         Thread.Sleep(1);
     }
     return(EmployerIDGenerator.CreateId());
 }
Ejemplo n.º 27
0
        public long NewIdentity()
        {
            if (_generator == null)
            {
                throw new Exception("_generator is not init.");
            }

            long id = _generator.CreateId();

            return(id);
        }
Ejemplo n.º 28
0
        public void GeneratorId_ShouldBePresent_InID1()
        {
            // We setup our generator so that the time is 0 and generator id equals 1023 so that all 10 bits are set
            // for the generator.
            var ts = new MockTimeSource();
            var m  = MaskConfig.Default;    // We use a default mask-config with 11 bits for the generator this time
            var g  = new IdGenerator(1023, TESTEPOCH, m, ts);

            // Make sure all expected bits are set
            Assert.AreEqual((1 << m.GeneratorIdBits) - 1 << m.SequenceBits, g.CreateId());
        }
Ejemplo n.º 29
0
        private static async Task Normal(IClusterClient client)
        {
            try
            {
                Console.WriteLine("Please enter the number of account");
                var accountCount = int.Parse(Console.ReadLine() ?? "10");
                Console.WriteLine("Please enter the number of executions");
                var times         = int.Parse(Console.ReadLine() ?? "10");
                var topupWatch    = new Stopwatch();
                var topupTaskList = new List <Task>();
                foreach (var account in Enumerable.Range(0, accountCount))
                {
                    topupTaskList.AddRange(Enumerable.Range(0, times).Select(x => client.GetGrain <IAccount>(account).TopUp(100, IdGen.CreateId().ToString())));
                }

                topupWatch.Start();
                await Task.WhenAll(topupTaskList);

                topupWatch.Stop();
                Console.WriteLine($"{times * accountCount} Recharge completed, taking: {topupWatch.ElapsedMilliseconds}ms");
                foreach (var account in Enumerable.Range(0, accountCount))
                {
                    Console.WriteLine($"The balance of account {account} is{await client.GetGrain<IAccount>(account).GetBalance()}");
                }

                var transferWatch    = new Stopwatch();
                var transferTaskList = new List <Task>();
                foreach (var account in Enumerable.Range(0, accountCount))
                {
                    transferTaskList.AddRange(Enumerable.Range(0, times).Select(x => client.GetGrain <IAccount>(account).Transfer(account + accountCount, 50, IdGen.CreateId().ToString())));
                }

                transferWatch.Start();
                await Task.WhenAll(transferTaskList);

                transferWatch.Stop();
                Console.WriteLine(
                    $"{times * accountCount}The transfer is completed, taking: {transferWatch.ElapsedMilliseconds}ms");
                foreach (var account in Enumerable.Range(0, accountCount))
                {
                    Console.WriteLine($"The balance of account {account} is{await client.GetGrain<IAccount>(account).GetBalance()}");
                }

                foreach (var account in Enumerable.Range(0, accountCount))
                {
                    Console.WriteLine($"The balance of account {account} is{await client.GetGrain<IAccount>(account + accountCount).GetBalance()}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 30
0
        public void GeneratorId_ShouldBePresent_InID2()
        {
            // We setup our generator so that the time is 0 and generator id equals 4095 so that all 12 bits are set
            // for the generator.
            var ts = new MockTimeSource();
            var m  = new MaskConfig(40, 12, 11); // We use a custom mask-config with 12 bits for the generator this time
            var g  = new IdGenerator(4095, TESTEPOCH, m, ts);

            // Make sure all expected bits are set
            Assert.AreEqual(-1 & ((1 << 12) - 1), g.Id);
            Assert.AreEqual((1 << 12) - 1 << 11, g.CreateId());
        }
Ejemplo n.º 31
0
        public void GeneratorId_ShouldBePresent_InID2()
        {
            // We setup our generator so that the time is 0 and generator id equals 4095 so that all 12 bits are set
            // for the generator.
            var ts = new MockTimeSource();
            var s  = new IdStructure(40, 12, 11); // We use a custom IdStructure with 12 bits for the generator this time
            var g  = new IdGenerator(4095, new IdGeneratorOptions(s, ts));

            // Make sure all expected bits are set
            Assert.AreEqual(-1 & ((1 << 12) - 1), g.Id);
            Assert.AreEqual((1 << 12) - 1 << 11, g.CreateId());
        }
Ejemplo n.º 32
0
        public void Sequence_ShouldIncrease_EveryInvocation()
        {
            // We setup our generator so that the time (current - epoch) results in 0, generator id 0 and we're only
            // left with the sequence increasing each invocation of CreateId();
            var ts = new MockTimeSource(TESTEPOCH);
            var m = MaskConfig.Default;
            var g = new IdGenerator(0, TESTEPOCH, MaskConfig.Default, ts);

            Assert.AreEqual(0, g.CreateId());
            Assert.AreEqual(1, g.CreateId());
            Assert.AreEqual(2, g.CreateId());
        }
Ejemplo n.º 33
0
        public void CreateId_Throws_OnSequenceOverflow()
        {
            var ts = new MockTimeSource(TESTEPOCH);
            var g = new IdGenerator(0, TESTEPOCH, new MaskConfig(41, 20, 2), ts);

            // We have a 2-bit sequence; generating 4 id's shouldn't be a problem
            for (int i = 0; i < 4; i++)
                Assert.AreEqual(i, g.CreateId());

            // However, if we invoke once more we should get an SequenceOverflowException
            g.CreateId();
        }
Ejemplo n.º 34
0
        public void GeneratorId_ShouldBePresent_InID1()
        {
            // We setup our generator so that the time (current - epoch) results in 0, generator id 1023 so that all 10 bits
            // are set for the generator.
            var ts = new MockTimeSource(TESTEPOCH);
            var m = MaskConfig.Default;             // We use a default mask-config with 11 bits for the generator this time
            var g = new IdGenerator(1023, TESTEPOCH, m, ts);

            // Make sure all expected bits are set
            Assert.AreEqual((1 << m.GeneratorIdBits) - 1 << m.SequenceBits, g.CreateId());
        }
Ejemplo n.º 35
0
        public void GeneratorId_ShouldBePresent_InID2()
        {
            // We setup our generator so that the time (current - epoch) results in 0, generator id 4095 so that all 12 bits
            // are set for the generator.
            var ts = new MockTimeSource(TESTEPOCH);
            var m = new MaskConfig(40, 12, 11);     // We use a custom mask-config with 12 bits for the generator this time
            var g = new IdGenerator(4095, TESTEPOCH, m, ts);

            // Make sure all expected bits are set
            Assert.AreEqual(-1 & ((1 << 12) - 1), g.Id);
            Assert.AreEqual((1 << 12) - 1 << 11, g.CreateId());
        }
Ejemplo n.º 36
0
        public void CreateId_Throws_OnClockBackwards()
        {
            var ts = new MockTimeSource(DateTime.UtcNow);
            var m = MaskConfig.Default;
            var g = new IdGenerator(0, TESTEPOCH, m, ts);

            g.CreateId();
            ts.PreviousTick(); //Set clock back 1 'tick' (ms)
            g.CreateId();
        }
Ejemplo n.º 37
0
        public void Sequence_ShouldReset_EveryNewTick()
        {
            // We setup our generator so that the time (current - epoch) results in 0, generator id 0 and we're only
            // left with the sequence increasing each invocation of CreateId();
            var ts = new MockTimeSource(TESTEPOCH);
            var m = MaskConfig.Default;
            var g = new IdGenerator(0, TESTEPOCH, m, ts);

            Assert.AreEqual(0, g.CreateId());
            Assert.AreEqual(1, g.CreateId());
            ts.NextTick();
            // Since the timestamp has increased, we should now have a much higher value (since the timestamp is shifted
            // left a number of bits (specifically GeneratorIdBits + SequenceBits)
            Assert.AreEqual((1 << (m.GeneratorIdBits + m.SequenceBits)) + 0, g.CreateId());
            Assert.AreEqual((1 << (m.GeneratorIdBits + m.SequenceBits)) + 1, g.CreateId());
        }