plugin-git-manager 1.4.0 → 1.4.1

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.
Files changed (53) hide show
  1. package/dist/client/317.e7b1d59371812c30.js +10 -0
  2. package/dist/client/434.05d0ba2b821105dc.js +10 -0
  3. package/dist/client/453.cdcba6d2d0c9522b.js +10 -0
  4. package/dist/client/454.625da741a7e1161f.js +10 -0
  5. package/dist/client/index.js +1 -1
  6. package/dist/client-v2/317.4e116f84ed9081b6.js +10 -0
  7. package/dist/client-v2/434.764113d20743a45b.js +10 -0
  8. package/dist/client-v2/453.5ab80c06d8e61a7e.js +10 -0
  9. package/dist/client-v2/454.b885b1d35ef7ff72.js +10 -0
  10. package/dist/client-v2/index.js +1 -1
  11. package/dist/locale/en-US.json +12 -1
  12. package/dist/locale/vi-VN.json +12 -1
  13. package/dist/locale/zh-CN.json +12 -1
  14. package/dist/node_modules/simple-git/package.json +1 -1
  15. package/dist/node_modules/zod/package.json +1 -1
  16. package/dist/server/actions/git-actions.js +299 -87
  17. package/dist/server/actions/gitlab-api.js +19 -12
  18. package/dist/server/actions/subtree.js +20 -10
  19. package/dist/server/plugin.js +134 -10
  20. package/dist/server/repository-access.js +2 -2
  21. package/dist/server/request-method-policy.js +2 -1
  22. package/dist/server/services/review-source.js +2 -1
  23. package/dist/server/utils/cluster-git.js +181 -0
  24. package/package.json +2 -2
  25. package/src/client/__tests__/FileExplorerAndManage.test.tsx +236 -0
  26. package/src/client/__tests__/workflowRoutes.test.ts +3 -1
  27. package/src/client/components/CommitHistory.tsx +19 -7
  28. package/src/client/components/FileExplorer.tsx +80 -34
  29. package/src/client/components/GitManagerSettings.tsx +21 -5
  30. package/src/client/components/GitOperations.tsx +25 -4
  31. package/src/client/components/GitRuntimeBanner.tsx +97 -0
  32. package/src/client/components/RepositoryConfig.tsx +28 -6
  33. package/src/client/context/GitManagerContext.tsx +156 -13
  34. package/src/client/workflowRoutes.ts +11 -0
  35. package/src/locale/en-US.json +12 -1
  36. package/src/locale/vi-VN.json +12 -1
  37. package/src/locale/zh-CN.json +12 -1
  38. package/src/server/__tests__/git-actions.test.ts +329 -4
  39. package/src/server/__tests__/smoke.test.ts +32 -1
  40. package/src/server/actions/git-actions.ts +322 -96
  41. package/src/server/actions/gitlab-api.ts +20 -14
  42. package/src/server/actions/subtree.ts +23 -6
  43. package/src/server/plugin.ts +152 -3
  44. package/src/server/repository-access.ts +2 -2
  45. package/src/server/request-method-policy.ts +1 -0
  46. package/src/server/services/review-source.ts +3 -2
  47. package/src/server/utils/cluster-git.ts +209 -0
  48. package/dist/client/317.2d0d33871e24ee24.js +0 -10
  49. package/dist/client/434.2401f7257495b66e.js +0 -10
  50. package/dist/client/453.58657b9ba0904477.js +0 -10
  51. package/dist/client-v2/317.d2466574d00f94d0.js +0 -10
  52. package/dist/client-v2/434.32b0a07b821b9329.js +0 -10
  53. package/dist/client-v2/453.f9a0ec6d8e1bd1cc.js +0 -10
@@ -232,14 +232,22 @@ export async function mergeRequests(ctx: Context, next: () => Promise<void>) {
232
232
  await next();
233
233
  }
234
234
 
