sailfork / t3code-github / .repos/ alchemy-effect/ packages/ cloudflare/ src/ R2/ WriteBucketBinding.ts

import type * as runtime from "@cloudflare/workers-types";
import { getRawStream } from "alchemy/Util/Stream";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { makeBucketBinding, makeHelpers } from "./BucketBinding.ts";
import type {
  Conditional,
  MultipartOptions,
  MultipartUpload,
  PutOptions,
  UploadPartOptions,
  UploadedPart,
} from "./BucketTypes.ts";
import { WriteBucket, type WriteBucketClient } from "./WriteBucket.ts";

/**
 * Implementation of the {@link WriteBucket} binding that uses a Worker binding.
 */
export const WriteBucketBinding = Layer.effect(
  WriteBucket,
  Effect.suspend(() => makeBucketBinding({ makeClient: makeWrite })),
);

/** Build the write half of the binding client. */
export const makeWrite = ({
  raw,
  use,
  tryPromise,
  wrapR2Object,
  wrapR2ObjectOrBody,
}: ReturnType<typeof makeHelpers>): WriteBucketClient => {
  const wrapR2MultipartUpload = (upload: runtime.R2MultipartUpload): MultipartUpload => ({
    ...upload,
    raw: upload,
    uploadId: upload.uploadId,
    abort: () => tryPromise(() => upload.abort()),
    complete: (uploadedParts: UploadedPart[]) =>
      tryPromise(() => upload.complete(uploadedParts)).pipe(Effect.map(wrapR2Object)),
    uploadPart: (
      partNumber: number,
      value:
        | ReadableStream
        | ArrayBuffer
        | ArrayBufferView
        | string
        | Blob
        | Stream.Stream<Uint8Array>,
      options?: UploadPartOptions,
    ) =>
      tryPromise(() =>
        upload.uploadPart(
          partNumber,
          Stream.isStream(value) ? value.pipe(Stream.toReadableStream()) : (value as any),
          options,
        ),
      ),
  });

  return {
    // @ts-expect-error
    put: (
      key: string,
      value:
        | ReadableStream
        | ArrayBuffer
        | ArrayBufferView
        | string
        | null
        | Blob
        | Stream.Stream<Uint8Array>,
      options?: PutOptions & {
        onlyIf: Conditional | Headers;
        contentLength?: number;
      },
    ) =>
      use((raw) => {
        if (Stream.isStream(value)) {
          // `contentLength` is ours; everything else (checksums, metadata,
          // conditions) is R2's and must reach it on every path.
          const { contentLength, ...r2Options } = options ?? {};
          const rawStream = getRawStream(value);
          if (rawStream) {
            // Keep explicit length validation without routing native chunks
            // through Effect. Without a hint, R2 uses the native stream's length.
            const readable =
              contentLength === undefined
                ? rawStream
                : rawStream.pipeThrough(new FixedLengthStream(contentLength));
            return raw.put(key, readable as any, r2Options);
          } else if (!contentLength) {
            throw new Error("Content length is required");
          }
          // R2 needs a known length, so the stream is piped through a fixed
          // length stream.
          const readable = Stream.toReadableStream(value).pipeThrough(
            new FixedLengthStream(contentLength),
          );
          return raw.put(key, readable as any, r2Options);
        }
        return raw.put(key, value as any, options);
      }).pipe(Effect.map(wrapR2ObjectOrBody)) as any,
    delete: (keys: string | string[]) => use((raw) => raw.delete(keys)),
    createMultipartUpload: (key: string, options?: MultipartOptions) =>
      use((raw) => raw.createMultipartUpload(key, options)).pipe(Effect.map(wrapR2MultipartUpload)),
    resumeMultipartUpload: (key: string, uploadId: string) =>
      raw.pipe(
        Effect.map((raw) => raw.resumeMultipartUpload(key, uploadId)),
        Effect.map(wrapR2MultipartUpload),
      ),
  };
};