Skip to content
Closed
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,19 @@
### Breaking changes

- Requires utopia-php/database `^8.0` instead of `^7.0.0`. Pass a database 8 `Utopia\Database\Database` to `TimeLimit\Database`; `getLogs()` returns database 8 `Document`s. PHP `>=8.5` is unchanged from 3.1.0.
- Requires appwrite/appwrite `^32.2.0` instead of `^27.1`, the SDK generation appwrite/appwrite itself runs this package against. `TimeLimit\Appwrite\TablesDB` takes an `Appwrite\Client`, so a caller still on a 27.x client upgrades with it. The adapter's own calls are unchanged: the `TablesDB` service, `Query`, `ID`, `TablesDBIndexType` and the `Row` model it reads all keep their signatures, and the SDK's tightened requirements (PHP `>=8.5`, `psr/http-client` `^1.0`, `utopia-php/client` `^0.6`) are ones abuse already carries.
- `TimeLimit\Database::ATTRIBUTES` and `TimeLimit\Database::INDEXES` are removed. `TimeLimit\Database::attributes()` and `TimeLimit\Database::indexes()` return the same schema as `Utopia\Database\Attribute` and `Utopia\Database\Index` objects, and `setup()` creates the collection from them. The schema is unchanged, so an existing `abuse` collection needs no migration.

### Changed

- The SDK client no longer follows redirects, so an `APPWRITE_ENDPOINT` that redirects (an `http://` endpoint on a host that forces `https://`, say) now fails the call instead of being followed with the API key attached. Point `Client::setEndpoint()` at the final URL.
- abuse does not require utopia-php/query directly; the query library arrives through utopia-php/database 8.
- `Adapter::check()` and `Adapter::peek()` are declared `@phpstan-impure`, so static analysis no longer assumes repeated calls return the same `Result`.
- `minimum-stability` is `dev` with `prefer-stable: true` until utopia-php/database 8.0.0 is tagged; it returns to `stable` with the tag.

### Tests

