@superblocksteam/sdk 2.0.117 → 2.0.118-next.0
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/.turbo/turbo-build.log +1 -1
- package/dist/cli-replacement/dev.d.mts +6 -0
- package/dist/cli-replacement/dev.d.mts.map +1 -1
- package/dist/cli-replacement/dev.mjs +1 -0
- package/dist/cli-replacement/dev.mjs.map +1 -1
- package/dist/client.d.ts +67 -6
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +94 -0
- package/dist/client.js.map +1 -1
- package/dist/dev-utils/dedupe-async.d.ts +16 -0
- package/dist/dev-utils/dedupe-async.d.ts.map +1 -0
- package/dist/dev-utils/dedupe-async.js +27 -0
- package/dist/dev-utils/dedupe-async.js.map +1 -0
- package/dist/dev-utils/dedupe-async.test.d.ts +2 -0
- package/dist/dev-utils/dedupe-async.test.d.ts.map +1 -0
- package/dist/dev-utils/dedupe-async.test.js +120 -0
- package/dist/dev-utils/dedupe-async.test.js.map +1 -0
- package/dist/dev-utils/dev-server-metrics.d.mts +95 -0
- package/dist/dev-utils/dev-server-metrics.d.mts.map +1 -0
- package/dist/dev-utils/dev-server-metrics.mjs +193 -0
- package/dist/dev-utils/dev-server-metrics.mjs.map +1 -0
- package/dist/dev-utils/dev-server-persist.test.mjs +117 -17
- package/dist/dev-utils/dev-server-persist.test.mjs.map +1 -1
- package/dist/dev-utils/dev-server.d.mts +19 -1
- package/dist/dev-utils/dev-server.d.mts.map +1 -1
- package/dist/dev-utils/dev-server.mjs +296 -28
- package/dist/dev-utils/dev-server.mjs.map +1 -1
- package/dist/flag.d.ts +1 -1
- package/dist/flag.d.ts.map +1 -1
- package/dist/flag.js +3 -3
- package/dist/flag.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/sdk.d.ts +8 -1
- package/dist/sdk.d.ts.map +1 -1
- package/dist/sdk.js +24 -1
- package/dist/sdk.js.map +1 -1
- package/dist/sdk.test.js +102 -1
- package/dist/sdk.test.js.map +1 -1
- package/dist/telemetry/index.d.ts +2 -1
- package/dist/telemetry/index.d.ts.map +1 -1
- package/dist/telemetry/index.js +8 -1
- package/dist/telemetry/index.js.map +1 -1
- package/dist/telemetry/logging.d.ts +1 -2
- package/dist/telemetry/logging.d.ts.map +1 -1
- package/dist/telemetry/logging.js +1 -1
- package/dist/telemetry/logging.js.map +1 -1
- package/dist/telemetry/memory-metrics.d.ts +3 -0
- package/dist/telemetry/memory-metrics.d.ts.map +1 -0
- package/dist/telemetry/memory-metrics.js +59 -0
- package/dist/telemetry/memory-metrics.js.map +1 -0
- package/dist/types/common.d.ts +1 -1
- package/dist/types/common.d.ts.map +1 -1
- package/dist/version-control.d.mts.map +1 -1
- package/dist/version-control.mjs +14 -19
- package/dist/version-control.mjs.map +1 -1
- package/eslint.config.js +6 -0
- package/package.json +8 -8
- package/src/cli-replacement/dev.mts +8 -0
- package/src/client.ts +189 -6
- package/src/dev-utils/dedupe-async.test.ts +151 -0
- package/src/dev-utils/dedupe-async.ts +45 -0
- package/src/dev-utils/dev-server-metrics.mts +252 -0
- package/src/dev-utils/dev-server-persist.test.mts +170 -19
- package/src/dev-utils/dev-server.mts +366 -32
- package/src/flag.ts +4 -4
- package/src/index.ts +19 -1
- package/src/sdk.test.ts +145 -6
- package/src/sdk.ts +36 -0
- package/src/telemetry/index.ts +9 -1
- package/src/telemetry/logging.ts +2 -2
- package/src/telemetry/memory-metrics.ts +90 -0
- package/src/types/common.ts +1 -1
- package/src/version-control.mts +11 -30
- package/test/version-control.test.mts +0 -2
- package/tsconfig.tsbuildinfo +1 -1
- package/turbo.json +1 -0
package/src/client.ts
CHANGED
|
@@ -2796,21 +2796,71 @@ export interface UsageRecordRow {
|
|
|
2796
2796
|
source: string;
|
|
2797
2797
|
}
|
|
2798
2798
|
|
|
2799
|
+
export interface UserCreditLimit {
|
|
2800
|
+
amountLimitCents: number | null;
|
|
2801
|
+
creditLimit: number | null;
|
|
2802
|
+
id: string;
|
|
2803
|
+
orgId: string;
|
|
2804
|
+
updatedAt: string;
|
|
2805
|
+
updatedBy: string | null;
|
|
2806
|
+
userId: string | null;
|
|
2807
|
+
}
|
|
2808
|
+
|
|
2809
|
+
export type OrgCreditLimit = Omit<UserCreditLimit, "userId">;
|
|
2810
|
+
|
|
2811
|
+
export interface BillingUsageLimitsResponse {
|
|
2812
|
+
limits: UserCreditLimit[];
|
|
2813
|
+
orgLimit: OrgCreditLimit | null;
|
|
2814
|
+
}
|
|
2815
|
+
|
|
2816
|
+
type BillingUsageLimitValue =
|
|
2817
|
+
| {
|
|
2818
|
+
amountLimitCents: number;
|
|
2819
|
+
creditLimit?: never;
|
|
2820
|
+
}
|
|
2821
|
+
| {
|
|
2822
|
+
amountLimitCents?: never;
|
|
2823
|
+
creditLimit: number;
|
|
2824
|
+
};
|
|
2825
|
+
|
|
2826
|
+
export type UpdateUserBillingUsageLimitRequest = BillingUsageLimitValue & {
|
|
2827
|
+
userId: string | null;
|
|
2828
|
+
};
|
|
2829
|
+
|
|
2830
|
+
export type UpdateOrgBillingUsageLimitRequest = BillingUsageLimitValue;
|
|
2831
|
+
|
|
2799
2832
|
export interface PlanSummary {
|
|
2800
2833
|
billingInterval: "annual" | "monthly";
|
|
2834
|
+
builderSeatsAssigned?: number;
|
|
2835
|
+
builderSeatsTotal?: number;
|
|
2836
|
+
contractEnd?: string | null;
|
|
2837
|
+
contractStart?: string | null;
|
|
2838
|
+
contractType?: string | null;
|
|
2801
2839
|
currentPlanCredits: number;
|
|
2802
2840
|
currentUsageCredits: number;
|
|
2803
2841
|
cycleStart: string | null;
|
|
2804
2842
|
cycleEnd: string | null;
|
|
2805
2843
|
creditsPerSeat: number | null;
|
|
2806
|
-
pricePerSeatAnnual: number | null;
|
|
2807
|
-
pricePerSeatMonthly: number | null;
|
|
2808
|
-
deployedAppsUsed: number;
|
|
2809
|
-
deployedAppsLimit: number;
|
|
2810
|
-
deployedAppsIncluded: number;
|
|
2811
2844
|
deployedAppsAdditional: number;
|
|
2812
|
-
deployedAppPriceMonthly: number | null;
|
|
2813
2845
|
deployedAppPriceAnnual: number | null;
|
|
2846
|
+
deployedAppPriceMonthly: number | null;
|
|
2847
|
+
deployedAppsIncluded: number;
|
|
2848
|
+
deployedAppsLimit: number;
|
|
2849
|
+
deployedAppsUsed: number;
|
|
2850
|
+
deployedAppCostCents?: number | null;
|
|
2851
|
+
dollarCommitAmountCents?: number | null;
|
|
2852
|
+
dollarCommitUsedCents?: number | null;
|
|
2853
|
+
overageAppsEnabled?: boolean;
|
|
2854
|
+
overageCreditsEnabled?: boolean;
|
|
2855
|
+
overageSeatsEnabled?: boolean;
|
|
2856
|
+
pricePerSeatAnnual: number | null;
|
|
2857
|
+
pricePerSeatMonthly: number | null;
|
|
2858
|
+
seatsUnlimited?: boolean;
|
|
2859
|
+
subscriptionStatus: string | null;
|
|
2860
|
+
topupCreditsPurchased: number;
|
|
2861
|
+
topupCreditsUsed: number;
|
|
2862
|
+
usageResetPeriodLimit: number;
|
|
2863
|
+
usageResetPeriodType: "annual" | "contract_term" | "monthly";
|
|
2814
2864
|
}
|
|
2815
2865
|
|
|
2816
2866
|
export async function fetchBillingUsageDaily({
|
|
@@ -2945,6 +2995,139 @@ export async function fetchBillingPlanSummary({
|
|
|
2945
2995
|
}
|
|
2946
2996
|
}
|
|
2947
2997
|
|
|
2998
|
+
export async function fetchBillingUsageLimits({
|
|
2999
|
+
cliVersion,
|
|
3000
|
+
token,
|
|
3001
|
+
superblocksBaseUrl,
|
|
3002
|
+
}: {
|
|
3003
|
+
cliVersion: string;
|
|
3004
|
+
token: string;
|
|
3005
|
+
superblocksBaseUrl: string;
|
|
3006
|
+
}): Promise<BillingUsageLimitsResponse> {
|
|
3007
|
+
try {
|
|
3008
|
+
const url = new URL(
|
|
3009
|
+
`${BASE_SERVER_API_URL_V1}/billing/user-credit-limits`,
|
|
3010
|
+
superblocksBaseUrl,
|
|
3011
|
+
);
|
|
3012
|
+
|
|
3013
|
+
const config: AxiosRequestConfig = {
|
|
3014
|
+
method: "get",
|
|
3015
|
+
url: url.toString(),
|
|
3016
|
+
headers: {
|
|
3017
|
+
Authorization: "Bearer " + token,
|
|
3018
|
+
[CLI_VERSION_HEADER]: cliVersion,
|
|
3019
|
+
},
|
|
3020
|
+
};
|
|
3021
|
+
const response = await axios(config);
|
|
3022
|
+
return response.data.data as BillingUsageLimitsResponse;
|
|
3023
|
+
} catch (e: any) {
|
|
3024
|
+
let message: string;
|
|
3025
|
+
if (e instanceof AxiosError) {
|
|
3026
|
+
message =
|
|
3027
|
+
(e.response?.data?.responseMeta?.message as string) ??
|
|
3028
|
+
JSON.stringify(e.response?.data) ??
|
|
3029
|
+
e.response?.statusText ??
|
|
3030
|
+
e?.message;
|
|
3031
|
+
} else {
|
|
3032
|
+
message = `${e?.message ? e?.message : e}`;
|
|
3033
|
+
}
|
|
3034
|
+
throw new Error(`Could not fetch billing usage limits: ${message}`);
|
|
3035
|
+
}
|
|
3036
|
+
}
|
|
3037
|
+
|
|
3038
|
+
export async function updateUserBillingUsageLimit({
|
|
3039
|
+
amountLimitCents,
|
|
3040
|
+
cliVersion,
|
|
3041
|
+
creditLimit,
|
|
3042
|
+
token,
|
|
3043
|
+
superblocksBaseUrl,
|
|
3044
|
+
userId,
|
|
3045
|
+
}: UpdateUserBillingUsageLimitRequest & {
|
|
3046
|
+
cliVersion: string;
|
|
3047
|
+
token: string;
|
|
3048
|
+
superblocksBaseUrl: string;
|
|
3049
|
+
}): Promise<{ success: boolean }> {
|
|
3050
|
+
try {
|
|
3051
|
+
const url = new URL(
|
|
3052
|
+
`${BASE_SERVER_API_URL_V1}/billing/user-credit-limits`,
|
|
3053
|
+
superblocksBaseUrl,
|
|
3054
|
+
);
|
|
3055
|
+
|
|
3056
|
+
const config: AxiosRequestConfig = {
|
|
3057
|
+
method: "put",
|
|
3058
|
+
url: url.toString(),
|
|
3059
|
+
headers: {
|
|
3060
|
+
Authorization: "Bearer " + token,
|
|
3061
|
+
[CLI_VERSION_HEADER]: cliVersion,
|
|
3062
|
+
},
|
|
3063
|
+
data: {
|
|
3064
|
+
userId,
|
|
3065
|
+
...(amountLimitCents !== undefined
|
|
3066
|
+
? { amountLimitCents }
|
|
3067
|
+
: { creditLimit }),
|
|
3068
|
+
},
|
|
3069
|
+
};
|
|
3070
|
+
const response = await axios(config);
|
|
3071
|
+
return response.data.data as { success: boolean };
|
|
3072
|
+
} catch (e: any) {
|
|
3073
|
+
let message: string;
|
|
3074
|
+
if (e instanceof AxiosError) {
|
|
3075
|
+
message =
|
|
3076
|
+
(e.response?.data?.responseMeta?.message as string) ??
|
|
3077
|
+
JSON.stringify(e.response?.data) ??
|
|
3078
|
+
e.response?.statusText ??
|
|
3079
|
+
e?.message;
|
|
3080
|
+
} else {
|
|
3081
|
+
message = `${e?.message ? e?.message : e}`;
|
|
3082
|
+
}
|
|
3083
|
+
throw new Error(`Could not update user billing usage limit: ${message}`);
|
|
3084
|
+
}
|
|
3085
|
+
}
|
|
3086
|
+
|
|
3087
|
+
export async function updateOrgBillingUsageLimit({
|
|
3088
|
+
amountLimitCents,
|
|
3089
|
+
cliVersion,
|
|
3090
|
+
creditLimit,
|
|
3091
|
+
token,
|
|
3092
|
+
superblocksBaseUrl,
|
|
3093
|
+
}: UpdateOrgBillingUsageLimitRequest & {
|
|
3094
|
+
cliVersion: string;
|
|
3095
|
+
token: string;
|
|
3096
|
+
superblocksBaseUrl: string;
|
|
3097
|
+
}): Promise<{ success: boolean }> {
|
|
3098
|
+
try {
|
|
3099
|
+
const url = new URL(
|
|
3100
|
+
`${BASE_SERVER_API_URL_V1}/billing/user-credit-limits/org`,
|
|
3101
|
+
superblocksBaseUrl,
|
|
3102
|
+
);
|
|
3103
|
+
|
|
3104
|
+
const config: AxiosRequestConfig = {
|
|
3105
|
+
method: "put",
|
|
3106
|
+
url: url.toString(),
|
|
3107
|
+
headers: {
|
|
3108
|
+
Authorization: "Bearer " + token,
|
|
3109
|
+
[CLI_VERSION_HEADER]: cliVersion,
|
|
3110
|
+
},
|
|
3111
|
+
data:
|
|
3112
|
+
amountLimitCents !== undefined ? { amountLimitCents } : { creditLimit },
|
|
3113
|
+
};
|
|
3114
|
+
const response = await axios(config);
|
|
3115
|
+
return response.data.data as { success: boolean };
|
|
3116
|
+
} catch (e: any) {
|
|
3117
|
+
let message: string;
|
|
3118
|
+
if (e instanceof AxiosError) {
|
|
3119
|
+
message =
|
|
3120
|
+
(e.response?.data?.responseMeta?.message as string) ??
|
|
3121
|
+
JSON.stringify(e.response?.data) ??
|
|
3122
|
+
e.response?.statusText ??
|
|
3123
|
+
e?.message;
|
|
3124
|
+
} else {
|
|
3125
|
+
message = `${e?.message ? e?.message : e}`;
|
|
3126
|
+
}
|
|
3127
|
+
throw new Error(`Could not update org billing usage limit: ${message}`);
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
|
|
2948
3131
|
// ---------------------------------------------------------------------------
|
|
2949
3132
|
// Knowledge (Facts)
|
|
2950
3133
|
// ---------------------------------------------------------------------------
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// Regression tests for the in-flight dedupe used by the dev-server graceful
|
|
2
|
+
// shutdown path (hq-o55a). The bug being guarded against: multiple signals
|
|
3
|
+
// (SIGINT, SIGTERM, SIGABRT, uncaughtException) fire in rapid succession during
|
|
4
|
+
// shutdown and each handler re-runs cleanup against already-freed native state,
|
|
5
|
+
// surfacing as `double free or corruption (fasttop)` from glibc.
|
|
6
|
+
|
|
7
|
+
import { describe, expect, it, vi } from "vitest";
|
|
8
|
+
|
|
9
|
+
import { dedupeAsync } from "./dedupe-async.js";
|
|
10
|
+
|
|
11
|
+
describe("dedupeAsync", () => {
|
|
12
|
+
it("invokes the wrapped function exactly once across concurrent calls", async () => {
|
|
13
|
+
const inner = vi.fn(async () => "ok");
|
|
14
|
+
const wrapped = dedupeAsync(inner);
|
|
15
|
+
|
|
16
|
+
const results = await Promise.all([
|
|
17
|
+
wrapped(),
|
|
18
|
+
wrapped(),
|
|
19
|
+
wrapped(),
|
|
20
|
+
wrapped(),
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
expect(inner).toHaveBeenCalledTimes(1);
|
|
24
|
+
expect(results).toEqual(["ok", "ok", "ok", "ok"]);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it("returns the same promise instance to all concurrent callers", () => {
|
|
28
|
+
const inner = vi.fn(async () => 42);
|
|
29
|
+
const wrapped = dedupeAsync(inner);
|
|
30
|
+
|
|
31
|
+
const p1 = wrapped();
|
|
32
|
+
const p2 = wrapped();
|
|
33
|
+
|
|
34
|
+
expect(p1).toBe(p2);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("invokes onDuplicate for each call after the first", async () => {
|
|
38
|
+
let resolveInner: (v: string) => void = () => {};
|
|
39
|
+
const inner = vi.fn(
|
|
40
|
+
() =>
|
|
41
|
+
new Promise<string>((resolve) => {
|
|
42
|
+
resolveInner = resolve;
|
|
43
|
+
}),
|
|
44
|
+
);
|
|
45
|
+
const onDuplicate = vi.fn();
|
|
46
|
+
const wrapped = dedupeAsync(inner, { onDuplicate });
|
|
47
|
+
|
|
48
|
+
const p1 = wrapped();
|
|
49
|
+
wrapped();
|
|
50
|
+
wrapped();
|
|
51
|
+
wrapped();
|
|
52
|
+
|
|
53
|
+
expect(onDuplicate).toHaveBeenCalledTimes(3);
|
|
54
|
+
expect(inner).toHaveBeenCalledTimes(1);
|
|
55
|
+
|
|
56
|
+
resolveInner("done");
|
|
57
|
+
await expect(p1).resolves.toBe("done");
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("retains the cached promise after the inner call settles — post-settle callers get the same outcome", async () => {
|
|
61
|
+
const inner = vi.fn(async () => "shutdown-complete");
|
|
62
|
+
const wrapped = dedupeAsync(inner);
|
|
63
|
+
|
|
64
|
+
await expect(wrapped()).resolves.toBe("shutdown-complete");
|
|
65
|
+
// Second invocation AFTER the first settled — must NOT re-trigger.
|
|
66
|
+
await expect(wrapped()).resolves.toBe("shutdown-complete");
|
|
67
|
+
expect(inner).toHaveBeenCalledTimes(1);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("propagates rejection to all callers without re-running the inner function", async () => {
|
|
71
|
+
const inner = vi.fn(async () => {
|
|
72
|
+
throw new Error("boom");
|
|
73
|
+
});
|
|
74
|
+
const wrapped = dedupeAsync(inner);
|
|
75
|
+
|
|
76
|
+
const p1 = wrapped();
|
|
77
|
+
const p2 = wrapped();
|
|
78
|
+
const p3 = wrapped();
|
|
79
|
+
|
|
80
|
+
await expect(p1).rejects.toThrow(/boom/);
|
|
81
|
+
await expect(p2).rejects.toThrow(/boom/);
|
|
82
|
+
await expect(p3).rejects.toThrow(/boom/);
|
|
83
|
+
expect(inner).toHaveBeenCalledTimes(1);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("retains the cached rejection after the inner call settles — post-settle callers get the same rejection without re-run", async () => {
|
|
87
|
+
// Guards against a future change that resets `inFlight = null` on
|
|
88
|
+
// rejection (a plausible "retry on failure" tweak). The shutdown
|
|
89
|
+
// contract is that BOTH outcomes are sticky — resolve and reject —
|
|
90
|
+
// because re-entering cleanup after a failed first attempt is what
|
|
91
|
+
// caused the original double-free. A passing test for the resolve path
|
|
92
|
+
// alone would let that regression slip through.
|
|
93
|
+
const inner = vi.fn(async () => {
|
|
94
|
+
throw new Error("boom");
|
|
95
|
+
});
|
|
96
|
+
const wrapped = dedupeAsync(inner);
|
|
97
|
+
|
|
98
|
+
await expect(wrapped()).rejects.toThrow(/boom/);
|
|
99
|
+
// Second invocation AFTER the first rejection settled — must NOT
|
|
100
|
+
// re-trigger and must surface the same rejection.
|
|
101
|
+
await expect(wrapped()).rejects.toThrow(/boom/);
|
|
102
|
+
expect(inner).toHaveBeenCalledTimes(1);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it("forwards args to the inner function on the first call only", async () => {
|
|
106
|
+
const inner = vi.fn(async (a: number, b: string) => `${a}-${b}`);
|
|
107
|
+
const wrapped = dedupeAsync(inner);
|
|
108
|
+
|
|
109
|
+
const p1 = wrapped(1, "first");
|
|
110
|
+
// Second call passes different args, but is short-circuited — inner
|
|
111
|
+
// should NOT be invoked again. The dedupe is intentionally
|
|
112
|
+
// input-agnostic: shutdown semantics don't depend on the second
|
|
113
|
+
// signal's arguments.
|
|
114
|
+
const p2 = wrapped(2, "second");
|
|
115
|
+
|
|
116
|
+
await expect(p1).resolves.toBe("1-first");
|
|
117
|
+
await expect(p2).resolves.toBe("1-first");
|
|
118
|
+
expect(inner).toHaveBeenCalledTimes(1);
|
|
119
|
+
expect(inner).toHaveBeenCalledWith(1, "first");
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("passes the duplicate caller's args to onDuplicate (for source-tagged logging)", async () => {
|
|
123
|
+
// The dev-server graceful shutdown threads a `source` field through
|
|
124
|
+
// (signal name, "uncaughtException", "/_sb_disconnect") so the
|
|
125
|
+
// duplicate-suppression log can tell apart "4 OS signals fired" from
|
|
126
|
+
// "1 signal fired and cleanup panicked 3 times". The dedupe must
|
|
127
|
+
// forward each duplicate's own args, not the first caller's.
|
|
128
|
+
let resolveInner: () => void = () => {};
|
|
129
|
+
const inner = vi.fn(
|
|
130
|
+
(arg: { source: string }): Promise<{ source: string }> =>
|
|
131
|
+
new Promise((resolve) => {
|
|
132
|
+
resolveInner = () => resolve(arg);
|
|
133
|
+
}),
|
|
134
|
+
);
|
|
135
|
+
const onDuplicate = vi.fn();
|
|
136
|
+
const wrapped = dedupeAsync(inner, { onDuplicate });
|
|
137
|
+
|
|
138
|
+
const p1 = wrapped({ source: "SIGTERM" });
|
|
139
|
+
wrapped({ source: "SIGINT" });
|
|
140
|
+
wrapped({ source: "SIGABRT" });
|
|
141
|
+
|
|
142
|
+
expect(onDuplicate).toHaveBeenCalledTimes(2);
|
|
143
|
+
expect(onDuplicate).toHaveBeenNthCalledWith(1, { source: "SIGINT" });
|
|
144
|
+
expect(onDuplicate).toHaveBeenNthCalledWith(2, { source: "SIGABRT" });
|
|
145
|
+
expect(inner).toHaveBeenCalledTimes(1);
|
|
146
|
+
expect(inner).toHaveBeenCalledWith({ source: "SIGTERM" });
|
|
147
|
+
|
|
148
|
+
resolveInner();
|
|
149
|
+
await p1;
|
|
150
|
+
});
|
|
151
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// In-flight call deduper. Wraps an async function so that concurrent invocations
|
|
2
|
+
// share the same promise — subsequent callers get the original in-flight result
|
|
3
|
+
// instead of triggering another execution.
|
|
4
|
+
//
|
|
5
|
+
// After the wrapped function settles (resolves OR rejects) the cached promise is
|
|
6
|
+
// retained so all post-settle callers receive the same outcome. There is no
|
|
7
|
+
// reset path: callers that want to "run again later" should use a fresh
|
|
8
|
+
// `dedupeAsync` instance.
|
|
9
|
+
//
|
|
10
|
+
// Used by the dev-server graceful shutdown path (hq-o55a). Multiple signals
|
|
11
|
+
// (SIGINT, SIGTERM, SIGABRT, uncaughtException) can fire in rapid succession
|
|
12
|
+
// during shutdown. Without a dedupe, every handler re-runs lockService /
|
|
13
|
+
// vite / httpServer cleanup against already-freed native state, which surfaces
|
|
14
|
+
// as `double free or corruption (fasttop)` from glibc and SIGABRT killing the
|
|
15
|
+
// process before it can exit cleanly.
|
|
16
|
+
|
|
17
|
+
export interface DedupeAsyncOptions<TArgs extends unknown[]> {
|
|
18
|
+
/**
|
|
19
|
+
* Optional callback invoked when a duplicate call is detected. The first
|
|
20
|
+
* caller's invocation runs normally; this fires for the 2nd, 3rd, …
|
|
21
|
+
* Useful for logging "shutdown already in progress; ignoring duplicate
|
|
22
|
+
* signal".
|
|
23
|
+
*
|
|
24
|
+
* Receives the *duplicate* call's args (not the first call's). The first
|
|
25
|
+
* call's args are what the wrapped function actually ran with — duplicates
|
|
26
|
+
* are intentionally short-circuited and their args are dropped from
|
|
27
|
+
* execution but surfaced here for logging.
|
|
28
|
+
*/
|
|
29
|
+
onDuplicate?: (...args: TArgs) => void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function dedupeAsync<TArgs extends unknown[], TResult>(
|
|
33
|
+
fn: (...args: TArgs) => Promise<TResult>,
|
|
34
|
+
options: DedupeAsyncOptions<TArgs> = {},
|
|
35
|
+
): (...args: TArgs) => Promise<TResult> {
|
|
36
|
+
let inFlight: Promise<TResult> | null = null;
|
|
37
|
+
return (...args: TArgs) => {
|
|
38
|
+
if (inFlight) {
|
|
39
|
+
options.onDuplicate?.(...args);
|
|
40
|
+
return inFlight;
|
|
41
|
+
}
|
|
42
|
+
inFlight = fn(...args);
|
|
43
|
+
return inFlight;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dev-server connection-phase metrics.
|
|
3
|
+
*
|
|
4
|
+
* Records counters and histograms for the dev-server endpoints that the editor
|
|
5
|
+
* and SABS hit during a live-edit connection: `/_sb_health`, `/_sb_connect`,
|
|
6
|
+
* `/_sb_activate`, `/_sb_disconnect`, `/_sb_status`, `/_sb_activity`, plus
|
|
7
|
+
* WebSocket upgrades, Vite eager-init, and warm-standby activation.
|
|
8
|
+
*
|
|
9
|
+
* Metrics are scoped to the dev-server's existing OTel pipeline. When telemetry
|
|
10
|
+
* has not yet initialized (warm-standby pre-activation), record calls are
|
|
11
|
+
* buffered and replayed by `flush()` once `configureTelemetry` completes, so
|
|
12
|
+
* warm-standby observations are not silently dropped into the no-op meter.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { isTelemetryInitialized } from "@superblocksteam/telemetry";
|
|
16
|
+
|
|
17
|
+
import { getMeter } from "../telemetry/index.js";
|
|
18
|
+
|
|
19
|
+
/** Dev-server endpoints that produce per-request metrics. */
|
|
20
|
+
export type DevServerEndpoint =
|
|
21
|
+
| "_sb_health"
|
|
22
|
+
| "_sb_connect"
|
|
23
|
+
| "_sb_activate"
|
|
24
|
+
| "_sb_disconnect"
|
|
25
|
+
| "_sb_status"
|
|
26
|
+
| "_sb_activity"
|
|
27
|
+
| "_sb_persist"
|
|
28
|
+
| "_sb_ready";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Allowlisted HTTP methods recorded as the `method` metric label. Anything
|
|
32
|
+
* outside this set — `req.method` is client-controlled, and `/_sb_health` is
|
|
33
|
+
* unauthenticated — is bucketed as `'OTHER'` to keep label cardinality bounded.
|
|
34
|
+
*/
|
|
35
|
+
const ALLOWED_METHODS: ReadonlySet<string> = new Set([
|
|
36
|
+
"GET",
|
|
37
|
+
"HEAD",
|
|
38
|
+
"POST",
|
|
39
|
+
"PUT",
|
|
40
|
+
"PATCH",
|
|
41
|
+
"DELETE",
|
|
42
|
+
"OPTIONS",
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
function sanitizeMethod(method: string): string {
|
|
46
|
+
const upper = method.toUpperCase();
|
|
47
|
+
return ALLOWED_METHODS.has(upper) ? upper : "OTHER";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Coarse failure type for dev-server endpoint outcomes. Distinct from raw HTTP
|
|
52
|
+
* status so dashboards can filter by reason without high-cardinality labels.
|
|
53
|
+
*/
|
|
54
|
+
export type DevServerFailureType =
|
|
55
|
+
| "none"
|
|
56
|
+
| "auth"
|
|
57
|
+
| "validation"
|
|
58
|
+
| "branch_mismatch"
|
|
59
|
+
| "vite_init"
|
|
60
|
+
| "internal";
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Outcome of the warm-standby activation handshake.
|
|
64
|
+
*
|
|
65
|
+
* accepted - 200 OK, transitioning to full server
|
|
66
|
+
* rejected - 400/413 (validation, body too large)
|
|
67
|
+
* error - JSON parse / unexpected exception
|
|
68
|
+
*/
|
|
69
|
+
export type WarmActivationOutcome = "accepted" | "rejected" | "error";
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Soft cap on buffered pre-init events. Warm-standby reasonably emits ~1
|
|
73
|
+
* `recordWarmPrewarm` + ~1 `recordWarmActivation` before activation, so the
|
|
74
|
+
* cap is generously above the expected load — it exists only to bound memory
|
|
75
|
+
* if `flush()` is somehow never called.
|
|
76
|
+
*/
|
|
77
|
+
const MAX_BUFFERED_EVENTS = 256;
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Records dev-server connection-phase metrics.
|
|
81
|
+
*
|
|
82
|
+
* Calls made before `configureTelemetry` completes are queued and replayed by
|
|
83
|
+
* `flush()` once telemetry is online. Without this, warm-standby observations
|
|
84
|
+
* are routed through `getMeter()`'s no-op fallback meter and silently dropped
|
|
85
|
+
* — defeating the metric's purpose, since warm activation is exactly the path
|
|
86
|
+
* we want to observe. The buffer is bounded to bound memory; instruments are
|
|
87
|
+
* still NOT cached, so each replayed call resolves a fresh meter.
|
|
88
|
+
*/
|
|
89
|
+
class DevServerMetrics {
|
|
90
|
+
/**
|
|
91
|
+
* Pre-init replay queue. Entries are bound `() => void` recorders that close
|
|
92
|
+
* over their args at call time, so labels are captured even if the buffer is
|
|
93
|
+
* drained much later.
|
|
94
|
+
*/
|
|
95
|
+
private bufferedRecorders: Array<() => void> = [];
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Routes a recorder to the live OTel meter when telemetry is up, or buffers
|
|
99
|
+
* it for replay when telemetry has not yet initialized.
|
|
100
|
+
*/
|
|
101
|
+
private record(recorder: () => void): void {
|
|
102
|
+
if (isTelemetryInitialized()) {
|
|
103
|
+
recorder();
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (this.bufferedRecorders.length >= MAX_BUFFERED_EVENTS) {
|
|
107
|
+
// Drop the oldest event rather than the new one — the most recent
|
|
108
|
+
// observations are typically the most informative for an investigator.
|
|
109
|
+
this.bufferedRecorders.shift();
|
|
110
|
+
}
|
|
111
|
+
this.bufferedRecorders.push(recorder);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Replays buffered recorders against the (now-initialized) meter and clears
|
|
116
|
+
* the queue. Idempotent — safe to call multiple times. Callers should invoke
|
|
117
|
+
* this immediately after `configureTelemetry()` resolves.
|
|
118
|
+
*
|
|
119
|
+
* No-ops if telemetry did not actually come up (e.g., `configureTelemetry`
|
|
120
|
+
* returned `false` due to a missing config or an internal init failure).
|
|
121
|
+
* Draining the buffer through a still-no-op meter would silently lose every
|
|
122
|
+
* observation AND clear the queue, so a later successful re-init via
|
|
123
|
+
* `onTokenReceived` could not recover them. Keeping the buffer intact lets
|
|
124
|
+
* a subsequent `flush()` call replay them once telemetry is genuinely live.
|
|
125
|
+
*/
|
|
126
|
+
flush(): void {
|
|
127
|
+
if (!isTelemetryInitialized()) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (this.bufferedRecorders.length === 0) {
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const events = this.bufferedRecorders;
|
|
134
|
+
this.bufferedRecorders = [];
|
|
135
|
+
for (const e of events) {
|
|
136
|
+
e();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Records the outcome of a dev-server HTTP endpoint request.
|
|
142
|
+
*/
|
|
143
|
+
recordEndpoint(
|
|
144
|
+
endpoint: DevServerEndpoint,
|
|
145
|
+
method: string,
|
|
146
|
+
status: number,
|
|
147
|
+
durationMs: number,
|
|
148
|
+
failureType: DevServerFailureType = "none",
|
|
149
|
+
): void {
|
|
150
|
+
const labels = {
|
|
151
|
+
endpoint,
|
|
152
|
+
method: sanitizeMethod(method),
|
|
153
|
+
status: String(status),
|
|
154
|
+
failure_type: failureType,
|
|
155
|
+
};
|
|
156
|
+
this.record(() => {
|
|
157
|
+
const meter = getMeter();
|
|
158
|
+
meter
|
|
159
|
+
.createCounter("dev_server_endpoint_requests_total", {
|
|
160
|
+
description:
|
|
161
|
+
"Count of dev-server endpoint requests by endpoint, status, and failure type.",
|
|
162
|
+
})
|
|
163
|
+
.add(1, labels);
|
|
164
|
+
meter
|
|
165
|
+
.createHistogram("dev_server_endpoint_duration_ms", {
|
|
166
|
+
description:
|
|
167
|
+
"Latency of dev-server endpoint requests in milliseconds.",
|
|
168
|
+
unit: "ms",
|
|
169
|
+
})
|
|
170
|
+
.record(durationMs, labels);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Records a WebSocket upgrade attempt against the dev-server's HTTP socket.
|
|
176
|
+
*/
|
|
177
|
+
recordSocketUpgrade(outcome: "accepted" | "rejected"): void {
|
|
178
|
+
this.record(() => {
|
|
179
|
+
getMeter()
|
|
180
|
+
.createCounter("dev_server_socket_upgrade_total", {
|
|
181
|
+
description:
|
|
182
|
+
"Count of WebSocket upgrade attempts against the dev-server HTTP socket.",
|
|
183
|
+
})
|
|
184
|
+
.add(1, { outcome });
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Records the duration and outcome of Vite eager-init (the call that creates
|
|
190
|
+
* the user-facing Vite server during /_sb_connect ramp-up).
|
|
191
|
+
*/
|
|
192
|
+
recordViteEagerInit(durationMs: number, outcome: "success" | "error"): void {
|
|
193
|
+
this.record(() => {
|
|
194
|
+
getMeter()
|
|
195
|
+
.createHistogram("dev_server_vite_eager_init_duration_ms", {
|
|
196
|
+
description:
|
|
197
|
+
"Duration of eager Vite server initialization in milliseconds.",
|
|
198
|
+
unit: "ms",
|
|
199
|
+
})
|
|
200
|
+
.record(durationMs, { outcome });
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Records the duration and outcome of warm-pod Vite dep-cache pre-warm.
|
|
206
|
+
*/
|
|
207
|
+
recordWarmPrewarm(durationMs: number, outcome: "success" | "error"): void {
|
|
208
|
+
this.record(() => {
|
|
209
|
+
getMeter()
|
|
210
|
+
.createHistogram("dev_server_warm_prewarm_duration_ms", {
|
|
211
|
+
description:
|
|
212
|
+
"Duration of warm-standby Vite dep-cache pre-warm in milliseconds.",
|
|
213
|
+
unit: "ms",
|
|
214
|
+
})
|
|
215
|
+
.record(durationMs, { outcome });
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Records a warm-standby activation request outcome.
|
|
221
|
+
*/
|
|
222
|
+
recordWarmActivation(outcome: WarmActivationOutcome): void {
|
|
223
|
+
this.record(() => {
|
|
224
|
+
getMeter()
|
|
225
|
+
.createCounter("dev_server_warm_activation_total", {
|
|
226
|
+
description:
|
|
227
|
+
"Count of warm-standby /_sb_activate requests by outcome.",
|
|
228
|
+
})
|
|
229
|
+
.add(1, { outcome });
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Records the time from receiving a successful /_sb_activate POST to the
|
|
235
|
+
* full Express dev-server being attached to the warm HTTP server (the
|
|
236
|
+
* "no-port-gap" handoff window — gateways see 502s if this stretches).
|
|
237
|
+
*/
|
|
238
|
+
recordWarmHandoff(durationMs: number): void {
|
|
239
|
+
this.record(() => {
|
|
240
|
+
getMeter()
|
|
241
|
+
.createHistogram("dev_server_warm_activation_handoff_duration_ms", {
|
|
242
|
+
description:
|
|
243
|
+
"Time from /_sb_activate acceptance to full dev server attached, in milliseconds.",
|
|
244
|
+
unit: "ms",
|
|
245
|
+
})
|
|
246
|
+
.record(durationMs);
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Process-wide dev-server metrics singleton. */
|
|
252
|
+
export const devServerMetrics = new DevServerMetrics();
|