コード例 #1
0
 /// <summary>
 /// Constructs an instance with the given configuration, and the default jitter.
 /// </summary>
 /// <param name="retryBackoff">The backoff policy for the time between retries. Must not be null.</param>
 /// <param name="timeoutBackoff">The backoff policy for timeouts of retries. Must not be null.</param>
 /// <param name="totalExpiration">The total expiration, across all retries. Must not be null.</param>
 /// <param name="retryFilter">A predicate to determine whether or not a particular exception should cause the operation to be retried,
 /// or null for the default filter.</param>
 public RetrySettings(
     BackoffSettings retryBackoff,
     BackoffSettings timeoutBackoff,
     Expiration totalExpiration,
     Predicate<RpcException> retryFilter) : this(retryBackoff, timeoutBackoff, totalExpiration, retryFilter, null)
 {
 }
コード例 #2
0
 public SET(Key key, BulkString value, Expiration expiration, Condition?condition = null)
 {
     this.key        = key;
     this.value      = value;
     this.expiration = expiration;
     this.condition  = condition;
 }
コード例 #3
0
ファイル: CacheAdapter.cs プロジェクト: usamabintariq/NCache
        CacheItem CreateCacheItem(object value, Expiration expiration)
        {
            DateTime absolute = Cache.NoAbsoluteExpiration;
            TimeSpan sliding  = Cache.NoSlidingExpiration;

            if (expiration != null)
            {
                switch (expiration.ExpirationType)
                {
                case ExpirationType.Absolute:
                    absolute = DateTime.Now.AddMinutes(expiration.Duration);
                    break;

                case ExpirationType.Sliding:
                    sliding = TimeSpan.FromMinutes(expiration.Duration);
                    break;
                }
            }

            CacheItem item = new CacheItem(value);

            item.AbsoluteExpiration = absolute;
            item.SlidingExpiration  = sliding;
            return(item);
        }
コード例 #4
0
        public async Task ErrorWithBackoffAfterDeadline_FailsRetry()
        {
            // Create a clock that starts at zero ticks.
            var clock        = new FakeClock(0);
            var scheduler    = new AdvanceFakeClockScheduler(clock);
            var callSettings = CallSettings.FromExpiration(Expiration.FromDeadline(new DateTime(TimeSpan.FromSeconds(10).Ticks, DateTimeKind.Utc)));
            var state        = new RetryState(clock, scheduler, s_retrySettings, callSettings);

            // The retry info contains a wait time that is past the deadline of the call.
            // The retry state will throw a DeadlineExceeded error without waiting.
            var retryInfo = new Rpc.RetryInfo {
                RetryDelay = Duration.FromTimeSpan(TimeSpan.FromSeconds(20))
            };
            Metadata trailers = new Metadata
            {
                { RetryState.RetryInfoKey, retryInfo.ToByteArray() }
            };
            var exception = new RpcException(new Status(StatusCode.Unavailable, "Bang"), trailers);

            Assert.True(state.CanRetry(exception));
            await Assert.ThrowsAsync <RpcException>(() => state.WaitAsync(exception, default));

            // Check that the clock has not been advanced to verify that the retry state did not wait 20 seconds
            // before throwing an exception.
            Assert.Equal(0, clock.GetCurrentDateTimeUtc().Ticks);
        }
コード例 #5
0
        public async Task ConsecutiveErrors_FailsRetryWhenDeadlineExceeded()
        {
            var clock        = new FakeClock(0);
            var scheduler    = new AdvanceFakeClockScheduler(clock);
            var callSettings = CallSettings.FromExpiration(Expiration.FromDeadline(new DateTime(TimeSpan.FromSeconds(7).Ticks, DateTimeKind.Utc)));
            var state        = new RetryState(clock, scheduler, s_retrySettings, callSettings);

            var retryInfo = new Rpc.RetryInfo {
                RetryDelay = Duration.FromTimeSpan(TimeSpan.FromSeconds(3))
            };
            Metadata trailers = new Metadata
            {
                { RetryState.RetryInfoKey, retryInfo.ToByteArray() }
            };
            var exception = new RpcException(new Status(StatusCode.Unavailable, "Bang"), trailers);

            Assert.True(state.CanRetry(exception));
            await state.WaitAsync(exception, default);

            Assert.True(state.CanRetry(exception));
            await state.WaitAsync(exception, default);

            Assert.True(state.CanRetry(exception));
            await Assert.ThrowsAsync <RpcException>(() => state.WaitAsync(exception, default));

            // Verify that the clock has been advanced 6 seconds.
            Assert.Equal(TimeSpan.FromSeconds(6).Ticks, clock.GetCurrentDateTimeUtc().Ticks);
        }
