Repository navigation
Expand file tree
/
Copy pathstore.ts
More file actions
312 lines (292 loc) · 9.19 KB
/
Copy pathstore.ts
File metadata and controls
312 lines (292 loc) · 9.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import { createLogger } from '@sim/logger'
import { toError } from '@sim/utils/errors'
import { generateShortId } from '@sim/utils/id'
import { truncate } from '@sim/utils/string'
import { cacheLargeValue, materializeLargeValueRefSync } from '@/lib/execution/payloads/cache'
import { collectLargeValueKeys } from '@/lib/execution/payloads/large-execution-value'
import {
LARGE_VALUE_REF_VERSION,
type LargeValueKind,
type LargeValueRef,
} from '@/lib/execution/payloads/large-value-ref'
import {
MAX_DURABLE_LARGE_VALUE_BYTES,
MAX_TRACE_ARCHIVE_BYTES,
} from '@/lib/execution/payloads/limits'
import {
assertDurableLargeValueSize,
assertInlineMaterializationSize,
assertLargeValueRefAccess,
isValidLargeValueKey,
readLargeValueRefFromStorage,
} from '@/lib/execution/payloads/materialization.server'
import { generateLargeValuePayloadKey } from '@/lib/uploads/contexts/execution/utils'
const logger = createLogger('LargeExecutionPayloadStore')
export interface LargeValueStoreContext {
workspaceId?: string
workflowId?: string
executionId?: string
largeValueExecutionIds?: string[]
largeValueKeys?: string[]
fileKeys?: string[]
allowLargeValueWorkflowScope?: boolean
userId?: string
requireDurable?: boolean
maxBytes?: number
/**
* When false, materialization does not register an execution_log reference for
* the key. Read-only consumers (e.g. viewing/exporting a completed log) set
* this: the value is already owned + referenced by its own execution, so
* re-registering on every read is wasteful and a needless failure point.
*/
trackReference?: boolean
}
function getKind(value: unknown): LargeValueKind {
if (typeof value === 'string') return 'string'
if (Array.isArray(value)) return 'array'
if (value && typeof value === 'object') return 'object'
return 'json'
}
function getPreview(value: unknown): unknown {
if (typeof value === 'string') {
return truncate(value, 256)
}
if (Array.isArray(value)) {
return { length: value.length }
}
if (value && typeof value === 'object') {
return { keys: Object.keys(value).slice(0, 20) }
}
return value
}
async function persistValue(
id: string,
json: string,
context: LargeValueStoreContext
): Promise<string | undefined> {
const { workspaceId, workflowId, executionId, userId } = context
if (!workspaceId || !workflowId || !executionId) {
if (context.requireDurable) {
throw new Error(
'Cannot persist large execution value without workspace, workflow, and execution IDs'
)
}
return undefined
}
const key = generateLargeValuePayloadKey({ workspaceId, workflowId, executionId }, id)
try {
const { StorageService } = await import('@/lib/uploads')
const fileInfo = await StorageService.uploadFile({
file: Buffer.from(json, 'utf8'),
fileName: key,
contentType: 'application/json',
context: 'execution',
preserveKey: true,
customKey: key,
cleanupOnMetadataFailure: true,
metadata: {
originalName: `large-value-${id}.json`,
uploadedAt: new Date().toISOString(),
purpose: 'execution-large-value',
workspaceId,
...(userId ? { userId } : {}),
},
})
return fileInfo.key
} catch (error) {
if (context.requireDurable) {
throw new Error(`Failed to persist large execution value: ${toError(error).message}`, {
cause: error,
})
}
logger.warn('Failed to persist large execution value, keeping in memory only', {
id,
error: toError(error).message,
})
return undefined
}
}
async function registerPersistedValueOwner(
key: string | undefined,
size: number,
referencedKeys: string[],
context: LargeValueStoreContext
): Promise<boolean> {
const { workspaceId, workflowId, executionId } = context
if (!key || !workspaceId || !workflowId || !executionId) {
return false
}
const { registerLargeValueOwner } = await import('@/lib/execution/payloads/large-value-metadata')
return await registerLargeValueOwner(
{
key,
workspaceId,
workflowId,
executionId,
size,
},
referencedKeys
)
}
async function deleteUntrackedPersistedValue(key: string): Promise<boolean> {
try {
const [{ StorageService }, { deleteFileMetadata }] = await Promise.all([
import('@/lib/uploads'),
import('@/lib/uploads/server/metadata'),
])
const result = await StorageService.deleteFiles([key], 'execution')
const deleteFailed = result.failed.some((failed) => failed.key === key)
if (deleteFailed) {
logger.warn('Failed to delete untracked large execution value from storage', {
key,
})
return false
}
await deleteFileMetadata(key)
return true
} catch (error) {
logger.warn('Failed to clean up untracked large execution value', {
key,
error: toError(error).message,
})
return false
}
}
export async function storeLargeValue(
value: unknown,
json: string,
size: number,
context: LargeValueStoreContext
): Promise<LargeValueRef> {
return persistLargeValue(value, json, size, context, MAX_DURABLE_LARGE_VALUE_BYTES)
}
/**
* Stores a completed execution archive with a larger cap than individual
* workflow values. Not kept in the in-process cache: the run is over, readers
* materialize it asynchronously from storage, and the archive can hold live
* run objects rather than their JSON form.
*/
export async function storeExecutionTraceArchive(
value: Record<string, unknown>,
json: string,
size: number,
context: LargeValueStoreContext
): Promise<LargeValueRef> {
return persistLargeValue(
value,
json,
size,
{ ...context, requireDurable: true },
MAX_TRACE_ARCHIVE_BYTES,
false
)
}
async function persistLargeValue(
value: unknown,
json: string,
size: number,
context: LargeValueStoreContext,
limitBytes: number,
cacheInProcess = true
): Promise<LargeValueRef> {
assertDurableLargeValueSize(size, limitBytes)
const referencedKeys = collectLargeValueKeys(value)
const id = `lv_${generateShortId(12)}`
let key = await persistValue(id, json, context)
if (key) {
// Only clean up the uploaded object when registration definitively did NOT
// record ownership (returns false). If registration THROWS, the metadata
// state is uncertain (a row may have partially committed), so we propagate
// without deleting — deleting could orphan a metadata row pointing at a
// now-missing object.
const registered = await registerPersistedValueOwner(key, size, referencedKeys, context)
if (!registered) {
await deleteUntrackedPersistedValue(key)
if (context.requireDurable) {
throw new Error('Failed to persist large execution value metadata')
}
key = undefined
}
}
const cached =
cacheInProcess && cacheLargeValue(id, value, size, context, { recoverable: Boolean(key) })
if (!key && !cached) {
throw new Error('Cannot retain large execution value without durable storage')
}
return {
__simLargeValueRef: true,
version: LARGE_VALUE_REF_VERSION,
id,
kind: getKind(value),
size,
key,
executionId: context.executionId,
preview: getPreview(value),
}
}
export async function materializeLargeValueRef(
ref: LargeValueRef,
context?: LargeValueStoreContext
): Promise<unknown> {
if (!context?.executionId) {
return undefined
}
assertLargeValueRefAccess(ref, context)
assertInlineMaterializationSize(ref.size, context.maxBytes)
if (!ref.key || !isValidLargeValueKey(ref)) {
return materializeLargeValueRefSync(ref, context)
}
if (context.trackReference !== false) {
const { addLargeValueReference } = await import('@/lib/execution/payloads/large-value-metadata')
// Reference tracking is GC-critical: if it fails, fail the read rather than
// return a value whose reference was never recorded (it could later be
// garbage-collected out from under a live consumer). Read-only consumers
// that don't need a reference set trackReference: false to skip this.
await addLargeValueReference(
{
workspaceId: context.workspaceId,
workflowId: context.workflowId,
executionId: context.executionId,
source: 'execution_log',
},
ref.key
)
}
try {
const cached = materializeLargeValueRefSync(ref, context)
if (cached !== undefined) {
return cached
}
const value = await readLargeValueRefFromStorage(ref, {
workspaceId: context.workspaceId,
workflowId: context.workflowId,
executionId: context.executionId,
largeValueExecutionIds: context.largeValueExecutionIds,
largeValueKeys: context.largeValueKeys,
allowLargeValueWorkflowScope: context.allowLargeValueWorkflowScope,
userId: context.userId,
maxBytes: context.maxBytes ?? ref.size,
})
if (value === undefined) {
return undefined
}
cacheLargeValue(
ref.id,
value,
ref.size,
{
...context,
executionId: ref.executionId ?? context.executionId,
},
{ recoverable: true }
)
return value
} catch (error) {
logger.warn('Failed to materialize persisted large execution value', {
id: ref.id,
key: ref.key,
error,
})
return undefined
}
}