Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/37440-draft-publish-pins.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@objectstack/client': patch
'@object-ui/app-shell': patch
---

fix(client, app-shell): every draft-then-publish Save publishes only the draft it wrote

Clause-②: yes (widening: `@objectstack/client` `meta.publishItem` accepts `draftVersion` and `parentVersion` beside `message` and `packageId`)
Metadata-protocol: none

`client.meta.publishItem(type, name, opts)` takes two optional pins. `draftVersion` (sent in the publish body beside `message`) names the pending draft the publish means to promote: pass your own draft save's receipt `version`, and a draft another writer changed after it is refused `409 METADATA_CONFLICT` with nothing published. `parentVersion` names the live row the publish means to replace (sent as `If-Match`; `null` asserts that no live row is stored, sent as `If-None-Match: *`). Omitted, the request is byte-identical to before and the publish is unpinned.

In the console, every Save that writes a draft and publishes it at once now pins that publish to the draft its own write returned: the Studio top bar's Save (objects, object extensions, flows and their on/off switch, hooks, an installed object's actions, permission sets, a new app, a new object or flow), the item page's Save, each row of the package's sharing-defaults table, 「Configure tabs」, an installed object's field arrangement, the design mode's header pins, menu and menu labels. When someone else's draft write lands on the same item between that draft write and the publish, nothing is published and the draft, which now holds their change, is kept pending instead of discarded; the Save says a draft is pending (the next Studio Save asks to reload or overwrite). The take-back of a refused Save's own draft is pinned to the same version, so it never removes a draft someone else changed. Against a server whose draft save returns no version, all of these publish unpinned, as before.
63 changes: 62 additions & 1 deletion packages/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1284,6 +1284,22 @@ function metaDeleteHeaders(options?: DeleteMetaItemOptions): Record<string, stri
return { 'If-Match': String(options.ifMatch) };
}

/**
* [#37440] The live-row pin of `meta.publishItem`
* (`PublishMetaItemRequestSchema.parentVersion`) as the publish door reads it:
* a token as `If-Match`, verbatim and unquoted as {@link metaSaveHeaders}
* sends it, and `null` ("no live row is stored") as `If-None-Match: *`. The
* door takes `*` alone and never beside `If-Match`, which one argument cannot
* produce. `undefined` (never `{}`) when unset or empty, so the call site
* omits the `headers` key and an unpinned publish is byte-identical to what
* it sent before.
*/
function metaPublishHeaders(parentVersion: string | null | undefined): Record<string, string> | undefined {
if (parentVersion === null) return { 'If-None-Match': '*' };
if (!parentVersion) return undefined;
return { 'If-Match': String(parentVersion) };
}

