|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// `rollbackToPackageCommit` carries every item a `revertCommit` step refused |
| 4 | +// into its own `failed[]`, and answers `success: false` for it. |
| 5 | +// |
| 6 | +// A package rollback is a loop of `revertCommit` calls, newest commit first. |
| 7 | +// `revertCommit` reports an item it refuses — here the restore of a row stored |
| 8 | +// under a non-canonical type, `STORED_TYPE_NOT_CANONICAL` — in its RETURNED |
| 9 | +// per-item `failed[]`; it does not throw. The rollback read only a thrown |
| 10 | +// error, so it dropped the returned refusals and answered `success: true` for |
| 11 | +// a package left half rolled back, naming nothing it had left in place. |
| 12 | +// |
| 13 | +// The declared answer (`RollbackToPackageCommitResponseSchema`) says |
| 14 | +// `success` is "True exactly when nothing failed", and each `failed[]` entry |
| 15 | +// is `{ commitId, error }`. A refused item therefore lands as one entry: the |
| 16 | +// commit it belongs to, and an `error` that names the item (`type/name`) and |
| 17 | +// quotes `revertCommit`'s client-facing refusal text. |
| 18 | +// |
| 19 | +// Driven over the real `SysMetadataRepository`, with the commit ledger served |
| 20 | +// by the engine double so `listCommits` plans the rollback itself. |
| 21 | + |
| 22 | +import { afterEach, describe, expect, it, vi } from 'vitest'; |
| 23 | +// [#5619] The producer's OWN write-verb dispatch decisions, from |
| 24 | +// `@objectstack/metadata-core` — objectql depends on this package. |
| 25 | +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; |
| 26 | +import { ObjectStackProtocolImplementation } from './protocol.js'; |
| 27 | + |
| 28 | +interface Row { |
| 29 | + id: string; |
| 30 | + type: string; |
| 31 | + name: string; |
| 32 | + organization_id: string | null; |
| 33 | + package_id: string | null; |
| 34 | + state: string; |
| 35 | + metadata: string; |
| 36 | +} |
| 37 | + |
| 38 | +interface HistoryRow { |
| 39 | + id: string; |
| 40 | + type: string; |
| 41 | + name: string; |
| 42 | + version: number; |
| 43 | + organization_id: string | null; |
| 44 | + operation_type: string; |
| 45 | +} |
| 46 | + |
| 47 | +const PKG = 'app.demo'; |
| 48 | + |
| 49 | +/** ADR-0048 overlay key — (type, name, org, state, package_id). */ |
| 50 | +const keyOf = (w: Record<string, unknown>) => |
| 51 | + `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; |
| 52 | + |
| 53 | +function matchesWhere(r: Record<string, unknown>, where: Record<string, unknown>): boolean { |
| 54 | + for (const [k, v] of Object.entries(where)) { |
| 55 | + if (k === '$or') { |
| 56 | + if (!(v as Array<Record<string, unknown>>).some((c) => matchesWhere(r, c))) return false; |
| 57 | + continue; |
| 58 | + } |
| 59 | + if (k.startsWith('$')) throw new Error(`test double: unsupported combinator '${k}'`); |
| 60 | + if (v === undefined) continue; |
| 61 | + if ((r[k] ?? null) !== v) return false; |
| 62 | + } |
| 63 | + return true; |
| 64 | +} |
| 65 | + |
| 66 | +/** One `apply` commit row in the driver's snake_case wire shape. */ |
| 67 | +const applyCommit = (id: string, createdAt: string, items: unknown[]) => ({ |
| 68 | + id, |
| 69 | + package_id: PKG, |
| 70 | + organization_id: null, |
| 71 | + operation: 'apply', |
| 72 | + message: `commit ${id}`, |
| 73 | + item_count: items.length, |
| 74 | + created_at: createdAt, |
| 75 | + items: JSON.stringify(items), |
| 76 | +}); |
| 77 | + |
| 78 | +function makeProtocol(opts: { unreadableCommits?: readonly string[] } = {}) { |
| 79 | + const rows = new Map<string, Row>(); |
| 80 | + const historyRows: HistoryRow[] = []; |
| 81 | + const commits: Array<Record<string, unknown>> = []; |
| 82 | + const unreadable = new Set(opts.unreadableCommits ?? []); |
| 83 | + let nextId = 0; |
| 84 | + |
| 85 | + const findRow = (w: Record<string, unknown>): { key: string; row: Row } | null => { |
| 86 | + if (w.id !== undefined) { |
| 87 | + for (const [k, r] of rows) if (r.id === w.id) return { key: k, row: r }; |
| 88 | + return null; |
| 89 | + } |
| 90 | + for (const [k, r] of rows) if (matchesWhere(r as any, w)) return { key: k, row: r }; |
| 91 | + return null; |
| 92 | + }; |
| 93 | + const matchesHistory = (h: HistoryRow, w: Record<string, unknown>): boolean => |
| 94 | + (['organization_id', 'type', 'name', 'version', 'operation_type'] as const) |
| 95 | + .every((k) => w[k] === undefined || h[k] === w[k]); |
| 96 | + |
| 97 | + const engine: any = { |
| 98 | + async findOne(table: string, o: { where: Record<string, unknown> }) { |
| 99 | + assertEngineFindOnePredicate(table, o); |
| 100 | + if (table === 'sys_metadata_commit') { |
| 101 | + // A commit the ledger LISTS but whose own read answers nothing — |
| 102 | + // the inner `revertCommit` then throws `COMMIT_NOT_FOUND`. |
| 103 | + if (unreadable.has(String(o.where.id))) return null; |
| 104 | + return commits.find((c) => c.id === o.where.id) ?? null; |
| 105 | + } |
| 106 | + if (table === 'sys_metadata_history') { |
| 107 | + return historyRows.find((h) => matchesHistory(h, o.where)) ?? null; |
| 108 | + } |
| 109 | + if (table !== 'sys_metadata') return null; |
| 110 | + return findRow(o.where)?.row ?? null; |
| 111 | + }, |
| 112 | + async find(table: string, o?: { where?: Record<string, unknown>; limit?: number }) { |
| 113 | + const matched: unknown[] = |
| 114 | + table === 'sys_metadata_commit' |
| 115 | + ? commits.filter((c) => c.package_id === o?.where?.package_id) |
| 116 | + : table === 'sys_metadata_history' |
| 117 | + ? historyRows.filter((h) => matchesHistory(h, o?.where ?? {})) |
| 118 | + : table === 'sys_metadata' |
| 119 | + ? Array.from(rows.values()).filter((r) => matchesWhere(r as any, o?.where ?? {})) |
| 120 | + : []; |
| 121 | + return typeof o?.limit === 'number' ? matched.slice(0, o.limit) : matched; |
| 122 | + }, |
| 123 | + async insert(table: string, data: Record<string, unknown>) { |
| 124 | + nextId += 1; |
| 125 | + if (table === 'sys_metadata_commit') { |
| 126 | + commits.push({ ...data }); |
| 127 | + return { id: String(data.id ?? `cm_${nextId}`) }; |
| 128 | + } |
| 129 | + if (table === 'sys_metadata_history') { |
| 130 | + const h = { ...(data as unknown as HistoryRow), id: `h_${nextId}` }; |
| 131 | + historyRows.push(h); |
| 132 | + return { id: h.id }; |
| 133 | + } |
| 134 | + if (table !== 'sys_metadata') return { id: 'side_effect_skip' }; |
| 135 | + const row = { ...(data as unknown as Row), id: `r_${nextId}` }; |
| 136 | + rows.set(keyOf(data), row); |
| 137 | + return { id: row.id }; |
| 138 | + }, |
| 139 | + async update(_t: string, data: Record<string, unknown>, o: { where: Record<string, unknown> }) { |
| 140 | + assertEngineUpdateDispatch(data, o); |
| 141 | + const found = findRow(o.where); |
| 142 | + if (!found) return { id: null }; |
| 143 | + const merged = { ...found.row, ...(data as unknown as Row) }; |
| 144 | + rows.delete(found.key); |
| 145 | + rows.set(keyOf(merged), merged); |
| 146 | + return { id: found.row.id }; |
| 147 | + }, |
| 148 | + async delete(_t: string, o: { where: Record<string, unknown> }) { |
| 149 | + assertEngineDeleteDispatch(o); |
| 150 | + const found = findRow(o.where); |
| 151 | + if (!found) return { deleted: 0 }; |
| 152 | + rows.delete(found.key); |
| 153 | + return { deleted: 1 }; |
| 154 | + }, |
| 155 | + async transaction<T>(cb: (ctx: unknown, info: { owned: boolean }) => Promise<T>): Promise<T> { |
| 156 | + return cb(undefined, { owned: true }); |
| 157 | + }, |
| 158 | + async syncObjectSchema() { return true; }, |
| 159 | + async dropObjectSchema() { return true; }, |
| 160 | + registry: { |
| 161 | + registerItem: () => undefined, |
| 162 | + registerObject: () => undefined, |
| 163 | + listItems: () => [], |
| 164 | + getItem: () => undefined, |
| 165 | + getObject: () => undefined, |
| 166 | + getPackage: () => undefined, |
| 167 | + getArtifactItem: () => undefined, |
| 168 | + removeRuntimeShadow: () => false, |
| 169 | + removeOverlayEntry: () => undefined, |
| 170 | + }, |
| 171 | + }; |
| 172 | + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map(), undefined) as any; |
| 173 | + return { protocol, rows, commits }; |
| 174 | +} |
| 175 | + |
| 176 | +/** Write a row through the repository, which stores `type` exactly as given. */ |
| 177 | +async function seed(protocol: any, type: string, name: string, label: string): Promise<void> { |
| 178 | + await protocol.ensureOverlayIndex(); |
| 179 | + const repo = protocol.getOverlayRepo(null); |
| 180 | + const ref = { type, name, org: 'env' }; |
| 181 | + const existing = await repo.get(ref, { state: 'active' }); |
| 182 | + await repo.put(ref, { name, label }, { |
| 183 | + parentVersion: existing?.hash ?? null, |
| 184 | + actor: null, |
| 185 | + source: 'test.rollback-item-failures', |
| 186 | + intent: 'runtime-only', |
| 187 | + state: 'active', |
| 188 | + }); |
| 189 | +} |
| 190 | + |
| 191 | +const stored = (rows: Map<string, Row>, type: string, name: string): any => { |
| 192 | + for (const r of rows.values()) if (r.type === type && r.name === name) return JSON.parse(r.metadata); |
| 193 | + return undefined; |
| 194 | +}; |
| 195 | + |
| 196 | +/** |
| 197 | + * The package's history: target `c0`; `c1` created `view/created_in_c1`; |
| 198 | + * `c2` created `view/created_in_c2`, edited `view/grid` (V1 → V2) and edited |
| 199 | + * `fields/a.b` (V1 → V2). The `fields` row is stored under the non-canonical |
| 200 | + * type, so `revertCommit` refuses to restore it (`STORED_TYPE_NOT_CANONICAL`). |
| 201 | + */ |
| 202 | +async function seedPackage(protocol: any, commits: Array<Record<string, unknown>>, opts: { refusedItem: boolean }) { |
| 203 | + await seed(protocol, 'view', 'grid', 'V1'); |
| 204 | + await seed(protocol, 'view', 'grid', 'V2'); |
| 205 | + await seed(protocol, 'view', 'created_in_c1', 'C1'); |
| 206 | + await seed(protocol, 'view', 'created_in_c2', 'C2'); |
| 207 | + if (opts.refusedItem) { |
| 208 | + await seed(protocol, 'fields', 'a.b', 'V1'); |
| 209 | + await seed(protocol, 'fields', 'a.b', 'V2'); |
| 210 | + } |
| 211 | + commits.push( |
| 212 | + applyCommit('c0', '2026-01-01T00:00:00Z', []), |
| 213 | + applyCommit('c1', '2026-01-02T00:00:00Z', [ |
| 214 | + { type: 'view', name: 'created_in_c1', existedBefore: false, prevVersion: null }, |
| 215 | + ]), |
| 216 | + applyCommit('c2', '2026-01-03T00:00:00Z', [ |
| 217 | + { type: 'view', name: 'grid', existedBefore: true, prevVersion: 1 }, |
| 218 | + ...(opts.refusedItem ? [{ type: 'fields', name: 'a.b', existedBefore: true, prevVersion: 1 }] : []), |
| 219 | + { type: 'view', name: 'created_in_c2', existedBefore: false, prevVersion: null }, |
| 220 | + ]), |
| 221 | + ); |
| 222 | +} |
| 223 | + |
| 224 | +afterEach(() => { |
| 225 | + vi.restoreAllMocks(); |
| 226 | +}); |
| 227 | + |
| 228 | +describe('rollbackToPackageCommit carries the items a revert step refused', () => { |
| 229 | + it('answers `success: false` and names the commit, the item and the refusal text', async () => { |
| 230 | + vi.spyOn(console, 'warn').mockImplementation(() => undefined); |
| 231 | + const { protocol, rows, commits } = makeProtocol(); |
| 232 | + await seedPackage(protocol, commits, { refusedItem: true }); |
| 233 | + |
| 234 | + // What the inner step itself reports for the refused item — the text |
| 235 | + // the rollback must carry. |
| 236 | + const refusal = 'is stored under the non-canonical metadata type \'fields\''; |
| 237 | + |
| 238 | + const res = await protocol.rollbackToPackageCommit({ commitId: 'c0' }); |
| 239 | + |
| 240 | + expect(res.success).toBe(false); |
| 241 | + expect(res.failed).toHaveLength(1); |
| 242 | + expect(Object.keys(res.failed[0]).sort()).toEqual(['commitId', 'error']); |
| 243 | + expect(res.failed[0].commitId).toBe('c2'); |
| 244 | + expect(res.failed[0].error).toContain('fields/a.b'); |
| 245 | + expect(res.failed[0].error).toContain(refusal); |
| 246 | + expect(res.failed[0].error).toContain('PUT /meta/field/a.b'); |
| 247 | + |
| 248 | + // Everything else is rolled back as before: both commits are reverted |
| 249 | + // (each step records its own revert commit) and the neighbours of the |
| 250 | + // refused item are undone. |
| 251 | + expect([...res.revertedCommits].sort()).toEqual(['c1', 'c2']); |
| 252 | + expect(stored(rows, 'view', 'created_in_c1')).toBeUndefined(); |
| 253 | + expect(stored(rows, 'view', 'created_in_c2')).toBeUndefined(); |
| 254 | + expect(stored(rows, 'view', 'grid')?.label).toBe('V1'); |
| 255 | + // The refused item stayed as it was. |
| 256 | + expect(stored(rows, 'fields', 'a.b')?.label).toBe('V2'); |
| 257 | + }); |
| 258 | + |
| 259 | + it('control: an all-clean rollback answers `success: true` with an empty `failed[]`', async () => { |
| 260 | + const { protocol, rows, commits } = makeProtocol(); |
| 261 | + await seedPackage(protocol, commits, { refusedItem: false }); |
| 262 | + |
| 263 | + const res = await protocol.rollbackToPackageCommit({ commitId: 'c0' }); |
| 264 | + |
| 265 | + expect(res).toEqual({ success: true, revertedCommits: expect.any(Array), failed: [] }); |
| 266 | + expect([...res.revertedCommits].sort()).toEqual(['c1', 'c2']); |
| 267 | + expect(stored(rows, 'view', 'grid')?.label).toBe('V1'); |
| 268 | + }); |
| 269 | + |
| 270 | + it('control: a commit whose revert throws still lands in `failed[]`, and the next commit is still reverted', async () => { |
| 271 | + vi.spyOn(console, 'warn').mockImplementation(() => undefined); |
| 272 | + const { protocol, rows, commits } = makeProtocol({ unreadableCommits: ['c2'] }); |
| 273 | + await seedPackage(protocol, commits, { refusedItem: false }); |
| 274 | + |
| 275 | + const res = await protocol.rollbackToPackageCommit({ commitId: 'c0' }); |
| 276 | + |
| 277 | + expect(res.success).toBe(false); |
| 278 | + expect(res.failed).toEqual([{ commitId: 'c2', error: "No commit 'c2'." }]); |
| 279 | + expect(res.revertedCommits).toEqual(['c1']); |
| 280 | + expect(stored(rows, 'view', 'created_in_c1')).toBeUndefined(); |
| 281 | + expect(stored(rows, 'view', 'grid')?.label).toBe('V2'); |
| 282 | + }); |
| 283 | +}); |
0 commit comments