/ opencodehub / src / lib / mirror-sync.ts
swadhinbiswas Add repository mirror management APIs and sync hardening · 2/19/2026
2ce335e
207 lines · 6.4 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
/**
 * 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 simpleGit, { SimpleGit } from "simple-git";
import path from "path";

const REPOS_BASE_PATH = process.env.REPOS_PATH || path.join(process.cwd(), "data", "repos");

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

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]);
    }
}

/**
 * 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 = path.join(REPOS_BASE_PATH, 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 = simpleGit(repoPath);
        await ensureUpstreamRemote(git, repo.mirrorUrl);

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

        const fetchResult = await git.raw([
            "fetch",
            "upstream",
            "+refs/heads/*:refs/heads/*",
            "+refs/tags/*:refs/tags/*",
            "--prune",
        ]);

        // 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),
    });

    let synced = 0;
    let failed = 0;

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

    logger.info({ synced, failed, total: mirrors.length }, "Mirror sync batch completed");

    return { synced, failed };
}

/**
 * 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 = path.join(REPOS_BASE_PATH, repo.diskPath);

    try {
        const git: SimpleGit = simpleGit(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 = path.join(REPOS_BASE_PATH, repo.diskPath);
    try {
        const git: SimpleGit = simpleGit(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 };
    }
}