Skip to content
NativePHPPublic

Repository files navigation

Midgard

A Laravel package that enables a client application to connect to an OAuth-protected Laravel API and use Eloquent models as the transportation layer.

Requires PHP 8.2+ and Laravel 12 or 13.

Setup

Add the API server credentials to your .env file:

API_SERVER_URL=
OAUTH_CLIENT_ID=
OAUTH_CLIENT_SECRET=

Publish the config if you need to change anything else:

php artisan vendor:publish --tag=api-config

The API client

Every request goes through an implementation of Native\Api\Client\Support\Contracts\Client. The package binds Native\Api\Client\Support\Base as the default, which is a Guzzle client that understands the API's JSON envelope (data, meta, links, errors). Bind your own implementation in a service provider if you need different behaviour:

$this->app->bind(
    \Native\Api\Client\Support\Contracts\Client::class,
    \App\Api\Client::class,
);

Client tokens

Acting as an anonymous user

For applications that don't require authenticating on behalf of specific users, e.g. for anonymous visitors only, your application should generate client access tokens using the Client Credentials OAuth grant.

Add the ClientAuthentication middleware in bootstrap/app.php:

// bootstrap/app.php

use Native\Api\Client\Auth\ClientAuthentication;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware) {
        // As global middleware that will run for every request
        $middleware->append(ClientAuthentication::class);

        // Or as an alias you can attach to specific routes or route groups
        $middleware->alias([
            'auth.client' => ClientAuthentication::class,
        ]);
    })
    ->create();

Used as an alias, the middleware accepts a list of scope names that should be assigned to the token generated for any routes that use it:

Route::get('/cars', CarController::class)->middleware('auth.client:read-cars,write-cars');

Tokens are stored on your default filesystem disk, keyed by request method and path, so your application doesn't have to generate a token on every request. A stored token is reused until it expires or the requested scopes change.

Acting as a known user

For applications that need to behave as a specific user (e.g. an admin system), your application will need to follow a full OAuth 2 Auth Code flow. This package makes this straightforward, but some setup will be required.

Add the following to your app's config/auth.php:

return [
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'oauth',
        ],
    ],

    'providers' => [
        'oauth' => [
            'driver' => 'oauth',
        ],
    ],
];

Then point a couple of routes at the package's controller. These have to match the redirect_uri and failure_uri in config/api.php, which default to /oauth/authenticate and /oauth/unauthenticated:

// routes/web.php

use Native\Api\Client\Auth\OAuthController;

Route::get('/oauth/authenticate', [OAuthController::class, 'authenticate']);
Route::get('/oauth/unauthenticated', [OAuthController::class, 'unauthenticated']);

The failure page ships with the package. Publish it if you want to style it yourself:

php artisan vendor:publish --tag=api-views

Resources

You interact with API resources as if they were Eloquent models. In fact you can create Eloquent models how you normally would, simply extend the built-in Resource class instead of Laravel's Eloquent Model:

<?php

namespace App\Models;

use Native\Api\Client\Support\Resource;

class Car extends Resource
{
}

Then you can use many of the methods you're used to with Eloquent models, but instead of building queries and persisting to a database, your data is retrieved and stored via HTTP calls, all with the same syntax you'd use for a database-backed model:

Car::find($id);
Car::findOrFail($id);
Car::orderBy('column1', 'desc');
Car::get(['column1', 'column2']);
Car::paginate();
Car::with('related')->get();

Resources use the api connection and default to a internal_id primary key. The endpoint is the kebab-cased plural of the class name unless you set $endpoint:

class Car extends Resource
{
    protected $endpoint = 'vehicles';
}

Declaring $with on a resource asks the API to inline those relations in the response (an include query param) rather than issuing a second request:

class Car extends Resource
{
    protected $with = ['wheels'];
}

Anything the API returns under a relationships key is hydrated onto the model when it's retrieved.

Asgard

Asgard server regions, screens, actions and #[Server] methods are set up under midgard.asgard in config/midgard.php. Each option is described there, and #[Server] methods are covered in docs/ASGARD-SERVER-METHODS.md.

Requests and answers

Every region render goes to {base}/render and names its regions in regions, a list even for one region. A server screen asks for ["screen"]. Regions of one component that load at the same moment go in one request, at most 16 at a time.

