/ opencodehub / src / lib / mirror-sync.ts
Swadhin Biswas Feat/federation (#82) · 8/19/2026
c0437ed
317 lines · 10.1 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/**
 * Repository Mirror Sync Library
 * Handles background synchronization of mirrored repositories
 */

import { getDatabase, schema } from "@/db";
import { eq } from "drizzle-orm";
import { logger } from "./logger";
import type { SimpleGit } from "simple-git";
import { decryptWorkflowSecret, isEncryptedWorkflowSecret } from "./workflow-secret-crypto";
import { createSimpleGit } from "./git";
import { resolveRepoPath } from "./git-storage";

interface SyncResult {
    success: boolean;
    refsUpdated: number;
    error?: string;
}

export interface SyncAllMirrorsOptions {
    staleOnly?: boolean;
    minSyncIntervalMinutes?: number;
    maxRepos?: number;
    staleAfterMinutes?: number;
}

export interface SyncAllMirrorsResult {
    synced: number;
    failed: number;
    total: number;
    eligible: number;
    skipped: number;
    stale: number;
    failedRepoIds: string[];
    durationMs: number;
}

async function ensureUpstreamRemote(git: SimpleGit, mirrorUrl: string): Promise<void> {
    const remotes = await git.getRemotes(true);
    const upstream = remotes.find((remote) => remote.name === "upstream");
    if (!upstream) {
        await git.addRemote("upstream", mirrorUrl);
        return;
    }

    const fetchUrl = upstream.refs.fetch;
    if (fetchUrl !== mirrorUrl) {
        await git.remote(["set-url", "upstream", mirrorUrl]);
    }
}

/**
 * Build a fetch URL for a mirror, embedding the (decrypted) auth token into
 * the URL transiently for https remotes when the repo has a mirrorToken.
 */
export function buildFetchUrl(mirrorUrl: string, mirrorToken: string | null | undefined): string {
    if (!mirrorToken) return mirrorUrl;
    if (!mirrorUrl.startsWith("https://")) return mirrorUrl;

    const token = isEncryptedWorkflowSecret(mirrorToken)
        ? decryptWorkflowSecret(mirrorToken)
        : mirrorToken;

    const parsed = new URL(mirrorUrl);
    const host = parsed.hostname;
    let username = "oauth2";
    if (host === "github.com" || host === "bitbucket.org") {
        username = "x-access-token";
    }
    parsed.username = username;
    parsed.password = token;
    return parsed.toString();
}

/**
 * Sync a single mirrored repository with its upstream
 */
export async function syncMirrorRepository(repoId: string): Promise<SyncResult> {
    const db = getDatabase();

    // Get repository
    const repo = await db.query.repositories.findFirst({
        where: eq(schema.repositories.id, repoId),
    });

    if (!repo) {
        return { success: false, refsUpdated: 0, error: "Repository not found" };
    }

    if (!repo.isMirror || !repo.mirrorUrl) {
        return { success: false, refsUpdated: 0, error: "Not a mirror repository" };
    }

    const repoPath = await resolveRepoPath(repo.diskPath);

    try {
        // Mark as syncing
        // @ts-expect-error - Drizzle multi-db union type issue
        await db.update(schema.repositories)
            .set({ mirrorSyncStatus: "syncing" })
            .where(eq(schema.repositories.id, repoId));

        const git: SimpleGit = createSimpleGit({ baseDir: repoPath });
                await ensureUpstreamRemote(git, repo.mirrorUrl);

        // Mirror upstream refs directly into local heads/tags.
        logger.info({ repoId, mirrorUrl: repo.mirrorUrl }, "Starting mirror sync");

        // When a token is stored, fetch from the authenticated URL directly so
        // the secret never persists in the remote's git config.
        const fetchArgs = repo.mirrorToken
            ? ["fetch", buildFetchUrl(repo.mirrorUrl, repo.mirrorToken), "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*", "--prune"]
            : ["fetch", "upstream", "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*", "--prune"];

        const fetchResult = await git.raw(fetchArgs);

        // Approximate updated refs from fetch output lines.
        const refsUpdated = fetchResult
            .split("\n")
            .filter((line) => line.includes("->"))
            .length;

        // Update sync status
        // @ts-expect-error - Drizzle multi-db union type issue
        await db.update(schema.repositories)
            .set({
                mirrorSyncStatus: "success",
                lastMirrorSyncAt: new Date(),
                updatedAt: new Date(),
            })
            .where(eq(schema.repositories.id, repoId));

        logger.info({ repoId, refsUpdated }, "Mirror sync completed");

        return { success: true, refsUpdated };
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : "Unknown error";

        logger.error({ repoId, error: errorMessage }, "Mirror sync failed");

        // @ts-expect-error - Drizzle multi-db union type issue
        await db.update(schema.repositories)
            .set({ mirrorSyncStatus: "failed" })
            .where(eq(schema.repositories.id, repoId));

        return { success: false, refsUpdated: 0, error: errorMessage };
    }
}

/**
 * Sync all mirror repositories
 */
export async function syncAllMirrors(): Promise<{ synced: number; failed: number }> {
    const db = getDatabase();

    const mirrors = await db.query.repositories.findMany({
        where: eq(schema.repositories.isMirror, true),
    });
    return syncAllMirrorsWithOptions(mirrors, {});
}

async function syncAllMirrorsWithOptions(
    mirrors: Array<typeof schema.repositories.$inferSelect>,
    options: SyncAllMirrorsOptions
): Promise<SyncAllMirrorsResult> {
    const startedAt = Date.now();
    const staleAfterMinutes = options.staleAfterMinutes ?? 24 * 60;
    const minSyncIntervalMinutes = Math.max(0, options.minSyncIntervalMinutes ?? 30);
    const staleOnly = options.staleOnly ?? true;
    const maxRepos = options.maxRepos && options.maxRepos > 0 ? options.maxRepos : mirrors.length;

    let synced = 0;
    let failed = 0;
    let skipped = 0;
    let stale = 0;
    const failedRepoIds: string[] = [];

    const nowMs = Date.now();
    const eligibleMirrors = mirrors.filter((mirror) => {
        const lastSyncMs = mirror.lastMirrorSyncAt?.getTime() ?? null;
        const ageMinutes = lastSyncMs === null ? null : Math.max(0, Math.floor((nowMs - lastSyncMs) / 60000));
        const isStale = ageMinutes === null ? true : ageMinutes > staleAfterMinutes;
        if (isStale) stale += 1;

        if (mirror.mirrorSyncStatus === "syncing") {
            skipped += 1;
            return false;
        }
        if (staleOnly && !isStale) {
            skipped += 1;
            return false;
        }
        if (!isStale && ageMinutes !== null && ageMinutes < minSyncIntervalMinutes) {
            skipped += 1;
            return false;
        }
        return true;
    }).slice(0, maxRepos);

    for (const mirror of eligibleMirrors) {
        const result = await syncMirrorRepository(mirror.id);
        if (result.success) {
            synced++;
        } else {
            failed++;
            failedRepoIds.push(mirror.id);
        }
    }

    const durationMs = Date.now() - startedAt;
    logger.info(
        {
            synced,
            failed,
            total: mirrors.length,
            eligible: eligibleMirrors.length,
            skipped,
            stale,
            durationMs,
        },
        "Mirror sync batch completed"
    );

    return {
        synced,
        failed,
        total: mirrors.length,
        eligible: eligibleMirrors.length,
        skipped,
        stale,
        failedRepoIds,
        durationMs,
    };
}

export async function syncAllMirrorsScheduled(
    options: SyncAllMirrorsOptions = {}
): Promise<SyncAllMirrorsResult> {
    const db = getDatabase();
    const mirrors = await db.query.repositories.findMany({
        where: eq(schema.repositories.isMirror, true),
    });
    return syncAllMirrorsWithOptions(mirrors, options);
}

/**
 * Initialize a new mirror repository
 */
export async function initializeMirror(repoId: string, mirrorUrl: string): Promise<SyncResult> {
    const db = getDatabase();

    const repo = await db.query.repositories.findFirst({
        where: eq(schema.repositories.id, repoId),
    });

    if (!repo) {
        return { success: false, refsUpdated: 0, error: "Repository not found" };
    }

    const repoPath = await resolveRepoPath(repo.diskPath);

    try {
        const git: SimpleGit = createSimpleGit({ baseDir: repoPath });

        await ensureUpstreamRemote(git, mirrorUrl);

        // Mark as mirror in DB
        // @ts-expect-error - Drizzle multi-db union type issue
        await db.update(schema.repositories)
            .set({
                isMirror: true,
                mirrorUrl: mirrorUrl,
                mirrorSyncStatus: "pending",
            })
            .where(eq(schema.repositories.id, repoId));

        // Perform initial sync
        return await syncMirrorRepository(repoId);
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : "Unknown error";
        return { success: false, refsUpdated: 0, error: errorMessage };
    }
}

export async function disableMirror(repoId: string): Promise<{ success: boolean; error?: string }> {
    const db = getDatabase();
    const repo = await db.query.repositories.findFirst({
        where: eq(schema.repositories.id, repoId),
    });
    if (!repo) return { success: false, error: "Repository not found" };

    const repoPath = await resolveRepoPath(repo.diskPath);
    try {
        const git: SimpleGit = createSimpleGit({ baseDir: repoPath });
        const remotes = await git.getRemotes(true);
        if (remotes.some((remote) => remote.name === "upstream")) {
            await git.removeRemote("upstream");
        }

        // @ts-expect-error - Drizzle multi-db union type issue
        await db.update(schema.repositories)
            .set({
                isMirror: false,
                mirrorUrl: null,
                mirrorSyncStatus: null,
                updatedAt: new Date(),
            })
            .where(eq(schema.repositories.id, repoId));

        return { success: true };
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : "Unknown error";
        logger.error({ repoId, error: errorMessage }, "Failed to disable mirror");
        return { success: false, error: errorMessage };
    }
}