natenho / Mockaco

🐵 HTTP mock server, useful to stub services and simulate dynamic API responses, leveraging ASP.NET Core features, built-in fake data generation and pure C# scripting
https://natenho.github.io/Mockaco/
Other
336 stars 39 forks source link

Optimize redundant mock scripts evaluation #103

Open w-ess opened 2 years ago

w-ess commented 2 years ago

Prerequisites

Description

Redundant script evaluation

Steps to reproduce

Given a mock with a single custom script in the body. Calling its respective method, the script will be evaluated twice.

Expected behavior

The script should be evaluated once.

Screenshots

image image

Additional context

No response

natenho commented 2 years ago

Hello @w-ess , could you provide more details? how are you noticing the duplication? I've just sent an e-mail so we can work on your case

w-ess commented 2 years ago

Hi, example sent by e-mail

natenho commented 2 years ago

The behavior described in this issue is actually by design and is caused by multiple template transformations occurring along the mocking pipeline, leading to re-evaluation of script snippets.

For instance, given the mock in the provided screenshot, the script <#= TesteObterLInk.ObterLinl() #> will be executed at 2 distinct moments:

1) Before deciding which mock to return, it needs to transform each template to evaluate the "condition" field of each one: https://github.com/natenho/Mockaco/blob/c3dcc72acb2d82155c8125721925693573a53af6/src/Mockaco.AspNetCore/Templating/Request/RequestConditionMatcher.cs#L47

Given that the condition is dynamic, the mock must not be returned when it is evaluated to false. This is step could be optimized to partially evaluate the template, looking only for the condition field

2) After deciding which mock to return, we need to effectively produce the output: https://github.com/natenho/Mockaco/blob/c3dcc72acb2d82155c8125721925693573a53af6/src/Mockaco.AspNetCore/Middlewares/RequestMatchingMiddleware.cs#L58

This stage leads to re-evaluation of mock scripts, this time with all context variables available (like route variables).

There is also a third possible moment where the script might be evaluated again, when using the callback template: https://github.com/natenho/Mockaco/blob/c3dcc72acb2d82155c8125721925693573a53af6/src/Mockaco.AspNetCore/Middlewares/CallbackMiddleware.cs#L62

@w-ess I'll change the title of the issue and consider this optimization as an improvement instead of an actual bug.