public TimeGenerator()
        {
            time = SystemClock.Instance.Now;

            _rnd = new RandomProvider();
            _rnd.Reset((int)time.Ticks);
        }
        /// <inheritdoc />
        public override ZoneInterval GetZoneInterval(Instant instant)
        {
            int lower = 0; // Inclusive
            int upper = Intervals.Count; // Exclusive

            while (lower < upper)
            {
                int current = (lower + upper) / 2;
                var candidate = Intervals[current];
                if (candidate.HasStart && candidate.Start > instant)
                {
                    upper = current;
                }
                else if (candidate.HasEnd && candidate.End <= instant)
                {
                    lower = current + 1;
                }
                else
                {
                    return candidate;
                }
            }
            // Note: this would indicate a bug. The time zone is meant to cover the whole of time.
            throw new InvalidOperationException(string.Format("Instant {0} did not exist in time zone {1}", instant, Id));
        }
        /// <summary>
        /// Gets the zone offset period for the given instant.
        /// </summary>
        /// <param name="instant">The Instant to find.</param>
        /// <returns>The ZoneInterval including the given instant.</returns>
        public override ZoneInterval GetZoneInterval(Instant instant)
        {
            if (tailZone != null && instant >= tailZoneStart)
            {
                // Clamp the tail zone interval to start at the end of our final period, if necessary, so that the
                // join is seamless.
                ZoneInterval intervalFromTailZone = tailZone.GetZoneInterval(instant);
                return intervalFromTailZone.RawStart < tailZoneStart ? firstTailZoneInterval : intervalFromTailZone;
            }
            
            int lower = 0; // Inclusive
            int upper = periods.Length; // Exclusive

            while (lower < upper)
            {
                int current = (lower + upper) / 2;
                var candidate = periods[current];
                if (candidate.RawStart > instant)
                {
                    upper = current;
                }
                // Safe to use RawEnd, as it's just for the comparison.
                else if (candidate.RawEnd <= instant)
                {
                    lower = current + 1;
                }
                else
                {
                    return candidate;
                }
            }
            // Note: this would indicate a bug. The time zone is meant to cover the whole of time.
            throw new InvalidOperationException($"Instant {instant} did not exist in time zone {Id}");
        }
Example #4
0
 public void MinusOffset_Zero_IsNeutralElement()
 {
     Instant sampleInstant = new Instant(1, 23456L);
     LocalInstant sampleLocalInstant = new LocalInstant(1, 23456L);
     Assert.AreEqual(sampleInstant, sampleLocalInstant.Minus(Offset.Zero));
     Assert.AreEqual(sampleInstant, sampleLocalInstant.MinusZeroOffset());
 }
Example #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ZoneTransition"/> class.
 /// </summary>
 /// <remarks>
 /// </remarks>
 /// <param name="instant">The instant that this transistion occurs at.</param>
 /// <param name="name">The name for the time at this transition e.g. PDT or PST.</param>
 /// <param name="standardOffset">The standard offset at this transition.</param>
 /// <param name="savings">The actual offset at this transition.</param>
 internal ZoneTransition(Instant instant, String name, Offset standardOffset, Offset savings)
 {
     Preconditions.CheckNotNull(name, "name");
     this.Instant = instant;
     this.Name = name;
     this.StandardOffset = standardOffset;
     this.Savings = savings;
 }
 /// <summary>
 /// Creates a zone with a single transition between two offsets.
 /// </summary>
 /// <param name="transitionPoint">The transition point as an <see cref="Instant"/>.</param>
 /// <param name="offsetBefore">The offset of local time from UTC before the transition.</param>
 /// <param name="offsetAfter">The offset of local time from UTC before the transition.</param>
 /// <param name="id">ID for the newly created time zone.</param>
 public SingleTransitionDateTimeZone(Instant transitionPoint, Offset offsetBefore, Offset offsetAfter, string id)
     : base(id, false, Offset.Min(offsetBefore, offsetAfter), Offset.Max(offsetBefore, offsetAfter))
 {
     EarlyInterval = new ZoneInterval(id + "-Early", null, transitionPoint,
         offsetBefore, Offset.Zero);
     LateInterval = new ZoneInterval(id + "-Late", transitionPoint, null,
         offsetAfter, Offset.Zero);
 }
 /// <summary>
 /// Creates a zone with a single transition between two offsets.
 /// </summary>
 /// <param name="transitionPoint">The transition point as an <see cref="Instant"/>.</param>
 /// <param name="offsetBefore">The offset of local time from UTC before the transition.</param>
 /// <param name="offsetAfter">The offset of local time from UTC before the transition.</param>
 public SingleTransitionZone(Instant transitionPoint, Offset offsetBefore, Offset offsetAfter)
     : base("Single", false, Offset.Min(offsetBefore, offsetAfter), Offset.Max(offsetBefore, offsetAfter))
 {
     earlyInterval = new ZoneInterval("Single-Early", Instant.MinValue, transitionPoint,
         offsetBefore, Offset.Zero);
     lateInterval = new ZoneInterval("Single-Late", transitionPoint, Instant.MaxValue,
         offsetAfter, Offset.Zero);
 }
