Skip to content
Open
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
14 changes: 9 additions & 5 deletions database/migrations/2025_10_15_000000_create_task_tables.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
/**
* Create the queue tables while retaining workers and tasks already stored by Evolution.
* Permissions and groups are handled by a separate migration.
*
* Indexed strings are sized so every key fits the MyISAM limit of 1000 bytes in utf8mb4 (4 bytes a
* character): identifier 128, scope 128, action 96 (identifier + action: 896 bytes), priority 16.
* The models refuse longer values (INDEXED_LENGTHS).
*/
return new class extends Migration {
/** Create each missing table independently so a partial installation can be repaired. */
Expand Down Expand Up @@ -45,8 +49,8 @@ private function createWorkersTable(): void
$table->comment('Workers for sTask');
$table->id();
$table->uuid('uuid')->nullable()->unique();
$table->string('identifier')->unique();
$table->string('scope')->default('');
$table->string('identifier', 128)->unique();
$table->string('scope', 128)->default('');
$table->string('class');
$table->boolean('active')->default(false);
$table->unsignedInteger('position')->default(0);
Expand All @@ -71,8 +75,8 @@ private function createTasksTable(): void
Schema::create('s_tasks', function (Blueprint $table) {
$table->comment('Async tasks for sTask');
$table->bigIncrements('id');
$table->string('identifier');
$table->string('action');
$table->string('identifier', 128);
$table->string('action', 96);
$table->unsignedSmallInteger('status')->default(10);
$table->text('message')->nullable();
$table->unsignedInteger('started_by')->nullable();
Expand All @@ -82,7 +86,7 @@ private function createTasksTable(): void
$table->timestamp('finished_at')->nullable();
$table->integer('attempts')->default(0);
$table->integer('max_attempts')->default(3);
$table->string('priority')->default('normal');
$table->string('priority', 16)->default('normal');
$table->integer('progress')->default(0);
$table->timestamps();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ public function up(): void
$table->comment('Live state and diagnostic cursor for sTask supervisors');
$table->bigIncrements('id');
$table->unsignedBigInteger('worker_id');
$table->string('identifier');
// 128: the key fits the MyISAM limit of 1000 bytes in utf8mb4, as s_workers.identifier
$table->string('identifier', 128);
$table->string('supervisor_key');
$table->char('key_hash', 64)->unique();
$table->string('state', 24)->default('stopped');
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

/**
* Restore the indexes a MyISAM site never got.
*
* Before 2.3.3 the indexed strings were VARCHAR(255): 1020 bytes in utf8mb4, over the MyISAM key limit
* of 1000 (and identifier + action over it in utf8mb3 too). The create then stopped after the table
* existed, and the next migrate skipped the existing table, so workers and tasks were stored without
* their keys. This shortens those columns to the lengths the create migrations use now (only where no
* stored value is longer) and adds every missing index. Tables with all their indexes are left alone,
* so the 255-character columns of sites that never failed stay as they are.
*
* @since 2.3.3
*/
return new class extends Migration {
/** Column => characters and how the create migrations define it. */
private const COLUMNS = [
's_workers' => ['identifier' => [128, null], 'scope' => [128, '']],
's_tasks' => ['identifier' => [128, null], 'action' => [96, null], 'priority' => [16, 'normal']],
's_supervisor_states' => ['identifier' => [128, null]],
];

/** Indexes of the create migrations: [unique?, columns]. */
private const INDEXES = [
's_workers' => [
[true, ['uuid']], [true, ['identifier']], [false, ['identifier']],
[false, ['scope']], [false, ['active']], [false, ['position']],
],
's_tasks' => [
[false, ['identifier', 'action']], [false, ['status']], [false, ['started_by']],
[false, ['start_at']], [false, ['created_at']], [false, ['priority']],
],
's_supervisor_states' => [
[true, ['key_hash']], [false, ['worker_id']], [false, ['identifier']],
[false, ['state']], [false, ['last_seen_at']],
],
];

public function up(): void
{
if (!in_array(DB::connection()->getDriverName(), ['mysql', 'mariadb'], true)) {
return;
}

foreach (self::INDEXES as $table => $indexes) {
if (Schema::hasTable($table)) {
$this->repair($table, $indexes);
}
}
}

public function down(): void
{
// the indexes belong to the tables; nothing to undo
}

/**
* @param array<int, array{0: bool, 1: list<string>}> $indexes
*/
private function repair(string $table, array $indexes): void
{
$missing = array_values(array_filter($indexes, fn (array $index): bool => !$this->hasIndex($table, $index[0], $index[1])));
if ($missing === []) {
return;
}

$lengths = [];
$collations = [];
foreach (Schema::getColumns($table) as $column) {
if (preg_match('/^varchar\((\d+)\)/i', (string) ($column['type'] ?? ''), $match)) {
$lengths[$column['name']] = (int) $match[1];
$collations[$column['name']] = $column['collation'] ?? null;
}
}

$tooLong = [];
$shorten = [];
foreach (self::COLUMNS[$table] as $name => [$length, $default]) {
if (($lengths[$name] ?? 0) <= $length) {
continue;
}
$longest = (int) DB::table($table)->max(DB::raw('CHAR_LENGTH(' . DB::getQueryGrammar()->wrap($name) . ')'));
if ($longest > $length) {
$tooLong[] = $name;
} else {
$shorten[$name] = [$length, $default];
}
}

if ($shorten !== []) {
Schema::table($table, function (Blueprint $blueprint) use ($shorten, $collations): void {
foreach ($shorten as $name => [$length, $default]) {
$column = $blueprint->string($name, $length);
// MODIFY without a collation would move the column to the table's default
if (!empty($collations[$name])) {
$column->collation($collations[$name]);
}
if ($default !== null) {
$column->default($default);
}
$column->change();
}
});
}

$add = [];
foreach ($missing as [$unique, $columns]) {
if (array_intersect($columns, $tooLong) !== []) {
$this->report("{$table}: no index on " . implode(', ', $columns) . ': a stored value is longer than the key allows.');
continue;
}
if ($unique && DB::table($table)->select($columns)->groupBy($columns)->havingRaw('COUNT(*) > 1')->exists()) {
$this->report("{$table}: no unique key on " . implode(', ', $columns) . ': rows share a value.');
continue;
}
$add[] = [$unique, $columns];
}

if ($add !== []) {
Schema::table($table, function (Blueprint $blueprint) use ($add): void {
foreach ($add as [$unique, $columns]) {
$unique ? $blueprint->unique($columns) : $blueprint->index($columns);
}
});
}
}

/**
* Whether an index covers exactly these columns, unique where the create made it unique. s_workers
* has both a unique key and a plain index on identifier, so a unique key stands in for a plain index
* only where the create made no unique key on the same columns.
*
* @param list<string> $columns
*/
private function hasIndex(string $table, bool $unique, array $columns): bool
{
$uniqueMayServe = !in_array([true, $columns], self::INDEXES[$table], true);
foreach (Schema::getIndexes($table) as $index) {
if ($index['primary'] || $index['columns'] !== $columns) {
continue;
}
if ($unique ? $index['unique'] : (!$index['unique'] || $uniqueMayServe)) {
return true;
}
}

return false;
}

private function report(string $message): void
{
try {
Log::warning('sTask migration: ' . $message);
} catch (\Throwable $exception) {
// the log is not bound in every context a migration runs in
}
}
};
4 changes: 2 additions & 2 deletions src/Controllers/sTaskController.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ public function create(Request $request)
$this->authorizeStask();

$request->validate([
'identifier' => 'required|string',
'action' => 'required|string',
'identifier' => 'required|string|max:' . sTaskModel::INDEXED_LENGTHS['identifier'],
'action' => 'required|string|max:' . sTaskModel::INDEXED_LENGTHS['action'],
'data' => 'array',
'priority' => 'in:low,normal,high',
]);
Expand Down
37 changes: 37 additions & 0 deletions src/Models/Concerns/FitsIndexedColumns.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php namespace Seiger\sTask\Models\Concerns;

use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;

/**
* Refuses to save a value longer than its indexed column.
*
* The indexed string columns are sized so their keys fit the MyISAM limit of 1000 bytes in utf8mb4
* (see the create migrations). A longer value would be cut silently by a non-strict MySQL session,
* and the worker or task it names would no longer be found. Only values being written are checked, so a
* row stored before the limit (a 255-character column left as it was) can still be updated.
*
* The model lists its columns in INDEXED_LENGTHS (column => characters).
*
* @since 2.3.3
*/
trait FitsIndexedColumns
{
protected static function bootFitsIndexedColumns(): void
{
static::saving(static function (Model $model): void {
foreach (static::INDEXED_LENGTHS as $column => $length) {
$value = $model->getAttribute($column);
if ($model->isDirty($column) && is_string($value) && mb_strlen($value) > $length) {
throw new InvalidArgumentException(sprintf(
'%s.%s holds at most %d characters, %d given.',
$model->getTable(),
$column,
$length,
mb_strlen($value)
));
}
}
});
}
}
6 changes: 6 additions & 0 deletions src/Models/sSupervisorState.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Seiger\sTask\Models\Concerns\FitsIndexedColumns;

/**
* Persisted live state and diagnostic deduplication cursor for one supervisor.
Expand All @@ -11,6 +12,11 @@
*/
class sSupervisorState extends Model
{
use FitsIndexedColumns;

/** Characters of the indexed string columns (create migration: keys within the MyISAM limit). */
public const INDEXED_LENGTHS = ['identifier' => sWorker::INDEXED_LENGTHS['identifier']];

/** @var string */
protected $table = 's_supervisor_states';

Expand Down
6 changes: 6 additions & 0 deletions src/Models/sTaskModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use EvolutionCMS\Models\User;
use Seiger\sTask\Models\Concerns\FitsIndexedColumns;

/**
* Class sTaskModel
Expand All @@ -16,6 +17,11 @@
*/
class sTaskModel extends Model
{
use FitsIndexedColumns;

/** Characters of the indexed string columns (create migration: keys within the MyISAM limit). */
public const INDEXED_LENGTHS = ['identifier' => sWorker::INDEXED_LENGTHS['identifier'], 'action' => 96, 'priority' => 16];

// Task status constants
public const TASK_STATUS_QUEUED = 10; // Task is queued for execution
public const TASK_STATUS_PREPARING = 30; // Task is being prepared
Expand Down
6 changes: 6 additions & 0 deletions src/Models/sWorker.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Seiger\sTask\Models\Concerns\FitsIndexedColumns;

/**
* Class sWorker
Expand All @@ -14,6 +15,11 @@
*/
class sWorker extends Model
{
use FitsIndexedColumns;

/** Characters of the indexed string columns (create migration: keys within the MyISAM limit). */
public const INDEXED_LENGTHS = ['identifier' => 128, 'scope' => 128];

protected $table = 's_workers';

protected $fillable = [
Expand Down
12 changes: 12 additions & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,15 @@ The large fixture stores 120 tasks with approximately 1 MiB of combined

Omit `--large` for the small functional fixture. Duration/memory metrics that were
already placeholders remain placeholders; their zero values are not measured usage.

## MyISAM key limit

`tests/myisam.php` (also run by `tests/run.php`) checks that the indexed string columns of the create
migrations match the models' `INDEXED_LENGTHS`, that every key fits the MyISAM limit of 1000 bytes in
utf8mb4, and that the models refuse longer values. With a MySQL or MariaDB server it also installs on
MyISAM utf8mb4, MyISAM utf8mb3 and InnoDB, and repairs tables a failed MyISAM create left without keys;
each run uses a database of its own and drops it:

```sh
STASK_TEST_MYSQL=user:password@host:port STASK_AUTOLOAD=/path/to/core/vendor/autoload.php php tests/myisam.php
```
14 changes: 7 additions & 7 deletions tests/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@ function app($abstract = null, array $parameters = [])

$loader = require $autoload;
$loader->addPsr4('Seiger\\sTask\\', dirname(__DIR__) . '/src/', true);
foreach ($loader->getClassMap() as $class => $file) {
if (str_starts_with($class, 'Seiger\\sTask\\')) {
$localFile = dirname(__DIR__) . '/src/'
. str_replace('\\', '/', substr($class, strlen('Seiger\\sTask\\'))) . '.php';
if (is_file($localFile)) {
$loader->addClassMap([$class => $localFile]);
}
// Every class of this checkout, including ones the site's (authoritative) class map does not know yet.
$sourceRoot = dirname(__DIR__) . '/src/';
$sources = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sourceRoot, FilesystemIterator::SKIP_DOTS));
foreach ($sources as $source) {
if ($source->getExtension() === 'php') {
$relative = substr(str_replace('\\', '/', $source->getPathname()), strlen(str_replace('\\', '/', $sourceRoot)), -4);
$loader->addClassMap(['Seiger\\sTask\\' . str_replace('/', '\\', $relative) => $source->getPathname()]);
}
}
if (realpath((new ReflectionClass(\Seiger\sTask\Services\SupervisorService::class))->getFileName())
Expand Down
Loading