GitNexus/gitnexus/test/unit/spring-destinations-phase.test.ts
glier b15ff2d888
feat(ingestion): mint Destination nodes from AsyncAPI 3.x documents (#3140)
* feat(ingestion): read AsyncAPI 3.x documents into broker addresses

Adds a format-driven reader that turns the `operations[]` entries of an
AsyncAPI 3.x document into (broker, address, direction) triples, plus the
protocol-to-broker map behind it. Nothing consumes it yet.

The reader lives outside `frameworks/spring/` on purpose, like
`destination-key.ts` and for the same reason: an AsyncAPI document is a
published artifact emitted by generators across several language toolchains
and written by hand as often as generated. The entry criterion is therefore
the document format -- a root `asyncapi` key -- and never the generator.

AsyncAPI 2.x is refused under its own countable reason rather than mapped.
Its `publish`/`subscribe` are inverted relative to 3.x `send`/`receive`, so
a naive mapping reverses every direction in the async graph while leaving it
connected: nothing fails, the arrows simply point the wrong way. A silent
skip would be indistinguishable from "this service publishes no document",
which is the one thing the refusal count has to be able to tell us.

The broker is read twice over -- from the operation's bindings and from its
channel's server protocol -- and the two readings must agree. A destination
keyed on the wrong broker joins a stranger, and with the document
contradicting itself there is no way to tell which reading is right, so the
operation is refused rather than decided by a coin flip.

An unmapped protocol passes through as its own literal instead of being
dropped, because `destinationNodeKey` takes a plain string precisely so a
non-Spring caller can attest to a broker Spring has no member for.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(cli): add --asyncapi-spec, an explicit path to AsyncAPI documents

Threads an `asyncApiSpecPath` option from the CLI, the server analyze
endpoint, and the programmatic entry through to `PipelineOptions`. Nothing
reads it yet; the reader added in the previous commit is still unwired.

Shaped deliberately after `springActuatorPath`, the existing option for an
out-of-band artifact: an explicit local path, accepting a directory or a
single file, resolved against the repository root so a committed
`docs/asyncapi` and an absolute cache populated by something else are both
natural, and `undefined` keeping the feature entirely off. Mirroring that
option rather than inventing a mechanism is what lets a downstream consumer
point the reader at documents fetched out of band without patching a file
here.

`analyze --watch` REJECTS the flag, exactly as it rejects --spring-actuator.
The watcher reacts to source changes and nothing watches a document
directory, so honouring it there would read the documents once and then
serve a stale answer for the rest of the session -- worse than refusing,
because it looks like it worked.

Additive only: 49 inserted lines, no deletions and no modified lines. Every
new interface member is optional and every forward is an object-literal
spread of an undefined value, so with the option unset the analyzer takes
byte-identical paths.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(ingestion): mint Destination nodes from AsyncAPI documents

Wires the reader into the destinations phase. With `--asyncapi-spec` set,
every `send` operation emits PUBLISHES_TO and every `receive` emits
CONSUMES_FROM against the ordinary resolved `Destination` node -- same key,
same `address` property -- so a document and a source site that name one
address on one broker land on ONE node and the two halves of a conversation
meet. Verified end to end: an address named only in a document is minted
with the right broker and direction, and an address a source site already
resolved stays a single node with its own `literal` provenance while the
same address on a different broker stays separate.

This claims only what a document states -- that the service talks to that
address, on that broker, in that direction -- and never which method does
it. The addresses in one document partition by (broker, action) into buckets
that usually hold more than one operation, so any assignment past a bucket
of size one is a heuristic, and a wrong one attaches a real address to the
wrong handler: a false connection wearing the clothes of a resolved one. The
edge therefore starts at the document, not at a callable. That is weaker
than a source-derived edge and worth having anyway, because it is available
where the source supplies nothing at all -- a programmatically registered
listener, a broker with no patterns here, a language whose messaging idiom
nobody has taught this codebase yet.

Documents are read even when the source pass found no messaging, which is
why the early return had to move: a repository whose brokers are invisible
to the patterns is precisely the case a published document covers, and an
early return keyed on source sites skipped the documents exactly there.

Their counters are kept in their own block rather than folded into the
existing ones. `refusalsByReason` is the denominator of the SOURCE
unresolved fraction, and a mistyped specification directory must not be able
to make the source look worse than it is. The block is absent -- not zeroed
-- when no path was configured, so "not asked for" stays distinguishable
from "asked for and found nothing"; those need different answers from an
operator and one zero cannot say which happened.

The direction assertion is the one that matters and it is pinned by type,
not by existence: inverting the mapping in the source tree fails exactly one
test, because every other assertion passes identically under both readings.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs: document --asyncapi-spec and why step 4 of the cascade stays empty

Adds the flag to both READMEs and to the three byte-identical copies of the
CLI skill, which a sync test pins together.

Also rewrites the note on the `specification` seam in the address cascade.
It said "nothing supplies it today", which was true and is now misleading:
a reader exists, and the hook is still unsupplied because of a decision
rather than for want of one.

A document names addresses; it does not name the method that uses one. To
hand an address to a particular candidate something must choose which of the
document's operations belongs to it, and the only division both sides agree
on -- (broker, action) -- leaves buckets that usually hold more than one
operation. On a real generated document exactly one bucket of four was
unambiguous. Every assignment past a bucket of size one is a heuristic, and
a wrong one puts a REAL address on a joining node under the wrong site: a
false connection wearing the clothes of a resolved one, which is the outcome
the keying rule exists to prevent.

The note also records the two things that would change that and are not
heuristics -- a document carrying the implementing symbol, or a
configuration source answering the `${key}` the candidate already recorded
-- and that the second wants its own resolver, since what it needs is the
placeholder key rather than the candidate.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(ingestion): refuse the document shapes that would forge a join

Four ways a conformant AsyncAPI document could mint a Destination that
connects two services which have said nothing about each other. Every one is
reachable from ordinary 3.x vocabulary, not from malformed input, and each is
now a countable refusal.

A PARAMETERIZED ADDRESS is a pattern, not a place. Two services that publish
`{env}.orders` share a template; one deploys with env=prod and the other with
env=staging, and keying on the template text merges them into a single node
with a publisher on one side and a subscriber on the other. This is the
document-side twin of `overridable-config-default`, which argues the same
thing about `${key:default}` in source. A channel declaring `parameters` is
the specification's own statement that its address is a template, so the
detector is a reading rather than a guess; the `{` test catches generators
that template without declaring.

ANY BINDINGS KEY WAS TAKEN AS A PROTOCOL. AsyncAPI allows `bindings` to be a
Reference Object, so the map's own key can be `$ref` -- and passed through,
that becomes half of a join key carrying no broker information at all. Two
services that both reference shared bindings and both name `orders` then land
on one node, defeating the broker-in-key rule that keeps `kafka orders` and
`rabbit orders` apart. A broker must now be spelled like a protocol name.

A BROKER CONTAINING A SPACE COLLIDES, because the node key joins with one:
("kafka orders", "x") and ("kafka", "orders x") are the same key. That was
latent while every broker came from Spring's closed union. This module is the
first caller to feed the shared helper text that a document wrote, which is
exactly the condition under which it stops being latent, so it is closed here
-- at the producer -- rather than by changing an encoding that `routeNodeKey`
shares.

THE ADDRESS WAS TRIMMED, while the source cascade keeps an address exactly as
written so `" orders "` stays its own node. Two producers of one key held
opposite whitespace policies and the document side erred toward joining.

Also: fold the transport-security protocol variants (`kafka-secure`,
`secure-mqtt`, `wss`, `stomps`, `https`) onto their base protocol. The
`amqp`->`rabbit` argument already in this file demands it -- AsyncAPI's server
vocabulary distinguishes them and its bindings vocabulary does not, so a
secured cluster's own document was being read as self-contradictory. Treat a
channel with no `servers` as available on all of the document's servers, which
is the specification's default and was costing every single-server document
its destinations. Bound the address and operation-id lengths, because
`generateId` concatenates rather than hashes, and bound total operations
across the run rather than only per document.

Read each file through ONE handle for both the size gate and the read, as
`actuator-runtime.ts` does and for the reason its comment gives (CodeQL
js/file-system-race): re-resolving the path lets a swapped file bypass the
cap, and the out-of-band cache this option reads is written by other tooling
by definition. Open it with O_NONBLOCK: the type check that rejects a FIFO is
unreachable without it, because opening a FIFO for reading blocks in open(2)
until a writer appears -- found by writing the test first and watching it time
out rather than fail.

Count symlinked entries and walk truncation instead of dropping them in
silence. A symlinked cache and a wrong path were producing identical results.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(analyze): rebuild when documents are configured, and report what was read

An AsyncAPI document is external to git freshness in exactly the way an
Actuator snapshot is: replacing one moves no commit and dirties no file. The
option's own README paragraph advertises an absolute cache written by other
tooling, and on the second run of that workflow the already-up-to-date fast
path fired, no document was ever opened, and the previous run's addresses were
served as current. Measured, not reasoned: editing a document and re-running
printed "Already up to date" and left the old address in the graph; with this
change the same probe re-reads and the new address replaces it.

So an enabled run forces a rebuild and dropping the option forces one more, to
clear document-derived evidence -- the treatment `springActuatorPath` already
gets, for the same reason. Only the FLAG is recorded in index metadata, not
the path: Actuator retains its inputs so future scans keep excluding them,
whereas a committed document is deliberately NOT excluded (it wants its real
`File` node), so there is nothing to retain and recording the path would put
an operator's directory layout into metadata for no consumer.

That also settles a defect it would have been tempting to patch separately. A
synthetic `File` node for an out-of-tree document carries a path that is in no
write set and is not covered by `isGraphWideNode`, so an incremental writeback
dropped the node while keeping its edges -- which then COPY against a row that
was never written, and fail into an IGNORE_ERRORS retry that reports success.
A forced rebuild has no incremental subgraph to get that wrong.

Distinguish the two meanings of `resolution: 'specification'`. That value
belongs to the address cascade and means a CODE candidate was resolved through
the step-4 hook; a node minted from a document has no code site and now says
`asyncapi-document`. Reusing one string would leave a query that groups by
provenance unable to separate an address a document states from one a document
was used to resolve, and only the second is a claim about source.

Report what was read. The stats block was justified on the grounds that an
operator must be able to tell a mistyped directory from a repository with no
documents -- and nothing surfaced it, so the justification was aspirational. A
configured path that yields nothing, or a walk that hit a bound, now warns
unconditionally, as `spring-auto-configuration.ts` does for the same class of
input. The phase summary carries the refusal breakdown rather than only the
totals, because the unresolved fraction is the number this work is judged on
and a bare count says how big the gap is without saying what would close it.

Tests for the three wiring lines that were individually deletable with a green
suite, following the templates already in the repository: a row in the
`--watch` rejection table, the CLI-threading assertion beside the Actuator
one, and the shipped-skill fragment that pins the flag in all three copies.
Also pin `filePath: ''` on a spec-minted destination -- the half of the keying
rule that stops a shared node becoming collateral damage of one document's
next change -- and the in-repo `File` branch, which was dead-code-able.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(ingestion): close the join-forging paths a second review round found

The `$ref` exclusion added last round fixed one instance of a class and left
the class open. A `bindings` map key of `x-scs-function` -- an ordinary
Specification Extension, which generators emit -- still became the broker, so
two unrelated services carrying one vendor annotation and one address landed
on ONE node whose broker half said nothing about any broker. And
`{ kafka: {}, x-internal: {} }` read as two brokers, losing a conformant
document and reporting it as self-contradictory, which also made any document
author a one-line saboteur of their own cross-service links.

So the two readers are now separate functions with opposite defaults, and the
header says why they must be. `servers[].protocol` is a FIELD DECLARED to hold
a protocol: an unrecognized value there is the document's own claim and passes
through, because refusing it would lose a destination the document states
plainly. A `bindings` MAP KEY is not that -- the specification puts `$ref` and
`x-` in the same namespace -- so a non-protocol key is the EXPECTED case and
only AsyncAPI's binding vocabulary may answer. The syntactic test that was
applied to both was the right rule for one of them.

The walk fix from last round introduced something worse than it reported. A
shared abort flag meant depth exhaustion in ONE branch terminated the whole
traversal, so ten good documents beside a twelve-deep unrelated subtree were
kept or lost depending on whether that subtree sorted before or after them.
Truncation and budget-exhaustion are now separate: depth returns from its own
branch, and only a genuinely global bound stops the walk.

Rewriting `protocol.ts` dropped the whitespace check from the server-protocol
path and made the node-key collision reachable again. The test written for
that collision last round caught it within the minute; the comment now records
that it was learned twice.

Everything else measured this round:

- The broker is the THIRD string that reaches a graph identifier, and it was
  unbounded while the header claimed there were two. A one-megabyte protocol in
  a document satisfying every other cap was measured producing a gigabyte of
  resident identifier strings, because `generateId` concatenates rather than
  hashes and the phase mints one id per node and per edge.
- The run-wide operation budget counted ACCEPTED operations, reproducing at the
  run level the exact defect the per-document cap was corrected for last round:
  a run whose every operation is refused never decrements it. Both now count
  operations EXAMINED, and `operation-cap` sets `truncated` -- it is a bound
  that stopped the operation count, which is what that flag is documented to
  mean.
- The channel-inherits-all-servers rule ran per operation. Hoisted: it depends
  only on the servers.
- A subdirectory that cannot be listed is counted rather than dropped, so a
  mixed-permission cache cannot report a clean, complete read.
- The read LOOPS, like the Actuator reader this claims to follow. A single read
  was never short across seven hundred probes on APFS, but POSIX permits it and
  FUSE mounts with `direct_io` -- the deployment this option targets -- return
  short counts. A document truncated at a line boundary still parses, so the
  failure is silent: operations vanish with `refusals: {}`.
- `parameters: {}` no longer refuses a literal address; an empty container
  states nothing and generators emit them.
- A channel that is itself a Reference Object gets its own reason instead of
  `no-address`, which was telling operators their documents omit addresses when
  the reader simply stops one hop short.
- A multi-protocol document resolves from its operation's own bindings; only
  when those are silent does an inherited multi-protocol server set refuse, and
  under `ambiguous-server-default` rather than a reason that says the document
  contradicts itself. It does not.
- HTTP and WebSocket are refused for destination minting. For a broker the
  topic is the namespace; for HTTP the host is, so keying on the path alone
  would make every service exposing `/events` one node. A `Route` already
  models an HTTP endpoint, with its method in the key.
- The sniff window is a parse gate, not a read gate, and four kilobytes refused
  a good document behind a licence header.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(ingestion): pin the wiring and the reporting that were deletable

Three lines could be deleted with the whole suite green, and each of them
makes the feature partly or wholly inert: the forward from `run-analyze` into
`PipelineOptions`, the forced rebuild while documents are configured, and the
cleanup rebuild when the option is dropped. None is visible one layer up,
where the CLI test asserts on a mock's arguments.

One integration test closes all three. It drives the real `runFullAnalysis`
against a real repository and asserts, in order: the enabled run does not take
the up-to-date fast path and logs the rebuild; the destination reaches the
graph, which only happens if the option is forwarded; a document edited with
the tree clean and the commit unchanged is re-read; dropping the option
rebuilds once and removes the document-derived evidence; and the run after
that is up to date again -- the "rebuilds once" half, which rests on the
metadata being written as a fresh literal rather than merged, and which
nothing pinned.

The document lives OUTSIDE the repository on purpose. That is the workflow the
option is documented for, and it is the only one where the hazard exists:
editing a tracked file dirties the tree and forces a rebuild anyway, so an
in-repo fixture would pass with the freshness fix reverted. Verified by
reverting both: deleting the forward fails on the empty destination list,
deleting the forced rebuild fails on the missing log line.

Also pinned, each because deleting the code it covers left the suite green:
the `parameters` half of the templated-address refusal (its old test supplied
a braced address too, so the `{` half alone satisfied it); the phase actually
forwarding `symlinksSkipped`; the unconditional warning, whose whole argument
is that a tally nobody can see is not a tally -- captured through the
repository's own `_captureLogger`; a `.yml` document; a character device,
which is the case the `isFile` check exists for and which the FIFO test does
not reach; and the bound that stops a walk.

Reject an empty `--asyncapi-spec` at the CLI. It resolved to the repository
root and walked the whole tree, defeating this module's own rule that there is
no glob-based auto-discovery -- and the HTTP entry point already rejected the
identical value. Two doors onto one option must not hold different rules.

Surface the flag in the MCP context resource beside `spring_actuator`. It
matters more there than for its neighbour: Actuator annotates nodes the source
pass already found, while document reading mints destinations and edges with
no code site, and nothing said where they came from.

Log the configured path relative to the repository. The same change refuses to
persist that path to index metadata because it would record an operator's
directory layout; holding that rule for metadata and not for logs was holding
it in one place.

Both test files now clean up their temporary directories.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* style(ingestion): apply the repository's prettier contract

`quality / format` runs `npx prettier --check .`, and three files added by this
branch were not formatted to it. No behaviour changes: the reader's line
breaks and two test literals move, nothing else.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(ingestion): release the mini-repo handle the document test allocated

`setupMiniRepo` documents that the caller owns cleanup, and every other test
in this file calls `repo.cleanup()` in its `finally`. The AsyncAPI document
test removed only the document directory, so each run left a temporary
repository behind.

The two owners are separate on purpose: the document directory is a SIBLING of
the repository, placed outside the working tree so that editing it cannot
dirty the tree and force a rebuild on its own. The repo's cleanup therefore
does not reach it, and both calls belong in the same block.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(ingestion): stop partial server evidence from reading as unanimous

Six review findings, every one a way this reader could name a broker the
document does not name. They share a shape: something is DROPPED rather than
refused, the remaining evidence agrees with itself, and an operation is
attributed with confidence to a broker its document never settled on. A wrong
broker is half a join key, so it does not produce a missing edge -- it produces
an edge to a stranger, reported as a fact.

CAPPED SERVER MAPS. A channel with no `servers` inherits all of them, and that
map is capped at 1,000. A document whose first thousand servers are Kafka and
whose thousand-and-first is JMS read as unanimously Kafka, because unanimity
was tested on the slice. Counted `server-cap` and set `truncated`, but neither
stopped the attribution. The inherited path now refuses under
`capped-server-default` -- checked BEFORE agreement, since a subset agrees with
itself for free.

ROOT SERVER REFERENCE OBJECTS. The Servers Object patterned field is
`Server Object | Reference Object`, so `{ $ref: '#/components/servers/prod' }`
is conformant. Reading `protocol` off the raw value dropped every one: an
all-reference document had no protocol at all, and -- worse -- a MIXED set lost
its disagreeing half and became unanimous. One hop is now followed, through
`#/servers` and `#/components/servers`; anything else is refused under
`unresolved-server-reference` rather than skipped.

CHANNEL BINDINGS. Only the operation's bindings were read. A conformant channel
carrying `bindings: { kafka: {} }` with no operation binding was dropped as
`protocol-unknown` while the document said plainly which broker it meant, and a
disagreement between the two levels was invisible. Both are read; a conflict is
`protocol-disagreement`.

EMPTY `servers`. "If `servers` is absent or empty, this channel MUST be
available on all the servers defined in the Servers Object" -- one sentence,
both cases. A zero-iteration loop returned `explicit: true`, which blocked the
inherited fallback and dropped valid operations.

POINTER DECODING ORDER. RFC 6901 percent-decodes the fragment BEFORE splitting
on `/`. The raw token was tested for a separator first, so `#/channels/orders%2Fv1`
passed a check it should have failed and then decoded into two segments -- a
pointer addressing `channels.orders.v1` was read as a channel named `orders/v1`,
inventing a channel the document never declared. A malformed escape is now
refused rather than resolved against its undecoded text. `~1` still resolves; it
is the pointer's own escape and belongs after segmentation.

THE SNIFF WINDOW. A fixed window decides by where the root key sits rather than
whether it is there, so every window is a false negative waiting for a longer
preamble -- 4 KiB was replaced by 64 KiB for that reason and inherited the same
defect. The whole text is scanned; it is already bounded and already in memory,
and the gate exists to skip the PARSE, which is the expensive half. A leading
UTF-8 BOM is stripped before both sniff and parse.

Twelve of the fourteen new tests were run against the unfixed reader and all
twelve failed; the other two are controls that must pass either way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(ingestion): simplify AsyncAPI pointer and binding resolution

Decode each $ref once, union binding evidence, and stop walking capped
server maps whose brokers are unused on the inherit path.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 22:01:15 +00:00

930 lines
38 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { afterAll, beforeEach, describe, expect, it } from 'vitest';
import { mkdtemp, writeFile, symlink, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { createKnowledgeGraph } from '../../src/core/graph/graph.js';
import { _captureLogger } from '../../src/core/logger.js';
import {
setJavaSpringMessageProducerFacts,
setJavaSpringNonHttpHandlerFacts,
} from '../../src/core/ingestion/languages/java/capture-side-channel.js';
import { SPRING_CONFIG_DESCRIPTION } from '../../src/core/ingestion/frameworks/spring/config-bindings.js';
import { destinationNodeKey } from '../../src/core/ingestion/destination-key.js';
import { springDestinationsPhase } from '../../src/core/ingestion/pipeline-phases/spring-destinations.js';
import type { SpringDestinationsOutput } from '../../src/core/ingestion/pipeline-phases/spring-destinations.js';
import type {
PipelineContext,
PhaseResult,
} from '../../src/core/ingestion/pipeline-phases/types.js';
import type { KnowledgeGraph } from '../../src/core/graph/types.js';
import { generateId } from '../../src/lib/utils.js';
/**
* Phase-level cover for the things `PipelineResult` cannot show.
*
* `runPipelineFromRepo` returns the graph but not the phase outputs, so the
* refusal counters — the number the feature is actually measured on — are only
* observable by driving the phase directly. The keying rule is asserted here a
* second time, from a hand-built pair of facts rather than from source, so a
* regression shows up whether it comes from the resolver or from the capture.
*/
const OWNER_RANGE = { startLine: 4, startCol: 4, endLine: 6, endCol: 5 } as const;
function callableNode(graph: KnowledgeGraph, filePath: string, name: string): void {
graph.addNode({
id: generateId('Method', `${filePath}:${name}`),
label: 'Method',
properties: {
name,
filePath,
// Capture ranges are 1-based; graph nodes are 0-based.
startLine: OWNER_RANGE.startLine - 1,
endLine: OWNER_RANGE.endLine - 1,
},
});
}
async function run(graph: KnowledgeGraph, files: string[]): Promise<SpringDestinationsOutput> {
const deps = new Map<string, PhaseResult<unknown>>([
[
'parse',
{
phaseName: 'parse',
durationMs: 0,
// `allPaths`, matching the phase: on a run with a storage path the
// parse phase returns an EMPTY `parsedFiles` and streams them from
// disk instead, so the path list is the only cursor that always holds.
output: { allPaths: files, moduleConstants: new Map() },
},
],
['scopeResolution', { phaseName: 'scopeResolution', durationMs: 0, output: {} }],
['springConfig', { phaseName: 'springConfig', durationMs: 0, output: {} }],
]);
const ctx = {
repoPath: '/repo',
graph,
onProgress: () => {},
pipelineStart: 0,
} as unknown as PipelineContext;
return springDestinationsPhase.execute(ctx, deps) as Promise<SpringDestinationsOutput>;
}
describe('springDestinations phase', () => {
let graph: KnowledgeGraph;
beforeEach(() => {
graph = createKnowledgeGraph();
});
it('counts every refusal by reason', () => {
// A decline that incremented nothing would be indistinguishable from a
// success in the one measure this feature is judged on.
const filePath = 'src/Refusals.java';
setJavaSpringNonHttpHandlerFacts(filePath, [
{
ownerScopeId: `${filePath}#refuse` as never,
ownerFilePath: filePath,
ownerRange: OWNER_RANGE,
annotations: [
{ name: 'KafkaListener', args: [{ name: 'topicPattern', text: '"orders.*"' }] },
{ name: 'KafkaListener', args: [{ name: 'topics', text: '{}' }] },
{ name: 'KafkaListener', args: [{ name: 'groupId', text: '"g"' }] },
{ name: 'KafkaListener' },
],
},
]);
setJavaSpringMessageProducerFacts(filePath, [
{
ownerScopeId: `${filePath}#publish` as never,
ownerRange: OWNER_RANGE,
template: 'kafka',
receiverName: 'kafkaTemplate',
methodName: 'send',
args: [{ text: 'record' }],
},
{
ownerScopeId: `${filePath}#publish2` as never,
ownerRange: OWNER_RANGE,
template: 'rabbit',
receiverName: 'rabbitTemplate',
methodName: 'convertAndSend',
args: [{ text: 'payload' }],
},
]);
callableNode(graph, filePath, 'refuse');
return run(graph, [filePath]).then((output) => {
expect(output.refusalsByReason).toEqual({
'topic-pattern': 1,
'empty-destination-list': 1,
'no-destination-argument': 1,
'annotation-arguments-unavailable': 1,
'producer-arity-unrecognized': 1,
'rabbit-default-exchange': 1,
});
expect(output.resolvedDestinations).toBe(0);
expect(output.unresolvedDestinations).toBe(0);
expect(output.edges).toBe(0);
});
});
it('keys two files that write the same placeholder to two distinct nodes', async () => {
for (const filePath of ['src/A.java', 'src/B.java']) {
setJavaSpringNonHttpHandlerFacts(filePath, [
{
ownerScopeId: `${filePath}#consume` as never,
ownerFilePath: filePath,
ownerRange: OWNER_RANGE,
annotations: [
{ name: 'KafkaListener', args: [{ name: 'topics', text: '"${app.topic}"' }] },
],
},
]);
setJavaSpringMessageProducerFacts(filePath, []);
callableNode(graph, filePath, 'consume');
}
const output = await run(graph, ['src/A.java', 'src/B.java']);
expect(output.unresolvedDestinations).toBe(2);
expect(output.resolvedDestinations).toBe(0);
const nodes = [...graph.iterNodes()].filter((node) => node.label === 'Destination');
expect(nodes).toHaveLength(2);
expect(new Set(nodes.map((node) => node.id)).size).toBe(2);
for (const node of nodes) {
expect(node.properties.address).toBeUndefined();
expect(node.properties.configKey).toBe('app.topic');
}
});
it('keys two DIFFERENT placeholders in one callable to two nodes as well', async () => {
// File plus owner line plus argument position is not unique on its own —
// two publishes in one method share all three. Merging them would be a
// false identity of the same kind, only smaller.
const filePath = 'src/Two.java';
setJavaSpringNonHttpHandlerFacts(filePath, []);
setJavaSpringMessageProducerFacts(filePath, [
{
ownerScopeId: `${filePath}#publish` as never,
ownerRange: OWNER_RANGE,
template: 'kafka',
receiverName: 'kafkaTemplate',
methodName: 'send',
args: [{ text: '"${a.topic}"' }, { text: 'payload' }],
},
{
ownerScopeId: `${filePath}#publish` as never,
ownerRange: OWNER_RANGE,
template: 'kafka',
receiverName: 'kafkaTemplate',
methodName: 'send',
args: [{ text: '"${b.topic}"' }, { text: 'payload' }],
},
]);
callableNode(graph, filePath, 'publish');
const output = await run(graph, [filePath]);
expect(output.unresolvedDestinations).toBe(2);
expect(output.edges).toBe(2);
});
it('keys two callables that START ON ONE LINE to two nodes', async () => {
// `void a() { k.send("${x}", p); } void b() { k.send("${x}", p); }` on one
// line. The key used to be file + owner START LINE + argument position, so
// both publishes landed on one node and both hung an edge off it.
const filePath = 'src/OneLine.java';
const range = { startLine: 3, startCol: 4, endLine: 3, endCol: 40 } as const;
setJavaSpringNonHttpHandlerFacts(filePath, []);
setJavaSpringMessageProducerFacts(filePath, [
{
ownerScopeId: `${filePath}#a` as never,
ownerRange: range,
template: 'kafka',
receiverName: 'kafkaTemplate',
methodName: 'send',
args: [{ text: '"${app.topic}"' }, { text: 'payload' }],
},
{
ownerScopeId: `${filePath}#b` as never,
ownerRange: { ...range, startCol: 41, endCol: 80 },
template: 'kafka',
receiverName: 'kafkaTemplate',
methodName: 'send',
args: [{ text: '"${app.topic}"' }, { text: 'payload' }],
},
]);
graph.addNode({
id: generateId('Method', `${filePath}:a`),
label: 'Method',
properties: { name: 'a', filePath, startLine: 2, endLine: 2 },
});
const output = await run(graph, [filePath]);
expect(output.unresolvedDestinations).toBe(2);
const nodes = [...graph.iterNodes()].filter((node) => node.label === 'Destination');
expect(new Set(nodes.map((node) => node.id)).size).toBe(2);
// Two identities alone would also hold if one publish had been dropped, so
// pin the edges: two publishes, landing on two DIFFERENT destinations. That
// is the regression — both used to hang off a single node.
const publishes = [...graph.iterRelationshipsByType('PUBLISHES_TO')];
expect(publishes).toHaveLength(2);
expect(new Set(publishes.map((rel) => rel.targetId)).size).toBe(2);
// Both edges leave the SAME callable, and that is not a defect of this
// phase. With no scope tree here, owner resolution falls back to matching a
// callable by line range — and the two facts, being on one line, carry the
// same range, so the fallback can only ever name one owner for both. That
// is precisely why destination identity must not be derived from the owner:
// the one thing the fallback cannot distinguish is the one thing that used
// to collapse the two publishes onto a single node.
//
// Adding a second Method node does NOT sharpen this. Two nodes sharing a
// range make the lookup ambiguous, `exactCallableOwnersByRange` maps that
// to `null` on purpose, and then NEITHER publish gets a callable — `a`
// loses its edge as well. Real ingestion resolves through the scope tree
// and never reaches this path.
const methodA = generateId('Method', `${filePath}:a`);
expect(publishes.every((rel) => rel.sourceId === methodA)).toBe(true);
});
it('keys two handlers apart even when neither fact carried an owner range', async () => {
// `ownerRange` is OPTIONAL on a handler fact and required on a producer.
// Keyed on the line alone the position degraded to 0 for the whole file and
// every consumer in it collapsed onto one node, invisibly.
const filePath = 'src/NoRange.java';
setJavaSpringNonHttpHandlerFacts(filePath, [
{
ownerScopeId: `${filePath}#first` as never,
ownerFilePath: filePath,
annotations: [
{ name: 'KafkaListener', args: [{ name: 'topics', text: '"${app.topic}"' }] },
],
},
{
ownerScopeId: `${filePath}#second` as never,
ownerFilePath: filePath,
annotations: [
{ name: 'KafkaListener', args: [{ name: 'topics', text: '"${app.topic}"' }] },
],
},
]);
setJavaSpringMessageProducerFacts(filePath, []);
graph.addNode({
id: generateId('File', filePath),
label: 'File',
properties: { name: 'NoRange.java', filePath },
});
const output = await run(graph, [filePath]);
expect(output.unresolvedDestinations).toBe(2);
const nodes = [...graph.iterNodes()].filter((node) => node.label === 'Destination');
expect(new Set(nodes.map((node) => node.id)).size).toBe(2);
});
it('does not merge two config keys that share a default', async () => {
// `${a.topic:events}` in one file and `${b.topic:events}` in another used to
// collapse onto one `Destination:events` and report a producer/consumer
// pair between two services that share nothing but a copy-pasted fallback.
for (const [filePath, key] of [
['src/SvcA.java', 'a.topic'],
['src/SvcB.java', 'b.topic'],
] as const) {
setJavaSpringNonHttpHandlerFacts(filePath, [
{
ownerScopeId: `${filePath}#consume` as never,
ownerFilePath: filePath,
ownerRange: OWNER_RANGE,
annotations: [
{ name: 'KafkaListener', args: [{ name: 'topics', text: `"\${${key}:events}"` }] },
],
},
]);
setJavaSpringMessageProducerFacts(filePath, []);
callableNode(graph, filePath, 'consume');
}
const output = await run(graph, ['src/SvcA.java', 'src/SvcB.java']);
expect(output.resolvedDestinations).toBe(0);
expect(output.unresolvedDestinations).toBe(2);
const nodes = [...graph.iterNodes()].filter((node) => node.label === 'Destination');
expect(nodes).toHaveLength(2);
for (const node of nodes) {
expect(node.properties.address).toBeUndefined();
// The default is kept as provenance, so the case stays countable and
// distinguishable from a bare `${key}`.
expect(node.properties.configDefault).toBe('events');
expect(node.properties.resolution).toBe('overridable-config-default');
}
expect(new Set(nodes.map((n) => n.properties.configKey))).toEqual(
new Set(['a.topic', 'b.topic']),
);
});
it('gives two files that write the same SpEL expression two nodes', async () => {
for (const filePath of ['src/SpelA.java', 'src/SpelB.java']) {
setJavaSpringNonHttpHandlerFacts(filePath, [
{
ownerScopeId: `${filePath}#consume` as never,
ownerFilePath: filePath,
ownerRange: OWNER_RANGE,
annotations: [
{
name: 'KafkaListener',
args: [{ name: 'topics', text: '"#{@kafkaProps.ordersTopic}"' }],
},
],
},
]);
setJavaSpringMessageProducerFacts(filePath, []);
callableNode(graph, filePath, 'consume');
}
const output = await run(graph, ['src/SpelA.java', 'src/SpelB.java']);
expect(output.resolvedDestinations).toBe(0);
expect(output.refusalsByReason['spel-expression']).toBe(2);
const nodes = [...graph.iterNodes()].filter((node) => node.label === 'Destination');
expect(nodes).toHaveLength(2);
for (const node of nodes) expect(node.properties.address).toBeUndefined();
});
it('never looks a configuration key up under the empty string', async () => {
// `${}` used to yield `configKey: ""`, and the phase then queried for it.
const filePath = 'src/EmptyKey.java';
graph.addNode({
id: 'property:empty',
label: 'Property',
properties: { name: '', filePath: 'application.yml', description: SPRING_CONFIG_DESCRIPTION },
});
setJavaSpringNonHttpHandlerFacts(filePath, [
{
ownerScopeId: `${filePath}#consume` as never,
ownerFilePath: filePath,
ownerRange: OWNER_RANGE,
annotations: [{ name: 'KafkaListener', args: [{ name: 'topics', text: '"${}"' }] }],
},
]);
setJavaSpringMessageProducerFacts(filePath, []);
callableNode(graph, filePath, 'consume');
const output = await run(graph, [filePath]);
expect(output.refusalsByReason['empty-config-key']).toBe(1);
expect(output.configKeyLinks).toBe(0);
});
it('JOINS a Kafka pair on an address a stranger spells the same way', async () => {
// THE regression. Three sites on one spelling of `orders`: a real Kafka
// pair — a publisher in one file, a listener in another, genuinely
// connected — plus an unrelated `@RabbitListener(queues = "orders")`
// somewhere else in the repository.
//
// Withdrawing the address from every site that named it made the third
// party's word choice enough to disconnect the other two: all three were
// keyed by site, none carried `address`, and the pair the feature exists to
// report was split by a file that has nothing to do with either half of it.
// With the broker in the key the pair meets on `kafka orders` and the
// stranger gets `rabbit orders`, which costs the pair nothing.
const publisherFile = 'src/KafkaPublisher.java';
const listenerFile = 'src/KafkaListener.java';
const strangerFile = 'src/UnrelatedRabbit.java';
setJavaSpringNonHttpHandlerFacts(publisherFile, []);
setJavaSpringMessageProducerFacts(publisherFile, [
{
ownerScopeId: `${publisherFile}#publish` as never,
ownerRange: OWNER_RANGE,
template: 'kafka',
receiverName: 'kafkaTemplate',
methodName: 'send',
args: [{ text: '"orders"' }, { text: 'payload' }],
},
]);
callableNode(graph, publisherFile, 'publish');
setJavaSpringNonHttpHandlerFacts(listenerFile, [
{
ownerScopeId: `${listenerFile}#consume` as never,
ownerFilePath: listenerFile,
ownerRange: OWNER_RANGE,
annotations: [{ name: 'KafkaListener', args: [{ name: 'topics', text: '"orders"' }] }],
},
]);
setJavaSpringMessageProducerFacts(listenerFile, []);
callableNode(graph, listenerFile, 'consume');
setJavaSpringNonHttpHandlerFacts(strangerFile, [
{
ownerScopeId: `${strangerFile}#consume` as never,
ownerFilePath: strangerFile,
ownerRange: OWNER_RANGE,
annotations: [{ name: 'RabbitListener', args: [{ name: 'queues', text: '"orders"' }] }],
},
]);
setJavaSpringMessageProducerFacts(strangerFile, []);
callableNode(graph, strangerFile, 'consume');
const output = await run(graph, [publisherFile, listenerFile, strangerFile]);
// Two nodes, both fully connectable, exactly as `GET /x` and `POST /x` are
// two Routes. Nothing is unresolved and nothing is withdrawn.
expect(output.resolvedDestinations).toBe(2);
expect(output.unresolvedDestinations).toBe(0);
expect(output.edges).toBe(3);
const nodes = [...graph.iterNodes()].filter((node) => node.label === 'Destination');
expect(nodes).toHaveLength(2);
const byBroker = new Map(nodes.map((node) => [String(node.properties.broker), node]));
const kafka = byBroker.get('kafka');
const rabbit = byBroker.get('rabbit');
expect(kafka).toBeDefined();
expect(rabbit).toBeDefined();
// Both carry the join key. Withdrawing it is what used to break the pair.
expect(kafka?.properties.address).toBe('orders');
expect(rabbit?.properties.address).toBe('orders');
expect(kafka?.properties.resolution).toBe('literal');
expect(rabbit?.properties.resolution).toBe('literal');
// Same `address`, DIFFERENT identity — the broker is what separates them.
expect(kafka?.id).not.toBe(rabbit?.id);
// A connecting destination carries no file, so no incremental delete of
// the stranger's file can cut the pair's node either.
expect(kafka?.properties.filePath).toBe('');
expect(rabbit?.properties.filePath).toBe('');
// Identity alone would also hold if an edge had been dropped, so pin the
// walk itself: the publisher and the listener meet on ONE node, from two
// different files, and the stranger is not on it.
const edgesTo = (id: string) =>
[...graph.iterRelationships()].filter(
(edge) =>
edge.targetId === id && (edge.type === 'PUBLISHES_TO' || edge.type === 'CONSUMES_FROM'),
);
const pair = edgesTo(kafka?.id as string);
expect(pair.map((edge) => edge.type).sort()).toEqual(['CONSUMES_FROM', 'PUBLISHES_TO']);
expect(new Set(pair.map((edge) => edge.sourceId)).size).toBe(2);
expect(
pair.map((edge) => String(graph.getNode(edge.sourceId)?.properties.filePath)).sort(),
).toEqual([listenerFile, publisherFile]);
// And the stranger keeps its own edge onto its own node — the subscription
// is a real fact, it just is not part of the pair.
const stray = edgesTo(rabbit?.id as string);
expect(stray.map((edge) => edge.type)).toEqual(['CONSUMES_FROM']);
expect(graph.getNode(stray[0]?.sourceId as string)?.properties.filePath).toBe(strangerFile);
});
it('gives one address named by two brokers two CONNECTABLE nodes', async () => {
// The same rule seen from the other side, and the case that used to
// disconnect both halves: a Kafka topic and a Rabbit queue that share a
// name are two places, so they are two nodes — but two ORDINARY nodes,
// each keeping its `address` and each free to meet its own counterpart.
// Nothing is refused, so `resolution` stays the resolver's own vocabulary.
const filePath = 'src/TwoBrokers.java';
setJavaSpringNonHttpHandlerFacts(filePath, [
{
ownerScopeId: `${filePath}#consume` as never,
ownerFilePath: filePath,
ownerRange: OWNER_RANGE,
annotations: [{ name: 'RabbitListener', args: [{ name: 'queues', text: '"orders"' }] }],
},
]);
setJavaSpringMessageProducerFacts(filePath, [
{
ownerScopeId: `${filePath}#consume` as never,
ownerRange: OWNER_RANGE,
template: 'kafka',
receiverName: 'kafkaTemplate',
methodName: 'send',
args: [{ text: '"orders"' }, { text: 'payload' }],
},
]);
callableNode(graph, filePath, 'consume');
const output = await run(graph, [filePath]);
expect(output.resolvedDestinations).toBe(2);
expect(output.unresolvedDestinations).toBe(0);
expect(output.edges).toBe(2);
const nodes = [...graph.iterNodes()].filter((node) => node.label === 'Destination');
expect(nodes).toHaveLength(2);
expect(new Set(nodes.map((node) => node.id)).size).toBe(2);
for (const node of nodes) {
expect(node.properties.address).toBe('orders');
expect(node.properties.name).toBe('orders');
expect(node.properties.resolution).toBe('literal');
}
expect(new Set(nodes.map((node) => node.properties.broker))).toEqual(
new Set(['kafka', 'rabbit']),
);
// Two edges, onto two different nodes: the publish and the subscription
// are real, and the two-hop walk between them still finds nothing, because
// they really are unrelated.
const targets = [...graph.iterRelationships()]
.filter((edge) => edge.type === 'PUBLISHES_TO' || edge.type === 'CONSUMES_FROM')
.map((edge) => edge.targetId);
expect(new Set(targets).size).toBe(2);
});
it('does not split a pair that names the SAME broker', async () => {
// The case the whole feature exists to report: a publisher and a subscriber
// agreeing on one address over one broker. A key that folded in anything
// per-site — the file, the owner — would split exactly these pairs and
// leave the feature emitting nothing but orphans.
const filePath = 'src/Agree.java';
setJavaSpringNonHttpHandlerFacts(filePath, [
{
ownerScopeId: `${filePath}#consume` as never,
ownerFilePath: filePath,
ownerRange: OWNER_RANGE,
annotations: [{ name: 'KafkaListener', args: [{ name: 'topics', text: '"orders"' }] }],
},
]);
setJavaSpringMessageProducerFacts(filePath, [
{
ownerScopeId: `${filePath}#consume` as never,
ownerRange: OWNER_RANGE,
template: 'kafka',
receiverName: 'kafkaTemplate',
methodName: 'send',
args: [{ text: '"orders"' }, { text: 'payload' }],
},
]);
callableNode(graph, filePath, 'consume');
const output = await run(graph, [filePath]);
expect(output.resolvedDestinations).toBe(1);
expect(output.unresolvedDestinations).toBe(0);
const nodes = [...graph.iterNodes()].filter((node) => node.label === 'Destination');
expect(nodes).toHaveLength(1);
expect(nodes[0]?.properties.address).toBe('orders');
expect(output.edges).toBe(2);
});
it('keys a second address independently of how many brokers named the first', async () => {
// Identity is now a function of ONE site — its broker and its address — so
// no other site can change it. This is the assertion that says so: a second
// address in the same file, on the same broker as one of the two claimants
// of the first, is untouched by any of it.
const filePath = 'src/Mixed.java';
setJavaSpringNonHttpHandlerFacts(filePath, [
{
ownerScopeId: `${filePath}#consume` as never,
ownerFilePath: filePath,
ownerRange: OWNER_RANGE,
annotations: [
{ name: 'RabbitListener', args: [{ name: 'queues', text: '"orders"' }] },
{ name: 'KafkaListener', args: [{ name: 'topics', text: '"shipments"' }] },
],
},
]);
setJavaSpringMessageProducerFacts(filePath, [
{
ownerScopeId: `${filePath}#consume` as never,
ownerRange: OWNER_RANGE,
template: 'kafka',
receiverName: 'kafkaTemplate',
methodName: 'send',
args: [{ text: '"orders"' }, { text: 'payload' }],
},
{
ownerScopeId: `${filePath}#consume` as never,
ownerRange: OWNER_RANGE,
template: 'kafka',
receiverName: 'kafkaTemplate',
methodName: 'send',
args: [{ text: '"shipments"' }, { text: 'payload' }],
},
]);
callableNode(graph, filePath, 'consume');
const output = await run(graph, [filePath]);
// `kafka orders`, `rabbit orders`, `kafka shipments`.
expect(output.resolvedDestinations).toBe(3);
expect(output.unresolvedDestinations).toBe(0);
const shipments = [...graph.iterNodes()].filter(
(node) => node.label === 'Destination' && node.properties.address === 'shipments',
);
// The Kafka listener and the Kafka publish of `shipments` share one node,
// which is what the second publish above is there to check.
expect(shipments).toHaveLength(1);
expect(shipments[0]?.properties.broker).toBe('kafka');
});
});
describe('destinationNodeKey', () => {
// Tested directly rather than through the phase. The address-only branch is
// UNREACHABLE from Spring — `SpringDestinationCandidate.broker` is required
// and every annotation rule and producer template supplies one — so driving
// it through a phase would mean staging a fact the capture layer cannot
// produce, and the test would read as though the branch were live.
it('puts a known broker in the key', () => {
expect(destinationNodeKey('kafka', 'orders')).toBe('kafka orders');
});
it('keeps two brokers on one address apart', () => {
expect(destinationNodeKey('kafka', 'orders')).not.toBe(destinationNodeKey('rabbit', 'orders'));
});
it('degrades to the address alone when no broker is known', () => {
// The shape the next language gets: an address captured without a broker to
// attest to still keys a node, because silence about the broker is not a
// claim about it. Empty string is treated as absent for the same reason —
// it is what a caller that has nothing to say tends to pass.
expect(destinationNodeKey(undefined, 'orders')).toBe('orders');
expect(destinationNodeKey('', 'orders')).toBe('orders');
});
});
/**
* AsyncAPI documents as a second source of destinations.
*
* DIRECTION IS THE ASSERTION THAT MATTERS. A swapped send/receive mapping
* emits both edge types, both nodes, and a fully connected graph — only with
* every arrow reversed. Any test that asserts a node or an edge EXISTS passes
* identically under the broken mapping, so each test below names the edge TYPE
* it expects for a given action.
*/
describe('springDestinations phase — AsyncAPI documents', () => {
let graph: KnowledgeGraph;
beforeEach(() => {
graph = createKnowledgeGraph();
});
const KAFKA_DOCUMENT = `
asyncapi: 3.0.0
info: { title: Order Service, version: 1.0.0 }
servers:
broker: { host: "example:9092", protocol: kafka }
channels:
outbound:
address: orders
servers: [{ $ref: "#/servers/broker" }]
inbound:
address: shipments
servers: [{ $ref: "#/servers/broker" }]
operations:
publishOrder:
action: send
channel: { $ref: "#/channels/outbound" }
onShipment:
action: receive
channel: { $ref: "#/channels/inbound" }
`;
// Tracked and removed; an earlier version of this suite left hundreds of
// temporary directories behind on developer machines.
const createdDirs: string[] = [];
afterAll(async () => {
for (const dir of createdDirs) await rm(dir, { recursive: true, force: true });
});
async function specDir(body: string = KAFKA_DOCUMENT): Promise<string> {
const dir = await mkdtemp(path.join(tmpdir(), 'gnx-phase-spec-'));
createdDirs.push(dir);
await writeFile(path.join(dir, 'asyncapi.yaml'), body, 'utf-8');
return dir;
}
async function runWithSpec(
files: string[],
asyncApiSpecPath: string | undefined,
): Promise<SpringDestinationsOutput> {
const deps = new Map<string, PhaseResult<unknown>>([
[
'parse',
{
phaseName: 'parse',
durationMs: 0,
output: { allPaths: files, moduleConstants: new Map() },
},
],
['scopeResolution', { phaseName: 'scopeResolution', durationMs: 0, output: {} }],
['springConfig', { phaseName: 'springConfig', durationMs: 0, output: {} }],
]);
const ctx = {
repoPath: '/repo',
graph,
onProgress: () => {},
pipelineStart: 0,
...(asyncApiSpecPath === undefined ? {} : { options: { asyncApiSpecPath } }),
} as unknown as PipelineContext;
return springDestinationsPhase.execute(ctx, deps) as Promise<SpringDestinationsOutput>;
}
function edgesFrom(address: string): { type: string; sourceId: string }[] {
const target = generateId('Destination', destinationNodeKey('kafka', address));
return [...graph.iterRelationships()]
.filter((r) => r.targetId === target)
.map((r) => ({ type: r.type, sourceId: r.sourceId }));
}
it('maps `send` to PUBLISHES_TO and `receive` to CONSUMES_FROM', async () => {
const output = await runWithSpec([], await specDir());
expect(output.specDocuments?.operations).toBe(2);
expect(output.specDocuments?.destinations).toBe(2);
expect(output.specDocuments?.edges).toBe(2);
// Swapping the mapping would leave both of these arrays non-empty and both
// nodes present; only the TYPE distinguishes the two readings.
expect(edgesFrom('orders').map((e) => e.type)).toEqual(['PUBLISHES_TO']);
expect(edgesFrom('shipments').map((e) => e.type)).toEqual(['CONSUMES_FROM']);
});
it('gives a spec-minted destination NO file path, and its own provenance', async () => {
await runWithSpec([], await specDir());
const node = [...graph.iterNodes()].find(
(n) => n.id === generateId('Destination', destinationNodeKey('kafka', 'orders')),
);
// `filePath: ''` is load-bearing, not cosmetic: a connecting destination is
// shared by every site that names it, and the incremental writeback deletes
// by file. Stamping it with the document's path would make a shared node
// collateral damage of that document's next change, taking every OTHER
// referrer's edge with it via DETACH DELETE.
expect(node?.properties.filePath).toBe('');
// Distinct from `'specification'`, which belongs to the address cascade and
// means a CODE candidate was resolved through the step-4 hook — a claim
// about source that this node is not making.
expect(node?.properties.resolution).toBe('asyncapi-document');
});
it('reads documents even when the source pass found no messaging at all', async () => {
// The early return used to be keyed on source sites alone. A repository
// whose broker this codebase has no patterns for is exactly the case a
// published document covers, so skipping documents there would drop the
// feature where it is most needed.
const output = await runWithSpec([], await specDir());
expect(output.resolvedDestinations).toBe(0);
expect(output.specDocuments?.destinations).toBe(2);
});
it('lands a document and a source site on ONE node for one (broker, address)', async () => {
const filePath = 'src/Orders.java';
setJavaSpringNonHttpHandlerFacts(filePath, []);
setJavaSpringMessageProducerFacts(filePath, [
{
ownerScopeId: `${filePath}#publish` as never,
ownerRange: OWNER_RANGE,
template: 'kafka',
receiverName: 'kafkaTemplate',
methodName: 'send',
args: [{ text: '"orders"' }, { text: 'payload' }],
},
]);
callableNode(graph, filePath, 'publish');
const output = await runWithSpec([filePath], await specDir());
const nodeId = generateId('Destination', destinationNodeKey('kafka', 'orders'));
const nodes = [...graph.iterNodes()].filter((n) => n.id === nodeId);
expect(nodes).toHaveLength(1);
expect(nodes[0].properties.address).toBe('orders');
// The source pass ran first and owns the provenance; the document joined
// its node rather than minting a second one.
expect(nodes[0].properties.resolution).toBe('literal');
expect(output.resolvedDestinations).toBe(1);
expect(output.specDocuments?.destinations).toBe(1);
// Two edges into one node — the publisher's and the document's — which is
// the whole point: both halves of a conversation meet on one node. Asserted
// by TYPE rather than by count: a count of two survives a reversal in
// either of the two paths that produced them.
expect(edgesFrom('orders').map((e) => e.type)).toEqual(['PUBLISHES_TO', 'PUBLISHES_TO']);
});
it('hangs the edge off the documents REAL File node when it is in the repo', async () => {
// The in-repo branch is the one the code calls "strictly better", and it is
// the branch that decides whether the graph grows a permanent pseudo-File
// node per document. Without a test, deleting it is invisible.
const dir = await specDir();
// `repoPath` is the fixture directory, so the document resolves inside it.
const deps = new Map<string, PhaseResult<unknown>>([
[
'parse',
{ phaseName: 'parse', durationMs: 0, output: { allPaths: [], moduleConstants: new Map() } },
],
['scopeResolution', { phaseName: 'scopeResolution', durationMs: 0, output: {} }],
['springConfig', { phaseName: 'springConfig', durationMs: 0, output: {} }],
]);
const ctx = {
repoPath: dir,
graph,
onProgress: () => {},
pipelineStart: 0,
options: { asyncApiSpecPath: 'asyncapi.yaml' },
} as unknown as PipelineContext;
// The document sits at <dir>/asyncapi.yaml, so its repo-relative path is
// `asyncapi.yaml`; register that File node and expect the edge to use it.
const inRepoId = generateId('File', 'asyncapi.yaml');
graph.addNode({
id: inRepoId,
label: 'File',
properties: { name: 'asyncapi.yaml', filePath: 'asyncapi.yaml' },
});
await springDestinationsPhase.execute(ctx, deps);
const [edge] = edgesFrom('orders');
expect(edge.sourceId).toBe(inRepoId);
expect(edge.sourceId).not.toBe(generateId('File', 'asyncapi:asyncapi.yaml'));
});
it('never lets a document give an unresolved destination an address', async () => {
const filePath = 'src/Placeholder.java';
setJavaSpringNonHttpHandlerFacts(filePath, [
{
ownerScopeId: `${filePath}#consume` as never,
ownerFilePath: filePath,
ownerRange: OWNER_RANGE,
annotations: [
{ name: 'KafkaListener', args: [{ name: 'topics', text: '"${app.topic}"' }] },
],
},
]);
setJavaSpringMessageProducerFacts(filePath, []);
callableNode(graph, filePath, 'consume');
const output = await runWithSpec([filePath], await specDir());
expect(output.unresolvedDestinations).toBe(1);
const unresolved = [...graph.iterNodes()].filter(
(n) => n.label === 'Destination' && n.properties.resolution === 'unresolved-config-key',
);
expect(unresolved).toHaveLength(1);
// The document names real addresses, and one of them may even be the value
// behind this placeholder — but nothing here knows that, so the node keeps
// its location key and stays unjoinable.
expect(unresolved[0].properties.address).toBeUndefined();
});
it('hangs the edge off a synthetic File when the document is outside the repo', async () => {
await runWithSpec([], await specDir());
const [edge] = edgesFrom('orders');
const source = [...graph.iterNodes()].find((n) => n.id === edge.sourceId);
expect(source?.label).toBe('File');
expect(String(source?.properties.filePath)).toBe('asyncapi:asyncapi.yaml');
});
it('forwards a non-zero symlink count out of the reader', async () => {
// The phase's stats block is the operator's only view of what was read.
// Hard-coding these to zero passed every test, because the only assertion
// on them was an all-zeros comparison on an empty directory.
const dir = await specDir();
await symlink(path.join(dir, 'asyncapi.yaml'), path.join(dir, 'linked.yaml'));
const output = await runWithSpec([], dir);
expect(output.specDocuments?.symlinksSkipped).toBe(1);
});
it('warns, out loud, when a configured path yielded nothing', async () => {
// The stats block is justified on the grounds that an operator must be able
// to tell a mistyped directory from a repository with no documents. That is
// only true if the warn actually fires, and nothing asserted that it did —
// the block could be deleted with the suite green.
const empty = await mkdtemp(path.join(tmpdir(), 'gnx-phase-empty-'));
createdDirs.push(empty);
const populated = await specDir();
const capture = _captureLogger();
try {
await runWithSpec([], empty);
const warnings = capture
.records()
.filter((record) => (record as { level?: number }).level === 40);
expect(warnings).toHaveLength(1);
expect((warnings[0] as { accepted?: number }).accepted).toBe(0);
} finally {
capture.restore();
}
const quiet = _captureLogger();
try {
await runWithSpec([], populated);
expect(
quiet.records().filter((record) => (record as { level?: number }).level === 40),
).toHaveLength(0);
} finally {
quiet.restore();
}
});
it('omits the stats block entirely when no path was configured', async () => {
// Absent must stay distinguishable from "configured and found nothing":
// a mistyped directory and a repository with no documents need different
// answers from an operator, and one zero cannot say which happened.
const output = await runWithSpec([], undefined);
expect(output.specDocuments).toBeUndefined();
expect('specDocuments' in output).toBe(false);
});
it('reports a configured path that yielded nothing, rather than staying silent', async () => {
const empty = await mkdtemp(path.join(tmpdir(), 'gnx-phase-spec-empty-'));
const output = await runWithSpec([], empty);
expect(output.specDocuments).toEqual({
symlinksSkipped: 0,
truncated: false,
scanned: 0,
accepted: 0,
operations: 0,
destinations: 0,
edges: 0,
refusalsByReason: {},
});
});
});