@opengeni/api-router 5.4.1 → 5.5.0-canary.37090756480001
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/dist/app.js +1 -1
- package/dist/{chunk-2QCRFD6U.js → chunk-ZQ7PIFGF.js} +719 -356
- package/dist/{chunk-2QCRFD6U.js.map → chunk-ZQ7PIFGF.js.map} +1 -1
- package/dist/claude-subscription-usage.d.ts +21 -0
- package/dist/http/api-error.d.ts +7 -0
- package/dist/index.js +1 -1
- package/dist/integrations/github-lens-connect.d.ts +2 -2
- package/dist/integrations/slack-interactions.d.ts +1 -1
- package/dist/mcp/first-party-tool-permissions.d.ts +8 -0
- package/dist/routes/billing.d.ts +4 -1
- package/dist/routes/client-errors.d.ts +104 -0
- package/dist/routes/insights.d.ts +2 -0
- package/dist/routes/sessions.d.ts +1 -0
- package/package.json +20 -20
- package/src/app.ts +28 -0
- package/src/http/api-error.ts +29 -1
- package/src/http/sse.ts +10 -4
- package/src/mcp/first-party-tool-permissions.ts +5 -0
- package/src/mcp/knowledge-entries.ts +3 -3
- package/src/mcp/server.ts +3 -1
- package/src/model-catalog.ts +5 -0
- package/src/routes/api-integrations.ts +6 -0
- package/src/routes/automations.ts +2 -4
- package/src/routes/billing.ts +118 -21
- package/src/routes/browser-sessions.ts +15 -1
- package/src/routes/client-errors.ts +201 -4
- package/src/routes/computer-sessions.ts +15 -1
- package/src/routes/connections.ts +55 -4
- package/src/routes/insights.ts +19 -1
- package/src/routes/pr-review.ts +2 -3
- package/src/routes/sessions.ts +97 -41
- package/src/routes/workspaces.ts +45 -74
- package/src/workspace-deletion.ts +9 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { environmentsEncryptionKeyBytes } from "@opengeni/config";
|
|
2
|
-
import { requireAgentConfigAdmission } from "@opengeni/core";
|
|
2
|
+
import { modelUnavailableHttpException, requireAgentConfigAdmission } from "@opengeni/core";
|
|
3
3
|
import {
|
|
4
4
|
AUTOMATION_WEBHOOK_MAX_BYTES,
|
|
5
5
|
AUTOMATION_MAX_MATCHED_TRIGGERS,
|
|
@@ -692,9 +692,7 @@ function workspaceCustomModelCommitGuard(input: {
|
|
|
692
692
|
reference,
|
|
693
693
|
});
|
|
694
694
|
if (!active) {
|
|
695
|
-
throw
|
|
696
|
-
message: `model is not available: ${input.modelId}`,
|
|
697
|
-
});
|
|
695
|
+
throw modelUnavailableHttpException(input.modelId);
|
|
698
696
|
}
|
|
699
697
|
};
|
|
700
698
|
}
|
package/src/routes/billing.ts
CHANGED
|
@@ -8,14 +8,17 @@ import {
|
|
|
8
8
|
type AccessContext,
|
|
9
9
|
type Permission,
|
|
10
10
|
} from "@opengeni/contracts";
|
|
11
|
+
import { OrganizationModelUsageQuery } from "@opengeni/contracts/organization-model-usage";
|
|
11
12
|
import { configuredEntitlements } from "@opengeni/config";
|
|
12
13
|
import {
|
|
13
14
|
applyCreditLedgerEntry,
|
|
14
15
|
getBillingBalance,
|
|
15
16
|
getBillingCustomer,
|
|
17
|
+
getCreditLedgerEntry,
|
|
16
18
|
hasCreditLedgerEntry,
|
|
17
19
|
isStripeWebhookProcessed,
|
|
18
20
|
listUsageEvents,
|
|
21
|
+
getOrganizationModelUsage,
|
|
19
22
|
getOrganizationUsageSummary,
|
|
20
23
|
getOrganizationUsageWorkspacePage,
|
|
21
24
|
withSessionRlsActorContext,
|
|
@@ -90,6 +93,19 @@ export function registerBillingRoutes(app: Hono, deps: ApiRouteDeps): void {
|
|
|
90
93
|
);
|
|
91
94
|
});
|
|
92
95
|
|
|
96
|
+
app.get("/v1/billing/usage-models", async (c) => {
|
|
97
|
+
const context = await requireAccessContext(c, deps);
|
|
98
|
+
const accountId = requireSelectedAccount(context, c.req.query("accountId"), "billing:read");
|
|
99
|
+
const parsed = OrganizationModelUsageQuery.safeParse(c.req.query());
|
|
100
|
+
if (!parsed.success)
|
|
101
|
+
throw new HTTPException(400, {
|
|
102
|
+
message: parsed.error.issues[0]?.message ?? "invalid model usage query",
|
|
103
|
+
});
|
|
104
|
+
return await withBillingUsageActor(deps, context, accountId, async () =>
|
|
105
|
+
c.json(await getOrganizationModelUsage(deps.db, { accountId, ...parsed.data })),
|
|
106
|
+
);
|
|
107
|
+
});
|
|
108
|
+
|
|
93
109
|
app.get("/v1/billing/entitlements", async (c) => {
|
|
94
110
|
const context = await requireAccessContext(c, deps);
|
|
95
111
|
const accountId = requireSelectedAccount(context, c.req.query("accountId"), "billing:read");
|
|
@@ -126,6 +142,7 @@ export function registerBillingRoutes(app: Hono, deps: ApiRouteDeps): void {
|
|
|
126
142
|
amountMicros,
|
|
127
143
|
creditsProductId: deps.settings.stripeCreditsProductId,
|
|
128
144
|
publicBaseUrl: deps.settings.publicBaseUrl,
|
|
145
|
+
webBaseUrl: deps.settings.webBaseUrl,
|
|
129
146
|
successUrl: body.successUrl,
|
|
130
147
|
cancelUrl: body.cancelUrl,
|
|
131
148
|
idempotencyKey,
|
|
@@ -161,6 +178,7 @@ export function registerBillingRoutes(app: Hono, deps: ApiRouteDeps): void {
|
|
|
161
178
|
stripeBillingPortalSessionCreateParams({
|
|
162
179
|
customerId,
|
|
163
180
|
publicBaseUrl: deps.settings.publicBaseUrl,
|
|
181
|
+
webBaseUrl: deps.settings.webBaseUrl,
|
|
164
182
|
returnUrl: parsed.data.returnUrl,
|
|
165
183
|
}),
|
|
166
184
|
);
|
|
@@ -226,24 +244,28 @@ export function stripeCheckoutSessionCreateParams(input: {
|
|
|
226
244
|
amountMicros: number;
|
|
227
245
|
creditsProductId?: string | undefined;
|
|
228
246
|
publicBaseUrl?: string | undefined;
|
|
247
|
+
webBaseUrl?: string | undefined;
|
|
229
248
|
successUrl?: string | undefined;
|
|
230
249
|
cancelUrl?: string | undefined;
|
|
231
250
|
idempotencyKey: string;
|
|
232
251
|
}): Stripe.Checkout.SessionCreateParams {
|
|
233
252
|
const successUrl = checkoutReturnUrl(
|
|
234
253
|
input.publicBaseUrl,
|
|
254
|
+
input.webBaseUrl,
|
|
235
255
|
input.successUrl,
|
|
236
256
|
"/billing?checkout=success",
|
|
237
257
|
"successUrl",
|
|
238
258
|
);
|
|
239
259
|
const cancelUrl = checkoutReturnUrl(
|
|
240
260
|
input.publicBaseUrl,
|
|
261
|
+
input.webBaseUrl,
|
|
241
262
|
input.cancelUrl,
|
|
242
263
|
"/billing?checkout=cancelled",
|
|
243
264
|
"cancelUrl",
|
|
244
265
|
);
|
|
245
266
|
return {
|
|
246
267
|
mode: "payment",
|
|
268
|
+
allow_promotion_codes: true,
|
|
247
269
|
customer: input.customerId,
|
|
248
270
|
customer_update: {
|
|
249
271
|
address: "auto",
|
|
@@ -278,6 +300,7 @@ export function stripeCheckoutSessionCreateParams(input: {
|
|
|
278
300
|
opengeni_credit_amount_usd: (input.amountCents / 100).toFixed(2),
|
|
279
301
|
opengeni_credit_micros: String(input.amountMicros),
|
|
280
302
|
opengeni_credit_idempotency_key: input.idempotencyKey,
|
|
303
|
+
opengeni_credit_coupon_v1: "1",
|
|
281
304
|
},
|
|
282
305
|
payment_intent_data: {
|
|
283
306
|
metadata: {
|
|
@@ -285,6 +308,7 @@ export function stripeCheckoutSessionCreateParams(input: {
|
|
|
285
308
|
opengeni_credit_amount_usd: (input.amountCents / 100).toFixed(2),
|
|
286
309
|
opengeni_credit_micros: String(input.amountMicros),
|
|
287
310
|
opengeni_credit_idempotency_key: input.idempotencyKey,
|
|
311
|
+
opengeni_credit_coupon_v1: "1",
|
|
288
312
|
},
|
|
289
313
|
},
|
|
290
314
|
invoice_creation: {
|
|
@@ -295,6 +319,7 @@ export function stripeCheckoutSessionCreateParams(input: {
|
|
|
295
319
|
opengeni_credit_amount_usd: (input.amountCents / 100).toFixed(2),
|
|
296
320
|
opengeni_credit_micros: String(input.amountMicros),
|
|
297
321
|
opengeni_credit_idempotency_key: input.idempotencyKey,
|
|
322
|
+
opengeni_credit_coupon_v1: "1",
|
|
298
323
|
},
|
|
299
324
|
},
|
|
300
325
|
},
|
|
@@ -304,16 +329,24 @@ export function stripeCheckoutSessionCreateParams(input: {
|
|
|
304
329
|
export function stripeBillingPortalSessionCreateParams(input: {
|
|
305
330
|
customerId: string;
|
|
306
331
|
publicBaseUrl?: string | undefined;
|
|
332
|
+
webBaseUrl?: string | undefined;
|
|
307
333
|
returnUrl?: string | undefined;
|
|
308
334
|
}): Stripe.BillingPortal.SessionCreateParams {
|
|
309
335
|
return {
|
|
310
336
|
customer: input.customerId,
|
|
311
|
-
return_url: checkoutReturnUrl(
|
|
337
|
+
return_url: checkoutReturnUrl(
|
|
338
|
+
input.publicBaseUrl,
|
|
339
|
+
input.webBaseUrl,
|
|
340
|
+
input.returnUrl,
|
|
341
|
+
"/billing",
|
|
342
|
+
"returnUrl",
|
|
343
|
+
),
|
|
312
344
|
};
|
|
313
345
|
}
|
|
314
346
|
|
|
315
347
|
function checkoutReturnUrl(
|
|
316
348
|
publicBaseUrl: string | undefined,
|
|
349
|
+
webBaseUrl: string | undefined,
|
|
317
350
|
candidate: string | undefined,
|
|
318
351
|
fallbackPath: string,
|
|
319
352
|
field: string,
|
|
@@ -323,14 +356,17 @@ function checkoutReturnUrl(
|
|
|
323
356
|
message: "OPENGENI_PUBLIC_BASE_URL is required for Stripe redirects",
|
|
324
357
|
});
|
|
325
358
|
}
|
|
326
|
-
const base = new URL(publicBaseUrl);
|
|
359
|
+
const base = new URL(webBaseUrl ?? publicBaseUrl);
|
|
327
360
|
const fallback = new URL(fallbackPath, base).toString();
|
|
328
361
|
if (!candidate) {
|
|
329
362
|
return fallback;
|
|
330
363
|
}
|
|
331
364
|
const parsed = new URL(candidate);
|
|
332
|
-
|
|
333
|
-
|
|
365
|
+
const allowedOrigins = new Set([new URL(publicBaseUrl).origin, base.origin]);
|
|
366
|
+
if (!allowedOrigins.has(parsed.origin)) {
|
|
367
|
+
throw new HTTPException(400, {
|
|
368
|
+
message: `${field} must use the OpenGeni public${allowedOrigins.size > 1 ? " or web" : ""} origin`,
|
|
369
|
+
});
|
|
334
370
|
}
|
|
335
371
|
return parsed.toString();
|
|
336
372
|
}
|
|
@@ -393,7 +429,8 @@ export type StripeCheckoutCreditDecision =
|
|
|
393
429
|
* Sessions created outside OpenGeni on the same Stripe account carry no
|
|
394
430
|
* `opengeni_` metadata and are acknowledged without effect. An OpenGeni
|
|
395
431
|
* session with malformed credit metadata still throws so the failure stays
|
|
396
|
-
* visible. Credits are granted
|
|
432
|
+
* visible. Credits are granted once Stripe reports the payment `paid` or a
|
|
433
|
+
* completed checkout fully covered by a coupon:
|
|
397
434
|
* on `checkout.session.completed` for immediate methods, or on
|
|
398
435
|
* `checkout.session.async_payment_succeeded` for delayed methods, whose
|
|
399
436
|
* completion event arrives `unpaid`. Both events carry the same session
|
|
@@ -408,13 +445,32 @@ export function stripeCheckoutCreditDecision(
|
|
|
408
445
|
if (session.mode !== "payment") {
|
|
409
446
|
return { action: "ignore", reason: "not_payment_mode" };
|
|
410
447
|
}
|
|
411
|
-
if (session.payment_status !== "paid") {
|
|
448
|
+
if (session.payment_status !== "paid" && !isFreeCouponCheckout(session)) {
|
|
412
449
|
return { action: "ignore", reason: "payment_not_paid" };
|
|
413
450
|
}
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
451
|
+
const credit = creditMetadata(session.metadata, `Stripe checkout session ${session.id}`);
|
|
452
|
+
if (
|
|
453
|
+
session.metadata?.opengeni_credit_coupon_v1 === "1" &&
|
|
454
|
+
(session.currency !== "usd" ||
|
|
455
|
+
session.amount_subtotal !== credit.amountMicros / 10_000 ||
|
|
456
|
+
typeof session.amount_total !== "number" ||
|
|
457
|
+
!Number.isSafeInteger(session.amount_total) ||
|
|
458
|
+
session.amount_total < 0)
|
|
459
|
+
) {
|
|
460
|
+
throw new Error(`Stripe checkout session ${session.id} has invalid credit package totals`);
|
|
461
|
+
}
|
|
462
|
+
return { action: "grant", credit };
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function isFreeCouponCheckout(session: Stripe.Checkout.Session): boolean {
|
|
466
|
+
return (
|
|
467
|
+
(session.payment_status === "paid" || session.payment_status === "no_payment_required") &&
|
|
468
|
+
session.status === "complete" &&
|
|
469
|
+
session.amount_total === 0 &&
|
|
470
|
+
typeof session.amount_subtotal === "number" &&
|
|
471
|
+
session.amount_subtotal > 0 &&
|
|
472
|
+
(session.total_details?.amount_discount ?? 0) >= session.amount_subtotal
|
|
473
|
+
);
|
|
418
474
|
}
|
|
419
475
|
|
|
420
476
|
async function handleCheckoutSessionPayment(
|
|
@@ -433,6 +489,7 @@ async function handleCheckoutSessionPayment(
|
|
|
433
489
|
return;
|
|
434
490
|
}
|
|
435
491
|
const credit = decision.credit;
|
|
492
|
+
const freeCouponCheckout = isFreeCouponCheckout(session);
|
|
436
493
|
if (!(await getManagedAccount(deps.db, credit.accountId))) {
|
|
437
494
|
// Another OpenGeni deployment sharing the Stripe account (or an account
|
|
438
495
|
// removed before a delayed payment settled). Retrying cannot succeed, so
|
|
@@ -457,9 +514,9 @@ async function handleCheckoutSessionPayment(
|
|
|
457
514
|
}
|
|
458
515
|
await applyCreditLedgerEntry(deps.db, {
|
|
459
516
|
accountId: credit.accountId,
|
|
460
|
-
type: "credit_topup",
|
|
517
|
+
type: freeCouponCheckout ? "grant" : "credit_topup",
|
|
461
518
|
amountMicros: credit.amountMicros,
|
|
462
|
-
sourceType: "stripe_checkout_session",
|
|
519
|
+
sourceType: freeCouponCheckout ? "stripe_checkout_coupon" : "stripe_checkout_session",
|
|
463
520
|
sourceId: session.id,
|
|
464
521
|
idempotencyKey: credit.idempotencyKey,
|
|
465
522
|
metadata: {
|
|
@@ -470,9 +527,15 @@ async function handleCheckoutSessionPayment(
|
|
|
470
527
|
: (session.payment_intent?.id ?? null),
|
|
471
528
|
stripePackageId: credit.packageId,
|
|
472
529
|
stripeCreditAmountUsd: credit.amountUsd,
|
|
530
|
+
...(session.metadata?.opengeni_credit_coupon_v1 === "1"
|
|
531
|
+
? {
|
|
532
|
+
stripeAmountTotalCents: session.amount_total,
|
|
533
|
+
stripeDiscountCents: session.total_details?.amount_discount ?? 0,
|
|
534
|
+
}
|
|
535
|
+
: {}),
|
|
473
536
|
},
|
|
474
537
|
});
|
|
475
|
-
recordCreditMicrosMetric(deps, "topup", credit.amountMicros);
|
|
538
|
+
recordCreditMicrosMetric(deps, freeCouponCheckout ? "grant" : "topup", credit.amountMicros);
|
|
476
539
|
}
|
|
477
540
|
|
|
478
541
|
async function mirrorPaymentIntentCustomer(deps: ApiRouteDeps, event: Stripe.Event): Promise<void> {
|
|
@@ -525,19 +588,21 @@ async function applyRefundDebit(
|
|
|
525
588
|
if (await hasCreditLedgerEntry(deps.db, accountId, idempotencyKey)) {
|
|
526
589
|
return;
|
|
527
590
|
}
|
|
591
|
+
const debitMicros = await creditAdjustmentMicros(deps, metadata, refund.amount);
|
|
528
592
|
await applyCreditLedgerEntry(deps.db, {
|
|
529
593
|
accountId,
|
|
530
594
|
type: "credit_refund",
|
|
531
|
-
amountMicros: -
|
|
595
|
+
amountMicros: -debitMicros,
|
|
532
596
|
sourceType: "stripe_refund",
|
|
533
597
|
sourceId: refund.id,
|
|
534
598
|
idempotencyKey,
|
|
535
599
|
metadata: {
|
|
536
600
|
stripeRefundId: refund.id,
|
|
537
601
|
stripePaymentIntentId: paymentIntentId(refund.payment_intent),
|
|
602
|
+
stripeRefundAmountCents: refund.amount,
|
|
538
603
|
},
|
|
539
604
|
});
|
|
540
|
-
recordCreditMicrosMetric(deps, "refund",
|
|
605
|
+
recordCreditMicrosMetric(deps, "refund", debitMicros);
|
|
541
606
|
}
|
|
542
607
|
|
|
543
608
|
async function holdDisputedCredits(
|
|
@@ -551,10 +616,11 @@ async function holdDisputedCredits(
|
|
|
551
616
|
if (!accountId) {
|
|
552
617
|
return;
|
|
553
618
|
}
|
|
619
|
+
const debitMicros = await creditAdjustmentMicros(deps, metadata, dispute.amount);
|
|
554
620
|
await applyCreditLedgerEntry(deps.db, {
|
|
555
621
|
accountId,
|
|
556
622
|
type: "credit_dispute_hold",
|
|
557
|
-
amountMicros: -
|
|
623
|
+
amountMicros: -debitMicros,
|
|
558
624
|
sourceType: "stripe_dispute",
|
|
559
625
|
sourceId: dispute.id,
|
|
560
626
|
idempotencyKey: `stripe:dispute_hold:${dispute.id}`,
|
|
@@ -580,10 +646,11 @@ async function releaseDisputedCredits(
|
|
|
580
646
|
if (!(await hasCreditLedgerEntry(deps.db, accountId, holdIdempotencyKey))) {
|
|
581
647
|
return;
|
|
582
648
|
}
|
|
649
|
+
const debitMicros = await creditAdjustmentMicros(deps, metadata, dispute.amount);
|
|
583
650
|
await applyCreditLedgerEntry(deps.db, {
|
|
584
651
|
accountId,
|
|
585
652
|
type: "credit_dispute_release",
|
|
586
|
-
amountMicros:
|
|
653
|
+
amountMicros: debitMicros,
|
|
587
654
|
sourceType: "stripe_dispute",
|
|
588
655
|
sourceId: dispute.id,
|
|
589
656
|
idempotencyKey: `stripe:dispute_release:${dispute.id}`,
|
|
@@ -591,6 +658,34 @@ async function releaseDisputedCredits(
|
|
|
591
658
|
});
|
|
592
659
|
}
|
|
593
660
|
|
|
661
|
+
async function creditAdjustmentMicros(
|
|
662
|
+
deps: ApiRouteDeps,
|
|
663
|
+
metadata: Stripe.Metadata | null,
|
|
664
|
+
amountCents: number,
|
|
665
|
+
): Promise<number> {
|
|
666
|
+
if (metadata?.opengeni_credit_coupon_v1 !== "1") return centsToMicros(amountCents);
|
|
667
|
+
const credit = creditMetadata(metadata, "Stripe adjustment");
|
|
668
|
+
const entry = await getCreditLedgerEntry(deps.db, credit.accountId, credit.idempotencyKey);
|
|
669
|
+
const paidCents = entry?.metadata.stripeAmountTotalCents;
|
|
670
|
+
if (
|
|
671
|
+
entry?.sourceType !== "stripe_checkout_session" ||
|
|
672
|
+
entry.amountMicros !== credit.amountMicros ||
|
|
673
|
+
typeof paidCents !== "number" ||
|
|
674
|
+
!Number.isSafeInteger(paidCents) ||
|
|
675
|
+
paidCents <= 0 ||
|
|
676
|
+
!Number.isSafeInteger(amountCents) ||
|
|
677
|
+
amountCents <= 0
|
|
678
|
+
) {
|
|
679
|
+
throw new Error("Stripe credit adjustment is missing a settled checkout");
|
|
680
|
+
}
|
|
681
|
+
const proportionalMicros =
|
|
682
|
+
(BigInt(entry.amountMicros) * BigInt(amountCents) + BigInt(Math.floor(paidCents / 2))) /
|
|
683
|
+
BigInt(paidCents);
|
|
684
|
+
return Number(
|
|
685
|
+
proportionalMicros > BigInt(entry.amountMicros) ? entry.amountMicros : proportionalMicros,
|
|
686
|
+
);
|
|
687
|
+
}
|
|
688
|
+
|
|
594
689
|
async function mirrorCustomer(
|
|
595
690
|
deps: ApiRouteDeps,
|
|
596
691
|
event: Stripe.Event,
|
|
@@ -628,18 +723,20 @@ async function metadataForRefund(
|
|
|
628
723
|
stripe: Stripe,
|
|
629
724
|
refund: Stripe.Refund,
|
|
630
725
|
): Promise<Stripe.Metadata | null> {
|
|
631
|
-
if (
|
|
726
|
+
if (refund.metadata?.opengeni_credit_idempotency_key) {
|
|
632
727
|
return refund.metadata;
|
|
633
728
|
}
|
|
634
729
|
const paymentIntent = paymentIntentId(refund.payment_intent);
|
|
635
|
-
return paymentIntent
|
|
730
|
+
return paymentIntent
|
|
731
|
+
? (await stripe.paymentIntents.retrieve(paymentIntent)).metadata
|
|
732
|
+
: refund.metadata;
|
|
636
733
|
}
|
|
637
734
|
|
|
638
735
|
async function metadataForDispute(
|
|
639
736
|
stripe: Stripe,
|
|
640
737
|
dispute: Stripe.Dispute,
|
|
641
738
|
): Promise<Stripe.Metadata | null> {
|
|
642
|
-
if (
|
|
739
|
+
if (dispute.metadata?.opengeni_credit_idempotency_key) {
|
|
643
740
|
return dispute.metadata;
|
|
644
741
|
}
|
|
645
742
|
const paymentIntent = paymentIntentId(
|
|
@@ -651,7 +748,7 @@ async function metadataForDispute(
|
|
|
651
748
|
}
|
|
652
749
|
const chargeId = typeof dispute.charge === "string" ? dispute.charge : dispute.charge?.id;
|
|
653
750
|
if (!chargeId) {
|
|
654
|
-
return
|
|
751
|
+
return dispute.metadata;
|
|
655
752
|
}
|
|
656
753
|
const charge = await stripe.charges.retrieve(chargeId);
|
|
657
754
|
const chargePaymentIntent = paymentIntentId(charge.payment_intent);
|
|
@@ -341,6 +341,7 @@ export function registerBrowserSessionRoutes(app: Hono, deps: ApiRouteDeps): voi
|
|
|
341
341
|
await authorizeSourceSession(deps, grant, request.sessionId, "session.control");
|
|
342
342
|
const origin = requestOrigin(context, deps.settings);
|
|
343
343
|
const authority = browserAuthorityRoot(deps);
|
|
344
|
+
let prepared: Awaited<ReturnType<typeof prepareBrowserSessionCreate>> | null = null;
|
|
344
345
|
|
|
345
346
|
try {
|
|
346
347
|
assertEphemeralBrowserCreateEnabled(
|
|
@@ -358,7 +359,7 @@ export function registerBrowserSessionRoutes(app: Hono, deps: ApiRouteDeps): voi
|
|
|
358
359
|
);
|
|
359
360
|
}
|
|
360
361
|
if (existing) assertCreateReplay(request, existing.session);
|
|
361
|
-
|
|
362
|
+
prepared = existing
|
|
362
363
|
? await prepareBrowserSessionCreate(
|
|
363
364
|
deps.db,
|
|
364
365
|
browserCreateInput(grant, workspaceId, request, existing.session.placement),
|
|
@@ -591,6 +592,18 @@ export function registerBrowserSessionRoutes(app: Hono, deps: ApiRouteDeps): voi
|
|
|
591
592
|
parsed.operation.state === "completed" && !parsed.operation.replayed ? 201 : 200,
|
|
592
593
|
);
|
|
593
594
|
} catch (error) {
|
|
595
|
+
if (prepared) {
|
|
596
|
+
// The operation lock fences a concurrent dispatch. Once a controller
|
|
597
|
+
// binding exists, retain its exact receipt for physical reconciliation.
|
|
598
|
+
await failBrowserSessionOperation(deps.db, {
|
|
599
|
+
accountId: grant.accountId,
|
|
600
|
+
workspaceId,
|
|
601
|
+
operationId: request.operationId,
|
|
602
|
+
browserSessionId: prepared.session.id,
|
|
603
|
+
onlyIfPreparedCreate: true,
|
|
604
|
+
error: interactionFailure(error),
|
|
605
|
+
}).catch(() => undefined);
|
|
606
|
+
}
|
|
594
607
|
throw browserRouteError(error);
|
|
595
608
|
}
|
|
596
609
|
});
|
|
@@ -4012,6 +4025,7 @@ async function ensureInteractionHolder(
|
|
|
4012
4025
|
},
|
|
4013
4026
|
os: placement.lease.os,
|
|
4014
4027
|
image: sandboxRuntime.image,
|
|
4028
|
+
imagePolicy: "new_creates_only",
|
|
4015
4029
|
rigVersionId: sourceSession.rigVersionId,
|
|
4016
4030
|
leaseTtlMs: deps.settings.sandboxLeaseTtlMs,
|
|
4017
4031
|
expectedEpoch: placement.lease.leaseEpoch,
|
|
@@ -10,6 +10,14 @@
|
|
|
10
10
|
// all drop reports. Because the route is anonymous, any HTTP client that omits
|
|
11
11
|
// or forges `Origin` can still send reports up to the admission ceiling, so
|
|
12
12
|
// alert on rates and ratios, not on absolute counts.
|
|
13
|
+
//
|
|
14
|
+
// The same route admits closed operational signals discriminated by a
|
|
15
|
+
// `signal` field: key requests that failed before any HTTP response
|
|
16
|
+
// (`opengeni_client_request_failures_total{action,reason}`), live-stream health
|
|
17
|
+
// (`opengeni_client_stream_events_total{stream,event}`), and web vitals
|
|
18
|
+
// (`opengeni_client_web_vital{metric,page}`). They carry the same closed-value
|
|
19
|
+
// guarantees and have their own per-key admission buckets, so a burst of one
|
|
20
|
+
// signal never spends the error kinds' budget.
|
|
13
21
|
import type { Settings } from "@opengeni/config";
|
|
14
22
|
import {
|
|
15
23
|
CLIENT_ERROR_KINDS,
|
|
@@ -17,7 +25,16 @@ import {
|
|
|
17
25
|
CLIENT_ERROR_REVISION_PATTERN,
|
|
18
26
|
CLIENT_ERROR_ROUTE_PATTERN,
|
|
19
27
|
CLIENT_ERRORS_PATH,
|
|
28
|
+
CLIENT_PAGES,
|
|
29
|
+
CLIENT_REQUEST_ACTIONS,
|
|
30
|
+
CLIENT_REQUEST_FAILURE_REASONS,
|
|
31
|
+
CLIENT_SIGNALS,
|
|
32
|
+
CLIENT_STREAM_EVENTS,
|
|
33
|
+
CLIENT_STREAMS,
|
|
34
|
+
CLIENT_WEB_VITAL_MAX_VALUE,
|
|
35
|
+
CLIENT_WEB_VITAL_METRICS,
|
|
20
36
|
type ClientErrorKind,
|
|
37
|
+
type ClientSignal,
|
|
21
38
|
} from "@opengeni/contracts/client-error-report";
|
|
22
39
|
import type { Observability } from "@opengeni/observability";
|
|
23
40
|
import type { Context, Hono } from "hono";
|
|
@@ -46,6 +63,42 @@ export const ClientErrorReport = z
|
|
|
46
63
|
.strict();
|
|
47
64
|
export type ClientErrorReport = z.infer<typeof ClientErrorReport>;
|
|
48
65
|
|
|
66
|
+
const route = z.string().regex(CLIENT_ERROR_ROUTE_PATTERN);
|
|
67
|
+
const revision = z.string().regex(CLIENT_ERROR_REVISION_PATTERN);
|
|
68
|
+
|
|
69
|
+
export const ClientSignalReport = z.discriminatedUnion("signal", [
|
|
70
|
+
z
|
|
71
|
+
.object({
|
|
72
|
+
signal: z.literal("request_failure"),
|
|
73
|
+
action: z.enum(CLIENT_REQUEST_ACTIONS),
|
|
74
|
+
reason: z.enum(CLIENT_REQUEST_FAILURE_REASONS),
|
|
75
|
+
route,
|
|
76
|
+
revision,
|
|
77
|
+
})
|
|
78
|
+
.strict(),
|
|
79
|
+
z
|
|
80
|
+
.object({
|
|
81
|
+
signal: z.literal("stream"),
|
|
82
|
+
stream: z.enum(CLIENT_STREAMS),
|
|
83
|
+
event: z.enum(CLIENT_STREAM_EVENTS),
|
|
84
|
+
route,
|
|
85
|
+
revision,
|
|
86
|
+
})
|
|
87
|
+
.strict(),
|
|
88
|
+
z
|
|
89
|
+
.object({
|
|
90
|
+
signal: z.literal("web_vital"),
|
|
91
|
+
metric: z.enum(CLIENT_WEB_VITAL_METRICS),
|
|
92
|
+
page: z.enum(CLIENT_PAGES),
|
|
93
|
+
value: z.number().finite().nonnegative(),
|
|
94
|
+
revision,
|
|
95
|
+
})
|
|
96
|
+
.strict()
|
|
97
|
+
.refine((report) => report.value <= CLIENT_WEB_VITAL_MAX_VALUE[report.metric]),
|
|
98
|
+
]);
|
|
99
|
+
export type ClientSignalReport = z.infer<typeof ClientSignalReport>;
|
|
100
|
+
export type ClientBeaconReport = ClientErrorReport | ClientSignalReport;
|
|
101
|
+
|
|
49
102
|
const CLIENT_ERRORS_METRIC = {
|
|
50
103
|
name: "opengeni_client_errors_total",
|
|
51
104
|
help: "Web client errors reported by browsers, by closed kind. Admission is bounded per API process, so this is a lower bound.",
|
|
@@ -55,7 +108,58 @@ const CLIENT_ERROR_REJECTIONS_METRIC = {
|
|
|
55
108
|
help: 'Web client error reports the API refused, by closed reason and kind ("unknown" when the body was not read or not valid).',
|
|
56
109
|
} as const;
|
|
57
110
|
|
|
111
|
+
const CLIENT_REQUEST_FAILURES_METRIC = {
|
|
112
|
+
name: "opengeni_client_request_failures_total",
|
|
113
|
+
help: "Key web client requests that failed before any HTTP response, by closed action and reason (network, timeout, offline). Admission is bounded per API process, so this is a lower bound.",
|
|
114
|
+
} as const;
|
|
115
|
+
const CLIENT_STREAM_EVENTS_METRIC = {
|
|
116
|
+
name: "opengeni_client_stream_events_total",
|
|
117
|
+
help: "Web client live-stream health events, by stream (session, workspace) and closed event (reconnect, reconnect_exhausted, long_disconnect). Admission is bounded per API process, so this is a lower bound.",
|
|
118
|
+
} as const;
|
|
119
|
+
const CLIENT_WEB_VITAL_METRIC = {
|
|
120
|
+
name: "opengeni_client_web_vital",
|
|
121
|
+
help: "Web vitals reported by browsers, by metric and closed page label. lcp, inp and ttfb are seconds; cls is the unitless layout-shift score.",
|
|
122
|
+
} as const;
|
|
123
|
+
/**
|
|
124
|
+
* Bucket bounds cover the published good/poor thresholds of every metric:
|
|
125
|
+
* CLS 0.1/0.25, INP 0.2/0.5 s, TTFB 0.8/1.8 s, LCP 2.5/4 s.
|
|
126
|
+
*/
|
|
127
|
+
export const CLIENT_WEB_VITAL_BUCKETS = [
|
|
128
|
+
0.01, 0.025, 0.05, 0.1, 0.2, 0.25, 0.5, 0.8, 1, 1.8, 2.5, 4, 6, 10, 20, 60,
|
|
129
|
+
];
|
|
130
|
+
|
|
58
131
|
export type ClientErrorAdmission = KeyedAdmission<ClientErrorKind>;
|
|
132
|
+
/** Keyed by `<signal>:<closed dimension>`, a finite set of buckets. */
|
|
133
|
+
export type ClientSignalAdmission = KeyedAdmission<string>;
|
|
134
|
+
|
|
135
|
+
/** Same bounds as the error kinds: one bucket per closed signal key. */
|
|
136
|
+
export function createClientSignalAdmission(
|
|
137
|
+
options: { capacity?: number; refillPerSecond?: number; now?: () => number } = {},
|
|
138
|
+
): ClientSignalAdmission {
|
|
139
|
+
return createKeyedAdmission<string>(options);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Web vitals arrive from every page load rather than only on failure, so they
|
|
144
|
+
* get a much larger dedicated bucket per metric (burst 1,200, then 20 a
|
|
145
|
+
* second per process). The browser samples vitals before sending.
|
|
146
|
+
*/
|
|
147
|
+
export function createClientWebVitalAdmission(
|
|
148
|
+
options: { capacity?: number; refillPerSecond?: number; now?: () => number } = {},
|
|
149
|
+
): ClientSignalAdmission {
|
|
150
|
+
return createKeyedAdmission<string>({ capacity: 1_200, refillPerSecond: 20, ...options });
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function signalAdmissionKey(report: ClientSignalReport): string {
|
|
154
|
+
switch (report.signal) {
|
|
155
|
+
case "request_failure":
|
|
156
|
+
return `request_failure:${report.action}`;
|
|
157
|
+
case "stream":
|
|
158
|
+
return `stream:${report.stream}:${report.event}`;
|
|
159
|
+
case "web_vital":
|
|
160
|
+
return `web_vital:${report.metric}`;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
59
163
|
|
|
60
164
|
/**
|
|
61
165
|
* One token bucket per closed kind bounds counter inflation and log volume
|
|
@@ -68,6 +172,12 @@ export function createClientErrorAdmission(
|
|
|
68
172
|
}
|
|
69
173
|
|
|
70
174
|
export function parseClientErrorReport(body: string | null): ClientErrorReport | null {
|
|
175
|
+
const report = parseClientBeaconReport(body);
|
|
176
|
+
return report && !isClientSignalReport(report) ? report : null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Parse any accepted beacon body: an error report or a closed signal report. */
|
|
180
|
+
export function parseClientBeaconReport(body: string | null): ClientBeaconReport | null {
|
|
71
181
|
if (body === null || new TextEncoder().encode(body).byteLength > CLIENT_ERROR_REPORT_MAX_BYTES) {
|
|
72
182
|
return null;
|
|
73
183
|
}
|
|
@@ -77,8 +187,14 @@ export function parseClientErrorReport(body: string | null): ClientErrorReport |
|
|
|
77
187
|
} catch {
|
|
78
188
|
return null;
|
|
79
189
|
}
|
|
80
|
-
const
|
|
81
|
-
|
|
190
|
+
const error = ClientErrorReport.safeParse(value);
|
|
191
|
+
if (error.success) return error.data;
|
|
192
|
+
const signal = ClientSignalReport.safeParse(value);
|
|
193
|
+
return signal.success ? signal.data : null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function isClientSignalReport(report: ClientBeaconReport): report is ClientSignalReport {
|
|
197
|
+
return "signal" in report;
|
|
82
198
|
}
|
|
83
199
|
|
|
84
200
|
/**
|
|
@@ -97,10 +213,14 @@ export function registerClientErrorRoutes(
|
|
|
97
213
|
observability: Observability;
|
|
98
214
|
settings: Pick<Settings, "corsAllowOriginRegex" | "publicBaseUrl" | "webBaseUrl">;
|
|
99
215
|
admission?: ClientErrorAdmission;
|
|
216
|
+
signalAdmission?: ClientSignalAdmission;
|
|
217
|
+
webVitalAdmission?: ClientSignalAdmission;
|
|
100
218
|
},
|
|
101
219
|
): void {
|
|
102
220
|
const { observability, settings } = deps;
|
|
103
221
|
const admission = deps.admission ?? createClientErrorAdmission();
|
|
222
|
+
const signalAdmission = deps.signalAdmission ?? createClientSignalAdmission();
|
|
223
|
+
const webVitalAdmission = deps.webVitalAdmission ?? createClientWebVitalAdmission();
|
|
104
224
|
// Publish the finite series at zero so the first failure after a deploy is
|
|
105
225
|
// an increase from a baseline rather than a series appearing from nothing.
|
|
106
226
|
for (const kind of CLIENT_ERROR_KINDS) {
|
|
@@ -111,6 +231,32 @@ export function registerClientErrorRoutes(
|
|
|
111
231
|
amount: 0,
|
|
112
232
|
});
|
|
113
233
|
}
|
|
234
|
+
for (const action of CLIENT_REQUEST_ACTIONS) {
|
|
235
|
+
for (const reason of CLIENT_REQUEST_FAILURE_REASONS) {
|
|
236
|
+
observability.incrementCounter({
|
|
237
|
+
...CLIENT_REQUEST_FAILURES_METRIC,
|
|
238
|
+
labels: { action, reason },
|
|
239
|
+
amount: 0,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
for (const stream of CLIENT_STREAMS) {
|
|
244
|
+
for (const event of CLIENT_STREAM_EVENTS) {
|
|
245
|
+
observability.incrementCounter({
|
|
246
|
+
...CLIENT_STREAM_EVENTS_METRIC,
|
|
247
|
+
labels: { stream, event },
|
|
248
|
+
amount: 0,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
// A rate-limited signal report is counted under its signal name as `kind`.
|
|
253
|
+
for (const signal of CLIENT_SIGNALS) {
|
|
254
|
+
observability.incrementCounter({
|
|
255
|
+
...CLIENT_ERROR_REJECTIONS_METRIC,
|
|
256
|
+
labels: { reason: "rate_limited", kind: signal },
|
|
257
|
+
amount: 0,
|
|
258
|
+
});
|
|
259
|
+
}
|
|
114
260
|
for (const reason of CLIENT_ERROR_REJECTION_REASONS) {
|
|
115
261
|
if (reason === "rate_limited") continue;
|
|
116
262
|
observability.incrementCounter({
|
|
@@ -125,7 +271,7 @@ export function registerClientErrorRoutes(
|
|
|
125
271
|
c: Context,
|
|
126
272
|
reason: ClientErrorRejectionReason,
|
|
127
273
|
status: 400 | 403 | 413 | 429,
|
|
128
|
-
kind: ClientErrorKind | "unknown" = "unknown",
|
|
274
|
+
kind: ClientErrorKind | ClientSignal | "unknown" = "unknown",
|
|
129
275
|
) => {
|
|
130
276
|
observability.incrementCounter({ ...CLIENT_ERROR_REJECTIONS_METRIC, labels: { reason, kind } });
|
|
131
277
|
c.header("cache-control", "no-store");
|
|
@@ -149,8 +295,16 @@ export function registerClientErrorRoutes(
|
|
|
149
295
|
if (origin !== undefined && !isAllowedBrowserOrigin(origin, settings)) {
|
|
150
296
|
return reject(c, "origin", 403);
|
|
151
297
|
}
|
|
152
|
-
const report =
|
|
298
|
+
const report = parseClientBeaconReport(await c.req.text().catch(() => null));
|
|
153
299
|
if (!report) return reject(c, "invalid", 400);
|
|
300
|
+
if (isClientSignalReport(report)) {
|
|
301
|
+
const bucket = report.signal === "web_vital" ? webVitalAdmission : signalAdmission;
|
|
302
|
+
if (!bucket.admit(signalAdmissionKey(report))) {
|
|
303
|
+
return reject(c, "rate_limited", 429, report.signal);
|
|
304
|
+
}
|
|
305
|
+
recordClientSignal(observability, report);
|
|
306
|
+
return c.body(null, 204);
|
|
307
|
+
}
|
|
154
308
|
if (!admission.admit(report.kind)) return reject(c, "rate_limited", 429, report.kind);
|
|
155
309
|
observability.incrementCounter({ ...CLIENT_ERRORS_METRIC, labels: { kind: report.kind } });
|
|
156
310
|
observability.warn("Web client error reported", {
|
|
@@ -163,3 +317,46 @@ export function registerClientErrorRoutes(
|
|
|
163
317
|
},
|
|
164
318
|
);
|
|
165
319
|
}
|
|
320
|
+
|
|
321
|
+
function recordClientSignal(observability: Observability, report: ClientSignalReport): void {
|
|
322
|
+
switch (report.signal) {
|
|
323
|
+
case "request_failure":
|
|
324
|
+
observability.incrementCounter({
|
|
325
|
+
...CLIENT_REQUEST_FAILURES_METRIC,
|
|
326
|
+
labels: { action: report.action, reason: report.reason },
|
|
327
|
+
});
|
|
328
|
+
observability.warn("Web client request failed before a response", {
|
|
329
|
+
surface: "web",
|
|
330
|
+
op: report.action,
|
|
331
|
+
reason: report.reason,
|
|
332
|
+
clientRoute: report.route,
|
|
333
|
+
clientRevision: report.revision,
|
|
334
|
+
});
|
|
335
|
+
return;
|
|
336
|
+
case "stream":
|
|
337
|
+
observability.incrementCounter({
|
|
338
|
+
...CLIENT_STREAM_EVENTS_METRIC,
|
|
339
|
+
labels: { stream: report.stream, event: report.event },
|
|
340
|
+
});
|
|
341
|
+
// An ordinary reconnect is routine; only a stream that gave up or stayed
|
|
342
|
+
// down is worth a log line.
|
|
343
|
+
if (report.event !== "reconnect") {
|
|
344
|
+
observability.warn("Web client live stream degraded", {
|
|
345
|
+
surface: "web",
|
|
346
|
+
op: report.stream,
|
|
347
|
+
reason: report.event,
|
|
348
|
+
clientRoute: report.route,
|
|
349
|
+
clientRevision: report.revision,
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
return;
|
|
353
|
+
case "web_vital":
|
|
354
|
+
observability.observeHistogram({
|
|
355
|
+
...CLIENT_WEB_VITAL_METRIC,
|
|
356
|
+
labels: { metric: report.metric, page: report.page },
|
|
357
|
+
value: report.value,
|
|
358
|
+
buckets: CLIENT_WEB_VITAL_BUCKETS,
|
|
359
|
+
});
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
}
|