Example #8
0
 public void Construction()
 {
     // 10 million ticks = 1 second...
     Instant instant = new Instant(10000000);
     // Epoch is 1970 UTC
     // An instant isn't really "in" a time zone or calendar, but
     // it's convenient to consider UTC in the ISO-8601 calendar.
     Assert.AreEqual("1970-01-01T00:00:01Z", instant.ToString());
 }
Example #9
0
 public void AdditionWithDuration()
 {
     // Some arbitrary instant. I've no idea when.
     Instant instant = new Instant(150000000);
     // A very short duration: a duration is simply a number of ticks.
     Duration duration = new Duration(1000);
     Instant later = instant + duration;
     Assert.AreEqual(new Instant(150001000), later);
 }
Example #10
0
        public CountdownActor(Label lbl, Form1 form, Instant deadline)
        {
            _labelUpdater = Context.ActorOf(Props.Create(() => new LabelUpdaterActor(lbl)));
            _alarm = Context.ActorOf(Props.Create(() => new AlarmActor(form)));
            _deadline = deadline;

            Receive<DateTime>(msg => UpdateDeadline(msg));
            Receive<object>(msg => Tick());
        }
 internal PartialZoneIntervalMap(Instant start, Instant end, IZoneIntervalMap map)
 {
     // Allowing empty maps makes life simpler.
     Preconditions.DebugCheckArgument(start <= end, nameof(end),
         "Invalid start/end combination: {0} - {1}", start, end);
     this.Start = start;
     this.End = end;
     this.map = map;
 }
 public void Construct_EndOfTime_Truncated()
 {
     const string name = "abc";
     var instant = new Instant(Instant.MaxValue.Ticks + minusOneHour.TotalTicks);
     var actual = new ZoneTransition(instant, name, threeHours, threeHours);
     Assert.AreEqual(instant, actual.Instant, "Instant");
     Assert.AreEqual(oneHour, actual.StandardOffset, "StandardOffset");
     Assert.AreEqual(Offset.Zero, actual.Savings, "Savings");
 }
        public void Comparison()
        {
            Instant equal = new Instant(1, 100L);
            Instant greater1 = new Instant(1, 101L);
            Instant greater2 = new Instant(2, 0L);

            TestHelper.TestCompareToStruct(equal, equal, greater1);
            TestHelper.TestNonGenericCompareTo(equal, equal, greater1);
            TestHelper.TestOperatorComparisonEquality(equal, equal, greater1, greater2);
        }
 public void SingleAggregateSchedule()
 {
     Instant i = new Instant(Tester.RandomGenerator.RandomInt32());
     OneOffSchedule oneOffSchedule = new OneOffSchedule(i);
     AggregateSchedule aggregateSchedule = new AggregateSchedule(oneOffSchedule);
     Assert.AreEqual(1, aggregateSchedule.Count());
     Assert.AreEqual(i, aggregateSchedule.Next(i - TimeHelpers.OneSecond));
     Assert.AreEqual(i, aggregateSchedule.Next(i));
     Assert.AreEqual(Instant.MaxValue, aggregateSchedule.Next(i + Duration.FromTicks(1)));
 }
Example #15
0
        public Duration KeepAlive(Instant now)
        {
            var newTimestamp = now;
            var oldTimestamp = this.LastKeepAlive;

            this.LastKeepAlive = newTimestamp;

            var lag = newTimestamp - oldTimestamp;
            return lag;
        }
 /// <summary>
 /// Gets the zone interval for the given instant.
 /// </summary>
 /// <param name="instant">The Instant to test.</param>
 /// <returns>The ZoneInterval in effect at the given instant.</returns>
 /// <exception cref="ArgumentOutOfRangeException">The instant falls outside the bounds
 /// of the recurrence rules of the zone.</exception>
 public override ZoneInterval GetZoneInterval(Instant instant)
 {
     ZoneRecurrence recurrence;
     var next = NextTransition(instant, out recurrence);
     // Now we know the recurrence we're in, we can work out when we went into it. (We'll never have
     // two transitions into the same recurrence in a row.)
     Offset previousSavings = ReferenceEquals(recurrence, standardRecurrence) ? dstRecurrence.Savings : Offset.Zero;
     var previous = recurrence.PreviousOrSameOrFail(instant, standardOffset, previousSavings);
     return new ZoneInterval(recurrence.Name, previous.Instant, next.Instant, standardOffset + recurrence.Savings, recurrence.Savings);
 }
