feat: workspace-scoped broadcast channel and post lifecycle events

Adds a private workspace channel (WorkspaceChannel, authorised by
membership) so list views can subscribe once and receive events for
every post in the workspace, instead of opening N per-post channels.

New events:
- PostCreated   (broadcast on workspace.{id})
- PostDeleted   (broadcast on workspace.{id}; carries primitive ids so
  it fires after \$post->delete())
- PostPlatformStatusUpdated now broadcasts on both post.{id} and
  workspace.{id} so focused views and lists share the same trigger.

All broadcast events migrated to the namespaced 'entity.action'
convention from Laravel's broadcasting docs and switched from
ShouldBroadcastNow to ShouldBroadcast on a dedicated 'broadcasts'
queue (added to the supervisor-1 list in config/horizon.php) to keep
HTTP responses fast:

  PostCreated                  -> post.created
  PostDeleted                  -> post.deleted
  PostPlatformStatusUpdated    -> post.platform.status.updated
  PostCommentCreated           -> post.comment.created
  NotificationCreated          -> notification.created
  PostCreationReady            -> ai.creation.completed

Drops the SubscriptionCreated event — it was broadcast on
users.{owner_id} but had no listeners (frontend or backend) and the
billing/PostHog flow already handles plan-change tracking elsewhere.

PostPlatformStatusUpdated payload trimmed to {post_id} since every
consumer (Show, Edit, Index) does router.reload({ only: [...] }) and
ignored the rich shape.
This commit is contained in:
Paulo Castellano 2026-05-07 16:02:22 -03:00
parent e653c900db
commit 06e72831f6
18 changed files with 372 additions and 75 deletions

View file

@ -5,6 +5,7 @@
namespace App\Actions\Post;
use App\Enums\Post\Status as PostStatus;
use App\Events\PostCreated;
use App\Models\Post;
use App\Models\User;
use App\Models\Workspace;
@ -38,7 +39,7 @@ public static function execute(Workspace $workspace, User $user, array $data): P
{
$scheduledAt = self::resolveScheduledAt($data);
return DB::transaction(function () use ($workspace, $user, $data, $scheduledAt): Post {
$post = DB::transaction(function () use ($workspace, $user, $data, $scheduledAt): Post {
$post = $workspace->posts()->create([
'user_id' => $user->id,
'content' => data_get($data, 'content', ''),
@ -72,6 +73,10 @@ public static function execute(Workspace $workspace, User $user, array $data): P
return $post;
});
PostCreated::dispatch($post);
return $post;
}
/**

View file

@ -4,12 +4,18 @@
namespace App\Actions\Post;
use App\Events\PostDeleted;
use App\Models\Post;
class DeletePost
{
public static function execute(Post $post): void
{
$postId = $post->id;
$workspaceId = $post->workspace_id;
$post->delete();
PostDeleted::dispatch($postId, $workspaceId);
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Broadcasting;
use App\Models\User;
use App\Models\Workspace;
class WorkspaceChannel
{
public function join(User $user, Workspace $workspace): bool
{
return $workspace->hasMember($user);
}
}

View file

@ -6,11 +6,11 @@
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PostCreationReady implements ShouldBroadcastNow
class PostCreationReady implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
@ -23,16 +23,16 @@ public function __construct(
public ?string $imageBody = null,
) {}
public function broadcastAs(): string
{
return 'ai.creation.completed';
}
public function broadcastOn(): PrivateChannel
{
return new PrivateChannel("users.{$this->userId}.ai-creation.{$this->creationId}");
}
public function broadcastAs(): string
{
return 'PostCreationReady';
}
/**
* @return array<string, mixed>
*/
@ -46,4 +46,9 @@ public function broadcastWith(): array
'error' => $this->error,
];
}
public function broadcastQueue(): string
{
return 'broadcasts';
}
}

View file

@ -7,15 +7,20 @@
use App\Models\Notification;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
class NotificationCreated implements ShouldBroadcastNow
class NotificationCreated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets;
public function __construct(public Notification $notification) {}
public function broadcastAs(): string
{
return 'notification.created';
}
public function broadcastOn(): array
{
return [
@ -23,11 +28,9 @@ public function broadcastOn(): array
];
}
public function broadcastAs(): string
{
return 'NotificationCreated';
}
/**
* @return array<string, mixed>
*/
public function broadcastWith(): array
{
return [
@ -47,4 +50,9 @@ public function broadcastWith(): array
],
];
}
public function broadcastQueue(): string
{
return 'broadcasts';
}
}

View file

