Skip to content

cache filter: Create an abstract test fixture for HttpCache implementations. - #19828

Merged
jmarantz merged 10 commits into
envoyproxy:mainfrom
mkbehr:http-cache-implementation-test
Feb 25, 2022
Merged

jmarantz merged 10 commits into
envoyproxy:mainfrom
mkbehr:http-cache-implementation-test

Conversation

@mkbehr

@mkbehr mkbehr commented Feb 4, 2022

Copy link
Copy Markdown
Contributor

Commit Message: cache filter: Create an abstract test fixture for HttpCache implementations.
Additional Description:
Move SimpleHttpCacheTest into a new HttpCacheImplementationTest filter. Other
HttpCache implementations can reuse the tests in HttpCacheImplementationTest by
defining an HttpCacheTestDelegate, which wraps the cache.

HttpCacheTestDelegate allows caches to specify whether or not they support
validating stale cache entries and updating their headers. The relevant tests
from SimpleHttpCacheTest are split into different versions to run depending on
whether or not the cache supports validation.

This also moves operator definitions out of
test/extensions/filters/http/cache/common.h to avoid linker errors.

Risk Level: Low
Testing: bazel test //test/extensions/filters/http/cache/...
Docs Changes: N/A
Release Notes: N/A
Platform Specific Features: N/A

Move SimpleHttpCacheTest into a new HttpCacheImplementationTest filter. Other
HttpCache implementations can reuse the tests in HttpCacheImplementationTest by
defining an HttpCacheTestDelegate, which wraps the cache.

HttpCacheTestDelegate allows caches to specify whether or not they support
validating stale cache entries and updating their headers. The relevant tests
from SimpleHttpCacheTest are split into different versions to run depending on
whether or not the cache supports validation.

This also moves operator definitions out of
test/extensions/filters/http/cache/common.h to avoid linker errors.

Signed-off-by: Michael Behr <[email protected]>
Signed-off-by: Michael Behr <[email protected]>

@capoferro capoferro left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks good, overall. Very minor comments added. Thanks for getting this in.


TEST_P(HttpCacheImplementationTest, VaryOnDisallowedKey) {
// Responses will vary on accept.
const std::string RequestPath("some-resource");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

across the tests, we should use lowercase underscore style. request_path, body1, etc.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done.


TEST_P(HttpCacheImplementationTest, VaryOnDisallowedKey) {
// Responses will vary on accept.
const std::string RequestPath("some-resource");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The path should be a real path, with a leading forward slash.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done.

Http::TestResponseHeaderMapImpl response_headers_1{{"date", time_value_1},
{"cache-control", "public,max-age=3600"},
{"accept", "image/*"},
{"vary", "accept"}};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

:status is set in other response headers. Perhaps we should set it in all of the tests' response headers (there's a mix of whether we set it or not).

On that note, I wonder if we should extract a "makeTestResponseHeaders()" function or something to give a base set of headers that the individual tests modify.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Put :status everywhere.

For now I think the base set of headers is too small for the helper to be worth it - it's just :status, and date for most but not all of the tests. So it'd save one or two lines for each test at the tradeoff of adding an extra step of indirection to read what the headers are, IMO not worth it.

}
const std::string actual_body = getBody(*lookup_context, 0, body.size());
if (body != actual_body) {
return AssertionFailure() << "Expected body == " << body << "\n Actual: " << actual_body;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Optional: Perhaps absl::StrFormat() is easier to read in a bunch of these concatenated strings?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I can't find a way to customize how absl::StrFormat() or absl::Substitute() print values to strings, so we'd have to add string converstion boilerplate which probably balances out the readability gains.

@jmarantz

jmarantz commented Feb 8, 2022

Copy link
Copy Markdown
Contributor

Thanks Michael -- I'll take a look once @capoferro LGTMs

capoferro
capoferro previously approved these changes Feb 9, 2022
@capoferro

Copy link
Copy Markdown
Contributor

@jmarantz Do we still need a reviewer from outside Google?

@jmarantz

jmarantz commented Feb 9, 2022

Copy link
Copy Markdown
Contributor

I think we don't need one for this extension and I'll try to review later today or tomorrow AM, and only defer to others if I see something concerning in the data plane.

Signed-off-by: Michael Behr <[email protected]>

@jmarantz jmarantz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I haven't finished looking at it but I found a concern I think it's worth addressing first before I do a complete pass. Thanks!

/wait

s += request_cache_control.max_stale_.has_value()
? "max-stale=" + std::to_string(request_cache_control.max_stale_.value().count()) + ", "
: "";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

WYDT about one call to absl::StrCat for lines 9-23, rather than all these incremental appends?


// For responses with body and trailers, wait for insertBody's callback before
// calling insertTrailers.
std::promise<absl::Status> insert_promise;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think this will be the first use of std::promise in Envoy. Not sure if that's a concern or not.

I'm not sure how it would interact in production code with the siloed/async threading model but maybe it's OK for tests?

I think should probably get someone else to weigh in on this also, but for now I asked on Slack.

In the meantime I have a functional issue with your usage below.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'd expect std::promise without std::async to be fine, since this isn't launching any new threads, just serving as a container to report the value. If there's a problem I can rewrite it to be a mutex-protected value and notification.

/*end_stream=*/!trailers.has_value());