コード例 #6
0
        /// <summary>
        /// Updates the call settings with configuration parameters.
        /// </summary>
        /// <param name="callSettings">The call settings.</param>
        /// <param name="config">The configuration.</param>
        /// <param name="serviceContext">The service context.</param>
        /// <returns></returns>
        private CallSettings UpdateCallSettingsWithConfigParameters(CallSettings callSettings,
                                                                    GoogleAdsConfig config, GoogleAdsServiceContext serviceContext)
        {
            callSettings = callSettings.WithHeader(MetadataKeyNames.DeveloperToken,
                                                   config.DeveloperToken)
                           .WithResponseMetadataHandler(delegate(Metadata metadata)
            {
                AdsResponseMetadata responseMetadata = new AdsResponseMetadata(metadata);
                serviceContext.OnResponseMetadataReceived(responseMetadata);
            });

            if (!string.IsNullOrEmpty(config.LoginCustomerId))
            {
                callSettings = callSettings.WithHeader(MetadataKeyNames.LoginCustomerId,
                                                       config.LoginCustomerId);
            }

            if (!string.IsNullOrEmpty(config.LinkedCustomerId))
            {
                callSettings = callSettings.WithHeader(MetadataKeyNames.LinkedCustomerId,
                                                       config.LinkedCustomerId);
            }

            if (!string.IsNullOrEmpty(config.LibraryIdentifierOverride))
            {
                callSettings = callSettings.WithHeader(MetadataKeyNames.LibraryIdentifier,
                                                       config.LibraryIdentifierOverride);
            }

            callSettings = callSettings.WithExpiration(Expiration.FromTimeout(
                                                           TimeSpan.FromMilliseconds(config.Timeout)));

            return(callSettings);
        }
コード例 #7
0
        /// <summary>验证数据,通过抛出异常的方式提示验证失败。</summary>
        /// <param name="isNew">是否插入</param>
        public override void Valid(Boolean isNew)
        {
            // 如果没有脏数据,则不需要进行任何处理
            if (!HasDirty)
            {
                return;
            }

            // 这里验证参数范围,建议抛出参数异常,指定参数名,前端用户界面可以捕获参数异常并聚焦到对应的参数输入框
            if (Created.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(Created), "Created不能为空!");
            }
            if (Expiration.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(Expiration), "Expiration不能为空!");
            }
            if (Description.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(Description), "Description不能为空!");
            }
            if (Value.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(Value), "Value不能为空!");
            }
            if (Type.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(Type), "Type不能为空!");
            }

            // 在新插入数据或者修改了指定字段时进行修正
        }
コード例 #8
0
ファイル: Deadline.cs プロジェクト: damccull/MyFlightbookWeb
        public bool IsValid()
        {
            ErrorString = string.Empty;

            if (String.IsNullOrEmpty(Name))
            {
                ErrorString = Resources.Currency.errDeadlineNoName;
            }
            if (RegenSpan <= 0 && RegenType != RegenUnit.None)
            {
                ErrorString = Resources.Currency.errDeadlineNoSpan;
            }
            if (!Expiration.HasValue() && AircraftHours <= 0)
            {
                ErrorString = Resources.Currency.errDeadlineNoDate;
            }
            if (Expiration.HasValue() && AircraftHours > 0)
            {
                ErrorString = Resources.Currency.errDeadlineHoursOrDate;
            }
            if (AircraftHours > 0 && AircraftID <= 0)
            {
                ErrorString = Resources.Currency.errDeadlineHoursWithoutAircraft;
            }
            return(ErrorString.Length == 0);
        }
