Skip to content
Belikhun edited this page Sep 15, 2026 · 1 revision

🌫️ Ether

Ether is blink's middleware system: one registry, one pipeline, and a family of stages around the router, the query engine, the event bus and the error page. A middleware is a class with a handle($context, $next) method; Ether resolves it through Essence and runs it in priority order.

The stages

Family Stage Wraps Context
router route The router before it matches a route Ether\Route\RouteContext
router request A matched route before its handler runs Ether\Request\RequestContext
router response The handler's Response before it is sent Ether\Response\ResponseContext
query query Every terminal operation of a Query Ether\Query\QueryContext
event event One Lightrail emission, once Ether\Event\EventDispatchContext
event handler One Lightrail handler call, in every execution mode Ether\Handler\HandlerInvocationContext
errorpage errorPage An error report while it is being built Ether\ErrorPage\ErrorPageContext

Each stage has an interface under Blink\Ether\<Stage>\<Stage>Middleware. Implementing one tells Ether which stage a class belongs to, so Ether::use() can attach it to the right stack without being told.

Registering

Register in a module's attach().

use Blink\Ether;

public function attach(): void {
	Ether::use(RequireWorkspace::class, "workspace", 150);
	Ether::use(TraceRequest::class, "trace.request");
	Ether::use(TraceQuery::class, "trace.query");
}

Ether::use() records the middleware in the registry and attaches it to its stage's global stack. The alias is optional and the priority defaults to 0; higher runs earlier.

Ether::register() records without attaching, for a middleware you want to name now and attach later, or only per route:

Ether::register(AuditRequest::class, "audit.request");
Ether::register(AuditResponse::class, "audit.response");
Ether::group("api", "audit.request", "audit.response");

Ether::request("api");
Ether::response("api");

The attach methods, one per stage: Ether::route(), request(), response(), query(), event(), handler(), errorPage(). Each takes any number of references.

References, aliases and groups

A reference is a class name, an alias, or a group. Groups are named lists of references:

Ether::group("web", "trace.request", "audit.request");

Rules the registry enforces:

  • a group may hold references from one family only, so router and query middleware never share one;
  • aliases and groups share a namespace and must not collide;
  • an unknown reference raises EtherInvalidMiddleware naming it, and the error page tells you where to register it.

Blink registers auth, setupEnv and cors for its own router middleware, with auth and setupEnv grouped as router.

Writing middleware

namespace App\Middleware;

use Blink\Ether\Request\RequestContext;
use Blink\Ether\Request\RequestMiddleware;

class RequireWorkspace implements RequestMiddleware {
	public function __construct(protected WorkspaceResolver $workspaces) {}

	public function handle(RequestContext $context, callable $next): mixed {
		if (!$this -> workspaces -> current())
			throw new AccessDenied("No workspace selected.");

		return $next($context);
	}
}

Constructor injection works because the middleware is built with Essence::make(). Returning without calling $next stops the pipeline: for a request stage the return value becomes the response body, for a handler stage the handler is recorded as skipped, for an event stage no handler runs at all.

Router stages

RouteContext carries the Request and three flags the auth middleware sets for the stages after it: authenticatedByHeader, isCrossSite, isOptionRequest. Route middleware may replace $context -> request; everything downstream reads from the context.

RequestContext adds the matched Route. ResponseContext adds the Response, which the middleware may mutate or replace:

class AddServerTiming implements ResponseMiddleware {
	public function handle(ResponseContext $context, callable $next): mixed {
		$response = $next($context);
		$context -> response -> header("Server-Timing", "app;dur=" . round($GLOBALS["RUNTIME"] -> stop() * 1000));
		return $response;
	}
}

Per route:

Router::GET("/api/orders", [ Orders::class, "index" ])
	-> middleware("api", RateLimit::class)
	-> withoutMiddleware("auth");

And on controller methods, #[Middleware(...)] and #[WithoutMiddleware(...)] from Blink\Http\Router\Attribute.

The query stage

Query middleware runs around every terminal operation: all(), first(), value(), count(), update(), delete(), exec() and the rest. The context names the operation and its kind (read, write or raw), and after $next holds the SQL, the parameters and the result.

class TraceQuery implements QueryMiddleware {
	public function handle(QueryContext $context, callable $next): mixed {
		$result = $next($context);
		Debug::log("{$context -> operation}: {$context -> sql}");
		return $result;
	}
}

Before $next, $context -> query is the builder itself, so a middleware can add a condition every query must carry:

if ($context -> query -> haveColumn("tenant_id"))
	$context -> query -> where("tenant_id", Tenant::current() -> id);

Per query, -> middleware() and -> withoutMiddleware() take the same references as a route.

The event stages

See Lightrail. In short: EventMiddleware wraps an emission and can mute it; HandlerMiddleware wraps each handler call and runs wherever the handler runs, a runner included. Observers attach or exclude handler middleware with #[Middleware] and #[WithoutMiddleware] from Blink\Lightrail\Attribute.

The error page stage

ErrorPageMiddleware sees a report while it is being built and can add context groups to it:

class WorkspaceContext implements ErrorPageMiddleware {
	public function handle(ErrorPageContext $context, callable $next): mixed {
		if ($context -> debugging) {
			$group = $context -> group("Workspace");
			$group -> add($context -> listItem("current", "Current", Workspace::current() ?-> out()));
		}

		return $next($context);
	}
}

$context -> debugging is false when CONFIG::$DEBUG is off; a report is reachable by anyone holding its id, so add nothing sensitive in that case.

The registry cache

Middleware metadata (class, stage, family, alias, group, priority) is cached under DATA_ROOT/caches so the registry does not inspect classes on every request. The cache is versioned by Blink::cacheVersion() and rewritten only when the snapshot changes. cache:clear removes it.

Clone this wiki locally