std::future<absl::Status> insert_future = insert_promise.get_future();
if (insert_future.wait_for(timeout) != std::future_status::ready) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think this won't work with simulated time. See test/test_common/test_time_system.h and use TestTimeSystem::waitFor instead.

I'm hoping this will go smoothly!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is here to let the test fail gracefully if the cache never calls the insert-done callback, instead of waiting forever. That means it does have to be wall-clock time, since there's no guarantee that advancing the simulated clock will make the callback fire.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Oh, never mind, I see what you mean. Will make that change tomorrow.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Tests pass fine with TestTimeSystem::waitFor, but I'm getting a format script error that I can't find a way around:

ERROR: ./test/extensions/filters/http/cache/http_cache_implementation_test_common.cc:138: Don't reference real-world time sources; use TimeSystem::advanceTime(Wait|Async)

Do you know what's wrong there?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Yes -- the lint script is expecting to see time_system_.waitFor here. I think if it's not too much of a hassle you could do a replacement of time_source_ for time_system_ in the test infrastructure. You could do that in a separate trivial rename PR first, or just roll it into this one.

I think the reason it was labeled time_source_ is that the prototype caching infrastructure was co-developed with what we now call TimeSystem, but at the time, the Timer semantics was rolled into the TimeSource API, before we decided that TimeSource, which is used in production code, should only have the methods to query the current system/monotonic time, and we should separate out the abstraction for messing with timers into TimeSystem, and for doing waits into TestTimeSystem.

Here's the hacky Python code that you are running into:

    # We want to look for a call to condvar.waitFor, but there's no strong pattern
    # to the variable name of the condvar. If we just look for ".waitFor" we'll also
    # pick up time_system_.waitFor(...), and we don't want to return true for that
    # pattern. But in that case there is a strong pattern of using time_system in
    # various spellings as the variable name.
    def has_cond_var_wait_for(self, line):
        wait_for = line.find(".waitFor(")
        if wait_for == -1:
            return False
        preceding = line[0:wait_for]
        if preceding.endswith("time_system") or preceding.endswith("timeSystem()") or \
          preceding.endswith("time_system_"):
            return False
        return True

Rather than making this hackier by also look for time_source and variants, I think we should just rename the variable-names in the caching infrastructure to be consistent with the rest of tests.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Got it, renamed the variable. The error message for this case isn't great, so I'll send out a separate PR to fix that.

Signed-off-by: Michael Behr <[email protected]>
@jmarantz

Copy link
Copy Markdown
Contributor

/wait

ping if you need help about sim-time. I created the SimulatedTime abstraction in fall 2018 specifically for caching tests, though Todd really drove the caching impl and Antonio has significantly changed SimulatedTime's impl since then.

@jmarantz

Copy link
Copy Markdown
Contributor

/wait

@jmarantz jmarantz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this review is challenging because it moves so much code around and it's difficult to know what's new and what's just been moved.

HttpCacheImplementationTest::HttpCacheImplementationTest()
: delegate_(GetParam()()), vary_allow_list_(getConfig().allowed_vary_headers()) {}

void HttpCacheImplementationTest::SetUp() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

any particular reason not to move the body of this into the ctor? Same with TearDown -> dtor below.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done.

}
if (!success_ready_for_more) {
insert_status = absl::UnknownError("Insert was aborted by cache");
insert_done = true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

what happens if there's a timeout after the insert_cancelled check above, and right before this line? Won't this write to an invalid stack address?

WDYT about bundling the insert mutex/done/cancelled bits into a structure and keeping a shared__ptr to that?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We're holding insert_mutex for the duration of this callback, so there can't be a timeout in the middle.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ah good point; agree this is correct. I still think it'd be cleaner to hold the insertion context in a single struct with one shared_ptr rather than two, but this is OK.

{"date", time_value_1}, {"cache-control", "public, max-age=3600"}};
// TODO(toddmgreer): Test with various date headers.
ASSERT_THAT(insert("/", response_headers, ""), IsOk());
time_system_.advanceTimeWait(Seconds(3600));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is pre-existing but it's unfortunate we have an unqualified function Seconds in this infrastructure used in some places, and absl::Seconds in others. It would be better IMO if the unqualified one had a name that wasn't a substring of absl::Seconds, and also conformed to Envoy naming conventions, e.g. chronoSeconds(...) or something.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Looks like this isn't defined for the cache filter, it's a type alias in common/time.h.

@jmarantz

Copy link
Copy Markdown
Contributor

/wait

Signed-off-by: Michael Behr <[email protected]>
}
if (!success_ready_for_more) {
insert_status = absl::UnknownError("Insert was aborted by cache");
insert_done = true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ah good point; agree this is correct. I still think it'd be cleaner to hold the insertion context in a single struct with one shared_ptr rather than two, but this is OK.

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.

3 participants