コード例 #9
0
ファイル: Deadline.cs プロジェクト: damccull/MyFlightbookWeb
        /// <summary>
        /// Saves (inserts or updates) the deadline currency into the DB
        /// </summary>
        public bool FCommit()
        {
            if (!IsValid())
            {
                return(false);
            }

            if (AircraftID <= 0)
            {
                AircraftID    = 0;
                AircraftHours = 0;
            }

            string szQ = String.Format(CultureInfo.InvariantCulture, "{0} SET username=?user, Name=?displayname, Expiration=?expiration, RegenSpan=?regenspan, RegenUnit=?regentype, aircraftID=?aircraft, aircraftHours=?hours {1}",
                                       ID == idUnknownDeadline ? "INSERT INTO deadlines" : "UPDATE deadlines", ID == idUnknownDeadline ? string.Empty : "WHERE idDeadlines=?id");
            DBHelper dbh = new DBHelper(szQ);

            dbh.DoNonQuery(
                (comm) =>
            {
                comm.Parameters.AddWithValue("expiration", Expiration.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
                comm.Parameters.AddWithValue("regenspan", RegenSpan);
                comm.Parameters.AddWithValue("regentype", (int)RegenType);
                comm.Parameters.AddWithValue("user", Username);
                comm.Parameters.AddWithValue("displayname", Name.LimitTo(255));
                comm.Parameters.AddWithValue("aircraft", AircraftID);
                comm.Parameters.AddWithValue("hours", AircraftHours);
                comm.Parameters.AddWithValue("id", ID);
            });
            ErrorString = dbh.LastError;
            return(ErrorString.Length == 0);
        }
コード例 #10
0
ファイル: PollSettingsTest.cs プロジェクト: qipa/gax-dotnet
        public void Sub1MultiplierProhibitied()
        {
            var expiration = Expiration.FromTimeout(TimeSpan.FromSeconds(1));

            Assert.Throws <ArgumentOutOfRangeException>(
                () => new PollSettings(expiration, TimeSpan.FromSeconds(2), 0.9, TimeSpan.FromSeconds(2)));
        }
コード例 #11
0
        public void RetrySettingsTiming()
        {
            // Sample: RetrySettingsTiming
            // The overall operation mustn't take more than 30 seconds.
            Expiration totalExpiration = Expiration.FromTimeout(TimeSpan.FromSeconds(30));

            // The delay between one RPC finishing and when we make the next one.
            // Each delay is double the previous one, with a maximum of 5s.
            // The first delay is 1s, then 2s, then 4s, then 5s, then 5s, etc.
            BackoffSettings retryBackoff = new BackoffSettings(
                delay: TimeSpan.FromSeconds(1),
                maxDelay: TimeSpan.FromSeconds(5),
                delayMultiplier: 2.0);

            // How long each individual RPC is allowed to take.
            // Each timeout is 1.5x the previous one, with a maximum of 10s.
            // The first timeout is 4s, then 6s, then 9s, then 10s, then 10s etc.
            BackoffSettings timeoutBackoff = new BackoffSettings(
                delay: TimeSpan.FromSeconds(4),
                maxDelay: TimeSpan.FromSeconds(10),
                delayMultiplier: 1.5);

            RetrySettings settings = new RetrySettings(retryBackoff, timeoutBackoff, totalExpiration);
            // End sample
        }
コード例 #12
0
ファイル: PollSettingsTest.cs プロジェクト: qipa/gax-dotnet
        public void NegativeMaxDelayProhibitied()
        {
            var expiration = Expiration.FromTimeout(TimeSpan.FromSeconds(1));

            Assert.Throws <ArgumentOutOfRangeException>(
                () => new PollSettings(expiration, TimeSpan.FromSeconds(2), 1.0, TimeSpan.FromSeconds(-2)));
        }
コード例 #13
0
        /// <summary>
        /// Creates a distributed list to which instances of customers are to be added
        /// </summary>
        /// be the key against which distributed list is to be stored.</param>
        private static void CreateListWithDataTypeAttributes()
        {
            //Attribute NamedTags Dictionary
            NamedTagsDictionary namedTags = new NamedTagsDictionary();

            namedTags.Add("Customers", "Loyal");
            //Expiration
            Expiration expiration = new Expiration(ExpirationType.Absolute, new TimeSpan(0, 1, 0));
            //with Tag Frequent
            Tag tag = new Tag("Frequent");

            //Group for distributed datatype
            string group = "Potential";

            // Item priority Default
            CacheItemPriority cacheItemPriority = CacheItemPriority.Default;

            // Resync Operation is disabled
            ResyncOptions resyncOptions = new ResyncOptions(false);

            DataTypeAttributes attributes = new DataTypeAttributes
            {
                Expiration    = expiration,
                NamedTags     = namedTags,
                Group         = group,
                ResyncOptions = resyncOptions,
                Priority      = cacheItemPriority
            };

            // Creating distributed list with the defined attributes
            _cache.DataTypeManager.CreateList <Customer>(_datatype, attributes);
        }
コード例 #14
0
        // [START monitoring_uptime_check_create]
        public static object CreateUptimeCheck(string projectId, string hostName,
                                               string displayName)
        {
            // Define a new config.
            var config = new UptimeCheckConfig()
            {
                DisplayName       = displayName,
                MonitoredResource = new MonitoredResource()
                {
                    Type   = "uptime_url",
                    Labels = { { "host", hostName } }
                },
                HttpCheck = new UptimeCheckConfig.Types.HttpCheck()
                {
                    Path = "/",
                    Port = 80,
                },
                Timeout = TimeSpan.FromSeconds(10).ToDuration(),
                Period  = TimeSpan.FromMinutes(5).ToDuration()
            };
            // Create a client.
            var         client      = UptimeCheckServiceClient.Create();
            ProjectName projectName = new ProjectName(projectId);
            // Create the config.
            var newConfig = client.CreateUptimeCheckConfig(
                projectName,
                config,
                CallSettings.FromExpiration(
                    Expiration.FromTimeout(
                        TimeSpan.FromMinutes(2))));

            Console.WriteLine(newConfig.Name);
            return(0);
        }
コード例 #15
0
        public async Task ResetDeadline()
        {
            var clock        = new FakeClock(0);
            var scheduler    = new AdvanceFakeClockScheduler(clock);
            var callSettings = CallSettings.FromExpiration(Expiration.FromDeadline(new DateTime(TimeSpan.FromSeconds(7).Ticks, DateTimeKind.Utc)));
            var state        = new RetryState(clock, scheduler, s_retrySettings, callSettings);

            var retryInfo = new Rpc.RetryInfo {
                RetryDelay = Duration.FromTimeSpan(TimeSpan.FromSeconds(3))
            };
            Metadata trailers = new Metadata
            {
                { RetryState.RetryInfoKey, retryInfo.ToByteArray() }
            };
            var exception = new RpcException(new Status(StatusCode.Unavailable, "Bang"), trailers);

            Assert.True(state.CanRetry(exception));
            await state.WaitAsync(exception, default);

            Assert.True(state.CanRetry(exception));
            await state.WaitAsync(exception, default);

            // Reset does not change the absolute deadline of the call.
            // The next retry attempt will therefore fail.
            state.Reset();

            Assert.True(state.CanRetry(exception));
            await Assert.ThrowsAsync <RpcException>(() => state.WaitAsync(exception, default));

            Assert.Equal(TimeSpan.FromSeconds(6).Ticks, clock.GetCurrentDateTimeUtc().Ticks);
        }
コード例 #16
0
        public async Task MultipleCallsEventualSuccess(bool async, bool serverStreaming)
        {
            var callDuration  = TimeSpan.FromTicks(300);
            var failures      = 4;      // Fifth call will succeed
            var name          = "name"; // Copied from request to response
            var scheduler     = new FakeScheduler();
            var time0         = scheduler.Clock.GetCurrentDateTimeUtc();
            var server        = new Server(failures, callDuration, scheduler);
            var retrySettings = new RetrySettings(
                retryBackoff: DoublingBackoff,
                timeoutBackoff: ConstantBackoff,
                totalExpiration: Expiration.FromTimeout(TimeSpan.FromSeconds(1)),
                retryFilter: null,
                delayJitter: RetrySettings.NoJitter);

            await scheduler.RunAsync(async() =>
            {
                var callSettings = CallSettings.FromCallTiming(CallTiming.FromRetry(retrySettings));
                var request      = new SimpleRequest {
                    Name = name
                };
                var result = await Call(async, serverStreaming, scheduler, server, request, callSettings);
                Assert.Equal(name, result.Name);
            });

            var firstCall  = time0;
            var secondCall = firstCall + callDuration + TimeSpan.FromTicks(1000);  // Delay for 1000 ticks
            var thirdCall  = secondCall + callDuration + TimeSpan.FromTicks(2000); // Delay for 2000 ticks
            var fourthCall = thirdCall + callDuration + TimeSpan.FromTicks(4000);  // Delay for 4000 ticks
            var fifthCall  = fourthCall + callDuration + TimeSpan.FromTicks(5000); // Delay for 5000 ticks, as that's the max

            server.AssertCallTimes(firstCall, secondCall, thirdCall, fourthCall, fifthCall);
            // Time of last action was when the call returned
            Assert.Equal(fifthCall + callDuration, scheduler.Clock.GetCurrentDateTimeUtc());
        }
コード例 #17
0
 public async Task CanAddALotOfEntitiesWithSameExpiry_ThenReadItBeforeItExpires_ButWillNotBeAbleToReadItAfterExpiry(int count)
 {
     using (var expiration = new Expiration())
     {
         await expiration.CanAddALotOfEntitiesWithSameExpiry_ThenReadItBeforeItExpires_ButWillNotBeAbleToReadItAfterExpiry(count);
     }
 }
コード例 #18
0
 /// <summary>
 /// Constructs an instance with the given configuration, and the default jitter.
 /// </summary>
 /// <param name="retryBackoff">The backoff policy for the time between retries. Must not be null.</param>
 /// <param name="timeoutBackoff">The backoff policy for timeouts of retries. Must not be null.</param>
 /// <param name="totalExpiration">The total expiration, across all retries. Must not be null.</param>
 /// <param name="retryFilter">A predicate to determine whether or not a particular exception should cause the operation to be retried,
 /// or null for the default filter.</param>
 public RetrySettings(
     BackoffSettings retryBackoff,
     BackoffSettings timeoutBackoff,
     Expiration totalExpiration,
     Predicate <RpcException> retryFilter) : this(retryBackoff, timeoutBackoff, totalExpiration, retryFilter, null)
 {
 }
コード例 #19
0
        public async Task RetryAfterTotalExpiration()
        {
            var settings = new BigtableServiceApiSettings();

            // Don't allow for any time to retry.
            settings.MutateRowsSettings = CallSettings.FromExpiration(Expiration.FromTimeout(TimeSpan.Zero));

            var request = new MutateRowsRequest
            {
                Entries =
                {
                    Mutations.CreateEntry("a", Mutations.DeleteFromRow()),
                    Mutations.CreateEntry("b", Mutations.DeleteFromRow()),
                    Mutations.CreateEntry("c", Mutations.DeleteFromRow())
                }
            };
            var client = Utilities.CreateMutateRowsMockClient(
                request,
                entriesForInitialStream: new[]
            {
                Utilities.CreateMutateRowsResponseEntry(0, Code.Ok),
                Utilities.CreateMutateRowsResponseEntry(1, Code.DeadlineExceeded),
                Utilities.CreateMutateRowsResponseEntry(2, Code.Ok)
            },
                entriesForRetryStreams: new[]
            {
                // 1st retry response entries
                new[] { Utilities.CreateMutateRowsResponseEntry(0, Code.Ok) }
            },
                settings: settings);

            var exception = await Assert.ThrowsAsync <RpcException>(() => client.MutateRowsAsync(request));

            Assert.Equal(StatusCode.DeadlineExceeded, exception.StatusCode);
        }
コード例 #20
0
ファイル: WHOISRecord.cs プロジェクト: shekky/whois-resolver
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendLine($"Domain: {Domain}");
            stringBuilder.AppendLine($"Registry Domain Id: {DomainId}");
            stringBuilder.AppendLine($"Registrar WhoIs Server: {WhoIsServer}");
            stringBuilder.AppendLine($"Registrar Url: {Url}");
            stringBuilder.AppendLine($"Updated Date: {Updated.ToString()}");
            stringBuilder.AppendLine($"Creation Date: {Created.ToString()}");
            stringBuilder.AppendLine($"Expiration Date: {Expiration.ToString()}");
            stringBuilder.AppendLine($"Registrar: {Registrar}");
            stringBuilder.AppendLine($"Registrar IANA Id: {IANAId}");
            stringBuilder.AppendLine($"Registrar Abuse Contact Email: {AbuseContactEmail}");
            stringBuilder.AppendLine($"Registrar Abuse Contact Phone: {AbuseContactPhone}");

            stringBuilder.AppendLine($"{Environment.NewLine}Name Servers{Environment.NewLine}");
            foreach (var nameServer in NameServers)
            {
                stringBuilder.AppendLine($"\tDomain: {nameServer.Domain}");
            }

            stringBuilder.AppendLine(" ");
            stringBuilder.AppendLine($"DNSSec: {DNSSec}");


            return(stringBuilder.ToString());
        }
