Skip to content
4 changes: 3 additions & 1 deletion app/Http/Controllers/NotificationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ public function index(ListNotificationsRequest $request, #[CurrentUser] User $us
$readAt = $action->handle($user);

return Inertia::render('notification/index', [
'notifications' => Inertia::scroll(fn (): CursorPaginator => $query->paginate($user, $request->type(), $request->through()))->matchOn('data.group_id'),
'notifications' => Inertia::scroll(
fn (): CursorPaginator => $query->paginate($user, $request->type()),
)->matchOn('data.group_id'),
'filters' => ['type' => $request->type()],
'readAt' => $readAt->toJSON(),
]);
Expand Down
29 changes: 29 additions & 0 deletions app/Http/Controllers/NotificationSyncController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Actions\UpdateNotificationsReadAt;
use App\Http\Requests\ListNotificationSyncRequest;
use App\Models\User;
use App\Queries\NotificationGroupsQuery;
use Illuminate\Container\Attributes\CurrentUser;
use Illuminate\Http\JsonResponse;

final readonly class NotificationSyncController
{
public function index(
ListNotificationSyncRequest $request,
#[CurrentUser] User $user,
NotificationGroupsQuery $query,
UpdateNotificationsReadAt $action,
): JsonResponse {
$action->handle($user);

return response()->json([
...$query->sync($user, $request->type(), $request->visible()),
'unread_notifications_count' => $query->unreadCount($user),
])->header('Cache-Control', 'private, no-store');
}
}
39 changes: 39 additions & 0 deletions app/Http/Requests/ListNotificationSyncRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

final class ListNotificationSyncRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}

/** @return array<string, list<string>> */
public function rules(): array
{
return [
'type' => ['nullable', 'in:all,replies,quotes,stars,mentions,follows,moderation'],
'visible' => ['sometimes', 'array', 'list', 'max:20'],
'visible.*' => ['required', 'uuid', 'distinct'],
];
}

public function type(): string
{
return $this->filled('type') ? $this->string('type')->value() : 'all';
}

/** @return list<string> */
public function visible(): array
{
/** @var list<string> $visible */
$visible = $this->validated('visible', []);

return $visible;
}
}
7 changes: 0 additions & 7 deletions app/Http/Requests/ListNotificationsRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace App\Http\Requests;

use Carbon\CarbonImmutable;
use Illuminate\Foundation\Http\FormRequest;

final class ListNotificationsRequest extends FormRequest
Expand All @@ -19,17 +18,11 @@ public function rules(): array
{
return [
'type' => ['nullable', 'in:all,replies,quotes,stars,mentions,follows,moderation'],
'through' => ['nullable', 'date'],
];
}

public function type(): string
{
return $this->filled('type') ? $this->string('type')->value() : 'all';
}

public function through(): ?CarbonImmutable
{
return $this->date('through')?->toImmutable();
}
}
111 changes: 91 additions & 20 deletions app/Queries/NotificationGroupsQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

use App\Models\Notification;
use App\Models\User;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Illuminate\Contracts\Pagination\CursorPaginator;
use Illuminate\Database\Eloquent\Builder;
Expand All @@ -22,31 +21,77 @@
private const int STACKED_ACTORS = 3;