@ -9,15 +9,20 @@
use App\Support\MentionParser;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
class PostCommentCreated implements ShouldBroadcastNow
class PostCommentCreated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets;
public function __construct(public PostComment $comment) {}
public function broadcastAs(): string
{
return 'post.comment.created';
}
public function broadcastOn(): array
{
return [
@ -25,11 +30,9 @@ public function broadcastOn(): array
];
}
public function broadcastAs(): string
{
return 'PostCommentCreated';
}
/**
* @return array<string, mixed>
*/
public function broadcastWith(): array
{
$mentionedIds = MentionParser::extractUserIds($this->comment->body ?? '');
@ -59,4 +62,9 @@ public function broadcastWith(): array
'mentioned_users' => $mentionedUsers,
];
}
public function broadcastQueue(): string
{
return 'broadcasts';
}
}

View file

@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Events;
use App\Models\Post;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PostCreated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(public Post $post) {}
public function broadcastAs(): string
{
return 'post.created';
}
public function broadcastOn(): array
{
return [
new PrivateChannel('workspace.'.$this->post->workspace_id),
];
}
/**
* @return array<string, string>
*/
public function broadcastWith(): array
{
return [
'post_id' => $this->post->id,
];
}
public function broadcastQueue(): string
{
return 'broadcasts';
}
}

View file

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
class PostDeleted implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets;
public function __construct(
public string $postId,
public string $workspaceId,
) {}
public function broadcastAs(): string
{
return 'post.deleted';
}
public function broadcastOn(): array
{
return [
new PrivateChannel('workspace.'.$this->workspaceId),
];
}
/**
* @return array<string, string>
*/
public function broadcastWith(): array
{
return [
'post_id' => $this->postId,
];
}
public function broadcastQueue(): string
{
return 'broadcasts';
}
}

View file

@ -7,11 +7,11 @@
use App\Models\PostPlatform;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PostPlatformStatusUpdated implements ShouldBroadcastNow
class PostPlatformStatusUpdated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
@ -19,33 +19,29 @@ public function __construct(public PostPlatform $postPlatform) {}
public function broadcastAs(): string
{
return 'PostPlatformStatusUpdated';
return 'post.platform.status.updated';
}
public function broadcastOn(): array
{
return [
new PrivateChannel('post.'.$this->postPlatform->post_id),
new PrivateChannel('workspace.'.$this->postPlatform->post->workspace_id),
];
}
/**
* @return array<string, string>
*/
public function broadcastWith(): array
{
$post = $this->postPlatform->post->fresh();
return [
'post_platform' => [
'id' => $this->postPlatform->id,
'status' => $this->postPlatform->status->value,
'platform_url' => $this->postPlatform->platform_url,
'error_message' => $this->postPlatform->error_message,
'published_at' => $this->postPlatform->published_at?->toISOString(),
],
'post' => [
'id' => $post->id,
'status' => $post->status->value,
'published_at' => $post->published_at?->toISOString(),
],
'post_id' => $this->postPlatform->post_id,
];
}
public function broadcastQueue(): string
{
return 'broadcasts';
}
}

View file

@ -214,7 +214,7 @@
'defaults' => [
'supervisor-1' => [
'connection' => 'redis',
'queue' => ['default', 'posthog'],
'queue' => ['default', 'posthog', 'broadcasts'],
'balance' => 'auto',
'autoScalingStrategy' => 'time',
'maxProcesses' => 1,

View file

@ -5,11 +5,14 @@
use App\Broadcasting\PostChannel;
use App\Broadcasting\UserAiCreationChannel;
use App\Broadcasting\UserAiGenerationChannel;
use App\Broadcasting\WorkspaceChannel;
use App\Broadcasting\WorkspaceUserChannel;
use Illuminate\Support\Facades\Broadcast;
Broadcast::channel('post.{post}', PostChannel::class);
Broadcast::channel('workspace.{workspace}', WorkspaceChannel::class);
Broadcast::channel('workspace.{workspace}.user.{owner}', WorkspaceUserChannel::class);
Broadcast::channel('users.{userId}.ai-gen.{generationId}', UserAiGenerationChannel::class);

View file

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
use App\Actions\Post\CreatePost;
use App\Events\PostCreated;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Event;
test('execute dispatches PostCreated with the persisted post', function () {
Event::fake([PostCreated::class]);
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$post = CreatePost::execute($workspace, $user, [
'content' => 'Hello world',
]);
Event::assertDispatched(
PostCreated::class,
fn (PostCreated $event) => $event->post->id === $post->id
&& $event->post->workspace_id === $workspace->id,
);
});

View file

@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
use App\Actions\Post\DeletePost;
use App\Events\PostDeleted;
use App\Models\Post;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Event;
test('execute deletes the post', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$post = Post::factory()->create([
'workspace_id' => $workspace->id,
'user_id' => $user->id,
]);
DeletePost::execute($post);
expect(Post::find($post->id))->toBeNull();
});
test('execute dispatches PostDeleted with the post and workspace ids', function () {
Event::fake([PostDeleted::class]);
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$post = Post::factory()->create([
'workspace_id' => $workspace->id,
'user_id' => $user->id,
]);
$postId = $post->id;
$workspaceId = $post->workspace_id;
DeletePost::execute($post);
Event::assertDispatched(
PostDeleted::class,
fn (PostDeleted $event) => $event->postId === $postId
&& $event->workspaceId === $workspaceId,
);
});

View file

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
use App\Broadcasting\WorkspaceChannel;
use App\Enums\UserWorkspace\Role;
use App\Models\User;
use App\Models\Workspace;
test('workspace channel allows a member to join', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$workspace->members()->attach($user->id, ['role' => Role::Member->value]);
$channel = new WorkspaceChannel;
expect($channel->join($user, $workspace))->toBeTrue();
});
test('workspace channel denies a non-member', function () {
$owner = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $owner->id]);
$outsider = User::factory()->create();
$channel = new WorkspaceChannel;
expect($channel->join($outsider, $workspace))->toBeFalse();
});