コード例 #21
0
        /// <summary>
        /// Gets the hash code for this object.
        /// </summary>
        /// <returns>
        /// The hash code for this object.
        /// </returns>
        /// <remarks>
        /// * CA2218:
        ///   * If two objects are equal in value based on the Equals override, they must both return the same value for calls
        ///     to GetHashCode.
        ///   * GetHashCode must be overridden whenever Equals is overridden.
        /// * It is fine if the value overflows.
        /// </remarks>
        public override int GetHashCode()
        {
            int result = Id.GetHashCode() +
                         GlobalUserId.GetHashCode() +
                         Expiration.GetHashCode() +
                         CardBrand.GetHashCode() +
                         RewardPrograms.GetHashCode();

            if (NameOnCard != null)
            {
                result += NameOnCard.GetHashCode();
            }

            if (LastFourDigits != null)
            {
                result += LastFourDigits.GetHashCode();
            }

            if (PanToken != null)
            {
                result += PanToken.GetHashCode();
            }

            return(result);
        }
コード例 #22
0
        public async Task PollUntilCompletedAsync_AlreadyCompleted()
        {
            var client = new FakeOperationsClient();

            client.AddSuccessfulOperation("op", client.Clock.GetCurrentDateTimeUtc(), new StringValue {
                Value = "result"
            });
            var initial = Operation <StringValue, Timestamp> .PollOnceFromName("op", client);

            Assert.True(initial.IsCompleted);
            var expectedMetadata            = GenerateExpectedMetadata(client.Clock, 0);
            List <Timestamp> actualMetadata = new List <Timestamp>();
            await client.FakeScheduler.RunAsync(async() =>
            {
                Assert.Equal(1, client.RequestCount);
                var settings = new PollSettings(Expiration.FromTimeout(TimeSpan.FromSeconds(5)), TimeSpan.FromSeconds(2));
                var final    = await initial.PollUntilCompletedAsync(settings, metadataCallback: actualMetadata.Add);
                Assert.Equal("result", final.Result.Value);
                // No more requests due to PollUntilCompletedAsync call
                Assert.Equal(1, client.RequestCount);
            });

            // Metadata was still added despite no RPCs being made
            Assert.Equal(expectedMetadata, actualMetadata);
        }