{"protocol":1,"component":"app.native.screens.home","regions":["stats","feed"],
 "state":{"period":"week","user_id":7},"read_only":["user_id"]}

Every answer is a fragments map with one part per region, next to a delta. A part has the region's version, made_at, an optional max_age and the fragment. A server screen's part has chrome too. A part of {"cached":true} means the copy the request declared is still good.

{"protocol":1,"delta":{},"fragments":{
 "stats":{"version":"q3V0bG9yZW1pcHN1","made_at":1763150000123,
  "fragment":{"type":"text","props":{"text":"42 sales"}}},
 "feed":{"cached":true}}}

Each region in a request still has its own timer and failure. A region the answer leaves out fails with reason invalid.

An action names exactly one region in regions, plus an action member. Its answer has that region's part, next to any other regions of the same component the server redrew with refresh(), and may carry refresh hints for other components.

State comes back on every answer

Every answer sends state back in delta: renders, batches, server screens, actions, #[Server] calls and uploads. A plain render's delta holds only what changed on the server, so it is usually {}. An action's, a call's and an upload's holds everything the server half changed. A cached answer still carries one.

The client applies the delta before it paints any fragment, the same way for every answer. Each prop is set only if it still holds the value the request sent, so an edit made while the request was out survives. A delta for a request that has timed out or failed is dropped with it. When the delta changes a prop, the regions in that answer are cached and watched for the new state. An empty delta, or one that only repeats what the component holds, costs nothing: no frame, no change to the push stream.

A delta never sets a #[LocalOnly] prop, a #[Computed] value, a midgard.asgard.state key, or a #[ServerReadOnly] prop. Each one is ignored and logged under debug.

Props the server may read but not change

use Native\Api\Client\Asgard\Attributes\ServerReadOnly;

#[ServerReadOnly]
public int $userId;

The prop goes to the server in state like any other. Every request that sends state also sends read_only, the keys the server may not change: these props and the component's #[Computed] values, left out when there are none. The server leaves them out of its delta. In debug it answers 500 read_only_changed when its code changed one, which the client reports like any other server error.

Redrawing regions after a call

A #[Server] method can ask the server to redraw regions once it has run:

#[Server(render: true)]                    // every region this component has drawn
#[Server(render: 'messages')]              // just this one
#[Server(render: ['messages', 'stats'])]   // these

Uploads take the same argument:

$this->uploadToServer('savePhoto', $this->photo, render: 'gallery');

The request names them in regions and declares any cached copies of them in cache. The answer's fragments holds those regions, then anything refresh() added, and they are painted after the delta like an action's extra regions. Without render the answer carries state, plus whatever refresh() asked for.

A server may refuse a render that names too many regions with 422 too_many_regions. The client then sends the same regions again in two requests of half the size each, down to one region. One region refused that way fails with reason server. A call or upload refused that way is not split. It fails like any other server error.

Telling the server about the app

