public async Task <bool> HandleAsync(TMessage message) { try { var ret = await RetryHelper.RetryAsync(async() => await DoHandleAsync(message), Idempotent?_maxRetry : 1, _backoffMs, p => { var ex = p as Exception <LightMessagerExceptionArgs>; if (ex != null) { return(true); } return(false); }); if (ret) { MarkConsumed(message); } return(ret); } catch (Exception ex) { _logger.Debug("未知异常:" + ex.Message + ";堆栈:" + ex.StackTrace); DoRequeue(message); } return(false); }
public async Task PlayAlbum(string albumId, string accessToken, CancellationToken cancellationToken) { await RetryHelper.RetryAsync( () => _player.PlayAlbum(albumId, accessToken: accessToken), logger : _logger, cancellationToken : cancellationToken); }
public override async Task <WorkLog> DoWorkAsync(IList <WorkLog> workLogs, WorkItemBase workItem = null) { // TODO --> Validar data local com base na UTC e corrigir, caso necessário. if (workItem == null) { throw new ArgumentNullException($"{nameof(workItem)} must be informed to CreateFileProcess."); } DateTime sendDate = ((ICreateFileWorkItemArguments)workItem.Arguments).SendDate; Console.WriteLine($"Creating file using parameter: {sendDate }"); string toSend = JsonConvert.SerializeObject(new { SendDate = sendDate }); dynamic id = await RetryHelper.RetryAsync <Exception>(async() => await PostWorkItemEndpointAddress <Guid>(toSend), 3, TimeSpan.FromSeconds(3), Logger); Console.WriteLine("Created file Id: {0}", id); CreateFileWorkResult result = new CreateFileWorkResult { FileName = "GNS.ORG001.T0000001.CS_20180129170710", WorkId = id, Success = true }; return(new WorkLog(this, result)); }
public async Task PlayPlaylist(string playlistId, string accessToken, CancellationToken cancellationToken) { await RetryHelper.RetryAsync( () => _player.PlayPlaylist(playlistId, accessToken), logger : _logger, cancellationToken : cancellationToken); }
public async Task <Models.Playlist[]> FindPlaylists(string searchText, string accessToken, CancellationToken cancellationToken) { string uriOrId = null; var uri = new SpotifyUri(searchText); if (uri.IsValid && uri.ItemType == "playlist") { uriOrId = uri.Uri; } //if (uri.IsValid) //{ // // spotify:user:daniellarsennz:playlist:5JOGypafQPEx0GkXyLb948 // MatchCollection matchesUserUri = SpotifyUriHelper.SpotifyUserPlaylistUriRegEx.Matches(searchText); // if (matchesUserUri.Any()) uriOrId = matchesUserUri[0].Value; //} //if (uriOrId == null) //{ // // spotify:playlist:5JOGypafQPEx0GkXyLb948 // MatchCollection matchesUri = SpotifyUriHelper.SpotifyUriRegEx.Matches(searchText); // if (matchesUri.Any() && SpotifyUriHelper.SpotifyUriType(matchesUri[0].Value) == "playlist") // { // uriOrId = matchesUri[0].Value; // } //} if (uriOrId == null) { // Spotify URL // https://open.spotify.com/user/daniellarsennz/playlist/3dzMCDJTULeZ7IgbWvotSB?si=bm-3giiVS76AW5yXplr-pQ MatchCollection matchesPlaylistUri = SpotifyPlaylistUrlRegex.Matches(searchText); if (matchesPlaylistUri.Any()) { uriOrId = matchesPlaylistUri[0].Value.Split('/').Last(); } } if (uriOrId != null) { return new[] { await GetPlaylist(accessToken, uriOrId) } } ; // search for the Playlist var results = await RetryHelper.RetryAsync( () => _playlists.SearchPlaylists(searchText, accessToken: accessToken), logger : _logger, cancellationToken : cancellationToken); if (results.Total > 0) { return(results.Items.Take(3).Select(ItemMappers.MapToPlaylist).ToArray()); } return(null); }
public async Task Process(IBatchMigrationContext batchContext) { object identityObject = null; string identityValue = null; HashSet <string> identitiesToProcess = new HashSet <string>(StringComparer.CurrentCultureIgnoreCase); foreach (var sourceWorkItem in batchContext.SourceWorkItems) { foreach (var field in context.IdentityFields) { if (sourceWorkItem.Fields.TryGetValueIgnoringCase(field, out identityObject)) { identityValue = (string)identityObject; if (!string.IsNullOrEmpty(identityValue) && identityValue.Contains("<") && identityValue.Contains(">") && (identityValue.Contains("@"))) { // parse out email address from the combo string identityValue = identityValue.Substring(identityValue.LastIndexOf("<") + 1, identityValue.LastIndexOf(">") - identityValue.LastIndexOf("<") - 1); if (!identitiesToProcess.Contains(identityValue) && !this.context.ValidatedIdentities.Contains(identityValue) && !this.context.InvalidIdentities.Contains(identityValue)) { Logger.LogTrace(LogDestination.File, $"Found identity {identityValue} in batch {batchContext.BatchId} which has not yet been validated for the target account"); identitiesToProcess.Add(identityValue); } } } } } Logger.LogTrace(LogDestination.File, $"Adding {identitiesToProcess.Count} identities to the account for batch {batchContext.BatchId}"); foreach (var identity in identitiesToProcess) { try { await RetryHelper.RetryAsync(async() => { return(await graphClient.CreateUserAsync(new GraphUserPrincipalNameCreationContext() { PrincipalName = identity }, Groups)); }, 5); context.ValidatedIdentities.Add(identity); } catch (Exception ex) { Logger.LogWarning(LogDestination.File, ex, $"Unable to add identity {identity} to the target account for batch {batchContext.BatchId}"); context.InvalidIdentities.Add(identity); } } Logger.LogTrace(LogDestination.File, $"Completed adding {identitiesToProcess.Count} identities to the account for batch {batchContext.BatchId}"); }
public async Task Retry_AsyncFunc_Invokes1Time() { // arrange int i = 0; // act int result = await RetryHelper.RetryAsync(() => AddOne(i), times : 3, waitMs : 0); // assert Assert.AreEqual(1, result); }
public async Task SetSpotifyAccessToken(string userId, BearerAccessRefreshToken token) { await RetryHelper.RetryAsync(async() => { var storedToken = await _data.GetOrDefault(UserAccessToken.CanonicalId(userId), userId); var uat = new UserAccessRefreshToken(userId, token); uat.EnforceInvariants(); if (storedToken == null) { await _data.Create(uat); } else { await _data.Replace(uat, storedToken.ETag); } }, waitMs : 10, logger : _logger); }
public override async Task <WorkLog> DoWorkAsync(IList <WorkLog> workLogs, WorkItemBase workItem = null) { MaskFileWorkResult workResult = GetWorkLog <MaskFileWorkResult>(workLogs); Console.WriteLine($"Maping file: {workResult.MaskedFileName}"); dynamic id = await RetryHelper.RetryAsync <Exception>(async() => await PostWorkItemEndpointAddress <Guid>(), 3, TimeSpan.FromSeconds(3), Logger); Console.WriteLine("Mapped file Id: {0}", id); MapFileWorkResult result = new MapFileWorkResult { ClearingFileId = 100, WorkId = id, Success = true }; return(new WorkLog(this, result)); }
public override async Task <WorkLog> DoWorkAsync(IList <WorkLog> workLogs, WorkItemBase workItem = null) { SendFileWorkResult workResult = GetWorkLog <SendFileWorkResult>(workLogs); Console.WriteLine($"Mapping send log: {workResult.LogConnectDirect}"); dynamic id = await RetryHelper.RetryAsync <Exception>(async() => await PostWorkItemEndpointAddress <Guid>(), 3, TimeSpan.FromSeconds(3), Logger); Console.WriteLine("Mapped send log Id: {0}", id); MapSendLogWorkResult result = new MapSendLogWorkResult { SendLogId = 200, WorkId = id, Success = true }; return(new WorkLog(this, result)); }
public override async Task <WorkLog> DoWorkAsync(IList <WorkLog> workLogs, WorkItemBase workItem = null) { TokenFileWorkResult workResult = GetWorkLog <TokenFileWorkResult>(workLogs); Console.WriteLine($"Masking file: {workResult.UntokenizedFileName}"); dynamic id = await RetryHelper.RetryAsync <Exception>(async() => await PostWorkItemEndpointAddress <Guid>(), 3, TimeSpan.FromSeconds(3), Logger); Console.WriteLine("Masked file Id: {0}", id); MaskFileWorkResult result = new MaskFileWorkResult { MaskedFileName = "GNS.ORG001.T0000001.CS_20180129170710_Masked", WorkId = id, Success = true }; return(new WorkLog(this, result)); }
public async Task HandleAsync(TMessage message) { try { await RetryHelper.RetryAsync(() => DoHandle(message), _maxRetry, _backoffMs, p => { var ex = p as Exception <LightMessagerExceptionArgs>; if (ex != null) { return(true); } return(false); }); } catch (Exception ex) { _logger.Debug("未知异常:" + ex.Message + ";堆栈:" + ex.StackTrace); message.NeedRequeue = true; } }
public override async Task <WorkLog> DoWorkAsync(IList <WorkLog> workLogs, WorkItemBase workItem = null) { CreateFileWorkResult workResult = GetWorkLog <CreateFileWorkResult>(workLogs); Console.WriteLine($"Tokenizing file: {workResult.FileName}"); dynamic id = await RetryHelper.RetryAsync <Exception>(async() => await PostWorkItemEndpointAddress <Guid>(), 3, TimeSpan.FromSeconds(3), Logger); Console.WriteLine("Tokenized Id: {0}", id); // Simulando um percentual abaixo do esperado para setar como fracasso o passo, mesmo que processado com sucesso (estatística, mínimo esperado não alcançado etc...). bool success = new Random().Next(1, 100) < 70; TokenFileWorkResult result = new TokenFileWorkResult { UntokenizedFileName = "GNS.ORG001.T0000001.CS_20180129170710_UnTokenized", WorkId = id, Success = success }; return(new WorkLog(this, result)); }
public async Task <UserAccessToken> GetSpotifyAccessToken(string userId) { return(await RetryHelper.RetryAsync(async() => { // get User Access Tokens from Cache var cachedToken = await _cache.Get <UserAccessToken>(Key(userId)); // Return cached token if hit if (cachedToken != null) { return cachedToken; } // Get token from storage var storedToken = await _data.GetOrDefault(UserAccessToken.CanonicalId(userId), userId); if (storedToken == null) { return null; } // Store AccessToken (only) in Cache. // Only store tokens that have not yet expired // Set Cache item expiry for when the token is due to expire. // DO NOT cache Refresh Tokens var expiry = storedToken.Expires.Subtract(DateTimeOffset.UtcNow); if (expiry.TotalMilliseconds > 0) { await _cache.Set( Key(userId), new UserAccessToken(storedToken), storedToken.Expires.Subtract(DateTimeOffset.UtcNow)); } return storedToken; }, waitMs : 10, logger : _logger)); }
public async Task Handle(TMessage message) { try { // 执行DoHandle可能会发生异常,如果是我们特定的异常则进行重试操作 // 否则直接抛出异常 await RetryHelper.RetryAsync(() => DoHandle(message), _maxRetry, _backoffMs, p => { var ex = p as Exception <LightMessagerExceptionArgs>; if (ex != null) { return(true); } return(false); }); } catch (Exception ex) { _logger.Error("handler执行未知异常,数据:" + JsonConvert.SerializeObject(message)); _logger.Error("handler执行未知异常:" + ex.Message + ";堆栈:" + ex.StackTrace); } }
public async Task <Models.Album> GetAlbum(string token, string uri) => ItemMappers.MapToAlbum(await RetryHelper.RetryAsync(() => _albums.GetAlbum(uri, accessToken: token), logger: _logger));
public async Task Retry_AsyncFuncReturnVoid_NoError() { // act await RetryHelper.RetryAsync(() => DoNothing(), times : 3, waitMs : 0); }
public async Task Retry_AsyncFuncError_ThrowsException() { // act await RetryHelper.RetryAsync(() => AddOneError(1), times : 3, waitMs : 1); }
public async Task Process(IBatchMigrationContext batchContext) { object identityObject = null; string identityValue = null; HashSet <string> identitiesToProcess = new HashSet <string>(StringComparer.CurrentCultureIgnoreCase); foreach (var sourceWorkItem in batchContext.SourceWorkItems) { foreach (var field in context.IdentityFields) { if (sourceWorkItem.Fields.TryGetValueIgnoringCase(field, out identityObject)) { identityValue = (string)identityObject; if (!string.IsNullOrEmpty(identityValue) && identityValue.Contains("<") && identityValue.Contains(">") && (identityValue.Contains("@"))) { // parse out email address from the combo string identityValue = identityValue.Substring(identityValue.LastIndexOf("<") + 1, identityValue.LastIndexOf(">") - identityValue.LastIndexOf("<") - 1); if (!identitiesToProcess.Contains(identityValue) && !this.context.ValidatedIdentities.Contains(identityValue) && !this.context.InvalidIdentities.Contains(identityValue)) { Logger.LogTrace(LogDestination.File, $"Found identity {identityValue} in batch {batchContext.BatchId} which has not yet been validated for the target account"); identitiesToProcess.Add(identityValue); } } } } } Logger.LogTrace(LogDestination.File, $"Adding {identitiesToProcess.Count} identities to the account for batch {batchContext.BatchId}"); foreach (var identity in identitiesToProcess) { try { var createUserResult = await RetryHelper.RetryAsync(async() => { return(await graphClient.CreateUserAsync(new GraphUserPrincipalNameCreationContext() { PrincipalName = identity })); }, 5); // using identity from createUserResult since the identity could be in a mangled format that ReadIdentities does not support var identities = await RetryHelper.RetryAsync(async() => { return(await identityHttpClient.ReadIdentitiesAsync(IdentitySearchFilter.MailAddress, createUserResult.MailAddress)); }, 5); if (identities.Count == 0) { Logger.LogWarning(LogDestination.File, $"Unable to add identity {identity} to the target account for batch {batchContext.BatchId}"); context.InvalidIdentities.Add(identity); } else { var assignResult = await RetryHelper.RetryAsync(async() => { return(await licensingHttpClient.AssignAvailableEntitlementAsync(identities[0].Id, dontNotifyUser: true)); }, 5); context.ValidatedIdentities.Add(identity); } } catch (Exception ex) { Logger.LogWarning(LogDestination.File, ex, $"Unable to add identity {identity} to the target account for batch {batchContext.BatchId}"); context.InvalidIdentities.Add(identity); } } Logger.LogTrace(LogDestination.File, $"Completed adding {identitiesToProcess.Count} identities to the account for batch {batchContext.BatchId}"); }
public async Task <bool> JoinPlaylist( string query, string token, Station station, string stationToken, CancellationToken cancellationToken) { // is the station playing? // default the position to what was returned by get info var info = await GetUserNowPlaying(stationToken); if ( info == null || !info.IsPlaying || info.Context == null || SpotifyUriHelper.NormalizeUri(info.Context.Uri) != SpotifyUriHelper.NormalizeUri(station.SpotifyUri)) { _logger.LogInformation($"JoinPlaylist: No longer playing station {station}"); _logger.LogDebug($"JoinPlaylist: station.SpotifyUri = {station.SpotifyUri}"); _logger.LogDebug($"JoinPlaylist: info = {JsonConvert.SerializeObject(info)}"); return(false); } (string itemId, (long positionMs, DateTime atUtc)position)itemPosition = (info.Item?.Id, (info.ProgressMs ?? 0, DateTime.UtcNow)); if (!SupportedSpotifyItemTypes.Contains(station.SpotifyContextType)) { throw new NotSupportedException($"\"{station.SpotifyContextType}\" is not a supported Spotify context type"); } var offset = await GetOffset(stationToken); if (offset.success) { // reset position to Station position itemPosition.itemId = offset.itemId; itemPosition.position = offset.position; } await TurnOffShuffleRepeat(token, info); try { // mute joining player await Volume(token, 0, info.Device.Id); // play from offset switch (station.SpotifyContextType) { case "album": await RetryHelper.RetryAsync( () => _player.PlayAlbumOffset( info.Context.Uri, info.Item.Id, accessToken: token, positionMs: PositionMsNow(itemPosition.position).positionMs), logger : _logger, cancellationToken : cancellationToken); break; case "playlist": await RetryHelper.RetryAsync( () => _player.PlayPlaylistOffset( info.Context.Uri, info.Item.Id, accessToken: token, positionMs: PositionMsNow(itemPosition.position).positionMs), logger : _logger, cancellationToken : cancellationToken); break; } if (offset.success) { await SyncJoiningPlayer(stationToken : stationToken, joiningToken : token); } } finally { // unmute joining player await Volume(token, (int)info.Device.VolumePercent, info.Device.Id); } return(true); }
private async Task WaitForCompilerHostToBeReady(string requestId) { await RetryHelper.RetryAsync(() => CheckForHealthPing(requestId), _eventSource, requestId, 5, 1000); }
public async Task <Models.Artist> GetArtist(string token, string uri) => ItemMappers.MapToArtist(await RetryHelper.RetryAsync(() => _artists.GetArtist(uri, accessToken: token), logger: _logger));
public async Task <Models.Playlist> GetPlaylist(string token, string uriOrId) => ItemMappers.MapToPlaylist(await RetryHelper.RetryAsync( () => _playlists.GetPlaylist(uriOrId, accessToken: token), logger: _logger));