Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions src/activity-log/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,39 @@ Documentation: https://hypervel.org/docs/activity-log

## Differences From Spatie Laravel Activity Log

- Public names use `ActivityLog` and `activity-log` casing. The global
`activity()` helper is retained.
- Use the `ActivityLog` facade in place of Spatie's `Activity` facade. The
config file and Artisan command prefix use `activity-log`, and environment
settings use `ACTIVITY_LOG_`. The global helper is `activity()`.
- `activity(null)` selects the configured default. Empty string and `"0"` are
distinct log names. `useLog(null)` and `inLog(null)` explicitly set a null name.
- Automatic model logging uses the event's in-memory snapshot without another
subject query. `refreshBeforeLogging()` provides an explicit,
transaction-only refresh for database-generated values.
- Dotted relation attributes retain the configured key even when traversal
resolves a snake-case, camel-case, or dynamic-relation alias.
- Optional buffering is coroutine-scoped, transaction-aware, and flushed in
bounded batches at Hypervel lifecycle boundaries.
- The activity model's connection owns the write. Spatie can defer a write
on another connection until the subject commits. Hypervel supports a
separate activity database, but a rollback on the subject connection does
not discard that activity. For atomic audit writes, disable buffering and
use the same connection and transaction. For durable cross-database
delivery, use an application outbox.
- Optional buffering is coroutine-scoped and flushes in bounded batches at
request and job boundaries. If an insert fails, its attempted batch is
discarded because retrying an ambiguous write can duplicate rows.
Unattempted rows remain eligible to flush.
- The facade resolves a stateless `ActivityLogManager`. Each fluent root
call gets a fresh logger, and reusing a logger after `log()` starts a new
activity even when the previous call failed or logging was disabled.
- Register callbacks and macros at worker boot. Resolve request-specific
values such as a batch UUID when the callback runs, since the same
registration serves later requests. See [Callbacks and Macros](https://hypervel.org/docs/activity-log#callbacks-and-macros).
- Hypervel reads package settings through `ActivityLogConfiguration`. Omitted
top-level settings use package defaults. If you supply a `buffer` group,
include both `enabled` and `batch_size`. Explicitly setting `activity_model`
or `enabled` to null is invalid.
- Cleanup uses the model's configured created-at column and primary key
to delete bounded batches. A custom model can record keyless activities,
but the built-in cleanup action requires a primary key.
- `setLogStatus()` is replaced by `enableLogging()`, `disableLogging()`, and
`withoutLogging()`. Tests reset callbacks through `flushState()` rather than
the upstream test-only `clearBeforeLoggingCallbacks()` alias.
Expand Down
1 change: 1 addition & 0 deletions src/activity-log/src/Actions/CleanActivityLogAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ private function newEligibleQuery(
->where($createdAtColumn, '<', $cutOffDate);

if ($logName !== null) {
// Custom activity models implement the storage contract and may have no inLog scope.
$query->where('log_name', $logName);
}

Expand Down
3 changes: 3 additions & 0 deletions src/activity-log/src/Actions/LogActivityAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ protected function beforeActivityLogged(ActivityContract&Model $activity): void
*/
protected function save(ActivityContract&Model $activity): void
{
// REMOVED: Spatie defers to the subject's transaction across connections.
// Only the activity connection owns this write. Atomic audits share the
// subject's transaction; durable delivery to another database needs an outbox.
if ($this->shouldBuffer()) {
$this->container->make(ActivityBuffer::class)->add($activity);

Expand Down
6 changes: 4 additions & 2 deletions src/activity-log/src/Support/ActivityBuffer.php
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,8 @@ protected function flushBatch(): void
$firstStaged = array_key_first($this->staged);
$records = [];

// Claim before writing: transaction callbacks and events may re-enter
// the buffer, and must never observe or insert this in-flight batch.
// Claim the batch before writing so reentrant callbacks cannot insert it again.
// Keep it removed on failure: if the commit outcome is unknown, a retry can duplicate rows.
foreach (array_slice($this->pending, 0, $this->batchSize(), preserve_keys: true) as $sequence => $record) {
if ($firstStaged !== null && $sequence >= $firstStaged) {
break;
Expand Down Expand Up @@ -363,6 +363,8 @@ protected function batchSize(): int

/**
* Ensure the activity still targets the configured connection and table.
*
* All rows in this buffer share an insert target and its transaction callbacks.
*/
protected function ensurePersistenceTargetWasNotChanged(ActivityContract&Model $activity): void
{
Expand Down
12 changes: 8 additions & 4 deletions src/activity-log/src/Support/ActivityLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -296,14 +296,18 @@ protected function getActivity(): ActivityContract&Model
*/
protected function useDefaultCauserIfNoneWasGiven(): void
{
if ($this->causerResolved || $this->getActivity()->getAttribute('causer_id') !== null) {
if ($this->causerResolved) {
return;
}

$causer = $this->causerResolver->resolve();
$activity = $this->getActivity();

if ($activity->getAttribute('causer_id') === null) {
$causer = $this->causerResolver->resolve();

if ($causer !== null) {
$this->getActivity()->causer()->associate($causer);
if ($causer !== null) {
$activity->causer()->associate($causer);
}
}

$this->causerResolved = true;
Expand Down
10 changes: 5 additions & 5 deletions src/activity-log/src/Support/CauserResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,12 @@ public function withCauser(Model|int|string|null $causer, Closure $callback): mi
/**
* Determine whether a resolver result can identify a causer.
*/
protected function isResolvable(mixed $causer): bool
protected function isResolvable(mixed $model): bool
{
return $causer instanceof Model
|| is_int($causer)
|| is_string($causer)
|| $causer === null;
return $model instanceof Model
|| is_int($model)
|| is_string($model)
|| $model === null;
}

/**
Expand Down
29 changes: 22 additions & 7 deletions src/docs/activity-log.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,21 @@ The `createdAt()` method uses the activity model's configured created-at column.

Use `activity('security')`, `useLog()`, or `inLog()` to select a log. These methods, `LogOptions::useLogName()`, and the `inLog` query scope also accept backed enums. Their backing values are stored as strings. Passing `null` to `activity()` selects `default_log_name`; empty string and `"0"` are valid, distinct log names. Calling `useLog(null)` or `inLog(null)` explicitly sets the pending activity's log name to `null`.

To read the log name back as an enum, register a custom activity model and add the cast to the model's existing casts:

```php
use App\Enums\LogName;
use Hypervel\ActivityLog\Models\Activity as BaseActivity;

class Activity extends BaseActivity
{
protected function casts(): array
{
return [...parent::casts(), 'log_name' => LogName::class];
}
}
```

<a name="placeholders"></a>
### Placeholders

Expand All @@ -233,7 +248,7 @@ activity()
->log('Invoice approved');
```

The default causer has already been associated when the tap runs.
The default causer is available when the tap runs. If the callback replaces or clears the causer, `log()` preserves that choice.

<a name="conditional-logging"></a>
### Conditional Logging
Expand Down Expand Up @@ -596,9 +611,9 @@ ACTIVITY_LOG_BUFFER_BATCH_SIZE=500
Buffered activities are kept in memory for the current coroutine and are never combined with activities from another request or job. The buffer is created only when the first activity needs it.

> [!WARNING]
> Buffering is not a durable queue. If you need activities to survive a worker crash or to be delivered across database connections, use an application outbox or queue.
> A worker crash can lose activities still in memory. If those activities must survive a crash, use a durable queue or transactional outbox.

Buffered activities are written in call order. Custom columns, timestamp settings, and database defaults are preserved.
The buffer writes each bounded batch in one transaction. Consecutive activities with the same columns share an insert. This preserves logging order and lets the database apply defaults to omitted columns. The activity model controls its timestamps.

Before enabling buffering, keep these differences in mind:

Expand All @@ -612,11 +627,11 @@ A UUID/ULID key can therefore exist before the row is persisted. Do not treat a
<a name="transactions"></a>
### Transactions

An activity prepared while its own activity connection is transacting is staged against that exact connection. The outer commit makes it eligible for insertion; rollback discards it. Savepoint order is preserved, and a transaction on another connection does not decide its outcome.
A buffered activity prepared inside a transaction on the activity model's connection becomes eligible for insertion when the outer transaction commits. Rolling back discards it. Savepoint order is preserved. If the subject uses a different connection, its transaction does not control the activity write, even when the activity was recorded by a model event.

After the domain transaction commits, buffered activities are written in a new transaction. Activities from rolled-back transactions are discarded, but the later insert is not atomic with your domain changes. A crash between the two commits can lose the activity.
When the activity and domain models share a connection, buffered activities are written in a new transaction after the domain transaction commits. A crash between the two commits can lose the activity. On a separate connection, the activity can be written before the domain transaction finishes.

If the activity must commit atomically with domain data, disable buffering and write it immediately using the same transaction and connection. For durable or cross-connection delivery, use an application outbox.
If the activity must commit atomically with domain data, disable buffering and write it immediately using the same transaction and connection. If delivery to a separate audit database must be guaranteed for each committed domain change, write an outbox record in the domain transaction and have a worker deliver it to the audit database.

Calling `ActivityBuffer::flush()` while the buffer has work and its activity connection has an open application transaction throws. It drains rows in call order and stops at the first activity whose transaction outcome is still pending.

Expand Down Expand Up @@ -741,7 +756,7 @@ Review custom models, actions, callbacks, and tests for these public differences
- `activity()` selects the default log name only for `null`, not empty string or `"0"`;
- automatic logging does not call `fresh()` unless `refreshBeforeLogging()` is enabled inside a transaction;
- dotted relation keys retain the configured spelling;
- buffering is coroutine-scoped, bounded, and transaction-aware;
- buffering is coroutine-scoped and bounded; a transaction on a separate subject connection does not defer or discard an activity write;
- `setLogStatus()` is replaced by `enableLogging()`, `disableLogging()`, and `withoutLogging()`;
- Hypervel clears registered callbacks between tests.

Expand Down
70 changes: 0 additions & 70 deletions tests/ActivityLog/ActivityLogManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace Hypervel\Tests\ActivityLog;

use Hypervel\ActivityLog\Actions\LogActivityAction;
use Hypervel\ActivityLog\ActivityLogManager;
use Hypervel\ActivityLog\Exceptions\CouldNotLogActivity;
use Hypervel\ActivityLog\Facades\ActivityLog;
Expand All @@ -18,7 +17,6 @@
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
use JMac\Testing\Matching\Argument;
use RuntimeException;

class ActivityLogManagerTest extends TestCase
{
Expand Down Expand Up @@ -76,74 +74,6 @@ function (string $marker): ActivityLogger {
$this->assertFalse(ActivityLog::hasMacro('marked'));
}

public function testBootRegistrarsDoNotResolveScopedServicesOrLoggers(): void
{
$this->app->bind(
ActivityLogger::class,
static fn (): never => throw new RuntimeException('logger resolved'),
);
$this->app->scoped(
CauserResolver::class,
static fn (): never => throw new RuntimeException('resolver resolved'),
);

ActivityLog::macro('registered_only', static fn (): null => null);
ActivityLog::beforeLogging(static function (): void {
});

$this->assertTrue(ActivityLog::hasMacro('registered_only'));
}

public function testDefaultCauserIsVisibleToEveryLoggingHook(): void
{
$causer = User::query()->firstOrFail();
$subject = new class extends Article {
/**
* Modify the activity before it is logged.
*/
public function beforeActivityLogged(Activity $activity, string $eventName): void
{
$activity->setAttribute(
'properties',
$activity->properties->put(
'subject_hook_causer',
$activity->causer?->getKey(),
),
);
}
};
$this->app->make(CauserResolver::class)->setCauser($causer);
LogActivityAction::beforeLogging(function (Activity $activity): void {
$activity->setAttribute(
'properties',
$activity->properties->put(
'global_callback_causer',
$activity->causer?->getKey(),
),
);
});

activity()
->performedOn($subject)
->tap(function (Activity $activity): void {
$activity->setAttribute(
'properties',
$activity->properties->put(
'tap_causer',
$activity->causer?->getKey(),
),
);
})
->log('Causer :causer.name');

$activity = Activity::query()->firstOrFail();

$this->assertSame('Causer name 1', $activity->description);
$this->assertSame($causer->getKey(), $activity->getProperty('tap_causer'));
$this->assertSame($causer->getKey(), $activity->getProperty('subject_hook_causer'));
$this->assertSame($causer->getKey(), $activity->getProperty('global_callback_causer'));
}

public function testAnonymousCauserDissociatesAnAlreadyResolvedDefault(): void
{
$causer = User::query()->firstOrFail();
Expand Down
16 changes: 11 additions & 5 deletions tests/ActivityLog/Commands/CleanActivityLogCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Hypervel\Support\Facades\Artisan;
use Hypervel\Tests\ActivityLog\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestWith;

class CleanActivityLogCommandTest extends TestCase
{
Expand Down Expand Up @@ -46,7 +47,7 @@ public function testCanCleanTheActivityLog(): void

$this->assertCount(60, Activity::all());

Artisan::call('activity-log:clean');
$this->assertSame(0, Artisan::call('activity-log:clean'));

$this->assertCount(31, Activity::all());

Expand All @@ -55,7 +56,9 @@ public function testCanCleanTheActivityLog(): void
$this->assertCount(0, Activity::where('created_at', '<', $cutOffDate)->get());
}

public function testCanAcceptDaysAsOptionToOverrideConfigSetting(): void
#[TestWith([1])]
#[TestWith([7])]
public function testCanAcceptDaysAsOptionToOverrideConfigSetting(int $days): void
{
foreach (range(1, 60) as $index) {
Activity::create([
Expand All @@ -66,11 +69,11 @@ public function testCanAcceptDaysAsOptionToOverrideConfigSetting(): void

$this->assertCount(60, Activity::all());

Artisan::call('activity-log:clean', ['--days' => 7]);
$this->assertSame(0, Artisan::call('activity-log:clean', ['--days' => $days]));

$this->assertCount(7, Activity::all());
$this->assertCount($days, Activity::all());

$cutOffDate = CarbonImmutable::now()->subDays(7)->format('Y-m-d H:i:s');
$cutOffDate = CarbonImmutable::now()->subDays($days)->format('Y-m-d H:i:s');

$this->assertCount(0, Activity::where('created_at', '<', $cutOffDate)->get());
}
Expand Down Expand Up @@ -137,6 +140,7 @@ public function testDoesNotCleanTheActivityLogWhenDaysOptionValueIsInvalid(mixed
$exitCode = Artisan::call('activity-log:clean', ['--days' => $days]);

$this->assertSame(1, $exitCode);
$this->assertStringContainsString('The days option must be a positive integer.', Artisan::output());
$this->assertCount(60, Activity::all());
}

Expand All @@ -152,6 +156,8 @@ public static function invalidDays(): array
'non-numeric string' => ['abc'],
'fraction' => ['7.5'],
'empty string' => [''],
'zero' => [0],
'negative' => [-1],
];
}
}
12 changes: 12 additions & 0 deletions tests/ActivityLog/Models/ActivityWithoutUpdatedAt.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Hypervel\Tests\ActivityLog\Models;

use Hypervel\ActivityLog\Models\Activity;

class ActivityWithoutUpdatedAt extends Activity
{
public const ?string UPDATED_AT = null;
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,12 @@ static function (): void {
}
}

public function testUsesTheCustomConnectionForImmediateWrites(): void
public function testUsesTheDefaultDatabaseConnection(): void
{
$this->assertSame(DB::connection('sqlite'), (new DefaultActivity)->getConnection());
}

public function testUsesTheDatabaseConnectionFromACustomModel(): void
{
config()->set(
'activity-log.activity_model',
Expand Down
5 changes: 4 additions & 1 deletion tests/ActivityLog/Models/CustomTableNameModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,13 @@ protected function tearDownInCoroutine(): void
}
}

public function testUsesTheCustomTableForImmediateQueriesAndCleanup(): void
public function testUsesActivityLogAsTheDefaultTableName(): void
{
$this->assertSame('activity_log', (new DefaultActivity)->getTable());
}

public function testUsesTheTableNameFromACustomModel(): void
{
config()->set(
'activity-log.activity_model',
CustomTableNameOnActivityModel::class,
Expand Down
2 changes: 1 addition & 1 deletion tests/ActivityLog/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public function getAuthPasswordName(): string
*/
public function getAuthPassword(): ?string
{
return $this->getAttribute('password');
return $this->getAttribute($this->getAuthPasswordName());
}

/**
Expand Down
Loading
Loading