From ecd631ea797b157663ff24aab2d1170603915396 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 2 Nov 2026 15:48:52 +0000 Subject: [PATCH] fix: return clear errors instead of "Error in native callback" (#406) Some FFI methods that don't return a status were not wrapped, so a core failure reached users as a generic "Error in native callback". - mismatches, message reify and log buffer return null from native code when the core returns NULL, and free the core's strings - mockServerMismatches and reifyMessage throw a clear error on null - message interaction methods are checked like the HTTP ones - errors reading verifier results reject the promise instead of being thrown from the native callback Fixes #406 Co-Authored-By: Claude Opus 5.5 --- native/consumer.cc | 26 ++++++- src/consumer/checkErrors.spec.ts | 28 ++++++- src/consumer/checkErrors.ts | 42 +++++++++-- src/consumer/index.ts | 125 ++++++++++++++++--------------- src/consumer/internals.spec.ts | 59 +++++++++++++++ src/consumer/internals.ts | 20 ++++- src/ffi/types.ts | 6 +- src/verifier/nativeVerifier.ts | 14 +++- 8 files changed, 241 insertions(+), 79 deletions(-) create mode 100644 src/consumer/internals.spec.ts diff --git a/native/consumer.cc b/native/consumer.cc index c413a99b..2d7d9439 100644 --- a/native/consumer.cc +++ b/native/consumer.cc @@ -95,7 +95,14 @@ Napi::Value PactffiFetchLogBuffer(const Napi::CallbackInfo& info) { const char* buffer = pactffi_fetch_log_buffer(log_id.c_str()); - return Napi::String::New(env, buffer); + if (buffer == NULL) { + return env.Null(); + } + + Napi::String logs = Napi::String::New(env, buffer); + pactffi_string_delete((char*)buffer); + + return logs; } /** @@ -184,6 +191,12 @@ Napi::Value PactffiMockServerMismatches(const Napi::CallbackInfo& info) { int32_t port = info[0].As().Int32Value(); char* res = pactffi_mock_server_mismatches(port); + // NULL when there is no mock server on the port, or the core panicked. + // Napi::String::New(env, NULL) would throw "Error in native callback". + if (res == NULL) { + return env.Null(); + } + return Napi::String::New(env, res); } @@ -1957,9 +1970,16 @@ Napi::Value PactffiMessageReify(const Napi::CallbackInfo& info) { MessageHandle handle = info[0].As().Uint32Value(); - auto res = pactffi_message_reify(handle); + const char* res = pactffi_message_reify(handle); - return Napi::String::New(env, res); + if (res == NULL) { + return env.Null(); + } + + Napi::String reified = Napi::String::New(env, res); + pactffi_string_delete((char*)res); + + return reified; } /** diff --git a/src/consumer/checkErrors.spec.ts b/src/consumer/checkErrors.spec.ts index 9208c1a0..5980bb2d 100644 --- a/src/consumer/checkErrors.spec.ts +++ b/src/consumer/checkErrors.spec.ts @@ -1,5 +1,5 @@ import logger from '../logger'; -import { wrapWithCheck } from './checkErrors'; +import { wrapAllWithResultCheck, wrapWithCheck } from './checkErrors'; describe('checkErrors', () => { const originalPactCrash = logger.pactCrash; @@ -33,4 +33,30 @@ describe('checkErrors', () => { expect(result).toBe(1); expect(called).toBe(true); }); + + describe('wrapAllWithResultCheck', () => { + it('checks status results and returns other results unchanged', () => { + const crashes: string[] = []; + logger.pactCrash = (message: string) => { + crashes.push(message); + }; + const contents = Buffer.from('contents'); + + const wrapped = wrapAllWithResultCheck({ + given: () => false, + setKey: () => true, + reifyMessage: () => '{"a":1}', + getRequestContents: () => contents, + withMetadata: () => undefined, + }); + + expect(wrapped.given()).toBe(false); + expect(wrapped.setKey()).toBe(true); + expect(wrapped.reifyMessage()).toBe('{"a":1}'); + expect(wrapped.getRequestContents()).toBe(contents); + expect(wrapped.withMetadata()).toBeUndefined(); + expect(crashes).toHaveLength(1); + expect(crashes[0]).toContain("at 'given'"); + }); + }); }); diff --git a/src/consumer/checkErrors.ts b/src/consumer/checkErrors.ts index ce8bf997..d5926553 100644 --- a/src/consumer/checkErrors.ts +++ b/src/consumer/checkErrors.ts @@ -1,5 +1,17 @@ import logger from '../logger'; +const checkResult = (result: unknown, contextMessage: string): void => { + if (typeof result !== 'boolean' && typeof result !== 'number') { + return; + } + const failed = typeof result === 'number' ? result !== 0 : !result; + if (failed) { + logger.pactCrash( + `The pact consumer core returned false at '${contextMessage}'. This\nshould only happen if the core methods were invoked out of order`, + ); + } +}; + export const wrapWithCheck = boolean | number>( f: CheckableFunction, @@ -7,13 +19,8 @@ export const wrapWithCheck = ) => (...args: Parameters): ReturnType => { const result = f(...args); - const failed = typeof result === 'number' ? result !== 0 : !result; - if (failed) { - logger.pactCrash( - `The pact consumer core returned false at '${contextMessage}'. This\nshould only happen if the core methods were invoked out of order`, - ); - } - return result; + checkResult(result, contextMessage); + return result as ReturnType; }; type CheckableFunction = T extends (...args: infer A) => boolean | number @@ -38,3 +45,24 @@ export const wrapAllWithCheck = >( (acc, curr) => Object.assign(acc, curr), {} as CheckableFunctions, ) as T; + +/** + * Like `wrapAllWithCheck`, for objects whose functions don't all return a + * status (such as messages, which also return contents). Boolean and numeric + * results are checked; any other result is returned unchanged. + */ +export const wrapAllWithResultCheck = < + T extends Record unknown>, +>( + o: T, +): T => + Object.fromEntries( + Object.entries(o).map(([key, f]) => [ + key, + (...args: never[]) => { + const result = f(...args); + checkResult(result, key); + return result; + }, + ]), + ) as T; diff --git a/src/consumer/index.ts b/src/consumer/index.ts index 6a1722db..b0fabbce 100644 --- a/src/consumer/index.ts +++ b/src/consumer/index.ts @@ -13,8 +13,12 @@ import { logErrorAndThrow, setLogLevel, } from '../logger'; -import { wrapAllWithCheck, wrapWithCheck } from './checkErrors'; -import { mockServerMismatches, writePact } from './internals'; +import { + wrapAllWithCheck, + wrapAllWithResultCheck, + wrapWithCheck, +} from './checkErrors'; +import { mockServerMismatches, reifyMessage, writePact } from './internals'; import type { AsynchronousMessage, ConsumerInteraction, @@ -76,60 +80,61 @@ const asyncMessage = ( pactPtr: number, messageCount: number, index: number, -) => ({ - // todo count the number of messages (and ref them?) - // Required to get contents - withPluginRequestInteractionContents: ( - contentType: string, - contents: string, - ) => { - return setPluginInteractionContents( - ffi, - interactionPtr, - INTERACTION_PART_REQUEST, - contentType, - contents, - ); - }, - expectsToReceive: (description: string) => - ffi.pactffiMessageExpectsToReceive(interactionPtr, description), - given: (state: string) => ffi.pactffiMessageGiven(interactionPtr, state), - givenWithParam: (state: string, name: string, value: string) => - ffi.pactffiMessageGivenWithParam(interactionPtr, state, name, value), - givenWithParams: (state: string, params: string) => - ffi.pactffiMessageGivenWithParams(interactionPtr, state, params), - setPending: (pending: boolean) => - ffi.pactffiSetPending(interactionPtr, pending), - setKey: (value: string) => ffi.pactffiSetKey(interactionPtr, value), - setComment: (key: string, value: string) => - ffi.pactffiSetComment(interactionPtr, key, value), - addTextComment: (comment: string) => - ffi.pactffiAddTextComment(interactionPtr, comment), - addInteractionReference: (group: string, name: string, value: string) => - ffi.pactffiAddInteractionReference(interactionPtr, group, name, value), - setInteractionTestName: (name: string) => - ffi.pactffiInteractionTestName(interactionPtr, name), - withContents: (body: string, contentType: string) => - ffi.pactffiMessageWithContents(interactionPtr, contentType, body), - withBinaryContents: (body: Buffer, contentType: string) => - ffi.pactffiMessageWithBinaryContents( - interactionPtr, - contentType, - body, - body.length, - ), - withMatchingRules: (rules: string) => - ffi.pactffiWithMatchingRules( - interactionPtr, - INTERACTION_PART_REQUEST, - rules, - ), - reifyMessage: () => ffi.pactffiMessageReify(interactionPtr), - withMetadata: (name: string, value: string) => - ffi.pactffiMessageWithMetadata(interactionPtr, name, value), - getRequestContents: () => - ffi.pactffiGetAsyncMessageRequestContents(pactPtr, messageCount, index), -}); +): AsynchronousMessage => + wrapAllWithResultCheck({ + // todo count the number of messages (and ref them?) + // Required to get contents + withPluginRequestInteractionContents: ( + contentType: string, + contents: string, + ) => { + return setPluginInteractionContents( + ffi, + interactionPtr, + INTERACTION_PART_REQUEST, + contentType, + contents, + ); + }, + expectsToReceive: (description: string) => + ffi.pactffiMessageExpectsToReceive(interactionPtr, description), + given: (state: string) => ffi.pactffiMessageGiven(interactionPtr, state), + givenWithParam: (state: string, name: string, value: string) => + ffi.pactffiMessageGivenWithParam(interactionPtr, state, name, value), + givenWithParams: (state: string, params: string) => + ffi.pactffiMessageGivenWithParams(interactionPtr, state, params), + setPending: (pending: boolean) => + ffi.pactffiSetPending(interactionPtr, pending), + setKey: (value: string) => ffi.pactffiSetKey(interactionPtr, value), + setComment: (key: string, value: string) => + ffi.pactffiSetComment(interactionPtr, key, value), + addTextComment: (comment: string) => + ffi.pactffiAddTextComment(interactionPtr, comment), + addInteractionReference: (group: string, name: string, value: string) => + ffi.pactffiAddInteractionReference(interactionPtr, group, name, value), + setInteractionTestName: (name: string) => + ffi.pactffiInteractionTestName(interactionPtr, name), + withContents: (body: string, contentType: string) => + ffi.pactffiMessageWithContents(interactionPtr, contentType, body), + withBinaryContents: (body: Buffer, contentType: string) => + ffi.pactffiMessageWithBinaryContents( + interactionPtr, + contentType, + body, + body.length, + ), + withMatchingRules: (rules: string) => + ffi.pactffiWithMatchingRules( + interactionPtr, + INTERACTION_PART_REQUEST, + rules, + ), + reifyMessage: () => reifyMessage(ffi, interactionPtr), + withMetadata: (name: string, value: string) => + ffi.pactffiMessageWithMetadata(interactionPtr, name, value), + getRequestContents: () => + ffi.pactffiGetAsyncMessageRequestContents(pactPtr, messageCount, index), + }); /** * Returns the PEM encoded CA certificate used by TLS mock servers, or null if it is @@ -268,7 +273,7 @@ export const makeConsumerPact = ( const index = messageCount; messageCount += 1; - return { + return wrapAllWithResultCheck({ withPluginRequestInteractionContents: ( contentType: string, contents: string, @@ -382,7 +387,7 @@ export const makeConsumerPact = ( messageCount, index, ), - }; + }); }, pactffiCreateMockServerForTransport( address: string, @@ -661,7 +666,7 @@ export const makeConsumerMessagePact = ( // TODO: will this automatically set the correct spec version? const interactionPtr = ffi.pactffiNewSyncMessage(pactPtr, description); - return { + return wrapAllWithResultCheck({ withPluginRequestInteractionContents: ( contentType: string, contents: string, @@ -775,7 +780,7 @@ export const makeConsumerMessagePact = ( messageCount, index, ), - }; + }); }, pactffiCreateMockServerForTransport( address: string, diff --git a/src/consumer/internals.spec.ts b/src/consumer/internals.spec.ts new file mode 100644 index 00000000..dfb816b6 --- /dev/null +++ b/src/consumer/internals.spec.ts @@ -0,0 +1,59 @@ +import type { Ffi } from '../ffi/types'; +import logger from '../logger'; +import { mockServerMismatches, reifyMessage } from './internals'; + +describe('internals', () => { + const originalPactCrash = logger.pactCrash; + + beforeEach(() => { + logger.pactCrash = () => {}; + }); + + afterEach(() => { + logger.pactCrash = originalPactCrash; + }); + + describe('#mockServerMismatches', () => { + it('parses the mismatches from the core', () => { + const ffi = { + pactffiMockServerMismatches: () => + JSON.stringify([ + { + type: 'request-mismatch', + mismatches: ['{"type":"QueryMismatch"}'], + }, + ]), + } as unknown as Ffi; + + expect(mockServerMismatches(ffi, 1234)).toEqual([ + { type: 'request-mismatch', mismatches: [{ type: 'QueryMismatch' }] }, + ]); + }); + + it('throws a clear error when the core returns no mismatches', () => { + const ffi = { + pactffiMockServerMismatches: () => null, + } as unknown as Ffi; + + expect(() => mockServerMismatches(ffi, 1234)).toThrow( + /mismatches for the mock server on port 1234/, + ); + }); + }); + + describe('#reifyMessage', () => { + it('returns the reified message', () => { + const ffi = { + pactffiMessageReify: () => '{"contents":"a"}', + } as unknown as Ffi; + + expect(reifyMessage(ffi, 1)).toBe('{"contents":"a"}'); + }); + + it('throws a clear error when the core returns no message', () => { + const ffi = { pactffiMessageReify: () => null } as unknown as Ffi; + + expect(() => reifyMessage(ffi, 1)).toThrow(/unable to reify the message/); + }); + }); +}); diff --git a/src/consumer/internals.ts b/src/consumer/internals.ts index c69d0ff5..68ab3130 100644 --- a/src/consumer/internals.ts +++ b/src/consumer/internals.ts @@ -10,9 +10,13 @@ export const mockServerMismatches = ( ffi: Ffi, port: number, ): MatchingResult[] => { - const results: MatchingResult[] = JSON.parse( - ffi.pactffiMockServerMismatches(port), - ); + const mismatches = ffi.pactffiMockServerMismatches(port); + if (mismatches === null) { + return logCrashAndThrow( + `The pact core couldn't return the mismatches for the mock server on port ${port}. The mock server may have already been cleaned up, or the core panicked`, + ); + } + const results: MatchingResult[] = JSON.parse(mismatches); return results.map((result: MatchingResult) => ({ ...result, ...('mismatches' in result @@ -60,3 +64,13 @@ export const writePact = ( ); } }; + +export const reifyMessage = (ffi: Ffi, interactionPtr: number): string => { + const reified = ffi.pactffiMessageReify(interactionPtr); + if (reified === null) { + return logCrashAndThrow( + 'The pact core was unable to reify the message. Check that the message contents are valid', + ); + } + return reified; +}; diff --git a/src/ffi/types.ts b/src/ffi/types.ts index 71bed413..7a2d411e 100644 --- a/src/ffi/types.ts +++ b/src/ffi/types.ts @@ -227,14 +227,14 @@ export type FfiConsumerFunctions = { ): FfiWritePactResponse; pactffiCleanupMockServer(port: number): boolean; pactffiMockServerMatched(port: number): boolean; - pactffiMockServerMismatches(port: number): string; + pactffiMockServerMismatches(port: number): string | null; pactffiGetTlsCaCertificate(): string | null; pactffiLogMessage(source: string, logLevel: string, message: string): void; pactffiLogToBuffer(level: FfiLogLevelFilter): number; pactffiInitWithLogLevel(level: string): void; pactffiLogToStdout(level: FfiLogLevelFilter): number; pactffiLogToFile(fileName: string, level: FfiLogLevelFilter): number; - pactffiFetchLogBuffer(logId: number): string; + pactffiFetchLogBuffer(logId: number): string | null; pactffiUsingPlugin( handle: FfiPactHandle, name: string, @@ -328,7 +328,7 @@ export type FfiConsumerFunctions = { key: string, value: string, ): void; - pactffiMessageReify(handle: FfiMessageHandle): string; + pactffiMessageReify(handle: FfiMessageHandle): string | null; pactffiGetAsyncMessageRequestContents( pact: FfiPactHandle, messageCount: number, diff --git a/src/verifier/nativeVerifier.ts b/src/verifier/nativeVerifier.ts index c8e7316c..90a69a28 100644 --- a/src/verifier/nativeVerifier.ts +++ b/src/verifier/nativeVerifier.ts @@ -26,8 +26,18 @@ export const verify = (opts: VerifierOptions): Promise => { ffi.pactffiVerifierExecute(handle, (err: Error, res: number) => { logger.debug(`shutting down verifier with handle ${handle}`); - const results = ffi.pactffiVerifierJson(handle); - ffi.pactffiVerifierShutdown(handle); + // This callback is called from native code, so an error thrown here would + // reach the user as "Error in native callback" instead of a rejection + let results: string; + try { + results = ffi.pactffiVerifierJson(handle); + } catch (e) { + logger.pactCrash(`Unable to read the verification results: ${e}`); + reject(e); + return; + } finally { + ffi.pactffiVerifierShutdown(handle); + } logger.debug(`response from verifier: ${err}, ${res}`); if (err) {