The Asgard protocol has no field for the platform, app version or anything else about the app. Send what the server should know with state, which adds keys to the state of every Asgard request (region renders, actions, #[Server] calls, uploads and each push stream subscription):

'state' => [
    'platform' => [\Native\Api\Client\Asgard\ServerRegion::class, 'platform'], // the default
    'app_version' => [\App\AppInfo::class, 'version'],
    'channel' => 'beta',
],
  • A value is sent as it is, or called each time a request is built when it is a closure or a [Class::class, 'method'] callable. Prefer the callable array: a closure in config stops php artisan config:cache working, and NativePHP runs that on the device.
  • Keys are property names (letters, digits and underscores, not starting with a digit). Values are scalars, null or arrays of those. Anything else throws.
  • A component's own public prop or #[Computed] of the same name wins, and its value is sent instead.
  • These keys are not props of the component, so a server delta that names one is ignored and logged under debug.
  • They are ordinary state, so they count wherever state counts, including the server's shared push cache. A server component reads one with a public property of the same name.

headers sends plain HTTP headers with every Asgard request, the push stream and the handshake included:

'headers' => [
    'X-App-Version' => [\App\AppInfo::class, 'version'],
],

The server reads them with request()->header(). TLS covers them, but the protocol's body encryption and signature do not, so do not put anything in them that the encryption is meant to protect. The server's shared push cache is not keyed by headers, so a shared region must not depend on one; send it in state instead. Names the transport or the protocol already uses (Accept, Authorization, Connection, Content-*, Cookie, Host, Last-Event-ID, Signature, Signature-Input, Transfer-Encoding, the method override headers, and anything starting Asgard- or X-Asgard-) are refused with an exception. A callable that gives null leaves the header out of that request.

The push stream

With stream on, the device keeps one push stream open for every region on screen. Each open stream holds a PHP worker on the server.

When the app goes to the background, the stream is closed so the server frees that worker. The device keeps its list of regions. When the app comes back, the stream opens again straight away with the version the device holds for each region. The server then signals every region that changed while the app was away, and every region the device holds no version for, so nothing pushed in the meantime is missed.

Patches

A server can change one list in a region without sending the whole region again, with Asgard::patch(...)->prepend(), ->append() or ->remove(). The device gets a patch event that names the list by its node key and carries only the new nodes, or the keys to remove. keep trims the list after a prepend (from the end) or an append (from the start).

Give the list a key (key="items"), and give each item one too. Remove works by item key, and keyed items keep their identity on screen as the list moves, so the renderer only adds and drops the rows that changed. A prepend or append first drops any item already in the list with the key of a node it inserts, so an item a full fetch already showed is never there twice.

The patch only applies when the device holds the version the patch was made from and the list is there. Anything else (a missed or out-of-order patch, a region not loaded yet, a cached copy on screen, an op the device cannot read) makes the device fetch the whole region, as a signal does. So the server must also change the data the region renders from. The first load, a reconnect and every fallback render the region in full, and that render must show the same list the patches built.

While that fetch is out, later patches don't ask again. The device keeps them, and when the region lands it applies the ones that follow on from the version it came with. Without that, a list taking patches faster than one fetch takes would never get an answer: each new ask dropped the one before.

Patched nodes are checked like any fragment's nodes, and their taps work the same. A patch never fires RegionCacheInvalidation. It drops the region's cached copy, and the next full answer stores a fresh one.

Applying a patch is cheap: no HTTP, and only the new nodes are checked. The region then repaints with the screen's next frame. Patches that land between two frames share one repaint.

A region keeps the elements it built from its tree, so a frame puts the same elements back instead of building them again, and native gets a REUSE marker for each one it already holds. A patch builds only its new rows and drops the removed ones. The rest are kept. A full fragment builds everything again. Screens that render by streaming have no elements to keep and build the region every frame.

The region cache

The app can keep a copy of each region and server screen it gets, and paint it at once the next time that region loads, even after the app was closed. It is off until you give it a TTL in seconds:

'cache' => [
    'ttl' => 300,     // ASGARD_CACHE_TTL, 0 is off
    'store' => null,  // ASGARD_CACHE_STORE, null is the app's default store
],

A region can set its own TTL, and 0 turns it off for that region. Server screens use the config value.

@server('stats', cacheTtl: 60)
    <native:text>Loading…</native:text>
@endserver

The store must keep its data when the app quits, so not array. The app's default store does on a device. Copies are keyed by the server, the component, the region and the state the request sent, so other state never paints another state's copy.

A cached copy does not stop the request. The request declares each copy that is still within its TTL, and the server either answers that the copy is still good or sends a new fragment. A copy past its TTL is still painted while the request is out, but it is not declared. The server's max_age for a region can cut the TTL shorter. A region painted from the cache joins the push stream only once the server has answered for it.

If the copy is gone by the time the server says it is good (flushed while the request was out), the region asks once more without declaring it.

The server can force a redraw with Asgard-Cache: invalidate. Before such a fragment replaces a cached copy, RegionCacheInvalidation fires. The new fragment is applied on the screen's next turn unless a listener keeps the copy:

use Native\Api\Client\Asgard\Events\CacheDecision;
use Native\Api\Client\Asgard\Events\RegionCacheInvalidation;

#[On(RegionCacheInvalidation::class, when: ['region' => 'drafts'])]
public function draftsChanged(CacheDecision $decision, ?int $oldMadeAt, ?int $newMadeAt): void
{
    $decision->ignore();
}

A Laravel listener gets the event and can call $event->ignore().

Clear the cache when the user logs out, so the next user never sees the last one's fragments:

\Native\Api\Client\Asgard\RegionCache::flush();

Testing

composer test
composer format

Releases

Sponsor this project

Contributors

Languages