-
-
Notifications
You must be signed in to change notification settings - Fork 15
feat: Port Laravel's once() helper with coroutine safety
#348
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
c45dadc
Add coroutine-safe Once class
binaryfire 5e00b0e
Add Onceable class for once() helper
binaryfire 7baff8d
Add once() helper function
binaryfire 79a47ec
Add OnceTest for coroutine-safe memoization
binaryfire 6487a09
Add OnceableTest for trace-based hash generation
binaryfire 0bb09f8
Add HasOnceHash contract for custom once() hashing
binaryfire 05657bc
Fix Onceable::tryFromTrace() missing return statement
binaryfire c93523b
Fix ProcessInspector phpstan annotation error
binaryfire 7c3431d
Apply php-cs-fixer formatting
binaryfire ed6904b
Fix duplicate type in ManagesFrequencies docblock
binaryfire 35e5b6d
Merge branch 'main' of github.com:hypervel/components
albertcht c966e00
Merge branch 'main' into feature/once
albertcht File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Hypervel\Support\Contracts; | ||
|
|
||
| interface HasOnceHash | ||
| { | ||
| /** | ||
| * Compute the hash that should be used to represent the object when given to a function using "once". | ||
| */ | ||
| public function onceHash(): string; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Hypervel\Support; | ||
|
|
||
| use Hypervel\Context\Context; | ||
| use WeakMap; | ||
|
|
||
| class Once | ||
| { | ||
| /** | ||
| * The context key for the current once instance. | ||
| */ | ||
| protected const INSTANCE_CONTEXT_KEY = '__support.once.instance'; | ||
|
|
||
| /** | ||
| * The context key for the once enabled flag. | ||
| */ | ||
| protected const ENABLED_CONTEXT_KEY = '__support.once.enabled'; | ||
|
|
||
| /** | ||
| * Create a new once instance. | ||
| * | ||
| * @param WeakMap<object, array<string, mixed>> $values | ||
| */ | ||
| protected function __construct(protected WeakMap $values) | ||
| { | ||
| } | ||
|
|
||
| /** | ||
| * Create a new once instance. | ||
| */ | ||
| public static function instance(): static | ||
| { | ||
| return Context::getOrSet(self::INSTANCE_CONTEXT_KEY, fn () => new static(new WeakMap())); | ||
| } | ||
|
|
||
| /** | ||
| * Get the value of the given onceable. | ||
| */ | ||
| public function value(Onceable $onceable): mixed | ||
| { | ||
| if (Context::get(self::ENABLED_CONTEXT_KEY, true) !== true) { | ||
| return call_user_func($onceable->callable); | ||
| } | ||
|
|
||
| $object = $onceable->object ?: $this; | ||
|
|
||
| $hash = $onceable->hash; | ||
|
|
||
| if (! isset($this->values[$object])) { | ||
| $this->values[$object] = []; | ||
| } | ||
|
|
||
| if (array_key_exists($hash, $this->values[$object])) { | ||
| return $this->values[$object][$hash]; | ||
| } | ||
|
|
||
| return $this->values[$object][$hash] = call_user_func($onceable->callable); | ||
| } | ||
|
|
||
| /** | ||
| * Re-enable the once instance if it was disabled. | ||
| */ | ||
| public static function enable(): void | ||
| { | ||
| Context::set(self::ENABLED_CONTEXT_KEY, true); | ||
| } | ||
|
|
||
| /** | ||
| * Disable the once instance. | ||
| */ | ||
| public static function disable(): void | ||
| { | ||
| Context::set(self::ENABLED_CONTEXT_KEY, false); | ||
| } | ||
|
|
||
| /** | ||
| * Flush the once instance. | ||
| */ | ||
| public static function flush(): void | ||
| { | ||
| Context::destroy(self::INSTANCE_CONTEXT_KEY); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Hypervel\Support; | ||
|
|
||
| use Closure; | ||
| use Hypervel\Support\Contracts\HasOnceHash; | ||
| use Laravel\SerializableClosure\Support\ReflectionClosure; | ||
|
|
||
| class Onceable | ||
| { | ||
| /** | ||
| * Create a new onceable instance. | ||
| * | ||
| * @param callable $callable | ||
| */ | ||
| public function __construct( | ||
| public string $hash, | ||
| public ?object $object, | ||
| public $callable, | ||
| ) { | ||
| } | ||
|
|
||
| /** | ||
| * Tries to create a new onceable instance from the given trace. | ||
| * | ||
| * @param array<int, array<string, mixed>> $trace | ||
| */ | ||
| public static function tryFromTrace(array $trace, callable $callable): ?static | ||
| { | ||
| if (! is_null($hash = static::hashFromTrace($trace, $callable))) { | ||
| $object = static::objectFromTrace($trace); | ||
|
|
||
| return new static($hash, $object, $callable); | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| /** | ||
| * Computes the object of the onceable from the given trace, if any. | ||
| * | ||
| * @param array<int, array<string, mixed>> $trace | ||
| * @return null|object | ||
| */ | ||
| protected static function objectFromTrace(array $trace) | ||
| { | ||
| return $trace[1]['object'] ?? null; | ||
| } | ||
|
|
||
| /** | ||
| * Computes the hash of the onceable from the given trace. | ||
| * | ||
| * @param array<int, array<string, mixed>> $trace | ||
| * @return null|string | ||
| */ | ||
| protected static function hashFromTrace(array $trace, callable $callable) | ||
| { | ||
| if (str_contains($trace[0]['file'] ?? '', 'eval()\'d code')) { | ||
| return null; | ||
| } | ||
|
|
||
| $uses = array_map( | ||
| static function (mixed $argument) { | ||
| if ($argument instanceof HasOnceHash) { | ||
| return $argument->onceHash(); | ||
| } | ||
|
|
||
| if (is_object($argument)) { | ||
| return spl_object_hash($argument); | ||
| } | ||
|
|
||
| return $argument; | ||
| }, | ||
| $callable instanceof Closure ? (new ReflectionClosure($callable))->getClosureUsedVariables() : [], | ||
| ); | ||
|
|
||
| $class = $callable instanceof Closure ? (new ReflectionClosure($callable))->getClosureCalledClass()?->getName() : null; | ||
|
|
||
| $class ??= isset($trace[1]['class']) ? $trace[1]['class'] : null; | ||
|
|
||
| return hash('xxh128', sprintf( | ||
| '%s@%s%s:%s (%s)', | ||
| $trace[0]['file'], | ||
| $class ? $class . '@' : '', | ||
| $trace[1]['function'], | ||
| $trace[0]['line'], | ||
| serialize($uses), | ||
| )); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Hypervel\Tests\Support; | ||
|
|
||
| use Hypervel\Support\Once; | ||
| use Hypervel\Tests\TestCase; | ||
|
|
||
| use function Hypervel\Coroutine\parallel; | ||
| use function Hypervel\Coroutine\run; | ||
|
|
||
| /** | ||
| * @internal | ||
| * @coversNothing | ||
| */ | ||
| class OnceTest extends TestCase | ||
| { | ||
| protected function setUp(): void | ||
| { | ||
| parent::setUp(); | ||
|
|
||
| Once::flush(); | ||
| Once::enable(); | ||
| } | ||
|
|
||
| protected function tearDown(): void | ||
| { | ||
| Once::flush(); | ||
| Once::enable(); | ||
|
|
||
| parent::tearDown(); | ||
| } | ||
|
|
||
| public function testOnceCachesWithinCoroutine(): void | ||
| { | ||
| $counter = $this->newCounter(); | ||
|
|
||
| $first = $this->runOnceWithCounter($counter); | ||
| $second = $this->runOnceWithCounter($counter); | ||
|
|
||
| $this->assertSame(1, $first); | ||
| $this->assertSame(1, $second); | ||
| $this->assertSame(1, $counter->value); | ||
| } | ||
|
|
||
| public function testOnceDifferentiatesClosureUses(): void | ||
| { | ||
| $results = array_map( | ||
| fn (int $value) => once(fn () => $value), | ||
| [1, 2], | ||
| ); | ||
|
|
||
| $this->assertSame([1, 2], $results); | ||
| } | ||
|
|
||
| public function testOnceIsCoroutineScoped(): void | ||
| { | ||
| $counter = $this->newCounter(); | ||
| $results = []; | ||
|
|
||
| run(function () use (&$results, $counter): void { | ||
| $results = parallel([ | ||
| fn () => $this->runOnceWithCounter($counter), | ||
| fn () => $this->runOnceWithCounter($counter), | ||
| ]); | ||
| }); | ||
|
|
||
| sort($results); | ||
|
|
||
| $this->assertSame([1, 2], $results); | ||
| $this->assertSame(2, $counter->value); | ||
| } | ||
|
|
||
| private function newCounter(): object | ||
| { | ||
| return new class { | ||
| public int $value = 0; | ||
| }; | ||
| } | ||
|
|
||
| private function runOnceWithCounter(object $counter): int | ||
| { | ||
| return once(function () use ($counter): int { | ||
| return ++$counter->value; | ||
| }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Hypervel\Tests\Support; | ||
|
|
||
| use Hypervel\Support\Contracts\HasOnceHash; | ||
| use Hypervel\Support\Onceable; | ||
| use Hypervel\Tests\TestCase; | ||
|
|
||
| /** | ||
| * @internal | ||
| * @coversNothing | ||
| */ | ||
| class OnceableTest extends TestCase | ||
| { | ||
| public function testTryFromTraceCapturesCallingObject(): void | ||
| { | ||
| $onceable = $this->createOnceable(fn () => 'value'); | ||
|
|
||
| $this->assertSame($this, $onceable->object); | ||
| } | ||
|
|
||
| public function testHashUsesOnceHashImplementation(): void | ||
| { | ||
| $trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2); | ||
|
|
||
| $value = new OnceHashStub('same'); | ||
| $onceableA = Onceable::tryFromTrace($trace, fn () => $value); | ||
|
|
||
| $value = new OnceHashStub('same'); | ||
| $onceableB = Onceable::tryFromTrace($trace, fn () => $value); | ||
|
|
||
| $value = new OnceHashStub('different'); | ||
| $onceableC = Onceable::tryFromTrace($trace, fn () => $value); | ||
|
|
||
| $this->assertNotNull($onceableA); | ||
| $this->assertNotNull($onceableB); | ||
| $this->assertNotNull($onceableC); | ||
| $this->assertSame($onceableA->hash, $onceableB->hash); | ||
| $this->assertNotSame($onceableA->hash, $onceableC->hash); | ||
| } | ||
|
|
||
| private function createOnceable(callable $callback): Onceable | ||
| { | ||
| $trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2); | ||
|
|
||
| $onceable = Onceable::tryFromTrace($trace, $callback); | ||
|
|
||
| $this->assertNotNull($onceable); | ||
|
|
||
| return $onceable; | ||
| } | ||
| } | ||
|
|
||
| class OnceHashStub implements HasOnceHash | ||
| { | ||
| public function __construct(private string $hash) | ||
| { | ||
| } | ||
|
|
||
| public function onceHash(): string | ||
| { | ||
| return $this->hash; | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.