Skip to content

Commit

Permalink
API to set folly::RequestContext for current scope
Browse files Browse the repository at this point in the history
Summary:There're currently two ways to set RequestContext
- RequestContext::create() - creates new context and sets it
- RequestContext::setContext(context) - sets context previously captured by saveContext
In most cases, the RequestContext is set back after the request is processed but sometimes it's not (especially with RequestContext::create). We want to measure cpu time for a request by measuring the total cpu time when a RequestContext is set, so we need to make sure that it's properly reset after the thread is done with the request. Scope guards can help us with that.

Reviewed By: haijunz

Differential Revision: D3156698

fb-gh-sync-id: cfb678531810e8be5faaf02cb7803bd247557e42
fbshipit-source-id: cfb678531810e8be5faaf02cb7803bd247557e42
  • Loading branch information
Mirek Klimos authored and Facebook Github Bot 6 committed Apr 18, 2016
1 parent 9ef6452 commit 35a8cc2
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions folly/io/async/Request.h
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,15 @@ class RequestContext {
}

// The following API is used to pass the context through queues / threads.
// saveContext is called to geta shared_ptr to the context, and
// saveContext is called to get a shared_ptr to the context, and
// setContext is used to reset it on the other side of the queue.
//
// Whenever possible, use RequestContextScopeGuard instead of setContext
// to make sure that RequestContext is reset to the original value when
// we exit the scope.
//
// A shared_ptr is used, because many request may fan out across
// multiple threads, or do post-send processing, etc.

static std::shared_ptr<RequestContext>
setContext(std::shared_ptr<RequestContext> ctx) {
using std::swap;
Expand All @@ -135,4 +138,24 @@ class RequestContext {
std::map<std::string, std::unique_ptr<RequestData>> data_;
};

class RequestContextScopeGuard {
private:
std::shared_ptr<RequestContext> prev_;

public:
// Create a new RequestContext and reset to the original value when
// this goes out of scope.
RequestContextScopeGuard() : prev_(RequestContext::saveContext()) {
RequestContext::create();
}

// Set a RequestContext that was previously captured by saveContext(). It will
// be automatically reset to the original value when this goes out of scope.
explicit RequestContextScopeGuard(std::shared_ptr<RequestContext> ctx)
: prev_(RequestContext::setContext(std::move(ctx))) {}

~RequestContextScopeGuard() {
RequestContext::setContext(std::move(prev_));
}
};
}

0 comments on commit 35a8cc2

Please sign in to comment.