/**
* An OAuth client application exactly as `@better-auth/oauth-provider` puts it
* on the wire: RFC 7591 §2 client metadata, snake_case, served BARE — these
Expand Down Expand Up @@ -2725,6 +2741,15 @@ export class ObjectStackClient {
* holds no draft and another package's draft is stored. Pass the package
* whose draft you mean as `opts.packageId` (`?package=` on the wire), as
* `saveItem` and `deleteItem` name the row they act on.
*
* PIN WHAT YOU PUBLISH when you wrote or read the draft first
* (`PublishMetaItemRequestSchema`'s two ADR-0008 pins): `draftVersion`
* names the draft you mean to promote, so a draft another writer changed
* after you wrote or read it is refused `409 METADATA_CONFLICT` and
* nothing is published on their behalf; `parentVersion` names the live
* row you mean to replace. Pass your own draft save's receipt `version`
* (or the draft read's) as `draftVersion` — never a fresh re-read, which
* would pin whatever draft is pending now, someone else's included.
*/
publishItem: async (
type: string,
Expand All @@ -2751,6 +2776,31 @@ export class ObjectStackClient {
* it.
*/
packageId?: string;
/**
* `PublishMetaItemRequestSchema.draftVersion` — the version token
* of the pending draft this publish means to promote: a draft
* save's receipt `version` (`saveItem` in draft mode) or the
* draft read's `version`. Sent as the `draftVersion` member of
* the publish body, beside `message`. A draft that moved since is
* refused `409 METADATA_CONFLICT`, its `currentVersion` naming the
* draft's current token (`null` when no draft is pending any
* more), and nothing is promoted. Omitted, whichever draft is
* pending is promoted, as before. An empty string pins nothing and
* is not sent.
*/
draftVersion?: string;
/**
* `PublishMetaItemRequestSchema.parentVersion` — the version token
* of the LIVE row this publish means to replace (a publish
* receipt's `version`, a read's `version`), sent as `If-Match`.
* `null` asserts that no live row is stored, sent as
* `If-None-Match: *`. A live row that does not match is refused
* `409 METADATA_CONFLICT` and nothing is promoted. Omitted, the
* publish replaces whatever is live, as before. It pins the live
* row only; the draft's own pin is `draftVersion`, and the two
* may be sent together (the door judges the draft first).
*/
parentVersion?: string | null;
},
): Promise<PublishMetaItemResponse> => {
const route = this.getRoute('metadata');
Expand All @@ -2764,9 +2814,20 @@ export class ObjectStackClient {
// `query`, not `qs` — it carries its own `?`; see `saveItem`'s note on
// the three meanings `qs` holds in this file.
const query = search ? `?${search}` : '';
// [#37440] The two ADR-0008 pins. `draftVersion` rides the BODY,
// beside `message` (the REST door reads it there); `parentVersion`
// rides a HEADER, as on the save and delete doors: a token as
// `If-Match`, `null` as `If-None-Match: *`. Each is omitted when
// unset, so an unpinned publish hands `fetch` the same `init` it
// always did.
const headers = metaPublishHeaders(opts?.parentVersion);
const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/publish${query}`, {
method: 'POST',
body: JSON.stringify(opts?.message ? { message: opts.message } : {}),
...(headers ? { headers } : {}),
body: JSON.stringify({
...(opts?.message ? { message: opts.message } : {}),
...(opts?.draftVersion ? { draftVersion: opts.draftVersion } : {}),
}),
});
return this.unwrapResponse<PublishMetaItemResponse>(res);
},
Expand Down
109 changes: 109 additions & 0 deletions packages/client/src/meta-publish-item-package.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -409,3 +409,112 @@ describe('[#23658] the real publish door: the only draft is another package\'s',
expect(publishRequests[1].packageId).toBe(OTHER_PKG);
}, 60_000);
});

// ---------------------------------------------------------------------------
// Part 3 — [#37440] the two pins: `draftVersion` (the draft) and
// `parentVersion` (the live row)
// ---------------------------------------------------------------------------

describe('[#37440] meta.publishItem pins — what reaches the wire', () => {
it('`draftVersion` rides the body beside `message`; `parentVersion` rides `If-Match`', async () => {
const { client, fetchMock } = createMockClient(PUBLISH_OK);
await client.meta.publishItem('view', 'shared_grid', {
message: 'ship it',
packageId: PKG,
draftVersion: 'draft-token',
parentVersion: 'live-token',
});
expect(bodyOfCall(fetchMock)).toEqual({ message: 'ship it', draftVersion: 'draft-token' });
const headers = fetchMock.mock.calls[0][1].headers as Record<string, string>;
expect(headers['If-Match']).toBe('live-token');
expect(headers).not.toHaveProperty('If-None-Match');
// A body member and a header: neither is put on the query string.
expect(new URL(String(fetchMock.mock.calls[0][0])).search).toBe(`?package=${PKG}`);
});

it('`parentVersion: null` asserts no live row: `If-None-Match: *`, never beside `If-Match`', async () => {
const { client, fetchMock } = createMockClient(PUBLISH_OK);
await client.meta.publishItem('view', 'shared_grid', { parentVersion: null });
const headers = fetchMock.mock.calls[0][1].headers as Record<string, string>;
expect(headers['If-None-Match']).toBe('*');
expect(headers).not.toHaveProperty('If-Match');
expect(bodyOfCall(fetchMock)).toEqual({});
});

it('CONTROL: unset (or empty) pins send nothing — the request an unpinned publish always sent', async () => {
const { client, fetchMock } = createMockClient(PUBLISH_OK);
await client.meta.publishItem('view', 'shared_grid', { draftVersion: '', parentVersion: '' });
await client.meta.publishItem('view', 'shared_grid', { draftVersion: undefined, parentVersion: undefined });
for (let i = 0; i < 2; i++) {
expect(String(fetchMock.mock.calls[i][0])).toBe(PUBLISH_URL);
expect(bodyOfCall(fetchMock, i)).toEqual({});
const headers = fetchMock.mock.calls[i][1].headers as Record<string, string>;
expect(headers).not.toHaveProperty('If-Match');
expect(headers).not.toHaveProperty('If-None-Match');
}
});
});

describe('[#37440] the real publish door: a draft another writer changed in between is never published', () => {
/**
* The caller's draft write (its receipt is its pin), then ANOTHER writer's
* draft write to the same address, landing before the caller's publish.
*/
async function interleaved(client: ObjectStackClient, name: string) {
await client.meta.saveItem('view', name, VIEW(name, 'live'), { packageId: PKG });
const mine = await client.meta.saveItem('view', name, VIEW(name, 'mine'), { packageId: PKG, mode: 'draft' });
await client.meta.saveItem('view', name, VIEW(name, 'theirs'), { packageId: PKG, mode: 'draft' });
return (mine as { version?: string }).version;
}

it('REPRODUCTION — unpinned (all the SDK could send before): the other writer\'s draft goes live', async () => {
const { engine, client } = await bootDoor();
await interleaved(client, 'interleaved_unpinned');
await client.meta.publishItem('view', 'interleaved_unpinned', { packageId: PKG });
expect(await rowsOf(engine, 'interleaved_unpinned')).toEqual([`${PKG}:active:theirs`]);
}, 60_000);

it('PIN — `draftVersion` = the caller\'s own receipt: refused 409 METADATA_CONFLICT, nothing promoted', async () => {
const { engine, client, publishRequests } = await bootDoor();
const mine = await interleaved(client, 'interleaved_pinned');
expect(typeof mine).toBe('string');
const err = await refusalOf(client.meta.publishItem('view', 'interleaved_pinned', { packageId: PKG, draftVersion: mine }));
expect(err.code).toBe('METADATA_CONFLICT');
expect(err.httpStatus).toBe(409);
// The live row stands; the moved draft (the other writer's) stays pending, unpublished.
expect(await rowsOf(engine, 'interleaved_pinned')).toEqual([`${PKG}:active:live`, `${PKG}:draft:theirs`].sort());
expect(publishRequests[0].draftVersion).toBe(mine);
}, 60_000);

it('CONTROL — no interleave: the same pinned publish promotes the caller\'s draft', async () => {
const { engine, client } = await bootDoor();
await client.meta.saveItem('view', 'uninterleaved', VIEW('uninterleaved', 'live'), { packageId: PKG });
const mine = await client.meta.saveItem('view', 'uninterleaved', VIEW('uninterleaved', 'mine'), {
packageId: PKG,
mode: 'draft',
});
const published = await client.meta.publishItem('view', 'uninterleaved', {
packageId: PKG,
draftVersion: (mine as { version?: string }).version,
});
expect(published.success).toBe(true);
expect(await rowsOf(engine, 'uninterleaved')).toEqual([`${PKG}:active:mine`]);
}, 60_000);

it('`parentVersion` pins the live row: a stale token is refused 409, the live token promotes', async () => {
const { engine, client, publishRequests } = await bootDoor();
const first = await client.meta.saveItem('view', 'live_pinned', VIEW('live_pinned', 'live'), { packageId: PKG });
const liveToken = (first as { version?: string }).version;
await client.meta.saveItem('view', 'live_pinned', VIEW('live_pinned', 'mine'), { packageId: PKG, mode: 'draft' });
// `null` asserts no live row — one is stored, so it is refused.
const err = await refusalOf(client.meta.publishItem('view', 'live_pinned', { packageId: PKG, parentVersion: null }));
expect(err.code).toBe('METADATA_CONFLICT');
expect(err.httpStatus).toBe(409);
expect(await rowsOf(engine, 'live_pinned')).toEqual([`${PKG}:active:live`, `${PKG}:draft:mine`].sort());
expect(publishRequests[0].parentVersion).toBeNull();
const published = await client.meta.publishItem('view', 'live_pinned', { packageId: PKG, parentVersion: liveToken });
expect(published.success).toBe(true);
expect(await rowsOf(engine, 'live_pinned')).toEqual([`${PKG}:active:mine`]);
expect(publishRequests[1].parentVersion).toBe(liveToken);
}, 60_000);
});
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ vi.mock('../../assistant/assistantBus', async (importOriginal) => ({

import { saveObjectPins, type ObjectPinsSaveDoors } from '../designModeHeaderPinsSave';
import type { ObjectPins } from '../designModeHeaderPinsModel';
import { draftPublishDoor } from '../../views/__tests__/draftPublishDoor-37440';

const TEXTS = {
notListed: 'not listed',
Expand Down Expand Up @@ -234,3 +235,35 @@ describe('saving the header pins (objectstack#36366)', () => {
expect(calls.at(-1)).toEqual(['reset', 'object', 'crm_lead', { state: 'draft', packageId: 'com.acme.crm' }]);
});
});

describe('the header pins Save publishes only the draft it wrote (objectstack#37440)', () => {
const authored = { name: 'crm_lead', label: 'Lead', actions: [{ name: 'convert', locations: ['record_header'] }] };
function doorDoors() {
const door = draftPublishDoor();
door.seedLive('object', 'crm_lead', 'com.acme.crm', authored);
const d: ObjectPinsSaveDoors = {
listPackages: async () =>
new Map([['com.acme.crm', { id: 'com.acme.crm', name: 'CRM', writable: true, manifest: { version: '1.0.0' } }]]),
ensureCustomization: async (base) => ({ basePackageId: base, packageId: `${base}.custom`, namespace: 'crm_custom', created: false, writable: true }),
client: { ...door.client, get: async () => null, layered: async () => ({ code: authored }) },
};
return { door, d };
}
const pins = { record: { pinned: ['log_call', 'convert'] } };

it("PIN: another writer's draft write between the save and its publish is refused, published by nobody, and kept", async () => {
const { door, d } = doorDoors();
door.interleave('object', 'crm_lead', 'com.acme.crm', { name: 'crm_lead', label: 'theirs' });
await expect(saveObjectPins(input(pins), TEXTS, d)).rejects.toThrow('pending draft');
expect(door.liveOf('object', 'crm_lead', 'com.acme.crm')).toEqual(authored);
expect(door.draftOf('object', 'crm_lead', 'com.acme.crm')).toEqual({ name: 'crm_lead', label: 'theirs' });
expect(door.calls.find(([c]) => c === 'publish')?.[3]).toMatchObject({ draftVersion: expect.any(String) });
});

it('CONTROL: with no write in between, the same pinned publish takes the pins live', async () => {
const { door, d } = doorDoors();
await saveObjectPins(input(pins), TEXTS, d);
expect(door.liveOf('object', 'crm_lead', 'com.acme.crm')).toEqual({ ...authored, actionLayout: pins });
expect(door.draftOf('object', 'crm_lead', 'com.acme.crm')).toBeUndefined();
});
});
Loading
Loading