コード例 #23
0
        public Uri GetAuthorizationUrl(string applicationName, Scope scope, Expiration expiration)
        {
            Guard.NotNullOrEmpty(applicationName, "applicationName");

            return(new Uri(string.Format("{0}/connect?key={1}&name={2}&response_type=token&scope={3}&expiration={4}",
                                         BaseUrl, _applicationKey, applicationName, scope.ToScopeString(), expiration.ToExpirationString())));
        }
コード例 #24
0
        public async Task RetryCancellation(bool serverStreaming, [CombinatorialValues(1500, 3500)] int delayMs)
        {
            // Note: Cannot test cancellation during wait for response header, due to FakeScheduler shortcomings.
            var async         = true;
            var scheduler     = new FakeScheduler();
            var time0         = scheduler.Clock.GetCurrentDateTimeUtc();
            var server        = new Server(10, TimeSpan.FromSeconds(1), scheduler);
            var retrySettings = new RetrySettings(
                retryBackoff: new BackoffSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), 1.0),
                timeoutBackoff: new BackoffSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), 1.0),
                delayJitter: RetrySettings.NoJitter,
                totalExpiration: Expiration.FromTimeout(TimeSpan.FromSeconds(10)),
                retryFilter: RetrySettings.DefaultFilter);
            var  delay = TimeSpan.FromMilliseconds(delayMs);
            Task task  = scheduler.RunAsync(async() =>
            {
                var cts    = new CancellationTokenSource();
                var unused = Task.Run(async() =>
                {
                    await scheduler.Delay(delay);
                    cts.Cancel();
                });
                var callSettings = CallSettings.FromCallTiming(CallTiming.FromRetry(retrySettings)).WithCancellationToken(cts.Token);
                var request      = new SimpleRequest {
                    Name = "irrelevant"
                };
                await Call(async, serverStreaming, scheduler, server, request, callSettings);
            });
            await Assert.ThrowsAsync <TaskCanceledException>(() => task);

            Assert.Equal(time0 + delay, scheduler.Clock.GetCurrentDateTimeUtc());
        }
