Skip to content

Commit a6652bc

Browse files
committed
Preserve trial uniqueness on renewal and show conversion losses
1 parent 8d6d67d commit a6652bc

9 files changed

Lines changed: 193 additions & 32 deletions

File tree

‎docs/privacy.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ We collect the e-mail addresses of those who communicate with us via e-mail or t
2323
## Data storage
2424

2525
* Exceptionless uses third party vendors and hosting partners to provide the necessary hardware, software, networking, storage, and related technology required to run Exceptionless. Although Exceptionless owns the code, databases, and all rights to the Exceptionless application, you retain all rights to your data.
26-
* You can delete your personal data at any time by visiting the my account page and clicking the delete account button.
26+
* You can delete your account data at any time by visiting the my account page and clicking the delete account button. Account deletion does not automatically remove the separate trial eligibility record described below.
27+
* To limit repeated free trials, we keep a separate trial eligibility record containing only a keyed, one-way identifier of your email address and the trial claim date. This record does not contain your email address, user ID, or organization ID. It expires after 365 days, including when you delete your account, and is removed through routine cleanup. After it expires, your mailbox can be eligible for another trial.
2728

2829
## Disclosure
2930

‎docs/trial-claim-privacy.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,4 @@ Before rollout, configure the secret on all hosts and stop old-version trial adm
2424

2525
The migration changes the active index. Existing backups or historical logs may still contain old digests until their own retention periods end; the migration does not retroactively erase those copies. Keep those copies restricted and account for them in the approved retention/erasure policy.
2626

27-
Claims use create-only repository insertion with the keyed identifier as the unique document ID. Duplicate claims return false; other storage failures abort admission. ID-based eligibility reads are real-time and do not require an immediate search refresh. Per-mailbox locks reduce contention; storage uniqueness is the final boundary.
27+
Claims use create-only repository insertion with the keyed identifier as the unique document ID, and expired claims are renewed with optimistic concurrency. Duplicate claims or renewal conflicts return false; other storage failures abort admission. Repository version metadata is not serialized into the retained claim. ID-based eligibility reads are real-time and do not require an immediate search refresh. Per-mailbox locks reduce contention; storage uniqueness is the final boundary.

‎src/Exceptionless.Core/Billing/BillingManager.cs‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,8 @@ public async Task<bool> CanAddOrganizationAsync(User? user)
8989
}
9090

9191
/// <summary>
92-
/// A no-card trial is only for someone new to Exceptionless: a user who belongs to no organization and created
93-
/// none, whose mailbox hasn't claimed a trial in the last <see cref="BillingOptions.TrialClaimRetentionDays"/> (under
92+
/// A no-card trial is for a user who belongs to no organization and has no existing organizations they created,
93+
/// whose mailbox hasn't claimed a trial in the last <see cref="BillingOptions.TrialClaimRetentionDays"/> days (under
9494
/// another alias or a deleted account), and whose email isn't on a blocked disposable domain. Call it while holding
9595
/// <see cref="AcquireTrialEmailLockAsync"/>.
9696
/// </summary>
@@ -145,13 +145,30 @@ public async Task<bool> TryClaimTrialAsync(User user)
145145
}
146146
catch (DuplicateDocumentException)
147147
{
148-
// An expired claim that cleanup hasn't removed yet doesn't block a new trial. The mailbox lock serializes renewals.
148+
// Renew expired claims with a version check, so storage enforces uniqueness even if the mailbox lock is lost.
149149
var claim = await _trialClaimRepository.GetByIdAsync(claimId);
150150
if (IsActiveClaim(claim))
151151
return false;
152152

153-
await _trialClaimRepository.SaveAsync(new TrialClaim { Id = claimId, CreatedUtc = _timeProvider.GetUtcNow().UtcDateTime });
154-
return true;
153+
try
154+
{
155+
if (claim is null)
156+
{
157+
// Cleanup removed the expired claim after the create failed; create-only admission still applies.
158+
await _trialClaimRepository.AddAsync(new TrialClaim { Id = claimId, CreatedUtc = _timeProvider.GetUtcNow().UtcDateTime });
159+
}
160+
else
161+
{
162+
claim.CreatedUtc = _timeProvider.GetUtcNow().UtcDateTime;
163+
await _trialClaimRepository.SaveAsync(claim);
164+
}
165+
166+
return true;
167+
}
168+
catch (DocumentException ex) when (ex is DuplicateDocumentException or VersionConflictDocumentException)
169+
{
170+
return false;
171+
}
155172
}
156173
}
157174

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,24 @@
1+
using System.Text.Json.Serialization;
12
using Foundatio.Repositories.Models;
23