Example #17
0
        public void Update(UpdateEventArgs args)
        {
            var elapsedTime = new TimeSpan(args.ElapsedTimeInS);

            this.time += elapsedTime;

            foreach (var gameObject in this.gameObjects)
            {
                gameObject.Update(elapsedTime);
            }
        }
Example #18
0
 public void Max()
 {
     Instant x = new Instant(100);
     Instant y = new Instant(200);
     Assert.AreEqual(y, Instant.Max(x, y));
     Assert.AreEqual(y, Instant.Max(y, x));
     Assert.AreEqual(x, Instant.Max(x, Instant.MinValue));
     Assert.AreEqual(x, Instant.Max(Instant.MinValue, x));
     Assert.AreEqual(Instant.MaxValue, Instant.Max(Instant.MaxValue, x));
     Assert.AreEqual(Instant.MaxValue, Instant.Max(x, Instant.MaxValue));
 }
        public void Equality()
        {
            Instant equal = new Instant(1, 100L);
            Instant different1 = new Instant(1, 200L);
            Instant different2 = new Instant(2, 100L);

            TestHelper.TestEqualsStruct(equal, equal, different1);
            TestHelper.TestOperatorEquality(equal, equal, different1);

            TestHelper.TestEqualsStruct(equal, equal, different2);
            TestHelper.TestOperatorEquality(equal, equal, different2);
        }