235
+ function parseMrIid(value: unknown, ctx: Context): number {
236
+ if (value === undefined || value === null || value === '') {
237
+ ctx.throw(400, 'mrIid is required');
238
+ }
239
+ const text = String(value).trim();
240
+ const parsed = typeof value === 'number' ? value : Number(text);
241
+ if (!/^\d+$/.test(text) || !Number.isSafeInteger(parsed) || parsed < 1) {
242
+ ctx.throw(400, 'Invalid merge request ID');
243
+ }
244
+ return parsed;
245
+ }
246
+
235
247
  export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>) {
236
248
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
237
249
  const params = getEffectiveActionParams(ctx);
238
- const { mrIid } = params;
239
-
240
- if (!mrIid) {
241
- ctx.throw(400, 'mrIid is required');
242
- }
250
+ const mrIid = parseMrIid(params.mrIid, ctx);
243
251
 
244
252
  let data;
245
253
  if (isGitHub) {
@@ -364,11 +372,12 @@ export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>
364
372
 
365
373
  /** Read enough provider data to detect omitted files without hiding provider errors. */
366
374
  export async function readChatMergeRequest(ctx: Context, mrIid: number, repositoryId?: number | string) {
375
+ const validMrIid = parseMrIid(mrIid, ctx);
367
376
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx, repositoryId);
368
377
  if (isGitHub) {
369
378
  const [request, fileResult] = await Promise.all([
370
- githubFetch(`/repos/${projectPath}/pulls/${mrIid}`, pat),
371
- githubFetch(`/repos/${projectPath}/pulls/${mrIid}/files`, pat, { page: 1, per_page: 51 }),
379
+ githubFetch(`/repos/${projectPath}/pulls/${validMrIid}`, pat),
380
+ githubFetch(`/repos/${projectPath}/pulls/${validMrIid}/files`, pat, { page: 1, per_page: 51 }),
372
381
  ]);
373
382
  const item = request.data;
374
383
  if (!Array.isArray(fileResult.data)) throw new Error('Unable to read merge request changes');
@@ -401,8 +410,8 @@ export async function readChatMergeRequest(ctx: Context, mrIid: number, reposito
401
410
 
402
411
  if (!pat) ctx.throw(400, 'Personal Access Token is required for GitLab API access');
403
412
  const [request, changeResult] = await Promise.all([
404
- gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}`, pat),
405
- gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}/changes`, pat),
413
+ gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${validMrIid}`, pat),
414
+ gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${validMrIid}/changes`, pat),
406
415
  ]);
407
416
  const item = request.data;
408
417
  const changeData = changeResult.data || {};
@@ -446,11 +455,8 @@ export async function readChatMergeRequest(ctx: Context, mrIid: number, reposito
446
455
  export async function mergeRequestNotes(ctx: Context, next: () => Promise<void>) {
447
456
  const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
448
457
  const params = getEffectiveActionParams(ctx);
449
- const { mrIid, page = 1, perPage = 50 } = params;
450
-
451
- if (!mrIid) {
452
- ctx.throw(400, 'mrIid is required');
453
- }
458
+ const { page = 1, perPage = 50 } = params;
459
+ const mrIid = parseMrIid(params.mrIid, ctx);
454
460
 
455
461
  let notes = [];
456
462
  const pagination = {
@@ -1,9 +1,18 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
1
10
  import { Context } from '@nocobase/actions';
2
11
  import * as fs from 'fs';
3
12
  import * as os from 'os';
4
13
  import * as path from 'path';
5
14
  import type { SimpleGit } from 'simple-git';
6
- import { createGit, validateBranch, validateLocalPath, withAuth } from './git-actions';
15
+ import { createGit, getGit, validateBranch, validateLocalPath, withAuth, type RepoLockManager } from './git-actions';
7
16
  import { getEffectiveActionParams } from '../repository-access';
8
17
  import { getRepoAccount } from '../utils/get-repo-account';
9
18
  import { redactError, redactPat } from '../utils/redact';
@@ -329,7 +338,8 @@ export async function subtreeOptions(ctx: Context, next: () => Promise<void>) {
329
338
  if (!account) ctx.throw(400, 'Repository has no Git account configured');
330
339
  const localPath = validateLocalPath(stringValue(repo.get('localPath')));
331
340
  const repoUrl = stringValue(repo.get('repoUrl'));
332
- const git = createGit(localPath);
341
+ const git = await getGit(ctx, localPath);
342
+ const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
333
343
 
334
344
  try {
335
345
  const data = await withAuth(
@@ -365,11 +375,13 @@ export async function subtreeOptions(ctx: Context, next: () => Promise<void>) {
365
375
  },
366
376
  account.username,
367
377
  remoteName,
378
+ lockManager,
368
379
  );
369
380
  ctx.body = { success: true, data };
370
381
  } catch (error) {
382
+ const status = (error as { status?: number })?.status === 503 ? 503 : 400;
371
383
  const safeError = redactError(error);
372
- ctx.throw(400, ctx.t(safeError.message, { ns: 'plugin-git-manager' }));
384
+ ctx.throw(status, ctx.t(safeError.message, { ns: 'plugin-git-manager' }));
373
385
  }
374
386
  await next();
375
387
  }
@@ -381,7 +393,8 @@ export async function subtreePreview(ctx: Context, next: () => Promise<void>) {
381
393
  const { config, repo, account } = await loadConfigAndRepository(ctx, configId);
382
394
  const localPath = validateLocalPath(stringValue(repo.get('localPath')));
383
395
  const repoUrl = stringValue(repo.get('repoUrl'));
384
- const git = createGit(localPath);
396
+ const git = await getGit(ctx, localPath);
397
+ const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
385
398
 
386
399
  try {
387
400
  const preview = await withAuth(
@@ -392,11 +405,13 @@ export async function subtreePreview(ctx: Context, next: () => Promise<void>) {
392
405
  () => createPreview(git, config),
393
406
  account.username,
394
407
  config.remoteName,
408
+ lockManager,
395
409
  );
396
410
  ctx.body = { success: true, data: preview };
397
411
  } catch (error) {
412
+ const status = (error as { status?: number })?.status === 503 ? 503 : 400;
398
413
  const safeError = redactError(error);
399
- ctx.throw(400, ctx.t(safeError.message, { ns: 'plugin-git-manager' }));
414
+ ctx.throw(status, ctx.t(safeError.message, { ns: 'plugin-git-manager' }));
400
415
  }
401
416
  await next();
402
417
  }
@@ -421,7 +436,8 @@ export async function subtreeRunOnAppProcess(ctx: Context, next: () => Promise<v
421
436
  const { config, repo, account } = await loadConfigAndRepository(ctx, runParams.configId);
422
437
  const localPath = validateLocalPath(stringValue(repo.get('localPath')));
423
438
  const repoUrl = stringValue(repo.get('repoUrl'));
424
- const git = createGit(localPath);
439
+ const git = await getGit(ctx, localPath);
440
+ const lockManager = (ctx as Context & { app?: { lockManager?: RepoLockManager } }).app?.lockManager;
425
441
  const runsRepository = ctx.db.getRepository('gitSubtreeRuns');
426
442
  const startedAt = new Date();
427
443
  const run = await runsRepository.create({
@@ -462,6 +478,7 @@ export async function subtreeRunOnAppProcess(ctx: Context, next: () => Promise<v
462
478
  },
463
479
  account.username,
464
480
  config.remoteName,
481
+ lockManager,
465
482
  );
466
483
 
467
484
  const finishedAt = new Date();
@@ -3,6 +3,7 @@
3
3
  import { Plugin } from '@nocobase/server';
4
4
  import type { Context } from '@nocobase/actions';
5
5
  import type { Database } from '@nocobase/database';
6
+ import * as fs from 'fs';
6
7
  import { resolve } from 'path';
7
8
  import { DataTypes } from 'sequelize';
8
9
  import * as gitActions from './actions/git-actions';
@@ -24,7 +25,13 @@ import { enforceReviewControlAccess } from './review-control-access';
24
25
  import { enforceRepositoryAccess, enforceRepositoryCollectionAccess } from './repository-access';
25
26
  import { enforceGitChatAdmission, registerGitChatContextStrategies } from './chat-context-admission';
26
27
  import { isGitManagerResourceResponse, redactCredentialFields } from './utils/redact';
27
- import { containsCredentialBearingUrlField, URL_USERINFO_NOT_ALLOWED } from './utils/url-security';
28
+ import {
29
+ assertAccountRepositoryUrl,
30
+ assertUrlHasNoUserInfo,
31
+ containsCredentialBearingUrlField,
32
+ URL_USERINFO_NOT_ALLOWED,
33
+ } from './utils/url-security';
34
+ import { dispatchClusterGitInstall, readClusterGitStatus } from './utils/cluster-git';
28
35
 
29
36
  const GIT_CONFIGURATION_URL_FIELDS = new Set(['repoUrl', 'baseUrl']);
30
37
 
@@ -59,6 +66,14 @@ export class PluginGitManagerServer extends Plugin {
59
66
  skillHubContentService!: SkillHubGitContentService;
60
67
  reviewService!: GitReviewService;
61
68
  legacyPostService!: LegacyPostService;
69
+ private gitAutoRestoreTimer: NodeJS.Timeout | null = null;
70
+
71
+ private stopGitAutoRestore() {
72
+ if (this.gitAutoRestoreTimer) {
73
+ clearTimeout(this.gitAutoRestoreTimer);
74
+ this.gitAutoRestoreTimer = null;
75
+ }
76
+ }
62
77
 
63
78
  async afterAdd() {
64
79
  this.reviewService = new GitReviewService(this.app);
@@ -136,6 +151,8 @@ export class PluginGitManagerServer extends Plugin {
136
151
  subtreeOptions: subtreeActions.subtreeOptions,
137
152
  subtreeRun: subtreeActions.subtreeRunOnAppProcess,
138
153
  subtreeReplace: subtreeActions.subtreeRunOnAppProcess,
154
+ runtimeStatus: gitActions.runtimeStatus,
155
+ installGit: gitActions.installGit,
139
156
  },
140
157
  });
141
158
 
@@ -157,7 +174,7 @@ export class PluginGitManagerServer extends Plugin {
157
174
  // Existing repository permissions are stored on fileContent and triggerReview.
158
175
  // Aliases let the ACL apply those same grants and scopes to review controls.
159
176
  for (const [action, aliases] of [
160
- ['fileContent', ['reviewCutoverStatus']],
177
+ ['fileContent', ['reviewCutoverStatus', 'runtimeStatus']],
161
178
  [
162
179
  'triggerReview',
163
180
  [
@@ -234,13 +251,29 @@ export class PluginGitManagerServer extends Plugin {
234
251
  .recoverStuckSubtreeRuns((this as any).app)
235
252
  .catch((err) => (this as any).app.log?.error?.('plugin-git-manager: recover subtree runs error', err));
236
253
  startPoller((this as any).app);
254
+
255
+ this.stopGitAutoRestore();
256
+ const restoreTimer = setTimeout(async () => {
257
+ this.gitAutoRestoreTimer = null;
258
+ if (gitActions.isGitAvailable()) return;
259
+ const clusterStatus = await readClusterGitStatus(this.app).catch(() => undefined);
260
+ if (clusterStatus?.available && clusterStatus.gitConfigured && clusterStatus.previouslyInitialized) {
261
+ await dispatchClusterGitInstall(this.app).catch(
262
+ (err) => this.app.log?.warn?.('plugin-git-manager: startup git restore via Cluster Manager failed', err),
263
+ );
264
+ }
265
+ }, 5_000);
266
+ restoreTimer.unref?.();
267
+ this.gitAutoRestoreTimer = restoreTimer;
237
268
  });
238
269
  (this as any).app.on('beforeStop', () => {
270
+ this.stopGitAutoRestore();
239
271
  unregisterReviewQueue((this as any).app);
240
272
  this.reviewService.stop();
241
273
  stopPoller(this.app);
242
274
  });
243
275
  (this as any).app.on('beforeDestroy', () => {
276
+ this.stopGitAutoRestore();
244
277
  unregisterReviewQueue((this as any).app);
245
278
  this.reviewService.stop();
246
279
  stopPoller(this.app);
@@ -276,6 +309,7 @@ export class PluginGitManagerServer extends Plugin {
276
309
  'gitManager:subtreePreview',
277
310
  'gitManager:subtreeOptions',
278
311
  'gitManager:reviewCutoverStatus',
312
+ 'gitManager:runtimeStatus',
279
313
  'workflowGitReview:status',
280
314
  ],
281
315
  });
@@ -315,6 +349,7 @@ export class PluginGitManagerServer extends Plugin {
315
349
  'gitManager:reviewResetPostClaim',
316
350
  'gitManager:reviewCancelQueued',
317
351
  'gitManager:reviewLegacyReleaseHold',
352
+ 'gitManager:installGit',
318
353
  'workflowGitReview:setup',
319
354
  'workflowGitReview:repair',
320
355
  ],
@@ -328,7 +363,7 @@ export class PluginGitManagerServer extends Plugin {
328
363
  // Repositories config — CRUD on gitRepositories and gitAccounts (no operations)
329
364
  (this as any).app.acl.registerSnippet({
330
365
  name: `pm.${(this as any).name}.repositories`,
331
- actions: ['gitRepositories:*', 'gitAccounts:*'],
366
+ actions: ['gitRepositories:*', 'gitAccounts:*', 'gitManager:runtimeStatus', 'gitManager:installGit'],
332
367
  });
333
368
 
334
369
  // Full management — all git manager actions
@@ -412,7 +447,119 @@ export class PluginGitManagerServer extends Plugin {
412
447
  if (ctx.request.body?.pat === '••••••••') {
413
448
  delete ctx.request.body.pat;
414
449
  }
450
+
451
+ const mergedValues: Record<string, unknown> = {
452
+ ...(requestBody && typeof requestBody === 'object' && !Array.isArray(requestBody) ? requestBody : {}),
453
+ ...(requestBody?.values && typeof requestBody.values === 'object' && !Array.isArray(requestBody.values)
454
+ ? requestBody.values
455
+ : {}),
456
+ ...(actionParams?.values && typeof actionParams.values === 'object' && !Array.isArray(actionParams.values)
457
+ ? actionParams.values
458
+ : {}),
459
+ };
460
+
461
+ try {
462
+ if (resource === 'gitAccounts') {
463
+ let existingAccount: { get(attribute: string): unknown } | null = null;
464
+ if (ctx.action?.actionName === 'update' && actionParams?.filterByTk != null) {
465
+ existingAccount = await ctx.db
466
+ .getRepository('gitAccounts')
467
+ .findOne({ filterByTk: actionParams.filterByTk });
468
+ }
469
+ const provider = String(mergedValues.provider ?? existingAccount?.get('provider') ?? 'gitlab').trim();
470
+ const rawBaseUrl =
471
+ mergedValues.baseUrl !== undefined ? mergedValues.baseUrl : existingAccount?.get('baseUrl');
472
+ const baseUrl = typeof rawBaseUrl === 'string' && rawBaseUrl.trim() ? rawBaseUrl.trim() : null;
473
+ if (baseUrl) {
474
+ assertUrlHasNoUserInfo(baseUrl);
475
+ let parsedBase: URL;
476
+ try {
477
+ parsedBase = new URL(baseUrl);
478
+ } catch {
479
+ throw new Error('Invalid repository or account URL');
480
+ }
481
+ if (parsedBase.protocol !== 'https:') {
482
+ throw new Error('Only HTTPS repository and account URLs are allowed');
483
+ }
484
+ if (provider === 'github' && parsedBase.origin !== 'https://github.com') {
485
+ throw new Error('GitHub accounts currently require github.com');
486
+ }
487
+ }
488
+ }
489
+
490
+ if (resource === 'gitRepositories') {
491
+ if (mergedValues.localPath !== undefined) {
492
+ gitActions.validateLocalPath(String(mergedValues.localPath));
493
+ }
494
+ if (mergedValues.repoUrl !== undefined) {
495
+ gitActions.validateRepoUrl(String(mergedValues.repoUrl).trim());
496
+ }
497
+ if (mergedValues.defaultBranch !== undefined && String(mergedValues.defaultBranch).trim()) {
498
+ gitActions.validateBranch(String(mergedValues.defaultBranch).trim());
499
+ }
500
+ if (mergedValues.repoUrl !== undefined || mergedValues.gitAccountId !== undefined) {
501
+ let existingRepo: { get(attribute: string): unknown } | null = null;
502
+ if (ctx.action?.actionName === 'update' && actionParams?.filterByTk != null) {
503
+ existingRepo = await ctx.db
504
+ .getRepository('gitRepositories')
505
+ .findOne({ filterByTk: actionParams.filterByTk });
506
+ }
507
+ const effectiveRepoUrl = String(
508
+ mergedValues.repoUrl !== undefined ? mergedValues.repoUrl : existingRepo?.get('repoUrl') || '',
509
+ ).trim();
510
+ const effectiveAccountId =
511
+ mergedValues.gitAccountId !== undefined ? mergedValues.gitAccountId : existingRepo?.get('gitAccountId');
512
+ if (
513
+ effectiveRepoUrl &&
514
+ (typeof effectiveAccountId === 'number' || typeof effectiveAccountId === 'string') &&
515
+ String(effectiveAccountId).trim()
516
+ ) {
517
+ const account = await ctx.db.getRepository('gitAccounts').findOne({ filterByTk: effectiveAccountId });
518
+ if (account) {
519
+ const baseUrl = String(account.get('baseUrl') || '').trim() || null;
520
+ const provider = String(account.get('provider') || 'gitlab').trim();
521
+ assertAccountRepositoryUrl(effectiveRepoUrl, baseUrl, provider);
522
+ }
523
+ }
524
+ }
525
+ }
526
+ } catch (error) {
527
+ const message = error instanceof Error ? error.message : String(error);
528
+ ctx.throw(400, ctx.t(message, { ns: (this as any).name }));
529
+ }
530
+ }
531
+
532
+ if (resource === 'gitRepositories' && ctx.action?.actionName === 'destroy') {
533
+ const targetRepos = (await ctx.db.getRepository('gitRepositories').find({
534
+ filterByTk: ctx.action.params?.filterByTk,
535
+ filter: ctx.action.params?.filter,
536
+ fields: ['id', 'localPath'],
537
+ })) as Array<{ get: (attribute: string) => unknown }>;
538
+ const localPaths = Array.from(
539
+ new Set(
540
+ targetRepos
541
+ .map((item) => item.get('localPath'))
542
+ .filter((value): value is string => typeof value === 'string' && Boolean(value.trim())),
543
+ ),
544
+ );
545
+ await next();
546
+ for (const rawLocalPath of localPaths) {
547
+ const remainingCount = await ctx.db.getRepository('gitRepositories').count({
548
+ filter: { localPath: rawLocalPath },
549
+ });
550
+ if (remainingCount > 0) continue;
551
+ try {
552
+ const resolvedPath = gitActions.validateLocalPath(rawLocalPath);
553
+ if (fs.existsSync(resolvedPath)) {
554
+ fs.rmSync(resolvedPath, { recursive: true, force: true });
555
+ }
556
+ } catch {
557
+ // Legacy invalid paths are ignored so record deletion still succeeds.
558
+ }
559
+ }
560
+ return;
415
561
  }
562
+
416
563
  return next();
417
564
  });
418
565
 
@@ -459,12 +606,14 @@ export class PluginGitManagerServer extends Plugin {
459
606
  }
460
607
 
461
608
  async beforeDisable() {
609
+ this.stopGitAutoRestore();
462
610
  unregisterReviewQueue((this as any).app);
463
611
  this.reviewService.stop();
464
612
  stopPoller(this.app);
465
613
  }
466
614
 
467
615
  async beforeUnload() {
616
+ this.stopGitAutoRestore();
468
617
  unregisterReviewQueue((this as any).app);
469
618
  this.reviewService.stop();
470
619
  stopPoller(this.app);
@@ -801,8 +801,8 @@ export async function enforceRepositoryAccess(ctx: RepositoryAccessContext, next
801
801
  const reviewId = asRepositoryId(params.reviewId);
802
802
  if (reviewId == null) return ctx.throw(400, 'reviewId is required');
803
803
  repositoryId = await repositoryIdFromReview(ctx, reviewId);
804
- } else if (actionName === 'pollNow') {
805
- repositoryId = asRepositoryId(params.repositoryId);
804
+ } else if (actionName === 'pollNow' || actionName === 'installGit') {
805
+ repositoryId = actionName === 'pollNow' ? asRepositoryId(params.repositoryId) : undefined;
806
806
  if (repositoryId == null) {
807
807
  const allowed = await hasUnrestrictedRepositoryAccess({
808
808
  acl: ctx.app.acl,
@@ -18,6 +18,7 @@ const READ_ACTIONS = new Set([
18
18
  'pollerStatus',
19
19
  'rolePermissions',
20
20
  'reviewCutoverStatus',
21
+ 'runtimeStatus',
21
22
  ]);
22
23
 
23
24
  export async function enforceGitRequestMethod(ctx: Context, next: () => Promise<void>) {
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { createHash } from 'crypto';
4
4
  import type { Database } from '@nocobase/database';
5
- import { createGit, validateBranch, validateLocalPath, validateRef } from '../actions/git-actions';
5
+ import { assertLocalGitReady, createGit, validateBranch, validateLocalPath, validateRef } from '../actions/git-actions';
6
6
  import { getRepoAccount } from '../utils/get-repo-account';
7
7
  import { parseGitLabProject } from '../utils/gitlab-url';
8
8
 
@@ -87,7 +87,8 @@ export async function resolveReviewProjectKey(db: Database, repo: RecordGetter):
87
87
  }
88
88
 
89
89
  async function validateCheckoutProject(db: Database, repo: RecordGetter, expectedProjectKey: string): Promise<void> {
90
- const git = createGit(validateLocalPath(String(repo.get('localPath') || '')));
90
+ const localPath = validateLocalPath(String(repo.get('localPath') || ''));
91
+ const git = await assertLocalGitReady(localPath);
91
92
  let origin: string;
92
93
  try {
93
94
  origin = (await git.raw(['remote', 'get-url', 'origin'])).trim();
@@ -0,0 +1,209 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ const CLUSTER_INSTALL_CHANNEL = 'cluster-manager.install-packages';
4
+ const AUTO_RESTORE_LOCK_KEY = 'git-manager:cluster-git-install';
5
+ const AUTO_RESTORE_COOLDOWN_MS = 45_000;
6
+
7
+ let lastDispatchAt = 0;
8
+
9
+ interface RecordGetter {
10
+ get(attribute: string): unknown;
11
+ }
12
+
13
+ interface PackageConfigRepository {
14
+ findOne(): Promise<RecordGetter | null>;
15
+ create(options: { values: Record<string, unknown> }): Promise<RecordGetter>;
16
+ update(options: { filterByTk: unknown; values: Record<string, unknown> }): Promise<unknown>;
17
+ }
18
+
19
+ interface PubSubLike {
20
+ isConnected?: () => Promise<boolean> | boolean;
21
+ publish(channel: string, payload: unknown): Promise<unknown>;
22
+ }
23
+
24
+ interface LockManagerLike {
25
+ runExclusive<T>(key: string, fn: () => Promise<T>, ttl?: number): Promise<T>;
26
+ }
27
+
28
+ export interface ClusterGitApp {
29
+ pm?: { get?: (name: string) => unknown };
30
+ db?: {
31
+ getCollection?: (name: string) => unknown;
32
+ getRepository?: (name: string) => PackageConfigRepository | undefined;
33
+ };
34
+ pubSubManager?: PubSubLike;
35
+ lockManager?: LockManagerLike;
36
+ log?: {
37
+ info?: (message: string, meta?: unknown) => void;
38
+ warn?: (message: string, meta?: unknown) => void;
39
+ error?: (message: string, meta?: unknown) => void;
40
+ };
41
+ }
42
+
43
+ export interface ClusterGitStatus {
44
+ available: boolean;
45
+ gitConfigured: boolean;
46
+ previouslyInitialized: boolean;
47
+ status: 'idle' | 'running' | 'succeeded' | 'failed';
48
+ progressPercent: number;
49
+ }
50
+
51
+ function parseAptPackages(raw: unknown): string[] {
52
+ if (typeof raw !== 'string' || !raw.trim()) return [];
53
+ return Array.from(
54
+ new Set(
55
+ raw
56
+ .split(/[\r\n,]+/)
57
+ .map((item) => item.trim())
58
+ .filter(Boolean),
59
+ ),
60
+ );
61
+ }
62
+
63
+ function hasGitInWhitelist(raw: unknown): boolean {
64
+ if (!raw) return false;
65
+ try {
66
+ const parsed = typeof raw === 'string' ? (JSON.parse(raw) as { apt?: unknown }) : (raw as { apt?: unknown });
67
+ return Array.isArray(parsed?.apt) && parsed.apt.includes('git');
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+
73
+ function normalizeStatus(raw: unknown): ClusterGitStatus['status'] {
74
+ if (raw === 'running' || raw === 'succeeded' || raw === 'failed') return raw;
75
+ return 'idle';
76
+ }
77
+
78
+ function isClusterManagerEnabled(app?: ClusterGitApp): boolean {
79
+ if (!app?.db?.getCollection?.('workerPackagesConfigs')) return false;
80
+ if (!app.pm?.get) return true;
81
+ return Boolean(app.pm.get('plugin-cluster-manager') || app.pm.get('cluster-manager'));
82
+ }
83
+
84
+ export async function readClusterGitStatus(app?: ClusterGitApp): Promise<ClusterGitStatus> {
85
+ if (!isClusterManagerEnabled(app)) {
86
+ return {
87
+ available: false,
88
+ gitConfigured: false,
89
+ previouslyInitialized: false,
90
+ status: 'idle',
91
+ progressPercent: 0,
92
+ };
93
+ }
94
+
95
+ const repo = app?.db?.getRepository?.('workerPackagesConfigs');
96
+ if (!repo) {
97
+ return {
98
+ available: false,
99
+ gitConfigured: false,
100
+ previouslyInitialized: false,
101
+ status: 'idle',
102
+ progressPercent: 0,
103
+ };
104
+ }
105
+
106
+ const config = await repo.findOne();
107
+ if (!config) {
108
+ return {
109
+ available: true,
110
+ gitConfigured: false,
111
+ previouslyInitialized: false,
112
+ status: 'idle',
113
+ progressPercent: 0,
114
+ };
115
+ }
116
+
117
+ const aptPackages = parseAptPackages(config.get('aptPackages'));
118
+ const whitelisted = hasGitInWhitelist(config.get('packageWhitelist'));
119
+ const status = normalizeStatus(config.get('initStatus'));
120
+ const rawPercent = Number(config.get('initProgressPercent') ?? 0);
121
+
122
+ return {
123
+ available: true,
124
+ gitConfigured: aptPackages.includes('git') || whitelisted,
125
+ previouslyInitialized: Boolean(config.get('lastInitAt') || whitelisted || status === 'succeeded'),
126
+ status,
127
+ progressPercent: Number.isFinite(rawPercent) ? Math.min(Math.max(rawPercent, 0), 100) : 0,
128
+ };
129
+ }
130
+
131
+ export async function dispatchClusterGitInstall(
132
+ app: ClusterGitApp | undefined,
133
+ options: { ensureGitInConfig?: boolean; force?: boolean } = {},
134
+ ): Promise<{ dispatched: boolean; reason?: string }> {
135
+ if (!isClusterManagerEnabled(app)) {
136
+ return { dispatched: false, reason: 'Cluster Manager plugin is not enabled' };
137
+ }
138
+
139
+ const pubSub = app?.pubSubManager;
140
+ const connected = pubSub ? (pubSub.isConnected ? await pubSub.isConnected() : true) : false;
141
+ if (!pubSub || !connected) {
142
+ return { dispatched: false, reason: 'Cluster PubSub is not connected' };
143
+ }
144
+
145
+ const repo = app?.db?.getRepository?.('workerPackagesConfigs');
146
+ if (!repo) {
147
+ return { dispatched: false, reason: 'Cluster package configuration repository is unavailable' };
148
+ }
149
+
150
+ const runDispatch = async (): Promise<{ dispatched: boolean; reason?: string }> => {
151
+ const now = Date.now();
152
+ if (!options.force && now - lastDispatchAt < AUTO_RESTORE_COOLDOWN_MS) {
153
+ return { dispatched: false, reason: 'Recent install dispatch still in cooldown' };
154
+ }
155
+
156
+ let config = await repo.findOne();
157
+ if (!config) {
158
+ if (!options.ensureGitInConfig) {
159
+ return { dispatched: false, reason: 'Cluster package configuration has not been initialized' };
160
+ }
161
+ config = await repo.create({ values: { aptPackages: 'git' } });
162
+ }
163
+
164
+ const currentStatus = normalizeStatus(config.get('initStatus'));
165
+ if (!options.force && currentStatus === 'running') {
166
+ return { dispatched: false, reason: 'Cluster package installation is already running' };
167
+ }
168
+
169
+ const aptPackages = parseAptPackages(config.get('aptPackages'));
170
+ if (!aptPackages.includes('git')) {
171
+ if (!options.ensureGitInConfig && !hasGitInWhitelist(config.get('packageWhitelist'))) {
172
+ return { dispatched: false, reason: 'git is not configured in Cluster Manager packages' };
173
+ }
174
+ if (options.ensureGitInConfig) {
175
+ aptPackages.push('git');
176
+ }
177
+ }
178
+
179
+ const aptMirrorUrl = String(config.get('aptMirrorUrl') || process.env.APT_MIRROR_URL || '').trim() || undefined;
180
+ await repo.update({
181
+ filterByTk: config.get('id'),
182
+ values: {
183
+ ...(options.ensureGitInConfig ? { aptPackages: aptPackages.join('\n') } : {}),
184
+ initStatus: 'running',
185
+ lastInitAt: new Date(),
186
+ initProgressPercent: 5,
187
+ initProgressLog: 'Installing git on app/worker nodes via Cluster Manager...',
188
+ },
189
+ });
190
+
191
+ await pubSub.publish(CLUSTER_INSTALL_CHANNEL, {
192
+ targetRole: 'all',
193
+ packages: { apt: ['git'] },
194
+ registryConfig: { aptMirrorUrl },
195
+ });
196
+ lastDispatchAt = Date.now();
197
+ app?.log?.info?.('plugin-git-manager: dispatched git installation via Cluster Manager');
198
+ return { dispatched: true };
199
+ };
200
+
201
+ if (app?.lockManager?.runExclusive) {
202
+ return app.lockManager.runExclusive(AUTO_RESTORE_LOCK_KEY, runDispatch, 30_000);
203
+ }
204
+ return runDispatch();
205
+ }
206
+
207
+ export function resetClusterGitDispatchCooldownForTests(): void {
208
+ lastDispatchAt = 0;
209
+ }