File size: 2,026 Bytes
45dc401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php

declare(strict_types=1);

namespace App\Domain\Analytics;

use App\Infrastructure\Database\BaseRepository;
use App\Infrastructure\Ids\UuidGenerator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

final class AnalyticsEventRepository extends BaseRepository
{
    public function __construct(private readonly UuidGenerator $ids) {}

    protected function table(): string
    {
        return 'analytics_events';
    }

    protected function hasDeletedAtColumn(): bool
    {
        return false;
    }

    /**
     * Append a single event. The only write method on this table.
     * occurred_at is server-assigned here to prevent client clock skew.
     * No UPDATE or DELETE is ever called on this table — a DB trigger enforces this.
     *
     * Returns the new event id.
     */
    public function record(array $data): string
    {
        $id = $this->ids->generate();
        DB::table($this->table())->insert(array_merge($data, [
            'id'          => $id,
            'occurred_at' => Carbon::now()->format('Y-m-d H:i:s.u'),
            'bot_score'   => $data['bot_score'] ?? 0,
        ]));
        return $id;
    }

    /**
     * Append multiple events in one INSERT. All share the same occurred_at wall-clock
     * instant; for strict ordering within the batch the caller may pre-populate
     * occurred_at with microsecond offsets.
     */
    public function recordBatch(array $events): void
    {
        if (empty($events)) {
            return;
        }
        $now  = Carbon::now()->format('Y-m-d H:i:s.u');
        $rows = array_map(function (array $event) use ($now): array {
            return array_merge($event, [
                'id'          => $this->ids->generate(),
                'occurred_at' => $event['occurred_at'] ?? $now,
                'bot_score'   => $event['bot_score'] ?? 0,
            ]);
        }, $events);

        foreach (array_chunk($rows, 500) as $chunk) {
            DB::table($this->table())->insert($chunk);
        }
    }
}