/** @return CursorPaginator<int, Notification> */
public function paginate(User $user, string $type = 'all', ?CarbonImmutable $through = null): CursorPaginator
public function paginate(User $user, string $type = 'all'): CursorPaginator
{
$order = 'PARTITION BY group_id ORDER BY CASE WHEN actor_position = 1 THEN 0 ELSE 1 END, created_at DESC, id DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING';
$events = $this->events($user, $type)->select('notifications.*')
->selectRaw("NTH_VALUE(actor_id, 2) OVER ({$order}) AS second_actor_id")
->selectRaw("NTH_VALUE(actor_id, 3) OVER ({$order}) AS third_actor_id");
$groups = $this->groupRepresentatives($user, $type)
->cursorPaginate(self::PER_PAGE)
->appends(request()->only('type'));

$query = Notification::query()->fromSub($events, 'notifications')
->where('group_rank', 1)
->with([
'actor' => fn (BelongsTo $query): BelongsTo => $query
->withExists(['followers as is_followed' => fn (Builder $query): Builder => $query->whereKey($user->id)]),
'commit',
$this->loadGroupRelations($user, array_values($groups->items()));

return $groups;
}

/**
* @param list<string> $visibleGroupIds
* @return array{
* head: list<Notification>,
* boundary: array{group_id: string, id: string}|null,
* visible: list<Notification>,
* missing_visible_group_ids: list<string>
* }
*/
public function sync(User $user, string $type = 'all', array $visibleGroupIds = []): array
{
$visibleGroupIds = array_slice($visibleGroupIds, 0, self::PER_PAGE);
$ranked = $this->groupRepresentatives($user, $type)
->reorder()
->select('notifications.*')
->selectRaw('ROW_NUMBER() OVER (ORDER BY created_at DESC, id DESC) AS sync_position');
$groups = Notification::query()
->fromSub($ranked, 'notifications')
->where(fn (NotificationBuilder $query): NotificationBuilder => $query
->where('sync_position', '<=', self::PER_PAGE + 1)
->when(
$visibleGroupIds !== [],
fn (NotificationBuilder $query): NotificationBuilder => $query
->orWhereIn('group_id', $visibleGroupIds),
))
->withCasts([
'event_count' => 'integer',
'sync_position' => 'integer',
])
->latest()->latest('id');
$perPage = $through instanceof CarbonImmutable
? max(self::PER_PAGE, $this->groupsSince($user, $through, $type)->where('group_rank', 1)->count())
: self::PER_PAGE;
->orderBy('sync_position')
->get();
$headWithBoundary = $groups->take(self::PER_PAGE + 1)->values();
$boundary = $headWithBoundary->count() > self::PER_PAGE
? $headWithBoundary->pop()
: null;
$head = array_values($headWithBoundary->all());
$headIds = array_map(fn (Notification $group): string => $group->group_id, $head);
$requestedVisibleIds = collect($visibleGroupIds)->diff($headIds)->values();
$visible = array_values($groups->whereIn('group_id', $requestedVisibleIds)->all());

$groups = $query->cursorPaginate($perPage)->appends(request()->except('through'));
$this->loadGroupRelations($user, [...$head, ...$visible]);

$this->loadStackedActors($groups->items());
foreach ([...$head, ...$visible] as $group) {
$group->makeHidden('sync_position');
}

return $groups;
$foundIds = [...$headIds, ...array_map(
fn (Notification $group): string => $group->group_id,
$visible,
)];

return [
'head' => $head,
'boundary' => $boundary instanceof Notification ? [
'group_id' => $boundary->group_id,
'id' => $boundary->id,
] : null,
'visible' => $visible,
'missing_visible_group_ids' => array_values(array_diff($visibleGroupIds, $foundIds)),
];
}

/**
Expand Down Expand Up @@ -182,6 +227,32 @@ private function group(NotificationBuilder $visible, string $type = 'all', ?Noti
->withCasts(['event_count' => 'integer']);
}

private function groupRepresentatives(User $user, string $type): NotificationBuilder
{
$order = 'PARTITION BY group_id ORDER BY CASE WHEN actor_position = 1 THEN 0 ELSE 1 END, created_at DESC, id DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING';
$events = $this->events($user, $type)->select('notifications.*')
->selectRaw("NTH_VALUE(actor_id, 2) OVER ({$order}) AS second_actor_id")
->selectRaw("NTH_VALUE(actor_id, 3) OVER ({$order}) AS third_actor_id");

return Notification::query()->fromSub($events, 'notifications')
->where('group_rank', 1)
->latest()
->latest('id');
}

/** @param list<Notification> $groups */
private function loadGroupRelations(User $user, array $groups): void
{
new Collection($groups)->load([
'actor' => fn (BelongsTo $query): BelongsTo => $query
->withExists(['followers as is_followed' => fn (Builder $query): Builder => $query->whereKey($user->id)]),
'commit',
]);

$this->loadStackedActors($groups);
}

/** @param array<int, Notification> $groups */
private function loadStackedActors(array $groups): void
{
Expand Down
Loading