Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import uk.co.compendiumdev.thingifier.adapter.http.apihandlers.FixedRouteResourcePreparer;
import uk.co.compendiumdev.thingifier.adapter.http.apihandlers.RouteApiResponsePolicyApplier;
import uk.co.compendiumdev.thingifier.adapter.http.apihandlers.RouteAuthPolicy;
import uk.co.compendiumdev.thingifier.adapter.http.apihandlers.RouteOperationCallbackApplier;
import uk.co.compendiumdev.thingifier.adapter.http.apihandlers.ThingifierApiRuntime;
import uk.co.compendiumdev.thingifier.adapter.http.apihandlers.route.ThingRoute;
import uk.co.compendiumdev.thingifier.adapter.http.lifecycle.ThingifierApiLifecycleContext;
Expand Down Expand Up @@ -135,6 +136,7 @@ public ApiResponse get(
request.path(),
context,
lifecycle,
request,
() -> get.handle(request.path(), request.queryParams(), context, lifecycle));
}

Expand Down Expand Up @@ -187,6 +189,7 @@ public ApiResponse head(
request.path(),
context,
lifecycle,
request,
() -> {
final ApiResponse response =
get.handle(request.path(), request.queryParams(), context, lifecycle);
Expand Down Expand Up @@ -220,6 +223,7 @@ public ApiResponse query(
request.path(),
context,
lifecycle,
request,
() ->
query.handle(
request.path(),
Expand Down Expand Up @@ -268,6 +272,7 @@ public ApiResponse delete(
request.path(),
context,
lifecycle,
request,
() -> delete.handle(request.path(), request.queryParams(), context, lifecycle));
}

Expand Down Expand Up @@ -321,6 +326,7 @@ public ApiResponse post(
request.path(),
context,
lifecycle,
request,
() ->
post.handle(
request.path(),
Expand Down Expand Up @@ -397,6 +403,7 @@ public ApiResponse put(
request.path(),
context,
lifecycle,
request,
() ->
put.handle(
request.path(),
Expand Down Expand Up @@ -484,6 +491,7 @@ public ApiResponse patch(
request.path(),
context,
lifecycle,
request,
() ->
patch.handle(
request.path(),
Expand Down Expand Up @@ -558,19 +566,44 @@ private ApiResponse withAuthorizedResponsePolicy(
final ThingifierRequestContext context,
final ThingifierApiLifecycleContext lifecycle,
final Supplier<ApiResponse> action) {
return withAuthorizedResponsePolicy(verb, url, context, lifecycle, null, action);
}

/**
* Applies auth, fixed-resource preparation, response policy, and route operation callbacks.
*
* <p>Callbacks run after response policies so they see the route-shaped API result, and before
* legacy HTTP response hooks so application code still has one final compatibility hook phase.
*
* @param verb routing verb used for route-rule lookup
* @param url generated API path
* @param context request context containing the active store
* @param lifecycle lifecycle context when called through HTTP processing, otherwise null
* @param request parsed request envelope, or null for older direct-call helpers
* @param action handler action to run when auth allows the request
* @return response after auth, response policy, and route callbacks have been applied
*/
private ApiResponse withAuthorizedResponsePolicy(
final RoutingVerb verb,
final String url,
final ThingifierRequestContext context,
final ThingifierApiLifecycleContext lifecycle,
final ApiRequestEnvelope request,
final Supplier<ApiResponse> action) {
final ApiResponse authResponse =
lifecycle == null ? authPolicy.rejectIfNotAuthorized(verb, url, context) : null;
if (authResponse != null) {
return withResponsePolicy(verb, url, authResponse, context);
return withResponsePolicy(verb, url, authResponse, context, lifecycle, request);
}
final ThingRoute route =
lifecycle == null ? runtime.routeFor(verb, url) : lifecycle.route();
final ApiResponse fixedResourceResponse =
new FixedRouteResourcePreparer(runtime).prepare(verb, url, route, context);
if (fixedResourceResponse != null) {
return withResponsePolicy(verb, url, fixedResourceResponse, context);
return withResponsePolicy(
verb, url, fixedResourceResponse, context, lifecycle, request);
}
return withResponsePolicy(verb, url, action.get(), context);
return withResponsePolicy(verb, url, action.get(), context, lifecycle, request);
}

/**
Expand Down Expand Up @@ -604,15 +637,20 @@ private ApiResponse withResponsePolicy(
final RoutingVerb verb,
final String url,
final ApiResponse response,
final ThingifierRequestContext context) {
final ThingifierRequestContext context,
final ThingifierApiLifecycleContext lifecycle,
final ApiRequestEnvelope request) {
final ApiResponse responseWithRepository = withRepository(response, context);
return new RouteApiResponsePolicyApplier(runtime)
.apply(
verb,
url,
responseWithRepository,
context.headers(),
apiResponse -> applyResponseEntityView(verb, url, apiResponse));
final ApiResponse policyResponse =
new RouteApiResponsePolicyApplier(runtime)
.apply(
verb,
url,
responseWithRepository,
context.headers(),
apiResponse -> applyResponseEntityView(verb, url, apiResponse));
return new RouteOperationCallbackApplier(runtime)
.apply(verb, url, policyResponse, context, lifecycle, request);
Comment on lines +652 to +653

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Run callbacks after the final HTTP policy pass

For HTTP-backed requests, this invokes callbacks after one response-policy application, but ThingifierHttpApi.httpResponseFor applies RouteApiResponsePolicyApplier again afterward. If a success policy changes 200 to an error status, for example, the callback observes that intermediate status while the second pass can select the matching error policy and expose a different status/body to the client, so afterStatus and result.statusCode() do not describe the promised final route-shaped result. Ensure the HTTP path applies response policy only once or move callback execution after its last application.

Useful? React with 👍 / 👎.

}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package uk.co.compendiumdev.thingifier.api.callbacks;

/**
* Controls how Thingifier reacts when a route operation callback throws.
*
* <p>Callbacks are trusted application code running after Thingifier has decided an operation
* result. Applications can choose whether a side-effect failure should fail the visible API request
* or be logged while preserving the original response.
*/
public enum CallbackFailurePolicy {
/**
* Convert the callback exception into a 500 API response.
*
* <p>This is the default because silently skipping application side effects can leave
* application-owned state inconsistent with Thingifier-managed data.
*/
FAIL_REQUEST,

/**
* Log the callback exception and preserve the original operation response.
*
* <p>Use this when the callback is observational, such as diagnostics or best-effort metrics,
* and the API operation should not fail because the callback failed.
*/
LOG_AND_CONTINUE
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package uk.co.compendiumdev.thingifier.api.callbacks;

/**
* Trusted application callback invoked after a route operation has produced an API result.
*
* <p>Use route operation callbacks for application side effects such as audit logging, projections,
* cache invalidation, or synchronising app-owned state. Response shaping should stay in route
* response policies or response hooks so callbacks can remain focused on observing the completed
* operation.
*/
@FunctionalInterface
public interface ThingifierApiOperationCallback {

/**
* Runs the application callback for one completed route operation.
*
* @param context immutable route, request, auth, and data-scope information
* @param result immutable operation outcome details
*/
void run(ThingifierApiOperationContext context, ThingifierApiOperationResult result);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
package uk.co.compendiumdev.thingifier.api.callbacks;

import uk.co.compendiumdev.thingifier.api.spec.ThingifierApiRouteRule;

/**
* Runtime-only registration for one route operation callback.
*
* <p>The definition is code-only by design. Java callbacks cannot safely round-trip through YAML or
* OpenAPI, so Thingifier stores them only in the in-memory API contract and uses the name for
* diagnostics.
*/
public final class ThingifierApiOperationCallbackDefinition {

/** Outcome selector used when deciding whether a callback should run. */
public enum Outcome {
/** Run for any completed outcome. */
ANY,

/** Run only for 2xx/3xx operation responses. */
SUCCESS,

/** Run only for non-success operation responses. */
FAILURE,

/** Run only when the final status code matches {@link #statusCode()}. */
STATUS
}

private final ThingifierApiRouteRule routeRule;
private final String name;
private final Outcome outcome;
private final Integer statusCode;
private final ThingifierApiOperationCallback callback;
private CallbackFailurePolicy failurePolicy;

/**
* Creates a callback registration.
*
* @param routeRule route that owns the callback
* @param name stable diagnostic name
* @param outcome outcome selector
* @param statusCode status code for {@link Outcome#STATUS}, otherwise null
* @param callback trusted application callback
*/
public ThingifierApiOperationCallbackDefinition(
final ThingifierApiRouteRule routeRule,
final String name,
final Outcome outcome,
final Integer statusCode,
final ThingifierApiOperationCallback callback) {
if (routeRule == null) {
throw new IllegalArgumentException("route rule is required");
}
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("callback name is required");
}
if (outcome == null) {
throw new IllegalArgumentException("callback outcome is required");
}
if (outcome == Outcome.STATUS && statusCode == null) {
throw new IllegalArgumentException("status callback requires a status code");
}
if (callback == null) {
throw new IllegalArgumentException("callback is required");
}
this.routeRule = routeRule;
this.name = name.trim();
this.outcome = outcome;
this.statusCode = statusCode;
this.callback = callback;
this.failurePolicy = CallbackFailurePolicy.FAIL_REQUEST;
}

/**
* Sets the failure policy for this callback.
*
* @param policy callback exception handling policy
* @return owning route rule so route configuration can continue fluently
*/
public ThingifierApiRouteRule onCallbackFailure(final CallbackFailurePolicy policy) {
if (policy == null) {
throw new IllegalArgumentException("callback failure policy is required");
}
this.failurePolicy = policy;
return routeRule;
}

/**
* Returns the stable diagnostic callback name.
*
* @return callback name
*/
public String name() {
return name;
}

/**
* Returns the outcome selector for this callback.
*
* @return configured outcome selector
*/
public Outcome outcome() {
return outcome;
}

/**
* Returns the status code matched by status-specific callbacks.
*
* @return status code, or null for non-status callbacks
*/
public Integer statusCode() {
return statusCode;
}

/**
* Returns the application callback.
*
* @return trusted callback
*/
public ThingifierApiOperationCallback callback() {
return callback;
}

/**
* Returns the configured callback failure policy.
*
* @return failure policy
*/
public CallbackFailurePolicy failurePolicy() {
return failurePolicy;
}

/**
* Reports whether this callback should run for the supplied result.
*
* @param result operation result
* @return true when the outcome selector matches
*/
public boolean matches(final ThingifierApiOperationResult result) {
if (result == null) {
return false;
}
switch (outcome) {
case ANY:
return true;
case SUCCESS:
return result.successful();
case FAILURE:
return result.failed();
case STATUS:
return statusCode != null && statusCode == result.statusCode();
default:
return false;
}
}
}
Loading
Loading