From 09f07401b082a54d170a86456ed9f9aee5b1994a Mon Sep 17 00:00:00 2001
From: Easton Evans <64231250+primetimeindy@users.noreply.github.com>
Date: Wed, 14 Oct 2026 10:02:02 -0500
Subject: [PATCH 1/3] feat(storage): add bounded conditional-create uploads
Expose opt-in SDK ifAbsent and CLI --if-absent for single-part uploads up to 5 MiB, preserving existing defaults.
Assisted-by: GPT-6.1-sol via Hermes Agent
---
conditional-create.offline.cjs | 214 +++++++++++++++++++++++++
packages/cli/src/lib/objects/put.ts | 47 +++++-
packages/cli/src/specs.yaml | 3 +
packages/storage/src/lib/object/put.ts | 37 ++++-
4 files changed, 297 insertions(+), 4 deletions(-)
create mode 100644 conditional-create.offline.cjs
diff --git a/conditional-create.offline.cjs b/conditional-create.offline.cjs
new file mode 100644
index 00000000..5cfe548b
--- /dev/null
+++ b/conditional-create.offline.cjs
@@ -0,0 +1,214 @@
+// Offline candidate regression harness. No install, CLI bootstrap or real auth.
+// Usage: node conditional-create.offline.cjs DEPENDENCY_ROOT ESBUILD_ROOT
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { createRequire, Module } = require('node:module');
+const { Readable } = require('node:stream');
+const net = require('node:net');
+const tls = require('node:tls');
+const http = require('node:http');
+const https = require('node:https');
+let networkAttempts = 0;
+const deny = () => { networkAttempts++; throw new Error('NETWORK DENIED'); };
+net.Socket.prototype.connect = deny;
+tls.connect = deny;
+http.request = https.request = http.get = https.get = deny;
+global.fetch = deny;
+const deps = createRequire(path.resolve(process.argv[2], '__offline__.cjs'));
+const esbuild = require(path.resolve(process.argv[3]));
+const { S3Client, GetObjectCommand } = deps('@aws-sdk/client-s3');
+const baseline = process.argv[4] === '--baseline';
+const sourceFiles = ['packages/storage/src/lib/object/put.ts', 'packages/cli/src/lib/objects/put.ts', 'packages/cli/src/specs.yaml'];
+function upstreamSource(file) {
+ assert.ok(sourceFiles.includes(file));
+ return require('node:child_process').execFileSync('/usr/bin/git', ['show', `HEAD:${file}`], {encoding:'utf8'});
+}
+const state = global.__conditionalTest = { clients: 0, auth: 0 };
+const requests = [];
+const compiledInputs = new Set();
+let objects = new Map();
+let injectForeign = false;
+let failStatus = 0;
+const foreign = Buffer.from('FOREIGN OWNER BYTES');
+const response = (statusCode, headers = {}, bytes = Buffer.alloc(0)) => ({
+ response: { statusCode, headers, body: Readable.from([bytes]) }
+});
+state.client = new S3Client({
+ region: 'auto', endpoint: 'https://offline.invalid', forcePathStyle: true,
+ credentials: { accessKeyId: 'SYNTHETIC_OFFLINE_ONLY', secretAccessKey: 'SYNTHETIC_NOT_A_SECRET' },
+ maxAttempts: 3, requestChecksumCalculation: 'WHEN_REQUIRED',
+ requestHandler: { async handle(req) {
+ const key = req.path;
+ requests.push({ method: req.method, path: key, headers: { ...req.headers }, query: { ...req.query } });
+ if (req.method === 'PUT') {
+ assert.equal(req.query.uploadId, undefined);
+ if (injectForeign) { objects.set(key, foreign); injectForeign = false; }
+ const status = failStatus || (req.headers['if-none-match'] === '*' && objects.has(key) ? 412 : 0);
+ if (status) return response(status, { 'content-type': 'application/xml' }, Buffer.from(`${status === 412 ? 'PreconditionFailed' : status === 403 ? 'AccessDenied' : 'ConditionalRequestConflict'}offline rejection`));
+ const chunks = [];
+ if (typeof req.body === 'string' || Buffer.isBuffer(req.body) || req.body instanceof Uint8Array) chunks.push(Buffer.from(req.body));
+ else for await (const c of req.body) chunks.push(Buffer.from(c));
+ objects.set(key, Buffer.concat(chunks));
+ return response(200, { etag: '"offline-etag"' });
+ }
+ if (req.method === 'GET' || req.method === 'HEAD') {
+ if (!objects.has(key)) return response(404);
+ const bytes = objects.get(key);
+ return response(200, { 'content-length': String(bytes.length), etag: '"offline-etag"' }, req.method === 'GET' ? bytes : Buffer.alloc(0));
+ }
+ throw new Error(`Unexpected wire method ${req.method}`);
+ } }
+});
+async function compile(entry, cli = false) {
+ const result = await esbuild.build({
+ entryPoints: [entry], bundle: true, write: false, metafile: true, platform: 'node', format: 'cjs',
+ plugins: [{ name: 'offline-only-boundaries', setup(build) {
+ if (baseline) build.onLoad({filter: /\/put\.ts$/}, a => {
+ const file = path.relative(process.cwd(), a.path);
+ if (sourceFiles.includes(file)) return {contents:upstreamSource(file),loader:'ts'};
+ });
+ build.onResolve({ filter: /^(@aws-sdk|@smithy)\// }, a => ({ path: deps.resolve(a.path), external: true }));
+ build.onResolve({ filter: /^\.\.\/(config|tigris-client)$/ }, a => ({ path: a.path, namespace: 'fixture' }));
+ build.onLoad({ filter: /.*/, namespace: 'fixture' }, () => ({ contents: `export const getConfig = () => ({bucket:'fixture'}); export const createTigrisClient = () => {globalThis.__conditionalTest.clients++; return {data:globalThis.__conditionalTest.client}};`, loader: 'js' }));
+ build.onResolve({ filter: /^@shared\/index$/ }, () => ({ path: path.resolve('shared/headers.ts') }));
+ build.onResolve({ filter: /^@shared\/utils$/ }, () => ({ path: path.resolve('shared/utils.ts') }));
+ if (cli) {
+ build.onResolve({ filter: /^@auth\// }, () => ({ path: 'auth-denied', namespace: 'cli-stub' }));
+ build.onResolve({ filter: /^@tigrisdata\/storage$/ }, () => ({ path: 'storage-facade', namespace: 'storage-facade' }));
+ build.onLoad({ filter: /.*/, namespace: 'storage-facade' }, () => ({ contents: `export {put} from './packages/storage/src/lib/object/put.ts'; export const list=()=>{throw new Error('list outside test scope')};`, resolveDir: process.cwd(), loader: 'js' }));
+ build.onResolve({ filter: /^@utils\/(exit|format|messages|mime)\.js$/ }, a => ({ path: a.path, namespace: 'cli-stub' }));
+ build.onLoad({ filter: /.*/, namespace: 'cli-stub' }, a => ({ contents: a.path === 'auth-denied'
+ ? `export async function getStorageConfig(){globalThis.__conditionalTest.auth++; return {bucket:'fixture'}}`
+ : `export const failWithError = (_,e) => {throw e instanceof Error ? e : new Error(e)}; export const printNextActions=()=>{}; export const formatOutput=()=>''; export const formatSize=String; export const msg=()=>''; export const printStart=()=>{}; export const printSuccess=()=>{}; export const getContentType=()=>undefined;`, loader: 'js' }));
+ build.onResolve({ filter: /^@utils\// }, a => ({ path: path.resolve('packages/cli/src/utils', a.path.slice(7).replace(/\.js$/, '.ts')) }));
+ }
+ } }]
+ });
+ for (const input of Object.keys(result.metafile.inputs)) {
+ assert.ok(!input.includes('packages/cli/src/auth/'), 'real auth provider must not be bundled');
+ compiledInputs.add(input);
+ }
+ const m = new Module(path.resolve('__offline_bundle__.cjs'), module);
+ m.filename = path.resolve('__offline_bundle__.cjs');
+ m.paths = module.paths;
+ m._compile(result.outputFiles[0].text, m.filename);
+ return m.exports;
+}
+let passed = 0, failed = 0;
+async function test(name, fn) {
+ requests.length = 0; objects = new Map(); injectForeign = false; failStatus = 0;
+ state.clients = state.auth = 0;
+ try { await fn(); assert.equal(networkAttempts, 0); passed++; console.log(`PASS ${name}`); }
+ catch (e) { failed++; console.log(`FAIL ${name}: ${e.message}`); }
+}
+(async () => {
+ const { put } = await compile('packages/storage/src/lib/object/put.ts');
+ const opts = { ifAbsent: true, access: 'private', config: { bucket: 'fixture' } };
+ await test('serialized conditional private PUT and exact GET readback', async () => {
+ const bytes = Buffer.from([0, 255, 17, 128, 10]);
+ const out = await put('new', bytes, opts); assert.ifError(out.error);
+ assert.equal(requests[0].method, 'PUT'); assert.equal(requests[0].headers['if-none-match'], '*');
+ assert.equal(requests[0].headers['x-amz-acl'], 'private');
+ const read = await state.client.send(new GetObjectCommand({ Bucket: 'fixture', Key: 'new' }));
+ assert.deepEqual(Buffer.from(await read.Body.transformToByteArray()), bytes);
+ assert.equal(out.data.size, bytes.length);
+ });
+ await test('foreign writer at dispatch: 412, unchanged bytes, no fallback', async () => {
+ injectForeign = true;
+ const out = await put('race', Buffer.from('ours'), opts);
+ assert.equal(out.error?.$metadata?.httpStatusCode, 412);
+ assert.deepEqual(objects.get('/fixture/race'), foreign);
+ assert.deepEqual(requests.map(r => r.method), ['PUT']);
+ });
+ await test('equal-byte conflict is still an error', async () => {
+ objects.set('/fixture/equal', Buffer.from('same'));
+ const out = await put('equal', Buffer.from('same'), opts);
+ assert.equal(out.error?.$metadata?.httpStatusCode, 412);
+ assert.deepEqual(requests.map(r => r.method), ['PUT']);
+ });
+ for (const status of [403, 409]) await test(`${status} is terminal without fallback`, async () => {
+ failStatus = status; const out = await put('reject', 'body', opts);
+ assert.equal(out.error?.$metadata?.httpStatusCode, status);
+ assert.equal(requests[0].headers['if-none-match'], '*'); assert.equal(requests.length, 1);
+ });
+ for (const [name, body, extra] of [
+ ['oversize buffer', Buffer.alloc(5 * 1024 * 1024 + 1), {}],
+ ['oversize UTF8 string', 'é'.repeat(3 * 1024 * 1024), {}],
+ ['unknown stream', new ReadableStream({start(c){c.close()}}), {}],
+ ['multipart', 'small', { multipart: true }],
+ ['custom part size', 'small', { partSize: 6 * 1024 * 1024 }]
+ ]) await test(`${name} refused before client resolution`, async () => {
+ const out = await put('reject', body, { ...opts, ...extra });
+ assert.match(out.error?.message || '', /ifAbsent/);
+ assert.equal(state.clients, 0); assert.equal(requests.length, 0); assert.equal(state.auth, 0);
+ });
+ await test('exact 5 MiB is single PUT', async () => {
+ const out = await put('limit', Buffer.alloc(5 * 1024 * 1024), opts); assert.ifError(out.error);
+ assert.deepEqual(requests.map(r => r.method), ['PUT']); assert.equal(requests[0].headers['if-none-match'], '*');
+ });
+ await test('empty and Blob bodies remain conditional', async () => {
+ for (const [key, body] of [['empty', ''], ['blob', new Blob(['blob bytes'])]]) {
+ const out = await put(key, body, opts); assert.ifError(out.error);
+ }
+ assert.ok(requests.filter(r=>r.method==='PUT').every(r=>r.headers['if-none-match']==='*'));
+ });
+ await test('default remains unconditional and allowOverwrite:false remains HEAD precheck', async () => {
+ objects.set('/fixture/default', foreign);
+ assert.ifError((await put('default', 'replacement', {config:{bucket:'fixture'}})).error);
+ assert.equal(requests[0].headers['if-none-match'], undefined);
+ requests.length = 0;
+ const out = await put('default', 'no', {allowOverwrite:false,config:{bucket:'fixture'}});
+ assert.equal(out.error.message, 'File already exists'); assert.deepEqual(requests.map(r=>r.method), ['HEAD']);
+ });
+ const cli = (await compile('packages/cli/src/lib/objects/put.ts', true)).default;
+ await test('CLI rejects if-absent stdin before auth seam', async () => {
+ await assert.rejects(cli({bucket:'fixture',key:'stdin','if-absent':true}), /if-absent/);
+ assert.equal(state.auth,0); assert.equal(requests.length,0);
+ });
+ await test('CLI forwards if-absent to real SDK wire', async () => {
+ await cli({bucket:'fixture',key:'cli',file:'LICENSE','if-absent':true,access:'private'});
+ assert.equal(requests[0].headers['if-none-match'],'*');
+ assert.equal(requests[0].headers['x-amz-acl'],'private');
+ assert.deepEqual(objects.get('/fixture/cli'), fs.readFileSync('LICENSE'));
+ });
+ fs.mkdirSync('.offline-fixtures', {recursive:true});
+ const fd = fs.openSync('.offline-fixtures/oversize', 'w');
+ fs.ftruncateSync(fd, 5 * 1024 * 1024 + 1); fs.closeSync(fd);
+ for (const file of ['.offline-fixtures/oversize', '.offline-fixtures']) await test(`CLI refuses ${file} before auth seam`, async () => {
+ await assert.rejects(cli({bucket:'fixture',key:'bad',file,'if-absent':true}), /if-absent/);
+ assert.equal(state.auth,0); assert.equal(requests.length,0);
+ });
+ await test('CLI conditional conflict propagates without fallback', async () => {
+ injectForeign = true;
+ await assert.rejects(cli({bucket:'fixture',key:'cli-race',file:'LICENSE','if-absent':true}), e=>e.$metadata?.httpStatusCode===412);
+ assert.deepEqual(objects.get('/fixture/cli-race'),foreign);
+ assert.deepEqual(requests.map(r=>r.method),['PUT']);
+ });
+ await test('CLI growth after fstat is bounded and refused before auth', async () => {
+ const file = '.offline-fixtures/growing';
+ fs.writeFileSync(file, 'tiny');
+ const original = fs.fstatSync;
+ fs.fstatSync = fd => { const stat = original(fd); fs.truncateSync(file,5*1024*1024+1); return stat; };
+ try {
+ await assert.rejects(cli({bucket:'fixture',key:'grow',file,'if-absent':true}), /if-absent/);
+ assert.equal(state.auth,0); assert.equal(requests.length,0);
+ } finally { fs.fstatSync = original; }
+ });
+ await test('explicit false keeps the unconditional path', async () => {
+ assert.ifError((await put('false','body',{...opts,ifAbsent:false})).error);
+ assert.equal(requests[0].headers['if-none-match'],undefined);
+ });
+ await test('oversize Blob refused before client resolution', async () => {
+ const out = await put('blob-large',new Blob([Buffer.alloc(5*1024*1024+1)]),opts);
+ assert.match(out.error?.message || '',/ifAbsent/); assert.equal(state.clients,0); assert.equal(requests.length,0);
+ });
+ await test('CLI spec exposes boolean opt-in', async () => {
+ const specFile = 'packages/cli/src/specs.yaml';
+ const spec = (baseline ? upstreamSource(specFile) : fs.readFileSync(specFile,'utf8')).split(' # put\n')[1].split(' # delete\n')[0];
+ assert.match(spec, /name: if-absent\n\s+description:.*\n\s+type: flag/);
+ });
+ const realAuthProviderImports = [...compiledInputs].filter(p=>p.includes('packages/cli/src/auth/')).length;
+ console.log(JSON.stringify({passed,failed,networkAttempts,realAuthProviderImports,realAuthProviderInvocations:0,compiledInputs:[...compiledInputs]}));
+ state.client.destroy(); process.exitCode = failed ? 1 : 0;
+})().catch(e=>{console.error(e);process.exitCode=1});
diff --git a/packages/cli/src/lib/objects/put.ts b/packages/cli/src/lib/objects/put.ts
index 06351d61..13843011 100644
--- a/packages/cli/src/lib/objects/put.ts
+++ b/packages/cli/src/lib/objects/put.ts
@@ -1,4 +1,12 @@
-import { createReadStream, statSync } from 'node:fs';
+import {
+ closeSync,
+ constants,
+ createReadStream,
+ fstatSync,
+ openSync,
+ readSync,
+ statSync,
+} from 'node:fs';
import { Readable } from 'node:stream';
import { getStorageConfig } from '@auth/provider.js';
import { put } from '@tigrisdata/storage';
@@ -30,6 +38,7 @@ export default async function putObject(options: Record) {
'cacheControl',
]);
const format = getFormat(options);
+ const ifAbsent = getOption(options, ['if-absent', 'ifAbsent'], false);
if (!bucketArg) {
failWithError(context, 'Bucket name or path is required');
@@ -51,10 +60,41 @@ export default async function putObject(options: Record) {
failWithError(context, 'File path is required (or pipe data via stdin)');
}
- let body: ReadableStream;
+ let body: ReadableStream | Buffer;
let fileSize: number | undefined;
- if (file) {
+ if (ifAbsent) {
+ const limit = 5 * 1024 * 1024;
+ if (!file) {
+ failWithError(context, '--if-absent requires a regular file up to 5 MiB; stdin is unsupported');
+ }
+ let fd: number | undefined;
+ try {
+ // Nonblocking open avoids waiting on a FIFO before the descriptor check.
+ fd = openSync(file, constants.O_RDONLY | constants.O_NONBLOCK);
+ const stats = fstatSync(fd);
+ if (!stats.isFile() || stats.size > limit) {
+ throw new Error('--if-absent requires a regular file up to 5 MiB');
+ }
+ // Read at most limit + 1, even if the file grows after fstat.
+ const bytes = Buffer.alloc(limit + 1);
+ let size = 0;
+ while (size < bytes.length) {
+ const count = readSync(fd, bytes, size, bytes.length - size, null);
+ if (count === 0) break;
+ size += count;
+ }
+ if (size > limit) {
+ throw new Error('--if-absent requires a regular file up to 5 MiB');
+ }
+ body = bytes.subarray(0, size);
+ fileSize = size;
+ } catch (error) {
+ failWithError(context, error);
+ } finally {
+ if (fd !== undefined) closeSync(fd);
+ }
+ } else if (file) {
// Read from file
try {
const stats = statSync(file);
@@ -83,6 +123,7 @@ export default async function putObject(options: Record) {
contentType ?? (file ? getContentType(file) : undefined);
const { data, error } = await put(key, body, {
+ ifAbsent,
access: access === 'public' ? 'public' : 'private',
contentType: resolvedContentType,
cacheControl,
diff --git a/packages/cli/src/specs.yaml b/packages/cli/src/specs.yaml
index 2b77394a..1727ee29 100644
--- a/packages/cli/src/specs.yaml
+++ b/packages/cli/src/specs.yaml
@@ -1931,6 +1931,9 @@ commands:
type: positional
examples:
- ./my-file.txt
+ - name: if-absent
+ description: Atomically create only if absent. Regular files up to 5 MiB only; stdin and multipart are unsupported
+ type: flag
- name: access
description: Access level
alias: a
diff --git a/packages/storage/src/lib/object/put.ts b/packages/storage/src/lib/object/put.ts
index 60979914..29676505 100644
--- a/packages/storage/src/lib/object/put.ts
+++ b/packages/storage/src/lib/object/put.ts
@@ -22,6 +22,14 @@ export type PutOptions = {
access?: 'public' | 'private';
addRandomSuffix?: boolean;
allowOverwrite?: boolean;
+ /**
+ * Atomically create only if the key is absent (If-None-Match: *).
+ * Supports string, Buffer or Blob bodies up to 5 MiB only. Streams,
+ * multipart and custom part sizes are rejected before client resolution.
+ * Conflicts are returned as errors, never retried unconditionally.
+ * Omitted/false preserves the existing allowOverwrite behavior.
+ */
+ ifAbsent?: boolean;
contentType?: string;
contentDisposition?: 'attachment' | 'inline';
/**
@@ -58,6 +66,29 @@ export async function put(
body: string | ReadableStream | Blob | Buffer,
options?: PutOptions
): Promise> {
+ if (options?.ifAbsent) {
+ const size =
+ typeof body === 'string'
+ ? Buffer.byteLength(body)
+ : Buffer.isBuffer(body)
+ ? body.byteLength
+ : body instanceof Blob
+ ? body.size
+ : undefined;
+ if (
+ size === undefined ||
+ size > 5 * 1024 * 1024 ||
+ options.multipart ||
+ options.partSize !== undefined
+ ) {
+ return {
+ error: new Error(
+ 'ifAbsent requires a string, Buffer or Blob up to 5 MiB without multipart or partSize'
+ ),
+ };
+ }
+ }
+
const config = getConfig();
const { data: tigrisClient, error } = createTigrisClient(options?.config);
@@ -100,8 +131,12 @@ export async function put(
CacheControl: options?.cacheControl ?? undefined,
Metadata: options?.metadata,
ACL: access,
+ ...(options?.ifAbsent ? { IfNoneMatch: '*' } : {}),
},
- partSize: options?.partSize ?? (options?.multipart ? 1024 * 1024 * 5 : 0),
+ // Bounded ifAbsent bodies always use one PutObject, never multipart.
+ partSize: options?.ifAbsent
+ ? 5 * 1024 * 1024
+ : (options?.partSize ?? (options?.multipart ? 1024 * 1024 * 5 : 0)),
queueSize: options?.queueSize,
leavePartsOnError: !(options?.multipart || options?.partSize),
abortController: options?.abortController
From 47515b27cc6ba17692943ee45bda03f7d1be59e2 Mon Sep 17 00:00:00 2001
From: Easton Evans <64231250+primetimeindy@users.noreply.github.com>
Date: Wed, 14 Oct 2026 10:02:15 -0500
Subject: [PATCH 2/3] chore(storage): add conditional-create release note
Assisted-by: GPT-6.1-sol via Hermes Agent
---
.changeset/bounded-conditional-create.md | 6 ++++++
1 file changed, 6 insertions(+)
create mode 100644 .changeset/bounded-conditional-create.md
diff --git a/.changeset/bounded-conditional-create.md b/.changeset/bounded-conditional-create.md
new file mode 100644
index 00000000..c25d9f89
--- /dev/null
+++ b/.changeset/bounded-conditional-create.md
@@ -0,0 +1,6 @@
+---
+"@tigrisdata/storage": minor
+"@tigrisdata/cli": minor
+---
+
+Add opt-in atomic create-only uploads with SDK `ifAbsent` and CLI `objects put --if-absent`. The bounded path sends `If-None-Match: *` for known-size bodies up to 5 MiB and rejects streams, multipart uploads and custom part sizes. Existing defaults and `allowOverwrite` behavior remain unchanged.
From 72d70773bc28fcdedc261d8a2ac71ff630162755 Mon Sep 17 00:00:00 2001
From: Easton Evans <64231250+primetimeindy@users.noreply.github.com>
Date: Wed, 14 Oct 2026 10:52:10 -0500
Subject: [PATCH 3/3] fix(cli): preserve browser builds for conditional uploads
Export existing memfs descriptor APIs and add lock-exact SDK, native CLI, and browser-shim regression tests.
Assisted-by: GPT-6.1-sol via Hermes Agent
---
packages/cli/src/browser/shims/node-fs.ts | 2 +
.../test/browser-conditional-create.test.ts | 168 ++++++++++++++++++
packages/cli/test/conditional-create.test.ts | 165 +++++++++++++++++
.../src/lib/object/put.if-absent.test.ts | 146 +++++++++++++++
4 files changed, 481 insertions(+)
create mode 100644 packages/cli/test/browser-conditional-create.test.ts
create mode 100644 packages/cli/test/conditional-create.test.ts
create mode 100644 packages/storage/src/lib/object/put.if-absent.test.ts
diff --git a/packages/cli/src/browser/shims/node-fs.ts b/packages/cli/src/browser/shims/node-fs.ts
index 4ba99f03..ecbc4246 100644
--- a/packages/cli/src/browser/shims/node-fs.ts
+++ b/packages/cli/src/browser/shims/node-fs.ts
@@ -7,6 +7,8 @@
import { fs } from '../volume.js';
export const {
+ constants,
+ fstatSync,
existsSync,
readFileSync,
writeFileSync,
diff --git a/packages/cli/test/browser-conditional-create.test.ts b/packages/cli/test/browser-conditional-create.test.ts
new file mode 100644
index 00000000..7d4bb0aa
--- /dev/null
+++ b/packages/cli/test/browser-conditional-create.test.ts
@@ -0,0 +1,168 @@
+///
+
+import { readFile } from 'node:fs/promises';
+import { getStorageConfig } from '@auth/provider.js';
+import { put } from '@tigrisdata/storage';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { parse } from 'yaml';
+import * as shim from '../src/browser/shims/node-fs.js';
+import { fs, resetVolume } from '../src/browser/volume.js';
+import putObject from '../src/lib/objects/put.js';
+import type { Specs } from '../src/types.js';
+import { setSpecs } from '../src/utils/specs.js';
+
+// Exercise the production handler against the browser's actual memfs and
+// stream substitutions. Auth and SDK are inert boundaries, not real login.
+vi.mock('node:fs', () => import('../src/browser/shims/node-fs.js'));
+vi.mock('node:stream', () => import('../src/browser/shims/node-stream.js'));
+vi.mock('@auth/provider.js', () => ({
+ getStorageConfig: vi.fn(async () => ({
+ endpoint: 'https://offline.invalid',
+ })),
+}));
+vi.mock('@tigrisdata/storage', () => ({ put: vi.fn() }));
+vi.mock('@utils/exit.js', () => ({
+ failWithError: (_context: unknown, error: unknown) => {
+ throw error instanceof Error ? error : new Error(String(error));
+ },
+ printNextActions: vi.fn(),
+}));
+
+const specs = parse(
+ await readFile(new URL('../src/specs.yaml', import.meta.url), 'utf8'),
+ { schema: 'core' }
+) as Specs;
+const file = '/tmp/payload.txt';
+const limit = 5 * 1024 * 1024;
+const options = { bucket: 'bucket', key: 'key', file, ifAbsent: true };
+
+beforeEach(() => {
+ resetVolume();
+ setSpecs(specs);
+ fs.writeFileSync(file, 'ours');
+ vi.mocked(put).mockResolvedValue({
+ data: {
+ path: 'key',
+ size: 4,
+ contentType: 'text/plain',
+ cacheControl: undefined,
+ contentDisposition: undefined,
+ etag: 'test',
+ metadata: undefined,
+ modified: new Date(0),
+ url: 'https://offline.invalid/key',
+ },
+ });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ resetVolume();
+});
+
+function expectClosed(close: ReturnType) {
+ expect(close).toHaveBeenCalledOnce();
+ const fd = close.mock.calls[0][0] as number;
+ expect(() => fs.fstatSync(fd)).toThrow();
+}
+
+describe('browser conditional-create filesystem compatibility', () => {
+ it('exports the actual memfs descriptor API and flags', () => {
+ expect(shim).toHaveProperty('constants', fs.constants);
+ expect(shim).toHaveProperty('fstatSync', fs.fstatSync);
+ });
+ it.each([0, 4, limit])(
+ 'uploads %i bounded bytes and closes the descriptor',
+ async (size) => {
+ fs.writeFileSync(file, Buffer.alloc(size, 97));
+ const close = vi.spyOn(shim, 'closeSync');
+ await putObject(options);
+ expectClosed(close);
+ expect(getStorageConfig).toHaveBeenCalledExactlyOnceWith({
+ withCredentialProvider: true,
+ });
+ expect(put).toHaveBeenCalledOnce();
+ const [key, body, config] = vi.mocked(put).mock.calls[0];
+ expect(key).toBe('key');
+ expect(Buffer.isBuffer(body)).toBe(true);
+ expect(body).toEqual(Buffer.alloc(size, 97));
+ expect(config).toMatchObject({
+ ifAbsent: true,
+ multipart: false,
+ access: 'private',
+ });
+ expect(config?.partSize).toBeUndefined();
+ }
+ );
+ it.each(['oversize', 'directory', 'missing', 'stdin'])(
+ 'rejects %s before auth or SDK',
+ async (kind) => {
+ if (kind === 'oversize') fs.writeFileSync(file, Buffer.alloc(limit + 1));
+ if (kind === 'directory') {
+ fs.unlinkSync(file);
+ fs.mkdirSync(file);
+ }
+ if (kind === 'missing') fs.unlinkSync(file);
+ const close = vi.spyOn(shim, 'closeSync');
+ await expect(
+ putObject({ ...options, file: kind === 'stdin' ? undefined : file })
+ ).rejects.toThrow();
+ expect(getStorageConfig).not.toHaveBeenCalled();
+ expect(put).not.toHaveBeenCalled();
+ if (kind === 'oversize' || kind === 'directory') expectClosed(close);
+ else expect(close).not.toHaveBeenCalled();
+ }
+ );
+ it('closes the descriptor on read failure without auth', async () => {
+ vi.spyOn(shim, 'readSync').mockImplementation(() => {
+ throw new Error('read failure');
+ });
+ const close = vi.spyOn(shim, 'closeSync');
+ await expect(putObject(options)).rejects.toThrow('read failure');
+ expectClosed(close);
+ expect(getStorageConfig).not.toHaveBeenCalled();
+ expect(put).not.toHaveBeenCalled();
+ });
+ it('bounds reads when the memfs file grows after fstat', async () => {
+ const stat = fs.fstatSync;
+ vi.spyOn(shim, 'fstatSync').mockImplementation(((fd: number) => {
+ const result = stat(fd);
+ fs.writeFileSync(file, Buffer.alloc(limit + 1));
+ return result;
+ }) as typeof stat);
+ const close = vi.spyOn(shim, 'closeSync');
+ await expect(putObject(options)).rejects.toThrow('up to 5 MiB');
+ expectClosed(close);
+ expect(getStorageConfig).not.toHaveBeenCalled();
+ expect(put).not.toHaveBeenCalled();
+ });
+ it('surfaces conflict without an unconditional retry', async () => {
+ vi.mocked(put).mockResolvedValue({
+ error: new Error('PreconditionFailed'),
+ });
+ const close = vi.spyOn(shim, 'closeSync');
+ await expect(putObject(options)).rejects.toThrow('PreconditionFailed');
+ expectClosed(close);
+ expect(put).toHaveBeenCalledOnce();
+ expect(vi.mocked(put).mock.calls[0][2]?.ifAbsent).toBe(true);
+ });
+ it.each([undefined, false])(
+ 'retains ordinary streaming with flag %s',
+ async (ifAbsent) => {
+ await putObject({ ...options, ifAbsent });
+ const [, body, config] = vi.mocked(put).mock.calls[0];
+ expect(Buffer.isBuffer(body)).toBe(false);
+ expect(config?.ifAbsent).toBe(false);
+ const reader = (body as ReadableStream).getReader();
+ const chunks: Uint8Array[] = [];
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ }
+ expect(Buffer.concat(chunks).toString()).toBe('ours');
+ }
+ );
+});
diff --git a/packages/cli/test/conditional-create.test.ts b/packages/cli/test/conditional-create.test.ts
new file mode 100644
index 00000000..4e3bf9b8
--- /dev/null
+++ b/packages/cli/test/conditional-create.test.ts
@@ -0,0 +1,165 @@
+import { execFileSync } from 'node:child_process';
+import {
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { getStorageConfig } from '@auth/provider.js';
+import { put } from '@tigrisdata/storage';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { parse } from 'yaml';
+import { createProgram } from '../src/cli-core.js';
+import putObject from '../src/lib/objects/put.js';
+import type { Specs } from '../src/types.js';
+import { setSpecs } from '../src/utils/specs.js';
+
+vi.mock('@auth/provider.js', () => ({
+ getStorageConfig: vi.fn(async () => ({
+ endpoint: 'https://offline.invalid',
+ })),
+}));
+vi.mock('@tigrisdata/storage', () => ({ put: vi.fn() }));
+vi.mock('@utils/analytics.js', () => ({ trackCommand: vi.fn() }));
+vi.mock('@utils/telemetry.js', () => ({
+ captureError: vi.fn(),
+ flushTelemetry: vi.fn(),
+ initTelemetry: vi.fn(),
+}));
+vi.mock('@utils/exit.js', () => ({
+ failWithError: (_context: unknown, error: unknown) => {
+ throw error instanceof Error ? error : new Error(String(error));
+ },
+ printNextActions: vi.fn(),
+ exitWithError: vi.fn(),
+}));
+
+const specs = parse(
+ readFileSync(new URL('../src/specs.yaml', import.meta.url), 'utf8'),
+ { schema: 'core' }
+) as Specs;
+let dir: string;
+let file: string;
+beforeEach(() => {
+ setSpecs(specs);
+ dir = mkdtempSync(join(tmpdir(), 'tigris-conditional-unit-'));
+ file = join(dir, 'payload.txt');
+ writeFileSync(file, 'ours');
+ vi.mocked(put).mockResolvedValue({
+ data: {
+ path: 'key',
+ size: 4,
+ contentType: 'text/plain',
+ cacheControl: undefined,
+ contentDisposition: undefined,
+ etag: 'test',
+ metadata: undefined,
+ modified: new Date(0),
+ url: 'https://offline.invalid/key',
+ },
+ });
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ rmSync(dir, { recursive: true, force: true });
+});
+
+async function dispatch(args: string[]) {
+ const program = createProgram({
+ specs,
+ version: 'offline-test',
+ hasImplementation: (parts) => parts.join('/') === 'objects/put',
+ loadModule: async (parts) => {
+ expect(parts).toEqual(['objects', 'put']);
+ return { module: { default: putObject }, error: null };
+ },
+ });
+ await program.parseAsync(args, { from: 'user' });
+}
+
+describe('native specs and Commander conditional-create dispatch', () => {
+ it.each([
+ ['objects', 'put', 'bucket', 'key'],
+ ['objects', 'put', 'bucket/key'],
+ ])(
+ 'passes boolean ifAbsent and bounded file bytes through %s',
+ async (...prefix) => {
+ await dispatch([...prefix, file, '--if-absent']);
+ expect(getStorageConfig).toHaveBeenCalledExactlyOnceWith({
+ withCredentialProvider: true,
+ });
+ expect(put).toHaveBeenCalledOnce();
+ const [key, body, options] = vi.mocked(put).mock.calls[0];
+ expect(key).toBe('key');
+ expect(Buffer.isBuffer(body)).toBe(true);
+ expect(body.toString()).toBe('ours');
+ expect(options).toMatchObject({
+ ifAbsent: true,
+ access: 'private',
+ multipart: false,
+ config: { bucket: 'bucket' },
+ });
+ expect(options?.partSize).toBeUndefined();
+ }
+ );
+ it('preserves omitted-flag streaming behavior', async () => {
+ await dispatch(['objects', 'put', 'bucket', 'key', file]);
+ const [, body, options] = vi.mocked(put).mock.calls[0];
+ expect(options?.ifAbsent).toBe(false);
+ expect(Buffer.isBuffer(body)).toBe(false);
+ await (body as ReadableStream).cancel();
+ });
+ it('accepts an exact 5 MiB regular file', async () => {
+ writeFileSync(file, Buffer.alloc(5 * 1024 * 1024));
+ await dispatch(['objects', 'put', 'bucket', 'key', file, '--if-absent']);
+ expect((vi.mocked(put).mock.calls[0][1] as Buffer).length).toBe(
+ 5 * 1024 * 1024
+ );
+ expect(vi.mocked(put).mock.calls[0][2]?.partSize).toBeUndefined();
+ });
+ it.each(['oversize', 'directory', 'missing', 'fifo', 'stdin'])(
+ 'rejects %s before auth or SDK access',
+ async (kind) => {
+ let input: string | undefined = file;
+ if (kind === 'oversize')
+ writeFileSync(file, Buffer.alloc(5 * 1024 * 1024 + 1));
+ if (kind === 'directory') {
+ input = join(dir, 'directory');
+ mkdirSync(input);
+ }
+ if (kind === 'missing') input = join(dir, 'missing');
+ if (kind === 'fifo') {
+ input = join(dir, 'fifo');
+ execFileSync('/usr/bin/mkfifo', [input]);
+ }
+ if (kind === 'stdin') input = undefined;
+ await expect(
+ dispatch([
+ 'objects',
+ 'put',
+ 'bucket',
+ 'key',
+ ...(input ? [input] : []),
+ '--if-absent',
+ ])
+ ).rejects.toThrow();
+ expect(getStorageConfig).not.toHaveBeenCalled();
+ expect(put).not.toHaveBeenCalled();
+ }
+ );
+ it('surfaces a conflict without retrying the SDK boundary', async () => {
+ vi.mocked(put).mockResolvedValue({
+ error: new Error('PreconditionFailed'),
+ });
+ await expect(
+ dispatch(['objects', 'put', 'bucket', 'key', file, '--if-absent'])
+ ).rejects.toThrow('PreconditionFailed');
+ expect(put).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/storage/src/lib/object/put.if-absent.test.ts b/packages/storage/src/lib/object/put.if-absent.test.ts
new file mode 100644
index 00000000..d0a21901
--- /dev/null
+++ b/packages/storage/src/lib/object/put.if-absent.test.ts
@@ -0,0 +1,146 @@
+import { Readable } from 'node:stream';
+import { S3Client } from '@aws-sdk/client-s3';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createTigrisClient } from '../tigris-client';
+import { put } from './put';
+
+// Keep the repository-wide integration cleanup inert for this offline suite.
+vi.mock('./list', () => ({
+ list: vi.fn(async () => ({ data: { items: [] } })),
+}));
+vi.mock('./remove', () => ({
+ remove: vi.fn(() => {
+ throw new Error('Unexpected cleanup delete');
+ }),
+}));
+vi.mock('../tigris-client', () => ({ createTigrisClient: vi.fn() }));
+
+const limit = 5 * 1024 * 1024;
+type Request = {
+ method: string;
+ headers: Record;
+ body?: unknown;
+};
+let requests: Request[];
+let client: S3Client;
+let status: number;
+let foreignBody: string | undefined;
+
+beforeEach(() => {
+ requests = [];
+ status = 200;
+ foreignBody = undefined;
+ client = new S3Client({
+ region: 'auto',
+ endpoint: 'https://offline.invalid',
+ forcePathStyle: true,
+ credentials: {
+ accessKeyId: 'offline-test-id',
+ secretAccessKey: 'offline-test-secret',
+ },
+ maxAttempts: 3,
+ requestHandler: {
+ handle: async (request: Request) => {
+ requests.push(request);
+ let code = status;
+ if (foreignBody !== undefined && request.method === 'PUT') {
+ if (request.headers['if-none-match'] === '*') code = 412;
+ else foreignBody = 'overwritten';
+ }
+ return {
+ response: {
+ statusCode: code,
+ headers: { etag: '"offline-etag"', 'content-length': '1' },
+ body: Readable.from(
+ code === 200
+ ? []
+ : [
+ `${code === 412 ? 'PreconditionFailed' : 'ConditionalRequestConflict'}conflict`,
+ ]
+ ),
+ },
+ };
+ },
+ },
+ });
+ vi.mocked(createTigrisClient).mockReturnValue({ data: client });
+});
+afterEach(() => {
+ client.destroy();
+ vi.clearAllMocks();
+});
+
+const config = { bucket: 'offline-bucket' };
+describe('put ifAbsent with real AWS serialization and an inert transport', () => {
+ it.each(['text', Buffer.from('text'), new Blob(['text'])])(
+ 'serializes a conditional private PUT for %s',
+ async (body) => {
+ const result = await put('nested/key', body, { ifAbsent: true, config });
+ expect(result.error).toBeUndefined();
+ const writes = requests.filter((r) => r.method === 'PUT');
+ expect(writes).toHaveLength(1);
+ expect(writes[0].headers['if-none-match']).toBe('*');
+ expect(writes[0].headers['x-amz-acl']).toBe('private');
+ expect(requests.map((r) => r.method)).toEqual(['PUT']);
+ }
+ );
+ it('accepts exactly 5 MiB as a single PUT', async () => {
+ expect(
+ (await put('key', Buffer.alloc(limit), { ifAbsent: true, config })).error
+ ).toBeUndefined();
+ expect(requests.map((r) => r.method)).toEqual(['PUT']);
+ });
+ it.each([409, 412])(
+ 'returns %s without unconditional retry or fallback',
+ async (code) => {
+ status = code;
+ const result = await put('key', 'ours', { ifAbsent: true, config });
+ expect(result.error).toBeDefined();
+ expect(result.data).toBeUndefined();
+ expect(requests).toHaveLength(1);
+ expect(requests[0].method).toBe('PUT');
+ expect(requests[0].headers['if-none-match']).toBe('*');
+ }
+ );
+ it('does not replace the simulated foreign object inserted before PUT', async () => {
+ foreignBody = 'foreign';
+ expect(
+ (await put('key', 'ours', { ifAbsent: true, config })).error
+ ).toBeDefined();
+ expect(foreignBody).toBe('foreign');
+ expect(requests.map((r) => r.method)).toEqual(['PUT']);
+ expect(requests[0].headers['if-none-match']).toBe('*');
+ });
+ it.each([
+ { body: Buffer.alloc(limit + 1), options: {} },
+ { body: 'é'.repeat(limit / 2 + 1), options: {} },
+ { body: new Blob([Buffer.alloc(limit + 1)]), options: {} },
+ { body: new ReadableStream(), options: {} },
+ { body: 'ok', options: { multipart: true } },
+ { body: 'ok', options: { partSize: limit } },
+ ])(
+ 'rejects unsupported body or upload mode before client resolution',
+ async ({ body, options }) => {
+ const result = await put('key', body, {
+ ...options,
+ ifAbsent: true,
+ config,
+ });
+ expect(result.error?.message).toContain('ifAbsent requires');
+ expect(createTigrisClient).not.toHaveBeenCalled();
+ expect(requests).toEqual([]);
+ }
+ );
+ it.each([undefined, false])(
+ 'preserves the unconditional default for ifAbsent=%s',
+ async (ifAbsent) => {
+ const result = await put('key', 'ours', {
+ ifAbsent,
+ config,
+ });
+ expect(result.error).toBeUndefined();
+ expect(requests[0].headers['if-none-match']).toBeUndefined();
+ expect(requests[0].method).toBe('PUT');
+ }
+ );
+});