import { unwrapResponseDto } from "@superblocksteam/shared";
const BATCH_SIZE = 64;
export async function uploadDirectorySnapshot(rpcClient, directorySnapshot, hashCache) {
    const itemsToUpload = [];
    const processRecursively = async (directorySnapshot) => {
        if (hashCache.check_directory(directorySnapshot.hash)) {
            // The directory already exists on the server, we don't need to upload anything.
            return;
        }
        const directoryContents = [];
        for (const snapshotDirEntry of directorySnapshot.contents) {
            const name = snapshotDirEntry.name;
            let entry;
            switch (snapshotDirEntry.type) {
                case "-": {
                    if (!hashCache.check_file_content(snapshotDirEntry.hash)) {
                        // We are not sure if the file exists on the server, so we need to upload it
                        itemsToUpload.push({
                            type: "fileContents",
                            contents: snapshotDirEntry.contents.toString("base64"),
                        });
                    }
                    entry = {
                        type: "-",
                        hash: snapshotDirEntry.hash,
                        executable: snapshotDirEntry.executable,
                        name,
                    };
                    break;
                }
                case "d": {
                    if (!hashCache.check_directory(snapshotDirEntry.hash)) {
                        await processRecursively({
                            hash: snapshotDirEntry.hash,
                            contents: snapshotDirEntry.contents,
                        });
                    }
                    entry = { type: "d", name, hash: snapshotDirEntry.hash };
                    break;
                }
                case "l": {
                    entry = { type: "l", target: snapshotDirEntry.target, name };
                    break;
                }
                default:
                    throw new Error(`Unknown entry type: ${snapshotDirEntry}`);
            }
            directoryContents.push(entry);
        }
        itemsToUpload.push({
            type: "directoryContents",
            contents: directoryContents,
        });
    };
    await processRecursively(directorySnapshot);
    for (let idx = 0; idx < itemsToUpload.length; idx += BATCH_SIZE) {
        const batch = itemsToUpload.slice(idx, idx + BATCH_SIZE);
        await unwrapResponseDto(rpcClient.call.v1.dbfs.putMany({
            items: batch,
        }));
    }
}
//# sourceMappingURL=upload-snapshot.js.map