コード例 #25
0
        public static Expiration GetExpiration(DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            #region Creating Sliding Expiration

            var modernSlidingExpiration = new Expiration(ExpirationType.None);

            if (slidingExpiration != TimeSpan.Zero)
            {
                modernSlidingExpiration = new Expiration(ExpirationType.Sliding, slidingExpiration);
            }

            #endregion

            #region Creating Absolute Expiration

            var modernAbsoluteExpiration = new Expiration(ExpirationType.None);

            if (absoluteExpiration.ToUniversalTime() != DateTime.MaxValue.ToUniversalTime())
            {
                modernAbsoluteExpiration = new Expiration(ExpirationType.Absolute, absoluteExpiration.ToLocalTime() - DateTime.Now.ToLocalTime());
            }

            #endregion

            return(modernAbsoluteExpiration.Type == ExpirationType.None ? modernSlidingExpiration : modernAbsoluteExpiration);
        }
コード例 #26
0
        public async Task RetryFilter_EventualSuccess(bool async, bool serverStreaming)
        {
            StatusCode failureCode = StatusCode.NotFound;

            StatusCode[] filterCodes  = new[] { StatusCode.NotFound, StatusCode.DeadlineExceeded };
            var          callDuration = TimeSpan.FromTicks(100);
            var          failures     = 1;
            var          scheduler    = new FakeScheduler();
            var          server       = new Server(failures, callDuration, scheduler, failureCode);
            // We're not really interested in the timing in this test.
            var retrySettings = new RetrySettings(
                retryBackoff: ConstantBackoff,
                timeoutBackoff: ConstantBackoff,
                delayJitter: RetrySettings.NoJitter,
                totalExpiration: Expiration.FromTimeout(TimeSpan.FromSeconds(1)),
                retryFilter: RetrySettings.FilterForStatusCodes(filterCodes));

            await scheduler.RunAsync(async() =>
            {
                var callSettings = CallSettings.FromCallTiming(CallTiming.FromRetry(retrySettings));
                var request      = new SimpleRequest {
                    Name = "irrelevant"
                };
                await Call(async, serverStreaming, scheduler, server, request, callSettings);
            });

            Assert.True(server.CallTimes.Count() > 1);
        }
コード例 #27
0
        public async Task RetryFilter_EventualFailure(bool async, bool serverStreaming, StatusCode failureCode, StatusCode[] filterCodes)
        {
            var callDuration = TimeSpan.FromTicks(100);
            var failures     = 1;
            var scheduler    = new FakeScheduler();
            var server       = new Server(failures, callDuration, scheduler, failureCode);
            // We're not really interested in the timing in this test.
            var retrySettings = new RetrySettings(
                retryBackoff: ConstantBackoff,
                timeoutBackoff: ConstantBackoff,
                delayJitter: RetrySettings.NoJitter,
                totalExpiration: Expiration.FromTimeout(TimeSpan.FromSeconds(1)),
                retryFilter: RetrySettings.FilterForStatusCodes(filterCodes));

            var task = scheduler.RunAsync(async() =>
            {
                var callSettings = CallSettings.FromCallTiming(CallTiming.FromRetry(retrySettings));
                var request      = new SimpleRequest {
                    Name = "irrelevant"
                };
                await Call(async, serverStreaming, scheduler, server, request, callSettings);
            });
            await Assert.ThrowsAsync <RpcException>(() => task);

            Assert.Equal(1, server.CallTimes.Count());
        }
