Skip to content

Commit db55398

Browse files
committed
Cleanup serialized context coming back from a task worker
1 parent 58739c1 commit db55398

File tree

4 files changed

+35
-1
lines changed

4 files changed

+35
-1
lines changed

src/Runner/FixableTaskResult.php

+8
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,14 @@ public function getContext(): ContextInterface
6969
return $this->result->getContext();
7070
}
7171

72+
public function withContext(ContextInterface $context): static
73+
{
74+
$new = clone $this;
75+
$new->result = $this->result->withContext($context);
76+
77+
return $new;
78+
}
79+
7280
public function withAppendedMessage(string $message): TaskResultInterface
7381
{
7482
$new = clone $this;

src/Runner/TaskHandler/Middleware/ParallelProcessingMiddleware.php

+17-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,9 @@ static function () use ($task, $runnerContext, $next, $currentEnv): TaskResultIn
5858

5959
return async(function () use ($task, $runnerContext, $execution): TaskResultInterface {
6060
try {
61-
return $execution->getFuture()->await();
61+
$result = $execution->getFuture()->await();
62+
63+
return $this->swapSerializedContext($result, $runnerContext);
6264
} catch (\Throwable $exception) {
6365
return TaskResult::createFailed(
6466
$task,
@@ -75,4 +77,18 @@ private function wrapException(\Throwable $error): ParallelException
7577
? ParallelException::fromVerboseThrowable($error)
7678
: ParallelException::fromThrowable($error);
7779
}
80+
81+
/**
82+
* The results coming back from a parallel worker contains a serialized context.
83+
* This context can be rather big, which can cause memory issues.
84+
*
85+
* This method will swap the serialized context with the original
86+
* context so that the serialized one gets garbage collected.
87+
*/
88+
private function swapSerializedContext(
89+
TaskResultInterface $result,
90+
TaskRunnerContext $runnerContext
91+
): TaskResultInterface {
92+
return $result->withContext($runnerContext->getTaskContext());
93+
}
7894
}

src/Runner/TaskResult.php

+8
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,14 @@ public function getContext(): ContextInterface
9595
return $this->context;
9696
}
9797

98+
public function withContext(ContextInterface $context): static
99+
{
100+
$new = clone $this;
101+
$new->context = $context;
102+
103+
return $new;
104+
}
105+
98106
public function withAppendedMessage(string $message): TaskResultInterface
99107
{
100108
$new = clone $this;

src/Runner/TaskResultInterface.php

+2
Original file line numberDiff line numberDiff line change
@@ -33,5 +33,7 @@ public function getMessage(): string;
3333

3434
public function getContext(): ContextInterface;
3535

36+
public function withContext(ContextInterface $context): static;
37+
3638
public function withAppendedMessage(string $message): self;
3739
}

0 commit comments

Comments
 (0)