Skip to content

Commit dfff8c3

Browse files
authored
refactor(workflow-code): simplify the source dir lock release and drop casts from the QA fixes (#10276)
Removes the source directory lock and uninstalls its interrupt release in one synchronous step (replacing three layered fixes), types the block rename rewrite by its input, writes the column strip without a cast, builds the loop fixture from a parameter, and folds a few single-use helpers. Behaviour is unchanged apart from the lock never being left half removed.
1 parent 07938f0 commit dfff8c3

12 files changed

Lines changed: 71 additions & 108 deletions

File tree

‎apps/sim/lib/table/columns/service.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import { userTableDefinitions, userTableRows } from '@sim/db/schema'
2020
import { createLogger } from '@sim/logger'
2121
import { resolveCurrencyCode } from '@sim/table-cells/currency'
2222
import { omit } from '@sim/utils/object'
23-
import { and, asc, count, eq, gt, type SQL, sql } from 'drizzle-orm'
23+
import { and, asc, count, eq, gt, sql } from 'drizzle-orm'
2424
import { OrchestrationError } from '@/lib/core/orchestration/types'
2525
import { columnMatchesRef, generateColumnId, getColumnId } from '@/lib/table/column-keys'
2626
import {
@@ -395,10 +395,7 @@ async function stripColumnData(
395395
columnIds: string[]
396396
): Promise<void> {
397397
await updateTableRowsWithDerivedSecretProvenance(trx, {
398-
rowWhere: and(
399-
eq(userTableRows.tableId, tableId),
400-
eq(userTableRows.workspaceId, workspaceId)
401-
) as SQL,
398+
rowWhere: sql`${userTableRows.tableId} = ${tableId} and ${userTableRows.workspaceId} = ${workspaceId}`,
402399
transformation: { mode: 'remove-columns', columnIds },
403400
})
404401
}

‎apps/sim/lib/workflows/editing/operations.test.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ mockGetBlock.mockImplementation((type: string) => MOCK_REGISTRY_BLOCKS[type])
166166

167167
vi.mock('@/lib/integrations/availability.server', () => integrationsAvailabilityMock)
168168

169-
function makeLoopWorkflow() {
169+
function makeLoopWorkflow(loopData: Record<string, unknown> = { loopType: 'for', count: 5 }) {
170170
return {
171171
blocks: {
172172
'loop-1': {
@@ -177,7 +177,7 @@ function makeLoopWorkflow() {
177177
enabled: true,
178178
subBlocks: {},
179179
outputs: {},
180-
data: { loopType: 'for', count: 5 },
180+
data: loopData,
181181
},
182182
'condition-1': {
183183
id: 'condition-1',
@@ -691,8 +691,7 @@ describe('a block rename', () => {
691691
})
692692

693693
it('rewrites references a loop holds in its collection and conditions, and in the loop record', () => {
694-
const workflow = makeLoopWorkflow()
695-
Object.assign(workflow.blocks['loop-1'].data, {
694+
const workflow = makeLoopWorkflow({
696695
loopType: 'forEach',
697696
collection: '<agent1.items>',
698697
whileCondition: '<agent1.more> === true',

‎apps/sim/lib/workflows/editing/operations.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ function renameBlock(blocks: Record<string, BlockState>, blockId: string, name:
8181
if (id === blockId) continue
8282
for (const subBlock of Object.values(block.subBlocks ?? {})) {
8383
if (subBlock.value === undefined || subBlock.value === null) continue
84-
subBlock.value = rewriteBlockNameReferences(subBlock.value, nameMap) as typeof subBlock.value
84+
subBlock.value = rewriteBlockNameReferences(subBlock.value, nameMap)
8585
}
8686
const data = block.data
8787
if (!data || (block.type !== 'loop' && block.type !== 'parallel')) continue

‎apps/sim/lib/workflows/references/block-rename.ts‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@ import { escapeRegExp } from '@sim/utils/string'
22

33
/**
44
* `value` with every `<oldName.` reference token rewritten to `<newName.` for each entry of
5-
* `nameMap` (normalized block names), recursing through arrays and objects. The editor's rename,
6-
* an operations-batch rename, and a workflow import all rewrite block references through this.
5+
* `nameMap` (normalized block names), recursing through arrays and objects; the result has the
6+
* shape `value` had. The editor's rename, an operations-batch rename, and a workflow import all
7+
* rewrite block references through this.
78
*/
8-
export function rewriteBlockNameReferences(
9-
value: unknown,
10-
nameMap: ReadonlyMap<string, string>
11-
): unknown {
9+
export function rewriteBlockNameReferences<T>(value: T, nameMap: ReadonlyMap<string, string>): T {
10+
return rewrite(value, nameMap) as T
11+
}
12+
13+
function rewrite(value: unknown, nameMap: ReadonlyMap<string, string>): unknown {
1214
if (typeof value === 'string') {
1315
let updatedValue = value
1416
nameMap.forEach((newName, oldName) => {
@@ -34,12 +36,12 @@ export function rewriteBlockNameReferences(
3436
return updatedValue
3537
}
3638
if (Array.isArray(value)) {
37-
return value.map((item) => rewriteBlockNameReferences(item, nameMap))
39+
return value.map((item) => rewrite(item, nameMap))
3840
}
3941
if (value && typeof value === 'object') {
4042
const result: Record<string, unknown> = {}
4143
for (const [key, val] of Object.entries(value)) {
42-
result[key] = rewriteBlockNameReferences(val, nameMap)
44+
result[key] = rewrite(val, nameMap)
4345
}
4446
return result
4547
}

‎apps/sim/lib/workspace-source/application/errors.ts‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,21 @@ export function isRefusal(error: unknown): error is OrchestrationError {
9595
)
9696
}
9797

98+
/** What to do about a name or key another resource holds, by what holds it and where it is declared. */
99+
function nameTakenHint(error: unknown, kind: WorkspaceKind): string {
100+
if (error instanceof ResourceKeyTakenError) {
101+
return 'Rename the key, or delete the resource that holds it.'
102+
}
103+
if (error instanceof WorkspaceFileFolderConflictError) {
104+
return 'Rename that folder in the file paths locally, or rename or delete the folder that holds the name in Sim.'
105+
}
106+
// A file has no declaration: its name is its path in the directory.
107+
if (kind === 'file') {
108+
return 'Rename it locally, or rename or delete the file that holds the name in Sim.'
109+
}
110+
return 'Rename it in its declaration, or rename or delete the resource that holds the name in Sim.'
111+
}
112+
98113
/**
99114
* A child use case's refusal as a finding about one resource: a resource (or a table's rows)
100115
* changed since the plan read it is `E_APPLY_STALE`, forbidden is `E_APPLY_FORBIDDEN`,
@@ -131,14 +146,7 @@ export function refusalDiagnostic(
131146
}
132147
if (error instanceof ResourceKeyTakenError || isNameTaken(error)) {
133148
return finding('E_NAME_TAKEN', error.message, {
134-
hint:
135-
error instanceof ResourceKeyTakenError
136-
? 'Rename the key, or delete the resource that holds it.'
137-
: error instanceof WorkspaceFileFolderConflictError
138-
? 'Rename that folder in the file paths locally, or rename or delete the folder that holds the name in Sim.'
139-
: resource.kind === 'file'
140-
? 'Rename it locally, or rename or delete the file that holds the name in Sim.'
141-
: 'Rename it in its declaration, or rename or delete the resource that holds the name in Sim.',
149+
hint: nameTakenHint(error, resource.kind),
142150
...resource,
143151
})
144152
}

‎apps/sim/stores/workflows/utils.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -161,10 +161,7 @@ function updateBlockReferences(
161161
}
162162

163163
if (subBlock.value !== undefined && subBlock.value !== null) {
164-
const updatedValue = rewriteBlockNameReferences(
165-
subBlock.value,
166-
nameMap
167-
) as SubBlockState['value']
164+
const updatedValue = rewriteBlockNameReferences(subBlock.value, nameMap)
168165
block.subBlocks[subBlockId] = { ...subBlock, value: updatedValue }
169166
}
170167
})

‎packages/sim-cli/src/commands/protocol/source-check.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -560,13 +560,9 @@ export async function checkWorkflowDir(
560560
if (finding.code !== 'W_UNKNOWN_OPTION' || blockKey === undefined || param === undefined) {
561561
return false
562562
}
563-
return optionsVaryOn(blockKey, (id) => id === param)
564-
}
565-
/** Whether a field of block `blockKey` that `matches` takes options varying by deployment. */
566-
const optionsVaryOn = (blockKey: string, matches: (subBlockId: string) => boolean) => {
567563
const type = compiled.workflow ? getOwn(compiled.workflow.blocks, blockKey)?.type : undefined
568564
const block = type === undefined ? undefined : catalogBlock(compiledDir.catalog, type)
569-
return block?.subBlocks.some((sub) => matches(sub.id) && sub.optionsVary === true) === true
565+
return block?.subBlocks.some((sub) => sub.id === param && sub.optionsVary === true) === true
570566
}
571567
const exempt = (finding: (typeof compiled.diagnostics)[number]) =>
572568
mayBeRenamed(finding) || variesByDeployment(finding)

‎packages/sim-cli/src/commands/protocol/source-dir-lock-release.test.ts‎

Lines changed: 22 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,24 @@
1-
import {
2-
existsSync,
3-
mkdirSync,
4-
mkdtempSync,
5-
realpathSync,
6-
rmSync,
7-
symlinkSync,
8-
writeFileSync,
9-
} from 'node:fs'
1+
import { existsSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs'
102
import { tmpdir } from 'node:os'
113
import { join } from 'node:path'
124
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
135

14-
/** What each installed interrupt release would remove, read when the signal arrives. */
15-
const signalTargets: Array<() => string | null> = []
6+
/** Each installed interrupt release: what it would remove, and whether the lock was there when it was uninstalled. */
7+
const releases: Array<{ target: () => string | null; lockAtDispose?: boolean }> = []
8+
let lockPath = ''
169

1710
vi.mock('./files-get', async (importOriginal) => {
1811
const actual = await importOriginal<typeof import('./files-get')>()
1912
return {
2013
...actual,
2114
removeStagingOnSignal: (target: () => string | null) => {
22-
signalTargets.push(target)
23-
return actual.removeStagingOnSignal(target)
15+
const release: (typeof releases)[number] = { target }
16+
releases.push(release)
17+
const dispose = actual.removeStagingOnSignal(target)
18+
return () => {
19+
release.lockAtDispose = existsSync(lockPath)
20+
dispose()
21+
}
2422
},
2523
}
2624
})
@@ -31,7 +29,8 @@ let dir: string
3129

3230
beforeEach(() => {
3331
dir = realpathSync(mkdtempSync(join(tmpdir(), 'sim-source-lock-release-')))
34-
signalTargets.length = 0
32+
lockPath = join(dir, SOURCE_DIR_LOCK)
33+
releases.length = 0
3534
})
3635

3736
afterEach(() => {
@@ -42,42 +41,26 @@ describe('the interrupt release of a directory lock', () => {
4241
it('targets the lock while the command holds it', async () => {
4342
let held: string | null = null
4443
await withSourceDirLock(dir, async () => {
45-
held = signalTargets[0]?.() ?? null
44+
held = releases[0]?.target() ?? null
4645
})
4746

48-
expect(held).toBe(join(dir, SOURCE_DIR_LOCK))
47+
expect(held).toBe(lockPath)
4948
})
5049

51-
it('targets nothing once the command removed its lock, so an interrupt during the rest of its cleanup leaves the next command’s lock', async () => {
52-
await withSourceDirLock(join(dir, 'out/a'), async () => {})
53-
const next = join(dir, 'out/a', SOURCE_DIR_LOCK)
54-
mkdirSync(next, { recursive: true })
50+
it('is uninstalled only once the lock is gone, so it never outlives the lock it removes', async () => {
51+
await withSourceDirLock(dir, async () => {})
5552

56-
expect(signalTargets[0]?.()).toBeNull()
57-
writeFileSync(join(next, 'owner.json'), JSON.stringify({ pid: process.pid + 1, host: 'other' }))
58-
expect(signalTargets[0]?.()).toBeNull()
59-
expect(existsSync(next)).toBe(true)
53+
expect(releases).toHaveLength(1)
54+
expect(releases[0].lockAtDispose).toBe(false)
6055
})
6156

62-
it('targets nothing when the lock at the path names another command', async () => {
63-
let target: string | null = 'unread'
64-
await withSourceDirLock(dir, async () => {
65-
writeFileSync(
66-
join(dir, SOURCE_DIR_LOCK, 'owner.json'),
67-
JSON.stringify({ pid: process.pid + 1, host: 'other' })
68-
)
69-
target = signalTargets[0]?.() ?? null
70-
})
71-
72-
expect(target).toBeNull()
73-
})
74-
it('uninstalls the interrupt release even when removing the lock fails', async () => {
57+
it('is uninstalled even when removing the lock fails', async () => {
7558
const listening = process.listenerCount('SIGINT')
7659
const outside = realpathSync(mkdtempSync(join(tmpdir(), 'sim-source-lock-outside-')))
7760

7861
const failed = withSourceDirLock(dir, async () => {
79-
rmSync(join(dir, SOURCE_DIR_LOCK), { recursive: true, force: true })
80-
symlinkSync(outside, join(dir, SOURCE_DIR_LOCK))
62+
rmSync(lockPath, { recursive: true, force: true })
63+
symlinkSync(outside, lockPath)
8164
})
8265

8366
await expect(failed).rejects.toMatchObject({ code: 'SOURCE_SYMLINK' })

‎packages/sim-cli/src/commands/protocol/source-dir/command-lock.ts‎

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
* rewrites the directory, so two commands on it never interleave their writes.
44
*/
55

6-
import { readFileSync, type Stats } from 'node:fs'
6+
import { rmSync, type Stats } from 'node:fs'
77
import { lstat, mkdir, readFile, realpath, rm, rmdir, stat, writeFile } from 'node:fs/promises'
88
import { hostname } from 'node:os'
99
import { dirname, join, resolve } from 'node:path'
@@ -183,38 +183,25 @@ export async function withSourceDirLock<T>(
183183
}
184184
const owner: LockOwner = { pid: process.pid, host: hostname() }
185185
// An interrupt (Ctrl-C) releases the lock too: a lock left behind is taken over only by a
186-
// command on the same host, so one left on a folder shared with a container would stay.
187-
// Once this command removes its lock the path may become another command's, which an interrupt
188-
// must leave alone: past the owner record, the release removes the lock only while it still
189-
// names this command.
190-
let ownerRecorded = false
191-
const ownedLock = (): string | null => {
192-
if (!ownerRecorded) return lock
193-
try {
194-
const recorded = toRecord(JSON.parse(readFileSync(join(lock, LOCK_OWNER_FILE), 'utf8')))
195-
return recorded.pid === owner.pid && recorded.host === owner.host ? lock : null
196-
} catch {
197-
return null
198-
}
199-
}
200-
const disposeSignalRelease = removeStagingOnSignal(ownedLock)
186+
// command on the same host, so one left on a folder shared with a container would stay. The
187+
// release stays installed until the lock is gone, since an interrupt a deferred write held is
188+
// raised again as `run` ends and would otherwise end the process mid-removal.
189+
const disposeSignalRelease = removeStagingOnSignal(() => lock)
201190
try {
202191
await writeFile(join(lock, LOCK_OWNER_FILE), JSON.stringify(owner))
203-
ownerRecorded = true
204192
return await run()
205193
} finally {
206-
// The signal release stays installed until the lock is gone: an interrupt a deferred write
207-
// held is raised again as `run` ends, and with no handler it would end the process mid-removal.
194+
// An interrupt is handled only between turns of the event loop, so removing the lock and
195+
// uninstalling its release in one synchronous step leaves no turn in which the release could
196+
// remove a lock another command took after this one, or find this one half removed.
208197
try {
209-
await rm(await checkedPath(root, SOURCE_DIR_LOCK, new Set()), {
210-
recursive: true,
211-
force: true,
212-
})
213-
// Folders the lock alone created go with it; one the command filled stays.
214-
await removeCreatedFolders()
198+
const held = await checkedPath(root, SOURCE_DIR_LOCK, new Set())
199+
rmSync(held, { recursive: true, force: true })
215200
} finally {
216201
disposeSignalRelease()
217202
}
203+
// Folders the lock alone created go with it; one the command filled stays.
204+
await removeCreatedFolders()
218205
}
219206
}
220207

‎packages/sim-cli/src/commands/protocol/source-exit-codes.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,7 @@ function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRow[] {
6969
},
7070
{
7171
code: 1,
72-
meaning:
73-
prefix === 'sim workspaces source'
74-
? 'The source has errors (each printed as `file:line:column` with a hint), a locked block (`E_APPLY_LOCKED_BLOCK`), a name another resource holds (`E_NAME_TAKEN`), a cancelled prompt, or the command failed'
75-
: 'The source has errors (each printed as `file:line:column` with a hint), a locked block (`E_APPLY_LOCKED_BLOCK`), a name another workflow holds (`SOURCE_NAME_TAKEN`), a cancelled prompt, or the command failed',
72+
meaning: `The source has errors (each printed as \`file:line:column\` with a hint), a locked block (\`E_APPLY_LOCKED_BLOCK\`), ${prefix === 'sim workspaces source' ? 'a name another resource holds (`E_NAME_TAKEN`)' : 'a name another workflow holds (`SOURCE_NAME_TAKEN`)'}, a cancelled prompt, or the command failed`,
7673
next: 'Fix what it printed and run it again',
7774
help: {
7875
'workflows source apply':

0 commit comments

Comments
 (0)