コード例 #28
0
        public async Task CallSettingsDeadlineIsObserved(bool async, bool serverStreaming)
        {
            var callDuration  = TimeSpan.FromTicks(300);
            var failures      = 4; // Fifth call would succeed, but we won't get that far.
            var scheduler     = new FakeScheduler();
            var time0         = scheduler.Clock.GetCurrentDateTimeUtc();
            var server        = new Server(failures, callDuration, scheduler);
            var callable      = server.Callable;
            var retrySettings = new RetrySettings(
                retryBackoff: DoublingBackoff,
                timeoutBackoff: ConstantBackoff,
                totalExpiration: Expiration.FromTimeout(TimeSpan.FromTicks(2500)),
                retryFilter: null,
                delayJitter: RetrySettings.NoJitter);

            var task = scheduler.RunAsync(async() =>
            {
                // Expiration makes it fail while waiting to make third call
                var callSettings = CallSettings.FromCallTiming(CallTiming.FromRetry(retrySettings));
                var request      = new SimpleRequest {
                    Name = "irrelevant"
                };
                await Call(async, serverStreaming, scheduler, server, request, callSettings);
            });
            await Assert.ThrowsAsync <RpcException>(() => task);

            var firstCall  = time0;
            var secondCall = firstCall + callDuration + TimeSpan.FromTicks(1000);

            server.AssertCallTimes(firstCall, secondCall);

            // We fail immediately when we work out that we would time out before we make the third
            // call - so this is before the actual total timeout.
            Assert.Equal((secondCall + callDuration).Ticks, scheduler.Clock.GetCurrentDateTimeUtc().Ticks);
        }
コード例 #29
0
        public async Task ExponentialTimeouts(bool async, bool serverStreaming)
        {
            var callDuration  = TimeSpan.FromTicks(300);
            var failures      = 2;
            var scheduler     = new FakeScheduler();
            var time0         = scheduler.Clock.GetCurrentDateTimeUtc();
            var server        = new Server(failures, callDuration, scheduler);
            var callable      = server.Callable;
            var retrySettings = new RetrySettings(
                retryBackoff: ConstantBackoff,   // 1500 ticks always
                timeoutBackoff: DoublingBackoff, // 1000, then 2000, then 4000
                totalExpiration: Expiration.FromTimeout(TimeSpan.FromTicks(4500)),
                retryFilter: null,
                delayJitter: RetrySettings.NoJitter);

            await scheduler.RunAsync(async() =>
            {
                // Expiration truncates the third timeout. We expect:
                // Call 1: t=0, deadline=1000, completes at 300
                // Call 2: t=1800, deadline=3800 (2000+1800), completes at 2100
                // Call 3, t=3600, deadline=4500 (would be 7600, but overall deadline truncates), completes at 3900 (with success)
                var callSettings = CallSettings.FromCallTiming(CallTiming.FromRetry(retrySettings));
                var request      = new SimpleRequest {
                    Name = "irrelevant"
                };
                await Call(async, serverStreaming, scheduler, server, request, callSettings);
            });

            server.AssertCallTimes(time0, time0 + TimeSpan.FromTicks(1800), time0 + TimeSpan.FromTicks(3600));
            server.AssertDeadlines(time0 + TimeSpan.FromTicks(1000), time0 + TimeSpan.FromTicks(3800), time0 + TimeSpan.FromTicks(4500));
            Assert.Equal(3900L, scheduler.Clock.GetCurrentDateTimeUtc().Ticks);
        }
コード例 #30
0
        /// <summary>
        /// Creates a service context that binds the service, callsettings and the client.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <returns>The service context.</returns>
        private GoogleAdsServiceContext CreateServiceContext(GoogleAdsConfig config)
        {
            GoogleAdsServiceContext serviceContext = new GoogleAdsServiceContext();
            CallSettings            callSettings   = CallSettings.FromCallTiming(
                CallTiming.FromRetry(new RetrySettings(
                                         retryBackoff : backoffSettings,
                                         timeoutBackoff : backoffSettings,
                                         totalExpiration : Expiration.FromTimeout(TimeSpan.FromMilliseconds(
                                                                                      config.Timeout)),
                                         retryFilter : retryFilter
                                         )))
                                                     .WithHeader(GoogleAdsConfig.DEVELOPER_TOKEN_KEYNAME, config.DeveloperToken)
                                                     .WithResponseMetadataHandler(delegate(Metadata metadata)
            {
                GoogleAdsResponseMetadata responseMetadata = new GoogleAdsResponseMetadata(metadata);
                serviceContext.OnResponseMetadataReceived(responseMetadata);
            });

            if (!string.IsNullOrEmpty(config.LoginCustomerId))
            {
                callSettings.WithHeader("login-customer-id", config.LoginCustomerId);
            }

            serviceContext.CallSettings = callSettings;
            return(serviceContext);
        }
