Skip to content
Merged
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
164 changes: 164 additions & 0 deletions Classes/Domain/DTO/FallbackChain.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
<?php

/*
* Copyright (c) 2025-2026 Netresearch DTT GmbH
* SPDX-License-Identifier: GPL-2.0-or-later
*/

declare(strict_types=1);

namespace Netresearch\NrLlm\Domain\DTO;

use JsonSerializable;

/**
* Ordered list of LlmConfiguration identifiers to try when the primary
* configuration fails with a retryable error.
*
* Fallback is shallow: a fallback configuration's own chain is ignored
* to prevent recursion and cycles. Identifiers are normalised (trimmed
* and lowercased) to match how `tx_nrllm_configuration.identifier`
* stores them (TCA `eval=trim,alphanum_x,lower,unique`); withLink(),
* without() and contains() all apply the same normalisation so a
* manually-edited JSON payload with stray whitespace or capitals still
* resolves to the right row. Normalised duplicates are dropped on entry
* via fromArray()/fromJson() and silently skipped by withLink().
*
* The constructor itself does NOT normalise — it trusts already-sanitised
* input (see the sanitize() docblock).
*/
final readonly class FallbackChain implements JsonSerializable
{
/**
* @param list<string> $configurationIdentifiers Ordered list of LlmConfiguration identifiers (should be pre-normalised)
*/
public function __construct(
public array $configurationIdentifiers = [],
) {}

/**
* @param array{configurationIdentifiers?: mixed} $data
*/
public static function fromArray(array $data): self
{
$identifiers = $data['configurationIdentifiers'] ?? [];
if (!is_array($identifiers)) {
return new self();
}
return new self(self::sanitize($identifiers));
}

public static function fromJson(string $json): self
{
if ($json === '') {
return new self();

Check warning on line 54 in Classes/Domain/DTO/FallbackChain.php

View workflow job for this annotation

GitHub Actions / fuzz / Mutation Testing (Infection)

Escaped Mutant for Mutator "ReturnRemoval": @@ @@ public static function fromJson(string $json): self { if ($json === '') { - return new self(); + } $data = json_decode($json, true); if (!is_array($data)) {
}
$data = json_decode($json, true);
if (!is_array($data)) {
return new self();
}
/** @var array{configurationIdentifiers?: mixed} $data */
return self::fromArray($data);
}

/**
* @return array{configurationIdentifiers: list<string>}
*/
public function toArray(): array
{
return [
'configurationIdentifiers' => $this->configurationIdentifiers,
];
}

public function toJson(): string
{
return json_encode($this->toArray(), JSON_THROW_ON_ERROR);
}

/**
* @return array{configurationIdentifiers: list<string>}
*/
public function jsonSerialize(): array
{
return $this->toArray();
}

public function isEmpty(): bool
{
return $this->configurationIdentifiers === [];
}

public function count(): int
{
return count($this->configurationIdentifiers);
}

public function contains(string $identifier): bool
{
return in_array(self::normalise($identifier), $this->configurationIdentifiers, true);
}
Comment thread
CybotTM marked this conversation as resolved.

/**
* Return a new chain with the given identifier appended, deduplicated.
* Empty / whitespace-only identifiers are silently ignored.
*/
public function withLink(string $identifier): self
{
$normalised = self::normalise($identifier);
if ($normalised === '' || $this->contains($normalised)) {
return $this;
}
return new self([...$this->configurationIdentifiers, $normalised]);
}
Comment thread
CybotTM marked this conversation as resolved.

/**
* Return a new chain without the given identifier.
* Useful for excluding the primary configuration before walking fallbacks.
*/
public function without(string $identifier): self
{
$normalised = self::normalise($identifier);
if ($normalised === '' || !$this->contains($normalised)) {
return $this;
}
$filtered = array_values(array_filter(
$this->configurationIdentifiers,
static fn(string $link): bool => $link !== $normalised,
));
return new self($filtered);
}
Comment thread
CybotTM marked this conversation as resolved.

/**
* Normalise input: drop non-strings, drop empty strings, trim, lowercase,
* drop duplicates, reindex as list. Matches the sanitisation TCA already
* applies to `tx_nrllm_configuration.identifier` so round-trips through
* hand-written JSON do not accidentally miss a row.
*
* @param array<mixed> $identifiers
*
* @return list<string>
*/
private static function sanitize(array $identifiers): array
{
$seen = [];
$out = [];
foreach ($identifiers as $identifier) {
if (!is_string($identifier)) {
continue;
}
$normalised = self::normalise($identifier);
if ($normalised === '' || isset($seen[$normalised])) {
continue;
}
$seen[$normalised] = true;
$out[] = $normalised;
}
return $out;
Comment thread
CybotTM marked this conversation as resolved.
}

private static function normalise(string $identifier): string
{
return strtolower(trim($identifier));
}
}
49 changes: 49 additions & 0 deletions Classes/Domain/Model/LlmConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace Netresearch\NrLlm\Domain\Model;

use Netresearch\NrLlm\Domain\DTO\FallbackChain;
use Netresearch\NrLlm\Domain\DTO\ModelSelectionCriteria;
use Netresearch\NrLlm\Domain\Enum\ModelSelectionMode;
use Netresearch\NrLlm\Service\Option\ChatOptions;
Expand Down Expand Up @@ -62,6 +63,12 @@ class LlmConfiguration extends AbstractEntity
protected int $maxRequestsPerDay = 0;
protected int $maxTokensPerDay = 0;
protected float $maxCostPerDay = 0.0;
/**
* JSON-encoded fallback chain (ordered list of LlmConfiguration identifiers).
* Populated automatically from the `fallback_chain` column by Extbase.
*/
protected string $fallbackChain = '';

protected bool $isActive = true;
protected bool $isDefault = false;
protected int $allowedGroups = 0;
Expand Down Expand Up @@ -326,6 +333,32 @@ public function getCrdate(): int
return $this->crdate;
}

/**
* Get the raw JSON fallback chain (as stored in the database).
*
* Extbase reads this getter during property mapping.
*/
public function getFallbackChain(): string
{
return $this->fallbackChain;
}

/**
* Get fallback chain as typed DTO.
*
* Returns an empty chain when nothing is configured, so callers never
* have to null-check before calling isEmpty() / configurationIdentifiers.
*/
public function getFallbackChainDTO(): FallbackChain
{
return FallbackChain::fromJson($this->fallbackChain);
}

public function hasFallbackChain(): bool
{
return !$this->getFallbackChainDTO()->isEmpty();
}

// ========================================
// Setters
// ========================================
Expand Down Expand Up @@ -466,6 +499,22 @@ public function setAllowedGroups(int $allowedGroups): void
$this->allowedGroups = $allowedGroups;
}

