-
Notifications
You must be signed in to change notification settings - Fork 1.5k
[PM-28265] storage reconciliation job #6615
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
67b1f1c
[PM-28265] storage reconciliation job
kdenney 95a015c
format
kdenney 0128eac
fixing cancellation
kdenney a9e92cc
final cleanup
kdenney 4075ab5
wording
kdenney 74d0812
tweaks
kdenney 2c7a84d
forgot registration
kdenney 9106728
use stripe constants
kdenney 2bbaf69
switching to the correct proration behavior
kdenney 71dec86
constant var
kdenney File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| ๏ปฟusing Bit.Billing.Jobs; | ||
| using Bit.Core.Utilities; | ||
| using Microsoft.AspNetCore.Mvc; | ||
|
|
||
| namespace Bit.Billing.Controllers; | ||
|
|
||
| [Route("jobs")] | ||
| [SelfHosted(NotSelfHostedOnly = true)] | ||
| [RequireLowerEnvironment] | ||
| public class JobsController( | ||
| JobsHostedService jobsHostedService) : Controller | ||
| { | ||
| [HttpPost("run/{jobName}")] | ||
| public async Task<IActionResult> RunJobAsync(string jobName) | ||
| { | ||
| if (jobName == nameof(ReconcileAdditionalStorageJob)) | ||
| { | ||
| await jobsHostedService.RunJobAdHocAsync<ReconcileAdditionalStorageJob>(); | ||
| return Ok(new { message = $"Job {jobName} scheduled successfully" }); | ||
| } | ||
|
|
||
| return BadRequest(new { error = $"Unknown job name: {jobName}" }); | ||
| } | ||
|
|
||
| [HttpPost("stop/{jobName}")] | ||
| public async Task<IActionResult> StopJobAsync(string jobName) | ||
| { | ||
| if (jobName == nameof(ReconcileAdditionalStorageJob)) | ||
| { | ||
| await jobsHostedService.InterruptAdHocJobAsync<ReconcileAdditionalStorageJob>(); | ||
| return Ok(new { message = $"Job {jobName} queued for cancellation" }); | ||
| } | ||
|
|
||
| return BadRequest(new { error = $"Unknown job name: {jobName}" }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,201 @@ | ||
| ๏ปฟusing System.Globalization; | ||
| using System.Text.Json; | ||
| using Bit.Billing.Services; | ||
| using Bit.Core; | ||
| using Bit.Core.Billing.Constants; | ||
| using Bit.Core.Jobs; | ||
| using Bit.Core.Services; | ||
| using Quartz; | ||
| using Stripe; | ||
|
|
||
| namespace Bit.Billing.Jobs; | ||
|
|
||
| public class ReconcileAdditionalStorageJob( | ||
| IStripeFacade stripeFacade, | ||
| ILogger<ReconcileAdditionalStorageJob> logger, | ||
| IFeatureService featureService) : BaseJob(logger) | ||
| { | ||
| private const string _storageGbMonthlyPriceId = "storage-gb-monthly"; | ||
| private const string _storageGbAnnuallyPriceId = "storage-gb-annually"; | ||
| private const string _personalStorageGbAnnuallyPriceId = "personal-storage-gb-annually"; | ||
|
|
||
| protected override async Task ExecuteJobAsync(IJobExecutionContext context) | ||
| { | ||
| if (!featureService.IsEnabled(FeatureFlagKeys.PM28265_EnableReconcileAdditionalStorageJob)) | ||
| { | ||
| logger.LogInformation("Skipping ReconcileAdditionalStorageJob, feature flag off."); | ||
| return; | ||
| } | ||
|
|
||
| var liveMode = featureService.IsEnabled(FeatureFlagKeys.PM28265_ReconcileAdditionalStorageJobEnableLiveMode); | ||
|
|
||
| // Execution tracking | ||
| var subscriptionsFound = 0; | ||
| var subscriptionsUpdated = 0; | ||
| var subscriptionsWithErrors = 0; | ||
| var failures = new List<string>(); | ||
|
|
||
| logger.LogInformation("Starting ReconcileAdditionalStorageJob (live mode: {LiveMode})", liveMode); | ||
|
|
||
| var priceIds = new[] { _storageGbMonthlyPriceId, _storageGbAnnuallyPriceId, _personalStorageGbAnnuallyPriceId }; | ||
|
|
||
| foreach (var priceId in priceIds) | ||
| { | ||
| var options = new SubscriptionListOptions { Limit = 100, Status = "active", Price = priceId }; | ||
|
|
||
| await foreach (var subscription in stripeFacade.ListSubscriptionsAutoPagingAsync(options)) | ||
| { | ||
| if (context.CancellationToken.IsCancellationRequested) | ||
| { | ||
| logger.LogWarning( | ||
| "Job cancelled!! Exiting. Progress at time of cancellation: Subscriptions found: {SubscriptionsFound}, " + | ||
| "Updated: {SubscriptionsUpdated}, Errors: {SubscriptionsWithErrors}{Failures}", | ||
| subscriptionsFound, | ||
| liveMode | ||
| ? subscriptionsUpdated | ||
| : $"(In live mode, would have updated) {subscriptionsUpdated}", | ||
| subscriptionsWithErrors, | ||
| failures.Count > 0 | ||
| ? $", Failures: {Environment.NewLine}{string.Join(Environment.NewLine, failures)}" | ||
| : string.Empty | ||
| ); | ||
| return; | ||
| } | ||
|
|
||
| if (subscription == null) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| logger.LogInformation("Processing subscription: {SubscriptionId}", subscription.Id); | ||
| subscriptionsFound++; | ||
|
|
||
| if (subscription.Metadata?.TryGetValue(StripeConstants.MetadataKeys.StorageReconciled2025, out var dateString) == true) | ||
| { | ||
| if (DateTime.TryParse(dateString, null, DateTimeStyles.RoundtripKind, out var dateProcessed)) | ||
| { | ||
| logger.LogInformation("Skipping subscription {SubscriptionId} - already processed on {Date}", | ||
| subscription.Id, | ||
| dateProcessed.ToString("f")); | ||
| continue; | ||
| } | ||
| } | ||
|
|
||
| var updateOptions = BuildSubscriptionUpdateOptions(subscription, priceId); | ||
|
|
||
| if (updateOptions == null) | ||
| { | ||
| logger.LogInformation("Skipping subscription {SubscriptionId} - no updates needed", subscription.Id); | ||
| continue; | ||
| } | ||
|
|
||
| subscriptionsUpdated++; | ||
amorask-bitwarden marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if (!liveMode) | ||
| { | ||
| logger.LogInformation( | ||
| "Not live mode (dry-run): Would have updated subscription {SubscriptionId} with item changes: {NewLine}{UpdateOptions}", | ||
| subscription.Id, | ||
| Environment.NewLine, | ||
| JsonSerializer.Serialize(updateOptions)); | ||
| continue; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| await stripeFacade.UpdateSubscription(subscription.Id, updateOptions); | ||
| logger.LogInformation("Successfully updated subscription: {SubscriptionId}", subscription.Id); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| subscriptionsWithErrors++; | ||
| failures.Add($"Subscription {subscription.Id}: {ex.Message}"); | ||
| logger.LogError(ex, "Failed to update subscription {SubscriptionId}: {ErrorMessage}", | ||
| subscription.Id, ex.Message); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| logger.LogInformation( | ||
| "ReconcileAdditionalStorageJob completed. Subscriptions found: {SubscriptionsFound}, " + | ||
| "Updated: {SubscriptionsUpdated}, Errors: {SubscriptionsWithErrors}{Failures}", | ||
| subscriptionsFound, | ||
| liveMode | ||
| ? subscriptionsUpdated | ||
| : $"(In live mode, would have updated) {subscriptionsUpdated}", | ||
| subscriptionsWithErrors, | ||
| failures.Count > 0 | ||
| ? $", Failures: {Environment.NewLine}{string.Join(Environment.NewLine, failures)}" | ||
| : string.Empty | ||
| ); | ||
| } | ||
|
|
||
| private SubscriptionUpdateOptions? BuildSubscriptionUpdateOptions( | ||
| Subscription subscription, | ||
| string targetPriceId) | ||
| { | ||
| if (subscription.Items?.Data == null) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| var updateOptions = new SubscriptionUpdateOptions | ||
| { | ||
| ProrationBehavior = "always_invoice", | ||
kdenney marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| Metadata = new Dictionary<string, string> | ||
| { | ||
| [StripeConstants.MetadataKeys.StorageReconciled2025] = DateTime.UtcNow.ToString("o") | ||
| }, | ||
| Items = [] | ||
| }; | ||
|
|
||
| var hasUpdates = false; | ||
|
|
||
| foreach (var item in subscription.Items.Data.Where(item => item?.Price?.Id == targetPriceId)) | ||
| { | ||
| hasUpdates = true; | ||
| var currentQuantity = item.Quantity; | ||
|
|
||
| if (currentQuantity > 4) | ||
kdenney marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| var newQuantity = currentQuantity - 4; | ||
| logger.LogInformation( | ||
| "Subscription {SubscriptionId}: reducing quantity from {CurrentQuantity} to {NewQuantity} for price {PriceId}", | ||
| subscription.Id, | ||
| currentQuantity, | ||
| newQuantity, | ||
| item.Price.Id); | ||
|
|
||
| updateOptions.Items.Add(new SubscriptionItemOptions | ||
| { | ||
| Id = item.Id, | ||
| Quantity = newQuantity | ||
| }); | ||
| } | ||
| else | ||
| { | ||
| logger.LogInformation("Subscription {SubscriptionId}: deleting storage item with quantity {CurrentQuantity} for price {PriceId}", | ||
| subscription.Id, | ||
| currentQuantity, | ||
| item.Price.Id); | ||
|
|
||
| updateOptions.Items.Add(new SubscriptionItemOptions | ||
| { | ||
| Id = item.Id, | ||
| Deleted = true | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| return hasUpdates ? updateOptions : null; | ||
| } | ||
|
|
||
| public static ITrigger GetTrigger() | ||
| { | ||
| return TriggerBuilder.Create() | ||
| .WithIdentity("EveryMorningTrigger") | ||
| .StartNow() | ||
| .WithCronSchedule("0 0 16 * * ?") // 10am CST daily; the pods execute in UTC time | ||
| .Build(); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.