コード例 #31
0
        public async Task FirstCallSucceeds(bool async, bool serverStreaming)
        {
            var name          = "name"; // Copied from request to response
            var scheduler     = new FakeScheduler();
            var time0         = scheduler.Clock.GetCurrentDateTimeUtc();
            var server        = new Server(0, TimeSpan.FromTicks(300), scheduler);
            var retrySettings = new RetrySettings(
                retryBackoff: DoublingBackoff,
                timeoutBackoff: ConstantBackoff,
                totalExpiration: Expiration.FromTimeout(TimeSpan.FromSeconds(1)),
                retryFilter: null,
                delayJitter: RetrySettings.NoJitter);

            await scheduler.RunAsync(async() =>
            {
                var callSettings = CallSettings.FromCallTiming(CallTiming.FromRetry(retrySettings));
                var request      = new SimpleRequest {
                    Name = name
                };
                var result = await Call(async, serverStreaming, scheduler, server, request, callSettings);
                Assert.Equal(name, result.Name);
            });

            server.AssertCallTimes(time0);
            // Time of last action was when the call returned
            Assert.Equal(300, scheduler.Clock.GetCurrentDateTimeUtc().Ticks);
        }
コード例 #32
0
ファイル: Trello.cs プロジェクト: Bunk/trellow
	    public Task<Uri> GetAuthorizationUri(string applicationName, Scope scope, Expiration expiration, Uri callbackUri = null)
	    {
	        return _client.GetAuthorizationUri(applicationName, scope, expiration, callbackUri);
	    }
コード例 #33
0
ファイル: CallTiming.cs プロジェクト: googleapis/gax-dotnet
 private CallTiming(RetrySettings retry, Expiration expiration)
 {
     Retry = retry;
     Expiration = expiration;
 }
コード例 #34
0
ファイル: Trello.cs プロジェクト: tjanssens/trellonet
 public Uri GetAuthorizationUrl(string applicationName, Scope scope, Expiration expiration = Expiration.ThirtyDays)
 {
     return _restClient.GetAuthorizationUrl(applicationName, scope, expiration);
 }
コード例 #35
0
 /// <summary>
 /// Constructs an instance with the given backoff configuration, the default RPC filter and
 /// jitter.
 /// </summary>
 /// <param name="retryBackoff">The backoff policy for the time between retries. Must not be null.</param>
 /// <param name="timeoutBackoff">The backoff policy for timeouts of retries. Must not be null.</param>
 /// <param name="totalExpiration">The total expiration, across all retries. Must not be null.</param>
 public RetrySettings(
     BackoffSettings retryBackoff,
     BackoffSettings timeoutBackoff,
     Expiration totalExpiration) : this(retryBackoff, timeoutBackoff, totalExpiration, null, null)
 {
 }
コード例 #36
0
ファイル: CallTiming.cs プロジェクト: googleapis/gax-dotnet
 /// <summary>
 /// Create a <see cref="CallTiming"/> with a simple expiration; no retry.
 /// </summary>
 /// <param name="expiration">The <see cref="Google.Api.Gax.Expiration"/> for a call without retry.</param>
 /// <returns>A <see cref="CallTiming"/> with the specified expiration; without retry.</returns>
 public static CallTiming FromExpiration(Expiration expiration) =>
     new CallTiming(null, GaxPreconditions.CheckNotNull(expiration, nameof(expiration)));
コード例 #37
0
 public SessionAttribute(List<string> itemsInSession, Expiration expiration)
     : this(itemsInSession)
 {
     _itemsInSession = itemsInSession;
     _expiration = expiration;
 }
コード例 #38
0
 /// <summary>
 /// Constructs an instance with the given configuration.
 /// </summary>
 /// <param name="retryBackoff">The backoff policy for the time between retries. Must not be null.</param>
 /// <param name="timeoutBackoff">The backoff policy for timeouts of retries. Must not be null.</param>
 /// <param name="totalExpiration">The total expiration, across all retries. Must not be null.</param>
 /// <param name="retryFilter">A predicate to determine whether or not a particular exception should cause the operation to be retried,
 /// or null for the default filter.</param>
 /// <param name="delayJitter">The delay jitter to apply for delays, or null for the defautl (random) jitter.</param>
 public RetrySettings(
     BackoffSettings retryBackoff,
     BackoffSettings timeoutBackoff,
     Expiration totalExpiration,
     Predicate<RpcException> retryFilter,
     IJitter delayJitter)
 {
     RetryBackoff = GaxPreconditions.CheckNotNull(retryBackoff, nameof(retryBackoff));
     TimeoutBackoff = GaxPreconditions.CheckNotNull(timeoutBackoff, nameof(timeoutBackoff));
     TotalExpiration = GaxPreconditions.CheckNotNull(totalExpiration, nameof(totalExpiration));
     RetryFilter = retryFilter ?? DefaultFilter;
     DelayJitter = delayJitter ?? RandomJitter;
 }