| 1 | import { Inject, Injectable, Logger } from '@nestjs/common'; |
| 2 | import { type Database, schema } from '@ghost/db'; |
| 3 | import { and, eq } from 'drizzle-orm'; |
| 4 | |
| 5 | import { DATABASE } from '../../../database/database.module.js'; |
| 6 | import { runGit, runGitStream } from '../../../lib/git/exec/run-git.js'; |
| 7 | import { resolveCommit } from '../../../lib/git/tree/resolve-ref.js'; |
| 8 | import { languageForPath } from '@ghost/languages'; |
| 9 | import { excluded } from '../../../utils/index.js'; |
| 10 | |
| 11 | const INSERT_CHUNK = 1_000; |
| 12 | |
| 13 | /** Symlinks and submodules are not files of the repository, so they hold no bytes. */ |
| 14 | const SKIPPED_MODES = new Set(['120000', '160000']); |
| 15 | |
| 16 | export interface LanguageBytes { |
| 17 | language: string; |
| 18 | bytes: number; |
| 19 | } |
| 20 | |
| 21 | @Injectable() |
| 22 | export class RepositoryLanguageService { |
| 23 | private readonly logger = new Logger(RepositoryLanguageService.name); |
| 24 | private readonly inFlight = new Map<string, Promise<LanguageBytes[]>>(); |
| 25 | |
| 26 | constructor(@Inject(DATABASE) private readonly db: Database) {} |
| 27 | |
| 28 | async getLanguages({ |
| 29 | repositoryId, |
| 30 | repoDirectory, |
| 31 | ref, |
| 32 | }: { |
| 33 | repositoryId: string; |
| 34 | repoDirectory: string; |
| 35 | ref: string; |
| 36 | }): Promise<LanguageBytes[]> { |
| 37 | const key = `${repositoryId}:${ref}`; |
| 38 | const pending = this.inFlight.get(key); |
| 39 | if (pending) return pending; |
| 40 | |
| 41 | const run = this.sync({ repositoryId, repoDirectory, ref }).finally(() => |
| 42 | this.inFlight.delete(key), |
| 43 | ); |
| 44 | this.inFlight.set(key, run); |
| 45 | return run; |
| 46 | } |
| 47 | |
| 48 | private async sync({ |
| 49 | repositoryId, |
| 50 | repoDirectory, |
| 51 | ref, |
| 52 | }: { |
| 53 | repositoryId: string; |
| 54 | repoDirectory: string; |
| 55 | ref: string; |
| 56 | }): Promise<LanguageBytes[]> { |
| 57 | const tip = await resolveCommit(repoDirectory, ref); |
| 58 | if (!tip) { |
| 59 | await this.forget(repositoryId, ref); |
| 60 | return []; |
| 61 | } |
| 62 | |
| 63 | const [state] = await this.db |
| 64 | .select() |
| 65 | .from(schema.repositoryLanguageIndex) |
| 66 | .where( |
| 67 | and( |
| 68 | eq(schema.repositoryLanguageIndex.repositoryId, repositoryId), |
| 69 | eq(schema.repositoryLanguageIndex.ref, ref), |
| 70 | ), |
| 71 | ); |
| 72 | |
| 73 | if (state?.indexedCommitSha === tip) return this.read(repositoryId, ref); |
| 74 | |
| 75 | // Only a fast-forward can be topped up: a force push or a pruned object makes the stored totals unrelated to the three, so count it again |
| 76 | const incremental = |
| 77 | state !== undefined && |
| 78 | (await this.isAncestor(repoDirectory, state.indexedCommitSha, tip)); |
| 79 | |
| 80 | const totals = incremental |
| 81 | ? await this.applyDiff({ |
| 82 | repoDirectory, |
| 83 | from: state!.indexedCommitSha, |
| 84 | to: tip, |
| 85 | totals: await this.readMap(repositoryId, ref), |
| 86 | }) |
| 87 | : await this.countTree(repoDirectory, tip); |
| 88 | |
| 89 | await this.forget(repositoryId, ref); |
| 90 | await this.write(repositoryId, ref, tip, totals); |
| 91 | |
| 92 | this.logger.log( |
| 93 | `Counted ${totals.size} languages for ${repositoryId} ${ref} (${ |
| 94 | incremental ? `${state!.indexedCommitSha}..${tip}` : 'full recount' |
| 95 | })`, |
| 96 | ); |
| 97 | |
| 98 | return sorted(totals); |
| 99 | } |
| 100 | |
| 101 | private async countTree(repoDirectory: string, tip: string) { |
| 102 | const totals = new Map<string, number>(); |
| 103 | |
| 104 | const records = splitRecords( |
| 105 | runGitStream({ |
| 106 | args: ['ls-tree', '-r', '-l', '-z', '--end-of-options', tip], |
| 107 | gitDir: repoDirectory, |
| 108 | }), |
| 109 | ); |
| 110 | |
| 111 | for await (const record of records) { |
| 112 | // "<mode> <type> <oid> <size>\t<path>", size padded, "-" for non-blobs |
| 113 | const tab = record.indexOf('\t'); |
| 114 | if (tab === -1) continue; |
| 115 | |
| 116 | const [mode, type, , size] = record.slice(0, tab).trim().split(/\s+/); |
| 117 | if (type !== 'blob' || SKIPPED_MODES.has(mode)) continue; |
| 118 | |
| 119 | add(totals, record.slice(tab + 1), Number(size)); |
| 120 | } |
| 121 | |
| 122 | return totals; |
| 123 | } |
| 124 | |
| 125 | private async applyDiff({ |
| 126 | repoDirectory, |
| 127 | from, |
| 128 | to, |
| 129 | totals, |
| 130 | }: { |
| 131 | repoDirectory: string; |
| 132 | from: string; |
| 133 | to: string; |
| 134 | totals: Map<string, number>; |
| 135 | }) { |
| 136 | const changes = await readRawDiff(repoDirectory, from, to); |
| 137 | const sizes = await this.sizesOf( |
| 138 | repoDirectory, |
| 139 | changes.flatMap(({ before, after }) => |
| 140 | [before?.oid, after?.oid].filter((oid): oid is string => Boolean(oid)), |
| 141 | ), |
| 142 | ); |
| 143 | |
| 144 | for (const { before, after } of changes) { |
| 145 | if (before) add(totals, before.path, -(sizes.get(before.oid) ?? 0)); |
| 146 | if (after) add(totals, after.path, sizes.get(after.oid) ?? 0); |
| 147 | } |
| 148 | |
| 149 | // a size git no longer agrees with would otherwise drift negative forever |
| 150 | for (const [language, bytes] of totals) { |
| 151 | if (bytes <= 0) totals.delete(language); |
| 152 | } |
| 153 | |
| 154 | return totals; |
| 155 | } |
| 156 | |
| 157 | private async sizesOf(repoDirectory: string, oids: string[]) { |
| 158 | const sizes = new Map<string, number>(); |
| 159 | if (oids.length === 0) return sizes; |
| 160 | |
| 161 | const output = await runGit({ |
| 162 | args: [ |
| 163 | 'cat-file', |
| 164 | '--batch-check=%(objectname) %(objecttype) %(objectsize)', |
| 165 | ], |
| 166 | gitDir: repoDirectory, |
| 167 | input: Buffer.from(`${[...new Set(oids)].join('\n')}\n`), |
| 168 | }); |
| 169 | |
| 170 | for (const line of output.split('\n')) { |
| 171 | const [oid, type, size] = line.trim().split(' '); |
| 172 | if (type === 'blob') sizes.set(oid, Number(size)); |
| 173 | } |
| 174 | |
| 175 | return sizes; |
| 176 | } |
| 177 | |
| 178 | private async read(repositoryId: string, ref: string) { |
| 179 | return sorted(await this.readMap(repositoryId, ref)); |
| 180 | } |
| 181 | |
| 182 | private async readMap(repositoryId: string, ref: string) { |
| 183 | const rows = await this.db |
| 184 | .select({ |
| 185 | language: schema.repositoryLanguageStat.language, |
| 186 | bytes: schema.repositoryLanguageStat.bytes, |
| 187 | }) |
| 188 | .from(schema.repositoryLanguageStat) |
| 189 | .where( |
| 190 | and( |
| 191 | eq(schema.repositoryLanguageStat.repositoryId, repositoryId), |
| 192 | eq(schema.repositoryLanguageStat.ref, ref), |
| 193 | ), |
| 194 | ); |
| 195 | |
| 196 | return new Map(rows.map(({ language, bytes }) => [language, bytes])); |
| 197 | } |
| 198 | |
| 199 | private async write( |
| 200 | repositoryId: string, |
| 201 | ref: string, |
| 202 | tip: string, |
| 203 | totals: Map<string, number>, |
| 204 | ) { |
| 205 | const rows = [...totals] |
| 206 | .filter(([, bytes]) => bytes > 0) |
| 207 | .map(([language, bytes]) => ({ repositoryId, ref, language, bytes })); |
| 208 | |
| 209 | for (let i = 0; i < rows.length; i += INSERT_CHUNK) { |
| 210 | await this.db |
| 211 | .insert(schema.repositoryLanguageStat) |
| 212 | .values(rows.slice(i, i + INSERT_CHUNK)) |
| 213 | .onConflictDoUpdate({ |
| 214 | target: [ |
| 215 | schema.repositoryLanguageStat.repositoryId, |
| 216 | schema.repositoryLanguageStat.ref, |
| 217 | schema.repositoryLanguageStat.language, |
| 218 | ], |
| 219 | set: { bytes: excluded(schema.repositoryLanguageStat.bytes) }, |
| 220 | }); |
| 221 | } |
| 222 | |
| 223 | await this.db |
| 224 | .insert(schema.repositoryLanguageIndex) |
| 225 | .values({ repositoryId, ref, indexedCommitSha: tip }) |
| 226 | .onConflictDoUpdate({ |
| 227 | target: [ |
| 228 | schema.repositoryLanguageIndex.repositoryId, |
| 229 | schema.repositoryLanguageIndex.ref, |
| 230 | ], |
| 231 | set: { indexedCommitSha: tip, updatedAt: new Date() }, |
| 232 | }); |
| 233 | } |
| 234 | |
| 235 | private async forget(repositoryId: string, ref: string) { |
| 236 | await this.db |
| 237 | .delete(schema.repositoryLanguageStat) |
| 238 | .where( |
| 239 | and( |
| 240 | eq(schema.repositoryLanguageStat.repositoryId, repositoryId), |
| 241 | eq(schema.repositoryLanguageStat.ref, ref), |
| 242 | ), |
| 243 | ); |
| 244 | await this.db |
| 245 | .delete(schema.repositoryLanguageIndex) |
| 246 | .where( |
| 247 | and( |
| 248 | eq(schema.repositoryLanguageIndex.repositoryId, repositoryId), |
| 249 | eq(schema.repositoryLanguageIndex.ref, ref), |
| 250 | ), |
| 251 | ); |
| 252 | } |
| 253 | |
| 254 | private async isAncestor( |
| 255 | repoDirectory: string, |
| 256 | ancestor: string, |
| 257 | descendant: string, |
| 258 | ) { |
| 259 | return runGit({ |
| 260 | args: ['merge-base', '--is-ancestor', ancestor, descendant], |
| 261 | gitDir: repoDirectory, |
| 262 | }).then( |
| 263 | () => true, |
| 264 | () => false, |
| 265 | ); |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | interface Side { |
| 270 | path: string; |
| 271 | oid: string; |
| 272 | } |
| 273 | |
| 274 | export interface RawChange { |
| 275 | before?: Side; |
| 276 | after?: Side; |
| 277 | } |
| 278 | |
| 279 | /** |
| 280 | * `git diff --raw -r -z` as sides to subtract and add. |
| 281 | * |
| 282 | * Each entry is ":<srcmode> <dstmode> <srcoid> <dstoid> <status>" followed by one path, or two for a rename or copy. Symlinks and submodules are dropped per side, so a file becoming a symlink still subtracts its old bytes. |
| 283 | */ |
| 284 | export async function readRawDiff( |
| 285 | gitDir: string, |
| 286 | from: string, |
| 287 | to: string, |
| 288 | ): Promise<RawChange[]> { |
| 289 | const raw = await runGit({ |
| 290 | args: [ |
| 291 | 'diff', |
| 292 | '--raw', |
| 293 | '-r', |
| 294 | '-z', |
| 295 | '--no-abbrev', // --no-abbrev keeps the oids full, which is what cat-file echoes back |
| 296 | '--end-of-options', |
| 297 | from, |
| 298 | to, |
| 299 | ], |
| 300 | gitDir, |
| 301 | }); |
| 302 | |
| 303 | const fields = raw.split('\0'); |
| 304 | const changes: RawChange[] = []; |
| 305 | |
| 306 | for (let i = 0; i < fields.length; i++) { |
| 307 | if (!fields[i].startsWith(':')) continue; |
| 308 | |
| 309 | const [srcMode, dstMode, srcOid, dstOid, status] = fields[i] |
| 310 | .slice(1) |
| 311 | .split(' '); |
| 312 | // a rename or a copy names the destination in a second path field |
| 313 | const renamed = status?.startsWith('R') || status?.startsWith('C'); |
| 314 | const srcPath = fields[++i]; |
| 315 | const dstPath = renamed ? fields[++i] : srcPath; |
| 316 | if (srcPath === undefined || dstPath === undefined) break; |
| 317 | |
| 318 | changes.push({ |
| 319 | before: isCounted(srcMode, srcOid) |
| 320 | ? { path: srcPath, oid: srcOid } |
| 321 | : undefined, |
| 322 | after: isCounted(dstMode, dstOid) |
| 323 | ? { path: dstPath, oid: dstOid } |
| 324 | : undefined, |
| 325 | }); |
| 326 | } |
| 327 | |
| 328 | return changes; |
| 329 | } |
| 330 | |
| 331 | function isCounted(mode: string, oid: string) { |
| 332 | return !SKIPPED_MODES.has(mode) && !/^0+$/.test(oid); |
| 333 | } |
| 334 | |
| 335 | /** NUL-terminated records, streamed, so a large tree is never held whole. */ |
| 336 | async function* splitRecords(chunks: AsyncIterable<string>) { |
| 337 | let carry = ''; |
| 338 | |
| 339 | for await (const chunk of chunks) { |
| 340 | carry += chunk; |
| 341 | const records = carry.split('\0'); |
| 342 | carry = records.pop() ?? ''; |
| 343 | for (const record of records) if (record) yield record; |
| 344 | } |
| 345 | |
| 346 | if (carry) yield carry; |
| 347 | } |
| 348 | |
| 349 | function add(totals: Map<string, number>, path: string, bytes: number) { |
| 350 | const language = languageForPath(path); |
| 351 | if (!language || !Number.isFinite(bytes)) return; |
| 352 | totals.set(language, (totals.get(language) ?? 0) + bytes); |
| 353 | } |
| 354 | |
| 355 | function sorted(totals: Map<string, number>): LanguageBytes[] { |
| 356 | return [...totals] |
| 357 | .filter(([, bytes]) => bytes > 0) |
| 358 | .map(([language, bytes]) => ({ language, bytes })) |
| 359 | .sort((a, b) => b.bytes - a.bytes); |
| 360 | } |