Skip to content

feat: add consumer-side support for synchronous (request/response) messages - #562

Open
fabio-andre-rodrigues wants to merge 15 commits into
pact-foundation:masterfrom
fabio-andre-rodrigues:feat/sync-message-support
Open

fabio-andre-rodrigues wants to merge 15 commits into
pact-foundation:masterfrom
fabio-andre-rodrigues:feat/sync-message-support

Conversation

@fabio-andre-rodrigues

@fabio-andre-rodrigues fabio-andre-rodrigues commented Sep 24, 2026 •

Copy link
Copy Markdown

Summary

PactNet currently only supports writing asynchronous (fire-and-forget) message pacts (IPactV4.WithMessageInteractions()). There is no way to write a V4 synchronous (request/response) message pact - the type PactFlow uses for AsyncAPI 3 operations that have a reply block.

The underlying pact_ffi native library this project wraps already has most of what's needed:

  • pactffi_new_sync_message_interaction exists in the native lib, but wasn't yet declared in NativeInterop.cs
  • The existing generic pactffi_with_body / pactffi_with_metadata FFI functions (already used for HTTP interactions in this codebase) work against a synchronous message interaction handle too, since they take an InteractionPart (Request/Response)

The one missing piece was a way to retrieve the generated (matchers stripped, generators applied) request/response contents of a synchronous message interaction for the consumer test - pactffi_message_reify only supports async messages. I've proposed pactffi_sync_message_generate_contents upstream in pact-reference: pact-foundation/pact-reference#555

Changes

  • IPactV4.WithSynchronousMessageInteractions() - new entry point, parallel to WithMessageInteractions()
  • ISyncMessagePactBuilderV4 / ISyncMessageBuilderV4 / IConfiguredSyncMessageVerifier - public API mirroring the existing async IMessagePactBuilderV4 / IMessageBuilderV4 / IConfiguredMessageVerifier, but with separate WithRequest*/WithResponse* methods for request and response content/metadata
  • SyncMessageInteractionDriver / SyncMessageBuilder / SyncMessagePactBuilder / ConfiguredSyncMessageVerifier - internal implementation, following the existing async message classes as closely as possible
  • NativeInterop.NewSyncMessageInteraction, NativeInterop.WithMetadata (the InteractionPart-aware variant used for both HTTP and sync messages), NativeInterop.SyncMessageGenerateContents

ConfiguredSyncMessageVerifier.Verify<TRequest, TResponse> reads the generated request via ISyncMessageInteractionDriver.GenerateContents() and passes it to the handler under test; the response content is stored in the pact but not currently asserted against the handler's return value, matching the existing async Verify<T>(Action<T>) semantics (which likewise doesn't assert anything beyond "the handler didn't throw"). Response-value assertion could be a good follow-up once there's agreement on the right semantics for it.

Note: the async message driver/verifier keeps its existing Reify() naming untouched - only the new synchronous-message members use GenerateContents(), since that's less reliant on Pact-specific "reify" terminology for callers who don't need to know about it.

⚠️ Depends on an unreleased pact_ffi function

This PR depends on pactffi_sync_message_generate_contents, proposed in pact-reference#555 and not yet in any pact_ffi release. Until that lands:

  • Everything up to calling .Verify/.VerifyAsync works today, since it only relies on FFI functions that already exist in the currently pinned pact_ffi version.
  • ConfiguredSyncMessageVerifier.Verify/VerifyAsync will throw EntryPointNotFoundException at runtime, since pactffi_sync_message_generate_contents isn't in the native library yet.

I've marked the one FFI-level integration test (FfiIntegrationTests.SyncMessageInteraction_v4_CreatesPactFile) as Skip for the same reason, to keep CI green. Opening this as a draft to get early feedback on the API shape while the pact-reference PR is reviewed; happy to update the pinned pact_ffi version and un-skip that test once a release is available.

Test plan

  • dotnet build (all projects)
  • dotnet test tests/PactNet.Tests - 166 passed, 1 skipped (the FFI-dependent integration test noted above)
  • Added SyncMessageBuilderTests, SyncMessagePactBuilderTests, ConfiguredSyncMessageVerifierTests mirroring the existing async message test coverage
  • Documented the new API in docs/messaging-pacts.md

@fabio-andre-rodrigues
fabio-andre-rodrigues marked this pull request as ready for review September 24, 2026 14:54
@mefellows

Copy link
Copy Markdown
Member

Thanks @fabio-andre-rodrigues! Have you reviewed this against #551, which is about creating synchronous messages for plugins?