- `DatabaseSchemaTest` covers `TimeLimit\Database` against database 8: hits counted per key and window, one row per key and window, `cleanup()` removing only earlier windows, and `setup()` running again without losing counts.
- `TablesDBTest` covers `TimeLimit\Appwrite\TablesDB::setup()` against a recording client: the table is created with its columns and indexes inline and nothing is created one by one or polled, and a table left behind by an earlier run is repaired through the per-type column endpoints with the same schema, its index types round tripping through the SDK's `TablesDBIndexType`. The same requests go out on appwrite/appwrite 27.1 and 32.2.
- The Appwrite `TablesDB` end-to-end fixture deletes only the database it created, cleans up after a failed setup, keeps ownership for a retry when cleanup fails, and reports both failures when setup and cleanup fail together (`TablesDBFixtureTest`).
- `DiscoveryTest` checks that the configured end-to-end discovery includes the backend and lifecycle cases.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"utopia-php/database": "^8.3.4",
"utopia-php/pools": "^2.0",
"utopia-php/psr7": "^0.2.1",
"appwrite/appwrite": "^27.1"
"appwrite/appwrite": "^32.2.0"
},
"require-dev": {
"phpbench/phpbench": "1.*"
Expand Down
113 changes: 113 additions & 0 deletions tests/TablesDBTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Utopia\Abuse\Adapter\TimeLimit\Appwrite\TablesDB;
use Utopia\Abuse\Result;
use Utopia\Abuse\Tests\TimeLimit\RacingTablesDBClient;
use Utopia\Abuse\Tests\TimeLimit\SetupTablesDBClient;

final class TablesDBTest extends TestCase
{
Expand Down Expand Up @@ -39,4 +40,116 @@ public function testHitBelowTheLimitReportsTheCountBeforeIt(): void
$this->assertSame(1, $result->remaining);
$this->assertSame(2, $client->count);
}

public function testSetupCreatesTheColumnsAndIndexesWithTheTable(): void
{
$client = new SetupTablesDBClient(tableExists: false);

new TablesDB('login', 2, 60, $client, 'abuse')->setup();

$creation = $this->paramsOf($client, 'POST', '/tablesdb/abuse/tables')[0];

$this->assertSame([
['key' => 'key', 'type' => 'string', 'size' => 255, 'required' => true],
['key' => 'time', 'type' => 'datetime', 'required' => true],
['key' => 'count', 'type' => 'integer', 'required' => true, 'min' => 0, 'max' => PHP_INT_MAX],
], $creation['columns']);
$this->assertSame([
['key' => 'unique1', 'type' => 'unique', 'attributes' => ['key', 'time']],
['key' => 'index2', 'type' => 'key', 'attributes' => ['time']],
], $creation['indexes']);

// Inline columns and indexes come back available, so none are created one by one or polled.
$this->assertSame([
'GET /tablesdb/abuse/tables/lock',
'POST /tablesdb',
'POST /tablesdb/abuse/tables',
'POST /tablesdb/abuse/tables',
], $this->calls($client));
}

public function testSetupRepairsATableLeftBehindByAnEarlierRun(): void
{
$client = new SetupTablesDBClient(tableExists: true);

new TablesDB('login', 2, 60, $client, 'abuse')->setup();

// Inline definitions only apply while the table is being created, so the columns and
// indexes of a table that already exists are added through their own endpoints and
// waited for.
$this->assertSame([
'GET /tablesdb/abuse/tables/lock',
'POST /tablesdb',
'POST /tablesdb/abuse/tables',
'POST /tablesdb/abuse/tables/Abuse/columns/string',
'POST /tablesdb/abuse/tables/Abuse/columns/datetime',
'POST /tablesdb/abuse/tables/Abuse/columns/integer',
'GET /tablesdb/abuse/tables/Abuse/columns',
'POST /tablesdb/abuse/tables/Abuse/indexes',
'POST /tablesdb/abuse/tables/Abuse/indexes',
'GET /tablesdb/abuse/tables/Abuse/indexes',
'POST /tablesdb/abuse/tables',
], $this->calls($client));

$this->assertSame(
['key' => 'key', 'size' => 255, 'required' => true],
$this->subset($client, '/tablesdb/abuse/tables/Abuse/columns/string', ['key', 'size', 'required']),
);
$this->assertSame(
['key' => 'time', 'required' => true],
$this->subset($client, '/tablesdb/abuse/tables/Abuse/columns/datetime', ['key', 'required']),
);
$this->assertSame(
['key' => 'count', 'required' => true, 'min' => 0, 'max' => PHP_INT_MAX],
$this->subset($client, '/tablesdb/abuse/tables/Abuse/columns/integer', ['key', 'required', 'min', 'max']),
);

// The type each index was defined with survives the round trip through the SDK's index type.
$indexes = $this->paramsOf($client, 'POST', '/tablesdb/abuse/tables/Abuse/indexes');
$this->assertSame(['unique', 'key'], \array_map(
static fn (array $params): string => $params['type'] instanceof \Stringable ? (string) $params['type'] : '',
$indexes,
));
$this->assertSame([['key', 'time'], ['time']], \array_map(
static fn (array $params): mixed => $params['columns'],
$indexes,
));
}

/**
* @return list<string>
*/
private function calls(SetupTablesDBClient $client): array
{
return \array_map(
static fn (array $request): string => $request['method'] . ' ' . $request['path'],
$client->requests,
);
}

/**
* @return list<array<string, mixed>>
*/
private function paramsOf(SetupTablesDBClient $client, string $method, string $path): array
{
return \array_values(\array_map(
static fn (array $request): array => $request['params'],
\array_filter(
$client->requests,
static fn (array $request): bool => $request['method'] === $method && $request['path'] === $path,
),
));
}

/**
* @param list<string> $keys
* @return array<string, mixed>
*/
private function subset(SetupTablesDBClient $client, string $path, array $keys): array
{
return \array_intersect_key(
$this->paramsOf($client, 'POST', $path)[0],
\array_fill_keys($keys, null),
);
}
}
132 changes: 132 additions & 0 deletions tests/TimeLimit/SetupTablesDBClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

