Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

registry: Fixes to allow layer uploads above 5GB #78

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
},
"dependencies": {
"@cfworker/base64url": "^1.12.5",
"@taylorzane/hash-wasm": "^0.0.11",
"@tsndr/cloudflare-worker-jwt": "^2.5.1",
"itty-router": "^4.0.27",
"zod": "^3.22.4"
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 30 additions & 16 deletions push/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { $, CryptoHasher, file, write } from "bun";
import { $, CryptoHasher, file, sleep, write } from "bun";
import { extract } from "tar";

import stream from "node:stream";
Expand Down Expand Up @@ -71,7 +71,7 @@ if (!(await file(tarFile).exists())) {

await mkdir(imagePath);

const result = await extract({
await extract({
file: tarFile,
cwd: imagePath,
});
Expand Down Expand Up @@ -251,7 +251,6 @@ async function pushLayer(layerDigest: string, readableStream: ReadableStream, to
throw new Error(`oci-chunk-max-length header is malformed (not a number)`);
}

const reader = readableStream.getReader();
const uploadId = createUploadResponse.headers.get("docker-upload-uuid");
if (uploadId === null) {
throw new Error("Docker-Upload-UUID not defined in headers");
Expand All @@ -271,9 +270,13 @@ async function pushLayer(layerDigest: string, readableStream: ReadableStream, to
let written = 0;
let previousReadable: ReadableLimiter | undefined;
let totalLayerSizeLeft = totalLayerSize;
const reader = readableStream.getReader();
let fail = "true";
let failures = 0;
while (totalLayerSizeLeft > 0) {
const range = `0-${Math.min(end, totalLayerSize) - 1}`;
const current = new ReadableLimiter(reader as ReadableStreamDefaultReader, maxToWrite, previousReadable);
await current.init();
const patchChunkUploadURL = parseLocation(location);
// we have to do fetchNode because Bun doesn't allow setting custom Content-Length.
// https://github.com/oven-sh/bun/issues/10507
Expand All @@ -284,14 +287,19 @@ async function pushLayer(layerDigest: string, readableStream: ReadableStream, to
"range": range,
"authorization": cred,
"content-length": `${Math.min(totalLayerSizeLeft, maxToWrite)}`,
"x-fail": fail,
}),
});
if (!patchChunkResult.ok) {
throw new Error(
`uploading chunk ${patchChunkUploadURL} returned ${patchChunkResult.status}: ${await patchChunkResult.text()}`,
);
previousReadable = current;
console.error(`${layerDigest}: Pushing ${range} failed with ${patchChunkResult.status}, retrying`);
await sleep(500);
if (failures++ >= 2) fail = "false";
continue;
}

fail = "true";
current.ok();
const rangeResponse = patchChunkResult.headers.get("range");
if (rangeResponse !== range) {
throw new Error(`unexpected Range header ${rangeResponse}, expected ${range}`);
Expand All @@ -308,18 +316,24 @@ async function pushLayer(layerDigest: string, readableStream: ReadableStream, to
const range = `0-${written - 1}`;
const uploadURL = new URL(parseLocation(location));
uploadURL.searchParams.append("digest", layerDigest);
const response = await fetch(uploadURL.toString(), {
method: "PUT",
headers: new Headers({
Range: range,
Authorization: cred,
}),
});
if (!response.ok) {
throw new Error(`${uploadURL.toString()} failed with ${response.status}: ${await response.text()}`);
for (let tries = 0; tries < 3; tries++) {
const response = await fetch(uploadURL.toString(), {
method: "PUT",
headers: new Headers({
Range: range,
Authorization: cred,
}),
});
if (!response.ok) {
console.error(`${layerDigest}: Finishing ${range} failed with ${response.status}, retrying`);
continue;
}

console.log("Pushed", layerDigest);
return;
}

console.log("Pushed", layerDigest);
throw new Error(`Could not push after multiple tries`);
}

const layersManifest = [] as {
Expand Down
27 changes: 25 additions & 2 deletions push/limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import stream from "node:stream";
export class ReadableLimiter extends stream.Readable {
public written: number = 0;
private leftover: Uint8Array | undefined;
private promise: Promise<Uint8Array> | undefined;
private accumulator: Uint8Array[];

constructor(
// reader will be used to read bytes until limit.
Expand All @@ -17,7 +19,27 @@ export class ReadableLimiter extends stream.Readable {
) {
super();

if (previousReader) this.leftover = previousReader.leftover;
if (previousReader) {
this.leftover = previousReader.leftover;
if (previousReader.accumulator.length > 0) {
this.promise = new Blob(previousReader.accumulator).bytes();
previousReader.accumulator = [];
}
}

this.accumulator = [];
}

async init() {
if (this.promise !== undefined) {
if (this.leftover !== undefined && this.leftover.length > 0)
this.leftover = await new Blob([await this.promise, this.leftover ?? []]).bytes();
else this.leftover = await this.promise;
}
}

ok() {
this.accumulator = [];
}

_read(): void {
Expand All @@ -27,6 +49,7 @@ export class ReadableLimiter extends stream.Readable {

if (this.leftover !== undefined) {
const toPushNow = this.leftover.slice(0, this.limit);
this.accumulator.push(toPushNow);
this.leftover = this.leftover.slice(this.limit);
this.push(toPushNow);
this.limit -= toPushNow.length;
Expand All @@ -50,7 +73,7 @@ export class ReadableLimiter extends stream.Readable {
}

if (arr.length === 0) return this.push(null);

this.accumulator.push(arr);
this.push(arr);
this.limit -= arr.length;
this.written += arr.length;
Expand Down
7 changes: 7 additions & 0 deletions src/registry/garbage-collector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import { ServerError } from "../errors";
import { ManifestSchema } from "../manifest";
import { isReference } from "./r2";

export type GarbageCollectionMode = "unreferenced" | "untagged";
export type GCOptions = {
Expand Down Expand Up @@ -219,6 +220,12 @@ export class GarbageCollector {
await this.list(`${options.name}/blobs/`, async (object) => {
const hash = object.key.split("/").pop();
if (hash && !referencedBlobs.has(hash)) {
const key = isReference(object);
// also push the underlying reference object
if (key) {
unreferencedKeys.push(key);
}

unreferencedKeys.push(object.key);
if (unreferencedKeys.length > deleteThreshold) {
if (!(await this.checkIfGCCanContinue(options.name, mark))) {
Expand Down
Loading
Loading