-
Notifications
You must be signed in to change notification settings - Fork 307
Expand file tree
/
Copy pathservicePing.ts
More file actions
205 lines (183 loc) · 6.61 KB
/
Copy pathservicePing.ts
File metadata and controls
205 lines (183 loc) · 6.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import { existsSync } from "fs";
import { SINGLE_TENANT_ORG_ID } from "@/lib/constants";
import { isServiceError } from "@/lib/utils";
import { __unsafePrisma } from "@/prisma";
import {
createLogger,
decryptActivationCode,
env,
SOURCEBOT_VERSION,
isValidOfflineLicenseActive
} from "@sourcebot/shared";
import { client } from "./client";
import { ServicePingRequest } from "./types";
import { ServiceErrorException } from "@/lib/serviceError";
import { getConfiguredLanguageModels } from "@/features/chat/utils.server";
const logger = createLogger('service-ping');
const SERVICE_PING_INTERVAL_MS = 24 * 60 * 60 * 1000; // 1 day
export const syncWithLighthouse = async (orgId: number) => {
// Look up the activation code from the License record
const license = await __unsafePrisma.license.findUnique({
where: { orgId },
});
const now = Date.now();
const DAY_MS = 24 * 60 * 60 * 1000;
const dauCutoff = new Date(now - 1 * DAY_MS);
const wauCutoff = new Date(now - 7 * DAY_MS);
const mauCutoff = new Date(now - 30 * DAY_MS);
const [
userCount,
repoCount,
dauCount,
wauCount,
mauCount,
] = await Promise.all([
__unsafePrisma.userToOrg.count({
where: {
orgId,
},
}),
__unsafePrisma.repo.count({
where: {
orgId,
},
}),
__unsafePrisma.user.count({
where: {
orgs: { some: { orgId } },
lastActiveAt: { gte: dauCutoff },
},
}),
__unsafePrisma.user.count({
where: {
orgs: { some: { orgId } },
lastActiveAt: { gte: wauCutoff },
},
}),
__unsafePrisma.user.count({
where: {
orgs: { some: { orgId } },
lastActiveAt: { gte: mauCutoff },
},
}),
]);
const activationCode = license?.activationCode
? decryptActivationCode(license.activationCode)
: undefined;
const isLanguageModelConfigured = (await getConfiguredLanguageModels()).length > 0;
const payload: ServicePingRequest = {
installId: env.SOURCEBOT_INSTALL_ID,
version: SOURCEBOT_VERSION,
hostname: env.AUTH_URL,
userCount,
repoCount,
dauCount,
wauCount,
mauCount,
deploymentType: inferDeploymentType(),
isTelemetryEnabled: env.SOURCEBOT_TELEMETRY_DISABLED === 'false',
isLanguageModelConfigured,
...(activationCode && { activationCode }),
};
await recordServicePingInDB(orgId, payload);
if (isValidOfflineLicenseActive()) {
logger.debug('Skipping service ping: active offline license detected.');
return;
}
const response = await client.ping(payload);
if (isServiceError(response)) {
logger.error(`Service ping failed:\n ${JSON.stringify(response, null, 2)}`)
if (license) {
await __unsafePrisma.license.update({
where: { orgId },
data: { lastSyncErrorCode: response.errorCode },
});
}
throw new ServiceErrorException(response);
}
logger.info(`Service ping sent successfully`);
// If we have a license and Lighthouse returned license data, sync it
if (license && response.license) {
const {
entitlements,
seats,
status,
planName,
unitAmount,
currency,
interval,
intervalCount,
nextRenewalAt,
nextRenewalAmount,
cancelAt,
trialEnd,
hasPaymentMethod,
yearlyTermStatus,
} = response.license;
await __unsafePrisma.license.update({
where: {
orgId
},
data: {
entitlements,
seats,
status,
planName,
unitAmount,
currency,
interval,
intervalCount,
nextRenewalAt: nextRenewalAt ? new Date(nextRenewalAt) : null,
nextRenewalAmount,
cancelAt: cancelAt ? new Date(cancelAt) : null,
trialEnd: trialEnd ? new Date(trialEnd) : null,
hasPaymentMethod,
yearlyTermStartedAt: yearlyTermStatus ? new Date(yearlyTermStatus.termStartedAt) : null,
yearlyTermEndsAt: yearlyTermStatus ? new Date(yearlyTermStatus.termEndsAt) : null,
yearlyTotalQuartersInTerm: yearlyTermStatus?.totalQuartersInTerm ?? null,
yearlyCurrentQuarterNumber: yearlyTermStatus?.currentQuarterNumber ?? null,
yearlyCurrentQuarterStartedAt: yearlyTermStatus ? new Date(yearlyTermStatus.currentQuarterStartedAt) : null,
yearlyCurrentQuarterEndsAt: yearlyTermStatus ? new Date(yearlyTermStatus.currentQuarterEndsAt) : null,
yearlyCommittedSeats: yearlyTermStatus?.committedSeats ?? null,
yearlyOverageSeats: yearlyTermStatus?.overageSeats ?? null,
yearlyBillableOverageSeats: yearlyTermStatus?.billableOverageSeats ?? null,
yearlyPeakSeats: yearlyTermStatus?.peakSeats ?? null,
lastSyncAt: new Date(),
lastSyncErrorCode: null,
},
});
logger.info(`License synced: entitlements=${entitlements.join(',')}, seats=${seats}, status=${status}`);
}
};
export const startServicePingCronJob = () => {
syncWithLighthouse(SINGLE_TENANT_ORG_ID).catch(() => { /* ignore error */ })
setInterval(
() => syncWithLighthouse(SINGLE_TENANT_ORG_ID).catch(() => { /* ignore error */ }),
SERVICE_PING_INTERVAL_MS
);
};
const inferDeploymentType = (): string => {
if (process.env.KUBERNETES_SERVICE_HOST) {
return 'kubernetes';
}
if (existsSync('/.dockerenv')) {
return 'docker';
}
return 'other';
};
const recordServicePingInDB = async (orgId: number, payload: ServicePingRequest) => {
// Strip the activation code before persisting.
const { activationCode: _activationCode, ...sanitizedPayload } = payload;
try {
await __unsafePrisma.servicePingEvent.create({
data: {
orgId,
payload: sanitizedPayload,
},
});
} catch (error) {
// Recording the ping is best-effort: a failure here must not prevent
// the actual ping from being sent to Lighthouse.
logger.error(`Failed to record service ping in database:\n ${error}`);
}
};