nodejs / release-cloudflare-worker

Infra for serving Node.js downloads and documentation.
https://nodejs.org/dist
MIT License
21 stars 5 forks source link

Refactor logic for fetching files and listing directories #111

Open flakey5 opened 3 months ago

flakey5 commented 3 months ago

Background

As of right now the code behind fetching files, heading files, and listing directories is functional and working fine. However, it isn't the cleanest.

Current Request Flow

image

Notable Points

Proposal

I have a few ideas that can make the code nicer to read and add some additional functionality that is/could be useful. I've implemented most of these ideas in my personal fork as POCs, https://github.com/flakey5/release-cloudflare-worker/tree/flakey5/20240330/contributors (term POC being used liberally in some cases)

A Provider

A Provider essentially acts like an API client. It abstracts the calls to a data source (e.g. r2, origin.nodejs.org) and returns the data in a shared type (e.g. GetFileResult for getting a file). It also should handle retry logic if necessary.

export interface Provider {
  head(path: string): Promise<HeadResult>;
  getFile(path: string, options?: GetFileOptions): Promise<GetFileResult>;
  readDirectory(path: string, options?: ReadDirectoryOptions): Promise<ReadDirectoryResult>;
}

So, an example of using a Provider to get a file from R2 would look something like:

const provider = new R2Provider({ ctx });
const result = await provider.getFile('some-file', { /* additional options, e.g. conditional headers */ });
if (!result.exists) {
  // file doesn't exist
} else {
  // do something with result.body
}

Providers will be created for R2 (R2Provider), R2's S3 API (S3Provider), and the origin server (OriginProvider). POC located here.

This API is a bit more complicated than what is currently implemented. However, it gives us a few benefits:

Our current implementation does not give us these benefits. It is hard coded to go to R2 and then the origin server if all retries to R2 get exhausted.

Additional changes

Proposed Request Flow

GET

image

HEAD

image

Wdyt cc @nodejs/web-infra ?