summaryrefslogtreecommitdiffstats
path: root/scripts/cache/files.ts
blob: e2bdf8bcf24f0a9a00734f1be1bc939319fb4055 (plain) (blame)
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
import { $ } from 'bun';
import { mkdir, readdir, rm, exists } from 'fs/promises';
import { join, relative, sep } from 'path';
import type { CacheMetadata, FileMetadata } from './utils';

export async function calculateFileChecksum(filePath: string): Promise<string> {
    const fileBlob = Bun.file(filePath);
    const size = fileBlob.size;

    const hasher = new Bun.CryptoHasher('sha256');
    if (size <= 10 * 1024 * 1024 /** 10MB */)
        return hasher.update(await fileBlob.arrayBuffer()).digest('hex');

    const reader = fileBlob.stream().getReader();
    while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        if (value) hasher.update(value);
    }

    return hasher.digest('hex');
}

export async function calculateDirectoryChecksums(
    paths: string[]
): Promise<Record<string, FileMetadata>> {
    const files: Record<string, FileMetadata> = {};

    for (const path of paths) {
        const entries = await readdir(path, {
            recursive: true,
            withFileTypes: true
        });

        await Promise.all(
            entries
                .filter((entry) => entry.isFile())
                .map(async (entry) => {
                    const fullPath = join(entry.parentPath, entry.name);
                    const relativePath = relative('.', fullPath).split(sep).join('/');

                    const size = Bun.file(fullPath).size;
                    const checksum = await calculateFileChecksum(fullPath);

                    files[relativePath] = { checksum, size };
                })
        );
    }

    return files;
}

export async function validateCache(metadata: CacheMetadata): Promise<boolean> {
    console.log('Validating cache...');
    let valid = 0;
    let invalid = 0;
    let missing = 0;

    const totalFiles = Object.keys(metadata.files).length;

    for (const [filePath, fileInfo] of Object.entries(metadata.files)) {
        const fullPath = join('.', filePath);

        if (!(await exists(fullPath))) {
            missing++;
            continue;
        }

        try {
            const actualChecksum = await calculateFileChecksum(fullPath);
            if (actualChecksum === fileInfo.checksum) valid++;
            else invalid++;
        } catch (e) {
            invalid++;
        }
    }

    const isValid = invalid === 0 && missing === 0;

    if (isValid) {
        console.log(`Cache is valid: ${valid} files matched`);
    } else {
        console.log(
            `Cache validation failed: ${valid} valid, ${invalid} invalid, ${missing} missing (total: ${totalFiles})`
        );
    }

    return isValid;
}

export async function extractTar(tarPath: string): Promise<void> {
    const compressedData = await Bun.file(tarPath).arrayBuffer();
    const decompressed = Bun.zstdDecompressSync(new Uint8Array(compressedData));

    // Write decompressed tar to temp file
    const tempTarPath = tarPath + '.tmp';
    await Bun.write(tempTarPath, decompressed);

    await $`tar -xf ${tempTarPath}`.quiet().finally(async () => {
        await rm(tempTarPath).catch(() => {});
    });
}

export async function compressToTar(
    paths: string[],
    outputPath: string
): Promise<Record<string, FileMetadata>> {
    const checksums = await calculateDirectoryChecksums(paths);

    const tempTarPath = outputPath + '.tmp';
    await $`tar -cf ${tempTarPath} ${paths}`.quiet();

    try {
        const tarData = await Bun.file(tempTarPath).arrayBuffer();
        const compressed = Bun.zstdCompressSync(new Uint8Array(tarData));
        await Bun.write(outputPath, compressed);
    } finally {
        await rm(tempTarPath).catch(() => {});
    }

    return checksums;
}

export async function ensureDir(dir: string): Promise<void> {
    if (!(await exists(dir))) {
        await mkdir(dir, { recursive: true });
    }
}

export async function cleanupDir(dir: string): Promise<void> {
    try {
        await rm(dir, { recursive: true, force: true });
    } catch (e: any) {
        if (e.code !== 'EBUSY' && e.code !== 'ENOTEMPTY') {
            throw e;
        }
    }
}