@langwatch/server 3.1.0-beta.4 → 3.1.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/langwatch/ee/admin/ImpersonationBanner.tsx +61 -0
- package/langwatch/ee/admin/ImpersonationSwitchBackMenuItem.tsx +30 -0
- package/langwatch/ee/admin/__tests__/ImpersonationBanner.integration.test.tsx +82 -0
- package/langwatch/ee/admin/__tests__/impersonation.service.unit.test.ts +231 -0
- package/langwatch/ee/admin/backoffice/BackofficeTable.tsx +200 -0
- package/langwatch/ee/admin/backoffice/__tests__/adminClient.unit.test.ts +147 -0
- package/langwatch/ee/admin/backoffice/__tests__/dateInputToISO.unit.test.ts +42 -0
- package/langwatch/ee/admin/backoffice/__tests__/userVisibility.unit.test.ts +174 -0
- package/langwatch/ee/admin/backoffice/adminClient.ts +114 -0
- package/langwatch/ee/admin/backoffice/resources/OrganizationFeaturesView.tsx +373 -0
- package/langwatch/ee/admin/backoffice/resources/OrganizationsView.tsx +677 -0
- package/langwatch/ee/admin/backoffice/resources/ProjectsView.tsx +647 -0
- package/langwatch/ee/admin/backoffice/resources/SubscriptionsView.tsx +628 -0
- package/langwatch/ee/admin/backoffice/resources/UsersView.tsx +556 -0
- package/langwatch/ee/admin/backoffice/useAdminResource.ts +104 -0
- package/langwatch/ee/admin/backoffice/userVisibility.ts +105 -0
- package/langwatch/ee/admin/impersonation.service.ts +170 -0
- package/langwatch/ee/admin/isAdmin.ts +9 -0
- package/langwatch/ee/admin/routes/admin.ts +531 -0
- package/langwatch/ee/admin/safeSelects.ts +64 -0
- package/langwatch/ee/billing/__tests__/customerService.unit.test.ts +183 -0
- package/langwatch/ee/billing/__tests__/growthSeatEvent.unit.test.ts +213 -0
- package/langwatch/ee/billing/__tests__/licensePurchaseHandler.unit.test.ts +250 -0
- package/langwatch/ee/billing/__tests__/notification.service.unit.test.ts +768 -0
- package/langwatch/ee/billing/__tests__/planLimits.unit.test.ts +19 -0
- package/langwatch/ee/billing/__tests__/planProvider.unit.test.ts +440 -0
- package/langwatch/ee/billing/__tests__/planTypes.unit.test.ts +32 -0
- package/langwatch/ee/billing/__tests__/pricing.unit.test.ts +54 -0
- package/langwatch/ee/billing/__tests__/seatEventSubscription.unit.test.ts +717 -0
- package/langwatch/ee/billing/__tests__/stripe.integration.test.ts +344 -0
- package/langwatch/ee/billing/__tests__/stripePrices.types.unit.test.ts +27 -0
- package/langwatch/ee/billing/__tests__/stripePricesLoader.unit.test.ts +72 -0
- package/langwatch/ee/billing/__tests__/subscription.service.unit.test.ts +730 -0
- package/langwatch/ee/billing/__tests__/subscriptionItemCalculator.unit.test.ts +176 -0
- package/langwatch/ee/billing/__tests__/usage-limit.service.unit.test.ts +706 -0
- package/langwatch/ee/billing/__tests__/usageReportingService.integration.test.ts +421 -0
- package/langwatch/ee/billing/__tests__/usageReportingService.unit.test.ts +515 -0
- package/langwatch/ee/billing/__tests__/webhookService.unit.test.ts +958 -0
- package/langwatch/ee/billing/currencyRouter.ts +18 -0
- package/langwatch/ee/billing/errors.ts +129 -0
- package/langwatch/ee/billing/index.ts +67 -0
- package/langwatch/ee/billing/middleware.ts +17 -0
- package/langwatch/ee/billing/notifications/notification.service.ts +651 -0
- package/langwatch/ee/billing/notifications/repositories/notification.repository.ts +51 -0
- package/langwatch/ee/billing/notifications/types.ts +9 -0
- package/langwatch/ee/billing/notifications/usage-limit.service.ts +622 -0
- package/langwatch/ee/billing/nurturing/hooks/activityTracking.ts +90 -0
- package/langwatch/ee/billing/nurturing/hooks/activityTracking.unit.test.ts +237 -0
- package/langwatch/ee/billing/nurturing/hooks/featureAdoption.ts +120 -0
- package/langwatch/ee/billing/nurturing/hooks/featureAdoption.unit.test.ts +324 -0
- package/langwatch/ee/billing/nurturing/hooks/index.ts +17 -0
- package/langwatch/ee/billing/nurturing/hooks/productInterest.ts +68 -0
- package/langwatch/ee/billing/nurturing/hooks/productInterest.unit.test.ts +138 -0
- package/langwatch/ee/billing/nurturing/hooks/promptCreation.integration.test.ts +288 -0
- package/langwatch/ee/billing/nurturing/hooks/promptCreation.ts +131 -0
- package/langwatch/ee/billing/nurturing/hooks/promptCreation.unit.test.ts +134 -0
- package/langwatch/ee/billing/nurturing/hooks/signupIdentification.ts +101 -0
- package/langwatch/ee/billing/nurturing/hooks/signupIdentification.unit.test.ts +317 -0
- package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.ts +49 -0
- package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.unit.test.ts +170 -0
- package/langwatch/ee/billing/nurturing/hooks/userSync.ts +143 -0
- package/langwatch/ee/billing/nurturing/hooks/userSync.unit.test.ts +307 -0
- package/langwatch/ee/billing/nurturing/nurturing.service.ts +179 -0
- package/langwatch/ee/billing/nurturing/nurturing.service.unit.test.ts +266 -0
- package/langwatch/ee/billing/nurturing/nurturing.service.wiring.unit.test.ts +109 -0
- package/langwatch/ee/billing/nurturing/types.ts +125 -0
- package/langwatch/ee/billing/planLimits.ts +190 -0
- package/langwatch/ee/billing/planProvider.ts +119 -0
- package/langwatch/ee/billing/planTypes.ts +53 -0
- package/langwatch/ee/billing/pricing.ts +57 -0
- package/langwatch/ee/billing/services/billableEventsQuery.ts +248 -0
- package/langwatch/ee/billing/services/customerService.ts +90 -0
- package/langwatch/ee/billing/services/licensePurchaseHandler.ts +73 -0
- package/langwatch/ee/billing/services/seatEventSubscription.ts +351 -0
- package/langwatch/ee/billing/services/seatSyncService.ts +34 -0
- package/langwatch/ee/billing/services/subscription.repository.ts +203 -0
- package/langwatch/ee/billing/services/subscription.service.ts +549 -0
- package/langwatch/ee/billing/services/subscriptionItemCalculator.ts +249 -0
- package/langwatch/ee/billing/services/usageReportingService.ts +301 -0
- package/langwatch/ee/billing/services/webhookService.ts +858 -0
- package/langwatch/ee/billing/stripe/stripeCatalog.json +1781 -0
- package/langwatch/ee/billing/stripe/stripeClient.ts +13 -0
- package/langwatch/ee/billing/stripe/stripePriceCatalog.ts +70 -0
- package/langwatch/ee/billing/stripe/stripePrices.types.ts +118 -0
- package/langwatch/ee/billing/subscriptionRouter.ts +202 -0
- package/langwatch/ee/billing/types.ts +102 -0
- package/langwatch/ee/billing/utils/currency.ts +99 -0
- package/langwatch/ee/billing/utils/growthSeatEvent.ts +137 -0
- package/langwatch/ee/licensing/__tests__/constants.unit.test.ts +56 -0
- package/langwatch/ee/licensing/__tests__/defaults.unit.test.ts +192 -0
- package/langwatch/ee/licensing/__tests__/fixtures/testKeys.ts +86 -0
- package/langwatch/ee/licensing/__tests__/fixtures/testLicenses.ts +92 -0
- package/langwatch/ee/licensing/__tests__/licenseGenerationService.unit.test.ts +232 -0
- package/langwatch/ee/licensing/__tests__/licenseHandler.integration.test.ts +419 -0
- package/langwatch/ee/licensing/__tests__/planMapping.unit.test.ts +195 -0
- package/langwatch/ee/licensing/__tests__/planTemplates.unit.test.ts +193 -0
- package/langwatch/ee/licensing/__tests__/signing.unit.test.ts +164 -0
- package/langwatch/ee/licensing/__tests__/validation.unit.test.ts +281 -0
- package/langwatch/ee/licensing/client.ts +29 -0
- package/langwatch/ee/licensing/constants.ts +195 -0
- package/langwatch/ee/licensing/defaults.ts +55 -0
- package/langwatch/ee/licensing/errors.ts +11 -0
- package/langwatch/ee/licensing/index.ts +52 -0
- package/langwatch/ee/licensing/licenseGenerationService.ts +87 -0
- package/langwatch/ee/licensing/licenseHandler.ts +308 -0
- package/langwatch/ee/licensing/planInfo.ts +46 -0
- package/langwatch/ee/licensing/planMapping.ts +37 -0
- package/langwatch/ee/licensing/planTemplates.ts +109 -0
- package/langwatch/ee/licensing/server.ts +43 -0
- package/langwatch/ee/licensing/signing.ts +43 -0
- package/langwatch/ee/licensing/types.ts +156 -0
- package/langwatch/ee/licensing/validation.ts +107 -0
- package/langwatch/ee/managed-providers/ManagedModelProviderAlert.tsx +29 -0
- package/langwatch/ee/managed-providers/managedBedrockConfig.ts +226 -0
- package/langwatch/ee/saas/ExtraFooterComponents.tsx +169 -0
- package/langwatch/package.json +1 -1
- package/package.json +1 -1
- package/packages/server/dist/cli.cjs +1 -1
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
import { env } from "../../../src/env.mjs";
|
|
2
|
+
import { createLogger } from "../../../src/utils/logger/server";
|
|
3
|
+
import type { UsageService } from "../../../src/server/app-layer/usage/usage.service";
|
|
4
|
+
import { getCurrentMonthStart } from "../../../src/server/utils/dateUtils";
|
|
5
|
+
import { TtlCache } from "../../../src/server/utils/ttlCache";
|
|
6
|
+
import { LIMIT_TYPE_DISPLAY_LABELS } from "../../../src/server/license-enforcement/constants";
|
|
7
|
+
import { captureException } from "../../../src/utils/posthogErrorCapture";
|
|
8
|
+
import {
|
|
9
|
+
NotificationService,
|
|
10
|
+
type UsageLimitEmailData,
|
|
11
|
+
} from "./notification.service";
|
|
12
|
+
import type { NotificationRepository } from "./repositories/notification.repository";
|
|
13
|
+
import type { OrganizationService } from "../../../src/server/app-layer/organizations/organization.service";
|
|
14
|
+
import { NOTIFICATION_TYPES } from "./types";
|
|
15
|
+
import type { PlanLimitNotifierInput, ResourceLimitNotifierInput } from "../types";
|
|
16
|
+
import type { PlanProvider } from "../../../src/server/app-layer/subscription/plan-provider";
|
|
17
|
+
|
|
18
|
+
const logger = createLogger("langwatch:notifications:usageLimit");
|
|
19
|
+
|
|
20
|
+
const USAGE_WARNING_THRESHOLDS = [50, 70, 90, 95, 100] as const; // Thresholds in ascending order
|
|
21
|
+
const MIN_DAYS_BETWEEN_ALERTS = 30;
|
|
22
|
+
|
|
23
|
+
// NOTE: In-memory cooldown does not survive restarts and does not coordinate across replicas. Accepted tradeoff: worst case is a duplicate Slack alert.
|
|
24
|
+
const resourceLimitCooldown = new TtlCache<true>(24 * 60 * 60 * 1000, "ttlcache:billing:limitCooldown:");
|
|
25
|
+
export { resourceLimitCooldown };
|
|
26
|
+
|
|
27
|
+
// Guards notifyPlanLimitReached against concurrent calls (burst of traces from
|
|
28
|
+
// a single org hitting the limit middleware at the same time). Two layers:
|
|
29
|
+
//
|
|
30
|
+
// 1. planLimitInFlight (sync Set) — blocks same-tick races where multiple
|
|
31
|
+
// Promise.all callers interleave before any async operation resolves.
|
|
32
|
+
// 2. planLimitCooldown (TtlCache) — blocks subsequent ticks and coordinates
|
|
33
|
+
// across pods via Redis. The DB 30-day window remains authoritative.
|
|
34
|
+
const planLimitInFlight = new Set<string>();
|
|
35
|
+
const planLimitCooldown = new TtlCache<true>(MIN_DAYS_BETWEEN_ALERTS * 24 * 60 * 60 * 1000, "ttlcache:billing:planLimitCooldown:");
|
|
36
|
+
export { planLimitInFlight, planLimitCooldown };
|
|
37
|
+
|
|
38
|
+
export interface UsageLimitData {
|
|
39
|
+
organizationId: string;
|
|
40
|
+
currentMonthMessagesCount: number;
|
|
41
|
+
maxMonthlyUsageLimit: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Service layer for usage limit notification business logic.
|
|
46
|
+
* Single Responsibility: Handle business logic for WHEN/WHAT to send.
|
|
47
|
+
*
|
|
48
|
+
* Delegates delivery to {@link NotificationService} (HOW to send).
|
|
49
|
+
* Framework-agnostic - no tRPC dependencies.
|
|
50
|
+
*/
|
|
51
|
+
export class UsageLimitService {
|
|
52
|
+
private readonly notificationRepository: NotificationRepository;
|
|
53
|
+
private readonly organizationService: OrganizationService;
|
|
54
|
+
private readonly usageService: UsageService;
|
|
55
|
+
private readonly notificationService: NotificationService;
|
|
56
|
+
private readonly planProvider: PlanProvider;
|
|
57
|
+
|
|
58
|
+
constructor({
|
|
59
|
+
notificationRepository,
|
|
60
|
+
organizationService,
|
|
61
|
+
usageService,
|
|
62
|
+
notificationService,
|
|
63
|
+
planProvider,
|
|
64
|
+
}: {
|
|
65
|
+
notificationRepository: NotificationRepository;
|
|
66
|
+
organizationService: OrganizationService;
|
|
67
|
+
usageService: UsageService;
|
|
68
|
+
notificationService: NotificationService;
|
|
69
|
+
planProvider: PlanProvider;
|
|
70
|
+
}) {
|
|
71
|
+
this.notificationRepository = notificationRepository;
|
|
72
|
+
this.organizationService = organizationService;
|
|
73
|
+
this.usageService = usageService;
|
|
74
|
+
this.notificationService = notificationService;
|
|
75
|
+
this.planProvider = planProvider;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Static factory method for creating a UsageLimitService with proper DI.
|
|
80
|
+
*/
|
|
81
|
+
static create({
|
|
82
|
+
notificationRepository,
|
|
83
|
+
organizationService,
|
|
84
|
+
usageService,
|
|
85
|
+
notificationService,
|
|
86
|
+
planProvider,
|
|
87
|
+
}: {
|
|
88
|
+
notificationRepository: NotificationRepository;
|
|
89
|
+
organizationService: OrganizationService;
|
|
90
|
+
usageService: UsageService;
|
|
91
|
+
notificationService: NotificationService;
|
|
92
|
+
planProvider: PlanProvider;
|
|
93
|
+
}): UsageLimitService {
|
|
94
|
+
return new UsageLimitService({ notificationRepository, organizationService, usageService, notificationService, planProvider });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Null-object factory: every method is a silent noop.
|
|
99
|
+
* Use in tests or non-SaaS deployments where no notifications are needed.
|
|
100
|
+
*/
|
|
101
|
+
static createNull(): UsageLimitService {
|
|
102
|
+
const noopRepo = {
|
|
103
|
+
findRecentByOrganization: async () => [],
|
|
104
|
+
create: async () => ({}) as any,
|
|
105
|
+
} as unknown as NotificationRepository;
|
|
106
|
+
const noopOrg = { findWithAdmins: async () => null } as unknown as OrganizationService;
|
|
107
|
+
const noopUsage = { getUsage: async () => ({ currentMonthMessagesCount: 0, maxMonthlyUsageLimit: 0 }) } as unknown as UsageService;
|
|
108
|
+
const noopPlan = { getActivePlan: async () => ({ name: "free" }) } as unknown as PlanProvider;
|
|
109
|
+
return new UsageLimitService({
|
|
110
|
+
notificationRepository: noopRepo,
|
|
111
|
+
organizationService: noopOrg,
|
|
112
|
+
usageService: noopUsage,
|
|
113
|
+
notificationService: NotificationService.createNull(),
|
|
114
|
+
planProvider: noopPlan,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Notifies internal channels that an organization has reached its plan limit.
|
|
120
|
+
* Absorbed from planLimitNotifier.ts.
|
|
121
|
+
*
|
|
122
|
+
* Checks IS_SAAS env, fetches org with admin members, enforces 30-day cooldown,
|
|
123
|
+
* then delegates to NotificationService for Slack and Hubspot delivery.
|
|
124
|
+
*/
|
|
125
|
+
async notifyPlanLimitReached({
|
|
126
|
+
organizationId,
|
|
127
|
+
planName,
|
|
128
|
+
}: PlanLimitNotifierInput): Promise<void> {
|
|
129
|
+
if (!env.IS_SAAS) {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Synchronous guard: blocks same-tick concurrent calls (e.g. 5 trace
|
|
134
|
+
// requests hitting Promise.all) before any await yields execution.
|
|
135
|
+
if (planLimitInFlight.has(organizationId)) {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
planLimitInFlight.add(organizationId);
|
|
139
|
+
|
|
140
|
+
try {
|
|
141
|
+
// Atomic cross-pod guard: SET NX EX claims the cooldown slot in a
|
|
142
|
+
// single Redis round-trip, closing the distributed TOCTOU window.
|
|
143
|
+
const claimed = await planLimitCooldown.claim(organizationId, true);
|
|
144
|
+
if (!claimed) {
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const organization = await this.organizationService.findWithAdmins(organizationId);
|
|
149
|
+
|
|
150
|
+
if (!organization) {
|
|
151
|
+
await planLimitCooldown.delete(organizationId);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (organization.sentPlanLimitAlert) {
|
|
156
|
+
const timeSinceLastAlert =
|
|
157
|
+
Date.now() - organization.sentPlanLimitAlert.getTime();
|
|
158
|
+
const daysSinceLastAlert = Math.floor(
|
|
159
|
+
timeSinceLastAlert / (1000 * 60 * 60 * 24),
|
|
160
|
+
);
|
|
161
|
+
|
|
162
|
+
if (daysSinceLastAlert < MIN_DAYS_BETWEEN_ALERTS) {
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const admin = organization.members[0]?.user;
|
|
168
|
+
|
|
169
|
+
const context = {
|
|
170
|
+
organizationId,
|
|
171
|
+
organizationName: organization.name,
|
|
172
|
+
adminName: admin?.name ?? undefined,
|
|
173
|
+
adminEmail: admin?.email ?? undefined,
|
|
174
|
+
planName,
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
// Both sends are fire-and-forget (errors swallowed internally),
|
|
178
|
+
// so use allSettled to await completion without short-circuiting.
|
|
179
|
+
await Promise.allSettled([
|
|
180
|
+
this.notificationService.sendSlackPlanLimitAlert(context),
|
|
181
|
+
this.notificationService.sendHubspotPlanLimitForm(context),
|
|
182
|
+
]);
|
|
183
|
+
|
|
184
|
+
try {
|
|
185
|
+
await this.organizationService.updateSentPlanLimitAlert(organizationId, new Date());
|
|
186
|
+
} catch (error) {
|
|
187
|
+
captureException(
|
|
188
|
+
new Error(
|
|
189
|
+
`Critical: plan limit notification sent but DB timestamp update failed for org ${organizationId} on plan ${planName}`,
|
|
190
|
+
{ cause: error },
|
|
191
|
+
),
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
} finally {
|
|
195
|
+
planLimitInFlight.delete(organizationId);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Notifies internal channels that an organization has reached a resource limit.
|
|
201
|
+
*
|
|
202
|
+
* Uses an in-memory 24-hour cooldown keyed by organizationId:limitType to avoid
|
|
203
|
+
* duplicate Slack alerts. Each limit type has its own cooldown window.
|
|
204
|
+
*/
|
|
205
|
+
async notifyResourceLimitReached({
|
|
206
|
+
organizationId,
|
|
207
|
+
limitType,
|
|
208
|
+
current,
|
|
209
|
+
max,
|
|
210
|
+
}: ResourceLimitNotifierInput): Promise<void> {
|
|
211
|
+
if (!env.IS_SAAS) {
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const cooldownKey = `${organizationId}:${limitType}`;
|
|
216
|
+
|
|
217
|
+
if (await resourceLimitCooldown.get(cooldownKey)) {
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
await resourceLimitCooldown.set(cooldownKey, true);
|
|
222
|
+
|
|
223
|
+
try {
|
|
224
|
+
const org = await this.organizationService.findWithAdmins(organizationId);
|
|
225
|
+
|
|
226
|
+
if (!org) {
|
|
227
|
+
await resourceLimitCooldown.delete(cooldownKey);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const admin = org.members[0]?.user;
|
|
232
|
+
const limitLabel = LIMIT_TYPE_DISPLAY_LABELS[limitType];
|
|
233
|
+
|
|
234
|
+
let planName = "unknown";
|
|
235
|
+
try {
|
|
236
|
+
planName =
|
|
237
|
+
(
|
|
238
|
+
await this.planProvider.getActivePlan({ organizationId })
|
|
239
|
+
).name ?? "unknown";
|
|
240
|
+
} catch {
|
|
241
|
+
// fall through with "unknown"
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
await this.notificationService.sendSlackResourceLimitAlert({
|
|
245
|
+
organizationId,
|
|
246
|
+
organizationName: org.name,
|
|
247
|
+
adminName: admin?.name ?? undefined,
|
|
248
|
+
adminEmail: admin?.email ?? undefined,
|
|
249
|
+
planName,
|
|
250
|
+
limitType: limitLabel,
|
|
251
|
+
current,
|
|
252
|
+
max,
|
|
253
|
+
});
|
|
254
|
+
} catch {
|
|
255
|
+
resourceLimitCooldown.delete(cooldownKey);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Checks if a usage limit warning notification should be sent and sends it if needed.
|
|
261
|
+
* Creates a notification record in the database after successfully sending the email.
|
|
262
|
+
*
|
|
263
|
+
* @param data Usage limit data including organization ID, current usage, and limit
|
|
264
|
+
* @returns The created notification record, or null if no notification was sent
|
|
265
|
+
*/
|
|
266
|
+
async checkAndSendWarning(data: UsageLimitData) {
|
|
267
|
+
const { organizationId, currentMonthMessagesCount, maxMonthlyUsageLimit } =
|
|
268
|
+
data;
|
|
269
|
+
|
|
270
|
+
const usagePercentage =
|
|
271
|
+
maxMonthlyUsageLimit > 0
|
|
272
|
+
? (currentMonthMessagesCount / maxMonthlyUsageLimit) * 100
|
|
273
|
+
: 0;
|
|
274
|
+
|
|
275
|
+
const crossedThreshold = this.calculateThreshold(usagePercentage);
|
|
276
|
+
|
|
277
|
+
if (!crossedThreshold) {
|
|
278
|
+
logger.debug(
|
|
279
|
+
{
|
|
280
|
+
organizationId,
|
|
281
|
+
usagePercentage,
|
|
282
|
+
lowestThreshold: USAGE_WARNING_THRESHOLDS[0],
|
|
283
|
+
},
|
|
284
|
+
"Usage below all warning thresholds, skipping notification",
|
|
285
|
+
);
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const organization = await this.organizationService.findWithAdmins(organizationId);
|
|
290
|
+
|
|
291
|
+
if (!organization) {
|
|
292
|
+
logger.warn({ organizationId }, "Organization not found");
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
if (organization.members.length === 0) {
|
|
297
|
+
logger.warn(
|
|
298
|
+
{ organizationId },
|
|
299
|
+
"No admin members found for organization",
|
|
300
|
+
);
|
|
301
|
+
return null;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Check if we've sent a notification for this specific threshold in the current calendar month.
|
|
305
|
+
//
|
|
306
|
+
// NOTE: This check-then-insert pattern has a small race window where two concurrent
|
|
307
|
+
// workers could both pass the check and send duplicate emails. This is acceptable
|
|
308
|
+
// because: (1) this runs from a single cron worker and a user-initiated tRPC mutation
|
|
309
|
+
// that is unlikely to fire concurrently, and (2) the worst case is a duplicate email
|
|
310
|
+
// in the same month, which is benign. If a stronger guarantee is needed, add a unique
|
|
311
|
+
// constraint on (organizationId, threshold, yearMonth) via a database migration.
|
|
312
|
+
const currentMonthStart = getCurrentMonthStart();
|
|
313
|
+
|
|
314
|
+
const recentNotifications =
|
|
315
|
+
await this.notificationRepository.findRecentByOrganization(
|
|
316
|
+
organizationId,
|
|
317
|
+
currentMonthStart,
|
|
318
|
+
);
|
|
319
|
+
|
|
320
|
+
const recentNotification = recentNotifications.find((notification) => {
|
|
321
|
+
if (!notification.metadata || typeof notification.metadata !== "object") {
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
const metadata = notification.metadata as Record<string, unknown>;
|
|
325
|
+
return (
|
|
326
|
+
metadata.type === NOTIFICATION_TYPES.USAGE_LIMIT_WARNING &&
|
|
327
|
+
metadata.threshold === crossedThreshold
|
|
328
|
+
);
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
if (recentNotification) {
|
|
332
|
+
logger.debug(
|
|
333
|
+
{
|
|
334
|
+
organizationId,
|
|
335
|
+
threshold: crossedThreshold,
|
|
336
|
+
lastSentAt: recentNotification.sentAt,
|
|
337
|
+
currentMonthStart,
|
|
338
|
+
},
|
|
339
|
+
"Notification already sent for this threshold in current calendar month, skipping duplicate",
|
|
340
|
+
);
|
|
341
|
+
return null;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// Fetch projects and their usage
|
|
345
|
+
const projects = await this.organizationService.findProjectsWithName(organizationId);
|
|
346
|
+
|
|
347
|
+
const projectIds = projects.map((p) => p.id);
|
|
348
|
+
const counts = await this.usageService.getCountByProjects({
|
|
349
|
+
organizationId,
|
|
350
|
+
projectIds,
|
|
351
|
+
});
|
|
352
|
+
const countsMap = new Map(counts.map((c) => [c.projectId, c.count]));
|
|
353
|
+
const projectUsageData = projects.map((p) => ({
|
|
354
|
+
id: p.id,
|
|
355
|
+
name: p.name,
|
|
356
|
+
messageCount: countsMap.get(p.id) ?? 0,
|
|
357
|
+
}));
|
|
358
|
+
|
|
359
|
+
const emailContext = this.buildEmailContext({
|
|
360
|
+
organizationName: organization.name,
|
|
361
|
+
usagePercentage,
|
|
362
|
+
currentMonthMessagesCount,
|
|
363
|
+
maxMonthlyUsageLimit,
|
|
364
|
+
crossedThreshold,
|
|
365
|
+
projectUsageData,
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
const deliverableAdmins = organization.members.filter(
|
|
369
|
+
(member) => member.user.email,
|
|
370
|
+
);
|
|
371
|
+
|
|
372
|
+
if (deliverableAdmins.length === 0) {
|
|
373
|
+
logger.info(
|
|
374
|
+
{
|
|
375
|
+
organizationId,
|
|
376
|
+
totalAdmins: organization.members.length,
|
|
377
|
+
usagePercentage: usagePercentage.toFixed(2),
|
|
378
|
+
threshold: crossedThreshold,
|
|
379
|
+
},
|
|
380
|
+
"No admins with email addresses found, skipping notification (no deliverable recipients)",
|
|
381
|
+
);
|
|
382
|
+
return null;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
try {
|
|
386
|
+
const { recipientsSuccessCount, recipientsFailureCount, failedRecipients } =
|
|
387
|
+
await this.dispatchEmails({
|
|
388
|
+
organizationId,
|
|
389
|
+
organizationName: organization.name,
|
|
390
|
+
deliverableAdmins,
|
|
391
|
+
emailContext,
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
if (recipientsSuccessCount === 0) {
|
|
395
|
+
logger.error(
|
|
396
|
+
{
|
|
397
|
+
organizationId,
|
|
398
|
+
recipientsFailureCount,
|
|
399
|
+
failedRecipients,
|
|
400
|
+
usagePercentage: usagePercentage.toFixed(2),
|
|
401
|
+
threshold: crossedThreshold,
|
|
402
|
+
},
|
|
403
|
+
"All usage limit warning emails failed to send, aborting notification creation to allow retries",
|
|
404
|
+
);
|
|
405
|
+
throw new Error(
|
|
406
|
+
`All ${recipientsFailureCount} usage limit warning emails failed to send`,
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const notification = await this.recordNotification({
|
|
411
|
+
organizationId,
|
|
412
|
+
currentMonthMessagesCount,
|
|
413
|
+
maxMonthlyUsageLimit,
|
|
414
|
+
usagePercentage,
|
|
415
|
+
crossedThreshold,
|
|
416
|
+
deliverableAdminsCount: deliverableAdmins.length,
|
|
417
|
+
recipientsSuccessCount,
|
|
418
|
+
recipientsFailureCount,
|
|
419
|
+
failedRecipients,
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
logger.info(
|
|
423
|
+
{
|
|
424
|
+
organizationId,
|
|
425
|
+
notificationId: notification.id,
|
|
426
|
+
recipientsCount: deliverableAdmins.length,
|
|
427
|
+
recipientsSuccessCount,
|
|
428
|
+
recipientsFailureCount,
|
|
429
|
+
...(recipientsFailureCount > 0 && { failedRecipients }),
|
|
430
|
+
usagePercentage: usagePercentage.toFixed(2),
|
|
431
|
+
threshold: crossedThreshold,
|
|
432
|
+
},
|
|
433
|
+
"Usage limit warning notifications sent successfully",
|
|
434
|
+
);
|
|
435
|
+
|
|
436
|
+
return notification;
|
|
437
|
+
} catch (error) {
|
|
438
|
+
logger.error(
|
|
439
|
+
{ error, organizationId },
|
|
440
|
+
"Error sending usage limit warning notifications",
|
|
441
|
+
);
|
|
442
|
+
throw error;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// -------------------------------------------------------------------------
|
|
447
|
+
// Private helpers for checkAndSendWarning
|
|
448
|
+
// -------------------------------------------------------------------------
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Finds the highest warning threshold crossed by the current usage percentage.
|
|
452
|
+
*/
|
|
453
|
+
private calculateThreshold(
|
|
454
|
+
usagePercentage: number,
|
|
455
|
+
): (typeof USAGE_WARNING_THRESHOLDS)[number] | undefined {
|
|
456
|
+
return USAGE_WARNING_THRESHOLDS.findLast(
|
|
457
|
+
(threshold) => usagePercentage >= threshold,
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Builds the email data object with severity, formatting, and presentation constants.
|
|
463
|
+
*/
|
|
464
|
+
private buildEmailContext({
|
|
465
|
+
organizationName,
|
|
466
|
+
usagePercentage,
|
|
467
|
+
currentMonthMessagesCount,
|
|
468
|
+
maxMonthlyUsageLimit,
|
|
469
|
+
crossedThreshold,
|
|
470
|
+
projectUsageData,
|
|
471
|
+
}: {
|
|
472
|
+
organizationName: string;
|
|
473
|
+
usagePercentage: number;
|
|
474
|
+
currentMonthMessagesCount: number;
|
|
475
|
+
maxMonthlyUsageLimit: number;
|
|
476
|
+
crossedThreshold: number;
|
|
477
|
+
projectUsageData: Array<{ id: string; name: string; messageCount: number }>;
|
|
478
|
+
}): UsageLimitEmailData {
|
|
479
|
+
const baseUrl = env.BASE_HOST ?? "https://app.langwatch.ai";
|
|
480
|
+
const actionUrl = `${baseUrl}/settings/usage`;
|
|
481
|
+
|
|
482
|
+
const logoUrl =
|
|
483
|
+
"https://hs-143534269.f.hubspotstarter-eu1.net/hub/143534269/hubfs/header-3.png?width=1116&upscale=true&name=header-3.png";
|
|
484
|
+
|
|
485
|
+
const cappedPercentage = Math.min(usagePercentage, 100);
|
|
486
|
+
const usagePercentageFormatted = Math.floor(cappedPercentage).toString();
|
|
487
|
+
|
|
488
|
+
let severity: string;
|
|
489
|
+
if (crossedThreshold >= 95) {
|
|
490
|
+
severity = "Critical";
|
|
491
|
+
} else if (crossedThreshold >= 90) {
|
|
492
|
+
severity = "High";
|
|
493
|
+
} else if (crossedThreshold >= 70) {
|
|
494
|
+
severity = "Medium";
|
|
495
|
+
} else {
|
|
496
|
+
severity = "Info";
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
return {
|
|
500
|
+
organizationName,
|
|
501
|
+
usagePercentage,
|
|
502
|
+
usagePercentageFormatted,
|
|
503
|
+
currentMonthMessagesCount,
|
|
504
|
+
maxMonthlyUsageLimit,
|
|
505
|
+
crossedThreshold,
|
|
506
|
+
projectUsageData,
|
|
507
|
+
actionUrl,
|
|
508
|
+
logoUrl,
|
|
509
|
+
severity,
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* Sends usage limit emails to all deliverable admins, tracking successes and failures.
|
|
515
|
+
*/
|
|
516
|
+
private async dispatchEmails({
|
|
517
|
+
organizationId,
|
|
518
|
+
organizationName,
|
|
519
|
+
deliverableAdmins,
|
|
520
|
+
emailContext,
|
|
521
|
+
}: {
|
|
522
|
+
organizationId: string;
|
|
523
|
+
organizationName: string;
|
|
524
|
+
deliverableAdmins: Array<{ user: { id: string; email: string | null } }>;
|
|
525
|
+
emailContext: UsageLimitEmailData;
|
|
526
|
+
}) {
|
|
527
|
+
const emailResults = await Promise.allSettled(
|
|
528
|
+
deliverableAdmins.map(async (member) => {
|
|
529
|
+
await this.notificationService.sendUsageLimitEmail({
|
|
530
|
+
to: member.user.email!,
|
|
531
|
+
orgName: organizationName,
|
|
532
|
+
usageData: emailContext,
|
|
533
|
+
});
|
|
534
|
+
}),
|
|
535
|
+
);
|
|
536
|
+
|
|
537
|
+
let recipientsSuccessCount = 0;
|
|
538
|
+
let recipientsFailureCount = 0;
|
|
539
|
+
const failedRecipients: Array<{ userId: string; error: string }> = [];
|
|
540
|
+
|
|
541
|
+
emailResults.forEach((result, index) => {
|
|
542
|
+
const member = deliverableAdmins[index];
|
|
543
|
+
if (!member) {
|
|
544
|
+
logger.warn(
|
|
545
|
+
{ index, organizationId },
|
|
546
|
+
"Member not found at index, skipping",
|
|
547
|
+
);
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
if (result.status === "fulfilled") {
|
|
552
|
+
recipientsSuccessCount++;
|
|
553
|
+
} else {
|
|
554
|
+
recipientsFailureCount++;
|
|
555
|
+
const errorMessage =
|
|
556
|
+
result.reason instanceof Error
|
|
557
|
+
? result.reason.message
|
|
558
|
+
: String(result.reason);
|
|
559
|
+
failedRecipients.push({
|
|
560
|
+
userId: member.user.id,
|
|
561
|
+
error: errorMessage,
|
|
562
|
+
});
|
|
563
|
+
logger.error(
|
|
564
|
+
{
|
|
565
|
+
userId: member.user.id,
|
|
566
|
+
error: errorMessage,
|
|
567
|
+
organizationId,
|
|
568
|
+
},
|
|
569
|
+
"Failed to send usage limit warning email",
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
return { recipientsSuccessCount, recipientsFailureCount, failedRecipients };
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* Creates a notification record in the repository after successful email delivery.
|
|
579
|
+
*/
|
|
580
|
+
private async recordNotification({
|
|
581
|
+
organizationId,
|
|
582
|
+
currentMonthMessagesCount,
|
|
583
|
+
maxMonthlyUsageLimit,
|
|
584
|
+
usagePercentage,
|
|
585
|
+
crossedThreshold,
|
|
586
|
+
deliverableAdminsCount,
|
|
587
|
+
recipientsSuccessCount,
|
|
588
|
+
recipientsFailureCount,
|
|
589
|
+
failedRecipients,
|
|
590
|
+
}: {
|
|
591
|
+
organizationId: string;
|
|
592
|
+
currentMonthMessagesCount: number;
|
|
593
|
+
maxMonthlyUsageLimit: number;
|
|
594
|
+
usagePercentage: number;
|
|
595
|
+
crossedThreshold: number;
|
|
596
|
+
deliverableAdminsCount: number;
|
|
597
|
+
recipientsSuccessCount: number;
|
|
598
|
+
recipientsFailureCount: number;
|
|
599
|
+
failedRecipients: Array<{ userId: string; error: string }>;
|
|
600
|
+
}) {
|
|
601
|
+
return this.notificationRepository.create({
|
|
602
|
+
organizationId,
|
|
603
|
+
sentAt: new Date(),
|
|
604
|
+
metadata: {
|
|
605
|
+
type: NOTIFICATION_TYPES.USAGE_LIMIT_WARNING,
|
|
606
|
+
currentUsage: currentMonthMessagesCount,
|
|
607
|
+
limit: maxMonthlyUsageLimit,
|
|
608
|
+
percentage: usagePercentage,
|
|
609
|
+
threshold: crossedThreshold,
|
|
610
|
+
recipientsCount: deliverableAdminsCount,
|
|
611
|
+
recipientsSuccessCount,
|
|
612
|
+
recipientsFailureCount,
|
|
613
|
+
...(recipientsFailureCount > 0 && {
|
|
614
|
+
failedRecipients: failedRecipients.map((f) => ({
|
|
615
|
+
userId: f.userId,
|
|
616
|
+
error: f.error,
|
|
617
|
+
})),
|
|
618
|
+
}),
|
|
619
|
+
},
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { getApp } from "../../../../src/server/app-layer/app";
|
|
2
|
+
import { captureException } from "../../../../src/utils/posthogErrorCapture";
|
|
3
|
+
|
|
4
|
+
const ONE_HOUR_MS = 60 * 60 * 1000;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* In-memory cache of the last time each user was identified for activity tracking.
|
|
8
|
+
* Keyed by userId, value is the timestamp of the last identify call.
|
|
9
|
+
*
|
|
10
|
+
* NOTE: debounce is process-local. In multi-instance deployments, each instance
|
|
11
|
+
* tracks independently. This is acceptable — Customer.io's 3000 req/3s limit
|
|
12
|
+
* is unlikely to be hit, and duplicate identify calls are idempotent.
|
|
13
|
+
*/
|
|
14
|
+
const lastActivitySentAt = new Map<string, number>();
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Timestamp of the last sweep pass. Sweeps run at most once per hour
|
|
18
|
+
* to avoid O(n) iteration overhead on every call.
|
|
19
|
+
*/
|
|
20
|
+
let lastSweepAt = 0;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Evicts entries older than ONE_HOUR_MS from the debounce cache.
|
|
24
|
+
* Only runs at most once per hour to keep per-call cost constant.
|
|
25
|
+
*/
|
|
26
|
+
function sweepExpiredEntries({ now }: { now: number }): void {
|
|
27
|
+
if (now - lastSweepAt < ONE_HOUR_MS) return;
|
|
28
|
+
for (const [cachedUserId, sentAt] of lastActivitySentAt) {
|
|
29
|
+
if (now - sentAt >= ONE_HOUR_MS) {
|
|
30
|
+
lastActivitySentAt.delete(cachedUserId);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
lastSweepAt = now;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Pushes last_active_at to Customer.io for inactivity detection.
|
|
38
|
+
*
|
|
39
|
+
* Debounced to at most once per hour per user to avoid excessive API calls.
|
|
40
|
+
* Fire-and-forget: never throws, never blocks the session callback.
|
|
41
|
+
*/
|
|
42
|
+
export function fireActivityTrackingNurturing({
|
|
43
|
+
userId,
|
|
44
|
+
hasOrganization = true,
|
|
45
|
+
}: {
|
|
46
|
+
userId: string;
|
|
47
|
+
/** When false, the user hasn't completed onboarding yet — skip identify to avoid ghost people in Customer.io. */
|
|
48
|
+
hasOrganization?: boolean;
|
|
49
|
+
}): void {
|
|
50
|
+
const nurturing = getApp().nurturing;
|
|
51
|
+
if (!nurturing) return;
|
|
52
|
+
if (!hasOrganization) return;
|
|
53
|
+
|
|
54
|
+
const now = Date.now();
|
|
55
|
+
sweepExpiredEntries({ now });
|
|
56
|
+
const lastSent = lastActivitySentAt.get(userId);
|
|
57
|
+
|
|
58
|
+
if (lastSent !== undefined && now - lastSent < ONE_HOUR_MS) {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
lastActivitySentAt.set(userId, now);
|
|
63
|
+
|
|
64
|
+
void nurturing
|
|
65
|
+
.identifyUser({
|
|
66
|
+
userId,
|
|
67
|
+
traits: { last_active_at: new Date(now).toISOString() },
|
|
68
|
+
})
|
|
69
|
+
.catch((error) => {
|
|
70
|
+
lastActivitySentAt.delete(userId);
|
|
71
|
+
captureException(error);
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Resets the debounce cache. Only exposed for testing.
|
|
77
|
+
* @internal
|
|
78
|
+
*/
|
|
79
|
+
export function resetActivityTrackingCache(): void {
|
|
80
|
+
lastActivitySentAt.clear();
|
|
81
|
+
lastSweepAt = 0;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Returns a snapshot of the cache for testing.
|
|
86
|
+
* @internal
|
|
87
|
+
*/
|
|
88
|
+
export function getActivityTrackingCacheSize(): number {
|
|
89
|
+
return lastActivitySentAt.size;
|
|
90
|
+
}
|