Line data Source code
1 : import { defineStore } from 'pinia'
2 : import { reactive, shallowRef, toRaw } from 'vue'
3 :
4 : import type {
5 : GraphScope,
6 : OwningGraphId,
7 : RootGraphId
8 : } from '@comfyorg/graph-model/graphScopeId'
9 : import type { LinkId } from '@comfyorg/graph-model/linkId'
10 : import type { LinkTopology } from '@comfyorg/graph-model/linkTopology'
11 : import { isFloatingTopology } from '@comfyorg/graph-model/linkTopology'
12 : import type { NodeId } from '@comfyorg/graph-model/nodeId'
13 :
14 : export type EndpointPatch = Partial<
15 : Pick<
16 : LinkTopology,
17 : 'originNodeId' | 'originSlot' | 'targetNodeId' | 'targetSlot'
18 : >
19 : >
20 :
21 : export interface EndpointUpdate {
22 : topology: LinkTopology
23 : patch: EndpointPatch
24 : }
25 : export interface EndpointUpdateError {
26 : code:
27 : | 'duplicate-topology'
28 : | 'unowned-topology'
29 : | 'duplicate-target'
30 : | 'occupied-target'
31 : message: string
32 : }
33 :
34 : type EndpointUpdateResult<T> =
35 : | { ok: true; value: T }
36 : | { ok: false; error: EndpointUpdateError }
37 :
38 28442 : function patchedEndpoints(
39 : topology: LinkTopology,
40 : patch: EndpointPatch
41 : ): EndpointPatch {
42 28442 : return {
43 : originNodeId: patch.originNodeId ?? topology.originNodeId,
44 : originSlot: patch.originSlot ?? topology.originSlot,
45 : targetNodeId: patch.targetNodeId ?? topology.targetNodeId,
46 : targetSlot: patch.targetSlot ?? topology.targetSlot
47 : }
48 : }
49 : /**
50 : * Endpoint slot keys are `${owningGraphId}:${nodeId}:${slot}`; slot is numeric
51 : * so the separator is unambiguous for any node id. Target (input side) and
52 : * origin (output side) keys are branded separately so a key built for one
53 : * index cannot be looked up in the other.
54 : */
55 : type TargetSlotKey = string & { readonly __brand: 'TargetSlotKey' }
56 : type OriginSlotKey = string & { readonly __brand: 'OriginSlotKey' }
57 :
58 1180155 : function targetKey(
59 : graphId: OwningGraphId,
60 : nodeId: NodeId,
61 : slot: number
62 : ): TargetSlotKey {
63 1180155 : return `${graphId}:${nodeId}:${slot}` as TargetSlotKey
64 : }
65 :
66 412498 : function originKey(
67 : graphId: OwningGraphId,
68 : nodeId: NodeId,
69 : slot: number
70 : ): OriginSlotKey {
71 412498 : return `${graphId}:${nodeId}:${slot}` as OriginSlotKey
72 : }
73 :
74 : type OriginIndex = Map<OriginSlotKey, Set<LinkTopology>>
75 :
76 : interface RootTopologyBucket {
77 : byId: Map<LinkId, LinkTopology>
78 : idsByOwner: Map<OwningGraphId, Set<LinkId>>
79 : targetIndex: Map<TargetSlotKey, LinkTopology>
80 : originIndex: OriginIndex
81 : }
82 :
83 2356 : const EMPTY_LINKS: ReadonlySet<LinkTopology> = new Set()
84 :
85 : /**
86 : * A link is keyed by its target input slot only when that slot uniquely
87 : * identifies it. Floating links (either endpoint unassigned) can share an
88 : * input slot with a real link and are not queried by target.
89 : */
90 115104 : function hasUniqueTarget(topology: LinkTopology): boolean {
91 115104 : return !isFloatingTopology(topology)
92 : }
93 :
94 : /**
95 : * Link topology store, partitioned by root and owning graph. At most one live
96 : * link can target a given input slot, so the target index answers the dominant
97 : * query ("is this input connected, and by what?") in one lookup. The root
98 : * bucket's link-id map is the identity authority; owner and slot maps are
99 : * derived indexes.
100 : */
101 2356 : export const useLinkStore = defineStore('link', () => {
102 2355 : const roots = reactive(new Map<RootGraphId, RootTopologyBucket>())
103 2355 : const revision = shallowRef(0)
104 :
105 430159 : function getRevision(): number {
106 430159 : return revision.value
107 : }
108 :
109 12116 : function rootBucket(rootGraphId: RootGraphId): RootTopologyBucket {
110 12116 : const existing = roots.get(rootGraphId)
111 12116 : if (existing) return existing
112 3548 : const created = reactive<RootTopologyBucket>({
113 : byId: new Map(),
114 : idsByOwner: new Map(),
115 : targetIndex: new Map(),
116 : originIndex: new Map()
117 : })
118 3548 : roots.set(rootGraphId, created)
119 3548 : return created
120 : }
121 :
122 43172 : function indexOrigin(
123 : bucket: RootTopologyBucket,
124 : topology: LinkTopology
125 : ): void {
126 43172 : if (isFloatingTopology(topology)) return
127 43165 : const key = originKey(
128 : topology.graphId,
129 : topology.originNodeId,
130 : topology.originSlot
131 : )
132 43165 : const existing = bucket.originIndex.get(key)
133 43172 : if (existing) {
134 8222 : existing.add(toRaw(topology))
135 8222 : return
136 : }
137 34943 : bucket.originIndex.set(key, reactive(new Set([toRaw(topology)])))
138 : }
139 :
140 28746 : function unindexOrigin(
141 : bucket: RootTopologyBucket,
142 : topology: LinkTopology
143 : ): void {
144 28746 : const key = originKey(
145 : topology.graphId,
146 : topology.originNodeId,
147 : topology.originSlot
148 : )
149 28746 : const links = bucket.originIndex.get(key)
150 28746 : if (!links?.delete(toRaw(topology))) return
151 28746 : if (!links.size) bucket.originIndex.delete(key)
152 : }
153 :
154 : /** Places a link whose target availability has already been validated. */
155 43172 : function placeValidated(
156 : bucket: RootTopologyBucket,
157 : topology: LinkTopology
158 : ): LinkTopology {
159 43172 : const placed = reactive(topology)
160 43172 : bucket.byId.set(placed.id, placed)
161 43172 : const ownerIds = bucket.idsByOwner.get(placed.graphId)
162 43172 : if (ownerIds) ownerIds.add(placed.id)
163 3943 : else bucket.idsByOwner.set(placed.graphId, reactive(new Set([placed.id])))
164 43172 : if (hasUniqueTarget(topology)) {
165 43165 : const key = targetKey(
166 : topology.graphId,
167 : topology.targetNodeId,
168 : topology.targetSlot
169 : )
170 43165 : bucket.targetIndex.set(key, placed)
171 : }
172 43172 : indexOrigin(bucket, placed)
173 43172 : return placed
174 : }
175 :
176 : /**
177 : * @returns The registered topology. Re-registering the same raw topology
178 : * under the same owner returns the incumbent; `undefined` means a distinct
179 : * topology occupies its ID or non-floating target slot.
180 : */
181 28453 : function registerLink(
182 : scope: GraphScope,
183 : topology: LinkTopology
184 : ): LinkTopology | undefined {
185 28453 : const incumbent = roots.get(scope.rootGraphId)?.byId.get(topology.id)
186 28453 : if (
187 : toRaw(incumbent) === toRaw(topology) &&
188 : incumbent?.graphId === scope.owningGraphId
189 : )
190 0 : return incumbent
191 28453 : return replaceLink(scope, undefined, topology)
192 : }
193 :
194 28958 : function canPlaceReplacement(
195 : scope: GraphScope,
196 : bucket: RootTopologyBucket | undefined,
197 : replacement: LinkTopology,
198 : replaced: LinkTopology | undefined
199 : ): boolean {
200 28958 : const incumbent = bucket?.byId.get(replacement.id)
201 28958 : if (incumbent && (!replaced || toRaw(incumbent) !== toRaw(replaced))) {
202 0 : console.error(
203 : `Link ${replacement.id} belongs to graph ${incumbent.graphId}; graph ${scope.owningGraphId} cannot overwrite it.`
204 : )
205 0 : return false
206 : }
207 28958 : if (replaced && (!bucket || !ownsPlacement(scope, bucket, replaced))) {
208 0 : return false
209 : }
210 28958 : return true
211 : }
212 :
213 28958 : function targetSlotIsAvailable(
214 : bucket: RootTopologyBucket | undefined,
215 : scope: GraphScope,
216 : replacement: LinkTopology,
217 : expected: LinkTopology | undefined
218 : ): boolean {
219 28958 : if (!hasUniqueTarget(replacement)) return true
220 28951 : const key = targetKey(
221 : scope.owningGraphId,
222 : replacement.targetNodeId,
223 : replacement.targetSlot
224 : )
225 28958 : const existing = bucket?.targetIndex.get(key)
226 28958 : if (toRaw(existing) !== toRaw(expected)) {
227 0 : console.error(`Link target slot ${key} is already occupied`)
228 0 : return false
229 : }
230 28951 : return true
231 : }
232 :
233 28958 : function displaceForReplacement(
234 : targetBucket: RootTopologyBucket,
235 : expected: LinkTopology | undefined,
236 : replaced: LinkTopology | undefined
237 : ): void {
238 28958 : if (expected) displace(targetBucket, expected)
239 28958 : if (replaced && toRaw(replaced) !== toRaw(expected)) {
240 0 : displace(targetBucket, replaced)
241 : }
242 : }
243 :
244 : /** Atomically replaces an expected target occupant with a new link. */
245 28958 : function replaceLink(
246 : scope: GraphScope,
247 : expected: LinkTopology | undefined,
248 : replacement: LinkTopology,
249 : replaced?: LinkTopology
250 : ): LinkTopology | undefined {
251 28958 : const bucket = roots.get(scope.rootGraphId)
252 28958 : if (expected && (!bucket || !ownsPlacement(scope, bucket, expected))) {
253 0 : return undefined
254 : }
255 28958 : if (!canPlaceReplacement(scope, bucket, replacement, replaced)) {
256 0 : return undefined
257 : }
258 28958 : if (!targetSlotIsAvailable(bucket, scope, replacement, expected)) {
259 0 : return undefined
260 : }
261 :
262 28958 : const targetBucket = bucket ?? rootBucket(scope.rootGraphId)
263 28958 : displaceForReplacement(targetBucket, expected, replaced)
264 : const owned = Object.assign(replacement, { graphId: scope.owningGraphId })
265 28958 : const placed = placeValidated(targetBucket, owned)
266 28958 : revision.value++
267 28958 : return placed
268 : }
269 :
270 : /** Removes a link placement that has already been validated. */
271 28746 : function displace(bucket: RootTopologyBucket, topology: LinkTopology): void {
272 28746 : if (hasUniqueTarget(topology)) {
273 28745 : const key = targetKey(
274 : topology.graphId,
275 : topology.targetNodeId,
276 : topology.targetSlot
277 : )
278 28745 : if (toRaw(bucket.targetIndex.get(key)) === toRaw(topology)) {
279 28745 : bucket.targetIndex.delete(key)
280 : }
281 : }
282 28746 : bucket.byId.delete(topology.id)
283 28746 : const ownerIds = bucket.idsByOwner.get(topology.graphId)
284 28746 : ownerIds?.delete(topology.id)
285 28746 : if (ownerIds?.size === 0) bucket.idsByOwner.delete(topology.graphId)
286 28746 : unindexOrigin(bucket, topology)
287 : }
288 :
289 14518 : function deleteLink(scope: GraphScope, topology: LinkTopology): boolean {
290 14518 : const bucket = roots.get(scope.rootGraphId)
291 14518 : if (!bucket || !ownsPlacement(scope, bucket, topology)) return false
292 14512 : displace(bucket, topology)
293 14518 : if (bucket.byId.size === 0) roots.delete(scope.rootGraphId)
294 14512 : revision.value++
295 14512 : return true
296 : }
297 :
298 28764 : function ownsPlacement(
299 : scope: GraphScope,
300 : bucket: RootTopologyBucket,
301 : topology: LinkTopology
302 : ): boolean {
303 28764 : return (
304 : topology.graphId === scope.owningGraphId &&
305 : toRaw(bucket.byId.get(topology.id)) === toRaw(topology)
306 : )
307 : }
308 :
309 8675 : function validateEndpointUpdates(
310 : scope: GraphScope,
311 : updates: readonly EndpointUpdate[],
312 : vacating: readonly LinkTopology[] = []
313 : ): EndpointUpdateError | undefined {
314 8675 : const bucket = roots.get(scope.rootGraphId)
315 8675 : const participants = [
316 : ...updates.map(({ topology }) => toRaw(topology)),
317 : ...vacating.map((topology) => toRaw(topology))
318 : ]
319 8675 : if (new Set(participants).size !== participants.length) {
320 0 : return {
321 : code: 'duplicate-topology',
322 : message: 'A link topology may only appear once in an endpoint batch'
323 : }
324 : }
325 :
326 8675 : for (const topology of participants) {
327 14234 : if (!bucket || !ownsPlacement(scope, bucket, topology)) {
328 0 : return {
329 : code: 'unowned-topology',
330 : message: `Link ${topology.id} does not own its current placement`
331 : }
332 : }
333 : }
334 :
335 8675 : const finalOwners = new Set<TargetSlotKey>()
336 8675 : for (const { topology, patch } of updates) {
337 14228 : const final = { ...toRaw(topology), ...patchedEndpoints(topology, patch) }
338 14228 : if (!hasUniqueTarget(final)) continue
339 :
340 14228 : const key = targetKey(
341 : topology.graphId,
342 : final.targetNodeId,
343 : final.targetSlot
344 : )
345 14228 : if (finalOwners.has(key)) {
346 0 : return {
347 : code: 'duplicate-target',
348 : message: `Multiple links target input slot ${final.targetNodeId}:${final.targetSlot}`
349 : }
350 : }
351 14228 : finalOwners.add(key)
352 :
353 14228 : const incumbent = bucket?.targetIndex.get(key)
354 14228 : if (incumbent && !participants.includes(toRaw(incumbent))) {
355 0 : return {
356 : code: 'occupied-target',
357 : message: `Link target slot ${final.targetNodeId}:${final.targetSlot} is already occupied`
358 : }
359 : }
360 : }
361 : }
362 :
363 : /** Atomically validates and applies endpoint updates and removals. */
364 8656 : function updateEndpoints(
365 : scope: GraphScope,
366 : updates: readonly EndpointUpdate[],
367 : removals: readonly LinkTopology[] = []
368 : ): EndpointUpdateResult<LinkTopology[]> {
369 8656 : const error = validateEndpointUpdates(scope, updates, removals)
370 8656 : if (error) return { ok: false, error }
371 :
372 8656 : const bucket = rootBucket(scope.rootGraphId)
373 14214 : for (const { topology } of updates) displace(bucket, topology)
374 8656 : for (const topology of removals) displace(bucket, topology)
375 :
376 8656 : const value = updates.map(({ topology, patch }) => {
377 14214 : Object.assign(reactive(topology), patchedEndpoints(topology, patch))
378 14214 : return placeValidated(bucket, topology)
379 : })
380 8656 : if (bucket.byId.size === 0) roots.delete(scope.rootGraphId)
381 8656 : revision.value++
382 8656 : return { ok: true, value }
383 : }
384 :
385 : /** Applies one endpoint patch atomically. */
386 27 : function updateEndpoint(
387 : scope: GraphScope,
388 : topology: LinkTopology,
389 : patch: EndpointPatch
390 : ): EndpointUpdateResult<LinkTopology> {
391 27 : const result = updateEndpoints(scope, [{ topology, patch }])
392 27 : return result.ok ? { ok: true, value: result.value[0] } : result
393 : }
394 :
395 640862 : function isInputSlotConnected(
396 : scope: GraphScope,
397 : nodeId: NodeId,
398 : slot: number
399 : ): boolean {
400 640862 : return (
401 : roots
402 : .get(scope.rootGraphId)
403 : ?.targetIndex.has(targetKey(scope.owningGraphId, nodeId, slot)) ?? false
404 : )
405 : }
406 :
407 478153 : function getInputSlotLink(
408 : scope: GraphScope,
409 : nodeId: NodeId,
410 : slot: number
411 : ): LinkTopology | undefined {
412 478153 : return roots
413 : .get(scope.rootGraphId)
414 : ?.targetIndex.get(targetKey(scope.owningGraphId, nodeId, slot))
415 : }
416 :
417 186295 : function isOutputSlotConnected(
418 : scope: GraphScope,
419 : nodeId: NodeId,
420 : slot: number
421 : ): boolean {
422 186295 : return (
423 : roots
424 : .get(scope.rootGraphId)
425 : ?.originIndex.has(originKey(scope.owningGraphId, nodeId, slot)) ?? false
426 : )
427 : }
428 :
429 167217 : function getOutputSlotLinks(
430 : scope: GraphScope,
431 : nodeId: NodeId,
432 : slot: number
433 : ): ReadonlySet<LinkTopology> {
434 167217 : return (
435 : roots
436 : .get(scope.rootGraphId)
437 : ?.originIndex.get(originKey(scope.owningGraphId, nodeId, slot)) ??
438 : EMPTY_LINKS
439 : )
440 : }
441 :
442 : /** Iterates every registered topology owned by a graph. */
443 112853 : function* graphTopologies(scope: GraphScope): Generator<LinkTopology> {
444 112853 : const bucket = roots.get(scope.rootGraphId)
445 112853 : const ids = bucket?.idsByOwner.get(scope.owningGraphId)
446 112853 : if (!bucket || !ids) return
447 112842 : for (const id of ids) {
448 649709 : const topology = bucket.byId.get(id)
449 649709 : if (topology) yield topology
450 : }
451 : }
452 :
453 14 : function getTopology(
454 : rootGraphId: RootGraphId,
455 : id: LinkId
456 : ): LinkTopology | undefined {
457 14 : return roots.get(rootGraphId)?.byId.get(id)
458 : }
459 :
460 11709 : function clearGraph(graphId: RootGraphId): void {
461 11709 : if (roots.delete(graphId)) revision.value++
462 : }
463 :
464 767 : function clearOwner(scope: GraphScope): void {
465 767 : const bucket = roots.get(scope.rootGraphId)
466 767 : const ids = bucket?.idsByOwner.get(scope.owningGraphId)
467 767 : if (!bucket || !ids) return
468 0 : for (const id of Array.from(ids)) {
469 0 : const topology = bucket.byId.get(id)
470 0 : if (topology) displace(bucket, topology)
471 : }
472 0 : if (bucket.byId.size === 0) roots.delete(scope.rootGraphId)
473 0 : revision.value++
474 : }
475 :
476 2355 : return {
477 : registerLink,
478 : replaceLink,
479 : updateEndpoint,
480 : updateEndpoints,
481 : validateEndpointUpdates,
482 : deleteLink,
483 : isInputSlotConnected,
484 : getInputSlotLink,
485 : isOutputSlotConnected,
486 : getOutputSlotLinks,
487 : getTopology,
488 : graphTopologies,
489 : getRevision,
490 : clearOwner,
491 : clearGraph
492 : }
493 : })
|