Skip to content

Latest commit

 

History

History
345 lines (276 loc) · 14.8 KB

reference.md

File metadata and controls

345 lines (276 loc) · 14.8 KB

Reference

Everything the README leaves out: the graph API in depth, connecting your own tables, the summary tables and the data endpoints.

Graph library API

The explorers are three shapes of one idea: a relationship graph. You describe a graph once in a service provider, and the package handles caching, rebuilding and serving it.

use SolutionForest\FilamentNetworkExplorer\Facades\NetworkGraph;

// Who invited whom (one parent per person).
NetworkGraph::tree('referrals')
    ->model(User::class)
    ->parentKey('referred_by_id');

// Who follows whom (direction matters, cycles are allowed).
NetworkGraph::directed('follows')
    ->pivot('follows', from: 'follower_id', to: 'followee_id')
    ->occurredKey('created_at');

// Who shares what (players sharing matches, devices sharing accounts).
NetworkGraph::shared('co-play')
    ->pivot('match_players', node: 'user_id', via: 'match_id')
    ->minShared(2);

Pick the graphs a panel shows by name:

NetworkExplorerPlugin::make()->graphs(['referrals', 'follows']);

Rebuild one graph, or every graph, from the CLI:

php artisan network-graph:rebuild referrals --sync
php artisan network-graph:rebuild

A directed graph also serves the following explorer. Add follows to the panel's graph list (or call followExplorer()) to show the page, and point network-explorer.follow_graph at a different name if yours is not called follows.

A pivot-backed shared graph serves the co-play explorer. Add its name to the panel's graph list (or call sharedExplorer()), and point network-explorer.shared_graph at it. The same contract serves the existing entity map, so devices sharing accounts and players sharing matches use one code path.

A rebuild bumps the graph revision, clears that graph's cache and fires Events\GraphRebuilt. The queued Jobs\RebuildGraph job does the same work in the background.

The core is Filament-free: definitions, sources, cache, jobs and JSON work in any Laravel app. See the contributor guide for architecture, naming, PHPStan, testing and performance rules.

Use your own data

The plugin does not expect any particular database design. Pick one of these:

  1. Fill the bundled tables. Run the migrations and have a job copy your data into the summary tables (listed below). Nothing else to write.

  2. Rename the tables. If you already have tables with the same shape, point the tables.* config at them.

  3. Write a data source. Implement EntityGraphSource and/or ReferralGraphSource against your own tables and bind it in a service provider:

    use SolutionForest\FilamentNetworkExplorer\Contracts\EntityGraphSource;
    
    $this->app->bind(EntityGraphSource::class, App\Graph\MyEntityGraphSource::class);
Contract Provides Default
Contracts\EntityGraphSource Groups, items, their details and links Sources\ReadModelEntityGraphSource
Contracts\ReferralGraphSource Referral networks, people, invite links, top lists Sources\ReadModelReferralGraphSource
Contracts\GraphSearch Search and single-item lookup Sources\ReadModelGraphSearch
Contracts\GraphSource Read model and rebuild for one graph Sources\ReadModelGraphSource
Contracts\GraphCache Caching answers Support\CacheGraphCache
Contracts\GraphRevision Per-graph revision markers Support\GraphRevision
Contracts\GraphInsightSource Cached overview insights for a graph Built into model tree graphs
Contracts\FollowGraphSource Communities, a bounded ego network and following insights Sources\DirectedGraphSource
Contracts\SharedGraphSource Groups, bounded members/pairs, co-play insights, overlap lookup Sources\PivotSharedGraphSource

If the tables don't exist yet, the default sources return empty pictures instead of errors.

Start with your own table

If your users table already has a "who invited me" column, you do not need an import job or a closure table. Register the graph once and run the rebuild:

// app/Providers/AppServiceProvider.php
use SolutionForest\FilamentNetworkExplorer\Facades\NetworkGraph;

public function boot(): void
{
    NetworkGraph::tree('referrals')
        ->model(User::class)
        ->parentKey('referred_by_id');
}
php artisan migrate
php artisan network-graph:rebuild referrals --sync

That is the whole setup. The plugin writes per-node aggregates (root, depth, direct count, downstream count, network id, self-referral and cycle flags) into network_graph_nodes and one summary row per network into network_graph_networks. Requests read those rows only; nothing walks the referral tree while a page is open. The optional referral_closure table is not needed by these graphs.

