forked from sourcebot-dev/sourcebot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinitialize.ts
More file actions
296 lines (270 loc) · 11.5 KB
/
initialize.ts
File metadata and controls
296 lines (270 loc) · 11.5 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import { ConnectionSyncStatus, OrgRole, Prisma, RepoIndexingStatus } from '@sourcebot/db';
import { env } from './env.mjs';
import { prisma } from "@/prisma";
import { SINGLE_TENANT_ORG_ID, SINGLE_TENANT_ORG_DOMAIN, SOURCEBOT_GUEST_USER_ID, SINGLE_TENANT_ORG_NAME } from './lib/constants';
import chokidar from 'chokidar';
import { ConnectionConfig } from '@sourcebot/schemas/v3/connection.type';
import { hasEntitlement, loadConfig, isRemotePath, syncSearchContexts } from '@sourcebot/shared';
import { isServiceError, getOrgMetadata } from './lib/utils';
import { ServiceErrorException } from './lib/serviceError';
import { SOURCEBOT_SUPPORT_EMAIL } from "@/lib/constants";
import { createLogger } from "@sourcebot/logger";
import { createGuestUser } from '@/lib/authUtils';
import { getOrgFromDomain } from './data/org';
const logger = createLogger('web-initialize');
const syncConnections = async (connections?: { [key: string]: ConnectionConfig }) => {
if (connections) {
for (const [key, newConnectionConfig] of Object.entries(connections)) {
const currentConnection = await prisma.connection.findUnique({
where: {
name_orgId: {
name: key,
orgId: SINGLE_TENANT_ORG_ID,
}
},
include: {
repos: {
include: {
repo: true,
}
}
}
});
const currentConnectionConfig = currentConnection ? currentConnection.config as unknown as ConnectionConfig : undefined;
const syncNeededOnUpdate =
(currentConnectionConfig && JSON.stringify(currentConnectionConfig) !== JSON.stringify(newConnectionConfig)) ||
(currentConnection?.syncStatus === ConnectionSyncStatus.FAILED);
const connectionDb = await prisma.connection.upsert({
where: {
name_orgId: {
name: key,
orgId: SINGLE_TENANT_ORG_ID,
}
},
update: {
config: newConnectionConfig as unknown as Prisma.InputJsonValue,
syncStatus: syncNeededOnUpdate ? ConnectionSyncStatus.SYNC_NEEDED : undefined,
isDeclarative: true,
},
create: {
name: key,
connectionType: newConnectionConfig.type,
config: newConnectionConfig as unknown as Prisma.InputJsonValue,
isDeclarative: true,
org: {
connect: {
id: SINGLE_TENANT_ORG_ID,
}
}
}
});
logger.info(`Upserted connection with name '${key}'. Connection ID: ${connectionDb.id}`);
// Re-try any repos that failed to index.
const failedRepos = currentConnection?.repos.filter(repo => repo.repo.repoIndexingStatus === RepoIndexingStatus.FAILED).map(repo => repo.repo.id) ?? [];
if (failedRepos.length > 0) {
await prisma.repo.updateMany({
where: {
id: {
in: failedRepos,
}
},
data: {
repoIndexingStatus: RepoIndexingStatus.NEW,
}
})
}
}
}
// Delete any connections that are no longer in the config.
const deletedConnections = await prisma.connection.findMany({
where: {
isDeclarative: true,
name: {
notIn: Object.keys(connections ?? {}),
},
orgId: SINGLE_TENANT_ORG_ID,
}
});
for (const connection of deletedConnections) {
logger.info(`Deleting connection with name '${connection.name}'. Connection ID: ${connection.id}`);
await prisma.connection.delete({
where: {
id: connection.id,
}
})
}
}
const syncDeclarativeConfig = async (configPath: string) => {
const config = await loadConfig(configPath);
const forceEnableAnonymousAccess = config.settings?.enablePublicAccess ?? env.FORCE_ENABLE_ANONYMOUS_ACCESS === 'true';
if (forceEnableAnonymousAccess) {
const hasAnonymousAccessEntitlement = hasEntitlement("anonymous-access");
if (!hasAnonymousAccessEntitlement) {
logger.warn(`FORCE_ENABLE_ANONYMOUS_ACCESS env var is set to true but anonymous access entitlement is not available. Setting will be ignored.`);
} else {
const org = await getOrgFromDomain(SINGLE_TENANT_ORG_DOMAIN);
if (org) {
const currentMetadata = getOrgMetadata(org);
const mergedMetadata = {
...(currentMetadata ?? {}),
anonymousAccessEnabled: true,
};
await prisma.org.update({
where: { id: org.id },
data: {
metadata: mergedMetadata,
},
});
logger.info(`Anonymous access enabled via FORCE_ENABLE_ANONYMOUS_ACCESS environment variable`);
}
}
}
// Apply FORCE_MEMBER_APPROVAL_REQUIRED environment variable setting
if (env.FORCE_MEMBER_APPROVAL_REQUIRED !== undefined) {
const forceMemberApprovalRequired = env.FORCE_MEMBER_APPROVAL_REQUIRED === 'true';
const org = await getOrgFromDomain(SINGLE_TENANT_ORG_DOMAIN);
if (org) {
await prisma.org.update({
where: { id: org.id },
data: { memberApprovalRequired: forceMemberApprovalRequired },
});
logger.info(`Member approval required set to ${forceMemberApprovalRequired} via FORCE_MEMBER_APPROVAL_REQUIRED environment variable`);
}
}
await syncConnections(config.connections);
await syncSearchContexts({
contexts: config.contexts,
orgId: SINGLE_TENANT_ORG_ID,
db: prisma,
});
}
const pruneOldGuestUser = async () => {
// The old guest user doesn't have the GUEST role
const guestUser = await prisma.userToOrg.findUnique({
where: {
orgId_userId: {
orgId: SINGLE_TENANT_ORG_ID,
userId: SOURCEBOT_GUEST_USER_ID,
},
role: {
not: OrgRole.GUEST,
}
},
});
if (guestUser) {
await prisma.user.delete({
where: {
id: guestUser.userId,
},
});
logger.info(`Deleted old guest user ${guestUser.userId}`);
}
}
const initSingleTenancy = async () => {
// Back fill the inviteId if the org has already been created to prevent needing to wipe the db
await prisma.$transaction(async (tx) => {
const org = await tx.org.findUnique({
where: {
id: SINGLE_TENANT_ORG_ID,
},
});
if (!org) {
await tx.org.create({
data: {
id: SINGLE_TENANT_ORG_ID,
name: SINGLE_TENANT_ORG_NAME,
domain: SINGLE_TENANT_ORG_DOMAIN,
inviteLinkId: crypto.randomUUID(),
memberApprovalRequired: env.FORCE_MEMBER_APPROVAL_REQUIRED === 'true' ? true :
env.FORCE_MEMBER_APPROVAL_REQUIRED === 'false' ? false :
true, // default to true if FORCE_MEMBER_APPROVAL_REQUIRED is not set
}
});
} else if (!org.inviteLinkId) {
await tx.org.update({
where: {
id: SINGLE_TENANT_ORG_ID,
},
data: {
inviteLinkId: crypto.randomUUID(),
}
});
}
});
// This is needed because v4 introduces the GUEST org role as well as making authentication required.
// To keep things simple, we'll just delete the old guest user if it exists in the DB
await pruneOldGuestUser();
const hasAnonymousAccessEntitlement = hasEntitlement("anonymous-access");
if (hasAnonymousAccessEntitlement) {
const res = await createGuestUser(SINGLE_TENANT_ORG_DOMAIN);
if (isServiceError(res)) {
throw new ServiceErrorException(res);
}
} else {
// If anonymous access entitlement is not enabled, set the flag to false in the org on init
const org = await getOrgFromDomain(SINGLE_TENANT_ORG_DOMAIN);
if (org) {
const currentMetadata = getOrgMetadata(org);
const mergedMetadata = {
...(currentMetadata ?? {}),
anonymousAccessEnabled: false,
};
await prisma.org.update({
where: { id: org.id },
data: { metadata: mergedMetadata },
});
}
}
// Apply FORCE_MEMBER_APPROVAL_REQUIRED environment variable setting
if (env.FORCE_MEMBER_APPROVAL_REQUIRED !== undefined) {
const forceMemberApprovalRequired = env.FORCE_MEMBER_APPROVAL_REQUIRED === 'true';
const org = await getOrgFromDomain(SINGLE_TENANT_ORG_DOMAIN);
if (org) {
await prisma.org.update({
where: { id: org.id },
data: { memberApprovalRequired: forceMemberApprovalRequired },
});
logger.info(`Member approval required set to ${forceMemberApprovalRequired} via FORCE_MEMBER_APPROVAL_REQUIRED environment variable`);
}
}
// Load any connections defined declaratively in the config file.
const configPath = env.CONFIG_PATH;
if (configPath) {
await syncDeclarativeConfig(configPath);
// watch for changes assuming it is a local file
if (!isRemotePath(configPath)) {
const watcher = chokidar.watch(configPath, {
ignoreInitial: true, // Don't fire events for existing files
awaitWriteFinish: {
stabilityThreshold: 100, // File size stable for 100ms
pollInterval: 100 // Check every 100ms
},
atomic: true // Handle atomic writes (temp file + rename)
});
watcher.on('change', async () => {
logger.info(`Config file ${configPath} changed. Re-syncing...`);
try {
await syncDeclarativeConfig(configPath);
} catch (error) {
logger.error(`Failed to sync config: ${error}`);
}
});
}
}
}
const initMultiTenancy = async () => {
const hasMultiTenancyEntitlement = hasEntitlement("multi-tenancy");
if (!hasMultiTenancyEntitlement) {
logger.error(`SOURCEBOT_TENANCY_MODE is set to ${env.SOURCEBOT_TENANCY_MODE} but your license doesn't have multi-tenancy entitlement. Please contact ${SOURCEBOT_SUPPORT_EMAIL} to request a license upgrade.`);
process.exit(1);
}
}
(async () => {
if (env.SOURCEBOT_TENANCY_MODE === 'single') {
await initSingleTenancy();
} else if (env.SOURCEBOT_TENANCY_MODE === 'multi') {
await initMultiTenancy();
} else {
throw new Error(`Invalid SOURCEBOT_TENANCY_MODE: ${env.SOURCEBOT_TENANCY_MODE}`);
}
})();