Example #20
0
        public void TestInstantOperators()
        {
            const long diff = TestTime2 - TestTime1;

            var time1 = new Instant(TestTime1);
            var time2 = new Instant(TestTime2);
            Duration duration = time2 - time1;

            Assert.AreEqual(diff, duration.Ticks);
            Assert.AreEqual(TestTime2, (time1 + duration).Ticks);
            Assert.AreEqual(TestTime1, (time2 - duration).Ticks);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ScheduledActionResult"/> class.
 /// </summary>
 /// <param name="due">The due.</param>
 /// <param name="started">The started.</param>
 /// <param name="duration">The duration.</param>
 /// <param name="exception">The exception.</param>
 /// <param name="cancelled">if set to <see langword="true"/> the action was cancelled.</param>
 /// <remarks></remarks>
 protected ScheduledActionResult(
     Instant due,
     Instant started,
     Duration duration,
     [CanBeNull] Exception exception,
     bool cancelled)
 {
     Due = due;
     Started = started;
     Duration = duration;
     Exception = exception;
     Cancelled = cancelled;
 }
        private static void TestToStringBase(Instant value, string gvalue)
        {
            string actual = value.ToString();
            Assert.AreEqual(gvalue, actual);
            actual = value.ToString("g", null);
            Assert.AreEqual(gvalue, actual);
            actual = value.ToString("g", CultureInfo.InvariantCulture);
            Assert.AreEqual(gvalue, actual);

            actual = string.Format("{0}", value);
            Assert.AreEqual(gvalue, actual);
            actual = string.Format("{0:g}", value);
            Assert.AreEqual(gvalue, actual);
        }
 public void DoubleAggregateSchedule()
 {
     Instant i = new Instant(Tester.RandomGenerator.RandomInt32());
     Instant j = i + TimeHelpers.OneSecond;
     OneOffSchedule s1 = new OneOffSchedule(i);
     OneOffSchedule s2 = new OneOffSchedule(j);
     AggregateSchedule aggregateSchedule = new AggregateSchedule(s1, s2);
     Assert.AreEqual(2, aggregateSchedule.Count());
     Assert.AreEqual(i, aggregateSchedule.Next(i - TimeHelpers.OneSecond));
     Assert.AreEqual(i, aggregateSchedule.Next(i));
     Assert.AreEqual(j, aggregateSchedule.Next(i + Duration.FromTicks(1)));
     Assert.AreEqual(j, aggregateSchedule.Next(j));
     Assert.AreEqual(Instant.MaxValue, aggregateSchedule.Next(j + Duration.FromTicks(1)));
 }
 internal PrecalculatedDateTimeZone([NotNull] string id, [NotNull] ZoneInterval[] intervals, IZoneIntervalMapWithMinMax tailZone)
     : base(id, false,
            ComputeOffset(intervals, tailZone, Offset.Min),
            ComputeOffset(intervals, tailZone, Offset.Max))
 {
     this.tailZone = tailZone;
     this.periods = intervals;
     this.tailZone = tailZone;
     this.tailZoneStart = intervals[intervals.Length - 1].RawEnd; // We want this to be AfterMaxValue for tail-less zones.
     if (tailZone != null)
     {
         // Cache a "clamped" zone interval for use at the start of the tail zone.
         firstTailZoneInterval = tailZone.GetZoneInterval(tailZoneStart).WithStart(tailZoneStart);
     }
     ValidatePeriods(intervals, tailZone);
 }
Example #25
0
        private static string ConvertNowLine(string line, Instant runTime)
        {
            var match = NowRegex.Match(line);
            if (!match.Success)
            {
                throw new Exception("Invalid line: " + line);
            }
            var local = LocalPattern.Parse(match.Groups["local"].Value.Replace("  ", " ")).Value;
            var name = match.Groups["name"].Value;
            var offsetAsDuration = local.InUtc().ToInstant() - runTime;
            // Round it to the nearest 5 minutes.
            var roundedSeconds = Math.Round(offsetAsDuration.TotalSeconds / 300) * 300;
            var offset = Offset.FromSeconds((int) roundedSeconds);

            return string.Format("Fixed: {0} {1}\r\n", OffsetPattern.Format(offset), name);
        }
 internal ZoneInterval GetZoneInterval(Instant instant)
 {
     Preconditions.DebugCheckArgument(instant >= Start && instant < End, nameof(instant),
         "Value {0} was not in the range [{0}, {1})", instant, Start, End);
     var interval = map.GetZoneInterval(instant);
     // Clamp the interval for the sake of sanity. Checking this every time isn't very efficient,
     // but we're not expecting this to be called too often, due to caching.
     if (interval.RawStart < Start)
     {
         interval = interval.WithStart(Start);
     }
     if (interval.RawEnd > End)
     {
         interval = interval.WithEnd(End);
     }
     return interval;
 }
 /// <summary>
 /// Initializes the <see cref="HighPrecisionClock"/> class.
 /// </summary>
 static HighPrecisionClock()
 {
     try
     {
         long time;
         GetSystemTimePreciseAsFileTime(out time);
         _getSysTimeAvailable = true;
     }
     catch (Exception)
     {
         _getSysTimeAvailable = false;
         if (Stopwatch.IsHighResolution)
         {
             // ReSharper disable once PossibleNullReferenceException
             _startedTime = SystemClock.Instance.Now;
             _startedTicks = Stopwatch.GetTimestamp();
         }
     }
 }
            /// <summary>
            /// Gets the zone offset period for the given instant. Null is returned if no period is
            /// defined by the time zone for the given instant.
            /// </summary>
            /// <param name="instant">The Instant to test.</param>
            /// <returns>The defined ZoneOffsetPeriod or null.</returns>
            public ZoneInterval GetZoneInterval(Instant instant)
            {
                int period = instant.DaysSinceEpoch >> PeriodShift;
                int index = period & CachePeriodMask;
                var node = instantCache[index];
                if (node == null || node.Period != period)
                {
                    node = HashCacheNode.CreateNode(period, map);
                    instantCache[index] = node;
                }

                // Note: moving this code into an instance method in HashCacheNode makes a surprisingly
                // large performance difference.
                while (node.Previous != null && node.Interval.RawStart > instant)
                {
                    node = node.Previous;
                }
                return node.Interval;
            }
        private static void TestToStringBase(Instant value, string gvalue)
        {
            string actual = value.ToString();
            Assert.AreEqual(gvalue, actual);
            actual = value.ToString("G");
            Assert.AreEqual(gvalue, actual);
            actual = value.ToString("N");
            Assert.AreEqual(value.Ticks.ToString("N0"), actual);
            actual = value.ToString("N", CultureInfo.InvariantCulture);
            Assert.AreEqual(value.Ticks.ToString("N0", CultureInfo.InvariantCulture), actual);
            actual = value.ToString(CultureInfo.InvariantCulture);
            Assert.AreEqual(gvalue, actual);
            actual = value.ToString("D");
            Assert.AreEqual(value.Ticks.ToString("D"), actual);

            actual = string.Format("{0}", value);
            Assert.AreEqual(gvalue, actual);
            actual = string.Format("{0:G}", value);
            Assert.AreEqual(gvalue, actual);
            actual = string.Format("{0:N}", value);
            Assert.AreEqual(value.Ticks.ToString("N0"), actual);
            actual = string.Format("{0:D}", value);
            Assert.AreEqual(value.Ticks.ToString("D"), actual);
        }
 /// <summary>
 ///     Should be greater or equal to the given <see cref="Instant" />
 /// </summary>
 /// <param name="expected"></param>
 /// <param name="because"></param>
 /// <param name="becauseArgs"></param>
 /// <returns></returns>
 public AndConstraint <InstantAssertions> BeGreaterOrEqualTo(Instant expected, string because = "", params object[] becauseArgs)
 {
     return(ExecuteAssertion(Subject >= expected, "to be greater than or equal to", expected, because, becauseArgs));
 }
 /// <summary>
 ///     Should be less than the given <see cref="Instant" />
 /// </summary>
 /// <param name="expected"></param>
 /// <param name="because"></param>
 /// <param name="becauseArgs"></param>
 /// <returns></returns>
 public AndConstraint <InstantAssertions> BeLessThan(Instant expected, string because = "", params object[] becauseArgs)
 {
     return(ExecuteAssertion(Subject < expected, "to be less than", expected, because, becauseArgs));
 }
Example #32
0
 public static Instant AsInstant(this Instant value)
 {
     return(value);
 }
 private static void UpdateVersionTimestamp(StreetNameDetail streetName, Instant versionTimestamp)
 => streetName.VersionTimestamp = versionTimestamp;
 public string GetRelativeTime(Instant start, Instant end)
 {
     return(GetRelativeTime(start.InUtc().LocalDateTime, end.InUtc().LocalDateTime));
 }
Example #35
0
 private void ChangeStatusScheduled(ChangeContentStatus command, Instant dueTime)
 {
     Raise(command, new ContentStatusScheduled {
         DueTime = dueTime
     });
 }
 /// <summary>
 ///     Should not be the given <see cref="Instant" />
 /// </summary>
 /// <param name="expected"></param>
 /// <param name="because"></param>
 /// <param name="becauseArgs"></param>
 /// <returns></returns>
 public AndConstraint <InstantAssertions> NotBe(Instant expected, string because = "", params object[] becauseArgs)
 {
     return(ExecuteAssertion(!Subject.HasValue || Subject != expected, "to not be", expected, because, becauseArgs));
 }
Example #37
0
 private static Instant FutureDays(int days)
 {
     return(Instant.FromDateTimeUtc(DateTime.UtcNow.Date.AddDays(days)));
 }
Example #38
0
 public static User Hypdrate(int id, Guid accessToken, string name, string emailHash, string countryCode, Instant createdDate)
 {
     return(new User(id, accessToken, name, emailHash, countryCode, createdDate));
 }
Example #39
0
        public void NodaTimeInstant_ParsesVariousValues(string input, Instant expected)
        {
            var actual = input.FromJson <Instant>();

            Assert.That(actual, Is.EqualTo(expected));
        }
Example #40
0
 public static User From(string name, string emailHash, string countryCode, Instant createdDate)
 {
     return(new User(null, Guid.NewGuid(), name, emailHash, countryCode, createdDate));
 }
Example #41
0
 public User(int?id, Guid accessToken, string name, string emailHash, string countryCode, Instant createdDate)
 {
     Id          = id;
     AccessToken = accessToken;
     Name        = name;
     EmailHash   = emailHash;
     CountryCode = countryCode;
     CreatedDate = createdDate;
 }
        public async IAsyncEnumerable <StoredEvent> QueryAllReverseAsync(string?streamFilter = null, Instant timestamp = default, int take = int.MaxValue,
                                                                         [EnumeratorCancellation] CancellationToken ct = default)
        {
            if (take <= 0)
            {
                yield break;
            }

            StreamPosition lastPosition = timestamp;

            var filterDefinition = CreateFilter(streamFilter, lastPosition);

            var find =
                Collection.Find(filterDefinition, Batching.Options)
                .Limit(take).Sort(Sort.Descending(TimestampField).Ascending(EventStreamField));

            var taken = 0;

            using (var cursor = await find.ToCursorAsync(ct))
            {
                while (taken < take && await cursor.MoveNextAsync(ct))
                {
                    foreach (var current in cursor.Current)
                    {
                        foreach (var @event in current.Filtered(lastPosition).Reverse())
                        {
                            yield return(@event);

                            taken++;

                            if (taken == take)
                            {
                                break;
                            }
                        }

                        if (taken == take)
                        {
                            break;
                        }
                    }
                }
            }
        }
Example #43
0
        public void SetUp()
        {
            testDescriptorDigest =
                DescriptorDigest.FromHash(
                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

            Mock.Get(mockBuildConfiguration).Setup(m => m.GetEventHandlers()).Returns(mockEventHandlers);

            Mock.Get(mockBuildConfiguration).Setup(m => m.GetContainerConfiguration()).Returns(mockContainerConfiguration);

            Mock.Get(mockBuildConfiguration).Setup(m => m.GetToolName()).Returns(() => null);

            Mock.Get(mockContainerConfiguration).Setup(m => m.GetCreationTime()).Returns(Instant.FromUnixTimeSeconds(0));

            Mock.Get(mockContainerConfiguration).Setup(m => m.GetEnvironmentMap()).Returns(ImmutableDictionary.Create <string, string>());

            Mock.Get(mockContainerConfiguration).Setup(m => m.GetProgramArguments()).Returns(ImmutableArray.Create <string>());

            Mock.Get(mockContainerConfiguration).Setup(m => m.GetExposedPorts()).Returns(ImmutableHashSet.Create <Port>());

            Mock.Get(mockContainerConfiguration).Setup(m => m.GetEntrypoint()).Returns(ImmutableArray.Create <string>());

            Mock.Get(mockContainerConfiguration).Setup(m => m.GetUser()).Returns("root");

            Mock.Get(mockCachedLayer).Setup(m => m.GetBlobDescriptor()).Returns(new BlobDescriptor(0, testDescriptorDigest));

            nonEmptyLayerHistory =
                HistoryEntry.CreateBuilder()
                .SetCreationTimestamp(Instant.FromUnixTimeSeconds(0))
                .SetAuthor("FibBase")
                .SetCreatedBy("fib-test")
                .Build();
            emptyLayerHistory =
                HistoryEntry.CreateBuilder()
                .SetCreationTimestamp(Instant.FromUnixTimeSeconds(0))
                .SetAuthor("FibBase")
                .SetCreatedBy("fib-test")
                .SetEmptyLayer(true)
                .Build();

            Image baseImage =
                Image.CreateBuilder(ManifestFormat.V22)
                .SetArchitecture("wasm")
                .SetOs("js")
                .AddEnvironment(ImmutableDic.Of("BASE_ENV", "BASE_ENV_VALUE", "BASE_ENV_2", "DEFAULT"))
                .AddLabel("base.label", "base.label.value")
                .AddLabel("base.label.2", "default")
                .SetWorkingDirectory("/base/working/directory")
                .SetEntrypoint(ImmutableArray.Create("baseImageEntrypoint"))
                .SetProgramArguments(ImmutableArray.Create("catalina.sh", "run"))
                .SetHealthCheck(
                    DockerHealthCheck.FromCommand(ImmutableArray.Create("CMD-SHELL", "echo hi"))
                    .SetInterval(Duration.FromSeconds(3))
                    .SetTimeout(Duration.FromSeconds(2))
                    .SetStartPeriod(Duration.FromSeconds(1))
                    .SetRetries(20)
                    .Build())
                .AddExposedPorts(ImmutableHashSet.Create(Port.Tcp(1000), Port.Udp(2000)))
                .AddVolumes(
                    ImmutableHashSet.Create(
                        AbsoluteUnixPath.Get("/base/path1"), AbsoluteUnixPath.Get("/base/path2")))
                .AddHistory(nonEmptyLayerHistory)
                .AddHistory(emptyLayerHistory)
                .AddHistory(emptyLayerHistory)
                .Build();

            Mock.Get(mockPullAndCacheBaseImageLayerStep).Setup(m => m.GetFuture()).Returns(Futures.ImmediateFutureAsync(mockCachedLayer));

            Mock.Get(mockPullAndCacheBaseImageLayersStep).Setup(m => m.GetFuture()).Returns(
                Futures.ImmediateFutureAsync <IReadOnlyList <ICachedLayer> >(
                    ImmutableArray.Create(
                        mockCachedLayer,
                        mockCachedLayer,
                        mockCachedLayer)));

            Mock.Get(mockPullBaseImageStep).Setup(m => m.GetFuture()).Returns(
                Futures.ImmediateFutureAsync(
                    new BaseImageWithAuthorization(baseImage, null)));

            mockClassesLayer = new CachedLayerWithType(mockCachedLayer, "classes");

            mockDependenciesLayer = new CachedLayerWithType(mockCachedLayer, "dependencies");

            mockExtraFilesLayer = new CachedLayerWithType(mockCachedLayer, "extra files");

            mockResourcesLayer = new CachedLayerWithType(mockCachedLayer, "resources");
        }
Example #44
0
        private static ZonedDateTime ParseZonedDateTime(string value)
        {
            var dateTime = DateTime.Parse(value);

            return(new ZonedDateTime(Instant.FromDateTimeUtc(dateTime.ToUniversalTime()), DateTimeZone.Utc));
        }
Example #45
0
        public async Task Test_generateHistoryObjectsAsync()
        {
            Mock.Get(mockBuildAndCacheApplicationLayersStep).Setup(s => s.GetFuture()).Returns(Task.FromResult <IReadOnlyList <ICachedLayer> >(ImmutableArray.Create(
                                                                                                                                                   mockDependenciesLayer,
                                                                                                                                                   mockResourcesLayer,
                                                                                                                                                   mockClassesLayer,
                                                                                                                                                   mockExtraFilesLayer)));
            string         createdBy      = "fib:" + ProjectInfo.VERSION;
            BuildImageStep buildImageStep =
                new BuildImageStep(
                    mockBuildConfiguration,
                    ProgressEventDispatcher.NewRoot(mockEventHandlers, "ignored", 1).NewChildProducer(),
                    mockPullBaseImageStep,
                    mockPullAndCacheBaseImageLayersStep,
                    mockBuildAndCacheApplicationLayersStep);
            Image image = await buildImageStep.GetFuture().ConfigureAwait(false);

            // Make sure history is as expected
            HistoryEntry expectedAddedBaseLayerHistory =
                HistoryEntry.CreateBuilder()
                .SetCreationTimestamp(Instant.FromUnixTimeSeconds(0))
                .SetComment("auto-generated by Fib")
                .Build();

            HistoryEntry expectedApplicationLayerHistoryDependencies =
                HistoryEntry.CreateBuilder()
                .SetCreationTimestamp(Instant.FromUnixTimeSeconds(0))
                .SetAuthor("Fib")
                .SetCreatedBy(createdBy)
                .SetComment("dependencies")
                .Build();

            HistoryEntry expectedApplicationLayerHistoryResources =
                HistoryEntry.CreateBuilder()
                .SetCreationTimestamp(Instant.FromUnixTimeSeconds(0))
                .SetAuthor("Fib")
                .SetCreatedBy(createdBy)
                .SetComment("resources")
                .Build();

            HistoryEntry expectedApplicationLayerHistoryClasses =
                HistoryEntry.CreateBuilder()
                .SetCreationTimestamp(Instant.FromUnixTimeSeconds(0))
                .SetAuthor("Fib")
                .SetCreatedBy(createdBy)
                .SetComment("classes")
                .Build();

            HistoryEntry expectedApplicationLayerHistoryExtrafiles =
                HistoryEntry.CreateBuilder()
                .SetCreationTimestamp(Instant.FromUnixTimeSeconds(0))
                .SetAuthor("Fib")
                .SetCreatedBy(createdBy)
                .SetComment("extra files")
                .Build();

            // Base layers (1 non-empty propagated, 2 empty propagated, 2 non-empty generated)
            Assert.AreEqual(nonEmptyLayerHistory, image.GetHistory()[0]);
            Assert.AreEqual(emptyLayerHistory, image.GetHistory()[1]);
            Assert.AreEqual(emptyLayerHistory, image.GetHistory()[2]);
            Assert.AreEqual(expectedAddedBaseLayerHistory, image.GetHistory()[3]);
            Assert.AreEqual(expectedAddedBaseLayerHistory, image.GetHistory()[4]);

            // Application layers (4 generated)
            Assert.AreEqual(expectedApplicationLayerHistoryDependencies, image.GetHistory()[5]);
            Assert.AreEqual(expectedApplicationLayerHistoryResources, image.GetHistory()[6]);
            Assert.AreEqual(expectedApplicationLayerHistoryClasses, image.GetHistory()[7]);
            Assert.AreEqual(expectedApplicationLayerHistoryExtrafiles, image.GetHistory()[8]);

            // Should be exactly 9 total
            Assert.AreEqual(9, image.GetHistory().Length);
        }
Example #46
0
 public Task ScheduleGroupedAsync(string key, T job, Instant dueTime, bool canInline,
                                  CancellationToken ct = default)
 {
     return(scheduling.ScheduleGroupedAsync(key, job, dueTime, canInline, ct));
 }
Example #47
0
        public static TimeSpan LocalTimeSpanFromUnixTime(this long unixTimeSeconds)
        {
            var localTime = Instant.FromUnixTimeSeconds(unixTimeSeconds).InZone(Zone);

            return(new TimeSpan(localTime.Hour, localTime.Minute, 00));
        }
 private static void UpdateVersionTimestamp(MunicipalityDetail municipality, Instant versionTimestamp)
 => municipality.VersionTimestamp = versionTimestamp;
 public void UpdateLastUsedCredentials(Instant currentInstant)
 {
     LastChangedCredentials = currentInstant;
 }
 public string GetRelativeTime(Instant instant)
 {
     return(GetRelativeTime(instant, SystemClock.Instance));
 }
 internal bool haveAlreadySentReport(Instant mostRecentReportBillingDate, SolarAndUtilityReport report)
 {
     return(!(mostRecentReportBillingDate.InZone(reportTimeZone).Date < report.billingDate));
 }
Example #52
0
 public bool Contains(Instant instant) => RawStart <= instant && instant < RawEnd;
 // Type is created as immutable to avoid problems with accidental changes to in-memory cache
 public JobProgress(Instant nextIterationStart, Instant nextIterationEnd, string nextToken)
 {
     NextIterationStart = nextIterationStart;
     NextIterationEnd   = nextIterationEnd;
     NextToken          = nextToken;
 }
Example #54
0
 /// <summary>
 /// Returns a copy of this zone interval, but with the given end instant.
 /// </summary>
 internal ZoneInterval WithEnd(Instant newEnd)
 {
     return(new ZoneInterval(Name, RawStart, newEnd, WallOffset, Savings));
 }
Example #55
0
 /// <summary>
 ///     Create new <see cref="Prayer" />.
 /// </summary>
 public Prayer(PrayerType type, Instant time)
 {
     Type = type;
     Time = time;
 }
Example #56
0
 /// <summary>
 /// Returns a copy of this zone interval, but with the given start instant.
 /// </summary>
 internal ZoneInterval WithStart(Instant newStart)
 {
     return(new ZoneInterval(Name, newStart, RawEnd, WallOffset, Savings));
 }
Example #57
0
        public void NodaTimeInstant_SerializesToExpectedText(Instant input, string expected)
        {
            var actual = input.ToJson();

            Assert.That(actual, Is.EqualTo(expected));
        }
Example #58
0
 public override string ToString()
 {
     return(Instant.FromDateTimeOffset(new DateTimeOffset(Year, Month, Day, Hour, Minute, Second, TimeSpan.Zero)).ToString());
 }
        public void WriteZoneIntervalTransition(Instant? previous, Instant value)
        {
            if (previous != null)
            {
                Preconditions.CheckArgument(value >= previous.Value, nameof(value), "Transition must move forward in time");
            }

            unchecked
            {
                if (value == Instant.BeforeMinValue)
                {
                    WriteCount(ZoneIntervalConstants.MarkerMinValue);
                    return;
                }
                if (value == Instant.AfterMaxValue)
                {
                    WriteCount(ZoneIntervalConstants.MarkerMaxValue);
                    return;
                }

                // In practice, most zone interval transitions will occur within 4000-6000 hours of the previous one
                // (i.e. about 5-8 months), and at an integral number of hours difference. We therefore gain a
                // significant reduction in output size by encoding transitions as the whole number of hours since the
                // previous, if possible.
                // If the previous value was "the start of time" then there's no point in trying to use it.
                if (previous != null && previous.Value != Instant.BeforeMinValue)
                {
                    // Note that the difference might exceed the range of a long, so we can't use a Duration here.
                    ulong ticks = (ulong) (value.Ticks - previous.Value.Ticks);
                    if (ticks % TicksPerHour == 0)
                    {
                        ulong hours = ticks / TicksPerHour;
                        // As noted above, this will generally fall within the 4000-6000 range, although values up to
                        // ~700,000 exist in TZDB.
                        if (ZoneIntervalConstants.MinValueForHoursSincePrevious <= hours &&
                            hours < ZoneIntervalConstants.MinValueForMinutesSinceEpoch)
                        {
                            WriteCount((int) hours);
                            return;
                        }
                    }
                }

                // We can't write the transition out relative to the previous transition, so let's next try writing it
                // out as a whole number of minutes since an (arbitrary, known) epoch.
                if (value >= ZoneIntervalConstants.EpochForMinutesSinceEpoch)
                {
                    ulong ticks = (ulong) (value.Ticks - ZoneIntervalConstants.EpochForMinutesSinceEpoch.Ticks);
                    if (ticks % TicksPerMinute == 0)
                    {
                        ulong minutes = ticks / TicksPerMinute;
                        // We typically have a count on the order of 80M here.
                        if (ZoneIntervalConstants.MinValueForMinutesSinceEpoch < minutes && minutes <= int.MaxValue)
                        {
                            WriteCount((int) minutes);
                            return;
                        }
                    }
                }
                // Otherwise, just write out a marker followed by the instant as a 64-bit number of ticks.  Note that
                // while most of the values we write here are actually whole numbers of _seconds_, optimising for that
                // case will save around 2KB (with tzdb 2012j), so doesn't seem worthwhile.
                WriteCount(ZoneIntervalConstants.MarkerRaw);
                WriteInt64(value.Ticks);
            }
        }
 public FantasyCriticUser(Guid userID, string userName, string normalizedUserName, string emailAddress,
                          string normalizedEmailAddress, bool emailConfirmed, string securityStamp, string passwordHash, Instant lastChangedCredentials)
 {
     UserID                 = userID;
     UserName               = userName;
     NormalizedUserName     = normalizedUserName;
     EmailAddress           = emailAddress;
     NormalizedEmailAddress = normalizedEmailAddress;
     EmailConfirmed         = emailConfirmed;
     SecurityStamp          = securityStamp;
     PasswordHash           = passwordHash;
     LastChangedCredentials = lastChangedCredentials;
 }