/**
* Set fallback chain from raw JSON (used by Extbase when hydrating from DB).
*/
public function setFallbackChain(string $fallbackChain): void
{
$this->fallbackChain = $fallbackChain;
}

/**
* Set fallback chain from typed DTO.
*/
public function setFallbackChainDTO(FallbackChain $fallbackChain): void
{
$this->fallbackChain = $fallbackChain->isEmpty() ? '' : $fallbackChain->toJson();
}

/**
* @param ObjectStorage<AbstractEntity>|null $beGroups
*/
Expand Down
71 changes: 71 additions & 0 deletions Classes/Provider/Exception/FallbackChainExhaustedException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

/*
* Copyright (c) 2025-2026 Netresearch DTT GmbH
* SPDX-License-Identifier: GPL-2.0-or-later
*/

declare(strict_types=1);

namespace Netresearch\NrLlm\Provider\Exception;

use Throwable;

/**
* Thrown when every configuration in a fallback chain (primary + fallbacks)
* failed with a retryable error. Carries per-attempt errors so callers can
* reason about the full failure sequence.
*/
final class FallbackChainExhaustedException extends ProviderException
{
/**
* @param list<array{configuration: string, error: Throwable}> $attemptErrors
*/
public function __construct(
string $message,
int $code,
private readonly array $attemptErrors,
?Throwable $previous = null,
) {
parent::__construct($message, $code, $previous);
}

/**
* @param list<array{configuration: string, error: Throwable}> $attempts
*/
public static function fromAttempts(array $attempts): self
{
$configurations = array_map(
static fn(array $attempt): string => $attempt['configuration'],
$attempts,
);
$last = $attempts === [] ? null : $attempts[array_key_last($attempts)]['error'];

$message = sprintf(
'All %d configuration(s) in the fallback chain failed: %s',
count($attempts),
implode(' -> ', $configurations),
);

return new self($message, 1745712001, $attempts, $last);
}

/**
* @return list<array{configuration: string, error: Throwable}>
*/
public function getAttemptErrors(): array
{
return $this->attemptErrors;
}

/**
* @return list<string>
*/
public function getAttemptedConfigurations(): array
{
return array_map(
static fn(array $attempt): string => $attempt['configuration'],
$this->attemptErrors,
);
}
}
Loading
Loading