Add the trait if you want per-model helpers:

use SolutionForest\FilamentNetworkExplorer\Concerns\HasReferralGraph;

final class User extends Authenticatable
{
    use HasReferralGraph;
}

$user->downstreamCount();       // everyone below this user
$user->directReferralCount();   // direct invitees only
$user->referralDepth();         // 0 for a network root
$user->referralNetwork()->get(); // all models in the same network

Use a different graph name and point the explorer at it with network-explorer.referral_graph. Use ->signupKey('registered_at') when your timestamp column is not created_at.

Incremental by default. After the first run, the command only recomputes the networks whose rows changed since the previous run (it watches updated_at and the numeric key). Pass --full to recompute everything, for example after deleting rows or changing the parent column definition.

Insights are computed by the rebuild. Top referrers, biggest networks, average signup-to-referral time, referral bursts (many signups under one referrer inside a time window), self-referral rate and shared-detail overlap rate are stored in network_graph_insights and shown on the referral explorer overview. Tune the window and thresholds under insights.* in the config.

The same rebuild runs on MySQL 8, PostgreSQL 15+ and SQLite. It expands the tree one level at a time in SQL instead of using a recursive CTE, so MySQL's cte_max_recursion_depth cannot break a deep chain.

Following a directed pivot

If your follows live in a pivot table, register a directed graph and rebuild it:

NetworkGraph::directed('follows')
    ->pivot('follows', from: 'follower_id', to: 'followee_id')
    ->occurredKey('created_at');
php artisan network-graph:rebuild follows --sync

The rebuild streams the pivot in chunks, stores one row per edge (with the reciprocal edge marked as mutual), aggregates in-degree, out-degree and mutual counts in SQL, and assigns connected communities with a chunked union-find. It writes network_graph_edges, network_graph_directed_nodes, network_graph_communities and the following insights in network_graph_insights.

The following overview shows:

  • most followed — highest in-degree;
  • fastest growing — new followers inside follow.insights.growth_window_days;
  • follows many, few follow back — at least spam_min_following follows and a follow-back rate at or below spam_max_follow_back_rate;
  • tight follow rings — complete mutual groups of 3 to max_ring_size people.

Opening a person requests a k-hop ego network (follow.ego.hops, default 2). Each node contributes at most follow.ego.fanout followers and followees, and the whole payload is capped by maxNodesPerView. The response counts what was left out (more_in, more_out, omitted_nodes, omitted_edges), so the page can say "+N more". The full graph is never sent.

Co-play from a pivot

If matches and their players live in a pivot table, register a shared graph and rebuild it:

NetworkGraph::shared('co-play')
    ->pivot('match_players', node: 'user_id', via: 'match_id')
    ->minShared(2)
    ->occurredKey('created_at')
    ->windowDays(90)
    ->overlapGraph('shared-devices');
php artisan network-graph:rebuild co-play shared-devices --sync

The rebuild streams the pivot ordered by match and player, forms pairs inside each match, and aggregates them in SQL. It writes network_graph_pairs (weighted, pruned below minShared), network_graph_shared_nodes (matches played, distinct partners, repeat partners, group) and network_graph_shared_groups. The co-play insights live in network_graph_insights under the shared key:

  • regular squads — dense groups of 3 to max_squad_size players;
  • always together — pairs with many shared matches and few other partners, a possible win-trading or boosting signal;
  • only play with one account — a likely smurf or alt;
  • also on a shared device — overlap with the node ids of overlapGraph(), checked over the top players by activity.

Pairs are bounded per match. At most shared.max_group_size players (default 200) are paired from one match, so the work is at most n(n-1)/2: a 100-player lobby is 4,950 pairs, and a larger event is sampled in node-id order. Group payloads are capped by shared.group_members and shared.group_edges.

The summary tables

