From 904cc77754207633faad92765b0ef12c70a6c745 Mon Sep 17 00:00:00 2001 From: Felipe Hertzer Date: Fri, 6 Nov 2026 14:47:58 +1100 Subject: [PATCH 1/2] send the ssm batches in parallel with more than 10 `bref-ssm:` variables the loader call `getParameters` once per 10 names, but it read each result before send the next batch, so the batches go one after the other and the cold start wait for every round trip. async-aws send the request when the result is created, so now all the batches are created first and read after. async-aws also throw a failure nobody read when the result is destructed, so every result is read even after one fail, and the first error is thrown after (same message for the 400 as before). --- src/Secrets.php | 42 ++++++++++++++++++----------- tests/SecretsTest.php | 62 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 15 deletions(-) diff --git a/src/Secrets.php b/src/Secrets.php index 91cd76c..d7ee270 100644 --- a/src/Secrets.php +++ b/src/Secrets.php @@ -101,28 +101,40 @@ private static function retrieveParametersFromSsm(?SsmClient $ssmClient, array $ $parameters = []; $parametersNotFound = []; - // The API only accepts up to 10 parameters at a time, so we batch the calls + // The API only accepts up to 10 parameters at a time, so we batch the calls. + // async-aws sends a request as soon as it is created: create every batch before reading any, + // so the batches run in parallel instead of one after the other. + $results = []; foreach (array_chunk($ssmNames, 10) as $batchOfSsmNames) { + $results[] = $ssm->getParameters([ + 'Names' => $batchOfSsmNames, + 'WithDecryption' => true, + ]); + } + + // Every result is read, even after one failed: async-aws throws a failure nobody read when the result is destructed + $failure = null; + foreach ($results as $result) { try { - $result = $ssm->getParameters([ - 'Names' => $batchOfSsmNames, - 'WithDecryption' => true, - ]); foreach ($result->getParameters() as $parameter) { $parameters[$parameter->getName()] = $parameter->getValue(); } + $parametersNotFound = array_merge($parametersNotFound, $result->getInvalidParameters()); } catch (RuntimeException $e) { - if ($e->getCode() === 400) { - // Extra descriptive error message for the most common error - throw new RuntimeException( - "Bref was not able to resolve secrets contained in environment variables from SSM because of a permissions issue with the SSM API. Did you add IAM permissions in serverless.yml to allow Lambda to access SSM? (docs: https://bref.sh/docs/environment/variables.html#at-deployment-time).\nFull exception message: {$e->getMessage()}", - $e->getCode(), - $e, - ); - } - throw $e; + $failure ??= $e; + } + } + + if ($failure !== null) { + if ($failure->getCode() === 400) { + // Extra descriptive error message for the most common error + throw new RuntimeException( + "Bref was not able to resolve secrets contained in environment variables from SSM because of a permissions issue with the SSM API. Did you add IAM permissions in serverless.yml to allow Lambda to access SSM? (docs: https://bref.sh/docs/environment/variables.html#at-deployment-time).\nFull exception message: {$failure->getMessage()}", + $failure->getCode(), + $failure, + ); } - $parametersNotFound = array_merge($parametersNotFound, $result->getInvalidParameters()); + throw $failure; } if (count($parametersNotFound) > 0) { diff --git a/tests/SecretsTest.php b/tests/SecretsTest.php index 9c85a10..039dc34 100644 --- a/tests/SecretsTest.php +++ b/tests/SecretsTest.php @@ -8,6 +8,8 @@ use AsyncAws\Ssm\ValueObject\Parameter; use Bref\Secrets\Secrets; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpClient\MockHttpClient; +use Symfony\Component\HttpClient\Response\MockResponse; class SecretsTest extends TestCase { @@ -103,6 +105,66 @@ public function test throws a clear error message on missing permissions putenv('SOME_VARIABLE'); } + public function test sends the batches of parameters in parallel(): void + { + // 11 parameters: two batches, as the API takes up to 10 at a time + $names = []; + for ($i = 1; $i <= 11; $i++) { + $names[] = "/some/parameter-$i"; + putenv("VAR_$i=bref-ssm:/some/parameter-$i"); + } + + $events = []; + $httpClient = new MockHttpClient(function (string $method, string $url, array $options) use (&$events): MockResponse { + $batch = json_decode($options['body'], true)['Names']; + $events[] = 'request'; + $body = (function () use (&$events, $batch) { + $events[] = 'read'; + yield json_encode([ + 'Parameters' => array_map(fn (string $name) => ['Name' => $name, 'Value' => "value of $name"], $batch), + 'InvalidParameters' => [], + ]); + })(); + + return new MockResponse($body, ['http_code' => 200, 'response_headers' => ['content-type' => 'application/x-amz-json-1.1']]); + }); + $ssmClient = new SsmClient(['region' => 'us-east-1', 'accessKeyId' => 'key', 'accessKeySecret' => 'secret'], null, $httpClient); + + Secrets::loadSecretEnvironmentVariables($ssmClient); + + // Both requests are sent before either response is read + $this->assertSame(['request', 'request', 'read', 'read'], $events); + foreach ($names as $i => $name) { + $this->assertSame("value of $name", getenv('VAR_' . ($i + 1))); + putenv('VAR_' . ($i + 1)); + } + } + + public function test throws a clear error message when every batch fails(): void + { + for ($i = 1; $i <= 11; $i++) { + putenv("VAR_$i=bref-ssm:/app/test-$i"); + } + + $ssmClient = $this->getMockBuilder(SsmClient::class) + ->disableOriginalConstructor() + ->getMock(); + // Both batches are sent, and both fail + $ssmClient->expects($this->exactly(2)) + ->method('getParameters') + ->willReturnCallback(fn () => ResultMockFactory::createFailing(GetParametersResult::class, 400, 'User: arn:aws:sts::123456:assumed-role/app-dev-us-east-1-lambdaRole/app-dev-hello is not authorized to perform: ssm:GetParameters')); + + $expected = preg_quote('Bref was not able to resolve secrets contained in environment variables from SSM because of a permissions issue with the SSM API.', '/'); + $this->expectExceptionMessageMatches("/^$expected/"); + try { + Secrets::loadSecretEnvironmentVariables($ssmClient); + } finally { + for ($i = 1; $i <= 11; $i++) { + putenv("VAR_$i"); + } + } + } + /** * @param array $resultParameters */ From 978f95cdef9226f4be5fa958cf4ec7110ab78996 Mon Sep 17 00:00:00 2001 From: Felipe Hertzer Date: Tue, 10 Nov 2026 11:03:04 +1100 Subject: [PATCH 2/2] type the test's result params for phpstan --- tests/SecretsTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/SecretsTest.php b/tests/SecretsTest.php index 039dc34..a09816a 100644 --- a/tests/SecretsTest.php +++ b/tests/SecretsTest.php @@ -13,6 +13,7 @@ class SecretsTest extends TestCase { + /** @var array{Name: string, Value: string} */ private array $resultParams = [ 'Name' => '/some/parameter', 'Value' => 'foobar',