1
0

JobsEndpointsTest.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Tests\Integration\Internal;
  4. use App\Tests\Integration\Support\AppTestCase;
  5. /**
  6. * End-to-end coverage for `/internal/jobs/*`. The AppTestCase boots a Slim
  7. * app whose ServerRequestFactory does NOT populate REMOTE_ADDR — so we
  8. * inject one explicitly via the request() helper override below to satisfy
  9. * InternalNetworkMiddleware.
  10. */
  11. final class JobsEndpointsTest extends AppTestCase
  12. {
  13. private const TOKEN = 'test-internal-token';
  14. protected function setUp(): void
  15. {
  16. // Ensure the container picks up our internal token.
  17. putenv('INTERNAL_JOB_TOKEN=' . self::TOKEN);
  18. $_ENV['INTERNAL_JOB_TOKEN'] = self::TOKEN;
  19. $_SERVER['INTERNAL_JOB_TOKEN'] = self::TOKEN;
  20. parent::setUp();
  21. // Override the internal-token middleware in the container so the
  22. // running Slim app validates against our test token. The base
  23. // AppTestCase wires a settings bundle that doesn't include the
  24. // token, so we patch the InternalTokenMiddleware factory directly.
  25. if (method_exists($this->container, 'set')) {
  26. /** @var \DI\Container $container */
  27. $container = $this->container;
  28. $container->set(
  29. \App\Infrastructure\Http\Middleware\InternalTokenMiddleware::class,
  30. new \App\Infrastructure\Http\Middleware\InternalTokenMiddleware(
  31. new \Slim\Psr7\Factory\ResponseFactory(),
  32. self::TOKEN,
  33. ),
  34. );
  35. }
  36. // Rebuild the app so it picks up the patched middleware.
  37. $this->app = \App\App\AppFactory::build($this->container);
  38. }
  39. public function testTickRequiresToken(): void
  40. {
  41. $resp = $this->internalRequest('POST', '/internal/jobs/tick', headers: []);
  42. self::assertSame(401, $resp->getStatusCode());
  43. }
  44. public function testTickRejectsWrongToken(): void
  45. {
  46. $resp = $this->internalRequest(
  47. 'POST',
  48. '/internal/jobs/tick',
  49. headers: ['Authorization' => 'Bearer wrong'],
  50. );
  51. self::assertSame(401, $resp->getStatusCode());
  52. }
  53. public function testExternalSourceReturns404OpaquePerSpec(): void
  54. {
  55. $resp = $this->internalRequest(
  56. 'POST',
  57. '/internal/jobs/tick',
  58. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  59. remoteAddr: '8.8.8.8',
  60. );
  61. self::assertSame(404, $resp->getStatusCode());
  62. }
  63. public function testTickSuccessProducesEnvelope(): void
  64. {
  65. $resp = $this->internalRequest(
  66. 'POST',
  67. '/internal/jobs/tick',
  68. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  69. );
  70. self::assertSame(200, $resp->getStatusCode());
  71. $body = $this->decode($resp);
  72. self::assertSame('tick', $body['job']);
  73. self::assertSame('success', $body['status']);
  74. self::assertArrayHasKey('run_id', $body);
  75. self::assertArrayHasKey('duration_ms', $body);
  76. }
  77. public function testRecomputeSucceedsWithEmptyTables(): void
  78. {
  79. $resp = $this->internalRequest(
  80. 'POST',
  81. '/internal/jobs/recompute-scores',
  82. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  83. );
  84. self::assertSame(200, $resp->getStatusCode());
  85. $body = $this->decode($resp);
  86. self::assertSame('recompute-scores', $body['job']);
  87. self::assertSame('success', $body['status']);
  88. }
  89. public function testConcurrentRecomputeProducesOneSuccessOneSkipped(): void
  90. {
  91. // Pre-acquire the lock to simulate "another worker is busy". The
  92. // second HTTP call must come back 409 with skipped_locked.
  93. $now = (new \DateTimeImmutable('now', new \DateTimeZone('UTC')));
  94. $lockSql = 'INSERT INTO job_locks (job_name, acquired_by, acquired_at, expires_at) '
  95. . 'VALUES (:job, :owner, :acquired, :expires)';
  96. $this->db->executeStatement($lockSql, [
  97. 'job' => 'recompute-scores',
  98. 'owner' => 'OTHER',
  99. 'acquired' => $now->format('Y-m-d H:i:s'),
  100. 'expires' => $now->modify('+5 minutes')->format('Y-m-d H:i:s'),
  101. ]);
  102. $resp = $this->internalRequest(
  103. 'POST',
  104. '/internal/jobs/recompute-scores',
  105. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  106. body: '{"full": true}',
  107. );
  108. self::assertSame(409, $resp->getStatusCode());
  109. $body = $this->decode($resp);
  110. self::assertSame('skipped_locked', $body['status']);
  111. }
  112. public function testRefreshGeoipReturns412(): void
  113. {
  114. $resp = $this->internalRequest(
  115. 'POST',
  116. '/internal/jobs/refresh-geoip',
  117. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  118. );
  119. self::assertSame(412, $resp->getStatusCode());
  120. $body = $this->decode($resp);
  121. self::assertSame('not_implemented', $body['error']);
  122. }
  123. public function testStatusListsAllRegisteredJobs(): void
  124. {
  125. $resp = $this->internalRequest(
  126. 'GET',
  127. '/internal/jobs/status',
  128. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  129. );
  130. self::assertSame(200, $resp->getStatusCode());
  131. $body = $this->decode($resp);
  132. self::assertArrayHasKey('jobs', $body);
  133. self::assertArrayHasKey('recompute-scores', $body['jobs']);
  134. self::assertArrayHasKey('cleanup-audit', $body['jobs']);
  135. self::assertArrayHasKey('enrich-pending', $body['jobs']);
  136. self::assertArrayHasKey('tick', $body['jobs']);
  137. }
  138. public function testCleanupAuditSucceedsAndRecordsRun(): void
  139. {
  140. $resp = $this->internalRequest(
  141. 'POST',
  142. '/internal/jobs/cleanup-audit',
  143. headers: ['Authorization' => 'Bearer ' . self::TOKEN],
  144. );
  145. self::assertSame(200, $resp->getStatusCode());
  146. $body = $this->decode($resp);
  147. self::assertSame('cleanup-audit', $body['job']);
  148. self::assertSame('success', $body['status']);
  149. $row = $this->db->fetchAssociative(
  150. "SELECT triggered_by, status FROM job_runs WHERE job_name = 'cleanup-audit'"
  151. );
  152. self::assertNotFalse($row);
  153. self::assertSame('schedule', $row['triggered_by']);
  154. self::assertSame('success', $row['status']);
  155. }
  156. /**
  157. * @param array<string, string> $headers
  158. */
  159. private function internalRequest(
  160. string $method,
  161. string $path,
  162. array $headers = [],
  163. ?string $body = null,
  164. string $remoteAddr = '127.0.0.1',
  165. ): \Psr\Http\Message\ResponseInterface {
  166. $factory = new \Slim\Psr7\Factory\ServerRequestFactory();
  167. $request = $factory->createServerRequest($method, $path, ['REMOTE_ADDR' => $remoteAddr]);
  168. foreach ($headers as $name => $value) {
  169. $request = $request->withHeader($name, $value);
  170. }
  171. if ($body !== null) {
  172. $stream = (new \Slim\Psr7\Factory\StreamFactory())->createStream($body);
  173. $request = $request->withBody($stream);
  174. $request = $request->withHeader('Content-Type', 'application/json');
  175. }
  176. return $this->app->handle($request);
  177. }
  178. }