34
namespace Exceptionless.Core.Models;
45

56
/// <summary>
6-
/// Records that a mailbox started its one no-card trial. It's kept apart from the user so deleting the account and
7+
/// Records a mailbox's latest no-card trial. It's kept apart from the user so deleting the account and
78
/// signing up again doesn't make the mailbox eligible again. Kept for
89
/// <see cref="Exceptionless.Core.Configuration.BillingOptions.TrialClaimRetentionDays"/> (12 months by default), including
910
/// after user/organization deletion, then removed so the mailbox can trial again. Contains no email, user ID, or organization ID.
1011
/// </summary>
11-
public sealed class TrialClaim : IIdentity, IHaveCreatedDate
12+
public sealed class TrialClaim : IIdentity, IHaveCreatedDate, IVersioned
1213
{
1314
/// <summary>
1415
/// Versioned HMAC identifier from <see cref="Exceptionless.Core.Billing.TrialEmailAddress.GetClaimId"/>.
1516
/// </summary>
1617
public string Id { get; set; } = null!;
1718

1819
public DateTime CreatedUtc { get; set; }
20+
21+
// Repository concurrency metadata is not part of the retained claim.
22+
[JsonIgnore]
23+
public string Version { get; set; } = String.Empty;
1924
}

‎src/Exceptionless.Web/ClientApp/src/lib/features/billing/components/change-plan-dialog.svelte‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@
200200
});
201201
202202
// Organization limits reflect the current plan, including the hidden trial plan.
203-
const downgradeLosses = $derived(isDowngrade && selectedPlan ? getDowngradeLosses(organization, selectedPlan) : []);
203+
const downgradeLosses = $derived(planDirty && selectedPlan ? getDowngradeLosses(organization, selectedPlan) : []);
204204
205205
let stripe = $state<null | Stripe>(null);
206206
let stripeElements = $state<StripeElements | undefined>(undefined);
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import { fireEvent, render, screen } from '@testing-library/svelte';
2+
import { describe, expect, it, vi } from 'vitest';
3+
4+
import type { ViewOrganization } from '#features/organizations/models.ts';
5+
import type { BillingPlan } from '#generated/api.ts';
6+
7+
const plans: BillingPlan[] = [
8+
{
9+
description: 'Free',
10+
has_premium_features: false,
11+
id: 'EX_FREE',
12+
is_hidden: false,
13+
max_events_per_month: 3000,
14+
max_projects: -1,
15+
max_users: -1,
16+
name: 'Free',
17+
price: 0,
18+
retention_days: 3
19+
},
20+
{
21+
description: 'Small',
22+
has_premium_features: true,
23+
id: 'EX_SMALL',
24+
is_hidden: false,
25+
max_events_per_month: 15000,
26+
max_projects: -1,
27+
max_users: -1,
28+
name: 'Small',
29+
price: 15,
30+
retention_days: 30
31+
},
32+
{
33+
description: 'Small yearly',
34+
has_premium_features: true,
35+
id: 'EX_SMALL_YEARLY',
36+
is_hidden: false,
37+
max_events_per_month: 15000,
38+
max_projects: -1,
39+
max_users: -1,
40+
name: 'Small (Yearly)',
41+
price: 165,
42+
retention_days: 30
43+
},
44+
{
45+
description: 'Medium',
46+
has_premium_features: true,
47+
id: 'EX_MEDIUM',
48+
is_hidden: false,
49+
max_events_per_month: 75000,
50+
max_projects: -1,
51+
max_users: -1,
52+
name: 'Medium',
53+
price: 49,
54+
retention_days: 90
55+
}
56+
];
57+
58+
vi.mock('#features/organizations/api.svelte.ts', () => ({
59+
changePlanMutation: () => ({ mutateAsync: vi.fn() }),
60+
getPlansQuery: () => ({ data: plans, error: null, isLoading: false })
61+
}));
62+
vi.mock('#features/billing/stripe.svelte.ts', async (importOriginal) => ({
63+
...(await importOriginal<typeof import('#features/billing/stripe.svelte.ts')>()),
64+
isStripeEnabled: () => true,
65+
loadStripeOnce: async () => null
66+
}));
67+
68+
import ChangePlanDialog from './change-plan-dialog.svelte';
69+
70+
describe('ChangePlanDialog loss warning', () => {
71+
it('warns for trial to Small in both intervals without blocking confirmation, then clears for Medium', async () => {
72+
// Arrange
73+
const organization = {
74+
billing_price: 0,
75+
card_last4: '4242',
76+
has_premium_features: true,
77+
id: 'trial-organization',
78+
max_events_per_month: 75000,
79+
name: 'Trial organization',
80+
plan_id: 'EX_TRIAL',
81+
plan_name: 'Trial',
82+
retention_days: 90,
83+
trial_ends_utc: '2099-01-01T00:00:00Z'
84+
} as ViewOrganization;
85+
86+
// Act
87+
render(ChangePlanDialog, { initialPlanId: 'EX_SMALL', onclose: vi.fn(), organization });
88+
89+
// Assert
90+
const losses = await screen.findByTestId('downgrade-losses');
91+
expect(losses).toHaveTextContent('event history drops from 90 days to 30 days');
92+
expect(losses).toHaveTextContent('limit drops to 15,000 events a month');
93+
expect(screen.getByRole('button', { name: 'Start Small yearly' })).toBeEnabled();
94+
95+
// Act
96+
await fireEvent.click(screen.getByRole('tab', { name: 'Monthly' }));
97+
98+
// Assert
99+
expect(losses).toHaveTextContent('event history drops from 90 days to 30 days');
100+
expect(screen.getByRole('button', { name: 'Start Small monthly' })).toBeEnabled();
101+
102+
// Act
103+
await fireEvent.click(screen.getByRole('button', { name: /^Medium/ }));
104+
105+
// Assert
106+
expect(screen.queryByTestId('downgrade-losses')).toBeNull();
107+
expect(screen.getByRole('button', { name: 'Start Medium monthly' })).toBeEnabled();
108+
});
109+
});

