Skip to content

storage: zero-copy Buffer in saveAssetFile (from PR #55 Copilot review) #57

@arndvs

Description

@arndvs

Parent PR: #55
Source comment: #55 (comment)
File: lib/cast/server/storage.ts:140
Confidence: 45 = 50 +20 specific +15 ≤10 lines −25 vague −15 semantics

Interpretation

saveAssetFile calls Buffer.from(bytes) on the incoming Uint8Array, which copies the data. For large uploads (up to UPLOAD_MAX_BYTES = 5MB) this doubles peak memory briefly. A zero-copy Buffer view over the same ArrayBuffer would avoid the copy.

Proposed approach

  • Replace Buffer.from(bytes) with Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength) to create a view instead of a copy
  • Verify the StorageAdapter's writeFile doesn't mutate the buffer (it shouldn't, but confirm)

Blockers / questions

  • Uint8Array from Request.arrayBuffer() may or may not share the underlying ArrayBuffer with other data — need to verify byteOffset is safe
  • 5MB copy is ~2ms on modern hardware — this is a micro-optimization

Context for shft

Files to read:

  • lib/cast/server/storage.tssaveAssetFile function
  • lib/cast/server/storage-adapter.tswriteFile contract on LocalFsAdapter
  • app/api/upload/route.ts — where bytes originates (new Uint8Array(await req.arrayBuffer()))

Acceptance criteria:

  • Buffer.from(bytes) replaced with zero-copy view
  • Upload route tests still pass
  • No mutation of the source ArrayBuffer

Feedback loops:

  • pnpm test
  • pnpm typecheck

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions