Skip to content

Commit 333e6f3

Browse files
fix(data-objectstack): uploadFile/uploadFiles upload through the storage service presigned flow (#38237)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoAoNwrZVJoUEFfvMURpRPKJ)_ Fixes #38163 Clause-②: no Metadata-protocol: none Route taken: (a). `uploadFile` and `uploadFiles` now upload through the package's own presigned storage adapter, `createObjectStackUploadAdapter`. `recordId` maps to `attachTo` with scope `attachments`, and the adapter's result maps to `FileUploadResult`. The declared `DataSource` contract promises an upload that returns a stored file, and the storage service is the one upload route the standard server serves, so (a) keeps that promise and (b) would not. Two options cannot be mapped: `fieldName` and `metadata`. Neither presigned request carries them. Those two are refused before any request, in the (b) manner, with an error that names the supported path, so nothing is dropped silently. Neither method sends a request to `/api/data/RESOURCE/upload` any more. Why refusing `fieldName` / `metadata` is not a narrowing (`Clause-②: no` stands): before this PR every call to either method failed. The standard server answers the old route 404 `ENDPOINT_NOT_FOUND` (405 with the version segment), whatever options were passed, so no caller had a working upload that carried those options. This PR removes no working behaviour. A call that always failed now succeeds without the two options, and with them it fails at once with an error that names the supported path, instead of a 404. The public types (`DataSource.uploadFile` / `uploadFiles`, `FileUploadResult`) are unchanged, and no metadata an author writes is affected (`Metadata-protocol: none`). ## 维护者速读 - 用户能看到什么变化:用界面数据层「上传文件」接口的应用和插件,上传现在真正落到存储服务,拿回已存好的文件;以前每次都失败。普通控制台用户无感,因为仓库里没人调用它。 - 为什么做:修复界面数据层对外声明却发往一条不存在地址的上传接口,替以后要调用它的应用解决问题。 - 出错会怎样:调用方传了直传流程带不了的两个附加选项,会立刻收到写明改法的报错,而不是被悄悄丢掉。其余改动可直接撤回。 - 要你做的:无。 ## What changes - `ui/packages/data-objectstack/src/index.ts`: `uploadFile` delegates to `createObjectStackUploadAdapter`, which sends `POST /api/v1/storage/upload/presigned`, the byte `PUT`, then `POST /api/v1/storage/upload/complete`. The adapter is built per call because `attachTo` is one of its construction options. The fetch it uses is built once per data source (`storageUploadFetch`). That fetch is the injected `uploadTransport` (#37506), plus the data source's `token` on every request to this server and never on a presigned URL on another origin. The same-origin check compares resolved origins: the URL is resolved against `baseUrl`, or the page's origin when `baseUrl` is empty, and it counts as this server only when the origins match (and, for a `baseUrl` with a path, the resolved path lies under it). A server that cannot be read, or a URL that does not parse, is not this server. `uploadFiles` is N sequential presigned uploads. The first refused file stops the batch, and the rejection's `details` carry `failedIndex` plus, as `uploaded`, the files already stored. The files after it are not sent. - Option mapping: `recordId` maps to `attachTo: { parentObject: resource, parentId: recordId }` and `scope: 'attachments'`. Without it, no scope is sent, so the server default applies, and `resource` is not sent. `onProgress` maps the adapter's 0 to 1 ratio to 0 to 100, spread across the batch for `uploadFiles`. `fieldName` and `metadata` reject with `UNSUPPORTED_OPERATION` before any request. - Errors: a refused storage request rejects `ObjectStackError` with `UPLOAD_ERROR`, the server's status, and `details.serverCode`. A failure that got no HTTP answer reaches the caller unchanged, as before. - `ui/packages/data-objectstack/src/upload-adapter.ts`: the presign refusal and the byte-PUT refusal now carry `status` (and `code`), as the completion refusal already did, so the mapping above can read them. Messages are unchanged. - No public shape changes: `DataSource.uploadFile` / `uploadFiles` and `FileUploadResult` are untouched. - `packages/qa/dogfood/test/data-objectstack-upload-route-38163.dogfood.test.ts`: the real-stack pin. `packages/qa/dogfood/package.json` gains one devDependency, `@object-ui/data-objectstack` (`workspace:*`), and `pnpm-lock.yaml` gains only that importer entry, written by `pnpm install`. With that, the pin resolves the adapter, the dogfood closure builds it, and the dogfood test hash follows adapter changes. `packages/qa/dogfood/vitest.config.ts` gains the one anchored alias `check:test-source-alias` prescribes, so the pin resolves the adapter's SOURCE in this checkout and not its last build. The dogfood package is private, so it needs no changeset. ## Tests - `uploadTransport-37506.test.ts` is updated, because its fake server now answers 404 on `/api/data/RESOURCE/upload` as the real one does. The #37506 pins keep their meaning: injected fetch, bearer on every request, connection state unchanged. A new top-level describe for #38163 checks that no request reaches the unserved route, the exact three-step sequence per file, the `recordId` mapping and result, the default scope without `recordId`, the refusal of `fieldName` and `metadata` with zero requests, token-only signing with no token on a foreign presigned URL, `UPLOAD_ERROR` code, status and serverCode, the partial-batch report, progress, and presigned URLs spelled protocol-relative (`//host`), slash-backslash and double-backslash getting no token while the presign and complete requests keep it. Ablation, run after the commit: with the previous string check restored, the slash-backslash case fails (1 of 15). The double-backslash case already got no token under that check. With the origin comparison removed, all three spellings and the cross-origin case fail (4 of 15). After restoring, git status is clean. - Unit ablation: with the base `index.ts` restored on disk, the file reported 12 of 12 failed. With the fix restored, it reported 21 of 21 passed (this file plus `objectstack-upload-scope-12055.test.ts`). - Package run: 128 of 128 test files and 1450 of 1450 tests passed, and `type-check` exited 0, both on 95e3f9f. - Real-stack pin (2 of 2 passing again on 95e3f9f; its `baseUrl` is a bare origin, so no path rule applies), first measured on head 9725c42, resolving the adapter source through the alias (the dependency is declared, and no link was made by hand). The stack is `bootStack` with `StorageServicePlugin`, the attachments fixture and a bearer-only session. `uploadFile` with a `recordId` (token only) and `uploadFiles` (host bearer fetch) pass 2 of 2. They assert committed `sys_file` rows, the `sys_attachment` row with its `attachmentId`, and that no request reached an unserved upload path. Ablation: with the base `index.ts` restored on disk (the file shows the old route twice), both tests fail with `UPLOAD_ERROR` "Not found", the server's 404. After `git checkout HEAD`, git status is clean and both pass again. The dogfood `typecheck` exits 0. ## Acceptance notes - `README.md` (File Uploads) does not describe `uploadFile` / `uploadFiles`, and it is outside the claimed surface. No sentence in it became false. ## Verification Read first: `index.ts`, at `uploadThroughStorage` and `storageUploadFetch` (where the token goes, and which URLs get it), then `uploadFiles` (what a partial batch reports). Two-minute check: run `pnpm --dir ui exec vitest run packages/data-objectstack/src/uploadTransport-37506.test.ts`. Expected: 15 passed. <details><summary>Local gates on head 95e3f9f</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 87 families over the 8 changed paths, and all 87 exited 0, `check:test-source-alias` included. The `--ran` reconciliation reported: 87 derived, 87 run, 0 NOT-MEASURED. `overlap-check` reported clean: origin/main, #38192 (which shares the dogfood `package.json`) and #38284 (which shares `pnpm-lock.yaml`) all merge cleanly. All other CI families are left to the PR's check-runs. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibx7DSQZnugnuX8CpCM)_ <!-- signed: repo:objectstack#3 · os-tesla · session_01L9qibx7DSQZnugnuX8CpCM --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent ed4ec27 commit 333e6f3

8 files changed

Lines changed: 582 additions & 131 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@object-ui/data-objectstack': patch
3+
---
4+
5+
fix(data-objectstack): `uploadFile` and `uploadFiles` upload through the storage service's presigned flow
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The two methods posted the file to `/api/data/<resource>/upload`, a route the standard server does not serve, so every call failed with 404 `ENDPOINT_NOT_FOUND`. They now upload through the storage service, the way `createObjectStackUploadAdapter` does: `POST /api/v1/storage/upload/presigned`, the byte `PUT`, then `POST /api/v1/storage/upload/complete`. `uploadFiles` uploads its files one after another.
11+
12+
- `recordId` attaches the file to that record of `resource` in the completing call (scope `attachments`), and the result's `metadata.attachmentId` names the attachment. Without `recordId` the file is stored under the server's default scope.
13+
- The result is the stored file: `id` is the `sys_file` id, `url` the stable download URL.
14+
- `onProgress` still receives 0 to 100.
15+
- `fieldName` and `metadata` are now refused with `UNSUPPORTED_OPERATION` before any request, because neither presigned request carries them. Before, they were sent to the missing route. To fill a file field, upload without them, then write the returned file onto the record with `update()`.
16+
- A refused storage request rejects with `UPLOAD_ERROR`, the server's status, and its error code in `details.serverCode`. When a file in `uploadFiles` is refused, the batch stops there. The error's `details` carry `failedIndex` and, as `uploaded`, the files already stored.
17+
18+
The requests still go through the injected `fetch`, outside the connection-state tracking, and the adapter's `token` is sent on every request to this server. A presigned byte URL on another origin does not get it: the same-origin check compares resolved origins, so a protocol-relative or backslash-spelled URL that resolves to another host is not this server.

‎packages/qa/dogfood/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
"@objectstack/verify": "workspace:*"
4444
},
4545
"devDependencies": {
46+
"@object-ui/data-objectstack": "workspace:*",
4647
"@objectstack/account": "workspace:*",
4748
"@objectstack/cli": "workspace:*",
4849
"@objectstack/cloud-connection": "workspace:*",
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// [#38163] `uploadFile` / `uploadFiles` of the ObjectStack data source
4+
// (`@object-ui/data-objectstack`) upload through the route a standard server
5+
// serves: the storage service's presigned flow. They used to post to
6+
// `/api/data/<resource>/upload`, which this stack answers 404
7+
// `ENDPOINT_NOT_FOUND`, so every call failed.
8+
//
9+
// The data source runs against a real stack (`bootStack` with
10+
// `StorageServicePlugin` and the attachments fixture), through a fetch that
11+
// hands each request to the stack's Hono app. The session is bearer-only:
12+
// no cookie exists on this transport, so a request that lost the bearer would
13+
// be anonymous and refused. What the pin reads: the call resolves, the
14+
// returned id names a committed `sys_file` row, a `recordId` upload wrote the
15+
// `sys_attachment` row, and no request reached an upload path the server does
16+
// not serve.
17+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
18+
import { mkdtempSync } from 'node:fs';
19+
import { join } from 'node:path';
20+
import { tmpdir } from 'node:os';
21+
import { bootStack, type VerifyStack } from '@objectstack/verify';
22+
import { StorageServicePlugin } from '@objectstack/service-storage';
23+
import { AuditPlugin } from '@objectstack/plugin-audit';
24+
import { ObjectStackAdapter } from '@object-ui/data-objectstack';
25+
import { attachmentsFixtureStack, attachmentsFixtureSecurity } from './fixtures/attachments-fixture.js';
26+
27+
const ORIGIN = 'http://stack-38163.test';
28+
const SYS = { isSystem: true } as const;
29+
/** An upload path the standard server does not serve: the data source's old one, with or without a version. */
30+
const UNSERVED_UPLOAD = /\/api\/(v\d+\/)?data\/[^/]+\/upload/;
31+
32+
describe('data-objectstack uploads reach the storage service on a real stack (#38163)', () => {
33+
let stack: VerifyStack;
34+
let admin: string;
35+
let ql: any;
36+
let caseId: string;
37+
const paths: string[] = [];
38+
39+
/** The stack's Hono app as a fetch; `withBearer` plays a host's authenticated fetch. */
40+
const stackFetch =
41+
(withBearer: string | null) =>
42+
async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
43+
const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url, ORIGIN);
44+
if (url.origin !== ORIGIN) throw new Error(`request left the stack: ${url.href}`);
45+
paths.push(`${init?.method ?? 'GET'} ${url.pathname}`);
46+
const headers = new Headers(init?.headers);
47+
if (withBearer) headers.set('Authorization', `Bearer ${withBearer}`);
48+
return stack.raw(`${url.pathname}${url.search}`, { ...init, headers });
49+
};
50+
51+
beforeAll(async () => {
52+
const rootDir = mkdtempSync(join(tmpdir(), 'upload-route-38163-'));
53+
stack = await bootStack(attachmentsFixtureStack as never, {
54+
security: attachmentsFixtureSecurity(),
55+
extraPlugins: [
56+
new StorageServicePlugin({ adapter: 'local', local: { rootDir }, bindToSettings: false }),
57+
new AuditPlugin(),
58+
],
59+
});
60+
admin = await stack.signIn();
61+
ql = await stack.kernel.getServiceAsync('objectql');
62+
const created = await stack.apiAs(admin, 'POST', '/data/att_case', { name: 'Upload target' });
63+
expect(created.status, 'create att_case').toBeLessThan(300);
64+
const body = (await created.json()) as any;
65+
caseId = String(body.id ?? body.record?.id ?? body.data?.id);
66+
}, 180_000);
67+
afterAll(async () => {
68+
await stack?.stop();
69+
});
70+
71+
it('uploadFile with recordId stores the file and attaches it to the record, under the token alone', async () => {
72+
paths.length = 0;
73+
const source = new ObjectStackAdapter({ baseUrl: ORIGIN, token: admin, fetch: stackFetch(null), autoReconnect: false });
74+
75+
const result = await source.uploadFile('att_case', new File(['hello'], 'hello.txt', { type: 'text/plain' }), {
76+
recordId: caseId,
77+
});
78+
79+
expect(result).toMatchObject({ filename: 'hello.txt', mimeType: 'text/plain', size: 5 });
80+
const file = await ql.findOne('sys_file', { where: { id: result.id }, context: SYS });
81+
expect(file, 'sys_file row').toBeTruthy();
82+
expect(file.status).toBe('committed');
83+
const attachment = await ql.findOne('sys_attachment', { where: { file_id: result.id }, context: SYS });
84+
expect(attachment, 'sys_attachment row').toBeTruthy();
85+
expect(attachment.parent_object).toBe('att_case');
86+
expect(String(attachment.parent_id)).toBe(caseId);
87+
expect(result.metadata?.attachmentId).toBe(attachment.id);
88+
expect(paths.filter((p) => UNSERVED_UPLOAD.test(p))).toEqual([]);
89+
}, 60_000);
90+
91+
it('uploadFiles stores every file, through a host fetch that carries the bearer', async () => {
92+
paths.length = 0;
93+
const source = new ObjectStackAdapter({ baseUrl: ORIGIN, fetch: stackFetch(admin), autoReconnect: false });
94+
95+
const results = await source.uploadFiles('att_case', [
96+
new File(['one'], 'one.txt', { type: 'text/plain' }),
97+
new File(['two!'], 'two.txt', { type: 'text/plain' }),
98+
]);
99+
100+
expect(results.map((r) => [r.filename, r.size])).toEqual([
101+
['one.txt', 3],
102+
['two.txt', 4],
103+
]);
104+
for (const r of results) {
105+
const file = await ql.findOne('sys_file', { where: { id: r.id }, context: SYS });
106+
expect(file?.status, `sys_file ${r.id}`).toBe('committed');
107+
}
108+
expect(paths.filter((p) => UNSERVED_UPLOAD.test(p))).toEqual([]);
109+
}, 60_000);
110+
});

‎packages/qa/dogfood/vitest.config.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,10 @@ export default defineConfig({
245245
// alias it to SOURCE so the pin is a verdict about the checkout,
246246
// not about a build artifact (#7668 is what a dist-resolved pin
247247
// costs).
248+
{
249+
find: /^@object-ui\/data-objectstack$/,
250+
replacement: path.resolve(__dirname, '../../../ui/packages/data-objectstack/src/index.ts'),
251+
},
248252
{
249253
find: /^@objectstack\/metadata-core$/,
250254
replacement: path.resolve(__dirname, '../../metadata-core/src/index.ts'),

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)