declare(strict_types=1);

namespace Utopia\Abuse\Tests\TimeLimit;

use Appwrite\AppwriteException;
use Appwrite\Client;
use Utopia\Abuse\Adapter\TimeLimit\Appwrite\TablesDB;

/**
* Answers the requests setup() makes, so the schema it asks the SDK for can be read
* off the wire without an Appwrite backend.
*/
final class SetupTablesDBClient extends Client
{
private const string TIMESTAMP = '2026-01-01T00:00:00.000+00:00';

/** @var list<array{method: string, path: string, params: array<string, mixed>}> */
public array $requests = [];

/**
* @param bool $tableExists answer the table creation with table_already_exists, the state a
* setup that stopped halfway leaves behind
*/
public function __construct(private readonly bool $tableExists)
{
parent::__construct();
}

/**
* @param array<string, mixed> $headers
* @param array<string, mixed> $params
* @return array<string, mixed>
*/
#[\Override]
public function call(string $method, string $path = '', array $headers = [], array $params = [], ?string $responseType = null): array
{
$this->requests[] = ['method' => $method, 'path' => $path, 'params' => $params];

if ($method === self::METHOD_GET) {
return match (true) {
\str_ends_with($path, '/columns') => ['total' => 0, 'columns' => []],
\str_ends_with($path, '/indexes') => ['total' => 0, 'indexes' => []],
// The lock table is what setup() reads to decide whether it ran to completion.
default => throw new AppwriteException('Table not found', 404, 'table_not_found'),
};
}

if ($path === '/tablesdb') {
throw new AppwriteException('Database already exists', 409, 'database_already_exists');
}

if (\str_ends_with($path, '/tables')) {
if ($this->tableExists && ($params['tableId'] ?? null) === TablesDB::TABLE_ID) {
throw new AppwriteException('Table already exists', 409, 'table_already_exists');
}

return $this->table($params);
}

return \str_ends_with($path, '/indexes')
? $this->index($params)
: $this->column(\substr($path, \strrpos($path, '/') + 1), $params);
}

/**
* @param array<string, mixed> $params
* @return array<string, mixed>
*/
private function table(array $params): array
{
return [
'$id' => $this->string($params['tableId'] ?? ''),
'$createdAt' => self::TIMESTAMP,
'$updatedAt' => self::TIMESTAMP,
'$permissions' => [],
'databaseId' => $this->string($params['databaseId'] ?? ''),
'name' => $this->string($params['name'] ?? ''),
'enabled' => true,
'rowSecurity' => false,
'columns' => [],
'indexes' => [],
'bytesMax' => 0,
'bytesUsed' => 0,
];
}

/**
* @param array<string, mixed> $params
* @return array<string, mixed>
*/
private function index(array $params): array
{
return [
'$id' => $this->string($params['key'] ?? ''),
'$createdAt' => self::TIMESTAMP,
'$updatedAt' => self::TIMESTAMP,
'key' => $this->string($params['key'] ?? ''),
'type' => $this->string($params['type'] ?? ''),
'status' => 'available',
'error' => '',
'columns' => $params['columns'] ?? [],
'lengths' => [],
];
}

/**
* @param array<string, mixed> $params
* @return array<string, mixed>
*/
private function column(string $type, array $params): array
{
return [
'$createdAt' => self::TIMESTAMP,
'$updatedAt' => self::TIMESTAMP,
'key' => $this->string($params['key'] ?? ''),
'type' => $type,
'status' => 'available',
'error' => '',
'required' => $params['required'] ?? false,
'size' => $params['size'] ?? 0,
// Only the datetime column carries a format, and the other columns ignore it.
'format' => '',
];
}

private function string(mixed $value): string
{
return \is_scalar($value) || $value instanceof \Stringable ? (string) $value : '';
}
}