View file

@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
use App\Events\PostCreated;
use App\Models\Post;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Broadcasting\PrivateChannel;
test('event broadcasts on the workspace channel', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$post = Post::factory()->create([
'workspace_id' => $workspace->id,
'user_id' => $user->id,
]);
$event = new PostCreated($post);
$channels = $event->broadcastOn();
expect($channels)->toHaveCount(1);
expect($channels[0])->toBeInstanceOf(PrivateChannel::class);
expect($channels[0]->name)->toBe('private-workspace.'.$workspace->id);
});
test('event broadcasts with the post id', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$post = Post::factory()->create([
'workspace_id' => $workspace->id,
'user_id' => $user->id,
]);
$event = new PostCreated($post);
expect($event->broadcastWith())->toBe(['post_id' => $post->id]);
});
test('event broadcasts as a stable name', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$post = Post::factory()->create([
'workspace_id' => $workspace->id,
'user_id' => $user->id,
]);
$event = new PostCreated($post);
expect($event->broadcastAs())->toBe('post.created');
});

View file

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
use App\Events\PostDeleted;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Support\Str;
test('event broadcasts on the workspace channel only', function () {
$event = new PostDeleted(Str::uuid()->toString(), 'workspace-123');
$channels = $event->broadcastOn();
expect($channels)->toHaveCount(1);
expect($channels[0])->toBeInstanceOf(PrivateChannel::class);
expect($channels[0]->name)->toBe('private-workspace.workspace-123');
});
test('event broadcasts with the post id', function () {
$postId = (string) Str::uuid();
$event = new PostDeleted($postId, 'workspace-123');
expect($event->broadcastWith())->toBe(['post_id' => $postId]);
});
test('event broadcasts as a stable name', function () {
$event = new PostDeleted(Str::uuid()->toString(), 'workspace-123');
expect($event->broadcastAs())->toBe('post.deleted');
});

View file

@ -28,48 +28,25 @@
]);
});
test('event broadcasts on correct channel', function () {
test('event broadcasts on the per-post and per-workspace channels', function () {
$event = new PostPlatformStatusUpdated($this->postPlatform);
$channels = $event->broadcastOn();
expect($channels)->toHaveCount(1);
expect($channels)->toHaveCount(2);
expect($channels[0])->toBeInstanceOf(PrivateChannel::class);
expect($channels[0]->name)->toBe('private-post.'.$this->post->id);
expect($channels[1])->toBeInstanceOf(PrivateChannel::class);
expect($channels[1]->name)->toBe('private-workspace.'.$this->workspace->id);
});
test('event broadcasts with correct data', function () {
$this->postPlatform->update([
'status' => 'published',
'platform_url' => 'https://linkedin.com/post/123',
'published_at' => now(),
]);
$event = new PostPlatformStatusUpdated($this->postPlatform->fresh());
$data = $event->broadcastWith();
expect($data)->toHaveKey('post_platform');
expect($data)->toHaveKey('post');
expect($data['post_platform']['id'])->toBe($this->postPlatform->id);
expect($data['post_platform']['status'])->toBe('published');
expect($data['post_platform']['platform_url'])->toBe('https://linkedin.com/post/123');
expect($data['post']['id'])->toBe($this->post->id);
});
test('event broadcasts error message when failed', function () {
$this->postPlatform->update([
'status' => 'failed',
'error_message' => 'API Error',
]);
$event = new PostPlatformStatusUpdated($this->postPlatform->fresh());
$data = $event->broadcastWith();
expect($data['post_platform']['error_message'])->toBe('API Error');
});
test('event broadcasts null published_at when not published', function () {
test('event broadcasts with the post id', function () {
$event = new PostPlatformStatusUpdated($this->postPlatform);
$data = $event->broadcastWith();
expect($data['post_platform']['published_at'])->toBeNull();
expect($event->broadcastWith())->toBe(['post_id' => $this->post->id]);
});
test('event broadcasts as a stable name', function () {
$event = new PostPlatformStatusUpdated($this->postPlatform);
expect($event->broadcastAs())->toBe('post.platform.status.updated');
});