Middleware
Intercepting Incoming Requests
A middleware is a piece of code that intercepts an incoming request before this request reaches the target servant. The same code also intercepts the outgoing response before it's sent back to the caller.
At a more technical level, a middleware is a dispatcher that holds another dispatcher ("next") and calls dispatch
on this next dispatcher as part of the implementation of its own dispatch
method.
A middleware can include logic before calling dispatch
on the next dispatcher (before the request is processed) and after calling dispatch
on the next dispatcher (after it receives the response). A middleware can also short-circuit the dispatch processing by returning a cached response or by returning an error.
Middleware API
In C++, a middleware is a concrete class that implements Ice::Object
and delegates to another dispatcher called “next”. For example:
// A typical C++ middleware class
class AuthorizationMiddleware final : public Ice::Object
{
public:
AuthorizationMiddleware(Ice::ObjectPtr next, std::string validToken);
void dispatch(
Ice::IncomingRequest& request,
std::function<void(Ice::OutgoingResponse)> sendResponse) final;
};
The constructor accepts the “next” dispatcher and other data, and dispatch
dispatches incoming requests by delegating to “next”.
You install a middleware on an object adapter by calling use
:
class ObjectAdapter
{
public:
ObjectAdapterPtr use(std::function<ObjectPtr(ObjectPtr)> middlewareFactory);
};
use
accepts a middleware factory – not a middleware. This allows the object adapter to create and connect the middleware into its dispatch pipeline when it receives its first request.
For example, you can call use
as follows:
adapter->use(
[](Ice::ObjectPtr next)
{
return make_shared<Server::AuthorizationMiddleware>(
std::move(next),
"iced tea");
});
The middleware, once created and woven into the dispatch pipeline, intercept requests in the order of their registration through use
.
Built-in Middleware
Ice installs automatically the following middleware at the beginning of the dispatch pipeline:
the logger middleware, unless both
Ice.Warning.Dispatch
andIce.Trace.Dispatch
are set to0
.the observer middleware, when the Metrics admin facet is enabled.