@adamrodger what's your view on how we should approach this?

There is also some inspo we can take from https://github.com/YOU54F/pact-net/tree/feat/sync-messaging

@fabio-andre-rodrigues

Copy link
Copy Markdown
Author

Thanks for the pointer, hadn't seen #551 yet. Just went through it.

They don't conflict behaviourally. #551 reuses pactffi_new_sync_message_interaction too, but for a completely different flow: it hands the plugin a raw content dict via pactffi_interaction_contents, spins up a real mock server on a transport (e.g. grpc), and drives an actual client against it. Verified via mismatches, the same as HTTP interactions. It never touches pactffi_sync_message_generate_contents, since there's a live server to hit instead of generated content to hand a test handler.

So I don't think the two need a unified API: one is generation-based consumer testing for plain sync messages (message queues, AsyncAPI reply blocks), the other is mock-server-based testing for plugin protocols. A single entry point covering both would need either two different code paths hidden behind one method, or forcing one model to do the other's job - and neither works. A message-queue consumer test has no client to dial a socket with; a gRPC client under test can't be exercised by handing it synthetic generated JSON instead of a real wire call. PactNet already draws this line between WithHttpInteractions() and WithMessageInteractions(), so I'd keep them as separate builder entry points (WithSynchronousMessageInteractions() here, something like WithSynchronousPluginInteractions(...) there) with consistent naming/shape, rather than merge the C# surface.

What will conflict mechanically, whichever of us merges second:

  • Both PRs declare NativeInterop.NewSyncMessageInteraction -> pactffi_new_sync_message_interaction. Duplicate member, compile error.
  • Add Synchronous Plugin Interaction Support  #551 reorganises Drivers/ into Drivers/Http/, Drivers/Message/, Drivers/Plugins/. I've already moved my sync message driver into Drivers/Message/ alongside the async one, so that part of the rebase is done on my end.

The YOU54F fork adds VerifyWithResponse/VerifyWithResponseAsync, which asserts the handler's returned response against the configured response. I've now added that to this PR: Verify/VerifyAsync check the handler's return value against the generated response content and throw if it doesn't match. Their implementation never calls pactffi_sync_message_generate_contents though - it compares the raw pre-generation JSON with a hand-rolled deep-equality check, so any matcher (Match.Type, regex) or generator (RandomInt etc.) in the response body wouldn't work right, since it needs literal equality between "expected" and "actual". Mine builds the same check on top of the FFI-generated content instead, so matchers/generators still apply.

@adamrodger, what's your take?

@adamrodger

Copy link
Copy Markdown
Contributor

Well, that's certainly a big one 😂

I think this needs a more in depth review, and needs taking into account alongside other PRs to do with sync/async messaging and plugins. I'll confess I've got really lost in the terminology and use cases of all of the interaction modes now on offer, and trying to keep up as a volunteer is very difficult.

Perhaps I can lean on @mefellows and @YOU54F to start to distill some of this info a plan - the interaction modes we need to support, the FFI methods that support them and the in-flight PRs that might address these. Then we can start to think about how to bring them all together into a rational API (although the above sounds like some good thought has already gone into that, so thank you @fabio-andre-rodrigues).

I want to get this landed, but it's a big old task that we don't really want to fumble, so I think needs more concentrated effort. I'd appreciate any help from the full time members of the Pact crew to map out what needs to happen ❤️

@fabio-andre-rodrigues

fabio-andre-rodrigues commented Sep 29, 2026 •

Copy link
Copy Markdown
Author

@adamrodger here's a map of the messaging modes, the FFI behind each one, and where the open PRs fit.

Modes

Mode Consumer test Provider verification
Async message FFI generates the message; the test passes it to a handler verifier asks PactNet's in-process messaging server for the message by description
Sync message FFI generates the request; the test passes it to a handler and checks the returned response same messaging server, which only sees the description, not the request
Plugin sync message (gRPC etc.) FFI loads the plugin and starts a mock server on its transport; a real client calls it, like HTTP not supported in PactNet

Sync and plugin sync both write Synchronous/Messages to the pact file, but one test generates content and the other runs a mock server. That's why #562 and #551 are separate entry points.

FFI → PactNet

Async (master)

PactNet FFI
ExpectsToReceive pactffi_new_message_interaction
Given pactffi_given, pactffi_given_with_param
WithMetadata pactffi_message_with_metadata (deprecated, strings only; replaced by pactffi_with_metadata)
WithJsonContent pactffi_message_with_contents
Verify pactffi_message_reify, pactffi_pact_handle_write_file