‎src/Exceptionless.Web/ClientApp/src/lib/features/billing/plan-downgrade.test.ts‎

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,30 +6,28 @@ const trial: PlanLimits = { has_premium_features: true, max_events_per_month: 75
66
const free: PlanLimits = { has_premium_features: false, max_events_per_month: 3000, retention_days: 3 };
77

88
describe('getDowngradeLosses', () => {
9-
it('lists retention, event limit, and premium losses when moving to free', () => {
10-
// Act
11-
const losses = getDowngradeLosses(trial, free);
12-
13-
// Assert
14-
expect(losses).toEqual(['event history drops from 90 days to 3 days', 'limit drops to 3,000 events a month', 'premium features turn off']);
15-
});
16-
17-
it('treats moving from unlimited events to a limit as a loss', () => {
9+
it.each([
10+
{
11+
current: trial,
12+
expected: ['event history drops from 90 days to 3 days', 'limit drops to 3,000 events a month', 'premium features turn off'],
13+
name: 'lists retention, event limit, and premium losses when moving to free',
14+
next: free
15+
},
16+
{
17+
current: { ...trial, max_events_per_month: -1 },
18+
expected: ['limit drops to 75,000 events a month'],
19+
name: 'treats moving from unlimited events to a limit as a loss',
20+
next: trial
21+
},
22+
{ current: free, expected: [], name: 'returns nothing when no limit goes down', next: trial }
23+
])('$name', (testCase) => {
1824
// Arrange
19-
const unlimited: PlanLimits = { ...trial, max_events_per_month: -1 };
20-
21-
// Act
22-
const losses = getDowngradeLosses(unlimited, trial);
23-
24-
// Assert
25-
expect(losses).toEqual(['limit drops to 75,000 events a month']);
26-
});
25+
const { current, expected, next } = testCase;
2726

28-
it('returns nothing when no limit goes down', () => {
2927
// Act
30-
const losses = getDowngradeLosses(free, trial);
28+
const losses = getDowngradeLosses(current, next);
3129

3230
// Assert
33-
expect(losses).toEqual([]);
31+
expect(losses).toEqual(expected);
3432
});
3533
});

‎tests/Exceptionless.Tests/Api/Endpoints/OrganizationEndpointTests.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3216,7 +3216,7 @@ public async Task PostAsync_AliasOfMailboxThatStartedTrial_GetsFreePlan(string f
32163216

32173217
[Theory]
32183218
[InlineData(364, "EX_FREE")]
3219-
[InlineData(366, "EX_TRIAL")]
3219+
[InlineData(365, "EX_TRIAL")]
32203220
public async Task PostAsync_MailboxRegisteredAgainAfterDeletingTrialAccount_GetsTrialOnlyAfterRetention(int daysLater, string expectedPlanId)
32213221
{
32223222
// Arrange
@@ -3230,7 +3230,7 @@ await SendRequestAsync(request => request.BasicAuthorization(original.EmailAddre
32303230
await SendRequestAsync(request => request.BasicAuthorization(original.EmailAddress, password).Delete()
32313231
.AppendPaths("users", "me").StatusCodeShouldBeAccepted());
32323232
TimeProvider.Advance(TimeSpan.FromDays(daysLater));
3233-
var returning = await CreateUserAsync("returning+again@exceptionless.test", password, isEmailAddressVerified: true);
3233+
var returning = await CreateUserAsync("returning@exceptionless.test", password, isEmailAddressVerified: true);
32343234

32353235
// Act
32363236
var organization = await WithBillingEnabledAsync(() => CreateOrganizationAsync(returning, password, "Returning Organization"));

‎tests/Exceptionless.Tests/Billing/BillingManagerIntegrationTests.cs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using Exceptionless.Core.Models;
44
using Exceptionless.Core.Repositories;
55
using Exceptionless.Tests.Utility;
6+
using Foundatio.Repositories.Models;
67
using Foundatio.Repositories.Utility;
78
using Xunit;
89

@@ -105,6 +106,36 @@ public async Task CanStartTrialAsync_PreviousTrialOlderThanRetention_ReturnsTrue
105106
Assert.True(canStartTrialAfter);
106107
}
107108

109+
[Fact]
110+
public async Task TryClaimTrialAsync_ConcurrentExpiredMailboxAliases_OnlyOneRenewsClaim()
111+
{
112+
// Arrange
113+
var billingManager = GetService<BillingManager>();
114+
var repository = GetService<ITrialClaimRepository>();
115+
var options = GetService<AppOptions>();
116+
var first = new User { EmailAddress = "renewal.race@gmail.com" };
117+
var alias = new User { EmailAddress = "renewalrace+again@googlemail.com" };
118+
await billingManager.TryClaimTrialAsync(first);
119+
TimeProvider.Advance(TimeSpan.FromDays(options.BillingOptions.TrialClaimRetentionDays + 1));
120+
var bothRenewing = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
121+
int arrivals = 0;
122+
using var handler = repository.DocumentsChanging.AddHandler(async (_, args) =>
123+
{
124+
if (args.ChangeType is not ChangeType.Saved)
125+
return;
126+
127+
if (Interlocked.Increment(ref arrivals) is 2)
128+
bothRenewing.SetResult();
129+
await bothRenewing.Task.WaitAsync(TimeSpan.FromSeconds(10), TestCancellationToken);
130+
});
131+
132+
// Act: bypass mailbox locks to verify storage still admits only one renewal.
133+
var acquired = await Task.WhenAll(billingManager.TryClaimTrialAsync(first), billingManager.TryClaimTrialAsync(alias));
134+
135+
// Assert
136+
Assert.Single(acquired, claimed => claimed);
137+
}
138+
108139
[Fact]
109140
public async Task RemoveExpiredTrialClaimsAsync_MixedClaimAges_RemovesOnlyExpiredClaims()
110141
{

0 commit comments

Comments
 (0)