Table Holds
entity_clusters One row per group, with its counts and level (low, warning, critical).
entity_cluster_members The items in each group and the details each item has.
entity_links Pairs of items in a group and how many details they share.
entity_attribute_links A fast item-to-detail lookup.
referral_stats One row per referral network: size, depth, top counts (imported read model).
referral_closure Who is above whom in each referral tree, and how many steps apart (imported read model, optional).
network_graph_nodes Per-person aggregates for a model-bound tree graph.
network_graph_networks One summary row per network above rebuild.min_network_size.
network_graph_meta Rebuild watermark so the next run can be incremental.
network_graph_insights The cached insights shown on the overview (referral and following).
network_graph_edges One row per directed edge, with a mutual flag and edge time.
network_graph_directed_nodes Per-person in-degree, out-degree, mutual count and community.
network_graph_communities One summary row per connected community.
network_graph_pairs One weighted, pruned pair row per two nodes in a shared graph.
network_graph_shared_nodes Matches played, partners, repeat partners and group id per node.
network_graph_shared_groups One summary row per connected group.

After your job writes new data, call app(\SolutionForest\FilamentNetworkExplorer\Contracts\GraphRevision::class)->bump() so cached answers refresh straight away. To invalidate one graph only, pass its name: ->bump('referrals').

Things to know

  • Multi-tenant apps: a panel with tenancy shows nothing until you call ->sharedAcrossTenants(), because the bundled tables have no tenant column. Caches are kept separate per panel and per tenant, and your data source receives the tenant id in GraphScope::$tenantId. To separate tenants' data, write a data source that filters by it, then opt in.
  • Search uses simple "contains" matching. That is fine for small and medium data. For very large data, connect GraphSearch to a proper search index.

Related graph action

Actions\RelatedGraphAction opens one node's graph from any table row. It comes in two presentations:

Presentation What happens
->drawer() (default) A slide-over mounts the explorer widget focused on the node. A footer link opens the full page.
->page() Links to related/{graph}/{node}, which redirects to the explorer page with ?focus=.
RelatedGraphAction::make()->graph('follows');          // drawer
RelatedGraphAction::make('openGraph')->graph('follows')->page();

// Or name the kind and let the panel's configured graph be used.
RelatedGraphAction::make()->kind('directed');          // referral, directed, shared

The row key is the node id; override it with ->node($record->uuid).

  • A graph is supported only when the panel shows its explorer and the graph is the one that explorer is configured with (referral_graph, follow_graph, shared_graph). Otherwise the action hides itself.
  • Tree and shared explorers focus a network or group, so the node id is mapped to the read-model network_id / group_id with one indexed query.
  • The page link is a plain route, so a table render never runs a query per row. The redirect resolves the focus id when the row is clicked.
  • In client mode both the route and the redirect carry the encrypted handle, never the raw id.
  • A node missing from the read model shows "not in the graph yet" in the drawer, and the page route answers 404.

Data endpoints

Each panel gets its own data endpoints under /{panel-path}/network-explorer. They require login, plus the optional Gate ability from the config. They support caching headers (ETag, 304), and return 404 for unknown ids.

Path Returns
overview Short lists of groups and referral networks, plus top referrers and cached insights.
clusters/{cluster} One group with its items and links.
networks/{network} One referral network with its people and invite links.
entities/{entity}/attributes One item and the details it has.
search?q= Search results. Add &graph= to search the people of that graph by id and the columns given to NetworkGraph::nodes()->search().
follows/overview Communities and the following insights.
…?graph=name On the follow and shared endpoints: read another graph of the same kind. Only a graph an explorer of this panel shows can be named; anything else is 404.
follows/people/{person}/ego?hops=2 A bounded ego network around one person.
shared/overview Co-play group summaries and insights.
shared/groups/{group} One co-play group with bounded players and pairs.
related/{graph}/{node} Redirect to the explorer page focused on that node (used by the page presentation of the related graph action).

What happens when you open a page

sequenceDiagram
    participant You as Browser
    participant Page as Filament page
    participant Data as Plugin data endpoint
    participant Cache
    participant DB as Summary tables

    You->>Page: Open the relationship map, referral or following explorer
    Page-->>You: Page with the 3D viewer
    You->>Data: Ask for the overview (short list)
    Data->>Cache: Already have this answer?
    alt Cached
        Cache-->>Data: Yes, reuse it
    else Not cached
        Data->>DB: Read the summary rows
        DB-->>Data: Rows
        Data->>Cache: Keep it for next time
    end
    Data-->>You: Overview (ids hidden on client panels)
    You->>Data: Open one group, network or person
    Data-->>You: Only that group, network or a bounded ego network
Loading