Sync (#562)

PactNet FFI
WithSynchronousMessageInteractions().ExpectsToReceive pactffi_new_sync_message_interaction
WithRequestJsonContent / WithResponseJsonContent pactffi_with_body (Request / Response)
WithRequestMetadata / WithResponseMetadata pactffi_with_metadata (Request / Response)
Verify pactffi_sync_message_generate_contents (merged in pact-reference, not released yet)

Plugin sync (#551)

PactNet FFI
WithSynchronousPluginInteractions(plugin, version, transport) pactffi_using_plugin
UponReceiving pactffi_new_sync_message_interaction
WithContent pactffi_interaction_contents
Verify pactffi_create_mock_server_for_transport, pactffi_mock_server_mismatches, pactffi_write_pact_file, pactffi_cleanup_plugins

Provider side, all modes: pactffi_verifier_set_provider_info + pactffi_verifier_add_provider_transport.

@YOU54F

YOU54F commented Oct 5, 2026

Copy link
Copy Markdown
Member

Happy to help review this PR and others, @fabio-andre-rodrigues has done a really excellent overview of the modes and functions above. I'll put it on my list for this week, as would love to see these changes land in pact-net <3

@YOU54F

YOU54F commented Oct 7, 2026

Copy link
Copy Markdown
Member

Hey @fabio-andre-rodrigues, released 0.5.10 of the ffi with your merged PR bringing in the new function pactffi_sync_message_generate_contents.

@fabio-andre-rodrigues

Copy link
Copy Markdown
Author

Updated on top of pact_ffi 0.5.10:

  • 82395a4 is the same commit as chore(ffi): upgrade to pact-ffi 0.5.10 #566 (cherry-picked to test end to end). It drops out when this rebases after chore(ffi): upgrade to pact-ffi 0.5.10 #566 merges.
  • 774224f fix: response metadata was always dropped. pactffi_with_metadata only applies to responses that already exist, and the response is created by the terminal WithResponseJsonContent. Metadata values are now serialised as JSON, so 1, "1", true and matchers keep their type.
  • a0a1e67 un-skips the FFI integration test and adds public API tests with pact fixtures.
  • 11a2a3b WithReference(group, name, value) on the sync builder, via pactffi_add_interaction_reference, same signature as feat: Add AsyncAPI reference support for message pacts (#557) #559.
  • 8b8a146 Verify checks the handler's response against the response matchers, not by exact equality. Match.Type("shipped") accepts any string, Match.Integer any integer, Match.Regex a format such as a datetime.

8b8a146 depends on pactffi_sync_message_match_response_contents from pact-foundation/pact-reference#557, so CI fails on those tests until a pact_ffi release includes it. Against a local build of that branch, all 180 tests pass on net8.0 and net462.

@YOU54F YOU54F left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested e2e with pact-foundation/pact-reference#557

nice work.

Appreciate the docs update, I think the last cherry on top would be updating the sample app to cover a sync message use case.

Merged in Max's changes from #551, there are a copy of minor changes, dupe ffi import, and the namespace for the message drivers.

src/PactNet/Drivers/IMessageInteractionDriver.cs renamed to src/PactNet/Drivers/Message/IMessageInteractionDriver.cs

but apart from that merged cleanly and everything is green, I'll mark as approved once the next ffi change is merged/released, sample app updated.

Hopefully by then Max's change will land, and we can rebase of it, and get this out.

@mefellows

Copy link
Copy Markdown
Member

Great work @fabio-andre-rodrigues, and thank you for the review Yousaf!

@adamrodger The compatibility suite might be a good guide in terms of what should be supported: https://github.com/pact-foundation/pact-compatibility-suite/blob/main/features/V4/synchronous_message_consumer.feature

I don't think it includes plugins however, so that's probably something we ought to review and get into the suite (cc @rholshausen @JP-Ellis)

What do you think would most help here @adamrodger - perhaps a walk-through / mob programming session?

@YOU54F

YOU54F commented Oct 15, 2026

Copy link
Copy Markdown
Member

YOU54F and others added 15 commits October 16, 2026 16:46
Update native library downloads and refresh Rust version metadata in
integration fixtures and the Orders API sample pact.

Retain existing repeated-header expectations and pact representations.
…ssages

PactNet already supports writing asynchronous (fire-and-forget) message
pacts, but had no way to write V4 synchronous message pacts (used by e.g.
AsyncAPI 3 operations with a reply block), even though the underlying
pact_ffi native library already exposes pactffi_new_sync_message_interaction
and can set request/response bodies and metadata on it via the existing
generic pactffi_with_body/pactffi_with_metadata functions.

This adds:
- IPactV4.WithSynchronousMessageInteractions() entry point
- ISyncMessagePactBuilderV4 / ISyncMessageBuilderV4 / IConfiguredSyncMessageVerifier
  public API, mirroring the existing async IMessagePactBuilderV4 API
- SyncMessageInteractionDriver, wiring the above onto the native FFI calls

The consumer-side Verify<TRequest, TResponse> reads the generated request
contents (matchers stripped, generators applied) via the new
pactffi_sync_message_reify FFI function and feeds it to the handler under
test; the response content is stored but not currently asserted against,
matching the existing async message Verify<T> semantics.

Depends on pactffi_sync_message_reify, proposed in
pact-foundation/pact-reference#555. Until that lands
in a released pact_ffi build, calling ConfiguredSyncMessageVerifier.Verify
will fail with EntryPointNotFoundException - the corresponding FFI
integration test is marked Skip until then.
Removed redundant phrase from summary comment.
Callers of PactNet don't need to know the Pact-internal term "reify" -
GenerateContents describes what the method actually returns. Matches the
pactffi_sync_message_generate_contents rename on the pact-reference side
(pact-foundation/pact-reference#555). The pre-existing async message
Reify()/pactffi_message_reify naming is untouched.
Adds a section to messaging-pacts.md covering WithSynchronousMessageInteractions,
alongside the existing fire-and-forget message docs. Notes that provider
verification isn't covered yet and that this depends on
pactffi_sync_message_generate_contents landing upstream.
Removed information about provider verification support and related issues.
MessageInteractionDriver.Reify() and SyncMessageInteractionDriver.GenerateContents()
copied the FFI-returned string into managed memory but never freed the
native allocation, leaking it on every call.
Verify/VerifyAsync already required the handler to return a TResponse
but never checked it, so a consumer test would pass regardless of what
the handler returned. Compare it against the FFI-generated response
content (matchers stripped, generators applied) via a structural JSON
equality check, so a mismatch fails the test instead of being silently
written to the pact file.
pact-foundation#551 reorganises Drivers/ into Http/, Message/ and Plugins/
subfolders. The sync message driver belongs in Message/ alongside the
async one, since it's the same message-queue-style request/response
category, not a plugin. Namespace stays PactNet.Drivers for now since
the rest of the tree hasn't moved yet; that follows once pact-foundation#551 lands.
pactffi_with_metadata only applies response metadata to responses that
already exist, and the response is created by the terminal
WithResponseJsonContent call, so response metadata was always dropped.
The builder now buffers it and applies it after the response content.

Request/response metadata values are now dynamic and serialised as JSON,
so strings, numbers, booleans and matchers keep their type in the pact
instead of relying on the FFI's parse-or-fallback-to-string behaviour.
Un-skip the FFI integration test now that 0.5.10 ships
pactffi_sync_message_generate_contents, and compare the written pact
against a fixture. Add public API tests for
WithSynchronousMessageInteractions covering body matchers, typed
metadata, response metadata matchers and a mismatching response.
Links a sync message interaction to an external resource such as an
AsyncAPI operation via pactffi_add_interaction_reference, written to
comments.references.{group}.{name}. Same signature as the async
WithReference proposed in pact-foundation#559.

The FFI parses the value as JSON, so the driver encodes it to keep a
string reference value a string in the pact.
Verify/VerifyAsync compared the handler's response to the generated
example by exact JSON equality, so a type matcher still required the
example value. They now call pactffi_sync_message_match_response_contents,
which applies the response's matching rules the same way the verifier
does: Match.Type checks the type of the example, Match.Integer and
Match.Decimal the kind of number, Match.Regex the format (e.g. datetimes),
and unexpected keys are allowed. Mismatches are reported by path.

Requires a pact_ffi release with pactffi_sync_message_match_response_contents.
Aligns the sync message integration fixtures with the ffi 0.5.12 /
models 1.3.17 metadata from the pact-ffi upgrade.
@YOU54F

YOU54F commented Nov 13, 2026

Copy link
Copy Markdown
Member

Hey @fabio-andre-rodrigues,

Check out the comments here

#551 (comment)

You can rebase off #569

Hoping to get this out soon 🤞🏾

@YOU54F YOU54F mentioned this pull request Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants