diff --git a/.github/workflows/native-platforms.yml b/.github/workflows/native-platforms.yml index b38dacf16..315bcba4e 100644 --- a/.github/workflows/native-platforms.yml +++ b/.github/workflows/native-platforms.yml @@ -55,20 +55,20 @@ jobs: PLATFORM: ${{ matrix.platform }} run: | $server = Join-Path $PWD 'build/native-software/server.jar' - $args = @('--console=plain', "-PnativeJavaExecutable=$env:SERVER_JAVA") + $gradleArgs = @('--console=plain', "-PnativeJavaExecutable=$env:SERVER_JAVA") if ($env:PLATFORM -in @('paper', 'folia')) { $eula = Join-Path $PWD 'build/native-software/eula.txt' - $args += @(':modules:updates:verifyNativeBukkitUpdates', "-PbukkitPlatform=$env:PLATFORM", "-PpaperServerJar=$server", "-PpaperEulaFile=$eula") + $gradleArgs += @(':modules:updates:verifyNativeBukkitUpdates', "-PbukkitPlatform=$env:PLATFORM", "-PpaperServerJar=$server", "-PpaperEulaFile=$eula") } else { - $args += @(':modules:updates:verifyNativeProxyUpdates', "-PnativePlatform=$env:PLATFORM", "-P$($env:PLATFORM)ServerJar=$server") + $gradleArgs += @(':modules:updates:verifyNativeProxyUpdates', "-PnativePlatform=$env:PLATFORM", "-P$($env:PLATFORM)ServerJar=$server") } - & ./gradlew @args + & ./gradlew @gradleArgs if ($LASTEXITCODE -ne 0) { throw 'Native platform acceptance failed' } - uses: actions/upload-artifact@v4 if: always() with: name: native-${{ matrix.platform }}-java${{ inputs.java }} path: | - modules/core/build/reports/tests/verifyNative* + modules/updates/build/reports/tests/verifyNative* build/update-catalog-native/**/*.log if-no-files-found: ignore diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cf60eea03..9617d05be 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -94,6 +94,9 @@ jobs: - name: Build and verify run: .\gradlew.bat clean check :distribution:build --console=plain + - name: Check binary API compatibility + run: .\gradlew.bat apiCheck --console=plain + - name: Verify release tooling shell: pwsh run: ./tools/release/check-release-tools.tests.ps1 @@ -115,7 +118,7 @@ jobs: git commit -m "release: $env:RELEASE_VERSION" if ($LASTEXITCODE -ne 0) { throw 'Release commit failed' } } - # A re-run after a partial failure may reuse the tag only if it already points at this commit. + # Повторный запуск после сбоя может взять существующий тег, только если он указывает на этот коммит. $existingTag = git rev-parse -q --verify "refs/tags/v$env:RELEASE_VERSION^{commit}" if ($LASTEXITCODE -eq 0) { if ($existingTag -ne (git rev-parse HEAD)) { throw "Tag v$env:RELEASE_VERSION already points at another commit" } @@ -148,7 +151,6 @@ jobs: '--title', "pnLibrary $env:RELEASE_VERSION", '--notes', $env:RELEASE_NOTES ) - if ($env:RELEASE_VERSION.Contains('-')) { $arguments += '--prerelease' } & gh @arguments if ($LASTEXITCODE -ne 0) { throw 'GitHub Release creation failed' } diff --git a/AGENTS.md b/AGENTS.md index 778cfbe1a..582637c10 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,7 +49,7 @@ ``` ## Где что -- `modules/`: api, core, common, runtime-spi, updates, bootstrap, console, features (config, currency, localization). +- `modules/`: api, core, common, spi, updates, bootstrap, console, features (config, currency, localization). - `platforms/`: bukkit, bungee, velocity, loader. - `.pnlibrary/releases.json` и `.pnlibrary/changelogs/<версия>.md`: каталог релизов библиотеки. - `integration/`: инструкция и заготовка `.pnlibrary` для плагинов на pnLibrary. @@ -57,8 +57,27 @@ ## Журнал (новое сверху) Обновляй эту секцию в конце каждой сессии: одна запись, что сделано и что осталось. +### 2026-11-18 (стиль Bungee) +- Продолжен существующий проход Bungee по образцу Velocity: упрощены сборка рантайма и зависимости, команды используют общий адаптер аудитории; серверный адаптер вынесен в `network/BungeeNetworkServer.kt`. Убраны внутренние KDoc-пересказы и лишние импорты, сохранены пояснения ограничений Bungee. Ранее начатые переносы пакетов сохранены. +- Проверено: 13 тестов Bungee, проверки модулей Bungee и сборка `distribution` прошли. Общий `apiCheck` падает на существующем расхождении `modules/api` (ChatTone, PnLogger, NetworkProxy); публичный API в этой сессии не менялся. Общий `spotlessCheck` также выявил нарушения форматирования за пределами Bungee. На живом прокси не проверялось. + +### 2026-11-10 (ошибки, безопасность, скорость) +- Ошибки: около 36 мест, где сбой пропадал молча, теперь пишут в логгер; `ERROR` без исключения уходит в FastStats (временное исключение). Не закрыто: в FastStats идёт `RuntimeException("тип: сообщение")` вместо исходного, нет повторной отправки. +- Безопасность: права проверяет получатель связи (`MenuDataServer.holds`), `link.key` 600, хосты скачивания (`TrustedHosts`), каталог релизов raw/API раньше jsDelivr, битые журналы пропускаются, `@ConfigSecret` в списках и картах. Не сделано: подпись запроса связи платформой-источником, таймаут `policy.check`, общий таймаут скачивания. Хеш политики не возвращали (пользователь убрал). +- Скорость (с тестами эквивалентности и счётчиками): журнал пачками, буфер логов, групповой коммит валюты и кеш закодированных транзакций, индекс плейсхолдеров, `Wildcards`, история событий, поиск перевода, HMAC, `PlayerHeads`. Файл валюты по-прежнему пишется целиком на каждое сохранение пачки. +- Копии баз: Postgres одной транзакцией, enum, параметры последовательностей, внешние ключи вне маски; MySQL литералы и размер INSERT; права на файлы. Identity-колонки и text/2dsphere-индексы Mongo неполно. +- Публикация: без ключа подписи работает `publishToMavenLocal`; подключение без публикации описано в `integration/README.md`. +- Порядок выпуска dev: `next` вливается в `main` PR (как #90), релиз запускается workflow `release` на `main`. Выпускается `0.1.0-dev.3`. + +### 2026-11-08 (копии баз) +- Копии баз MySQL/MariaDB, MongoDB и PostgreSQL по аннотациям: `@BackupDatabase(tables = [...])` с масками `*`, `@BackupTable`, несколько баз на полях одного класса (`database = "ID"` у `@DatabaseField` и `@BackupTable`, без аннотаций на классе). Драйверы грузятся лениво через Libby при первом использовании. +- Меню копий идёт по плагинам и датам; выдача файлов копии вместо возврата (кнопка и `/pn updates backups files`). +- Обновление библиотеки сохраняет вариант `universal`; `universal-full` попадает в файлы релиза и `checksums.sha256`. +- Сверены `integration/` и CHANGELOG (раздел `next` сгруппирован), в инструкцию для плагинов добавлены резервные копии. +- Осталось: проверка на живых базах и серверах, релиз `0.1.0-dev.3`, идея отпечатка сервера, вес `universal` 5,6 МБ. + ### 2026-11-05 (логгер, прокси, тесты) -- Логгер один: конфиги, интеграции Bukkit и перезапуск пишут через `PnLogger` (`PlatformPnLogger` в `runtime-spi`), серьёзное попадает в чёрный ящик; у `info`/`debug` можно передать исключение. Общая сборка связи прокси вынесена в `core/proxy/ProxyLink` с откатом при сбое запуска. Меню Bukkit перенесены в пакет `menu`. +- Логгер один: конфиги, интеграции Bukkit и перезапуск пишут через `PnLogger` (`PlatformPnLogger` в `spi`), серьёзное попадает в чёрный ящик; у `info`/`debug` можно передать исключение. Общая сборка связи прокси вынесена в `core/proxy/ProxyLink` с откатом при сбое запуска. Меню Bukkit перенесены в пакет `menu`. - Перезапуск без `restart-script`: сервер останавливается, дальше его поднимает панель или start.sh, это не ошибка. - FastStats оставлен как был (`ErrorTracker.contextAware()`), правку откатили по просьбе. - Тесты: миграция конфигов, кадры связи и `LinkSecret`, откат обновления после сбоя публикации, задачи, скрытие секретов в отчёте. Ошибок не нашли. @@ -79,7 +98,7 @@ - Изучены LimboAPI, LimboAuth, LimboFilter и LirTitles, правила записаны в «Как должен читаться код». Меню Bukkit разделено по ролям (`MenuSessions`, `BukkitMenuSession`, `MenuListener`, `MenuInventories`), флаги заменены методами. `PnLibraryImpl` переписан как сценарий запуска без псевдонимов (320 → 284). Убраны 124 однострочных KDoc над `override` вне публичного API. Проверено: `catch (Throwable)` почти везде прибирает и пробрасывает, это оставлено; `lateinit` в основном коде нет. - Глобальный `LinkHub` заменён классом `Link`: его создаёт рантайм платформы (`openLink` на Bukkit, `connectLink` на Velocity/Bungee) и передаёт через конструкторы командам, меню (`MenuHost.link`) и слушателям. `/pnproxy` теперь регистрирует рантайм прокси, а не `PnLibraryLauncher`; команда запускается через `PnLibrary.dispatchRuntimeCommand`. Убраны `ProxyMenuCommands.runner` и `RemoteMenus.data`. На живой сети (прокси + сервер) не проверялось. - Рефлексия: папку и логгер плагина теперь даёт платформа (`PlatformOwnerMetadata.ownerDataFolder/ownerLogger`), а не `getMethod("getDataFolder")` в ядре и конфигах. Folia собрана в `compat/Folia` (методы ищутся один раз, а не при каждой задаче и клике). Головы с текстурой — одна реализация (`PlayerHeads`), замена hex-цветов вынесена в `HexColors`. Убраны лишние: проверка Folia в bStats, `getOnlinePlayers` через рефлексию (нужно было только для 1.7). Оставшаяся рефлексия в Bukkit нужна: рантайм собран против Spigot 1.8 и зовёт новые API только там, где они есть. -- `DisplayZone.zone` оставлен: пишется один раз при старте из `config.yml`, это настройка отображения, протягивать `ZoneId` через 16 файлов форматирования незачем. +- `DisplayZone.zone` оставлен: пишется при старте и при смене `time-zone` из настроек библиотеки (`data/settings.json`), это настройка отображения, протягивать `ZoneId` через 16 файлов форматирования незачем. - Дальше: комментарии-пересказы над `private`/`internal` (около 600, только вручную); на живом Folia-сервере новый `Folia` не проверялся. ### 2026-11-05 (документы) diff --git a/CHANGELOG.md b/CHANGELOG.md index ccb6c50f5..fa33f568b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,15 +2,179 @@ ## Ветка next (0.1.0-dev) -- **Плейсхолдеры.** Дерево с аргументами (`player`, `param`, `choice`), адрес `плагин/модуль:путь`, генерация веток - `from`, `table`, `list`, форматы по четырём уровням и свои форматы модуля, доступ `access`, запись `update`, - публикация в PlaceholderAPI из той же регистрации. Команда `/pn placeholders`, страница в `/pn gui`. - Подробности: docs/placeholders.md. +- Версия 0.1.0-dev.6: API несовместим с dev.5, поколение API (`PnLibraryApi.VERSION`) поднято с 1 до 2. Плагины, которые объявляли `pnLibraryApi(1, 1)`, нужно перевести на новое API и объявить `pnLibraryApi(2, 2)`. +### Сценарии в одной папке +- Загрузки: `maxBytes` задаёт наибольший размер для одного файла, больше или меньше общего потолка в 512 МБ (`FileDownload`, `variant`, зависимости). +- Загрузки: без SHA-256 файл берётся с первой ссылки, которая ответила; сравнение копий между зеркалами и запоминание сумм убраны, остальные адреса служат запасными. +- Зависимости плагинов, варианты файла: `variant(...)` задаёт отдельный файл под платформу и версию Minecraft со своими ссылкой, SHA-256 и зеркалами; скачивается и проверяется только подходящий. В меню появился экран «Что не хватает» со скачиванием группы кликом. +- Зависимости плагинов: у `ExternalPluginDependency` появились `title` и `description`. Карточка «не хватает плагинов» и `/pn deps` делят список на обязательные и необязательные, показывают название, описание, все ссылки и способ проверки файла (есть ли SHA-256 автора). Описание в `docs/dependencies.md`. +- Обновления, ремастер API: `UpdateService` разделён на пять частей: `products`, `plans`, `settings`, `backups`, `history`. Убраны методы-заглушки «не поддерживается»: в каждой части работает всё. `checkNow` стал `plans.check`, `currentPlan` стал `plans.current`, `history()` стал `plans.recent`, `setChannel` стал `settings.channel`, `setHeld` разделён на `settings.hold` и `settings.release`, `backups()` стал `backups.list`, `rollback(id, restoreConfigurations, actor)` стал `backups.rollback(id, actor, restoreConfigurations)`, `historyPage` и `historyCount` стали `history.page` и `history.count`. `confirm` из API убран: он никогда не работал, подтверждение идёт командой `/pn update confirm`. Все методы с `actor` его принимают необязательным. +- Плейсхолдеры в тексте: один вид скобок `{...}` вместо трёх. `{имя}` читает сначала значение запуска (`player`, `price`), затем плейсхолдер pnLibrary; `{плагин/модуль:путь}` адресует плейсхолдер явно, `{papi:имя}` берёт из PlaceholderAPI (`%имя%` остаётся тоже). Старые `[имя]` больше не плейсхолдер: префикс вроде `[pnTest]` остаётся текстом и не даёт предупреждения «Placeholder … is not registered». Нужно заменить `[имя]` на `{имя}` в действиях, сообщениях и выражениях. Описание в `docs/placeholders.md`. +- Меню «Библиотеки плагинов»: сначала выбор плагина (сколько у него библиотек, модулей, какой размер, есть ли конфликт версий) или «Все библиотеки» одним списком; у библиотеки «Принадлежит» (плагину или модулю плагина), «Файл» и «Папка» считаются от папки сервера, а не обрезанный хвост пути. +- Диск: `/pn modules disk` и кнопка «Диск плагинов» в меню показывают, сколько места занимает каждый плагин сервера (jar, настройки, библиотеки, журналы, данные), сколько свободно на диске. У библиотек плагинов видны размер и место, где лежит jar. +- Библиотеки: на плагин (`PluginRegistration.libraries`) и на модуль, `title` и `description` у библиотеки и у модуля (`metadata { description(...) }`), `loadClass`, `find`, `remove`, `PluginRegistry.allModules()` и `libraryUsage()`, `/pn modules libs|plugins`, экраны «Библиотеки». `shared()` на Bukkit и BungeeCord грузит в загрузчик плагина-владельца. +- Библиотеки модуля: `PluginModule.libraries()` и `ModuleLibrary`. Откуда качать: один список мест `source { link(...) | repository(...) }`, у каждого своя сумма и имя, сколько угодно; пробуются по порядку, затем Maven Central, первое рабочее побеждает. `LibraryScope` (плагин, отдельный загрузчик, pnLibrary), `platforms`, необязательность, классификатор. +- Модули: `registerModule(id, PluginModule)` с методами `onEnable`/`onDisable`/`onReload`, `ModuleContext.control` (`enable`, `disable`, `restart`, `reload`, `autoStart`), команда `/pn modules` и экраны меню «Модули плагинов» (также кнопка «Модули» в карточке плагина). Выключенные навсегда модули хранятся в `data/modules/preferences.json`. Подробности в `docs/modules.md`. +- Обновления: в карточке продукта можно выбрать сборку Java (`UpdateService.setJavaBuild`, `UpdateSnapshot.javaBuilds/javaBuild/recommendedJava`, команда `/pn updates set <плагин> java `). Без выбора берётся сборка, как у установленного продукта. +- `api.tasks`: по одному типу на файл и подпапки `spec` (`TaskSpec`, `TaskSpecBuilder`, `TaskAction`, `TaskContext`, `TaskExecution`, `TaskConflictPolicy`) и `info` (`TaskId`, `TaskStatus`, `TaskSnapshot`, `TaskQuery`). Новое: задача классом `ScheduledTask` (`scope.schedule(MyTask(args))`), `TaskStatus.isTerminal`, `TaskSnapshot.isActive`, `TaskQuery.matches(snapshot)`; дубли в `core` удалены. Импорты нужно поправить. +- (теперь в пакете `api.tasks.run` вместе с `TaskLagHandler`/`LagResponse`) `TaskContext` расширен: `key`, `tags`, `executionKind`, `interval`, `skippedCount`, `previousStartedAt`, `isCancelled`, `snapshot()`, `isFirstRun`, `isRepeating`, `lag`, `elapsed`, `every(n)`, `cancelAfter(n)`. Исправлено: `scheduledAt` у повторяющейся задачи теперь плановое время каждого запуска, а не время первого. Подзадачи: `context.later(delay) { ... }`, `context.spawn(spec или ScheduledTask)` запускают следующую задачу в той же области, без доступа к `tasks`; новые `execution` и `TaskContext.SUBTASK_TAG`. Новое в задачах: `maxLag` (пропустить запуск, который запоздал дольше заданного), `tolerateFailures` (повторяющаяся задача переживает N ошибок подряд), `TaskSnapshot.failedCount`, `TaskContext.isLate(порог)`. +- `PluginUpdateRequest`: правило `.artifact(...)` стало необязательным. Какой файл подходит серверу, решает каталог `releases.json` (платформа и диапазон Java у каждого файла), а Java плагина берётся из его `ProductDescriptor`. +- `api.updates` разложен: `request` (`PluginUpdateRequest`, `PluginUpdateArtifact`, `CatalogSource`), `product` (`ProductDescriptor`, `ProductId`, `UpdateChannel`), `history` (`UpdateHistoryEntry`); в корне остались `UpdateService` и `UpdateRegistration`. +- `api.proxy` переименован в `api.network` (`NetworkProxy`, `NetworkServer`, `NetworkPlayer`); `placeholders.model`, `placeholders.tree.scope`; файлы API, где лежало несколько разных классов, разделены по одному на файл (каталоги однотипных классов вроде ошибок команд и встроенных действий оставлены вместе). +- `metrics` и `observability` разложены: `metrics.provider`, `metrics.error`, `observability.report`, `observability.observation`; в ядре `metrics.session`, `metrics.factory`, `observability.store`. +- Остальные пакеты API разложены: `dependencies.external`, `diagnostics.report`, `plugin.lifecycle`, `plugin.metadata`, `audiences.player`; файлы с несколькими классами (`logging`, `dependencies`, `downloads`, `observability`, `metrics`, `cooldowns`) разделены по одному классу на файл. В ядре `diagnostics` разделён на `config`, `command`, `redaction`, `journal` на `store` и `view`. +- `LagResponse.CANCEL`: обработчик лага может отменить задачу насовсем, если после такой задержки запускать её уже незачем. +- Команды в API разложены: `api.commands.definition` (`CommandDefinition`, `CommandNode`, `ArgumentType`, DSL `command`) и `api.commands.error` (`CommandError`, `fail`, `ensure`); `CommandContext`, `CommandSender`, `CommandRegistration` остались в корне. Движок команд ядра лежит в `core.commands.engine`. +- Подзадачи — полноценные задачи: у них есть `parentId`, `context.repeat(n, every) { }`, `context.spawn { ... }` (DSL), `cancelWithParent` (отмена вместе с родителем); `/pn tasks` и меню показывают в `/pn tasks` и меню подзадачи вложены в родителя (список показывает только верхний уровень, у родителя кнопка «Подзадачи», у подзадачи «Подзадача от»), есть слот «Опоздания». Лаги сервера: `TaskLag` (`lag`, `missedRuns`), `ScheduledTask.onLag`, `onLag(порог, handler)`/`whenLate(порог, consumer)` в билдере, ответ `LagResponse` (RUN/SKIP), `TaskSnapshot.lastLag/worstLag`, «Опоздание» в чате и GUI. +- `api.text` разложен на `cache` (`ComponentCachePolicy`, `ComponentCacheScope`, `ComponentCacheStatistics`) и `serializer` (`ComponentSerializer`, `ComponentSerializerType`). Новое: `ComponentCachePolicy.DISABLED`, `ComponentCacheStatistics.lookups`, `ComponentTemplate.values(map)`. Импорты нужно поправить. +- `api.updates` разложен на `catalog` (`CatalogSource`, `ProductDescriptor`, `ProductId`, `UpdateChannel`) и `state` (`UpdateState`, `UpdateSnapshot`, `UpdatePlanSnapshot`, `BlockedReason`, `UpdateActor`); `api.placeholders` на `adapter` и `cache`. Импорты нужно поправить. +- `api.actions` стал `api.scenario.actions`, `api.requirements` стал `api.scenario.requirements`, калькулятор вынесен в `api.scenario.expression`. `ChatPalette` и `ChatTone` перенесены в `api.chat.style`. Несовместимое изменение API: нужно поправить импорты. + +### События по папкам +- Пакет `api.events` разложен: корень (`Event`, `ResultedEvent`, `EventDescription`), `bus` (`EventService`, `EventScope`, `DispatchMode`), `listener` (`Listener`, `EventHandler`, `EventPriority`, `EventSubscription`, `EventListenerRegistration`, `EventListenerBuilder`, `subscribe`), `inspect` (`EventInspector`, `EventInfo`, `ListenerInfo`), `inspect.history` (`EventDay`, `EventHour`), `inspect.trace` (`EventTrace`), `player`. В `core.events`: `registration`, `player`, `inspect`, `inspect.history`, `inspect.trace`. +- `EventInspector`: убраны заглушки по умолчанию у `hourly`, `asyncQueued`, `exportHistory`. Новое: `on().listenOnce { }` слушает только первое событие. Несовместимое изменение API. + +### Новая система действий и требований +- `api.actions` переписан: `Action.run` возвращает `ActionResult` (`Done`, `Stopped`, `Failed`). Ошибка шага откатывает прошлые шаги через `ActionContext.onUndo`; блок `attempt` ловит ошибку и показывает сообщение. +- `api.checks` заменён на `api.requirements`: `Requirement` отвечает `Verdict.Met` или `Verdict.Unmet(reason)`, значения берутся из контекста, плейсхолдеров pnLibrary и PlaceholderAPI. Списание денег — действие `charge` (`give`, требование `balance`), слова добавляет сама библиотека для всех плагинов. +- Выражения: `Expression` (математика, логика, функции, плейсхолдеры), требование `expression`, текст `{= ... }`, действия `set`, `call`, `random`, обработчики ошибок по коду в `attempt`, именованные `define`/`defineRequirement`/`defineFunction` (на модуль или на библиотеку, с политикой конфликтов). +- Удалены `ActionNode`, `ActionText`, форматы DeluxeMenus, шаблоны `run`, `group`, `require` со старыми полями, `InternalPnLibraryApi`. Несовместимое изменение API. + +### Убран Activity API +- Удалены `PnLibrary.activity`, `ActivityService`, `ActivityEvent` и остальные типы пакета `api.activity`. Вместо них `PnLibrary.observability`: + `capture { }` для события, `failure(error)` для ошибки, `recent(query)` для чтения. Несовместимое изменение API. +- Слои игроков: `AudienceSender` и `PlayerCapability` вынесены в отдельные файлы, `PlayerEffects.kt` разделён на `PlayerEffect` и `PlayerParticle`. + +### Настройки библиотеки без файлов +- `config.yml` и `downloads.yml` больше не читаются. Все настройки меняются командой `/pn settings list|get|set|reset` (право `pnlibrary.settings`) + и в меню «Настройки» → «Параметры библиотеки»; значения лежат в `data/settings.json`, список настроек один (`SettingsRegistry`), описание в + [docs/settings.md](docs/settings.md). +- Старые файлы при первом запуске переносятся в `settings.json` и переименовываются в `*.yml.old`; выбор `/pn deps auto` главнее `downloads.yml`. +- Новые настройки: время проверки обновлений (`updates.check-interval`) и таймауты скачивания обновлений. Настройки загрузок и часового пояса + работают сразу, остальные после перезапуска. + +### Справка в папке плагина +- В `plugins/pnLibrary` библиотека сама пишет `Помощь.txt` (помощь, Discord, репозиторий, главные команды), `Настройки.txt` (все настройки с + текущими значениями, описаниями и командой для изменения) и `Команды.txt` (все команды `/pn` и права, в том числе `/pn settings`, `/pn configs`, + `/pn support`, `/pn gui`, `/pn deps`, подкоманды `/pn updates` и `/pn update`). Они создаются заново при каждом запуске, `Настройки.txt` ещё и после + изменения настройки. Если JVM не умеет русские имена файлов, они называются `HELP.txt`, `SETTINGS.txt` и `COMMANDS.txt`. +- Список команд и прав один, в коде (`LibraryCommandGuide`); тест сверяет его с правами в `plugin.yml`. В `plugin.yml` добавлены права + `pnlibrary.configs`, `pnlibrary.configs.edit`, `pnlibrary.servers` и `pnlibrary.currency.list` (по умолчанию у операторов, как и раньше). +- В файлы настроек плагинов больше не пишется заметка с Discord; в старых файлах она удаляется при следующей записи. + +### Настройки в меню +- Переключатели везде показываются словами `включено` и `выключено` (меню, `/pn settings`, `Настройки.txt`); в команде принимаются также + `вкл`, `выкл`, `да`, `нет`, `true`, `false`, `on`, `off`. В подсказке переключателя вариант по умолчанию помечен серым курсивом `(по умолчанию)`, + отдельной строки «По умолчанию» у переключателя больше нет. +- Часовой пояс выбирается в меню из одного постраничного списка всех поясов. У каждого пояса видно время там сейчас (`21:45`) и смещение + (`UTC+03:00`, с учётом летнего времени). Кнопки: сортировка (по смещению UTC или по алфавиту), «Популярные» (Москва, Лондон, Нью-Йорк и другие), + «Поиск» и «Ввести в чате». Поиск: `/pn settings pick <ключ> [часть названия]`, например `new york`. Настройки с длинным списком значений + описываются типом `CHOICE` и `ChoiceSource`; Tab в `/pn settings set` подсказывает пояса. +- В меню часовой пояс переключается кликом, как настройка с вариантами в конфигах: клик следующий пояс из «Популярных», правый клик предыдущий, + Shift + клик открывает полный список. В подсказке окно значений со строками `▲ выше ещё N` и `▼ ниже ещё N`, смещение и время там сейчас; + пояс вне популярных стоит первой строкой. `ChoiceSource.cycle` задаёт набор для прокрутки. +- Числа: `@ConfigStep(шаг, единица)`, `@ConfigDuration(TimeUnit)` (в меню «1 ч 30 мин», шаги секунда/минута/час, ввод `90m`, `1h30m`). + Колёсико мыши открывает редактор числа: шаги вниз и вверх разного размера, «Минимум», «Максимум», ввод в чате. +- Тексты: `@ConfigHint(format, examples, values, strict)`; со `strict` текст становится списком выбора. Длинный список листается + отдельным экраном (Shift + клик). +- В списках: кнопки страниц `◀ Страница N` / `Страница N ▶`, номер страницы и диапазон на средней кнопке. В карточке файла виден полный класс. + +### Зависимости +- У внешней зависимости несколько источников без контрольной суммы: `Dependencies.plugin(имя, версия, listOf(url1, url2))`, + `ExternalPluginDependency.Builder.mirror(url)`, `FileDownload.Builder.mirror(url)`. Файлы с разных адресов сверяются; при расхождении загрузка отклоняется. + Единственный адрес запоминает SHA-256 первой загрузки: если файл по нему изменился, нужно подтверждение администратора. +- Автозагрузка недостающих плагинов включена по умолчанию (у зависимости с прямой ссылкой). Выбор администратора лежит в данных + (`downloads/preferences.state`), а не в конфиге, и главнее `downloads.yml`; переключатель есть в меню настроек и в `/pn deps auto on|off`. +- Чего не хватает: сообщение в консоли со ссылками и кодом. `/pn deps` показывает список, `/pn deps install <код>` скачивает сразу, даже при выключенной автозагрузке. + Право `pnlibrary.deps`. + +### Конфигурации +- Регистрация полиморфных типов по адресу: `.into("плагин" | "плагин/модуль" | "плагин/модуль:путь" | ConfigAddress | ManagedConfig)`. + `ConfigTypeAccess` и `.access(...)` удалены. Регистрация живёт и умирает с модулем регистранта. +- Защита: нельзя занять слова базового типа и хозяина файла; хозяин ограничивает расширения `extensions { allow/deny/denyAll }`. +- `ConfigOptions.unknownTypes` (`FAIL`/`SKIP`): при `SKIP` элемент списка с незнакомым `type` пропускается и остаётся в файле; + запись заблокирована, пока есть пропущенные. Ожидающие конфиги перечитываются при регистрации типа. +- Идентификаторы `плагин/модуль:путь` (`ConfigId`, `ConfigAddress`, `ConfigInfo`) и каталог: + `library.configurations.all/find/get/require/byModel/types`, `library.plugins.getById/requireById`, `PluginRegistration.configs()`, + `ConfigScope.list/get/require`, `ManagedConfig.id/info`. +- `ConfigOptions.root` (`PLUGIN`, `PLUGINS`, `SERVER`) и `ConfigOptions.readOnly`. +- Команда `/pn configs [страница] | info | reload | validate | types`, право `pnlibrary.configs`. +- Файл по любому абсолютному пути: `scope.yamlAt(Path)` (корень `ConfigRoot.EXTERNAL`, ID `плагин/модуль:@external/<путь>`). + Путь может прийти из собственного конфига плагина. Файл считается своим: создаётся и перезаписывается, секреты скрываются в отчётах. +- Один класс `PluginAccess` (`ownerOnly()`, `shared()`, `only(...)`, `builder()`) вместо `PlaceholderAccess`, `CurrencyAccess` + и `ConfigExtensionPolicy`; `configs.extensions { }` теперь тоже на нём. +- Правка настроек в игре: аннотация `@ConfigEditable(title, description, apply)`, `ManagedConfig.settings` и `edit(path, text)`, + `ConfigApply` (`LIVE`, `RELOAD`, `RESTART`). Секреты (`@ConfigSecret`) не показываются. Команды `/pn configs settings ` и + `/pn configs edit <путь> <значение>` (право `pnlibrary.configs.edit`), страница «Конфигурации» в `/pn gui`: плагины → модули → файлы (или все файлы плагина с названием модуля), с переключением и страницами. +- Колбэки: `ManagedConfig.onChanged(...)` (чтение, запись, правка) и `onReloadRequired(...)` (изменена настройка, которой нужно + перечитывание или перезапуск); принимают несколько обработчиков, ошибка одного не мешает другим. `ConfigInfo.pendingApply`. +- Адрес собирается из частей, строки не нужны: `ConfigAddress.plugin("shop").inModule("main").inFile("a.yml")`; `into` принимает ещё `PluginId`, `ConfigScope`, `ConfigInfo`, `ManagedConfig`. +- Адрес `*` (`ConfigAddress.everywhere()`, в билдерах `.everywhere()`): слово типа и сериализатор можно добавить во все файлы всех плагинов. +- Сериализаторы в чужих файлах: `scope.serializerFor(serializer).into(адрес).priority(n).register()`, список `configurations.serializers()`. + Свои сериализаторы модуля главнее добавленных, хозяин ограничивает `extensions { }`, чужим файлам нельзя подменить примитивы + и типы `java.`/`kotlin.`. Сериализаторы читаются при каждом чтении файла, поэтому добавление после `yaml(...)` тоже работает. + +### Плейсхолдеры +- Дерево с аргументами (`player`, `param`, `choice`), адрес `плагин/модуль:путь`, генерация веток `from`, `table`, `list`, + форматы по четырём уровням и свои форматы модуля, доступ `access`, запись `update`, публикация в PlaceholderAPI из той же + регистрации. Команда `/pn placeholders`, страница в `/pn gui`. Подробности: docs/placeholders.md. + +### Обновления +- `updates.yml` и список `ignored` удалены. Автообновление включено по умолчанию, меняется командой или в меню: + `/pn updates set <плагин> auto on|off` и `/pn updates set all auto on|off` (новый метод `UpdateService.setAutomaticDownloadForAllPlugins`). + Отложить обновление можно только паузой до 7 суток. Старый файл переименовывается в `updates.yml.old`. +- Напоминания об обновлении идут по своему интервалу (6 часов по умолчанию, в коде от 1 минуты до 6 часов) в консоль и + в чат администраторам (Bukkit, Velocity, BungeeCord), без обращения к GitHub. Администратор их не отключает. +- Обновление библиотеки сохраняет вариант сборки: если стоит `universal.jar` (его кладёт установщик в плагинах), берётся новый + `universal.jar`, а не файл платформы. +- Релиз: `pnLibrary-<версия>-universal-full.jar` (Kotlin и Adventure внутри, без скачивания при старте) загружается в релиз + GitHub и попадает в `checksums.sha256`. +- Необязательные библиотеки (драйверы баз, компилятор ECJ) скачиваются через Libby только при первом использовании + (`LibraryLoader.loadOptional`, `OptionalLibrary`), а не на старте. + +### Резервные копии перед обновлением +- Копии с типом и именем (`BackupKind`: конфигурация, база данных, данные игроков, прочее; `PluginUpdateRequest.Builder.backup`). + Наборы хранятся 30 дней, при 500 МБ и больше в консоль идёт предупреждение; удалить: `/pn updates backups delete ` + (`UpdateService.deleteBackup`). +- `PluginUpdateRequest.Builder.backupExport`: плагин сам выгружает данные перед обновлением; файл хранится с набором, + откат его не восстанавливает. +- Базы по аннотациям: MySQL/MariaDB, PostgreSQL (`DatabaseKind.POSTGRESQL`: таблицы текущей схемы с индексами, ограничениями + и последовательностями) и MongoDB (`DatabaseKind.MONGODB`, `DatabaseRole.URI`). Аннотации: `@BackupDatabase`, `@DatabaseField`, `@BackupTable`. + Вернуть базу можно кнопкой в меню отката (с предупреждением о потере данных) или `/pn updates backups restore` (`UpdateService.restoreDatabase`). +- Только нужные таблицы или коллекции: `@BackupDatabase(..., tables = [...])` и `@BackupTable`; в имени работает `*`. Без них копируется вся база. +- Несколько баз в одном классе: поля привязываются к базе через `database = "ID"` у `@DatabaseField` и `@BackupTable`, + отдельные классы и аннотации на классе не нужны. +- Меню копий идёт по плагинам и датам. Выдать файлы копии вместо возврата: кнопка «Выдать файлы» или `/pn updates backups files <плагин>`. + +### Ошибки, безопасность, скорость +- **Ошибки не теряются.** Сбои журнала, статистики, задач, закрытия платформ, валют и плейсхолдеров пишутся в логгер на уровне + `ERROR`/`CRITICAL`; запись уровня `ERROR` и выше без исключения тоже уходит в трекер ошибок (FastStats). +- **Срок хранения записей.** `ObservationScope.keepFor(Duration)` задаёт автор плагина в коде, срок перекрывает срок уровня. + В отчёте поддержки у записей есть `timeUtc` и `expiresUtc`. Раздел «Сообщить о проблеме» в docs/diagnostics.md. +- **Безопасность.** Права на опасные действия по связи проверяет получатель, а не вызывающий; `link.key` и файлы копий + создаются с правами владельца; каталог релизов берёт raw/API раньше jsDelivr; хосты скачивания ограничены списком; + имя JAR платформы должно начинаться с `pnLibrary-`; битый `journal.json` не блокирует обновления и откаты; + `@ConfigSecret` работает внутри списков и карт (`by-name.*.pin`). +- **Старый Adventure.** На серверах, где Adventure слишком старый для MiniMessage (например Paper 1.16.5), MiniMessage заменяется + упрощённым разбором (цвета, `#rrggbb`, декорации, `reset`, `br`, экранирование `\<`), в лог пишется одно предупреждение. +- **Копии баз.** PostgreSQL возвращается одной транзакцией, копируются enum-типы, параметры последовательностей и внешние + ключи таблиц вне маски; MySQL сохраняет переводы строк в литералах и режет `INSERT` по размеру; Mongo-индексы сохраняют + `partialFilterExpression` и `collation`. +- **Скорость.** Журнал пишется пачками, буфер логов не очищает повторы заново, групповой коммит и кеш закодированных + транзакций в валюте, индекс плейсхолдеров, кеш шаблонов `Wildcards`, история событий без общей блокировки, предрассчитанные + триграммы в поиске перевода, одна проверка HMAC на кадр связи, журнал при входе админа собирается не на главном потоке. +- **Лёгкий universal на Bukkit и BungeeCord.** Libby не скачивал MiniMessage и plain-сериализатор (на BungeeCord ещё gson-сериализатор), плагин падал при старте с `NoClassDefFoundError: net/kyori/adventure/text/minimessage/MiniMessage`. Эти библиотеки добавлены в списки загрузки, тест `RuntimeLibrariesTest` следит за списками. +- **Ссылки поддержки.** `PnLibraryIdentity.SUPPORT_URL` и `REPOSITORY_URL` больше не `const`: компилятор не копирует их в плагины, они читаются из запущенной библиотеки, и новая ссылка доходит до плагинов без пересборки (после одной пересборки на этом API). В карточку уведомления об обновлении добавлена строка поддержки. +- **Vault.** Пока Essentials не загрузил настройки, подключение валюты Vault тихо откладывается до следующего события, а не пишет SEVERE на каждой попытке. +- **Публикация.** Без ключа подписи `publishToMavenLocal` работает (артефакты неподписанные); подключение без публикации + описано в integration/README.md. + +### Прочее - **Статистика.** Почасовые срезы в журнал, `/pn stats`, страница меню. -- **Модули.** Из `core` вынесены `link`, `placeholders`, `events`, `upload`, `journal`: границы между функциями теперь проверяет +- **Модули.** Из `core` вынесены `link`, `placeholders`, `events`, `upload`, `journal`: границы между функциями проверяет компилятор. Имена пакетов не менялись. - **Исправлено.** Folia: библиотека стартует с `link.key`, задачи вышедшего игрока снимаются с учёта. Карта сети не превышает лимит кадра. - Прокси не затирает нечитаемый `link.key`. Обновления: на Paper плагины работают из `plugins/.paper-remapped`, папка бэкапа конфигов + Прокси не затирает нечитаемый `link.key`. На Paper плагины работают из `plugins/.paper-remapped`, папка бэкапа конфигов больше не отклоняется. Отчёт поддержки не содержит значений `@ConfigSecret` и `excluded-paths`, а сбой скрытия прячет значение целиком. Пулы данных меню закрываются при остановке. - **Структура.** `core/commands` разнесён по функциям, длинные файлы и методы разбиты, классы с `Impl`/`Manager` @@ -40,6 +204,7 @@ ## config.yml +- В шапке `config.yml` на русском и английском перечислены все команды и права; тест сверяет её с `plugin.yml`. - `privacy` по умолчанию `false`: личные данные в отчёте показываются, скрыть их можно, поставив `true`. - В комментарии к `excluded-paths` пример: путь для всех файлов или `плагин/файл.yml:путь` для одного файла одного плагина. - Параметр `journal-join-notice` убран: сводка недавних проблем при входе администратора показывается всегда. diff --git a/README.md b/README.md index 20fb7eb98..bf1685865 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ ## Установка на сервер -Положите `pnLibrary-<версия>-universal.jar` в `plugins/` — один файл работает на Bukkit, BungeeCord и Velocity. +Положите `pnLibrary-<версия>-universal.jar` в `plugins/` — один файл работает на Bukkit, BungeeCord и Velocity. Если у сервера нет доступа к репозиториям при старте, возьмите `pnLibrary-<версия>-universal-full.jar`. Команды (Bukkit): @@ -37,11 +37,11 @@ | `/pn money` | управление валютами плагинов | | `/pn stats` | почасовая статистика ошибок, задач и событий | | `/pn placeholders [test <адрес>]` | список и проверка плейсхолдеров | -| `/pn bus`, `/pn tasks`, `/pn groups` | шина событий, задачи, группы серверов | -| `/pn servers`, `/pn support` | серверы прокси, обращение в поддержку | +| `/pn bus`, `/pn tasks` | шина событий, задачи плагинов | +| `/pn servers`, `/pn support` | серверы сети, обращение в поддержку | | `/pn debug [all\|плагин]` | отчёт для поддержки | -На BungeeCord и Velocity каталог доступен из консоли командой `/pn update`. Все команды обновлений и права описаны +На BungeeCord и Velocity команда называется `/pnproxy` (коротко `/pnp`): каталог обновлений, `events`, `bus`, `tasks`, `stats`, `placeholders`, `debug`, `servers` и `groups` (группы серверов есть только на прокси). Все команды обновлений и права описаны в [docs/updates.md](docs/updates.md). Остальные права (по умолчанию у операторов): @@ -53,6 +53,13 @@ | `pnlibrary.stats` | `/pn stats` и страница статистики в меню | | `pnlibrary.placeholders` | `/pn placeholders`: список и проверка плейсхолдеров | | `pnlibrary.debug` | `/pn debug` | +| `pnlibrary.tasks` | `/pn tasks` | +| `pnlibrary.events.bus` | `/pn bus` | +| `pnlibrary.groups` | `/pnproxy groups` | +| `pnlibrary.servers` | `/pn servers` | +| `pnlibrary.currency.list` | список валют в `/pn money` | + +Права обновлений (`pnlibrary.updates.*`) описаны в [docs/updates.md](docs/updates.md). ## Подключение к плагину @@ -66,6 +73,8 @@ dependencies { В `plugin.yml` плагина: `depend: [pnLibrary]`. +Какие модули подключать и как собрать библиотеку локально, не публикуя, описано в [integration/README.md](integration/README.md). + ```kotlin val library = PnLibraryProvider.get() val registration = library.plugins.register(this) @@ -83,8 +92,9 @@ API состоит из интерфейсов, моделей и небольш ./gradlew :distribution:shadowUniversal # distribution/build/libs/pnLibrary-<версия>-universal.jar ``` -`installAcceptanceToPaper` копирует сборку на тестовый сервер; путь задаётся свойством `pnlibrary.installDir` -(например, в `~/.gradle/gradle.properties`). +Кроме лёгкого `universal` (Kotlin и Adventure скачиваются при старте) есть `universal-full` (`shadowUniversalFull`): +всё внутри, ничего не скачивается. Он лежит в релизе GitHub как ручная загрузка и в каталог обновлений не входит. +Платформенные сборки: `shadowBukkit`, `shadowBungee`, `shadowVelocity`. ## Документация @@ -92,22 +102,26 @@ API состоит из интерфейсов, моделей и небольш - [Архитектура и модули](docs/architecture.md) - [Команды: ошибки, уровни ответа, полный пример](docs/commands.md) - [События: слушатели, приоритеты, результаты](docs/events.md) +- [Кулдауны: паузы на игрока и действие](docs/cooldowns.md) - [Конфигурации](docs/configuration.md) +- [Настройки библиотеки и права: `/pn settings`](docs/settings.md) - [Обновления: команды, права, откат](docs/updates.md) +- [Зависимости плагинов: что не хватает, откуда качать, `/pn deps`](docs/dependencies.md) - [Сеть: прокси, ключ связи, группы серверов](docs/network.md) - [Подключение плагина к pnLibrary: для людей и ИИ](integration/README.md) - [Папка `.pnlibrary` в репозитории плагина](docs/repository.md) -- [Действия](docs/actions.md) -- [Проверки](docs/checks.md) +- [Действия и требования](docs/actions.md) - [Каталог релизов](docs/releases.md) - [Ручная проверка перед выпуском](docs/verification.html) -- [Плейсхолдеры](docs/placeholders.md) +- [Плейсхолдеры](docs/placeholders.md), [пример](docs/placeholders-example.md) +- [Хранилища](docs/storage.md) - [Задачи](docs/tasks.md) - [Диагностика](docs/diagnostics.md) - [Метрики](docs/metrics.md) - [Валюта](docs/currency.md) - [Локализация Minecraft](docs/localization.md) - [Расширения](docs/expansions.md) +- [Черновик API 2](docs/api2-draft.md) - [Удалённые политики](docs/remote-policies.md) - [Встраиваемый установщик для всех платформ](modules/bootstrap/README.md) - [Консольные карточки](modules/console/README.md) diff --git a/build.gradle.kts b/build.gradle.kts index 147f1b861..dcb3b821f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -27,11 +27,6 @@ apiValidation { ignoredProjects.addAll( listOf( "core", - "link", - "journal", - "upload", - "events", - "placeholders", "updates", "distribution", "runtime", @@ -160,7 +155,7 @@ val verifyPublicModuleBoundaries = tasks.register("verifyPublicModuleBoundaries" doLast { val signatureModules = subprojects.filter { module -> module.file("api").listFiles()?.any { it.extension == "api" } == true - }.map { it.path }.toSet() - ":modules:runtime-spi" + }.map { it.path }.toSet() - ":modules:spi" check(signatureModules == publicModuleDependencies.keys) { "Public module registry and signature modules differ: " + "${(signatureModules - publicModuleDependencies.keys) + (publicModuleDependencies.keys - signatureModules)}" @@ -182,19 +177,19 @@ tasks.named("check") { dependsOn( verifyPublicModuleBoundaries, publicModuleDependencies.keys.map { "$it:apiCheck" }, - ":modules:runtime-spi:apiCheck", + ":modules:spi:apiCheck", ) } dependencies { dokka(project(":modules:common")) dokka(project(":modules:api")) - dokka(project(":modules:runtime-spi")) + dokka(project(":modules:spi")) dokka(project(":modules:core")) dokka(project(":modules:updates")) dokka(project(":modules:features:currency-api")) dokka(project(":modules:features:currency-runtime")) - dokka(project(":modules:features:minecraft-localization-api")) + dokka(project(":modules:features:localization-api")) dokka(project(":modules:bootstrap")) dokka(project(":platforms:bukkit:bootstrap")) dokka(project(":platforms:bungee:bootstrap")) diff --git a/distribution/build.gradle.kts b/distribution/build.gradle.kts index 8d20242d5..bb31495ce 100644 --- a/distribution/build.gradle.kts +++ b/distribution/build.gradle.kts @@ -14,7 +14,7 @@ evaluationDependsOn(":modules:core") evaluationDependsOn(":modules:updates") evaluationDependsOn(":modules:common") evaluationDependsOn(":modules:features:config-api") -evaluationDependsOn(":modules:features:minecraft-localization-api") +evaluationDependsOn(":modules:features:localization-api") evaluationDependsOn(":platforms:bukkit:api") evaluationDependsOn(":platforms:bukkit:localization") evaluationDependsOn(":platforms:bungee:api") @@ -163,7 +163,7 @@ tasks.register("shadowUniversal") { } // The same universal JAR with Kotlin and Adventure packed, for servers that cannot reach a repository at start or -// when a download must never be needed. It is a manual download: it is not in the release catalog, because the +// when a download must never be needed. It is a release asset with a checksum, a manual download: it is not in the catalog, because the // updater picks one UNIVERSAL file per release and two would be ambiguous. LibraryLoader sees Kotlin already there // and downloads nothing. tasks.register("shadowUniversalFull") { @@ -203,7 +203,7 @@ val shadowUpdater = tasks.register("shadowUpdater") { archiveBaseName = "${rootProject.property("pnlibrary.name")}-updater" configurations = listOf(updaterRuntime) applyCommonConfig() - manifest { attributes["Main-Class"] = "org.pnfolder.pnlibrary.core.updates.install.OfflineUpdateInstaller" } + manifest { attributes["Main-Class"] = "org.pnfolder.pnlibrary.updates.install.OfflineUpdateInstaller" } } val verifyOfflineInstaller = tasks.register("verifyOfflineInstaller") { @@ -214,7 +214,7 @@ val verifyOfflineInstaller = tasks.register("verifyOfflineInstaller") // When both tasks are requested, finish copying before reading a JAR from it. mustRunAfter("copyDeveloperArtifacts") classpath = files(shadowUpdater.flatMap { it.archiveFile }) - mainClass.set("org.pnfolder.pnlibrary.core.updates.install.OfflineUpdateInstaller") + mainClass.set("org.pnfolder.pnlibrary.updates.install.OfflineUpdateInstaller") val fixture = layout.buildDirectory.dir("offline-installer-smoke/plugins/pnLibrary") args("--server-stopped", fixture.get().asFile.absolutePath) doFirst { fixture.get().asFile.mkdirs() } @@ -232,8 +232,8 @@ val commonJar = project(":modules:common").tasks.named("jar") val commonSources = project(":modules:common").tasks.named("sourcesJar") val configApiJar = project(":modules:features:config-api").tasks.named("jar") val configApiSources = project(":modules:features:config-api").tasks.named("sourcesJar") -val localizationApiJar = project(":modules:features:minecraft-localization-api").tasks.named("jar") -val localizationApiSources = project(":modules:features:minecraft-localization-api").tasks.named("sourcesJar") +val localizationApiJar = project(":modules:features:localization-api").tasks.named("jar") +val localizationApiSources = project(":modules:features:localization-api").tasks.named("sourcesJar") val localizationJar = project(":platforms:bukkit:localization").tasks.named("jar") val localizationSources = project(":platforms:bukkit:localization").tasks.named("sourcesJar") val apiJar = project(":modules:api").tasks.named("jar") @@ -471,10 +471,10 @@ tasks.named("check") { dependsOn(verifyBukkitLocalizationLoads) } val writeReleaseManifest = tasks.register("writeReleaseManifest") { group = "distribution" description = "Derives release catalog data, sidecars and checksums from verified packaged artifacts" - dependsOn(verifyEmbeddedMetadata, shadowUpdater) + dependsOn(verifyEmbeddedMetadata, shadowUpdater, "shadowUniversalFull") mustRunAfter("copyDeveloperArtifacts") val artifactNames = releasePlatforms.map { "pnLibrary-$pnVer-${it.id}.jar" } + - listOf("pnLibrary-updater-$pnVer.jar") + listOf("pnLibrary-$pnVer-universal-full.jar", "pnLibrary-updater-$pnVer.jar") val directory = layout.buildDirectory.dir("libs") inputs.files(artifactNames.map { directory.map { dir -> dir.file(it) } }) inputs.property("repository", rootProject.property("pnlibrary.repository").toString()) diff --git a/docs/actions.md b/docs/actions.md index afae7c43a..2dee3c6fd 100644 --- a/docs/actions.md +++ b/docs/actions.md @@ -1,153 +1,144 @@ -# Действия +# Сценарии: действия и требования -Действия делают что-то с игроком: пишут в чат, играют звук, выполняют команду. Они выполняются сверху вниз. Проверки («можно или нельзя») описаны отдельно, в [checks.md](checks.md). +Сценарий — список **действий** (`Action`) из конфига. Действие что-то делает, **требование** (`Requirement`) только отвечает «да» или «нет». -У каждого действия есть `type`, его настройки пишутся под ним: +## Действие и его итог -```yaml -join: - - type: message - message: Привет, %player_name% +Каждое действие возвращает `ActionResult`: - - type: title - title: Привет - subtitle: '%player_name%' - stay: 3s +| Итог | Что значит | Что дальше | +|---|---|---| +| `Done` | шаг выполнен | идёт следующий | +| `Stopped(reason)` | сценарий закончен нарочно, например требование не выполнено | список обрывается, ничего не откатывается | +| `Failed(code, message)` | шаг не смог | список обрывается, **откатываются** прошлые шаги (деньги возвращаются) | - - type: delay - duration: 2s - do: - - type: sound - sound: entity.player.levelup +Исключение внутри действия превращается в `Failed("action.error", ...)`. + +```kotlin +val result = module.actions.execute(config.onBuy, player, values = mapOf("item" to "diamond")) ``` -## Плейсхолдеры в тексте +## Типы действий -У каждого вида свои скобки, поэтому по записи видно, откуда значение: +`message`, `actionbar`, `title`, `sound`, `command`, `log`, `effect`, `particle` — вывод и команды. +`delay`, `repeat` — отложенное и повторяющееся (отдельные сценарии, ошибка там пишется в лог). +`if`, `require`, `attempt`, `stop` — управление. +`charge`, `give` — деньги. -| Запись | Откуда берётся | -|---|---| -| `[имя]` | значение, которое плагин передал в действие или выставил по ходу выполнения | -| `{имя}` | плейсхолдер pnLibrary: плагина, общий библиотеки | -| `{плагин:ключ}` | плейсхолдер другого плагина (нужен доступ, который разрешил владелец) | -| `%имя%` | PlaceholderAPI, и только он | +## Требования -`player` и `player_name` — всегда ник игрока. Неизвестное имя остаётся в тексте как написано, чтобы опечатка была видна. -Результат подстановки второй раз не читается. Если в YAML строка начинается со скобки, возьмите её в кавычки. +`permission`, `compare`, `chance`, `item`, `experience`, `near`, `all`, `any`, `not`, плюс `balance` для денег. +`compare` берёт любые значения: `[значение сценария]`, `{плейсхолдер pnLibrary}`, `%внешний%`, обычное число. -### Форматирование +## Деньги и ошибки -После `|` идёт цепочка форматов, она применяется слева направо; аргументы — после `:` через запятую: -`{money|group}`, `[hp|number:1]`, `{online|plural:игрок,игрока,игроков}`, `{rank|default:нет|upper}`. +`charge` списывает деньги и регистрирует откат. Если следующий шаг упал, деньги вернутся сами. +`attempt` ловит ошибку, откатывает свой блок и показывает сообщение через `{error}` и `{error_code}`. -| Формат | Что делает | -|---|---| -| `upper`, `lower`, `capitalize`, `trim` | регистр и пробелы | -| `default:текст` | подставляет `текст`, если значения нет или оно пустое | -| `boolean:да,нет` | `true` даёт первое, остальное второе | -| `plural:яблоко,яблока,яблок` | склонение по числу | -| `duration` | секунды в вид `1d 2h 3m 4s` | -| `number:2` | число с двумя знаками после запятой | -| `group` | разряды: `1234567` → `1 234 567` | -| `short` | `1500` → `1.5k`, `2300000` → `2.3M` | +```yaml +on-buy: + - type: require + when: + type: compare + left: '%vault_eco_balance%' + operator: greater-or-equal + right: 100 + deny: + - { type: message, messages: ['&c{reason}'] } + - type: attempt + do: + - { type: charge, currency: money, amount: 100 } + - { type: command, command: 'give {player} diamond 1' } + fail: + - { type: message, messages: ['&cНе вышло: {error}'] } +``` -Неизвестный формат оставляет значение как есть. +Коды ошибок денег: `currency.insufficient-funds`, `currency.unavailable`, `currency.unsupported`, `currency.invalid-amount`, `currency.rejected`, `currency.failed`. -**Формат одного плейсхолдера.** Его описывают рядом с самим плейсхолдером, значение приходит уже нужного типа: +## Свои действия и требования ```kotlin -placeholders.register("rating") { - it.resolve { 3 } - .format("bar") { value, arguments, _ -> arguments.getOrElse(0) { "★" }.repeat(value) } -} +val greet = Action { ctx -> ctx.player.sendMessage(Component.text("Привет")); ActionResult.Done } +val vip = Requirement { ctx -> Verdict.of(ctx.player.hasPermission("vip"), "только для VIP") } ``` -Теперь `{rating|bar}` даёт `★★★`, а `{rating|bar:#}` — `###`. Такой формат понимает только этот плейсхолдер и главнее -одноимённого общего. Если в цепочке перед ним значение уже стало текстом, формат пропускается. +## Расширение: куда и как регистрировать -**Общий формат** (для всех значений типа в плагине): `placeholders.formatter("stars", Number::class.java) { ... }`. -Имя формата — строчные буквы, цифры, `_` и `-`. +Слово действия или требования добавляется одним механизмом `configs.type().name("my")`. Область задаётся через `into(...)`: -## Действия +| Вызов | Где слово работает | +|---|---| +| без `into` | в конфигах своего модуля | +| `.into(plugin)` или `.into("quests")` | во всех файлах плагина | +| `.into("quests/main")` | в одном модуле | +| `.into("quests/main:quests.yml")` или `.into(config)` | в одном файле | +| `.everywhere()` | во всех плагинах (на всю библиотеку) | +| `.registerEach(listOf(a, b))` | в нескольких местах сразу, при ошибке откатывается всё | -| `type` | Что делает | Настройки | -|---|---|---| -| `message` | сообщение игроку | `message` (строка) или `messages` (список), `target: ALL_PLAYERS` — всем | -| `actionbar` | текст над панелью предметов | `text` | -| `title` | большой заголовок | `title`, `subtitle`, `fade-in`, `stay`, `fade-out` | -| `sound` | звук | `sound` (`entity.villager.no` или `ENTITY_VILLAGER_NO`), `volume`, `pitch` | -| `console` | команда от консоли | `command` без `/` | -| `player` | команда от игрока | `command` без `/` | -| `log` | запись в журнал сервера | `text`, `level` | -| `effect` | эффект зелья | см. `EffectAction` | -| `particle` | частицы | см. `ParticleAction` | -| `run` | выполнить именованный шаблон | `name` | -| `stop` | остановить всю цепочку | нет | - -## Обёртки - -Обёртка управляет действиями, которые лежат у неё в `do:`: когда они выполнятся, с каким шансом, при каком условии и сколько раз. Обёртки вкладываются друг в друга. - -| `type` | Настройки | Что делает | -|---|---|---| -| `delay` | `duration`, `do` | выполняет `do` после паузы; без `do` — ставит на паузу всё, что ниже | -| `chance` | `probability` (`10%`), `do`, `else` | выполняет `do` с шансом, иначе `else` | -| `if` | `check`, `do`, `else` | выполняет `do`, если проверка прошла, иначе `else`; список дальше идёт в любом случае | -| `require` | `check`, `deny` | если проверка не прошла — выполняет отказ и **останавливает** цепочку | -| `repeat` | `times`, `every`, `do` | выполняет `do` `times` раз (до 1000), первый раз сразу | -| `group` | `do` | собирает несколько действий в одно | +Конфликты имён: `.onConflict(ConfigTypeConflict.FAIL)` (по умолчанию, ошибка), `KEEP` (оставить старое, не регистрировать), `REPLACE` (заменить своё и то, у чего приоритет ниже). Слова самой библиотеки и слова плагина-хозяина файла чужие плагины перебить не могут, при равных словах решает `.priority(n)`. Снятие: закрыть `ConfigTypeRegistration`, оно закрывается и вместе с владельцем. + +Сервисы для своих действий: зарегистрируйте их в `module.services`, они доступны из `ctx.service(Type::class.java)`. + +## Выражения: математика и логика + +Требование `expression` и текст `{= ... }` считают что угодно: числа, строки, права, плейсхолдеры. ```yaml -buy: - - type: require # «нет» → отказ проверки и стоп - check: has-100 - - type: console - command: give %player_name% diamond 1 - - type: if # «нет» → else, дальше идём - check: vip - do: - - type: message - message: Бонус VIP - else: - - type: message - message: Купите VIP - - type: chance - probability: 10% - do: - - type: message - message: Вам повезло! - - type: repeat - times: 3 - every: 1s - do: - - type: sound - sound: block.note_block.pling +when: + type: expression + expression: "level() >= 10 && (permission('shop.vip') || {shop:discount} > 20) && chance(0.5)" ``` -`check:` принимает имя проверки из блока `checks:` или проверку прямо на месте (`type: permission` и т. д.). Подробно — в [checks.md](checks.md). - -## Шаблоны +```yaml +- { type: set, name: price, expression: "round(base * (1 - {shop:discount} / 100), 2)" } +- { type: message, messages: ['Цена: {price}, уровень {= level() * 2}'] } +``` -Одинаковые куски описываются один раз и вызываются по имени: `type: run` с `name: refuse`. Шаблоны передаёт плагин. Неизвестное имя даёт предупреждение с подсказкой, зацикливание останавливается на 16 уровнях. +Значения: имя (`balance`) читает значение сценария, потом плейсхолдер pnLibrary; `{плагин:ключ}` — плейсхолдер, `%имя%` — внешний, `[имя-с-дефисом]` — значение сценария. +Операторы: `! -`, `^`, `* / %`, `+ -`, `< <= > >=`, `== !=`, `&&`, `||`, `условие ? a : b`. +Функции: `min max abs round floor ceil sqrt pow clamp random chance len upper lower contains startsWith endsWith has if permission level exp items distance`. +Свою функцию добавляет плагин: `module.actions.defineFunction("kills") { ctx, args -> ... }`, и в выражении пишут `kills() >= 100`. +Ошибка в тексте выражения видна при загрузке конфига, ошибка при расчёте даёт «не выполнено» с причиной. -## Ошибки в конфиге +## Свои именованные действия и требования -Ошибка говорит, где она и что не так, и подсказывает при опечатке. Действие строкой (`'[console] give …'`, как в DeluxeMenus) не принимается: ошибка показывает, как записать его через `type`: +```kotlin +module.actions.define("give-kit") { ctx -> kits.give(ctx.player, ctx.format("{kit}")); ActionResult.Done } +module.actions.defineRequirement("is-vip", Requirement { ctx -> Verdict.of(ctx.player.hasPermission("vip"), "только VIP") }) +``` +```yaml +- { type: call, name: give-kit, args: { kit: starter } } # args видны только внутри вызова +- { type: require, when: { type: ref, name: is-vip } } ``` -Invalid configuration value at buy[1]: An action is written with a 'type', not as a line of text. Write it as: -- type: console - command: give %player_name% apple + +`scope = DefinitionScope.LIBRARY` делает имя общим для всех плагинов (закрывайте handle при выключении плагина), `conflict = FAIL | KEEP | REPLACE` решает, что делать с занятым именем. Имя модуля перекрывает общее. + +## Ловить ошибки по типу + +`attempt` умеет разные реакции на коды ошибок: + +```yaml +- type: attempt + do: [ { type: charge, currency: money, amount: 100 } ] + on: + - codes: [currency.insufficient-funds] + do: [ { type: message, messages: ['&cНужно 100 монет'] } ] + - codes: ['currency.*'] + do: [ { type: message, messages: ['&cБанк не отвечает'] } ] + fail: [ { type: message, messages: ['&cОшибка: {error}'] } ] ``` -## Из кода +Ещё: `set` (запомнить значение), `random` (выбор с весами). -```kotlin -class ShopConfig( - val checks: Map = emptyMap(), - val buy: List = emptyList(), -) +## Откат в конфиге -val context = module.actions.context(player, allPlayers, templates = config.templates, checks = config.checks) -context.execute(config.buy) +Откат можно выключить прямо в конфиге: `undo: false` у `attempt` (блок ничего не откатывает) или у `charge` / `give` (эта операция не откатывается). + +```yaml +- type: attempt + undo: false # деньги и всё остальное внутри останутся, даже если шаг упал + do: [ { type: charge, currency: money, amount: 100 }, { type: command, command: 'risky' } ] + fail: [ { type: message, messages: ['&cОшибка'] } ] +- { type: charge, currency: money, amount: 50, undo: false } # только эта операция не откатится ``` diff --git a/docs/api2-draft.md b/docs/api2-draft.md index 62dff8f94..8772b241b 100644 --- a/docs/api2-draft.md +++ b/docs/api2-draft.md @@ -117,8 +117,8 @@ PlaceholderAPI не публикуется, и ничего случайного ### Общий прогон текста Одна точка `render(text, player)`: сначала наши `{pnclans/war:score}`, затем оставшиеся `%...%` отдаются -PlaceholderAPI, если он установлен, всё нерешённое остаётся как есть. Нужен адаптер PlaceholderAPI для Bukkit -(в коде платформ его пока нет). +PlaceholderAPI, если он установлен, всё нерешённое остаётся как есть. Адаптер PlaceholderAPI для Bukkit уже есть +(`PlaceholderApiIntegration`). Что сейчас адресуется и как (находки по коду): diff --git a/docs/architecture.md b/docs/architecture.md index da7da5f2d..dcb92a98e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -13,12 +13,14 @@ modules/api, modules/common, features/*-api публичный контра platforms/*/api контракты конкретной платформы (меню, предметы, ...) ▲ │ реализует -modules/core ──────────► modules/runtime-spi рантайм: обновления, журнал, команды, метрики, отчёты +modules/core + внутренние модули ► modules/spi + рантайм: команды, метрики, отчёты, сборка частей; + updates вынесен в свои модули ▲ ▲ │ │ реализует platforms/*/runtime адаптеры платформ: команды, задачи, логи, игроки ▲ -distribution итоговые jar-файлы, в том числе universal +distribution итоговые jar-файлы: bukkit, bungeecord, velocity, universal, universal-full ``` Плагин видит только интерфейсы и модели. Где лежит реализация, он не знает, и она может меняться, не ломая его. @@ -77,8 +79,8 @@ Velocity требует 17, Paper Brigadier и FastStats для Velocity тре |---|---| | `modules/common` | общие помощники JVM: `AtomicFiles`, `Digests`, `RussianText`, версии Minecraft и Java | | `modules/api` | публичный API: команды, задачи, события, конфиги, обновления, диагностика, метрики, чат | -| `modules/runtime-spi` | контракт адаптера платформы и общие части адаптеров | -| `modules/core` | реализация рантайма | +| `modules/spi` | контракт адаптера платформы и общие части адаптеров | +| `modules/core` | реализация рантайма; внутри крупные пакеты разложены по подпапкам: `menu` (`data`, `screens`, `style`), `link` (`wire`, `remote`, `report`), `placeholders` (`entries`, `formatters`, `builtin`), `downloads` (`fetch`, `settings`, `dependencies`), `upload` | | `modules/updates` | обновления: каталог релизов, выбор версий, установка, откат; от `core` не зависит, `core` подключает её и передаёт тему консоли | | `modules/console` | карточки и деревья для консоли (Java, без зависимостей) | | `modules/features/config-*` | типизированные YAML-конфиги: API и реализация, см. [configuration.md](configuration.md) | @@ -88,6 +90,7 @@ Velocity требует 17, Paper Brigadier и FastStats для Velocity тре | `platforms/bukkit/runtime` | адаптер Bukkit, Spigot, Paper и Folia и реализации контрактов выше | | `platforms/bukkit/paper` | регистрация команд через Brigadier на Paper (Java 21) | | `platforms/bukkit/localization` | реализация `minecraft-localization-api` для Bukkit: перевод и поиск материалов, зачарований, существ и т.д. (`BukkitLocaleTranslations`); входит в Bukkit- и universal-JAR, плагинам подключается как `compileOnly` | +| `platforms/loader` | Java 8 загрузчик: при старте скачивает Kotlin и Adventure (Libby) для лёгкого `universal`, при `universal-full` ничего не качает | | `modules/bootstrap` | общая часть встраиваемого установщика: версии, релиз GitHub, проверка и установка `universal.jar` | | `platforms/*/bootstrap` | вход установщика для Bukkit, BungeeCord и Velocity: плагин сам ставит pnLibrary и проверяет версию | | `platforms/bungee/api`, `platforms/velocity/api` | доступ к прокси-серверу платформы | @@ -98,33 +101,53 @@ Velocity требует 17, Paper Brigadier и FastStats для Velocity тре | `tools/release`, `tools/api`, `tools/ci` | скрипты, которые запускает CI: выпуск релиза, проверка поколения API, подготовка нативных сборок | | `tools/support` | `decode_pnsupport.py`: расшифровка отчётов `/pn debug` | +## Папка данных + +Состояние библиотеки лежит в одной папке `plugins/pnLibrary/data/`. Рядом с ней остаются только то, что правит администратор +(`localization/`), `link.key` и серверная папка `plugins/update`; настройки библиотеки лежат в `data/settings.json`. В корне папки пишутся три справки для администратора (`Помощь.txt`, `Настройки.txt`, `Команды.txt`), их текст живёт в коде. Все пути задаёт один класс +`LibraryPaths` (пакет `updates.layout`, модуль `updates`: его видят и `updates`, и `core`). + +``` +data/ + updates/ каталог, события, транзакции, копии, preferences.json (каналы, автозагрузка, паузы), install.lock + journal/ журнал сервера + history/ task-history.tsv, event-history.tsv + reports/ отчёты поддержки + observability/ observations.jsonl, attachments/ + diagnostics/history/ + downloads/ состояние скачивания + upload-ledger.json +``` + +Каналы, автозагрузку и паузы хранит один файл `preferences.json` (`UpdatePreferencesStore`): одна блокировка и одна модель +в памяти, каждый владелец (`UpdatePolicyOverrides`, `FreezeStore`) меняет только свой раздел. `LegacyLayoutMigration` при старте +(и перед офлайн-установщиком) переносит состояние старых версий в `data/`, ничего не перезаписывая, и сливает старые +`settings.json` и `freezes.json` в `preferences.json`. + ## Пакеты `core` | Пакет | За что отвечает | |---|---| -| `core.runtime` | запуск рантайма (`PnLibraryLauncher`), жизненный цикл, `config.yml`, часовой пояс | +| `core.runtime` | запуск рантайма (`PnLibraryLauncher`, корень сборки `PnLibraryImpl`), жизненный цикл, часовой пояс | +| `core.settings` | настройки библиотеки: один реестр `SettingsRegistry` (ключ, тип, границы, описание), хранилище `SettingsStore` (`data/settings.json`), разовый перенос старых `config.yml` и `downloads.yml`; `LibraryInfoFiles` каждый запуск (и каждое изменение настройки) заново пишет `Помощь.txt`, `Настройки.txt` и `Команды.txt` из реестра настроек, единого списка команд и прав `LibraryCommandGuide` и текущих ссылок, файл переписывается только если изменился текст, сбой записи не мешает запуску; команда `/pn settings` и страница меню читают этот реестр, см. [settings.md](settings.md) | | `core.commands` | дерево команд, разбор аргументов, пять уровней ответа на ошибки | | `core.commands.events`, `.tasks`, `.groups`, `.proxy` | команды `/pn bus`, `/pn tasks`, группы серверов, `/pn servers` и управление прокси | | `core.menu` | меню `/pn gui`, платформенно-нейтральное; данные берёт у `MenuData` (свои или чужого сервера по связи) | -| `core.link` | связь серверов через плагин-сообщения: подпись, доклады, запросы данных, удалённые действия | +| `core.link` (модуль `link`) | связь серверов через плагин-сообщения: подпись, доклады, запросы данных, удалённые действия | | `core.stats` | счётчики сервера для `/pn stats` и меню | -| `core.journal` | журнал событий `/pn events` и сводка ошибок при входе | +| `core.journal` (модуль `journal`) | журнал событий `/pn events` и сводка ошибок при входе | | `core.observability`, `core.diagnostics`, `core.logging` | «чёрный ящик», отчёты для поддержки, логи | | `core.upload` | загрузка зашифрованных отчётов | -| `core.updates.catalog` | страницы и команды каталога обновлений | -| `core.updates.service` | сервис обновлений и оркестратор | -| `core.updates.policy` | `updates.yml`, каналы, автозагрузка, переопределения | -| `core.updates.install` | подбор версий, подготовка, установка, офлайн-установщик | -| `core.updates.history` | журнал обновлений, состояние, снимки конфигов | -| `core.updates.engine` | каталоги релизов, загрузка, проверка, транзакции, пауза | +| `updates.*` (модуль `updates`; `layout` пути и перенос старой папки) и `core.updates.catalog` (в `core`) | `core.updates.catalog` команды и страницы; `service` сервис обновлений, `policy` каналы и автозагрузка, `install` подбор версий и установка, `history` журнал и снимки, `engine` каталоги, загрузка, проверка, транзакции, `databases` копии баз данных | | `core.downloads` | загрузка зависимостей плагинов | | `core.metrics` | bStats и FastStats за одним `MetricsService` | | `core.plugin` | регистрация плагинов и модулей | | `core.plugin.module` | сборка модуля: ресурсы, метаданные, зависимости, расширения | | `core.remote` | политики | -| `core.placeholders`, `core.events`, `core.tasks`, `core.cooldowns`, `core.services`, `core.audiences`, `core.text` | реализации одноимённых сервисов API | +| `core.placeholders`, `core.events` (свои модули), `core.tasks`, `core.services`, `core.text`, `core.expansions` | реализации одноимённых сервисов API | | `core.ui` | цвета палитры для консоли | -| `core.io`, `core.security`, `core.lifecycle` | текстовые файлы, шифрование, очистка ресурсов | +| `core.cleanup`, `core.lifecycle` | очистка ресурсов, связь рантайма с ресурсами (шифрование отчётов — `core.observability.report`) | +| `core.proxy` | сборка связи с прокси (`ProxyLink`) | ## Сообщения diff --git a/docs/checks.md b/docs/checks.md deleted file mode 100644 index 15efb14e7..000000000 --- a/docs/checks.md +++ /dev/null @@ -1,130 +0,0 @@ -# Проверки - -Проверка отвечает на вопрос «можно или нельзя» и ничего не меняет. Проверки живут отдельно от действий: их можно спросить из кода, из меню, из команды или вызвать из списка действий. - -## Где пишутся - -Проверки описываются в блоке `checks:` с именами. У каждой есть `check` (само условие), `deny` (что сделать при «нет») и `success` (что сделать при «да»). `deny` и `success` необязательны и содержат обычные действия. - -```yaml -checks: - has-100: - check: - type: '>=' - input: '%vault_eco_balance%' - output: 100 - deny: - - type: message - message: '&cНужно 100 монет' - - vip: - check: - type: permission - permission: group.vip -``` - -## Как вызвать из действий - -| Запись | При «да» | При «нет» | -|---|---|---| -| `type: require`, `check: имя` | выполняется `success`, дальше идём | выполняется `deny`, цепочка **останавливается** | -| `type: if`, `check: имя`, `do`, `else` | выполняется `do` | выполняется `else`, дальше идём | - -`if` только спрашивает: `deny` и `success` проверки не выполняются. `require` выполняет их. - -Вместо имени можно написать проверку на месте: - -```yaml -- type: require - check: - type: permission - permission: shop.use - deny: - - type: message - message: Нет доступа -``` - -## Типы - -| `type` | Настройки | -|---|---| -| `permission` (`has permission`) | `permission` | -| `has permissions` | `permissions`, `minimum` | -| `has item` | `material`, `amount`, `name`, `name_contains`, `lore_contains` | -| `has exp` | `amount`, `level` | -| `is near` | `location` (`world,x,y,z`), `distance` | -| `==`, `!=`, `>=`, `<=`, `>`, `<` | `input`, `output` — сравнение чисел | -| `string equals`, `string equals ignorecase`, `string contains` | `input`, `output` | -| `string length` | `input`, `min`, `max` | -| `regex matches` | `input`, `regex` | -| `is object` | `input`, `object` (`INT`, `DOUBLE`, `UUID`) | -| `chance` | `probability` (`25%` или `0.25`) | - -`!` перед типом переворачивает ответ: `type: '!has permission'`. - -## Сочетания - -Сочетания — тоже проверки, их можно вкладывать. В списке `checks` можно писать и имена из блока `checks:`. - -```yaml -# все сразу -type: all -checks: - - type: permission - permission: shop.use - - type: not - check: - type: permission - permission: shop.banned - -# любая -type: any -checks: - - type: permission - permission: group.admin - - type: permission - permission: group.moderator - -# не меньше двух из трёх -type: at-least -count: 2 -checks: - - vip - - has-100 - - type: '>=' - input: '%player_level%' - output: 30 -``` - -## Запись DeluxeMenus - -Ключи блока как в DeluxeMenus: `requirements`, `optional`, `minimum_requirements`, `stop_at_success`, `deny_commands`, `success_commands`. Действия внутри пишутся через `type`, как везде. - -```yaml -checks: - veteran: - requirements: - level: - type: '>=' - input: '%player_level%' - output: 30 - optional: true - vip: - type: has permission - permission: group.vip - optional: true - minimum_requirements: 1 - deny_commands: - - type: message - message: '&7Нужен 30 уровень или VIP' -``` - -Старое действие `type: requirements` с таким блоком тоже работает и означает `require`. - -## Из кода - -```kotlin -val context = module.actions.context(player, allPlayers, checks = config.checks) -val hasMoney: Boolean = config.checks.getValue("has-100").check(context) // только ответ -val allowed: Boolean = config.checks.getValue("can-trade").test(context) // ответ и deny/success -``` diff --git a/docs/commands.md b/docs/commands.md index 1bedd1991..16676a9fd 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -4,6 +4,8 @@ `plugin.yml` не нужно: pnLibrary делает это сама. На современном Paper команда регистрируется ещё и через родную систему Brigadier, и клиент сам проверяет аргументы и подсказывает. +Команды самой библиотеки (`/pn …`) описаны не здесь: их полный список с правами библиотека пишет в `plugins/pnLibrary/Команды.txt`. + Этот файл самодостаточный: сначала идея, потом полный рабочий пример, потом справочник. ## 1. Идея в одном абзаце @@ -11,7 +13,7 @@ Вы описываете дерево команды: слова (`literal`) и аргументы (`argument`) с типами. Если игрок ввёл что-то не так, у него нет права, он не в сети, или ваша команда сама решила, что продолжать нельзя, возникает **ошибка**. Ошибка это обычный класс (`CommandError`). Вы подписываетесь на **тип** ошибки и отвечаете как хотите: текстом, звуком, action bar, -записью в лог. Если вы не ответили, отвечает стандарт библиотеки из `config.yml`. +записью в лог. Если вы не ответили, отвечает стандарт библиотеки (текст `no-permission-message` в `/pn settings`). ## 2. Полный пример @@ -27,16 +29,16 @@ import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.NamedTextColor import org.bukkit.Bukkit import org.bukkit.plugin.java.JavaPlugin -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.commands.ArgumentType -import org.pnfolder.pnlibrary.api.commands.BadUsage +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.error.BadUsage import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandError +import org.pnfolder.pnlibrary.api.commands.error.CommandError import org.pnfolder.pnlibrary.api.commands.CommandRegistration -import org.pnfolder.pnlibrary.api.commands.InvalidArgument -import org.pnfolder.pnlibrary.api.commands.NoPermission -import org.pnfolder.pnlibrary.api.commands.PlayerNotFound -import org.pnfolder.pnlibrary.api.commands.ensure +import org.pnfolder.pnlibrary.api.commands.error.InvalidArgument +import org.pnfolder.pnlibrary.api.commands.error.NoPermission +import org.pnfolder.pnlibrary.api.commands.error.PlayerNotFound +import org.pnfolder.pnlibrary.api.commands.error.ensure import org.pnfolder.pnlibrary.api.plugin.onCommandError import org.pnfolder.pnlibrary.api.runtime.PnLibraryProvider import java.util.UUID @@ -185,8 +187,8 @@ class ShopExamplePlugin : JavaPlugin() { | `/shop` без права `shop.use` | `NoPermission` | плагин: «[Магазин] У вас нет доступа…» | | `/shop buy bow` без права `shop.vip` (проверка в коде) | `NoPermission` | плагин: «[Магазин] У вас нет доступа…» | | `/shop buy bow 5` и не хватает денег | `NoMoney` (своя ошибка) | модуль: «Не хватает монет: нужно 175.» | -| консоль: `/shop buy sword` | `PlayerOnly` | стандарт библиотеки из `config.yml` | -| игрок: `/shop reload` | `ConsoleOnly` | стандарт библиотеки из `config.yml` | +| консоль: `/shop buy sword` | `PlayerOnly` | стандарт библиотеки | +| игрок: `/shop reload` | `ConsoleOnly` | стандарт библиотеки | ## 3. Пять уровней ответа @@ -196,7 +198,7 @@ class ShopExamplePlugin : JavaPlugin() { 2. **Команда**: `registerCommand("shop") { onError("…") }` 3. **Модуль плагина**: `module.onCommandError { … }` 4. **Весь плагин**: `registration.onCommandError { … }` -5. **Библиотека**: стандартные тексты и звук в `config.yml` +5. **Библиотека**: стандартные тексты и звук в коде библиотеки На одном уровне обработчик ближайшего класса побеждает: `InvalidArgument` отвечает раньше, чем `BadUsage`. Обработчик на подкоманде действует и на всё, что ниже неё. Ошибка в вашем обработчике пишется в лог и в журнал, а @@ -329,10 +331,10 @@ if (item == "bow") { ## 10. Стандарт библиотеки -В `config.yml` настраивается один текст: +Администратор настраивает один текст, командой или в меню (см. [settings.md](settings.md)): -```yaml -no-permission-message: Недостаточно прав для этой команды. +``` +/pn settings set no-permission-message Недостаточно прав для этой команды. ``` Остальные стандартные ответы («Использование», «Неверное значение», «Игрок не в сети», «Только в игре», «Только из консоли», diff --git a/docs/configuration.md b/docs/configuration.md index 0baa947f5..aad5fbfef 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -29,15 +29,15 @@ val config = context.configs.yaml("settings.yml") { Settings() } val settings = config.load().value // создаёт файл при первом запуске ``` -Дальше: `config.value` — текущее значение, `config.reload()` — перечитать файл, `config.save()` — записать. +Дальше: `config.get()` — текущее значение, `config.reload()` — перечитать файл, `config.save()` — записать, `config.update { … }` — изменить и сохранить. -Из Java используйте `scope.yaml(path, Settings.class, Settings::new)`. +`context.configs` — это `ConfigScope` модуля. Из Java используйте `scope.yaml(path, Settings.class, Settings::new)`. ## Проверка значений Работают два способа, их проблемы складываются в один `ConfigValidationException`: -1. **Аннотации** на полях: `@ConfigRange`, `@ConfigNotBlank`, `@ConfigPattern`, `@ConfigRequired`. +1. **Аннотации** на полях: `@ConfigRange`, `@ConfigNotBlank`, `@ConfigPattern`, `@ConfigRequired`. Остальные аннотации: `@ConfigComment`, `@ConfigKey`, `@ConfigIgnore`, `@ConfigAlias`, `@ConfigNewLine`, `@ConfigOrder`, `@ConfigDefaultOnInvalid`, `@ConfigSerializeWith`, `@ConfigPolymorphic`. 2. **Программные правила** для условий, которые аннотациями не выразить: ```kotlin @@ -57,8 +57,8 @@ val config = scope.yaml("settings.yml", ConfigOptions.DEFAULT, validator) { Sett | `unknownValues` | Что делать с ключами, которых нет в модели (по умолчанию оставить). | | `comments` | Синхронизация комментариев из кода. | | `backups` | Делать ли резервную копию перед перезаписью. | -| `migrations` | Версионная цепочка миграций `ConfigMigrationPlan`. По умолчанию `ConfigMigrationPlan.INITIAL`. | -| `naming` | Преобразование имён полей в ключи YAML, например `KEBAB_CASE`. | +| `migrations` | Версионная цепочка миграций `ConfigMigrationPlan`. По умолчанию `ConfigSteps.NONE`; `withoutVersion()` отключает маркер. | +| `naming` | Преобразование имён полей в ключи YAML: `AS_DECLARED`, `CAMEL_CASE`, `SNAKE_CASE`, `KEBAB_CASE`, `UPPER_SNAKE_CASE`. | Явное имя ключа задаёт `@ConfigKey` и всегда сильнее `naming`. @@ -106,12 +106,214 @@ val config = scope.yaml("shop.yml", ConfigOptions.builder().migrations(ShopSteps Реализацию базового типа публикует билдер. Ничего не публикуется, пока не вызван `register()`: ```kotlin -val registration = scope.type() - .name("message") - .alias("msg") +val registration = module.configs.type() + .name("item") + .alias("items") .priority(10) - .access(ConfigTypeAccess.everyone()) + .into("shop/main") // куда добавляем слово .register() ``` -Без `access` тип виден только владельцу. Закрытие `registration` убирает тип. +Регистрация живёт и умирает вместе с модулем того, кто её сделал. Закрытие `registration` убирает слово. + +### Куда добавляется слово (`into`) + +Адрес везде один: `ConfigAddress`. Его не надо писать строкой, он собирается из частей (плагин → модуль → файл): + +```kotlin +val shop = ConfigAddress.plugin("shop") // весь плагин +val main = shop.inModule("main") // один модуль плагина +val rewards = main.inFile("rewards.yml") // один файл +val bukkit = main.inFile("bukkit.yml", ConfigRoot.SERVER) // файл из другого корня + +module.configs.type().name("item").into(main).register() +``` + +Что принимает `into` (одно и то же у слов типов и у сериализаторов): + +| Что передать | Охват | +| --- | --- | +| ничего | только свои конфиги модуля | +| `PluginId` или `ConfigAddress.plugin("shop")` | все конфиги плагина | +| `ConfigScope` другого модуля (`otherModule.configs`) | все файлы этого модуля | +| `ConfigAddress.plugin("shop").inModule("main")` | один модуль | +| `ManagedConfig` или `ConfigInfo` из каталога | один файл | +| `ConfigAddress…inFile("rewards.yml")` | один файл по пути | +| `.everywhere()` | все файлы всех плагинов | + +Строка (`"shop"`, `"shop/main"`, `"shop/main:rewards.yml"`, `"*"`) осталась короткой записью для команд и конфигов; в коде +берите объекты. Найти нужное можно в каталоге: `library.configurations.all()` даёт `ConfigInfo` с `address` и `moduleAddress`, +`library.plugins` даёт список плагинов. + +Слово становится понятно хозяину конфига сразу: ожидающие конфиги перечитываются при регистрации. При закрытии типа +перечитывания нет, значение уйдёт при следующем `reload`. + +### Защита + +- слова, объявленные у базового типа аннотацией `@ConfigTypes`, и слова плагина-хозяина файла занять нельзя; +- хозяин файла решает, кому можно расширять его конфиги: `module.configs.extensions { allow("partner"); deny("evil") }` + или `denyAll()` (правила те же, что у плейсхолдеров и валют: класс `PluginAccess`). По умолчанию открыто; +- `ConfigOptions.unknownTypes`: `FAIL` (ошибка, по умолчанию) или `SKIP`. При `SKIP` элемент списка с незнакомым `type` + пропускается, но остаётся в файле. Пока есть пропущенные, `save`, `update` и `resetToDefaults` заблокированы, чтобы не + затереть чужие записи. Появится тип, файл перечитается сам. + +### Сериализаторы в чужих файлах + +Сериализатор типа можно добавить так же, как слово: по тому же адресу (`*`, плагин, модуль, файл). + +```kotlin +// только в этом модуле (как раньше) +module.configs.serializer(PointSerializer()) + +// в чужих файлах +val shop = ConfigAddress.plugin("shop") +module.configs.serializerFor(PointSerializer()).into(shop).register() // весь плагин +module.configs.serializerFor(PointSerializer()).into(shop.inModule("main").inFile("places.yml")).register() // один файл +module.configs.serializerFor(PointSerializer()).priority(5).everywhere().register() // везде + +library.configurations.serializers() // что добавлено и кем +``` + +Правила: +- у файла свой модуль главнее: его собственные сериализаторы (и `@ConfigSerializeWith`) не заменяются, добавление закрывает + только то, для чего у модуля сериализатора нет; среди добавлений выигрывает большее `priority`; +- хозяин решает, кому можно: `module.configs.extensions { allow(...); deny(...) }` действует и на сериализаторы. Для адреса + плагина или модуля отказ даёт ошибку регистрации, для `*` модуль с отказом просто пропускается; +- для чужих файлов нельзя брать примитивы и типы из `java.`, `javax.`, `kotlin.`, `jdk.` (иначе можно подменить чтение обычных + значений); в своём модуле можно любые; +- закрытие `registration` или модуля убирает сериализатор. Уже прочитанные файлы держат значение до следующего `reload`. + +Слово полиморфного типа тоже принимает `*`: `.into("*")` или `.everywhere()`. Слово плагина-хозяина файла при этом не +затеняется: в его файле действует его значение. + +## Адреса и каталог конфигов + +Каждый файл имеет идентификатор `плагин/модуль:путь`, например `shop/main:rewards.yml`. Разбор: `ConfigId.parse`, +`ConfigAddress.parse` (адрес может быть неполным: `shop`, `shop/main`). + +```kotlin +library.configurations.all() // List +library.configurations.get(id) // ManagedConfig? +library.configurations.find("shop/main") // List по адресу +library.configurations.byModel(Rewards::class.java) // все файлы с такой моделью +library.configurations.types(Reward::class.java) // слова полиморфного типа и кто их добавил +library.plugins.requireById("shop").configs() // файлы плагина +module.configs.list() // файлы своего модуля +``` + +`ConfigInfo` не содержит значений, поэтому секреты через него не утекают. + +## Файлы вне папки плагина + +`ConfigOptions.builder().root(...)` выбирает корень пути: + +| Корень | Где | В ID | +| --- | --- | --- | +| `PLUGIN` | папка плагина (по умолчанию) | `shop/main:rewards.yml` | +| `PLUGINS` | папка `plugins` | `shop/main:@plugins/Other/config.yml` | +| `EXTERNAL` | любой абсолютный путь (`yamlAt`) | `shop/main:@external/D:/data/x.yml` | +| `SERVER` | корень сервера | `shop/main:@server/bukkit.yml` | + +Для чужих корней принудительно: файла нет → ошибка (не создаём), резервная копия включена, `REMOVE` заменяется на +`PRESERVE`. Выход за корень и символические ссылки наружу запрещены. Такие файлы не показываются диагностике. + +### Файл в любом месте + +Если файл лежит где угодно (другой диск, подключённая папка, путь взят из собственного конфига плагина), открывайте его по +абсолютному пути: + +```kotlin +val path = Path.of(settings.value.dataFile) // путь пришёл из вашего основного конфига +val data = module.configs.yamlAt(path) { DataFile() } +``` + +Это ваш файл: он создаётся, если его нет, и перезаписывается, ограничений чужих корней нет. ID: `плагин/модуль:@external/<путь>`. +Секреты (`@ConfigSecret`) скрываются в отчётах, как и в своей папке. Один физический файл пишет один конфиг, остальные +открывают его с `readOnly()`. Файлы на другой машине (SFTP, HTTP) не поддерживаются, нужна подключённая папка. + +`ConfigOptions.readOnly()`: файл только читается, ничего не пишется. Читателей одного файла может быть несколько, +писатель на физический файл только один. + +## Правка настроек в игре + +Поле, которое администратор может менять из игры, помечается `@ConfigEditable`: + +```kotlin +class ShopConfig { + @field:ConfigEditable("Магазин включён", "Можно ли покупать предметы.") + var enabled: Boolean = true + + @field:ConfigEditable("Размер пула", "Сколько соединений держать открытыми.", apply = ConfigApply.RESTART) + @field:ConfigRange(min = 1.0, max = 64.0) + var poolSize: Int = 10 + + @field:ConfigSecret + var token: String = "" // секреты в списке никогда не показываются +} +``` + +Поддерживаются boolean, целые и дробные числа, текст и enum; границы берутся из `@ConfigRange`. Значение проверяется так же, +как при записи файла, и при отказе файл не меняется. + +| `apply` | Когда настройка начинает работать | +| --- | --- | +| `LIVE` | сразу, плагин читает значение каждый раз | +| `RELOAD` | после перечитывания: плагин берёт значение в своём обработчике | +| `RESTART` | после перезапуска сервера | + +```kotlin +config.settings // настройки с текущими значениями +config.edit("pool-size", "20") // изменить и записать, вернёт старое и новое значение + +config.onChanged(Consumer { change -> cache.clear() }) // файл прочитан, записан или изменён +config.onReloadRequired(Consumer { request -> // изменили настройку с RELOAD или RESTART + if (request.apply == ConfigApply.RELOAD) pool.resize(config.value.poolSize) +}) +``` + +В обе функции можно передать несколько обработчиков; ошибка одного не мешает остальным. Пока изменения не заработали, +`ConfigInfo.pendingApply` показывает, чего они ждут; чтение файла снимает `RELOAD`, перезапуск — `RESTART`. + +В игре: `/pn gui` → «Конфигурации» (переключатель — клик, вариант — клик по кругу, число — левый и правый клик, текст — вводится +в чате) или команды `/pn configs settings ` и `/pn configs edit <путь> <значение>`. Менять может тот, у кого есть право +`pnlibrary.configs.edit`. + +## Команда `/pn configs` + +Право `pnlibrary.configs`, консоль проходит всегда. Значения из файлов команда не показывает. + +| Команда | Что делает | +| --- | --- | +| `/pn configs [страница]` | список файлов | +| `/pn configs info ` | где лежит, загружен ли, что пропущено, проблемы | +| `/pn configs reload ` | перечитать; при ошибке остаётся прежнее значение | +| `/pn configs validate ` | проверка без записи | +| `/pn configs types <тип>` | слова полиморфного типа и кто их добавил | +| `/pn configs settings ` | настройки файла, которые можно менять в игре | +| `/pn configs edit <путь> <значение>` | изменить настройку и сохранить файл (право `pnlibrary.configs.edit`) | + +## Секреты и отчёты поддержки + +Поле с паролем, токеном или вебхуком помечается `@field:ConfigSecret`: его значение скрывается в отчёте `/pn debug`, +отдельной записи в настройках библиотеки не нужно. Остальное из настроек библиотеки: `privacy` (по умолчанию выключено), см. [settings.md](settings.md). + +## Резервные копии баз данных + +Если плагин хранит данные в MySQL/MariaDB, PostgreSQL или MongoDB, их можно копировать перед обновлением плагина и +возвращать при откате. Это описывается аннотациями (`DatabaseKind`: `MYSQL`, `MONGODB`, `POSTGRESQL`): + +- `@BackupDatabase(kind, name, tables)` на поле с именем базы (или на поле-секции подключения, или на классе + конфигурации); повторяемая, имена баз в плагине различаются. В `tables` допустима маска `*` (`"log_*"`), пусто — все. +- `@DatabaseField(role, database)` связывает поля `host`, `port`, `database`, `user`, `password` с базой, если их имена + нестандартные (`DatabaseRole`). Пароль помечайте `@ConfigSecret`. +- `@BackupTable(database)` на поле с именем таблицы. + +```kotlin +@field:BackupDatabase(DatabaseKind.POSTGRESQL, "Clans", tables = ["clans", "clan_members"]) +var clansDb = "clans" +@field:DatabaseField(DatabaseRole.HOST, database = "Clans") +var clansHost = "pg.local" +``` + +Копируются только таблицы (коллекции в MongoDB); триггеры, процедуры и представления нет. Подробности и меню +копий: [updates.md](updates.md). diff --git a/docs/cooldowns.md b/docs/cooldowns.md new file mode 100644 index 000000000..29b120c7d --- /dev/null +++ b/docs/cooldowns.md @@ -0,0 +1,30 @@ +# Кулдауны + +`module.cooldowns` хранит паузы на пару «кто» (`UUID`) и «что» (имя действия). Время идёт по монотонным часам, не зависит +от смены системных часов и живёт, пока работает модуль. Имя действия сравнивается без регистра и пробелов по краям. + +```kotlin +val result = module.cooldowns.acquire(player.uniqueId, "kit", Duration.ofMinutes(10)) +if (!result.allowed) { + player.sendMessage("Подождите ещё ${result.remaining.seconds} с") + return +} +giveKit(player) +``` + +| Метод | Что делает | +|---|---| +| `acquire(кто, что, срок)` | атомарно включает паузу, если её нет; иначе отказ с остатком | +| `has`, `remaining` | есть ли пауза и сколько осталось | +| `set` | ставит срок (ноль снимает) | +| `extend` | продлевает от текущего срока или от сейчас | +| `reset` | снимает одну паузу | +| `active(кто)` | все действующие паузы игрока с остатком, самые долгие первыми | +| `clear(кто)` | снимает все паузы игрока, например при выходе; возвращает сколько снято | +| `clear()` | снимает все паузы модуля | +| `size` | сколько пауз действует сейчас | + +Просроченные записи удаляются по ходу работы (каждые 256 записей и при чтении), поэтому игрок, к которому больше не +обращаются, не копится в памяти. Закрытый сервис отвергает чтение и создание, а очистка остаётся безопасной. + +Паузы не сохраняются между запусками сервера. Нужна пауза, переживающая перезапуск, храните срок в своих данных. diff --git a/docs/currency.md b/docs/currency.md index 73ea9a826..a608d55eb 100644 --- a/docs/currency.md +++ b/docs/currency.md @@ -21,7 +21,7 @@ PlayerPoints. Мосты к Vault и PlayerPoints и команда `/pn money` ## 1. Взять валюту ```kotlin -val currencies = module.currencies // Java: CurrencyApi.from(module) +val currencies = module.currencies // import ...api.currency.currencies; Java: CurrencyApi.from(module) val money = currencies.require("vault:money") // Vault, если он установлен val coins = currencies.get("coins") // своя валюта по имени или псевдониму, либо null @@ -105,7 +105,7 @@ val coins = module.currencies.register("coins") { definition -> По умолчанию валюту видит только её владелец. Чтобы открыть доступ: ```kotlin -currency.access(CurrencyAccess.shared()) // всем плагинам pnLibrary +currency.access(PluginAccess.shared()) // всем плагинам pnLibrary currency.access { it.owner().allow("pnshop").allowMatching("pn*").deny("pnbeta") } ``` diff --git a/docs/dependencies.md b/docs/dependencies.md new file mode 100644 index 000000000..fecc7c90d --- /dev/null +++ b/docs/dependencies.md @@ -0,0 +1,95 @@ +# Зависимости плагина + +Плагин при регистрации говорит, какие другие плагины ему нужны. pnLibrary проверяет их при запуске и, если чего-то +не хватает, либо скачивает сама, либо показывает администратору, что и откуда взять. + +## Что можно указать + +```kotlin +plugin.depends( + ExternalPluginDependency.builder("Vault", "1.7.0") // имя плагина и минимальная версия + .title("Экономика") // короткое имя для людей + .description("Нужна для денег и магазинов.") // зачем она нужна + .artifact("https://example.org/Vault.jar", sha256 = "3c0e…") // прямая ссылка и сумма издателя + .mirror("https://mirror.example.org/Vault.jar") // запасной адрес того же файла + .downloadPage("https://example.org/vault") // страница, если автоскачивание не подходит + .required(true) // false: плагин запустится и без неё + .automaticDownload(true) // разрешить скачивать самой + .build(), +) +``` + +Короткая запись для простых случаев: `Dependencies.plugin("Vault", "1.7.0", "https://example.org/vault")` (страница, ручная +установка) и `Dependencies.plugin("Vault", "1.7.0", listOf("https://a.org/Vault.jar", "https://b.org/Vault.jar"))` +(несколько адресов без суммы). + +| Поле | Что значит | +|---|---| +| `title`, `description` | как зависимость называется и зачем нужна: попадают в сообщение администратору | +| `required` | обязательная (по умолчанию) или нет; в сообщении они разделены | +| `artifact`, `mirror` | откуда качать: первый адрес, потом запасные по очереди, сколько угодно | +| `sha256` | сумма издателя; после скачивания считается SHA-256 файла и сверяется с ней. Суммы нет: файл берётся с первой ссылки, которая ответила, ничего не сравнивается и не запоминается | +| `maxBytes` | наибольший размер этого файла в байтах; без него действует общий потолок 512 МБ, можно и уменьшить, и увеличить (до 2 ГБ). У варианта свой `maxBytes`, у общего файла `.maxBytes(...)` в билдере | +| `automaticDownload` | можно ли скачивать без команды администратора | +| `downloadPage` | куда идти, если файл нельзя скачать автоматически | + +Скачанный JAR ещё раз проверяется: имя плагина внутри и его версия должны совпасть с тем, что просили. + +## Три режима скачивания + +| Режим | Что значит | +|---|---| +| `MANUAL` | сами не качаем, только показываем карточку со ссылками (по умолчанию, когда нет прямой ссылки) | +| `AUTOMATIC` | качаем сами, пока администратор не выключил автозагрузку (по умолчанию, когда есть прямая ссылка) | +| `FORCED` | качаем сами, даже если автозагрузка выключена | + +Задаётся `downloadPolicy(...)`, `automaticDownload(true|false)` или `forceAutomaticDownload(true)`. + +## Разные файлы для разных серверов + +Если плагину нужен свой jar под платформу или версию Minecraft, добавьте варианты. У каждого свои ссылка, SHA-256 +и зеркала. Берётся первый подходящий этому серверу, и проверяется только его сумма: остальные файлы не скачиваются и не +сравниваются. Общий файл (`url` или `artifact`) остаётся запасным, если ни один вариант не подошёл. + +```kotlin +ExternalPluginDependency.builder("Vault", "1.7.0") + .variant("https://example.org/Vault-legacy.jar", "ab12…", minecraftBefore = "1.20", label = "для 1.19 и старше") + .variant("https://example.org/Vault-velocity.jar", "cd34…", platforms = setOf(PlatformType.VELOCITY)) + .variant("https://example.org/Vault-new.jar", "ef56…", minecraftFrom = "1.20", mirrors = listOf("https://mirror.example.org/Vault-new.jar")) + .downloadPage("https://example.org/vault") + .build() +``` + +| Параметр | Что значит | +|---|---| +| `platforms` | для каких платформ файл (пусто: для всех) | +| `minecraftFrom` | с какой версии Minecraft, включительно | +| `minecraftBefore` | до какой версии, не включая | +| `label` | название варианта, видно в карточке | + +Версия Minecraft известна только на сервере Bukkit/Paper; на прокси подходят варианты без ограничения по версии. Если ни один +вариант не подошёл, карточка пишет об этом и показывает страницу для ручной загрузки. + +## Что видит администратор + +Автоскачивание включено (`/pn deps auto on`, по умолчанию включено): библиотека качает файл сама, пишет в консоль, что +подготовлено, а плагины загружаются при следующем запуске. Сервер сама не перезапускает. + +Выключено, или у зависимости нет прямой ссылки: в консоль выходит карточка «НЕ ХВАТАЕТ ПЛАГИНОВ». В ней два списка, +**обязательные** и **необязательные**, у каждого плагина название, версия, описание, все ссылки и способ проверки файла. +Ниже код установки: `/pn deps install <код>` скачивает всё из этой карточки сразу, ввод кода и есть подтверждение. +`/pn deps` показывает то же самое в любой момент. + +То же есть в меню: **Настройки → «Недостающие плагины»** включает и выключает автозагрузку, **«Что не хватает»** показывает группы со +ссылками и скачивает группу кликом (нужно право на настройки). + +## Права + +`/pn deps` и экран меню «Что не хватает» требуют право `pnlibrary.deps` (в меню: право на настройки); консоль может всё. + +## Что пока не так + +- Свои плагины pnFolder как зависимость (`ManagedProductDependency`) ставятся через систему обновлений, а не через карточку + выше; сейчас она их сама не доустанавливает (`allowNewPlugins` выключен), блокируя обновление с причиной + «нужен такой-то продукт». +- Зеркала одного файла делят одну сумму; для разных файлов используйте варианты. diff --git a/docs/diagnostics.md b/docs/diagnostics.md index 5392209b8..2a027659c 100644 --- a/docs/diagnostics.md +++ b/docs/diagnostics.md @@ -24,9 +24,15 @@ DiagnosticRegistration reg = PnLibraryProvider.get().getDiagnostics().register(" - Уровень подробности задаёт `DiagnosticLevel`, запрос на отладку — `DebugRequest`. - Закройте `DiagnosticRegistration` при выключении плагина. +## Отчёт `/pn debug` + +Отчёт зашифрован, расшифровывает его поддержка (`tools/support/decode_pnsupport.py`). Настройка `privacy` +(`/pn settings set privacy true`, по умолчанию `false`) скрывает имена, UUID, адреса и пинг игроков. Значения в конфигах плагинов скрывает +аннотация `@ConfigSecret`, см. [configuration.md](configuration.md). + ## Логгер модуля и чёрный ящик -`ModuleContext.logger` (`PnLogger`) пишет в консоль и в «чёрный ящик»: буфер диагностики, журнал `journal/` и, для ошибки +`ModuleContext.logger` (`PnLogger`) пишет в консоль и в «чёрный ящик»: буфер диагностики, журнал `data/journal/` и, для ошибки с исключением, отчёт об ошибках. Короткие формы (`info`, `success`, `warning`, `error`, `critical`) пишут везде. `critical` — сбой, после которого плагин не работает; в консоли строка идёт с пометкой `[CRITICAL]`, успех — с `[OK]`. | Вызов | Консоль | Чёрный ящик | @@ -42,4 +48,30 @@ DiagnosticRegistration reg = PnLibraryProvider.get().getDiagnostics().register(" поддержки ей делать нечего (например, сообщение при каждом тике или ожидаемый отказ игрока). `debug` заменяет `Level.FINE`: деталь попадает в отчёт, а консоль остаётся чистой. -Уровни: `DEBUG` (только в отчёт), `INFO`, `SUCCESS`, `WARNING`, `ERROR`. Записи видно в `/pn events` (фильтр по уровню, карточка со стеком, повторы сводятся в одну строку), в `/pn gui` и в отчёте поддержки. Внутри самой библиотеки (конфиги, обновления, загрузки, интеграции) пишет тот же логгер, поэтому её сбои попадают в тот же чёрный ящик. +Уровни (`LogLevel`): `DEBUG` (только в отчёт), `INFO`, `SUCCESS`, `WARNING`, `ERROR`, `CRITICAL`. Записи видно в `/pn events` (фильтр по уровню, карточка со стеком, повторы сводятся в одну строку), в `/pn gui` и в отчёте поддержки. Внутри самой библиотеки (конфиги, обновления, загрузки, интеграции) пишет тот же логгер, поэтому её сбои попадают в тот же чёрный ящик. + +## Сообщить о проблеме + +Плагин записывает проблему в журнал наблюдений: что случилось (`message`), где (`plugin`, `source`), детали (`data`) и, если есть, исключение. + +```kotlin +val observability = PnLibraryProvider.get().observability +observability.capture { + plugin("pnMarket") + source("auction/expire") + level(ObservationLevel.ERROR) + message("Лот не возвращён владельцу") + data("lot" to lotId, "owner" to ownerId) + keepFor(Duration.ofDays(365)) +} +observability.failure(error) { plugin("pnMarket"); source("auction/save") } // уровень ERROR, исключение записано +``` + +Срок хранения задаёт автор в коде через `keepFor(...)` (до 3650 дней), у каждой записи свой; игрок и админ его не меняют. +Без `keepFor` срок зависит от уровня: `TRACE` 6 часов, `INFO` 7 дней, `NOTICE` и `WARNING` 30 дней, `ERROR` 90 дней, +`CRITICAL` без срока. Указанный срок заменяет срок уровня и в большую, и в меньшую сторону. Всего хранится не больше 10 000 записей. + +В отчёте поддержки (`/pn debug`) записи лежат в `observability/observations.jsonl`, по строке на запись: +`timeUtc` (когда случилось), `expiresUtc` (когда будет удалена, если срок задан), `plugin`, `source`, `level`, `message`, +`data`, `errorType`. Сводка по плагинам, местам и уровням — в `observability/analytics.json` +(`byPlugin`, `bySource`, `byLevel`, последние записи с `timestampUtc`). Записи `PnLogger` и `diagnostics.record` попадают туда же. diff --git a/docs/events.md b/docs/events.md index 2f840564e..c38451a6b 100644 --- a/docs/events.md +++ b/docs/events.md @@ -145,12 +145,12 @@ bus.plugins(ShopPurchaseEvent::class.java) // какие плагины с bus.listeners(PluginId.of("shop"), ModuleId.of("cart")) // слушатели одного модуля ``` -В игре и в консоли то же самое показывает команда `/pn bus` (право `pnlibrary.events.bus`). +В игре и в консоли то же самое показывает команда `/pn bus` (право `pnlibrary.events.bus`). Подкоманды: `listeners`, `plugin`, `top`, `calls`, `denied`, `slow`, `errors`, `history`, `day`, `range`, `trace`/`traces`, `export` (`csv`, `json`), `clear`. ## 9. История вызовов по дням pnLibrary считает, сколько раз в какой день вызвали каждое событие и сколько вызовов были отклонены. Счётчики лежат в -`event-history.tsv` в папке данных и переживают перезапуск; запись идёт в фоне не чаще раза в минуту и при остановке. +`data/history/event-history.tsv` и переживают перезапуск; запись идёт в фоне не чаще раза в минуту и при остановке. ```kotlin val bus = PnLibraryProvider.get().events.inspector diff --git a/docs/ideas/README.md b/docs/ideas/README.md new file mode 100644 index 000000000..859aee987 --- /dev/null +++ b/docs/ideas/README.md @@ -0,0 +1,8 @@ +# Идеи на будущее + +Здесь лежат идеи, которые пока не делаем. Это не план и не обещание: файл нужен, чтобы мысль не потерялась. +Когда идея берётся в работу, её описание переезжает в обычную документацию, а здесь остаётся ссылка. + +| Идея | Статус | +|---|---| +| [Какие настройки выбирают другие](popular-settings.md) | не начата | diff --git a/docs/ideas/popular-settings.md b/docs/ideas/popular-settings.md new file mode 100644 index 000000000..1e5cba9bd --- /dev/null +++ b/docs/ideas/popular-settings.md @@ -0,0 +1,42 @@ +# Какие настройки выбирают другие + +Статус: идея, не начата. + +## Суть + +У настроек, которые одинаково устроены у всех (включено/выключено, выбор из списка, число), библиотека может +показывать, какое значение чаще всего стоит у других серверов, например «это включено у 70% серверов» или +«значение `ru` выбрали 50%». Тогда администратор в меню или в чате видит, что выбирает большинство, и может +сравнить со своим выбором. Подсказка ничего не меняет сама. + +## Как это может работать + +1. **Что собираем.** Только значения настроек библиотеки из реестра (`core/settings`): ключ и выбранное значение. + Никаких адресов, имён, путей, игроков и списков плагинов. +2. **Как отправляем.** Через уже существующую систему метрик (bStats, см. [metrics.md](../metrics.md)): каждая + настройка с небольшим набором значений становится одной диаграммой «ключ → значение». Свои серверы для этого не нужны. +3. **Как получаем обратно.** Только если у платформы метрик есть публичный способ прочитать общую картину по + диаграмме. Если такого способа нет, идею не делаем в этом виде: поднимать свой сервер ради подсказки не стоит. +4. **Что показываем.** В подсказке у пункта меню отдельная строка вроде `[ У других ] 70% — включено`, а в + `/pn settings get` та же информация одной строкой. Данные кэшируются на диске в `data/` и обновляются редко. + +## Что надо решить до начала + +- **Можно ли получить данные из API метрик.** Это главное. Нужно проверить, отдаёт ли выбранный провайдер + распределение значений по диаграмме без авторизации и без лимитов, и как часто. +- **Согласие.** Отправка включается только явно, и по умолчанию выключена. Сейчас метрики опциональны, так и оставляем. + Получение чужой статистики не должно требовать отправки своей, либо это надо решить отдельно. +- **Какие настройки годятся.** Только те, где значений мало и они одинаковы у всех: переключатели, выбор из списка. + Часовой пояс, числа, тексты и всё, что идентифицирует сервер, не отправляем. +- **Что считать «большинством».** Показывать процент только когда данных достаточно (например, от нескольких + десятков серверов), иначе цифра вводит в заблуждение. +- **Прокси.** На прокси-сети настройки у каждого узла свои. Решить, считается ли сеть одним сервером. + +## Куда это ложится в коде + +- Реестр настроек (`SettingsRegistry`, `SettingSpec`) уже знает тип и допустимые значения каждой настройки. + Нужен флаг «участвует в статистике» в `SettingSpec`, по умолчанию выключенный. +- Отправка: рядом с остальными диаграммами в `MetricsService`. +- Показ: строка в `LibrarySettingsScreens` и в `/pn settings get`, берёт данные из локального кэша. +- Хранение кэша: `data/` рядом с остальным состоянием библиотеки, см. [storage.md](../storage.md). +- Документация: когда идея будет сделана, описание уйдёт в [settings.md](../settings.md) и [metrics.md](../metrics.md). diff --git a/docs/localization.md b/docs/localization.md index 1ec898c88..cd7f045e9 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -30,10 +30,11 @@ val localization = module.localization localization.bukkitLocale(version, MinecraftLocale.RU_RU).thenAccept { bukkit -> sender.sendMessage(bukkit.translate(Material.DIAMOND_SWORD).text) // «Алмазный меч» } +``` Из Java: `BukkitLocalization.locale(localization, version, MinecraftLocale.RU_RU)`. Нейтральную таблицу, загруженную через -`localization.locale(...)`, можно обернуть вручную: `BukkitLocaleTranslations.wrap(table)`. -``` +`localization.locale(...)`, можно обернуть вручную: `BukkitLocaleTranslations.wrap(table)`. Расширение `bukkitLocale` +лежит в `org.pnfolder.pnlibrary.bukkit.localization`. `version` — это `MinecraftVersion` сервера. Языки задаются типом `MinecraftLocale` (опечатку в коде поймает компилятор); строку с кодом языка тоже можно передать. Загрузить сразу несколько языков с запасным: diff --git a/docs/modules.md b/docs/modules.md new file mode 100644 index 000000000..6e3707766 --- /dev/null +++ b/docs/modules.md @@ -0,0 +1,224 @@ +# Модули плагина: включить, выключить, перезапустить + +Плагин делится на модули (`registration.registerModule(...)`). Если модуль зарегистрирован вместе с `PluginModule`, +администратор может переключать его командами и в меню, не перезапуская сервер. + +```kotlin +class Shop : PluginModule { + override fun onEnable(context: ModuleContext) { + context.registerCommand("shop") { /* ... */ } + } + override fun onDisable(context: ModuleContext) { /* закрыть то, что открыл сам */ } + override fun onReload(context: ModuleContext): Boolean { + // перечитать настройки на месте; false значит «не умею», тогда модуль перезапустится + return false + } +} + +registration.registerModule("shop", Shop()) +``` + +Методы пустые по умолчанию, переопределяйте нужные. При выключении библиотека сама отменяет задачи модуля и снимает его +команды. Слушатели и всё, что модуль открыл сам, закрывается в `onDisable`. + +`context.control` (`ModuleControl`) даёт то же из кода: `state` (`ENABLED`, `DISABLED`, `FAILED`), `lastError`, `enable()`, +`disable()`, `restart()`, `reload()`, `autoStart`/`setAutoStart(...)`. Ошибка в методе не выбрасывается: модуль становится +`FAILED`, ошибка видна в `lastError`, команде и меню, а `enable()` пробует ещё раз. Модуль без `PluginModule` виден в списке, +но не переключается. + +## Команды + +| Команда | Что делает | +|---|---| +| `/pn modules` | все модули и их состояние | +| `/pn modules view <плагин:модуль>` | карточка: состояние, ошибка, автозапуск, кнопки | +| `/pn modules enable\|disable\|restart\|reload <плагин:модуль>` | переключить сейчас | +| `/pn modules auto <плагин:модуль> on\|off` | включать ли модуль вместе с сервером (сохраняется) | + +Право: `pnlibrary.modules`; консоль может всегда. Вместо `плагин:модуль` можно написать просто id модуля, если он один. + +## Меню + +Главное меню, «Модули плагинов»: список и карточка с кнопками «Включить», «Выключить», «Перезапустить», «Перечитать», +«Включать с сервером». В карточке плагина обновлений есть кнопка «Модули» только с его модулями. Всё, что есть в меню, есть и +командой, и наоборот. + +## Что запоминается + +Модули, которые администратор оставил выключенными, хранятся в `data/modules/preferences.json` (`{"disabled": [...]}`). +Такой модуль не запускается при старте сервера, пока его не включат командой или кнопкой «Включать с сервером». + +## Библиотеки модуля + +Модуль сам просит нужные ему Maven-библиотеки: что скачать, откуда и как проверить. Библиотека загружается через Libby +перед `onEnable`, при каждом запуске модуля; уже загруженная второй раз не скачивается. + +```kotlin +class Shop : PluginModule { + override fun libraries() = listOf( + ModuleLibrary.builder("com.zaxxer", "HikariCP", "5.1.0") + .source { repository("https://repo.example.org/maven2/").sha256("3c0e…64 символа") } // другой файл отклоняется + .build(), + ModuleLibrary.of("org.slf4j:slf4j-api:2.0.13"), // коротко: Maven Central + ) + + override fun onEnable(context: ModuleContext) { + val pool = context.libraries.classLoader.loadClass("com.zaxxer.hikari.HikariDataSource") + } +} +``` + +| Настройка | Смысл | +|---|---| +| `source { … }` | место, откуда можно взять jar: ссылка или репозиторий, своя сумма и имя; можно сколько угодно (см. «Откуда берётся jar») | +| `mavenCentral(false)` | не заходить в Maven Central (по умолчанию он пробуется последним) | +| `classifier(...)` | классификатор, например `shaded` | +| `scope(LibraryScope.…)` | куда загружать: `PLUGIN` (по умолчанию), `ISOLATED`, `LIBRARY` | +| `platforms(PlatformType.…)` | грузить только на этих платформах; без вызова грузится везде | +| `optional()` | модуль запустится, даже если библиотеку загрузить не удалось | + +Транзитивные зависимости не подтягиваются: перечислите все нужные jar. Нужную библиотеку можно запросить и позже: +`context.libraries.load("группа:артефакт:версия")`. Не загрузилась обязательная библиотека: модуль в состоянии `FAILED`, причина +в `/pn modules view`. + +### Библиотеки плагина, просмотр и удаление + +Библиотеку можно зарегистрировать на весь плагин: её увидят все его модули, и она скачается один раз. + +```kotlin +val registration = library.plugins.register(this) +registration.libraries.load("org.slf4j:slf4j-api:2.0.13") // на плагин, для всех модулей +registration.registerModule("shop", Shop()) // у Shop свои libraries() +``` + +| Что | Как | +|---|---| +| какие библиотеки у модуля | `context.libraries.loaded` (свои), `.available` (свои и плагина) | +| какие у плагина | `registration.libraries.loaded`; со всеми модулями: `registration.allLibraries` | +| найти по имени | `libraries.find("com.zaxxer", "HikariCP")` | +| взять класс | `libraries.loadClass("com.zaxxer.hikari.HikariDataSource")`: сначала в библиотеках модуля, потом плагина | +| убрать из списка | `libraries.remove(library)`: список очищается, повторно не грузится; сам jar из памяти не выгрузить, классы живут до перезапуска сервера | + +В `/pn modules view <модуль>` перечислены библиотеки модуля и (со словами «от плагина») библиотеки его плагина; в меню +в карточке модуля видно их число. + +### Куда загружается библиотека + +- **`PLUGIN`** (по умолчанию): на Bukkit и BungeeCord библиотека добавляется в загрузчик плагина-владельца (того, что + зарегистрировал модуль), так что классы видны его собственному коду. На Velocity общий загрузчик пока pnLibrary. +- **`ISOLATED`**: отдельный загрузчик на владельца, `libraries.classLoader` и `libraries.loadClass(...)`. Два модуля могут + взять две версии одной библиотеки без конфликта; плагин видит её классы только через этот загрузчик. +- **`LIBRARY`**: загрузчик pnLibrary, классы видят все плагины с зависимостью от pnLibrary. Нужно редко: версии разных + плагинов спорят между собой. Берите, только если плагины должны делить библиотеку намеренно. + +Платформу (Bukkit, BungeeCord, Velocity) pnLibrary определяет сама: ничего менять не нужно. `platforms(...)` нужен, только +если библиотека нужна на части платформ; на остальных она тихо пропускается и не считается ошибкой. + +### Откуда берётся jar + +Способ один: список мест `source { … }`. Библиотека пробует их по порядку, пока одно не отдаст jar, который проходит проверку. +После всех ваших мест идёт Maven Central, если не выключен `mavenCentral(false)`. Мест можно написать сколько угодно, хоть тысячу. + +Внутри блока выбирается адрес и, по желанию, сумма и имя: + +| В блоке | Смысл | +|---|---| +| `link("https://…/a.jar")` | прямая ссылка на сам jar: pnLibrary просто скачивает его | +| `repository("https://…/maven2/")` | репозиторий или зеркало: pnLibrary строит путь по координатам (`группа/артефакт/версия/артефакт-версия.jar`) и качает по нему | +| `sha256("…")` | сумма jar из этого места; другой файл отвергается, пробуется следующее место | +| `name("…")` | название места для ошибок и меню; без него это хост адреса | +| `description("…")` | одно предложение, что это за место, например «основной репозиторий компании» | + +Не получилось скачать, сети нет или сумма не совпала: берётся следующее место. Библиотека не загрузилась, только если не +сработало ни одно; в ошибке причина по каждому месту. Место, которое только что не сработало, остальные библиотеки пробуют последним +(пять минут, только в памяти, ничего не сохраняется): так мёртвое зеркало не задерживает каждую загрузку. Самое быстрое место по IP не +подбирается: порядок задаёте вы, самое надёжное ставьте первым. Сумма проверяется только если вы её указали, иначе jar из этого места +не проверяется, в `/pn modules libs` видно «jar не проверяется». pnLibrary ничего не запоминает сама. + +### Полные примеры + +```kotlin +// 1. Только координаты: Maven Central +ModuleLibrary.of("org.slf4j:slf4j-api:2.0.13") + +// 2. Один репозиторий и сумма, потом Maven Central +ModuleLibrary.builder("com.zaxxer", "HikariCP", "5.1.0") + .title("Пул соединений") // название самой библиотеки + .description("Держит соединения с базой.") // описание самой библиотеки + .source { repository("https://repo.example.org/maven2/").sha256("3c0e…").name("Наш репозиторий").description("Основной") } + .build() + +// 3. Только прямая ссылка, больше никуда не заходить +ModuleLibrary.builder("org.example", "tool", "1.0") + .source { link("https://cdn.example.org/tool-1.0.jar").sha256("9f2a…").name("CDN") } + .mavenCentral(false) + .build() + +// 4. Много мест подряд, ссылки и репозитории вперемешку +ModuleLibrary.builder("com.zaxxer", "HikariCP", "5.1.0") + .source { link("https://cdn.example.org/HikariCP-5.1.0.jar").sha256("3c0e…").name("CDN") } + .source { repository("https://mirror.example.org/maven/").sha256("9f2a…").name("Зеркало") } // другая сборка, другая сумма + .source { repository("https://repo.example.org/maven2/") } // без проверки + .source { link("https://backup.example.org/hikari.jar").name("Запасная") } + .build() // в конце Maven Central + +// 5. Остальные настройки +ModuleLibrary.builder("net.dv8tion", "JDA", "5.0.0") + .classifier("withDependencies") // jar с классификатором + .scope(LibraryScope.ISOLATED) // свой загрузчик, версия не спорит с чужими + .platforms(PlatformType.BUKKIT) // только на Bukkit; на остальных тихо пропускается + .optional() // модуль запустится и без неё + .build() + +// 6. Из Java, готовое место можно использовать в нескольких библиотеках +LibrarySource corp = LibrarySource.builder().repository("https://nexus.corp.example/maven/").sha256("…").name("Корп").build(); +ModuleLibrary.builder("g", "a", "1").source(corp).build(); +``` + +### Название и описание + +Чтобы администраторы и игроки понимали, что это: + +```kotlin +ModuleLibrary.builder("com.zaxxer", "HikariCP", "5.1.0") + .title("Пул соединений") + .description("Держит открытые соединения с базой, чтобы запросы шли быстрее.") + .build() + +registration.registerModule("shop", Shop()) { it.metadata { m -> m.description("Магазин: покупка и продажа предметов.") } } +``` + +### Вся библиотека целиком + +- `library.plugins.allModules()`: все модули всех плагинов. +- `library.plugins.libraryUsage()`: все библиотеки и кто их зарегистрировал (`LibraryUsage.owner`: `плагин` или `плагин:модуль`). +- `/pn modules plugins`: плагины с модулями и числом библиотек. +- `/pn modules libs [<плагин>|<плагин:модуль>]`: библиотеки с названием, описанием, режимом загрузки и предупреждениями + («сумма ещё не проверена», «другая версия у другого плагина»). +- Меню: главная, «Библиотеки плагинов» (сначала выбор плагина или «Все библиотеки»; у библиотеки видно, чья она, файл и папка от корня сервера) и «Модули плагинов»; карточка плагина обновлений, «Библиотеки»; карточка модуля, + «Библиотеки». У модуля в списке виден его `description`. + +## Диск: сколько места занимают плагины и библиотеки + +`/pn modules disk` и кнопка «Диск плагинов» на главной странице меню (право `pnlibrary.modules`) показывают, сколько места +занимает каждый плагин сервера, не только наши. Для каждого плагина считается: + +| Часть | Что в неё входит | +|---|---| +| плагин | jar плагина в папке `plugins` | +| настройки | `yml`, `yaml`, `json`, `toml`, `properties`, `conf`, `cfg`, `hocon`, `ini`, `xml` в его папке | +| библиотеки | файлы в папках `lib`, `libs`, `libraries` его папки | +| журналы | `*.log`, папка `logs`, сжатые журналы | +| данные | всё остальное: базы, кэши, сохранения | + +Сверху итог: сколько занято всего, сколько весят библиотеки, зарегистрированные через pnLibrary, сколько свободно на диске и какой +он по размеру. Плагины идут от самого большого; тот, что занимает половину и больше, подсвечен. + +Jar без папки (плагин без своих файлов) считается отдельным плагином. Jar и папка склеиваются по имени без версии: `Shop-1.2.3.jar` +и папка `Shop` дают одну строку. + +В `/pn modules libs` и в карточке библиотеки в меню теперь видны размер jar и место, где он лежит. Пока библиотека не загружена +или нет загрузчика, этих полей нет. + +Подсчёт папки запоминается на 30 секунд, чтобы клики по меню не обходили диск каждый раз. Если плагинов много и папки огромные, +первое открытие может занять секунду. Меню другого сервера показывает диск того сервера. diff --git a/docs/network.md b/docs/network.md index 608c9f146..cd540dea9 100644 --- a/docs/network.md +++ b/docs/network.md @@ -63,8 +63,8 @@ ### Команды -Каждая команда начинается со слова, а потом идёт имя группы, поэтому группу можно назвать как угодно, даже `create`. На прокси -`/pnproxy groups …`, на игровом сервере `/pn groups …`. Если ввести команду не до конца, под ней появится описание. +Каждая команда начинается со слова, а потом идёт имя группы, поэтому группу можно назвать как угодно, даже `create`. Команда есть только на прокси: +`/pnproxy groups …` (или `/pnp groups …`). Если ввести команду не до конца, под ней появится описание. | Команда | Что делает | |---|---| @@ -88,14 +88,16 @@ Выбрав в «Сети» другой сервер или прокси, вы видите его меню целиком: обновления, журнал, события, задачи, резервные копии и настройки. Сам экран строит сервер, на котором вы стоите. Другой сервер только отвечает на запросы и выполняет команды. Права проверяются на вашем сервере, а получатель доверяет любому, кто знает `link.key`. +Удалённых действий немного: `/pn servers <сервер> check`, `update <плагин>`, `auto <плагин> on|off` (права `pnlibrary.updates.view`, `.download`, `.settings`). Команды и файлы по связи не передаются; запрос действует один раз. ## 7. Другие неочевидные вещи -- **`config.yml`:** в нём только то, что стоит менять: приватность, пути, исключённые из отчёта, срок хранения истории (от 30 - дней), часовой пояс и текст «нет прав». Остальное задано в коде. Старые параметры при запуске удаляются после резервной копии, в - консоль выводится предупреждение. Это нормально. +- **Настройки библиотеки:** файлов настроек нет, всё меняется командой `/pn settings` и в меню, значения лежат в + `data/settings.json`: приватность, срок хранения истории (от 30 дней), часовой пояс, текст «нет прав», загрузки файлов, время + проверки обновлений и `journal-foreign-plugins` (писать ли в журнал ошибки плагинов, не подключённых к pnLibrary). Остальное + задано в коде. См. [settings.md](settings.md). - **Отчёт для поддержки** всегда собирается, сохраняется на сервере и отправляется только в зашифрованном виде. Личные данные игроков по умолчанию в него не попадают. -- **Как скрыть значение из отчёта:** в `config.yml` добавьте путь через точку, например `database.password`. +- **Как скрыть значение из отчёта:** пометьте поле в классе конфигурации аннотацией `@ConfigSecret`. - **Статистика (bStats):** общий выключатель лежит в `plugins/bStats/config.yml`, он принадлежит владельцу сервера. - **Замена jar при работающем сервере** не подхватывается до перезапуска. diff --git a/docs/overview.md b/docs/overview.md index 5fcbfa0ed..4deefdb62 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -27,33 +27,35 @@ val context = registration.registerModule("main") // ModuleContext моду | Команды | дерево команд без `plugin.yml`, ошибки, подсказки | [commands.md](commands.md) | | События | шина с приоритетами, `/pn bus`, история вызовов, экспорт | [events.md](events.md) | | Конфигурации | код-первые YAML с комментариями и проверкой | [configuration.md](configuration.md) | -| Действия и проверки | списки действий и условий в YAML | [actions.md](actions.md), [checks.md](checks.md) | +| Действия и проверки | списки действий и условий в YAML | [actions.md](actions.md) | | Плейсхолдеры | типизированные значения `%плагин_ключ%` | [placeholders.md](placeholders.md) | | Задачи | отложенные и повторяющиеся, в том числе Folia | [tasks.md](tasks.md) | | Диагностика | отчёты `/pn debug`, журнал `/pn events` | [diagnostics.md](diagnostics.md) | | Метрики | bStats и другие провайдеры | [metrics.md](metrics.md) | | Валюта | Vault, PlayerPoints | [currency.md](currency.md) | | Локализация | названия предметов и сущностей Minecraft | [localization.md](localization.md) | +| Хранилища | какие файлы библиотека держит на диске | [storage.md](storage.md) | +| Сеть | прокси, ключ связи, группы серверов | [network.md](network.md) | | Кулдауны, чат, меню, предметы | общие инструменты (меню и предметы только Bukkit) | пакеты `api.cooldowns`, `api.chat`, `platforms/bukkit` | | Расширения | свои модули поверх библиотеки | [expansions.md](expansions.md) | ## Как работают обновления -1. **Установка.** Bootstrap-плагин (`modules/bootstrap`) скачивает pnLibrary с GitHub и кладёт её в `plugins/`. -2. **Проверка.** Сразу при старте и затем каждые `checks.interval` (по умолчанию 6 часов, минимум 5 минут) +1. **Установка.** Bootstrap-плагин (`modules/bootstrap`) скачивает `universal.jar` с GitHub и кладёт его в `plugins/`; можно и вручную (есть ещё `universal-full` без загрузок при старте). +2. **Проверка.** Сразу при старте и затем каждые 6 часов библиотека читает каталоги `releases.json` самой себя и зарегистрированных плагинов. Выключить проверки нельзя. 3. **Канал.** Берётся самый новый релиз, который разрешает канал: `stable` < `rc` < `beta` < `alpha` < `dev`. - Канал pnLibrary задаётся в `updates.yml` (`library.channel`), канал плагина — командой - `/pn updates set <плагин> channel <канал>` или в `PluginUpdateRequest`. + Канал pnLibrary и плагина меняется командой + `/pn updates set <плагин> channel <канал>` (пока доступен только `dev`); плагин может задать свой в `PluginUpdateRequest`. 4. **Подготовка.** Файл скачивается, сверяется SHA-256, кладётся в транзакцию. Jar не заменяется на ходу. 5. **Применение.** Только при следующем запуске сервера; сервер сам не перезапускается. 6. **Откат и журнал.** Резервные копии и история действий хранятся; `/pn updates history`. Пока у pnLibrary нет ни одного `stable`-релиза (сейчас все релизы — `dev`), по умолчанию стоит канал `dev`, иначе библиотека после установки не нашла бы обновлений. Когда появится стабильная ветка, значение по умолчанию станет -`stable`. Уже созданный `updates.yml` не перезаписывается: канал в нём меняется вручную. +`stable`. Канал меняется командой, файла настроек обновлений нет. ## Поддержка В консоли при запуске и выключении плагинов pnFolder показывается блок с приглашением в Discord на русском и английском; -тот же текст лежит в шапке `config.yml`. Отключить его нельзя. +Отключить его нельзя. diff --git a/docs/placeholders-plan.md b/docs/placeholders-plan.md index 6bdc6d4eb..f6928affb 100644 --- a/docs/placeholders-plan.md +++ b/docs/placeholders-plan.md @@ -1,7 +1,7 @@ # Плейсхолдеры: план системы -Статус: решения согласованы с пользователем, реализация идёт по шагам. Ветка `next`. -Что уже сделано в коде: адрес `плагин/модуль:имя` и поиск по нему (`PlaceholderAddress`, `PlaceholderAddressIndex`). +Статус: реализовано в `next`; этот документ хранит замысел, а отличия от него и итог — в разделе 12. +Как пользоваться: [placeholders.md](placeholders.md). ## 1. Адрес @@ -342,7 +342,7 @@ placeholders(papi = "clans") { ## 11. Порядок работ -1. Сделано: адрес и поиск по адресу. +1. Сделано: адрес и поиск по адресу (пункты 2–7 тоже сделаны, см. раздел 12; пункт 8 — не закончен). 2. Короткие имена внутри своего плагина. 3. Общий прогон `render` с PlaceholderAPI и его адаптер для Bukkit. 4. Публикация с явным префиксом, проверка занятых префиксов. diff --git a/docs/placeholders.md b/docs/placeholders.md index bfde1d382..e485bf841 100644 --- a/docs/placeholders.md +++ b/docs/placeholders.md @@ -16,6 +16,23 @@ В PlaceholderAPI тот же плейсхолдер виден как `%префикс_модуль~путь%`, если его группа опубликована (`placeholders(papi = "clans") { ... }`): `%clans_war~score.Alex%`. Ветки с `inside()` наружу не выходят. +## Как писать в тексте + +В тексте (сообщение действия, строка конфига) значения пишутся одним способом, в фигурных скобках: + +| Запись | Что читается | +|---|---| +| `{имя}` | сначала значение этого запуска (`player`, `price`, `error`), затем плейсхолдер pnLibrary своего плагина | +| `{плагин/модуль:путь}` | плейсхолдер pnLibrary: свой, библиотеки или чужого плагина | +| `{papi:имя}` | только PlaceholderAPI: `{papi:server_tps}` | +| `{= выражение}` | расчёт: `{= level * 2}` | +| `%имя%` | PlaceholderAPI в привычной записи; нужна, когда текст читают и другие плагины | + +После `|` идёт цепочка форматов: `{price|number:2}`, `{money|group}`. Если имя есть и среди значений запуска, и среди +плейсхолдеров, побеждает значение запуска; чужой плейсхолдер можно взять полным адресом. Неизвестное имя остаётся в тексте +как написано, чтобы опечатка была видна. Квадратные скобки ничего не значат: `[pnTest]` в префиксе остаётся текстом. +В выражениях то же имя пишется без скобок: `level * 2`. + ## Дерево ```kotlin @@ -120,7 +137,7 @@ module.formats { ## Ключи Ключ типизирован: `PlaceholderKey.of("balance", Long::class.java)`. Значение настраивается в билдере -(`PlaceholderBuilder`): откуда брать, кто может читать (`PlaceholderAccess`), как кэшировать (`PlaceholderCachePolicy`, +(`PlaceholderBuilder`): откуда брать, кто может читать (`PluginAccess`), как кэшировать (`PlaceholderCachePolicy`, `PlaceholderCacheScope`). ```kotlin diff --git a/docs/releases.md b/docs/releases.md index 5d4db9bc0..8cfe203f3 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -1,14 +1,19 @@ # Выпуск pnLibrary Полный выпуск запускается через Actions `release`: версия, описание и выбор Maven-публикации. -Сборка проверяет все четыре основных JAR, затем создаёт `distribution/build/libs/release-manifest.json`, -метаданные рядом с JAR и `checksums.sha256`. Версия, канал, API и Java берутся из той же модели, +Сборка проверяет все четыре платформенных JAR (bukkit, bungeecord, velocity, universal), затем создаёт +`distribution/build/libs/release-manifest.json`, метаданные `*.jar.meta.json` рядом с JAR и `checksums.sha256`. +После сборки отдельным шагом запускается `apiCheck`. Версия, канал, API и Java берутся из той же модели, которая формирует встроенный `META-INF/pnlibrary/component.json`; размеры и хеши — из готовых файлов. `tools/release/update-catalog.ps1` переносит эти данные в `.pnlibrary/releases.json` и создаёт changelog. +В каталог идут ровно четыре артефакта (bukkit, bungeecord, velocity, universal); `universal-full` в каталог не входит. Он проверяет хеши и согласованность метаданных, сохраняет историю и отклоняет перезапись существующей версии. -Workflow коммитит каталог, changelog и версию перед тегом. Список GitHub assets тоже берётся из manifest: -основные JAR, updater, метаданные и суммы. +Workflow коммитит каталог, changelog и версию перед тегом. Список GitHub assets берётся из `assets` в manifest: +четыре платформенных JAR, `pnLibrary-<версия>-universal-full.jar`, `pnLibrary-updater-<версия>.jar`, +`checksums.sha256` (суммы всех JAR, включая `universal-full` и updater) и `release-manifest.json`. +Файлы `*.meta.json` нужны только скрипту каталога и в релиз не попадают. Релиз создаётся обычным, +не pre-release, даже если в версии есть суффикс канала. ## Обновление зависимостей @@ -59,7 +64,7 @@ Maven публикует артефакты, настроенные в Gradle ч - Версию без суффикса (`0.1.0`) не выпускаем: она новее всех `-stable.N` и ломает порядок. - Канал пользователя принимает свой канал и более зрелые: `dev` видит всё, `stable` только `stable`. - Поле `channel` в каталоге должно совпадать со словом версии; тест `RepositoryLayoutTest` это проверяет. -- Канал самой pnLibrary сейчас зафиксирован в коде как `dev` (см. `TODO` в `UpdateSettings`). +- Канал самой pnLibrary сейчас по умолчанию `dev` (`UpdateConfiguration.LibraryPolicy`); пока публикуется только `dev`, в командах выбора доступен только он (`ONLY_DEV` в `UpdateCatalogSettingsCommands`). Пример каталога со всеми каналами: [integration/template/.pnlibrary/releases.json](../integration/template/.pnlibrary/releases.json) (заполненный образец для плагина, его changelog-файлы рядом в `changelogs/`). diff --git a/docs/remote-policies.md b/docs/remote-policies.md index 56740f144..efeb2b020 100644 --- a/docs/remote-policies.md +++ b/docs/remote-policies.md @@ -1,10 +1,46 @@ # Удалённые политики -Политика — один `.java`-файл по ссылке `https://` или `file:`, не больше 1 МБ. Сервер компилирует его -своим javac. Если сервер запущен на JRE без компилятора, при старте тот же загрузчик Libby, что берёт Kotlin, -докачивает компилятор ECJ (около 3 МБ, SHA-256 зашит в коде) в `libraries/pnlibrary`, и политика компилируется им, -поэтому JDK не нужен. Если докачать не удалось, проверка политики сообщает об этом, дальше действует `onError`. Политика всегда собирается под Java 8 и работает на любой Java. Ошибка -политики обрабатывается согласно `onError`. +Политика — один `.java`-файл по ссылке `https://` или `file:` (абсолютной), не больше 1 МБ. Класс в файле +реализует `RemotePolicy`, имеет публичный конструктор без аргументов и возвращает `RemotePolicyResult` +(`allow()`, `deny(текст)` или `allowing(...)`/`denying(...)` с карточкой: статус, заголовок, детали, шаги, ссылки). +Из контекста политика видит продукт, платформу, версию сервера и значения `values`, заданные плагином. + +```java +public class ExamplePolicy implements RemotePolicy { + public RemotePolicyResult check(RemotePolicyContext context) { + if (context.getProduct().getVersion().startsWith("0.")) { + return RemotePolicyResult.deny("Эта версия больше не поддерживается"); + } + return RemotePolicyResult.allow(); + } +} +``` + +## Настройки + +`RemotePolicySettings` задаёт плагин: + +| Поле | По умолчанию | Смысл | +|---|---|---| +| `source` | обязательно | ссылка на `.java`-файл | +| `checkEvery` | 6 часов | как часто политика проверяется заново, не реже раза в минуту | +| `onDeny` | `DISABLE_PLUGIN` | что делать при отказе: `DISABLE_PLUGIN` или `DISABLE_MODULE` | +| `onError` | `DENY` | что делать, если политику не удалось проверить (нет сети, нет компилятора, битый файл): `DENY` считает это отказом, `DENY_UNTIL_CHECKED` не запускает плагин, пока не было ни одной успешной проверки, `KEEP_RUNNING` пишет предупреждение и продолжает | +| `supportUrl` | Discord pnFolder | куда отправить администратора, если плагин не запустился | +| `startupTimeout` | 20 секунд | сколько запуск плагина ждёт первую проверку | +| `values` | пусто | значения для политики | + +Скачивание: таймаут соединения 8 секунд, чтения 30 секунд. + +## Компиляция + +Сервер компилирует файл своим javac. Если сервер запущен на JRE без компилятора, тот же загрузчик Libby, что берёт +Kotlin, при первой проверке политики докачивает компилятор ECJ в `libraries/pnlibrary` (3.43 для Java 17 и новее, +3.26 для старой Java), и политика компилируется им, поэтому JDK не нужен. Если докачать не удалось, проверка +политики сообщает об этом, дальше действует `onError`. Политика всегда собирается под Java 8 и работает на любой +Java. Сервер с javac ничего не скачивает. + +## Безопасность Исполняемые политики — доверенный код с полномочиями JVM сервера. ClassLoader не является песочницей. Защита политики — доступ к репозиторию, где она лежит: храните её в репозитории с ограниченной записью. diff --git a/docs/repository.md b/docs/repository.md index c4a7f7f17..a08dadf3c 100644 --- a/docs/repository.md +++ b/docs/repository.md @@ -12,7 +12,9 @@ Заполненный образец со всеми каналами и changelog-файлами лежит в [integration/template/.pnlibrary](../integration/template/.pnlibrary). -Репозиторий читается с ветки `main`. Файлы нужно закоммитить в неё до выхода релиза. +По умолчанию файл читается с ветки `main` (ветку, тег или коммит можно задать, см. ниже). Файлы нужно закоммитить +в неё до выхода релиза. Адрес файла: `raw.githubusercontent.com`, запасные источники — GitHub Contents API и jsDelivr. +Размер `releases.json` не больше 1 МБ. ## `releases.json` @@ -70,7 +72,7 @@ | `version` | версия релиза по semver; на GitHub ему соответствует тег `v<версия>` | | `channel` | `stable`, `rc`, `beta`, `alpha` или `dev`; обычные серверы получают только `stable` | | `description` | короткое описание в одну строку, оно показывается в уведомлении | -| `changelogUrl` | ссылка на файл из `changelogs/` (необязательно) | +| `changelogUrl` | ссылка на файл из `changelogs/`, только HTTPS (необязательно) | | `publishedAt` | время публикации в UTC | | `api` | какие версии API pnLibrary поддерживает релиз | | `artifacts` | файлы релиза: имя, платформа, диапазоны версий, ссылка, сумма (см. ниже) | @@ -88,7 +90,7 @@ |---|---| | `file` | безопасное имя JAR; для `platform: "UNIVERSAL"` — обязательно вида `<имя>-<версия>-universal.jar` | | `platform` | `BUKKIT`, `BUNGEECORD`, `VELOCITY` или `UNIVERSAL` (один файл для всех трёх) | -| `java` | диапазон версий Java (необязательно; без него файл не ограничен по Java) | +| `java` | диапазон версий Java `{ "minimum": 8, "maximum": 21 }` (необязательно; без него минимум 8, сверху не ограничен) | | `minecraft` | диапазон версий Minecraft, только для `BUKKIT` (необязательно) | | `platformApi` | диапазон версии платформы, только для `BUNGEECORD`/`VELOCITY` (необязательно) | | `url` | ссылка на файл, только HTTPS | @@ -102,8 +104,9 @@ размер) пропускается. Если во всём релизе нет ни одной годной записи под платформу установщика (ни точной, ни `UNIVERSAL`), он идёт за файлом на GitHub-релиз этой версии. -Правила: версии не повторяются, у релиза есть хотя бы один файл, ссылки только по HTTPS. Нарушение любого правила -сообщается с путём к полю (`releases[2].artifacts[0].url`). Пустой список `"releases": []` допустим. +Правила: версии не повторяются, у релиза есть хотя бы один файл, ссылки только по HTTPS, `file` состоит из +латиницы, цифр, `.`, `_`, `-` и заканчивается на `.jar`, `size` положителен. Нарушение сообщается с путём к полю +(`releases[2].artifacts[0].url`). Пустой список `"releases": []` допустим. ## `changelogs/<версия>.md` @@ -142,8 +145,13 @@ ```java .updates("PnFolder", "pnCases", updater -> updater .branch("master") // по умолчанию "main" - .catalogPath("updates") // по умолчанию ".pnlibrary", необязательно - .artifact("(?i)^pnCases-[0-9].*\.jar$", 17)) + .catalogPath("updates")) // по умолчанию ".pnlibrary", необязательно ``` +Правило `.artifact(...)` не нужно: какой файл подходит серверу, решает каталог (платформа и диапазон Java каждого +файла), а Java плагина берётся из его описания. Правило нужно только плагину, который в одном репозитории выпускает +разные сборки под разные версии Java. + +Вместо ветки можно указать тег (`.tag("v1.0")`) или коммит (`.commit("abc1234")`). + Если каталог не найден, в сообщении об ошибке будет полный адрес `releases.json`, чтобы сразу видеть, какую ветку проверить. diff --git a/docs/settings.md b/docs/settings.md new file mode 100644 index 000000000..63c99919a --- /dev/null +++ b/docs/settings.md @@ -0,0 +1,169 @@ +# Настройки библиотеки + +У pnLibrary нет файлов настроек. Всё, что администратор может менять, меняется командой `/pn settings` или в меню +(`/pn gui` → «Настройки» → «Параметры библиотеки»). Значения хранятся в одном файле `plugins/pnLibrary/data/settings.json`: +в нём только то, что вы изменили, остальное берётся из кода. Файл не нужно править руками, но он безопасен: неизвестный ключ, +значение не того типа или вне границ пропускаются с предупреждением в консоли, берётся значение по умолчанию, сервер всё равно +запускается. Если файл вообще не читается, он сохраняется как `settings.json.broken`. + +Рядом лежат три файла, которые библиотека создаёт сама и открывает для администратора: `Помощь.txt` (где получить помощь, ссылки на Discord и +репозиторий, главные команды), `Настройки.txt` (каждая настройка: ключ, название, текущее значение, по умолчанию, границы, когда заработает, +описание, готовая команда для изменения) и `Команды.txt` (каждая команда `/pn` и каждое право: что делает, какое право нужно, где команда есть). +Все пишутся заново при каждом запуске, `Настройки.txt` ещё и сразу после изменения настройки, поэтому значения и ссылки в них всегда +свежие, а ручные правки не сохраняются. Если JVM сервера не умеет создавать файлы с русскими именами (кодировка имён файлов не UTF-8), файлы +называются `HELP.txt`, `SETTINGS.txt` и `COMMANDS.txt`. Если записать их не удалось, в консоль выводится одно предупреждение, работа не страдает. + +Единственный список настроек находится в коде (`SettingsRegistry`): команда, меню и тест документации читают его. +Тест проверяет, что каждая настройка описана на этой странице. + +## Команда `/pn settings` + +Право `pnlibrary.settings` (в меню подходит и `pnlibrary.admin`), консоль проходит всегда. Работает на играх-серверах и на прокси, на +прокси меняются настройки самого прокси. + +| Команда | Что делает | +| --- | --- | +| `/pn settings [list] [страница]` | все настройки со значениями; изменённые отмечены значением по умолчанию (`включено`/`выключено` у переключателей) | +| `/pn settings get <ключ>` | одна настройка: значение, по умолчанию, границы, примеры, когда заработает | +| `/pn settings set <ключ> <значение>` | проверить, сохранить в `data/settings.json` и применить | +| `/pn settings reset <ключ>` | вернуть значение по умолчанию | +| `/pn settings pick <ключ> [часть названия]` | игрок: открыть в меню список значений настройки с выбором, только подходящие под часть названия | + +Ключи и значения подсказываются по Tab. Если значение не подходит, ответ называет причину и допустимые границы, ничего не +меняется. Если изменение заработает только после перезапуска, ответ об этом говорит. + +Типы значений: + +- **вкл/выкл**: везде показывается как `включено` и `выключено` (в меню, в `/pn settings`, в `Настройки.txt`); вводить можно `вкл`, `выкл`, `включено`, `выключено`, `да`, `нет`, `true`, `false`, `on`, `off`; +- **число**: целое число в границах настройки; +- **время**: число с единицей, `30s`, `15m`, `6h`, `1h30m`, `2d` (подходят и `с`, `м`, `ч`, `д`); +- **текст**: всё, что написано после ключа, пробелы допустимы; +- **выбор из списка**: значение из длинного списка, например часовой пояс; в меню прокручивается кликом, команда принимает любое известное значение, Tab подставляет значения списка. + +В меню переключатель меняется кликом, число кликом (левый больше, правый меньше, Shift на десять), текст и время вводятся в чате по +подсказке, колёсико возвращает значение по умолчанию. Если смотреть меню другого сервера или прокси, меняются его настройки. + +У переключателя в подсказке два варианта, `включено` и `выключено`; тот, что стоит по умолчанию, помечен серым курсивом `(по умолчанию)`. +Отдельной строки «По умолчанию» у переключателя нет; у остальных настроек она появляется, только когда значение изменено. + +### Выбор из длинного списка (часовой пояс) + +В меню «Часовой пояс» работает как переключатель с прокруткой, такой же, как у настроек с вариантами в меню конфигов: + +``` +Часовой пояс +[ Значение ] Europe/Berlin +[ Вариант ] 3 из 21 +[ Смещение ] UTC+01:00 +[ Сейчас там ] 19:45 + · UTC + · Europe/London + ➤ Europe/Berlin + · Europe/Kyiv + ... + ▼ ниже ещё 10 +▸ Клик следующий +▸ Правый клик предыдущий +▸ Shift + клик весь список +``` + +Клик записывает следующее значение (по кругу), правый клик предыдущее, окно из 8 строк идёт за текущим значением, строки +`▲ выше ещё N` и `▼ ниже ещё N` показывают, что скрыто. Крутится набор «Популярные» (`ChoiceSource.cycle`; у источника без такого набора +крутятся все значения). Если текущий пояс в набор не входит (например `Europe/Samara`), он стоит первой строкой окна со стрелкой, в строке +`Вариант` написано `— из 21`, а клик переходит к первому популярному (правый клик к последнему). Shift + клик открывает постраничный список +всех поясов (по 45 на странице); ввод в чате теперь только в нём. Колёсико возвращает значение по умолчанию, когда оно изменено. +В списке текущий пояс зелёный и не нажимается, клик по любому другому записывает его и возвращает к настройкам. Под каждым поясом написано, +что в нём сейчас, чтобы выбирать, не зная названия: + +``` +[ Смещение ] UTC+03:00 +[ Сейчас там ] 21:45 +``` + +Время идёт по 24-часовым часам, смещение берётся на сегодня, с учётом летнего времени (`UTC`, `UTC+03:00`, `UTC-05:00`). + +Нижний ряд: + +| Слот | Кнопка | Что делает | +|---|---|---| +| 46 | Ввести в чате | предлагает написать пояс точно (`/pn settings set time-zone …`) | +| 47 | Сортировка | клик переключает `по смещению UTC` (сначала по смещению, затем по названию; по умолчанию) и `по алфавиту` | +| 51 | Популярные | клик переключает `Все` и `Популярные`: UTC, Лондон, Берлин, Киев, Минск, Москва, Стамбул, Дубай, Ташкент, Алма-Ата, Дели, Бангкок, Шанхай, Токио, Сидней, Окленд, Сан-Паулу и четыре пояса США; при поиске вместо неё «Сбросить поиск» | +| 52 | Поиск | клик просит в чате часть названия; колёсико сбрасывает поиск | + +Выбранные порядок и набор сохраняются при листании страниц. Для популярных порядок задан списком, поэтому кнопка сортировки там скрыта. + +**Поиск.** Команда `/pn settings pick <ключ> [часть названия]` (только игрок, право `pnlibrary.settings`) открывает список настройки, уже сужённый до поясов, +в названии которых есть эта часть; регистр и различие между `_`, `/` и пробелом не важны, поэтому `/pn settings pick time-zone new york` найдёт `America/New_York`. +Заголовок показывает запрос, кнопка «Сбросить поиск» возвращает весь список; если ничего нет, написано «Ничего не найдено». Tab подсказывает ключи настроек с таким списком. + +Список поясов строится на самом сервере или клиенте меню из `ZoneId.getAvailableZoneIds()`: региональные id (`Europe/Moscow`, `America/New_York`) +и `UTC`; устаревшие псевдонимы (`US/Pacific`, `SystemV/…`) и ряд `Etc/GMT±N` не показываются. По сети передаётся только имя списка, поэтому выбор работает и в меню +прокси. Команда `/pn settings set time-zone` по-прежнему принимает любой id, который знает Java, а Tab подсказывает пояса из списка. + +Любую другую настройку можно сделать выбором из списка: в `SettingsRegistry` у неё тип `CHOICE` и список `ChoiceSource` (значения, способы сортировки, +необязательные популярные значения и строки «что это» для каждого значения). + +## Настройки + +| Ключ | Тип, границы | По умолчанию | Заработает | Что делает | +| --- | --- | --- | --- | --- | +| `privacy` | вкл/выкл | выкл | после перезапуска | Скрывать в диагностическом отчёте имена, UUID, адреса, пинг игроков и названия текущих серверов. | +| `history-retention-days` | число, 30–365 | 30 | после перезапуска | Сколько дней хранить историю диагностики. | +| `journal-foreign-plugins` | вкл/выкл | выкл | после перезапуска | Писать ли в журнал предупреждения и ошибки плагинов, не подключённых к pnLibrary. | +| `time-zone` | выбор из списка, id часового пояса | пояс сервера | сразу | Часовой пояс всех времён, которые показывает pnLibrary. Время хранится в UTC, смена пояса ничего не портит. Примеры: `UTC`, `Europe/Moscow`. | +| `no-permission-message` | текст, до 256 символов | Недостаточно прав для этой команды. | после перезапуска | Что видит игрок без права на команду pnLibrary или другого плагина, у которого нет своего сообщения. | +| `downloads.enabled` | вкл/выкл | вкл | сразу | Система загрузок. Выключена: все запросы плагинов на загрузку отклоняются. | +| `downloads.automatic` | вкл/выкл | вкл | сразу | Загрузки, которые плагин запускает сам, без команды (в том числе недостающие плагины). Тот же выбор делает `/pn deps auto on\|off` и переключатель в меню. | +| `downloads.destinations.data-folder` | вкл/выкл | вкл | сразу | Сохранять скачанные файлы в папку данных плагина, который их запросил. | +| `downloads.destinations.cache` | вкл/выкл | вкл | сразу | Сохранять скачанные файлы в общий кэш pnLibrary. | +| `updates.check-interval` | время, 15 минут – 7 дней | 6ч | после перезапуска | Как часто опрашивать каталоги релизов; первая проверка идёт при запуске. | +| `updates.connect-timeout` | время, 1 с – 2 минуты | 10с | после перезапуска | Сколько ждать соединения при скачивании файла обновления. | +| `updates.read-timeout` | время, 5 с – 10 минут | 30с | после перезапуска | Сколько ждать данных от молчащего сервера при скачивании файла обновления. | + +Остальное (интервал напоминаний об обновлениях, размер файла обновления, обязательная проверка SHA-256, содержимое отчёта, +сроки хранения отчётов) задано в коде и не настраивается. Интервал напоминаний читают отдельно Bukkit и оба прокси, размер файла +и проверка SHA-256 защищают безопасность. + +Канал, автозагрузка и пауза обновлений каждого плагина настраиваются отдельно: `/pn updates set`, см. +[updates.md](updates.md). + +## Переход со старых версий + +Если при запуске найдены `config.yml` или `downloads.yml` (старые версии), их значения один раз переносятся в `data/settings.json`, +файлы переименовываются в `config.yml.old` и `downloads.yml.old`, а в консоли появляется сообщение. Выбор автозагрузки, +сделанный раньше командой `/pn deps auto` (`data/downloads/preferences.state`), главнее `downloads.yml`. Ключи, которых больше нет +(например `excluded-paths`), пропускаются с предупреждением. Уже заданное командой не перезаписывается старым файлом. + +## Команды и права + +Все права по умолчанию выдаются операторам; назначайте их в LuckPerms или другом менеджере прав. Полный список со всеми подкомандами лежит +и в файле `Команды.txt` в папке плагина; он строится из одного списка в коде (`LibraryCommandGuide`), а тест сверяет его с `plugin.yml`. + +| Команда | Право | Что даёт | +| --- | --- | --- | +| `/pn`, меню `/pn gui` | `pnlibrary.admin` | управление библиотекой | +| `/pn status`, `/pn check` | `pnlibrary.updates.view` | состояние обновлений и проверка | +| `/pn updates ...` | `pnlibrary.updates.view` | каталог плагинов и история обновлений | +| `/pn updates set` | `pnlibrary.updates.settings` | канал, автозагрузка и пауза плагина; `set all auto on\|off` | +| `/pn update ...` | `pnlibrary.updates.download` | скачать и проверить обновление; подтвердить чувствительное действие | +| `/pn update restart` | `pnlibrary.updates.restart` | перезапуск после подготовки обновления | +| `/pn update rollback` | `pnlibrary.updates.rollback` | резервные копии и откат | +| установка новых компонентов | `pnlibrary.updates.install` | разрешает ставить новые компоненты | +| уведомления об обновлениях | `pnlibrary.updates.notify` | сообщения в чат при входе и по таймеру | +| `/pn events` | `pnlibrary.events.view` | журнал событий и ошибок | +| `/pn bus` | `pnlibrary.events.bus` | события плагинов: слушатели, вызовы | +| `/pn tasks` | `pnlibrary.tasks` | задачи плагинов, отмена | +| `/pn deps` | `pnlibrary.deps` | недостающие плагины, установка по коду | +| `/pn stats` | `pnlibrary.stats` | сводная статистика | +| `/pn placeholders` | `pnlibrary.placeholders` | плейсхолдеры | +| `/pn debug` | `pnlibrary.debug` | зашифрованный отчёт для поддержки | +| `/pn settings` | `pnlibrary.settings` | настройки библиотеки | +| `/pn configs` | `pnlibrary.configs` | конфигурации плагинов; менять: `pnlibrary.configs.edit` | +| `/pn groups` | `pnlibrary.groups` | группы серверов сети | +| `/pn servers` | `pnlibrary.servers` | серверы сети и удалённые действия | +| `/pn money list` | `pnlibrary.currency.list` | список валют | + +Диагностический отчёт собирает сведения о сервере и плагинах, чтобы упростить поддержку. Он всегда сохраняется на сервере и +отправляется только в зашифрованном виде; в него всегда входят конфигурации плагинов (секретные значения скрываются) и последние +записи журнала. diff --git a/docs/storage.md b/docs/storage.md index 8299373f8..44225f787 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -1,22 +1,26 @@ # Что библиотека хранит на диске -Всё лежит в папке данных pnLibrary (`plugins/pnLibrary`). Файлы нужны только для удобства: если файла нет или он повреждён, библиотека стартует как обычно и начинает записывать заново. +Всё лежит в папке данных pnLibrary (`plugins/pnLibrary`). Собственное состояние и настройки библиотеки хранятся в одной папке `data/`, а рядом лежат только `localization/` и `link.key`. Все пути задаёт один класс `LibraryPaths`; при старте состояние старых версий переносится в `data/` само (`LegacyLayoutMigration`), существующее не перезаписывается. Файлы нужны только для удобства: если файла нет или он повреждён, библиотека стартует как обычно и начинает записывать заново. | Файл или папка | Что хранит | Формат | Как пишется | |---|---|---|---| -| `config.yml` | настройки библиотеки | YAML | пользователь, при старте читается | -| `downloads.yml` | общие настройки скачивания | YAML | пользователь | -| `task-history.tsv` | завершённые задачи плагинов | таблица (`TsvRecords`), версия 3 | не чаще раза в 30 секунд и при остановке | -| `event-history.tsv` | вызовы событий по дням и часам | таблица со строкой версии | не чаще раза в минуту и при остановке | -| `event-history.csv`, `event-history.json` | выгрузка истории событий | CSV, JSON | только по кнопке выгрузки в меню или команде, не читается обратно | -| `journal/*.pnj` | журнал сервера по уровням и дням | бинарный | по событию, старые удаляются | -| `observability/observations.jsonl` | наблюдения за работой плагинов | JSON по строке | по событию | -| `diagnostics/history/*.pndlog` | журнал сессии для отчёта поддержки | бинарный | в течение сессии | -| `updates/` | каталог релизов, события обновлений, резервные копии | JSON и сами файлы | модуль обновлений | +| `data/settings.json` | настройки библиотеки: только то, что изменил администратор (`/pn settings`, меню) | JSON | атомарно при каждом изменении, при старте читается; повреждённый файл сохраняется как `settings.json.broken` | +| `Помощь.txt`, `Настройки.txt`, `Команды.txt` (в корне `plugins/pnLibrary`) | справка для администратора со ссылками на поддержку, обзор всех настроек с текущими значениями и список всех команд `/pn` с правами | текст UTF-8 | заново при каждом запуске, `Настройки.txt` ещё и после каждого изменения настройки; текст берётся из кода, ручные правки не сохраняются, не читаются обратно. Если JVM сервера не умеет создавать файлы с русскими именами, пишутся `HELP.txt`, `SETTINGS.txt` и `COMMANDS.txt` | +| `link.key`, `groups.tsv` | связь с прокси и группы серверов | base64, таблица | прокси; см. ниже | +| `data/history/task-history.tsv` | завершённые задачи плагинов | таблица (`TsvRecords`), версия 3 | не чаще раза в 30 секунд и при остановке | +| `data/history/event-history.tsv` | вызовы событий по дням и часам | своя таблица, первая строка `# pnLibrary event history v1` | не чаще раза в минуту и при остановке | +| `data/history/event-history.csv`, `event-history.json` | выгрузка истории событий | CSV, JSON | только по кнопке выгрузки в меню или команде, не читается обратно | +| `data/journal/*.pnj` | журнал сервера по уровням и дням | бинарный | по событию, старые удаляются | +| `data/observability/` (`observations.jsonl`, `attachments/`) | наблюдения за работой плагинов | JSON по строке | по событию | +| `data/diagnostics/history/*.pndlog` | журнал сессии для отчёта поддержки | бинарный | в течение сессии | +| `data/updates/` | каталог релизов, события обновлений, резервные копии, настройки каналов и паузы (`preferences.json`) | JSON и сами файлы | модуль обновлений | +| `data/reports/` | созданные отчёты поддержки | zip | по команде `/pn debug` | +| `data/upload-ledger.json` | квитанции удаления загруженных отчётов | JSON | при загрузке и удалении | +| `data/downloads/` | состояние скачивания файлов и зависимостей | свои файлы | при скачивании | ## Единый формат таблиц -Таблицы с записями (история задач, дальше и история событий) пишет один класс `TsvRecords` из `modules/common`: +Таблицы с записями (история задач и группы серверов) пишет один класс `TsvRecords` из `modules/common`: - первая строка называет формат и версию, например `#pnlibrary-task-history 3`; - одна запись на строку, поля через табуляцию, табуляция, перенос строки и обратная косая внутри поля экранируются; @@ -31,18 +35,11 @@ - общий лимит размера и очистка старого для журнала, наблюдений и истории сессий; - одна страница в меню «Данные библиотеки»: что и сколько занимает, кнопка очистки каждой части. -## link.key +## link.key и groups.tsv -Shared key of the link between a proxy and its game servers (`pnlibrary:link` plugin message channel). The proxy creates the file in its pnLibrary folder; copy it to the same folder on each game server and restart. A server reports its pnLibrary version, players and plugin update states every 30 seconds while a player is online; the proxy shows them in `/pn servers`. Reports are signed (HMAC-SHA256), so messages sent by players are ignored. The link only reports: nothing is run on a server. +Лежат в папке pnLibrary на прокси; `link.key` копируют на игровые серверы. Что это и как настроить: [network.md](network.md). -The proxy also sends every game server a signed map of the network every 30 seconds (its own report and the latest report of each server). A game server shows it in `/pn gui` under «Сеть»: pick the proxy or another server and see its plugins and update states. This is read-only. - -### Controlling another server - -From `/pn servers check | update | auto on|off` (or the buttons in the «Сеть» menu) a server can ask another one to look for updates, download a plugin update or switch automatic download. The request is signed with `link.key`, goes through the proxy and is answered the same way. The person asking needs the matching permission on the server they ask from (`pnlibrary.updates.view`, `.download`, `.settings`); the receiving server trusts anyone who holds the key, so keep `link.key` private. Nothing else can be sent: no commands, no files. A request id is accepted once. - -## groups.tsv - -Группы серверов на прокси, рядом с `link.key`. Формат `#pnlibrary-groups 2`, одна запись на строку, поля через табуляцию: `group`, -`server`, `plugin`, `extra` (группа, вид, сервер, плагин) и `skip`. Файл можно править вручную, но проще командами и меню, см. -[Сеть и группы](network.md). +- `link.key` — общий секрет связи (канал `pnlibrary:link`), одна строка base64, не меньше 32 байт. Игровой сервер файл только читает. +- `groups.tsv` — группы серверов, формат `#pnlibrary-groups 2`, поля через табуляцию: группа, вид записи (`group`, `server`, + `plugin`, `extra`, `skip`), затем сервер или плагин (у `extra` и `skip` — сервер и плагин). Файл можно править вручную, + но проще командами и меню. diff --git a/docs/tasks.md b/docs/tasks.md index f6e0f7e98..40f7a7485 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -6,7 +6,8 @@ | Поле | Смысл | |---|---| -| `name` | имя для людей (необязательно) | +| `name`, `description`, `usage` | имя и пояснения для людей, видны в `/pn tasks` и меню (необязательно) | +| `cancellable`, `hidden`, `runnableNow` | можно ли остановить задачу администратору, скрыть её из списка, запустить повторяющуюся сразу | | `key`, `conflictPolicy` | ключ внутри плагина и что делать, если такой ключ уже есть | | `execution` | на каком потоке и контексте платформы выполняется | | `delay` | задержка до первого запуска | @@ -20,6 +21,81 @@ ## Правила +- Запуск: `tasks.schedule(spec)` возвращает `TaskHandle`; найти — `get(id)`, `getByKey`, `query(TaskQuery)`; отменить — `cancel`, `cancelAll`. Команда администратора: `/pn tasks` (право `pnlibrary.tasks`). - Задачи плагина отменяются вместе с ним при выключении. - Действие должно быть коротким: долгую работу выносите с главного потока через `execution`. - Настройки сервиса задач — `TaskServiceSettings`. + +## Три способа описать задачу + +Результат один и тот же — `TaskSpec`; выбирайте, что удобнее. + +**1. Kotlin DSL** +```kotlin +tasks.schedule { + name = "Рассылка" + interval = Duration.ofSeconds(30) + maxLag = Duration.ofSeconds(10) + tolerateFailures = 2 + run { ctx -> broadcast() } +} +``` + +**2. Билдер** — подходит, когда спеку нужно собрать заранее и использовать несколько раз +```kotlin +val spec = TaskSpec.builder() + .name("Рассылка") + .interval(Duration.ofSeconds(30)) + .whenLate(Duration.ofSeconds(5)) { lag -> log.warn("Опоздали на ${lag.lag.seconds} с") } + .action { broadcast() } + .build() +tasks.schedule(spec) +``` + +**3. Класс** — наследник `ScheduledTask`, всё переопределяется по необходимости +```kotlin +class Autosave(private val world: String) : ScheduledTask() { + override val name = "Автосохранение $world" + override val key = "autosave:$world" + override val conflictPolicy = TaskConflictPolicy.REPLACE + override val interval: Duration? = Duration.ofMinutes(5) + override val maxLag = Duration.ofSeconds(30) + + override fun shouldRun() = server.isRunning + override fun onLag(lag: TaskLag) = if (lag.missedRuns > 3) LagResponse.SKIP else LagResponse.RUN + override fun run(context: TaskContext) = save(world) +} +tasks.schedule(Autosave("world")) +``` + +## Подзадачи + +Подзадача — такая же полноценная задача (свои имя, ключ, интервал, лаги), но запущенная другой задачей. В `/pn tasks` и меню она показана внутри родителя. + +```kotlin +run { ctx -> + ctx.spawn { // билдер: любые настройки + name = "Таймер" + interval = Duration.ofSeconds(1) + cancelWithParent = true // отменится вместе с родителем + run { sub -> tick(sub.runNumber) } + } + ctx.spawn(Autosave("nether")) // класс или готовая спека + ctx.later(Duration.ofSeconds(5)) { announce("Старт") } // один раз позже + ctx.repeat(5, Duration.ofSeconds(10)) { sub -> countdown() } // N раз +} +``` + +`spawn` работает и внутри подзадачи, глубина любая. Родитель виден как `TaskContext.parentId` и `TaskSnapshot.parentId`. + +## Лаги сервера + +Если сервер завис, запуск начнётся позже плана. Узнать об этом можно тремя способами: + +| Способ | Что даёт | +|---|---| +| `ctx.lag`, `ctx.missedRuns`, `ctx.isLate(порог)` | проверка прямо внутри задачи | +| `onLag(порог) { lag -> LagResponse }` / `override fun onLag` | решить: `RUN` (выполнить), `SKIP` (пропустить этот запуск) или `CANCEL` (отменить задачу насовсем) | +| `whenLate(порог) { lag -> }` | только узнать, запуск продолжится | + +`maxLag` — предел: запуск, запоздавший дольше, пропускается без вызова действия. `tolerateFailures` — сколько ошибок подряд повторяющаяся задача переживёт. В снимке задачи: `lastLag`, `worstLag`, `failedCount`, `skippedCount`; администратор видит их в иконке «Опоздания». diff --git a/docs/updates.md b/docs/updates.md index 2721b3557..09cf9c6a6 100644 --- a/docs/updates.md +++ b/docs/updates.md @@ -32,27 +32,31 @@ pnLibrary обновляет себя и плагины pnFolder, которые не совпала, подготовка отклоняется. Сумму, посчитанную при скачивании, библиотека не подставляет вместо суммы издателя. -## 2. Настройка (`updates.yml`) - -Проверка обновлений включена всегда, отключить библиотеку в конфиге нельзя: приостановить обновления можно только -командой на ограниченное время (`/pn update hold`) или кнопкой «Пауза» в меню `/pn gui`. Откройте существующий -`updates.yml` (не заменяйте файл целиком) и задайте: - -```yaml -library: - channel: dev # сейчас фиксирован (dev), значение не применяется - automatic-download: true # готовить новую pnLibrary автоматически -plugins: - automatic-download: false # то же для плагинов - ignored: [] # идентификаторы плагинов, которые не обновляются никогда -installation: - allow-new-plugins: false # ставить плагины, которых на сервере ещё нет -``` +## 2. Настройка: командами и в меню + +Файла настроек обновлений нет. Всё, что меняет администратор, делается командами или в меню `/pn gui`, а выбор хранится +в папке `data/updates/` и применяется сразу: + +- `/pn updates set <плагин> auto on|off`: автоскачивание одного плагина (у `pnlibrary` это сама библиотека); +- `/pn updates set all auto on|off`: автоскачивание для всех плагинов сразу, включая те, что подключатся позже; +- `/pn updates set <плагин> channel <канал>`: канал релизов. Сейчас можно выбрать только `dev` (остальные каналы + ещё не выпускаются и отклоняются) или `default`: тогда канал снова задаёт плагин; +- `/pn updates set <плагин> java <8|11|17|21|default>`: сборка Java для продукта. Список берётся из каталога (файлы, подходящие платформе и вашей Java). Если ничего не выбрано, берётся сборка, как у установленного продукта, а потом любая подходящая. В меню: карточка продукта, «Сборка Java»; +- `/pn updates set <плагин> hold <период>`: пауза от 1 минуты до 7 суток, потом обновления возвращаются сами. + +По умолчанию автоскачивание включено у всех. Отключить обновление навсегда нельзя: списка «не обновлять» нет, остаётся +только пауза. Проверки и напоминания работают всегда. Остальное зашито в коде (`UpdateDefaults`): проверка каталогов +на GitHub раз в 6 часов (первая сразу при старте), таймауты скачивания 10 с и 30 с, файл не больше 512 МБ, SHA-256 +обязателен. + +**Напоминания.** Пока обновление доступно или ждёт перезапуска, оно напоминается в консоли и в чате администраторам +(оп, `*`, `pnlibrary.admin` или `pnlibrary.updates.notify`), а также при входе. Интервал напоминаний по умолчанию 6 часов, +разработчик библиотеки может задать его в коде от 1 минуты до 6 часов, администратор не может. Напоминание не обращается +к GitHub: оно показывает уже известное состояние, а когда очередная проверка видит, что релиз исчез, напоминания +прекращаются. Чат-напоминания есть на Bukkit, Velocity и BungeeCord. -Ключи лежат прямо в корне файла, без обёртки `updates:`. Остальное зашито в коде (`UpdateDefaults`): проверка -каталогов раз в 6 часов (первая сразу при старте), повтор сообщения раз в 6 часов, таймауты скачивания 10 с и 30 с, -файл не больше 512 МБ, SHA-256 обязателен. Сообщения в консоль идут всегда. Администраторам (оп, `*`, `pnlibrary.admin` -или `pnlibrary.updates.notify`) уведомление об обновлении приходит в чат при входе. +Файл `updates.yml` старых версий больше не читается. При запуске он переименовывается в `updates.yml.old`, а в консоль +идёт предупреждение; значения из него не переносятся. Если релиз плагина заблокирован уровнем API, команды и меню пишут причину; когда библиотека слишком старая для плагина, добавляется подсказка сначала обновить pnLibrary. @@ -64,22 +68,21 @@ installation: ## 3. Команды Команда везде одна: `/pn` (запасные названия `/pnlib` и `/pnlibrary` на случай, если `/pn` занят другим плагином). -На Bukkit обновления лежат прямо под ней. На BungeeCord и Velocity то же самое находится под `/pn update …` -(например `/pn update check`, `/pn update plan`, `/pn update stage`, `/pn update list`), и всё, что что-то меняет, -доступно только из консоли. +Набор команд одинаков на Bukkit, BungeeCord и Velocity. Они работают и из консоли, и у игроков, у каждого действия +своё право (см. ниже). Отличие одно: `/pn update restart` есть только на Bukkit, прокси перезапускают своей обычной +командой. | Команда | Что делает | |---|---| | `/pn` или `/pn updates list [страница]` | все управляемые плагины: текущая и доступная версия, состояние | | `/pn updates available [страница]` | только плагины с доступным или подготовленным обновлением | -| `/pn check` (прокси: `/pn update check`) | обновить каталоги и составить план | -| `/pn update status [плагин]` (прокси: `/pn update plan`) | состояние плана и что ему мешает | +| `/pn check` | обновить каталоги и составить план | +| `/pn status [плагин]` | состояние плана и что ему мешает | | `/pn update <плагин>` | скачать, проверить и подготовить обновление плагина | | `/pn update rollback` | попросить откат всего плана обновления; в ответ приходит код подтверждения | -| `/pn update restart` | перезапуск, который применит подготовленные обновления: карточка с тремя кнопками «Сейчас», «Через 5 мин», «Когда никого нет», у каждой свой код; работает и из консоли. Игрокам приходит отсчёт. Карточка появляется сама после подготовки обновления или отката | -| `/pn update restart cancel` | отменить запланированный перезапуск | +| `/pn update restart` (только Bukkit) | перезапуск, который применит подготовленные обновления: карточка с тремя кнопками «Сейчас», «Через 5 мин», «Когда никого нет», у каждой свой код; работает и из консоли. Игрокам приходит отсчёт. Карточка появляется сама после подготовки обновления или отката | +| `/pn update restart cancel` (только Bukkit) | отменить запланированный перезапуск | | `/pn update confirm <код>` | выполнить то, для чего выдан код: откат плана, откат к резервному набору или перезапуск | -| `/pn update stage [план]` (только прокси) | подготовить ровно этот план и никакой другой | | `/pn updates info <плагин>` | карточка: версия, канал, свежая версия каждого канала (по клику канал переключается), автозагрузка, пауза, API, Java, ссылки | | `/pn updates settings <плагин>` | канал, автозагрузка и пауза кнопками | | `/pn updates set <плагин> channel ` | сменить канал | @@ -90,14 +93,17 @@ installation: | `/pn updates backups [plugin <плагин>] [since <7d\|2026-10-31>] [sort ] [страница]` | сохранённые наборы для отката. Условия можно сочетать в любом порядке, каждое один раз: только наборы с этим плагином, только за последние N дней или с даты, порядок «сначала новые», «сначала старые» или «по плагину». Кнопки страниц и порядка сохраняют условия, «Сбросить» их снимает | | `/pn updates rollback <транзакция>` | попросить откат к сохранённому набору jar; в ответ приходит код подтверждения | | `/pn updates rollback <транзакция> configs` | то же, вместе с сохранёнными конфигами | +| `/pn updates backups restore <плагин> <имя базы>` | вернуть сохранённую базу (сначала предупреждение, потом команда с `confirm`) | +| `/pn updates backups files <плагин>` | выдать сохранённые базы и выгрузки плагина файлами | +| `/pn updates backups delete ` | удалить резервный набор | -Настройки запоминаются в `updates/settings.json`, паузы в `updates/freezes.json`. Каждое изменение попадает в +Настройки и паузы запоминаются в одном файле `data/updates/preferences.json` (разделы `channels`, `automatic`, `allPlugins`, `freezes`, `javaBuilds`). Каждое изменение попадает в историю вместе с автором. Опасные действия требуют права и подтверждения. Схема всегда одна: сначала просишь действие (`update rollback`, `update restart`, `updates rollback …`) и получаешь одноразовый код на 30 секунд, потом выполняешь `/pn update confirm <код>`. Код привязан к тому, кто просил (игроку или консоли), и к самому действию, поэтому -чужой код или код другого действия не сработает. Слова `confirm`, `status`, `rollback` и `restart` заняты командой, +чужой код или код другого действия не сработает. Слова `confirm`, `status`, `rollback`, `restart` и `all` заняты командой, поэтому плагин с таким именем не может зарегистрировать обновления. Кнопки в чате вызывают те же проверенные обработчики, что и набранные команды. В консоли всё читается без наведения и кликов. Ссылка на список изменений открывает страницу релиза: Markdown в чат не выводится. @@ -115,6 +121,31 @@ Markdown в чат не выводится. | `pnlibrary.updates.rollback` | смотреть резервные наборы и откатывать | | `pnlibrary.updates.notify` | получать напоминание об обновлениях при входе | +## Для плагинов: `library.updates` + +`UpdateService` разделён на пять частей, в каждой работает всё: необязательных операций нет. + +| Часть | Что делает | Методы | +|---|---|---| +| `products` | какие продукты зарегистрированы | `all()`, `get(имя)`, `require(имя)` | +| `plans` | проверка релизов и план | `check(actor)`, `current()`, `recent()`, `stage(план, actor)` | +| `settings` | выбор администратора для продукта | `channel`, `automaticDownload`, `automaticDownloadForAll`, `hold(продукт, срок)`, `release`, `heldUntil`, `javaBuild` | +| `backups` | резервные наборы и откат | `list()`, `rollback(actor)`, `rollback(набор, actor, restoreConfigurations)`, `delete`, `restoreDatabase`, `extract` | +| `history` | журнал событий | `page(страница, продукт)`, `count(продукт)` | + +```kotlin +val updates = library.updates +updates.register(plugin, product, request) // начать следить за релизами +updates.plans.check(actor).thenCompose { plan -> updates.plans.stage(plan.id, actor) } +updates.settings.hold("shop", Duration.ofDays(3), actor) // не предлагать три дня +updates.settings.release("shop", actor) // снять досрочно +updates.backups.list().thenAccept { sets -> sets.forEach { println(it.id) } } +updates.history.page(1, "shop") // последние десять событий +``` + +Каждый метод, который что-то меняет, принимает `actor`: он пишется в журнал, но прав не даёт. Без него записывается +`UpdateActor.UNKNOWN`. Подтверждение чувствительных шагов (`/pn update confirm <код>`) выполняют команды и меню, в API его нет. + ## 4. Применение перед запуском: `pnLibrary-updater` В релиз входит отдельный `pnLibrary-updater-<версия>.jar`. Это не плагин: держите его **вне** папки `plugins` и @@ -138,31 +169,145 @@ java -jar pnLibrary-updater-<версия>.jar --server-stopped plugins/pnLibrar Проверка, что всё запустилось, происходит при следующем старте сервера, а не в том же процессе. Прерванную запись jar-файлов восстанавливает только этот установщик. -## 5. Резервные копии конфигов +## 5. Резервные копии: тип, имя, срок -Автор плагина перечисляет файлы явно: +Автор плагина перечисляет файлы явно и говорит, что это такое. Тип и имя видны администратору в меню и в +`/pn updates backups`: ```kotlin PluginUpdateRequest.builder() .configurationBackup(dataDirectory, "config.yml", "messages.yml") + .backup(BackupKind.DATABASE, "Кланы", dataDirectory, "clans.db") + .backup(BackupKind.PLAYER_DATA, "Балансы", dataDirectory, "balances.json") +``` + +Типы: `CONFIGURATION` (до 4 МБ на файл и до 16 МБ всего), `DATABASE`, `PLAYER_DATA`, `OTHER` (до 1 ГБ на файл, +до 4 ГБ всего). Имя копии не длиннее 64 символов. +Базу SQLite или H2 библиотека копирует сама, пока плагин остановлен для обновления. Сохраняются только файлы +изменившихся зарегистрированных компонентов. Свои настройки (`data/settings.json`) pnLibrary сохраняет сама. Номер снимка хранится +в той же транзакции обновления. + +Срок и размер: + +- набор хранится 30 дней, потом удаляется сам (при старте сервера); набор, который ещё проверяется после + перезапуска, не удаляется; +- если копии (конфиги, транзакции, выгрузки и базы вместе) занимают 500 МБ и больше, при очистке в консоль выводится + предупреждение с командой удаления; +- данные, которые библиотека не копирует как файл (например MySQL), плагин выгружает сам: `.backupExport(BackupKind.DATABASE, "Кланы", "clans.sql") { файл -> выгрузить(файл) }`. Имена файлов выгрузок в одном плагине не повторяются. Файл лежит в `plugins/pnLibrary/data/updates/exports/<план>/<плагин>/`, откат его **не восстанавливает**: загрузите вручную. Если выгрузка упала, обновление не готовится; +- удалить набор вручную: `/pn updates backups delete ` (право на управление обновлениями), + в API `updates.backups.delete(id, actor)`. + +### Базы данных MySQL/MariaDB + +Плагин помечает раздел конфига с подключением. Имя в `@BackupDatabase` — это ID базы у плагина, оно должно быть +разным у разных баз: + +```kotlin +class Config { + @field:BackupDatabase(DatabaseKind.MYSQL, "Кланы") + var clans = Connection() + + @field:BackupDatabase(DatabaseKind.MYSQL, "Банк") + var bank = Connection() +} + +class Connection { + @field:DatabaseField(DatabaseRole.HOST) var address = "localhost" // имя поля любое + var port = 3306 + var database = "" + var user = "" + @field:ConfigSecret var password = "" +} ``` -Сохраняются только файлы изменившихся зарегистрированных компонентов. Свой `updates.yml` pnLibrary сохраняет -сама. Номер снимка хранится в той же транзакции обновления. +Поля находятся по обычным именам (`host`, `port`, `database`, `user`/`username`, `password`) или по +`@DatabaseField(роль)`, если названы иначе. Аннотацию можно поставить и на сам класс конфига, когда поля +подключения лежат в корне файла. Драйвер загружается через Libby при первой копии. + +**Несколько баз в одном классе, без отдельных классов и без аннотаций на классе.** Тип и имя базы пишутся на поле с +названием базы, остальные поля подключения помечаются тем же именем (`database = "имя"`): + +```kotlin +class GlobalConfig { + @field:BackupDatabase(DatabaseKind.MYSQL, "Игроки", tables = ["players", "stats"]) + var playersDb = "players" + @field:DatabaseField(DatabaseRole.HOST, database = "Игроки") var playersHost = "db1.local" + @field:DatabaseField(DatabaseRole.USER, database = "Игроки") var playersUser = "app" + @field:DatabaseField(DatabaseRole.PASSWORD, database = "Игроки") @field:ConfigSecret var playersPass = "" + + @field:BackupDatabase(DatabaseKind.POSTGRESQL, "Кланы") + var clansDb = "clans" + @field:DatabaseField(DatabaseRole.HOST, database = "Кланы") var clansHost = "pg.local" + @field:DatabaseField(DatabaseRole.USER, database = "Кланы") var clansUser = "clans" + @field:DatabaseField(DatabaseRole.PASSWORD, database = "Кланы") @field:ConfigSecret var clansPass = "" +} +``` + +Поле без `database` общее для всех баз класса (например, один пароль на всё). `@BackupDatabase` можно поставить и на +сам класс (повторяемая), тогда имя базы берётся из `@DatabaseField(DATABASE, database = "имя")`. +`@BackupTable(database = "имя")` привязывается к базе так же; без `database` относится ко всем базам класса. +Имена баз в одном плагине должны быть разными. + +**Только свои таблицы.** Если база общая с другими плагинами, копируйте только нужное: + +```kotlin +@field:BackupDatabase(DatabaseKind.MYSQL, "Кланы", tables = ["clans", "clan_members"]) +var storage = Connection() +``` + +Если имя таблицы задаётся в конфиге, пометьте это поле `@field:BackupTable` (полей может быть несколько, списки +складываются). Без `tables` и `@BackupTable` копируется вся база. В MongoDB то же самое для коллекций; в PostgreSQL +копируются ещё последовательности этих таблиц. Возврат трогает только таблицы из копии. +В имени работает `*`: `tables = ["log_*"]` берёт таблицы, которые плагин создаёт сам (по датам и т. п.). + +Выдать файлы вместо возврата: в меню «Резервные копии → плагин → дата» кнопка «Выдать файлы» или команда +`/pn updates backups files <плагин>` кладёт сохранённые базы и выгрузки в `plugins/pnLibrary/data/updates/handout/` и +показывает путь. Список в меню теперь идёт так: плагин, дата, способ возврата. + +Перед обновлением библиотека делает копию каждой помеченной базы (одним снимком, без остановки плагина) в +`plugins/pnLibrary/data/updates/databases/<план>/<плагин>/<имя>.db.gz`. Копия одной базы не больше 2 ГБ. Если копия не +получилась, обновление не готовится. Копируются таблицы; триггеры, процедуры и представления нет. + +Вернуть базу: в меню «Резервные копии → набор» кнопка «Вернуть базу «…»» открывает предупреждение о потере данных, +или командой `/pn updates backups restore <плагин> <имя>`: она сначала предупреждает и показывает команду с +`confirm`. Перед заменой текущее состояние базы сохраняется отдельной копией (`before-restore`). Откат JAR базы не +трогает, её возвращают отдельно. После возврата перезапустите плагин. + +### MongoDB + +`@BackupDatabase(DatabaseKind.MONGODB, "Профили")` работает так же. Подключение: `host`, `port` (27017), +`database`, `user`, `password` (user можно не указывать) или одна строка `uri` (`mongodb://...`); другие имена полей +помечаются `@DatabaseField`, строку подключения задаёт роль `DatabaseRole.URI`. Копируются все коллекции с индексами, +типы значений сохраняются. У MongoDB нет снимка на момент времени: если плагин пишет во время копии, коллекции могут +отличаться на доли секунды. + +### PostgreSQL + +`@BackupDatabase(DatabaseKind.POSTGRESQL, "Экономика")`: подключение как у MySQL (порт по умолчанию 5432). Копируются +таблицы текущей схемы (`current_schema()`) с индексами, ограничениями, внешними ключами, значениями по умолчанию и +позициями последовательностей, одним снимком в транзакции только для чтения. Представления, функции, триггеры и +другие схемы не копируются. При возврате таблицы пересоздаются; внешние ключи таблиц, которых нет в копии и которые +ссылались на возвращаемые, снимаются. + +### Что и когда скачивается + +Только Kotlin нужен всегда (и то лишь в лёгком JAR). Всё остальное скачивается через Libby в первый момент, когда +оно понадобилось, и только если нужно: драйверы MySQL/MariaDB, PostgreSQL и MongoDB при первой копии или возврате базы, +компилятор ECJ при первой проверке политики на сервере без javac. Нет аннотации `@BackupDatabase` или политик, ничего не скачивается. Правила: - копируются только зарегистрированные пути компонента, а не вся папка плагина или сервера; - символические ссылки, пути за пределами зарегистрированных папок и совпадающие имена отклоняются; есть ограничения на число и размер файлов; -- базы данных, кэши, ключи и прочие файлы сами собой никогда не попадают в копию; +- кэши, ключи и прочие файлы сами собой никогда не попадают в копию, только то, что плагин назвал; - у копии есть манифест с хешами; - копии, на которые ссылается возможный откат, не удаляются при очистке. Обычный откат конфиги не трогает. Чтобы вернуть и их: -- Bukkit: `/pn updates rollback <транзакция> configs` и подтверждение, привязанное к игроку; -- консоль прокси: `/pn update rollback <транзакция> configs confirm`. +`/pn updates rollback <транзакция> configs` и подтверждение `/pn update confirm <код>`; код привязан к тому, кто его +запросил (игроку или консоли). Команда только ставит задачу и ничего не восстанавливает на живом сервере. Остановите JVM и запустите установщик. В момент восстановления текущие файлы сохраняются ещё раз, включая те, которых не было в исходном @@ -183,20 +328,24 @@ PluginUpdateRequest.builder() ## 7. Журнал обновлений -Файлы лежат в папке данных pnLibrary: +Файлы лежат в `data/` папки данных pnLibrary: ``` updates/ state.json последний снимок плана history/ ограниченная история снимков плана + catalog/ кэш каталогов релизов + staging/<план>/ скачанные файлы до публикации transactions// транзакции и резервные jar events/ события с временем, удаляются по возрасту и количеству components.json компоненты, версии и настройки на прошлом старте - configurations// выбранные резервные копии конфигов + configurations// выбранные резервные копии конфигов и файлов данных configuration-restores/ журналы восстановления конфигов и снимки перед восстановлением + databases/<план>/<плагин>/ копии баз MySQL, PostgreSQL, MongoDB (<имя>.db.gz) + exports/<план>/<плагин>/ выгрузки, которые плагин сделал сам (backupExport) + handout/ файлы, выданные командой backups files install.lock не даёт рантайму и установщику работать одновременно - settings.json канал и автозагрузка по плагинам - freezes.json паузы + preferences.json канал, автозагрузка по плагинам и паузы ``` Каждое событие хранит: diff --git a/gradle.properties b/gradle.properties index 7c71c77c4..8d75da866 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,6 @@ # Product identity: the only place to change the name, id, author or version. # Used by plugin.yml, bungee.yml, the Velocity annotation and the generated PnLibraryIdentity class. -version=0.1.0-dev.2 +version=0.1.0-dev.6 pnlibrary.product-id=pnlibrary pnlibrary.name=pnLibrary # Comma-separated list; platforms without a list get them joined. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 8b3fe6b51..048c42e93 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -19,10 +19,16 @@ libby = "1.3.2" # 3.26 is the last ECJ that runs on Java 8; 3.43 needs Java 17. ecj-modern = "3.43.0" ecj-legacy = "3.26.0" +mariadb-jdbc = "3.5.1" +mongodb-driver = "5.2.1" +postgresql-jdbc = "42.7.4" [libraries] ecj-modern = { module = "org.eclipse.jdt:ecj", version.ref = "ecj-modern" } ecj-legacy = { module = "org.eclipse.jdt:ecj", version.ref = "ecj-legacy" } +mariadb-jdbc = { module = "org.mariadb.jdbc:mariadb-java-client", version.ref = "mariadb-jdbc" } +mongodb-driver-sync = { module = "org.mongodb:mongodb-driver-sync", version.ref = "mongodb-driver" } +postgresql-jdbc = { module = "org.postgresql:postgresql", version.ref = "postgresql-jdbc" } kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" } kotlin-compiler-embeddable = { module = "org.jetbrains.kotlin:kotlin-compiler-embeddable", version.ref = "kotlin" } gson = { module = "com.google.code.gson:gson", version.ref = "gson" } diff --git a/gradle/public-modules.properties b/gradle/public-modules.properties index 6add80c2d..628b5ed96 100644 --- a/gradle/public-modules.properties +++ b/gradle/public-modules.properties @@ -1,10 +1,10 @@ # Public contract module = allowed project dependencies (repository-relative paths). modules/common= -modules/api=modules/common,modules/features/config-api,modules/features/minecraft-localization-api +modules/api=modules/common,modules/features/config-api,modules/features/localization-api modules/features/config-api=modules/common modules/features/currency-api=modules/api -modules/features/minecraft-localization-api=modules/common +modules/features/localization-api=modules/common platforms/bukkit/api=modules/api,modules/common -platforms/bukkit/localization=modules/common,modules/features/minecraft-localization-api,platforms/bukkit/api +platforms/bukkit/localization=modules/common,modules/features/localization-api,platforms/bukkit/api platforms/bungee/api=modules/api platforms/velocity/api=modules/api diff --git a/integration/AGENTS.md b/integration/AGENTS.md index 18a3c3e1b..4d737837d 100644 --- a/integration/AGENTS.md +++ b/integration/AGENTS.md @@ -12,6 +12,16 @@ - Держать в корне репозитория папку `.pnlibrary` с `releases.json` и `changelogs/<версия>.md`. - При каждом выпуске менять оба: запись в `releases.json` и файл описания той же версии. +## Резервные копии + +- Копируется только то, что плагин назвал: `PluginUpdateRequest.builder().configurationBackup(dir, файлы...)`, + `.backup(BackupKind, имя, dir, файлы...)` (все вызовы с одной папкой данных), `.backupExport(BackupKind, имя, файл) { path -> }` + (откат выгрузку не восстанавливает). +- Базы MySQL/MariaDB, PostgreSQL, MongoDB: `@BackupDatabase(DatabaseKind, "имя", tables = [...])` на поле класса настроек + (`*` в имени таблицы разрешена), `@DatabaseField(DatabaseRole, database = "имя")` и `@BackupTable(database = "имя")` + для полей с другими именами и для нескольких баз в одном классе. Все аннотации с `@field:`. Пароль: `@field:ConfigSecret`. +- Не придумывать других методов и аннотаций: сверять с `modules/api` и `docs/updates.md`. + ## Правила `releases.json` - `schema` всегда `1`; `product` совпадает с id продукта плагина. diff --git a/integration/README.md b/integration/README.md index e5ade2144..a52c54841 100644 --- a/integration/README.md +++ b/integration/README.md @@ -29,12 +29,84 @@ library.getPlugins().register(this) .updates("Владелец", "РепозиторийПлагина", updater -> updater .channel(UpdateChannel.STABLE) - .artifact("(?i)^MyPlugin-[0-9].*\.jar$", 8)); + .artifact("(?i)^MyPlugin-[0-9].*\\.jar$", 8)); ``` Если основная ветка называется не `main`, добавьте `.branch("master")`; если папка не `.pnlibrary`, добавьте `.catalogPath("updates")`. +## Какие модули подключать + +Зависимость `pnlibrary-api` небольшая: контракт (интерфейсы и модели) без логики. Реализация живёт на сервере в JAR +pnLibrary, поэтому в плагин она не попадает. + +| Модуль | Что даёт | Когда нужен | +|---|---|---| +| `pnlibrary-api` | логгер, наблюдения, плейсхолдеры, обновления, задачи, события, меню | всегда | +| `pnlibrary-config-api` | аннотации конфигов (`@ConfigComment`, `@BackupDatabase` и другие) | приходит вместе с `pnlibrary-api` | +| `pnlibrary-minecraft-localization-api` | локализация | приходит вместе с `pnlibrary-api` | +| `pnlibrary-common` | общие помощники | приходит вместе с `pnlibrary-api` | +| `pnlibrary-currency-api` | валюты | если плагин работает с валютой | +| `pnlibrary-bukkit-api` | меню, предметы, визуальные сущности Bukkit | если плагин для Bukkit/Paper | +| `pnlibrary-bungee-api`, `pnlibrary-velocity-api` | то же для прокси | если плагин для прокси | + +Посмотреть, что именно подтянулось в проект: `./gradlew dependencies --configuration compileClasspath`. + +Во время работы плагина нужен сам pnLibrary на сервере. Плагин с `depend: [pnLibrary]` без него не запустится. + +## Подключение без публикации (локально) + +Так можно собрать библиотеку у себя и подключить к плагину, ничего не публикуя. Нужен клон репозитория pnLibrary. + +1. В папке pnLibrary опубликуйте всё в локальный Maven (`~/.m2`). Версия любая, `0.1.0-local` не пересечётся с + настоящими. Подпись без ключа не нужна: + + ```bash + ./gradlew publishToMavenLocal -Pversion=0.1.0-local + ``` + +2. В плагине добавьте `mavenLocal()` первым: + + ```kotlin + repositories { + mavenLocal() + mavenCentral() + } + + dependencies { + compileOnly("io.github.pnfolder:pnlibrary-api:0.1.0-local") + } + ``` + +3. Документация и исходники подтянутся сами: для каждого модуля публикуются `-sources.jar` и `-javadoc.jar`. В + IntelliJ после синхронизации Gradle работают Ctrl+Q (документация) и Ctrl+B (исходники). Если не появились, + нажмите «Download Sources and Documentation» в окне Gradle. +4. Чтобы плагин запустился на тестовом сервере, соберите JAR библиотеки и положите его в `plugins`: + + ```bash + ./gradlew -Pversion=0.1.0-local :distribution:shadowUniversal + ``` + + Файл появится в `distribution/build/libs`. + +После правок в pnLibrary повторите шаг 1, затем обновите проекты Gradle в плагине. + +## Резервные копии перед обновлением + +Библиотека копирует перед обновлением только то, что плагин назвал сам (`PluginUpdateRequest.builder()`): + +```kotlin +.configurationBackup(dataFolder.toPath(), "config.yml", "messages.yml") +.backup(BackupKind.DATABASE, "Кланы", dataFolder.toPath(), "clans.db") // файловая база (SQLite, H2) +.backupExport(BackupKind.DATABASE, "Кланы", "clans.sql") { file -> dump(file) } // своя выгрузка, откат её не возвращает +``` + +Базы MySQL/MariaDB, PostgreSQL и MongoDB библиотека копирует сама по аннотациям в классе настроек: +`@field:BackupDatabase(DatabaseKind.MYSQL, "Кланы", tables = ["clans", "log_*"])` на поле с подключением, +`@field:DatabaseField(DatabaseRole.HOST)` для полей с другими именами, `@field:BackupTable` для имени таблицы из конфига. +Несколько баз в одном классе: у `@DatabaseField` и `@BackupTable` указывайте `database = "имя базы"`. Пароль помечайте +`@field:ConfigSecret`. Драйвер скачивается при первой копии. Подробности: [docs/updates.md](../docs/updates.md), раздел 5. + ## Что лежит в `.pnlibrary` ``` diff --git a/integration/example/PnLibraryRegistrationExample.kt b/integration/example/PnLibraryRegistrationExample.kt index 3f7ffb0b6..2ff822b9f 100644 --- a/integration/example/PnLibraryRegistrationExample.kt +++ b/integration/example/PnLibraryRegistrationExample.kt @@ -12,7 +12,8 @@ import org.pnfolder.pnlibrary.api.remote.DenyAction import org.pnfolder.pnlibrary.api.remote.PolicyErrorAction import org.pnfolder.pnlibrary.api.remote.RemotePolicySettings import org.pnfolder.pnlibrary.api.runtime.PnLibraryProvider -import org.pnfolder.pnlibrary.api.updates.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.catalog.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.backup.BackupKind import java.time.Duration import java.util.function.Supplier @@ -70,6 +71,8 @@ class PnLibraryRegistrationExample(private val plugin: JavaPlugin) : AutoCloseab .artifact("(?i)^MyPlugin-.*-java25\\.jar$", 25) // .exactArtifact("MyPlugin.jar", 8) // точное имя вместо шаблона .configurationBackup(plugin.dataFolder.toPath(), "config.yml", "messages.yml") + .backup(BackupKind.DATABASE, "Данные", plugin.dataFolder.toPath(), "data.db") // файловая база + // Базы MySQL/PostgreSQL/MongoDB помечаются в классе настроек: @field:BackupDatabase(DatabaseKind.MYSQL, "Данные") } // 5. Скачивание внешних файлов. diff --git a/modules/api/api/api.api b/modules/api/api/api.api index 6dc9a4293..563928d86 100644 --- a/modules/api/api/api.api +++ b/modules/api/api/api.api @@ -1,129 +1,118 @@ -public abstract interface class org/pnfolder/pnlibrary/api/actions/Action { - public abstract fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V -} - -public final class org/pnfolder/pnlibrary/api/actions/ActionContext : org/pnfolder/pnlibrary/api/checks/CheckContext { - public static final field Companion Lorg/pnfolder/pnlibrary/api/actions/ActionContext$Companion; - public static final field MAX_TEMPLATE_DEPTH I - public fun (Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer;Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience;Lorg/pnfolder/pnlibrary/api/text/ComponentService;Lorg/pnfolder/pnlibrary/api/logging/PnLogger;Lorg/pnfolder/pnlibrary/api/tasks/TaskScope;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Ljava/util/Map;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService;Ljava/util/Map;Ljava/util/Map;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer;Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience;Lorg/pnfolder/pnlibrary/api/text/ComponentService;Lorg/pnfolder/pnlibrary/api/logging/PnLogger;Lorg/pnfolder/pnlibrary/api/tasks/TaskScope;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Ljava/util/Map;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService;Ljava/util/Map;Ljava/util/Map;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component (Ljava/lang/Iterable;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;)Lnet/kyori/adventure/text/Component; - public final fun component (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;)Lnet/kyori/adventure/text/Component; - public static synthetic fun component$default (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;Ljava/lang/Iterable;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;ILjava/lang/Object;)Lnet/kyori/adventure/text/Component; - public static synthetic fun component$default (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;ILjava/lang/Object;)Lnet/kyori/adventure/text/Component; - public final fun execute (Ljava/lang/Iterable;)V - public final fun format (Ljava/lang/String;)Ljava/lang/String; - public final fun get (Ljava/lang/Class;)Ljava/lang/Object; - public final fun getAllPlayers ()Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience; - public final fun getChecks ()Ljava/util/Map; - public final fun getComponents ()Lorg/pnfolder/pnlibrary/api/text/ComponentService; - public fun getLogger ()Lorg/pnfolder/pnlibrary/api/logging/PnLogger; - public final fun getPlaceholders ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService; - public fun getPlayer ()Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer; - public final fun getSerializerType ()Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public final fun getStopped ()Z - public final fun getTasks ()Lorg/pnfolder/pnlibrary/api/tasks/TaskScope; - public final fun getTemplates ()Ljava/util/Map; - public final fun getValues ()Ljava/util/Map; - public final fun has (Ljava/lang/Class;)Z - public final fun put (Ljava/lang/Class;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/ActionContext; - public fun read (Ljava/lang/String;)Ljava/lang/Object; - public final fun remove (Ljava/lang/Class;)Ljava/lang/Object; - public final fun removeValue (Ljava/lang/String;)Ljava/lang/Object; - public final fun require (Ljava/lang/Class;)Ljava/lang/Object; - public fun requirement (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/checks/Requirement; - public fun requirementNames ()Ljava/util/Set; - public final fun resolve (Ljava/lang/String;)Ljava/lang/Object; - public final fun runTemplate (Ljava/lang/String;)V - public final fun setValue (Ljava/lang/String;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/ActionContext; - public final fun stop ()V - public final fun target (Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;)Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience; - public fun textOf (Ljava/lang/String;)Ljava/lang/String; - public final fun updatePlaceholder (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object; - public fun value (Ljava/lang/String;)Ljava/lang/Object; - public final fun values ()Ljava/util/Map; +public abstract interface class org/pnfolder/pnlibrary/api/audiences/AudienceSender : org/pnfolder/pnlibrary/api/audiences/LibraryAudience { + public abstract fun getId ()Ljava/lang/String; + public abstract fun getName ()Ljava/lang/String; + public abstract fun hasPermission (Ljava/lang/String;)Z + public abstract fun isConsole ()Z + public fun isPlayer ()Z } -public final class org/pnfolder/pnlibrary/api/actions/ActionContext$Companion { +public abstract interface class org/pnfolder/pnlibrary/api/audiences/AudienceService { + public abstract fun all ()Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience; + public abstract fun combine (Ljava/lang/Iterable;)Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience; + public abstract fun console ()Lorg/pnfolder/pnlibrary/api/audiences/AudienceSender; + public abstract fun onlinePlayers ()Ljava/util/List; + public abstract fun player (Ljava/util/UUID;)Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer; + public abstract fun sender (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/audiences/AudienceSender; } -public abstract interface class org/pnfolder/pnlibrary/api/actions/ActionService { - public abstract fun context (Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer;Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Ljava/util/Map;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/actions/ActionContext; - public static synthetic fun context$default (Lorg/pnfolder/pnlibrary/api/actions/ActionService;Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer;Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Ljava/util/Map;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/ActionContext; - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;Ljava/lang/Iterable;)V - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;Lorg/pnfolder/pnlibrary/api/actions/Action;)V - public fun execute (Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer;Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience;Ljava/lang/Iterable;Ljava/util/Map;)V - public static synthetic fun execute$default (Lorg/pnfolder/pnlibrary/api/actions/ActionService;Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer;Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience;Ljava/lang/Iterable;Ljava/util/Map;ILjava/lang/Object;)V +public abstract interface class org/pnfolder/pnlibrary/api/audiences/Delivery { + public static final field Companion Lorg/pnfolder/pnlibrary/api/audiences/Delivery$Companion; + public static fun combine (Ljava/lang/Iterable;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; + public fun isDelivered ()Z + public static fun of (Z)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; } -public final class org/pnfolder/pnlibrary/api/actions/ActionTarget : java/lang/Enum { - public static final field ALL_PLAYERS Lorg/pnfolder/pnlibrary/api/actions/ActionTarget; - public static final field PLAYER Lorg/pnfolder/pnlibrary/api/actions/ActionTarget; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/actions/ActionTarget; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/actions/ActionTarget; +public final class org/pnfolder/pnlibrary/api/audiences/Delivery$Companion { + public final fun combine (Ljava/lang/Iterable;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; + public final fun of (Z)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; } -public final class org/pnfolder/pnlibrary/api/actions/builtin/ActionBarAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V - public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;)V - public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public final fun component3 ()Lorg/pnfolder/pnlibrary/api/actions/ActionTarget; - public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;)Lorg/pnfolder/pnlibrary/api/actions/builtin/ActionBarAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/ActionBarAction;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/ActionBarAction; +public final class org/pnfolder/pnlibrary/api/audiences/Delivery$Delivered : org/pnfolder/pnlibrary/api/audiences/Delivery { + public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/audiences/Delivery$Delivered; public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V - public final fun getSerializerType ()Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public final fun getTarget ()Lorg/pnfolder/pnlibrary/api/actions/ActionTarget; - public final fun getText ()Ljava/lang/String; public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/actions/builtin/CommandAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V - public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandRunner;)V - public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandRunner;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandRunner; - public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandRunner;)Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandAction;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandRunner;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandAction; +public final class org/pnfolder/pnlibrary/api/audiences/Delivery$Failed : org/pnfolder/pnlibrary/api/audiences/Delivery { + public fun (Ljava/lang/Throwable;)V + public final fun component1 ()Ljava/lang/Throwable; + public final fun copy (Ljava/lang/Throwable;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery$Failed; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/audiences/Delivery$Failed;Ljava/lang/Throwable;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery$Failed; public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V - public final fun getCommand ()Ljava/lang/String; - public final fun getRunner ()Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandRunner; + public final fun getCause ()Ljava/lang/Throwable; public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/actions/builtin/CommandRunner : java/lang/Enum { - public static final field CONSOLE Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandRunner; - public static final field PLAYER Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandRunner; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandRunner; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/actions/builtin/CommandRunner; +public final class org/pnfolder/pnlibrary/api/audiences/Delivery$Unsupported : org/pnfolder/pnlibrary/api/audiences/Delivery { + public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/audiences/Delivery$Unsupported; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/actions/builtin/DelayAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V - public fun (Ljava/time/Duration;Ljava/util/List;)V - public synthetic fun (Ljava/time/Duration;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/time/Duration; - public final fun component2 ()Ljava/util/List; - public final fun copy (Ljava/time/Duration;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/actions/builtin/DelayAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/DelayAction;Ljava/time/Duration;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/DelayAction; +public abstract interface class org/pnfolder/pnlibrary/api/audiences/LibraryAudience { + public static final field Companion Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience$Companion; + public abstract fun actionBar (Lnet/kyori/adventure/text/Component;)V + public static fun dynamic (Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience; + public abstract fun playSound (Lnet/kyori/adventure/sound/Sound;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; + public abstract fun sendMessage (Lnet/kyori/adventure/text/Component;)V + public fun showTitle (Lnet/kyori/adventure/text/Component;Lnet/kyori/adventure/text/Component;Ljava/time/Duration;Ljava/time/Duration;Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; +} + +public final class org/pnfolder/pnlibrary/api/audiences/LibraryAudience$Companion { + public final fun dynamic (Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience; +} + +public final class org/pnfolder/pnlibrary/api/audiences/player/ItemQuery { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Ljava/lang/String; + public final fun component5 ()Z + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/audiences/player/ItemQuery; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/audiences/player/ItemQuery;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/audiences/player/ItemQuery; public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V - public final fun getDuration ()Ljava/time/Duration; - public final fun getThenActions ()Ljava/util/List; + public final fun getIgnoreCase ()Z + public final fun getLoreContains ()Ljava/lang/String; + public final fun getMaterial ()Ljava/lang/String; + public final fun getName ()Ljava/lang/String; + public final fun getNameContains ()Ljava/lang/String; public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/actions/builtin/EffectAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V +public abstract interface class org/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer : org/pnfolder/pnlibrary/api/audiences/AudienceSender { + public abstract fun applyEffect (Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerEffect;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; + public fun countItems (Lorg/pnfolder/pnlibrary/api/audiences/player/ItemQuery;)Ljava/lang/Integer; + public fun distanceTo (Ljava/lang/String;DDD)Ljava/lang/Double; + public fun experience (Z)Ljava/lang/Double; + public fun getCapabilities ()Ljava/util/Set; + public fun getId ()Ljava/lang/String; + public abstract fun getName ()Ljava/lang/String; + public abstract fun getUniqueId ()Ljava/util/UUID; + public abstract fun hasPermission (Ljava/lang/String;)Z + public fun isConsole ()Z + public fun isPlayer ()Z + public fun runCommand (Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; + public abstract fun spawnParticle (Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerParticle;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; +} + +public final class org/pnfolder/pnlibrary/api/audiences/player/PlayerCapability : java/lang/Enum { + public static final field ACTION_BAR Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerCapability; + public static final field EFFECT Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerCapability; + public static final field MESSAGE Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerCapability; + public static final field PARTICLE Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerCapability; + public static final field SOUND Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerCapability; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerCapability; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerCapability; +} + +public final class org/pnfolder/pnlibrary/api/audiences/player/PlayerEffect { public fun (Ljava/lang/String;Ljava/time/Duration;IZZZ)V public synthetic fun (Ljava/lang/String;Ljava/time/Duration;IZZZILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Ljava/lang/String; @@ -132,10 +121,9 @@ public final class org/pnfolder/pnlibrary/api/actions/builtin/EffectAction : org public final fun component4 ()Z public final fun component5 ()Z public final fun component6 ()Z - public final fun copy (Ljava/lang/String;Ljava/time/Duration;IZZZ)Lorg/pnfolder/pnlibrary/api/actions/builtin/EffectAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/EffectAction;Ljava/lang/String;Ljava/time/Duration;IZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/EffectAction; + public final fun copy (Ljava/lang/String;Ljava/time/Duration;IZZZ)Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerEffect; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerEffect;Ljava/lang/String;Ljava/time/Duration;IZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerEffect; public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V public final fun getAmbient ()Z public final fun getAmplifier ()I public final fun getDuration ()Ljava/time/Duration; @@ -146,74 +134,7 @@ public final class org/pnfolder/pnlibrary/api/actions/builtin/EffectAction : org public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/actions/builtin/GroupAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V - public fun (Ljava/util/List;)V - public synthetic fun (Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/util/List; - public final fun copy (Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/actions/builtin/GroupAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/GroupAction;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/GroupAction; - public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V - public final fun getSteps ()Ljava/util/List; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/actions/builtin/IfAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V - public fun (Lorg/pnfolder/pnlibrary/api/checks/Check;Ljava/util/List;Ljava/util/List;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/checks/Check;Ljava/util/List;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/checks/Check; - public final fun component2 ()Ljava/util/List; - public final fun component3 ()Ljava/util/List; - public final fun copy (Lorg/pnfolder/pnlibrary/api/checks/Check;Ljava/util/List;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/actions/builtin/IfAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/IfAction;Lorg/pnfolder/pnlibrary/api/checks/Check;Ljava/util/List;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/IfAction; - public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V - public final fun getCheck ()Lorg/pnfolder/pnlibrary/api/checks/Check; - public final fun getElseActions ()Ljava/util/List; - public final fun getThenActions ()Ljava/util/List; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/actions/builtin/LogAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V - public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/logging/LogLevel;)V - public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/logging/LogLevel;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/logging/LogLevel; - public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/logging/LogLevel;)Lorg/pnfolder/pnlibrary/api/actions/builtin/LogAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/LogAction;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/logging/LogLevel;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/LogAction; - public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V - public final fun getLevel ()Lorg/pnfolder/pnlibrary/api/logging/LogLevel; - public final fun getText ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/actions/builtin/MessageAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V - public fun (Ljava/util/List;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;)V - public synthetic fun (Ljava/util/List;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/util/List; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public final fun component3 ()Lorg/pnfolder/pnlibrary/api/actions/ActionTarget; - public final fun copy (Ljava/util/List;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;)Lorg/pnfolder/pnlibrary/api/actions/builtin/MessageAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/MessageAction;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/MessageAction; - public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V - public final fun getMessages ()Ljava/util/List; - public final fun getSerializerType ()Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public final fun getTarget ()Lorg/pnfolder/pnlibrary/api/actions/ActionTarget; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/actions/builtin/ParticleAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V +public final class org/pnfolder/pnlibrary/api/audiences/player/PlayerParticle { public fun (Ljava/lang/String;IDDDD)V public synthetic fun (Ljava/lang/String;IDDDDILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Ljava/lang/String; @@ -222,10 +143,9 @@ public final class org/pnfolder/pnlibrary/api/actions/builtin/ParticleAction : o public final fun component4 ()D public final fun component5 ()D public final fun component6 ()D - public final fun copy (Ljava/lang/String;IDDDD)Lorg/pnfolder/pnlibrary/api/actions/builtin/ParticleAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/ParticleAction;Ljava/lang/String;IDDDDILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/ParticleAction; + public final fun copy (Ljava/lang/String;IDDDD)Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerParticle; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerParticle;Ljava/lang/String;IDDDDILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/audiences/player/PlayerParticle; public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V public final fun getCount ()I public final fun getKey ()Ljava/lang/String; public final fun getOffsetX ()D @@ -236,3278 +156,3442 @@ public final class org/pnfolder/pnlibrary/api/actions/builtin/ParticleAction : o public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/actions/builtin/RepeatAction : org/pnfolder/pnlibrary/api/actions/Action { - public static final field Companion Lorg/pnfolder/pnlibrary/api/actions/builtin/RepeatAction$Companion; - public static final field MAX_TIMES I - public fun ()V - public fun (ILjava/time/Duration;Ljava/util/List;)V - public synthetic fun (ILjava/time/Duration;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()I - public final fun component2 ()Ljava/time/Duration; - public final fun component3 ()Ljava/util/List; - public final fun copy (ILjava/time/Duration;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/actions/builtin/RepeatAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/RepeatAction;ILjava/time/Duration;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/RepeatAction; - public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V - public final fun getEvery ()Ljava/time/Duration; - public final fun getThenActions ()Ljava/util/List; - public final fun getTimes ()I - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/actions/builtin/RepeatAction$Companion { +public class org/pnfolder/pnlibrary/api/chat/ChatKit { + public static final field Companion Lorg/pnfolder/pnlibrary/api/chat/ChatKit$Companion; + public static final field MAX_LINE I + public static final field MAX_MESSAGE I + public fun (Lorg/pnfolder/pnlibrary/api/chat/ChatReader;)V + public final fun actions ([Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/Component; + public final fun blank ()Lnet/kyori/adventure/text/Component; + public final fun bracketed (Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; + public final fun button (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; + public final fun chip (ILjava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; + public final fun commandHints ([Lkotlin/Pair;)Ljava/util/List; + public final fun confirmation (Ljava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/util/List; + public final fun confirmationChoices (Ljava/lang/String;Ljava/util/List;Ljava/util/List;)Ljava/util/List; + public final fun dot ()Lnet/kyori/adventure/text/Component; + public final fun field (Ljava/lang/String;Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/Component; + public final fun framed (Ljava/util/List;)Ljava/util/List; + public final fun getReader ()Lorg/pnfolder/pnlibrary/api/chat/ChatReader; + public final fun glyph (C)Ljava/lang/String; + public final fun header (Ljava/lang/String;Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/Component; + public static synthetic fun header$default (Lorg/pnfolder/pnlibrary/api/chat/ChatKit;Ljava/lang/String;Lnet/kyori/adventure/text/Component;ILjava/lang/Object;)Lnet/kyori/adventure/text/Component; + public final fun hoverField (Ljava/lang/String;Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/Component; + public final fun linkButton (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; + public final fun mark (Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone;)Lnet/kyori/adventure/text/Component; + public final fun note (Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; + public static synthetic fun note$default (Lorg/pnfolder/pnlibrary/api/chat/ChatKit;Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;ILjava/lang/Object;)Lnet/kyori/adventure/text/Component; + public final fun notice (Lorg/pnfolder/pnlibrary/api/chat/ChatNotice;)Ljava/util/List; + public final fun option (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; + public final fun safeLink (Ljava/lang/String;)Z + public final fun section (Ljava/lang/String;)Lnet/kyori/adventure/text/Component; + public final fun selected (Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; + public final fun setting (Ljava/lang/String;Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/Component; + public final fun shown (Ljava/lang/String;)Ljava/lang/String; + public final fun spaced (Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/Component; + public final fun text (Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; + public static synthetic fun text$default (Lorg/pnfolder/pnlibrary/api/chat/ChatKit;Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;ILjava/lang/Object;)Lnet/kyori/adventure/text/Component; + public final fun tooltip ([Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/event/HoverEvent; } -public final class org/pnfolder/pnlibrary/api/actions/builtin/RequireAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V - public fun (Lorg/pnfolder/pnlibrary/api/checks/Check;Lorg/pnfolder/pnlibrary/api/checks/Requirement;Ljava/util/List;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/checks/Check;Lorg/pnfolder/pnlibrary/api/checks/Requirement;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/checks/Check; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/checks/Requirement; - public final fun component3 ()Ljava/util/List; - public final fun copy (Lorg/pnfolder/pnlibrary/api/checks/Check;Lorg/pnfolder/pnlibrary/api/checks/Requirement;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/actions/builtin/RequireAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/RequireAction;Lorg/pnfolder/pnlibrary/api/checks/Check;Lorg/pnfolder/pnlibrary/api/checks/Requirement;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/RequireAction; - public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V - public final fun getCheck ()Lorg/pnfolder/pnlibrary/api/checks/Check; - public final fun getDeny ()Ljava/util/List; - public final fun getRequirement ()Lorg/pnfolder/pnlibrary/api/checks/Requirement; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/chat/ChatKit$Companion { } -public final class org/pnfolder/pnlibrary/api/actions/builtin/RunAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V - public fun (Ljava/lang/String;)V - public synthetic fun (Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/actions/builtin/RunAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/RunAction;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/RunAction; +public final class org/pnfolder/pnlibrary/api/chat/ChatNotice { + public fun (Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone;Ljava/lang/String;Ljava/lang/String;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone;Ljava/lang/String;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun copy (Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/chat/ChatNotice; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/chat/ChatNotice;Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/chat/ChatNotice; public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V - public final fun getName ()Ljava/lang/String; + public final fun getDetail ()Ljava/lang/String; + public final fun getText ()Ljava/lang/String; + public final fun getTone ()Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone; public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/actions/builtin/SoundAction : org/pnfolder/pnlibrary/api/actions/Action { +public final class org/pnfolder/pnlibrary/api/chat/ChatReader { + public static final field CONSOLE Lorg/pnfolder/pnlibrary/api/chat/ChatReader; + public static final field Companion Lorg/pnfolder/pnlibrary/api/chat/ChatReader$Companion; + public static final field PLAYER Lorg/pnfolder/pnlibrary/api/chat/ChatReader; public fun ()V - public fun (Ljava/lang/String;Lnet/kyori/adventure/sound/Sound$Source;FFLorg/pnfolder/pnlibrary/api/actions/ActionTarget;)V - public synthetic fun (Ljava/lang/String;Lnet/kyori/adventure/sound/Sound$Source;FFLorg/pnfolder/pnlibrary/api/actions/ActionTarget;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Lnet/kyori/adventure/sound/Sound$Source; - public final fun component3 ()F - public final fun component4 ()F - public final fun component5 ()Lorg/pnfolder/pnlibrary/api/actions/ActionTarget; - public final fun copy (Ljava/lang/String;Lnet/kyori/adventure/sound/Sound$Source;FFLorg/pnfolder/pnlibrary/api/actions/ActionTarget;)Lorg/pnfolder/pnlibrary/api/actions/builtin/SoundAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/SoundAction;Ljava/lang/String;Lnet/kyori/adventure/sound/Sound$Source;FFLorg/pnfolder/pnlibrary/api/actions/ActionTarget;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/SoundAction; + public fun (ZZ)V + public synthetic fun (ZZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Z + public final fun component2 ()Z + public final fun copy (ZZ)Lorg/pnfolder/pnlibrary/api/chat/ChatReader; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/chat/ChatReader;ZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/chat/ChatReader; public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V - public final fun getKey ()Ljava/lang/String; - public final fun getPitch ()F - public final fun getSource ()Lnet/kyori/adventure/sound/Sound$Source; - public final fun getTarget ()Lorg/pnfolder/pnlibrary/api/actions/ActionTarget; - public final fun getVolume ()F + public final fun getAscii ()Z + public final fun getInteractive ()Z public fun hashCode ()I + public static final fun of (Lorg/pnfolder/pnlibrary/api/commands/CommandSender;)Lorg/pnfolder/pnlibrary/api/chat/ChatReader; public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/actions/builtin/StopAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V +public final class org/pnfolder/pnlibrary/api/chat/ChatReader$Companion { + public final fun of (Lorg/pnfolder/pnlibrary/api/commands/CommandSender;)Lorg/pnfolder/pnlibrary/api/chat/ChatReader; } -public final class org/pnfolder/pnlibrary/api/actions/builtin/TitleAction : org/pnfolder/pnlibrary/api/actions/Action { - public fun ()V - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;ILkotlin/jvm/internal/DefaultConstructorMarker;)V +public final class org/pnfolder/pnlibrary/api/chat/ConfirmChoice { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V public final fun component1 ()Ljava/lang/String; public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Ljava/time/Duration; - public final fun component4 ()Ljava/time/Duration; - public final fun component5 ()Ljava/time/Duration; - public final fun component6 ()Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public final fun component7 ()Lorg/pnfolder/pnlibrary/api/actions/ActionTarget; - public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;)Lorg/pnfolder/pnlibrary/api/actions/builtin/TitleAction; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/actions/builtin/TitleAction;Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/actions/ActionTarget;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/actions/builtin/TitleAction; + public final fun component3 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/chat/ConfirmChoice; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/chat/ConfirmChoice;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/chat/ConfirmChoice; public fun equals (Ljava/lang/Object;)Z - public fun execute (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)V - public final fun getFadeIn ()Ljava/time/Duration; - public final fun getFadeOut ()Ljava/time/Duration; - public final fun getSerializerType ()Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public final fun getStay ()Ljava/time/Duration; - public final fun getSubtitle ()Ljava/lang/String; - public final fun getTarget ()Lorg/pnfolder/pnlibrary/api/actions/ActionTarget; - public final fun getTitle ()Ljava/lang/String; + public final fun getCommand ()Ljava/lang/String; + public final fun getHint ()Ljava/lang/String; + public final fun getLabel ()Ljava/lang/String; public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/actions/internal/ActionNode : org/pnfolder/pnlibrary/api/config/ConfigNodeRewriter { - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/actions/internal/ActionNode; - public fun rewrite (Ljava/util/Map;Ljava/lang/String;)Ljava/util/Map; -} - -public final class org/pnfolder/pnlibrary/api/actions/internal/ActionText : org/pnfolder/pnlibrary/api/config/ConfigTextParser { - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/actions/internal/ActionText; - public synthetic fun parse (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Ljava/lang/Object; - public fun parse (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Lorg/pnfolder/pnlibrary/api/actions/Action; -} - -public final class org/pnfolder/pnlibrary/api/activity/ActivityAttachment { - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JLjava/lang/String;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/chat/style/ChatPalette { + public static final field ACCENT Lnet/kyori/adventure/text/format/TextColor; + public static final field DANGER Lnet/kyori/adventure/text/format/TextColor; + public static final field FAINT Lnet/kyori/adventure/text/format/TextColor; + public static final field INFO Lnet/kyori/adventure/text/format/TextColor; + public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/chat/style/ChatPalette; + public static final field LABEL Lnet/kyori/adventure/text/format/TextColor; + public static final field OK Lnet/kyori/adventure/text/format/TextColor; + public static final field ORANGE Lnet/kyori/adventure/text/format/TextColor; + public static final field SOFT Lnet/kyori/adventure/text/format/TextColor; + public static final field TEXT Lnet/kyori/adventure/text/format/TextColor; + public static final field WARN Lnet/kyori/adventure/text/format/TextColor; +} + +public final class org/pnfolder/pnlibrary/api/chat/style/ChatTone : java/lang/Enum { + public static final field FAILURE Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone; + public static final field INFO Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone; + public static final field PROGRESS Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone; + public static final field SUCCESS Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone; + public static final field WARNING Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone; +} + +public final class org/pnfolder/pnlibrary/api/chat/style/ChatToneKt { + public static final fun getColor (Lorg/pnfolder/pnlibrary/api/chat/style/ChatTone;)Lnet/kyori/adventure/text/format/TextColor; +} + +public final class org/pnfolder/pnlibrary/api/commands/CommandContext { + public fun (Lorg/pnfolder/pnlibrary/api/commands/CommandSender;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/commands/CommandSender;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/commands/CommandSender; + public final fun component2 ()Ljava/util/List; public final fun component3 ()Ljava/lang/String; public final fun component4 ()Ljava/lang/String; - public final fun component5 ()J - public final fun component6 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JLjava/lang/String;)Lorg/pnfolder/pnlibrary/api/activity/ActivityAttachment; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/activity/ActivityAttachment;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JLjava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/activity/ActivityAttachment; + public final fun component5 ()Ljava/util/Map; + public final fun contains (Ljava/lang/String;)Z + public final fun copy (Lorg/pnfolder/pnlibrary/api/commands/CommandSender;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/commands/CommandContext; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;Lorg/pnfolder/pnlibrary/api/commands/CommandSender;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/commands/CommandContext; public fun equals (Ljava/lang/Object;)Z - public final fun getContentType ()Ljava/lang/String; - public final fun getEventId ()Ljava/lang/String; - public final fun getId ()Ljava/lang/String; - public final fun getName ()Ljava/lang/String; - public final fun getSha256 ()Ljava/lang/String; - public final fun getSize ()J + public final fun get (Ljava/lang/String;)Ljava/lang/Object; + public final fun getArguments ()Ljava/util/List; + public final fun getCurrentInput ()Ljava/lang/String; + public final fun getInvokedAlias ()Ljava/lang/String; + public final fun getParsedValues ()Ljava/util/Map; + public final fun getSender ()Lorg/pnfolder/pnlibrary/api/commands/CommandSender; public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/activity/ActivityBundle { - public fun ()V - public fun (Ljava/util/List;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)V - public synthetic fun (Ljava/util/List;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/util/List; - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public final fun component4 ()Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; - public final fun component5 ()Ljava/lang/String; - public final fun component6 ()Ljava/lang/String; - public final fun component7 ()Ljava/lang/String; - public final fun component8 ()Ljava/lang/String; - public final fun component9 ()Ljava/util/Map; - public final fun copy (Ljava/util/List;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/activity/ActivityBundle; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/activity/ActivityBundle;Ljava/util/List;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/activity/ActivityBundle; - public fun equals (Ljava/lang/Object;)Z - public final fun getCategory ()Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public final fun getCorrelationId ()Ljava/lang/String; - public final fun getFiles ()Ljava/util/List; - public final fun getMetadata ()Ljava/util/Map; - public final fun getPluginId ()Ljava/lang/String; - public final fun getSessionId ()Ljava/lang/String; - public final fun getSeverity ()Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; - public final fun getSource ()Ljava/lang/String; - public final fun getType ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/commands/CommandRegistration : java/lang/AutoCloseable { + public abstract fun close ()V + public abstract fun getCommand ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition; + public abstract fun isClosed ()Z +} + +public abstract interface class org/pnfolder/pnlibrary/api/commands/CommandSender : org/pnfolder/pnlibrary/api/audiences/AudienceSender { + public fun actionBar (Lnet/kyori/adventure/text/Component;)V + public fun getSupportsInteraction ()Z + public fun playSound (Lnet/kyori/adventure/sound/Sound;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; + public abstract fun send (Lnet/kyori/adventure/text/Component;)V + public fun sendMessage (Lnet/kyori/adventure/text/Component;)V } -public final class org/pnfolder/pnlibrary/api/activity/ActivityCategory : java/lang/Enum { - public static final field COMMAND Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public static final field DIAGNOSTICS Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public static final field ERROR Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public static final field FEATURE Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public static final field LIFECYCLE Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public static final field SECURITY Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public static final field SYSTEM Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public static final field UPDATE Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public static final field USER_ACTION Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; +public final class org/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec { + public static final field BOOLEAN Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static final field Companion Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Companion; + public static final field GREEDY Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static final field TEXT Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Kind;Ljava/lang/Double;Ljava/lang/Double;Ljava/util/List;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun choice (Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static final fun decimal ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static final fun decimal (D)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static final fun decimal (DD)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public final fun getChoices ()Ljava/util/List; + public final fun getKind ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Kind; + public final fun getMaximum ()Ljava/lang/Double; + public final fun getMinimum ()Ljava/lang/Double; + public static final fun integer ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static final fun integer (I)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static final fun integer (II)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static final fun long ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static final fun long (J)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static final fun long (JJ)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; +} + +public final class org/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Companion { + public final fun choice (Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public final fun decimal ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public final fun decimal (D)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public final fun decimal (DD)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static synthetic fun decimal$default (Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Companion;DDILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public final fun integer ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public final fun integer (I)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public final fun integer (II)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static synthetic fun integer$default (Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Companion;IIILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public final fun long ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public final fun long (J)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public final fun long (JJ)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static synthetic fun long$default (Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Companion;JJILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; +} + +public final class org/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Kind : java/lang/Enum { + public static final field BOOLEAN Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Kind; + public static final field CHOICE Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Kind; + public static final field DECIMAL Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Kind; + public static final field GREEDY Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Kind; + public static final field INTEGER Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Kind; + public static final field LONG Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Kind; + public static final field TEXT Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Kind; public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Kind; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec$Kind; +} + +public abstract interface class org/pnfolder/pnlibrary/api/commands/definition/ArgumentType { + public static final field Companion Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType$Companion; + public static fun boolean ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public static fun choice ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public static fun decimal ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public static fun decimal (DD)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public static fun enumeration (Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public fun error (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/error/CommandError; + public fun getSpec ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec; + public static fun greedyString ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public static fun integer ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public static fun integer (II)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public static fun long ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public static fun long (JJ)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public abstract fun parse (Ljava/lang/String;)Ljava/lang/Object; + public static fun player (Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public static fun string ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; +} + +public final class org/pnfolder/pnlibrary/api/commands/definition/ArgumentType$Companion { + public final fun boolean ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public final fun choice ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public final fun decimal ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public final fun decimal (DD)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public final fun enumeration (Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public final fun greedyString ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public final fun integer ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public final fun integer (II)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public final fun long ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public final fun long (JJ)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public final fun player (Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public final fun string ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; +} + +public abstract interface class org/pnfolder/pnlibrary/api/commands/definition/CommandAvailability { + public abstract fun isAvailable (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;)Z } -public final class org/pnfolder/pnlibrary/api/activity/ActivityEvent { - public fun (Ljava/lang/String;JLjava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)V - public synthetic fun (Ljava/lang/String;JLjava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component10 ()Ljava/util/Map; - public final fun component2 ()J - public final fun component3 ()Ljava/lang/String; - public final fun component4 ()Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public final fun component5 ()Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; - public final fun component6 ()Ljava/lang/String; - public final fun component7 ()Ljava/lang/String; - public final fun component8 ()Ljava/lang/String; - public final fun component9 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;JLjava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/activity/ActivityEvent; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/activity/ActivityEvent;Ljava/lang/String;JLjava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/activity/ActivityEvent; - public fun equals (Ljava/lang/Object;)Z - public final fun getCategory ()Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public final fun getCorrelationId ()Ljava/lang/String; - public final fun getEventId ()Ljava/lang/String; - public final fun getMetadata ()Ljava/util/Map; - public final fun getPluginId ()Ljava/lang/String; - public final fun getSessionId ()Ljava/lang/String; - public final fun getSeverity ()Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; - public final fun getSource ()Ljava/lang/String; - public final fun getTimestamp ()J - public final fun getType ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/commands/definition/CommandBuilder { + public final fun acceptsExtraArguments ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun aliases ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun argument (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final synthetic fun argument (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun availableIf (Lorg/pnfolder/pnlibrary/api/commands/definition/CommandAvailability;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun build ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition; + public final fun consoleBypassesPermission ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun consoleBypassesPermission (Z)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public static synthetic fun consoleBypassesPermission$default (Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun consoleOnly ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun executes (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun executesAsync (Lorg/pnfolder/pnlibrary/api/commands/definition/CommandHandler;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun getErrorHandlers ()Ljava/util/LinkedHashMap; + public final fun literal (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final synthetic fun literal (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun mount (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun noPermissionMessage (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun onError (Ljava/lang/Class;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun onError (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/commands/error/CommandErrorHandler;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun permission (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun permission (Ljava/lang/String;[Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun playerOnly ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun suggests (Ljava/util/function/Function;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun suggestsAsync (Lorg/pnfolder/pnlibrary/api/commands/definition/SuggestionHandler;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; +} + +public final class org/pnfolder/pnlibrary/api/commands/definition/CommandDefinition { + public static final field Companion Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition$Companion; + public static final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; + public final fun getAliases ()Ljava/util/Set; + public final fun getConsoleBypassesPermission ()Z + public final fun getExecution ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandHandler; + public final fun getName ()Ljava/lang/String; + public final fun getNoPermissionMessage ()Ljava/lang/String; + public final fun getPermission ()Ljava/lang/String; + public final fun getRoot ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNode; + public final fun getSuggestions ()Lorg/pnfolder/pnlibrary/api/commands/definition/SuggestionHandler; } -public final class org/pnfolder/pnlibrary/api/activity/ActivityQuery { - public fun ()V - public fun (ILjava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/Long;Ljava/lang/Long;)V - public synthetic fun (ILjava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/Long;Ljava/lang/Long;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()I - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public final fun component4 ()Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; - public final fun component5 ()Ljava/lang/Long; - public final fun component6 ()Ljava/lang/Long; - public final fun copy (ILjava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/Long;Ljava/lang/Long;)Lorg/pnfolder/pnlibrary/api/activity/ActivityQuery; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/activity/ActivityQuery;ILjava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/Long;Ljava/lang/Long;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/activity/ActivityQuery; - public fun equals (Ljava/lang/Object;)Z - public final fun getCategory ()Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory; - public final fun getLimit ()I - public final fun getMinimumSeverity ()Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; - public final fun getPluginId ()Ljava/lang/String; - public final fun getSince ()Ljava/lang/Long; - public final fun getUntil ()Ljava/lang/Long; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/commands/definition/CommandDefinition$Companion { + public final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandBuilder; } -public abstract interface class org/pnfolder/pnlibrary/api/activity/ActivityService : java/lang/AutoCloseable { - public abstract fun attach (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[B)Lorg/pnfolder/pnlibrary/api/activity/ActivityAttachment; - public abstract fun attachFile (Ljava/lang/String;Ljava/nio/file/Path;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/activity/ActivityAttachment; - public static synthetic fun attachFile$default (Lorg/pnfolder/pnlibrary/api/activity/ActivityService;Ljava/lang/String;Ljava/nio/file/Path;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/activity/ActivityAttachment; - public abstract fun clear ()V - public abstract fun close ()V - public fun diagnostic (Ljava/util/List;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/activity/ActivityEvent; - public static synthetic fun diagnostic$default (Lorg/pnfolder/pnlibrary/api/activity/ActivityService;Ljava/util/List;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/activity/ActivityEvent; - public fun exportAttachmentManifest ()[B - public abstract fun exportAttachments ()Ljava/util/Map; - public abstract fun exportJournal ()[B - public abstract fun recent (Lorg/pnfolder/pnlibrary/api/activity/ActivityQuery;)Ljava/util/List; - public static synthetic fun recent$default (Lorg/pnfolder/pnlibrary/api/activity/ActivityService;Lorg/pnfolder/pnlibrary/api/activity/ActivityQuery;ILjava/lang/Object;)Ljava/util/List; - public fun record (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/activity/ActivityEvent; - public fun record (Lorg/pnfolder/pnlibrary/api/activity/ActivityBundle;)Lorg/pnfolder/pnlibrary/api/activity/ActivityEvent; - public abstract fun record (Lorg/pnfolder/pnlibrary/api/activity/ActivityEvent;)Lorg/pnfolder/pnlibrary/api/activity/ActivityEvent; - public static synthetic fun record$default (Lorg/pnfolder/pnlibrary/api/activity/ActivityService;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/activity/ActivityEvent; - public fun recordWithFile (Ljava/nio/file/Path;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/activity/ActivityEvent; - public static synthetic fun recordWithFile$default (Lorg/pnfolder/pnlibrary/api/activity/ActivityService;Ljava/nio/file/Path;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/activity/ActivityCategory;Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/activity/ActivityEvent; -} - -public final class org/pnfolder/pnlibrary/api/activity/ActivitySeverity : java/lang/Enum { - public static final field CRITICAL Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; - public static final field ERROR Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; - public static final field INFO Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; - public static final field NOTICE Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; - public static final field TRACE Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; - public static final field WARNING Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; +public final class org/pnfolder/pnlibrary/api/commands/definition/CommandDefinitionKt { + public static final synthetic fun command (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition; + public static final fun completedExecution ()Ljava/util/concurrent/CompletionStage; + public static final fun completedSuggestions (Ljava/util/List;)Ljava/util/concurrent/CompletionStage; +} + +public abstract interface class org/pnfolder/pnlibrary/api/commands/definition/CommandHandler { + public abstract fun execute (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;)Ljava/util/concurrent/CompletionStage; +} + +public final class org/pnfolder/pnlibrary/api/commands/definition/CommandNode { + public final fun getAcceptsExtraArguments ()Z + public final fun getAlsoPermissions ()Ljava/util/List; + public final fun getArgumentType ()Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType; + public final fun getAvailability ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandAvailability; + public final fun getChildren ()Ljava/util/List; + public final fun getConsoleBypassesPermission ()Z + public final fun getDescription ()Ljava/util/List; + public final fun getErrorHandlers ()Ljava/util/Map; + public final fun getExecution ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandHandler; + public final fun getKind ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeKind; + public final fun getName ()Ljava/lang/String; + public final fun getNoPermissionMessage ()Ljava/lang/String; + public final fun getPermission ()Ljava/lang/String; + public final fun getSenderRule ()Lorg/pnfolder/pnlibrary/api/commands/definition/SenderRule; + public final fun getSuggestions ()Lorg/pnfolder/pnlibrary/api/commands/definition/SuggestionHandler; + public final fun isExecutable ()Z +} + +public final class org/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder { + public final fun acceptsExtraArguments ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun argument (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final synthetic fun argument (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/commands/definition/ArgumentType;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun availableIf (Lorg/pnfolder/pnlibrary/api/commands/definition/CommandAvailability;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun consoleBypassesPermission ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun consoleBypassesPermission (Z)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public static synthetic fun consoleBypassesPermission$default (Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun consoleOnly ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun description ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun executes (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun executesAsync (Lorg/pnfolder/pnlibrary/api/commands/definition/CommandHandler;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun getErrorHandlers ()Ljava/util/LinkedHashMap; + public final fun literal (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final synthetic fun literal (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun noPermissionMessage (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun onError (Ljava/lang/Class;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun onError (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/commands/error/CommandErrorHandler;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun permission (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun permission (Ljava/lang/String;[Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun playerOnly ()Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun suggests (Ljava/util/function/Function;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; + public final fun suggestsAsync (Lorg/pnfolder/pnlibrary/api/commands/definition/SuggestionHandler;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeBuilder; +} + +public final class org/pnfolder/pnlibrary/api/commands/definition/CommandNodeKind : java/lang/Enum { + public static final field ARGUMENT Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeKind; + public static final field LITERAL Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeKind; + public static final field ROOT Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeKind; public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/activity/ActivitySeverity; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeKind; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/commands/definition/CommandNodeKind; } -public abstract interface class org/pnfolder/pnlibrary/api/audiences/AudienceSender : org/pnfolder/pnlibrary/api/audiences/LibraryAudience { - public abstract fun getId ()Ljava/lang/String; - public abstract fun getName ()Ljava/lang/String; - public abstract fun hasPermission (Ljava/lang/String;)Z - public abstract fun isConsole ()Z - public fun isPlayer ()Z +public final class org/pnfolder/pnlibrary/api/commands/definition/SenderRule : java/lang/Enum { + public static final field ANY Lorg/pnfolder/pnlibrary/api/commands/definition/SenderRule; + public static final field CONSOLE Lorg/pnfolder/pnlibrary/api/commands/definition/SenderRule; + public static final field PLAYER Lorg/pnfolder/pnlibrary/api/commands/definition/SenderRule; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/definition/SenderRule; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/commands/definition/SenderRule; } -public abstract interface class org/pnfolder/pnlibrary/api/audiences/AudienceService { - public abstract fun all ()Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience; - public abstract fun combine (Ljava/lang/Iterable;)Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience; - public abstract fun console ()Lorg/pnfolder/pnlibrary/api/audiences/AudienceSender; - public abstract fun onlinePlayers ()Ljava/util/List; - public abstract fun player (Ljava/util/UUID;)Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer; - public abstract fun sender (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/audiences/AudienceSender; +public abstract interface class org/pnfolder/pnlibrary/api/commands/definition/SuggestionHandler { + public abstract fun suggest (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;)Ljava/util/concurrent/CompletionStage; } -public abstract interface class org/pnfolder/pnlibrary/api/audiences/Delivery { - public static final field Companion Lorg/pnfolder/pnlibrary/api/audiences/Delivery$Companion; - public static fun combine (Ljava/lang/Iterable;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; - public fun isDelivered ()Z - public static fun of (Z)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; +public class org/pnfolder/pnlibrary/api/commands/error/BadUsage : org/pnfolder/pnlibrary/api/commands/error/CommandError { + public fun (Ljava/lang/String;)V + public final fun getUsage ()Ljava/lang/String; + public fun placeholders ()Ljava/util/Map; } -public final class org/pnfolder/pnlibrary/api/audiences/Delivery$Companion { - public final fun combine (Ljava/lang/Iterable;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; - public final fun of (Z)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; +public class org/pnfolder/pnlibrary/api/commands/error/CommandError { + public fun ()V + public fun (Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun format (Ljava/lang/String;)Ljava/lang/String; + public final fun getDefaultMessage ()Ljava/lang/String; + public fun placeholders ()Ljava/util/Map; } -public final class org/pnfolder/pnlibrary/api/audiences/Delivery$Delivered : org/pnfolder/pnlibrary/api/audiences/Delivery { - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/audiences/Delivery$Delivered; - public fun equals (Ljava/lang/Object;)Z - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/commands/error/CommandErrorHandler { + public abstract fun handle (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;Lorg/pnfolder/pnlibrary/api/commands/error/CommandError;)V } -public final class org/pnfolder/pnlibrary/api/audiences/Delivery$Failed : org/pnfolder/pnlibrary/api/audiences/Delivery { - public fun (Ljava/lang/Throwable;)V - public final fun component1 ()Ljava/lang/Throwable; - public final fun copy (Ljava/lang/Throwable;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery$Failed; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/audiences/Delivery$Failed;Ljava/lang/Throwable;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery$Failed; - public fun equals (Ljava/lang/Object;)Z - public final fun getCause ()Ljava/lang/Throwable; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/commands/error/CommandErrorKt { + public static final fun ensure (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;ZLkotlin/jvm/functions/Function0;)V + public static final fun fail (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;Lorg/pnfolder/pnlibrary/api/commands/error/CommandError;)Ljava/lang/Void; } -public final class org/pnfolder/pnlibrary/api/audiences/Delivery$Unsupported : org/pnfolder/pnlibrary/api/audiences/Delivery { - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/audiences/Delivery$Unsupported; - public fun equals (Ljava/lang/Object;)Z - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public class org/pnfolder/pnlibrary/api/commands/error/CommandFailed : org/pnfolder/pnlibrary/api/commands/error/CommandError { + public fun ()V + public fun (Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V } -public final class org/pnfolder/pnlibrary/api/audiences/ItemQuery { - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Ljava/lang/String; - public final fun component4 ()Ljava/lang/String; - public final fun component5 ()Z - public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/audiences/ItemQuery; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/audiences/ItemQuery;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/audiences/ItemQuery; - public fun equals (Ljava/lang/Object;)Z - public final fun getIgnoreCase ()Z - public final fun getLoreContains ()Ljava/lang/String; - public final fun getMaterial ()Ljava/lang/String; - public final fun getName ()Ljava/lang/String; - public final fun getNameContains ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/commands/error/CommandFailure : java/lang/RuntimeException { + public fun (Lorg/pnfolder/pnlibrary/api/commands/error/CommandError;)V + public final fun getError ()Lorg/pnfolder/pnlibrary/api/commands/error/CommandError; } -public abstract interface class org/pnfolder/pnlibrary/api/audiences/LibraryAudience { - public static final field Companion Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience$Companion; - public abstract fun actionBar (Lnet/kyori/adventure/text/Component;)V - public static fun dynamic (Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience; - public abstract fun playSound (Lnet/kyori/adventure/sound/Sound;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; - public abstract fun sendMessage (Lnet/kyori/adventure/text/Component;)V - public fun showTitle (Lnet/kyori/adventure/text/Component;Lnet/kyori/adventure/text/Component;Ljava/time/Duration;Ljava/time/Duration;Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; +public final class org/pnfolder/pnlibrary/api/commands/error/ConsoleOnly : org/pnfolder/pnlibrary/api/commands/error/CommandError { + public fun ()V } -public final class org/pnfolder/pnlibrary/api/audiences/LibraryAudience$Companion { - public final fun dynamic (Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience; +public class org/pnfolder/pnlibrary/api/commands/error/IncompleteCommand : org/pnfolder/pnlibrary/api/commands/error/BadUsage { + public fun (Ljava/lang/String;)V } -public abstract interface class org/pnfolder/pnlibrary/api/audiences/LibraryPlayer : org/pnfolder/pnlibrary/api/audiences/AudienceSender { - public abstract fun applyEffect (Lorg/pnfolder/pnlibrary/api/audiences/PlayerEffect;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; - public fun countItems (Lorg/pnfolder/pnlibrary/api/audiences/ItemQuery;)Ljava/lang/Integer; - public fun distanceTo (Ljava/lang/String;DDD)Ljava/lang/Double; - public fun experience (Z)Ljava/lang/Double; - public fun getCapabilities ()Ljava/util/Set; - public fun getId ()Ljava/lang/String; - public abstract fun getName ()Ljava/lang/String; - public abstract fun getUniqueId ()Ljava/util/UUID; - public abstract fun hasPermission (Ljava/lang/String;)Z - public fun isConsole ()Z - public fun isPlayer ()Z - public fun runCommand (Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; - public abstract fun spawnParticle (Lorg/pnfolder/pnlibrary/api/audiences/PlayerParticle;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; +public class org/pnfolder/pnlibrary/api/commands/error/InvalidArgument : org/pnfolder/pnlibrary/api/commands/error/BadUsage { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public final fun getArgument ()Ljava/lang/String; + public final fun getValue ()Ljava/lang/String; + public fun placeholders ()Ljava/util/Map; } -public final class org/pnfolder/pnlibrary/api/audiences/PlayerCapability : java/lang/Enum { - public static final field ACTION_BAR Lorg/pnfolder/pnlibrary/api/audiences/PlayerCapability; - public static final field EFFECT Lorg/pnfolder/pnlibrary/api/audiences/PlayerCapability; - public static final field MESSAGE Lorg/pnfolder/pnlibrary/api/audiences/PlayerCapability; - public static final field PARTICLE Lorg/pnfolder/pnlibrary/api/audiences/PlayerCapability; - public static final field SOUND Lorg/pnfolder/pnlibrary/api/audiences/PlayerCapability; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/audiences/PlayerCapability; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/audiences/PlayerCapability; +public class org/pnfolder/pnlibrary/api/commands/error/NoPermission : org/pnfolder/pnlibrary/api/commands/error/CommandError { + public fun (Ljava/lang/String;)V + public final fun getPermission ()Ljava/lang/String; + public fun placeholders ()Ljava/util/Map; } -public final class org/pnfolder/pnlibrary/api/audiences/PlayerEffect { - public fun (Ljava/lang/String;Ljava/time/Duration;IZZZ)V - public synthetic fun (Ljava/lang/String;Ljava/time/Duration;IZZZILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/time/Duration; - public final fun component3 ()I - public final fun component4 ()Z - public final fun component5 ()Z - public final fun component6 ()Z - public final fun copy (Ljava/lang/String;Ljava/time/Duration;IZZZ)Lorg/pnfolder/pnlibrary/api/audiences/PlayerEffect; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/audiences/PlayerEffect;Ljava/lang/String;Ljava/time/Duration;IZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/audiences/PlayerEffect; - public fun equals (Ljava/lang/Object;)Z - public final fun getAmbient ()Z - public final fun getAmplifier ()I - public final fun getDuration ()Ljava/time/Duration; - public final fun getIcon ()Z - public final fun getKey ()Ljava/lang/String; - public final fun getParticles ()Z - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public class org/pnfolder/pnlibrary/api/commands/error/OnCooldown : org/pnfolder/pnlibrary/api/commands/error/CommandError { + public fun (Ljava/time/Duration;)V + public final fun getRemaining ()Ljava/time/Duration; + public fun placeholders ()Ljava/util/Map; } -public final class org/pnfolder/pnlibrary/api/audiences/PlayerParticle { - public fun (Ljava/lang/String;IDDDD)V - public synthetic fun (Ljava/lang/String;IDDDDILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()I - public final fun component3 ()D - public final fun component4 ()D - public final fun component5 ()D - public final fun component6 ()D - public final fun copy (Ljava/lang/String;IDDDD)Lorg/pnfolder/pnlibrary/api/audiences/PlayerParticle; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/audiences/PlayerParticle;Ljava/lang/String;IDDDDILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/audiences/PlayerParticle; - public fun equals (Ljava/lang/Object;)Z - public final fun getCount ()I - public final fun getKey ()Ljava/lang/String; - public final fun getOffsetX ()D - public final fun getOffsetY ()D - public final fun getOffsetZ ()D - public final fun getSpeed ()D - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public class org/pnfolder/pnlibrary/api/commands/error/PlayerNotFound : org/pnfolder/pnlibrary/api/commands/error/InvalidArgument { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V } -public class org/pnfolder/pnlibrary/api/chat/ChatKit { - public static final field Companion Lorg/pnfolder/pnlibrary/api/chat/ChatKit$Companion; - public static final field MAX_LINE I - public static final field MAX_MESSAGE I - public fun (Lorg/pnfolder/pnlibrary/api/chat/ChatReader;)V - public final fun actions ([Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/Component; - public final fun blank ()Lnet/kyori/adventure/text/Component; - public final fun bracketed (Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; - public final fun button (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; - public final fun chip (ILjava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; - public final fun commandHints ([Lkotlin/Pair;)Ljava/util/List; - public final fun confirmation (Ljava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/util/List; - public final fun confirmationChoices (Ljava/lang/String;Ljava/util/List;Ljava/util/List;)Ljava/util/List; - public final fun dot ()Lnet/kyori/adventure/text/Component; - public final fun field (Ljava/lang/String;Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/Component; - public final fun framed (Ljava/util/List;)Ljava/util/List; - public final fun getReader ()Lorg/pnfolder/pnlibrary/api/chat/ChatReader; - public final fun glyph (C)Ljava/lang/String; - public final fun header (Ljava/lang/String;Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/Component; - public static synthetic fun header$default (Lorg/pnfolder/pnlibrary/api/chat/ChatKit;Ljava/lang/String;Lnet/kyori/adventure/text/Component;ILjava/lang/Object;)Lnet/kyori/adventure/text/Component; - public final fun hoverField (Ljava/lang/String;Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/Component; - public final fun linkButton (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; - public final fun mark (Lorg/pnfolder/pnlibrary/api/chat/ChatTone;)Lnet/kyori/adventure/text/Component; - public final fun note (Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; - public static synthetic fun note$default (Lorg/pnfolder/pnlibrary/api/chat/ChatKit;Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;ILjava/lang/Object;)Lnet/kyori/adventure/text/Component; - public final fun notice (Lorg/pnfolder/pnlibrary/api/chat/ChatNotice;)Ljava/util/List; - public final fun option (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; - public final fun safeLink (Ljava/lang/String;)Z - public final fun section (Ljava/lang/String;)Lnet/kyori/adventure/text/Component; - public final fun selected (Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; - public final fun setting (Ljava/lang/String;Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/Component; - public final fun shown (Ljava/lang/String;)Ljava/lang/String; - public final fun spaced (Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/Component; - public final fun text (Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;)Lnet/kyori/adventure/text/Component; - public static synthetic fun text$default (Lorg/pnfolder/pnlibrary/api/chat/ChatKit;Ljava/lang/String;Lnet/kyori/adventure/text/format/TextColor;ILjava/lang/Object;)Lnet/kyori/adventure/text/Component; - public final fun tooltip ([Lnet/kyori/adventure/text/Component;)Lnet/kyori/adventure/text/event/HoverEvent; +public final class org/pnfolder/pnlibrary/api/commands/error/PlayerOnly : org/pnfolder/pnlibrary/api/commands/error/CommandError { + public fun ()V } -public final class org/pnfolder/pnlibrary/api/chat/ChatKit$Companion { +public class org/pnfolder/pnlibrary/api/commands/error/UnknownArgument : org/pnfolder/pnlibrary/api/commands/error/BadUsage { + public fun (Ljava/lang/String;Ljava/lang/String;)V + public final fun getValue ()Ljava/lang/String; + public fun placeholders ()Ljava/util/Map; } -public final class org/pnfolder/pnlibrary/api/chat/ChatNotice { - public fun (Lorg/pnfolder/pnlibrary/api/chat/ChatTone;Ljava/lang/String;Ljava/lang/String;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/chat/ChatTone;Ljava/lang/String;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/chat/ChatTone; - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Ljava/lang/String; - public final fun copy (Lorg/pnfolder/pnlibrary/api/chat/ChatTone;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/chat/ChatNotice; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/chat/ChatNotice;Lorg/pnfolder/pnlibrary/api/chat/ChatTone;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/chat/ChatNotice; - public fun equals (Ljava/lang/Object;)Z - public final fun getDetail ()Ljava/lang/String; - public final fun getText ()Ljava/lang/String; - public final fun getTone ()Lorg/pnfolder/pnlibrary/api/chat/ChatTone; - public fun hashCode ()I +public final class org/pnfolder/pnlibrary/api/cooldowns/CooldownResult { + public static final field Companion Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownResult$Companion; + public synthetic fun (ZLjava/time/Duration;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun allowed ()Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownResult; + public static final fun denied (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownResult; + public final fun getAllowed ()Z + public final fun getRemaining ()Ljava/time/Duration; public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/chat/ChatNoticeKt { - public static final fun getColor (Lorg/pnfolder/pnlibrary/api/chat/ChatTone;)Lnet/kyori/adventure/text/format/TextColor; +public final class org/pnfolder/pnlibrary/api/cooldowns/CooldownResult$Companion { + public final fun allowed ()Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownResult; + public final fun denied (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownResult; } -public final class org/pnfolder/pnlibrary/api/chat/ChatPalette { - public static final field ACCENT Lnet/kyori/adventure/text/format/TextColor; - public static final field DANGER Lnet/kyori/adventure/text/format/TextColor; - public static final field FAINT Lnet/kyori/adventure/text/format/TextColor; - public static final field INFO Lnet/kyori/adventure/text/format/TextColor; - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/chat/ChatPalette; - public static final field LABEL Lnet/kyori/adventure/text/format/TextColor; - public static final field OK Lnet/kyori/adventure/text/format/TextColor; - public static final field ORANGE Lnet/kyori/adventure/text/format/TextColor; - public static final field SOFT Lnet/kyori/adventure/text/format/TextColor; - public static final field TEXT Lnet/kyori/adventure/text/format/TextColor; - public static final field WARN Lnet/kyori/adventure/text/format/TextColor; +public abstract interface class org/pnfolder/pnlibrary/api/cooldowns/CooldownService : java/lang/AutoCloseable { + public abstract fun acquire (Ljava/util/UUID;Ljava/lang/String;Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownResult; + public abstract fun active (Ljava/util/UUID;)Ljava/util/Map; + public abstract fun clear ()V + public abstract fun clear (Ljava/util/UUID;)I + public abstract fun extend (Ljava/util/UUID;Ljava/lang/String;Ljava/time/Duration;)Ljava/time/Duration; + public abstract fun getSize ()I + public abstract fun has (Ljava/util/UUID;Ljava/lang/String;)Z + public abstract fun remaining (Ljava/util/UUID;Ljava/lang/String;)Ljava/time/Duration; + public abstract fun reset (Ljava/util/UUID;Ljava/lang/String;)Z + public abstract fun set (Ljava/util/UUID;Ljava/lang/String;Ljava/time/Duration;)V } -public final class org/pnfolder/pnlibrary/api/chat/ChatReader { - public static final field CONSOLE Lorg/pnfolder/pnlibrary/api/chat/ChatReader; - public static final field Companion Lorg/pnfolder/pnlibrary/api/chat/ChatReader$Companion; - public static final field PLAYER Lorg/pnfolder/pnlibrary/api/chat/ChatReader; - public fun ()V - public fun (ZZ)V - public synthetic fun (ZZILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Z - public final fun component2 ()Z - public final fun copy (ZZ)Lorg/pnfolder/pnlibrary/api/chat/ChatReader; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/chat/ChatReader;ZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/chat/ChatReader; - public fun equals (Ljava/lang/Object;)Z - public final fun getAscii ()Z - public final fun getInteractive ()Z - public fun hashCode ()I - public static final fun of (Lorg/pnfolder/pnlibrary/api/commands/CommandSender;)Lorg/pnfolder/pnlibrary/api/chat/ChatReader; - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/dependencies/Dependencies { + public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/dependencies/Dependencies; + public static final fun managed (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun managed (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun managed (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun managed (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static synthetic fun managed$default (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/util/List;Z)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static synthetic fun plugin$default (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static synthetic fun plugin$default (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; + public static synthetic fun plugin$default (Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; } -public final class org/pnfolder/pnlibrary/api/chat/ChatReader$Companion { - public final fun of (Lorg/pnfolder/pnlibrary/api/commands/CommandSender;)Lorg/pnfolder/pnlibrary/api/chat/ChatReader; +public final class org/pnfolder/pnlibrary/api/dependencies/DependencyBuilder { + public fun ()V + public final fun build ()Ljava/util/List; + public final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder; + public final fun plugin (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder; + public final fun product (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder; } -public final class org/pnfolder/pnlibrary/api/chat/ChatTone : java/lang/Enum { - public static final field FAILURE Lorg/pnfolder/pnlibrary/api/chat/ChatTone; - public static final field INFO Lorg/pnfolder/pnlibrary/api/chat/ChatTone; - public static final field PROGRESS Lorg/pnfolder/pnlibrary/api/chat/ChatTone; - public static final field SUCCESS Lorg/pnfolder/pnlibrary/api/chat/ChatTone; - public static final field WARNING Lorg/pnfolder/pnlibrary/api/chat/ChatTone; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/chat/ChatTone; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/chat/ChatTone; +public final class org/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder { + public final fun artifact (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun automaticDownload (Z)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun description (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun downloadPage (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun downloadPolicy (Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun forceAutomaticDownload (Z)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun maxBytes (J)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun maximumVersion (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun maximumVersionExclusive (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun minimumVersion (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun mirror (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun required (Z)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun title (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun url (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun variant (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/Long;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public static synthetic fun variant$default (Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder;Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/Long;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun verifyPluginId (Z)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; + public final fun verifyVersion (Z)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; } -public final class org/pnfolder/pnlibrary/api/chat/ConfirmChoice { - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/chat/ConfirmChoice; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/chat/ConfirmChoice;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/chat/ConfirmChoice; - public fun equals (Ljava/lang/Object;)Z - public final fun getCommand ()Ljava/lang/String; - public final fun getHint ()Ljava/lang/String; - public final fun getLabel ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder { + public final fun downloadPolicy (Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder; + public final fun github (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder; + public final fun maximumVersion (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder; + public final fun maximumVersionExclusive (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder; + public final fun minimumVersion (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder; + public final fun required (Z)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder; } -public abstract interface class org/pnfolder/pnlibrary/api/checks/Check { - public abstract fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z +public final class org/pnfolder/pnlibrary/api/dependencies/DownloadPolicy : java/lang/Enum { + public static final field AUTOMATIC Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; + public static final field FORCED Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; + public static final field MANUAL Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; } -public abstract interface class org/pnfolder/pnlibrary/api/checks/CheckContext { - public abstract fun getLogger ()Lorg/pnfolder/pnlibrary/api/logging/PnLogger; - public abstract fun getPlayer ()Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer; - public abstract fun read (Ljava/lang/String;)Ljava/lang/Object; - public abstract fun requirement (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/checks/Requirement; - public fun requirementNames ()Ljava/util/Set; - public abstract fun textOf (Ljava/lang/String;)Ljava/lang/String; - public abstract fun value (Ljava/lang/String;)Ljava/lang/Object; +public abstract interface class org/pnfolder/pnlibrary/api/dependencies/PluginDependency { + public fun getAutomaticDownload ()Z + public fun getDownloadPolicy ()Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; + public fun getExternal ()Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency; + public fun getForceAutomaticDownload ()Z + public fun getManaged ()Lorg/pnfolder/pnlibrary/api/dependencies/external/ManagedProductDependency; + public fun getRequired ()Z + public abstract fun getVersions ()Lorg/pnfolder/pnlibrary/api/dependencies/VersionConstraint; } -public final class org/pnfolder/pnlibrary/api/checks/Requirement { - public static final field SINGLE Ljava/lang/String; - public fun ()V - public fun (Ljava/util/Map;IZLjava/util/List;Ljava/util/List;)V - public synthetic fun (Ljava/util/Map;IZLjava/util/List;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public fun (Lorg/pnfolder/pnlibrary/api/checks/Check;Ljava/util/List;Ljava/util/List;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/checks/Check;Ljava/util/List;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun check (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public final fun component1 ()Ljava/util/Map; - public final fun component2 ()I - public final fun component3 ()Z - public final fun component4 ()Ljava/util/List; - public final fun component5 ()Ljava/util/List; - public final fun copy (Ljava/util/Map;IZLjava/util/List;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/checks/Requirement; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/Requirement;Ljava/util/Map;IZLjava/util/List;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/Requirement; - public fun equals (Ljava/lang/Object;)Z - public final fun getDeny ()Ljava/util/List; - public final fun getEntries ()Ljava/util/Map; - public final fun getMinimum ()I - public final fun getStopAtSuccess ()Z - public final fun getSuccess ()Ljava/util/List; - public fun hashCode ()I - public final fun test (Lorg/pnfolder/pnlibrary/api/actions/ActionContext;)Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/dependencies/VersionConstraint { + public fun (Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun accepts (Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)Z + public final fun getMaximumExclusive ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; + public final fun getMaximumInclusive ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; + public final fun getMinimum ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; } -public final class org/pnfolder/pnlibrary/api/checks/Requirement$Entry { - public fun ()V - public fun (Lorg/pnfolder/pnlibrary/api/checks/Check;ZLjava/util/List;Ljava/util/List;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/checks/Check;ZLjava/util/List;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/checks/Check; - public final fun component2 ()Z - public final fun component3 ()Ljava/util/List; - public final fun component4 ()Ljava/util/List; - public final fun copy (Lorg/pnfolder/pnlibrary/api/checks/Check;ZLjava/util/List;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/checks/Requirement$Entry; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/Requirement$Entry;Lorg/pnfolder/pnlibrary/api/checks/Check;ZLjava/util/List;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/Requirement$Entry; - public fun equals (Ljava/lang/Object;)Z - public final fun getCheck ()Lorg/pnfolder/pnlibrary/api/checks/Check; - public final fun getDeny ()Ljava/util/List; - public final fun getOptional ()Z - public final fun getSuccess ()Ljava/util/List; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/dependencies/external/ExternalArtifact { + public fun (Ljava/net/URI;Ljava/lang/String;Ljava/util/List;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;)V + public synthetic fun (Ljava/net/URI;Ljava/lang/String;Ljava/util/List;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun fits (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;Ljava/lang/String;)Z + public final fun getLabel ()Ljava/lang/String; + public final fun getMaxBytes ()Ljava/lang/Long; + public final fun getMinecraftBefore ()Ljava/lang/String; + public final fun getMinecraftFrom ()Ljava/lang/String; + public final fun getMirrors ()Ljava/util/List; + public final fun getPlatforms ()Ljava/util/Set; + public final fun getSha256 ()Ljava/lang/String; + public final fun getUri ()Ljava/net/URI; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/AllCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Ljava/util/List;)V - public synthetic fun (Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/util/List; - public final fun copy (Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/checks/builtin/AllCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/AllCheck;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/AllCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getChecks ()Ljava/util/List; - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency : org/pnfolder/pnlibrary/api/dependencies/PluginDependency { + public static final field Companion Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun artifactFor (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalArtifact; + public static final fun builder (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun getArtifact ()Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalArtifact; + public final fun getArtifacts ()Ljava/util/List; + public final fun getDescription ()Ljava/lang/String; + public final fun getDownloadPage ()Ljava/net/URI; + public fun getDownloadPolicy ()Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; + public fun getExternal ()Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency; + public final fun getMinimumVersion ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; + public final fun getPlugin ()Ljava/lang/String; + public fun getRequired ()Z + public final fun getTitle ()Ljava/lang/String; + public final fun getVerifyPluginId ()Z + public final fun getVerifyVersion ()Z + public fun getVersions ()Lorg/pnfolder/pnlibrary/api/dependencies/VersionConstraint; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/AnyCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Ljava/util/List;)V - public synthetic fun (Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/util/List; - public final fun copy (Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/checks/builtin/AnyCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/AnyCheck;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/AnyCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getChecks ()Ljava/util/List; - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder { + public final fun artifact (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun automaticDownload (Z)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun build ()Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency; + public final fun description (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun downloadPage (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun downloadPolicy (Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun forceAutomaticDownload (Z)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun maxBytes (J)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun maximumVersion (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun maximumVersionExclusive (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun mirror (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun required (Z)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun title (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun url (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun variant (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun variant (Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/Long;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public static synthetic fun variant$default (Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder;Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/Long;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun verifyPluginId (Z)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; + public final fun verifyVersion (Z)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; +} + +public final class org/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Companion { + public final fun builder (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency$Builder; +} + +public final class org/pnfolder/pnlibrary/api/dependencies/external/ManagedProductDependency : org/pnfolder/pnlibrary/api/dependencies/PluginDependency { + public static final field Companion Lorg/pnfolder/pnlibrary/api/dependencies/external/ManagedProductDependency$Companion; + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/dependencies/VersionConstraint;Ljava/lang/String;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/dependencies/VersionConstraint;Ljava/lang/String;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Ljava/lang/String;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Ljava/lang/String;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun getDownloadPolicy ()Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; + public fun getManaged ()Lorg/pnfolder/pnlibrary/api/dependencies/external/ManagedProductDependency; + public final fun getMinimumVersion ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public final fun getRepositoryName ()Ljava/lang/String; + public final fun getRepositoryOwner ()Ljava/lang/String; + public fun getRequired ()Z + public fun getVersions ()Lorg/pnfolder/pnlibrary/api/dependencies/VersionConstraint; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/AtLeastCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (ILjava/util/List;)V - public synthetic fun (ILjava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()I - public final fun component2 ()Ljava/util/List; - public final fun copy (ILjava/util/List;)Lorg/pnfolder/pnlibrary/api/checks/builtin/AtLeastCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/AtLeastCheck;ILjava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/AtLeastCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getChecks ()Ljava/util/List; - public final fun getCount ()I - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/dependencies/external/ManagedProductDependency$Companion { } -public final class org/pnfolder/pnlibrary/api/checks/builtin/ChanceCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (D)V - public synthetic fun (DILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()D - public final fun copy (D)Lorg/pnfolder/pnlibrary/api/checks/builtin/ChanceCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/ChanceCheck;DILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/ChanceCheck; +public final class org/pnfolder/pnlibrary/api/diagnostics/DebugRequest { + public static final field Companion Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest$Companion; + public fun (Ljava/lang/String;ZZZ)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Z + public final fun component3 ()Z + public final fun component4 ()Z + public final fun copy (Ljava/lang/String;ZZZ)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest;Ljava/lang/String;ZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; public fun equals (Ljava/lang/Object;)Z - public final fun getProbability ()D + public final fun getConfigs ()Z + public final fun getLocal ()Z + public final fun getLogs ()Z + public final fun getTarget ()Ljava/lang/String; public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z + public static final fun parse ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; + public static final fun parse ([Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/Comparison : java/lang/Enum { - public static final field ABSENT Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public static final field CONTAINS Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public static final field EQUALS Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public static final field GREATER_OR_EQUAL Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public static final field GREATER_THAN Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public static final field LESS_OR_EQUAL Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public static final field LESS_THAN Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public static final field NOT_EQUALS Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public static final field NUMBER_EQUALS Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public static final field NUMBER_NOT_EQUALS Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public static final field PRESENT Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; +public final class org/pnfolder/pnlibrary/api/diagnostics/DebugRequest$Companion { + public final fun parse ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; + public final fun parse ([Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; + public static synthetic fun parse$default (Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest$Companion;[Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/ExperienceCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (IZ)V - public synthetic fun (IZILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()I - public final fun component2 ()Z - public final fun copy (IZ)Lorg/pnfolder/pnlibrary/api/checks/builtin/ExperienceCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/ExperienceCheck;IZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/ExperienceCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getAmount ()I - public final fun getLevel ()Z - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration { + public static final field Companion Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder; + public final fun getExcludedPaths ()Ljava/util/List; + public final fun getPath ()Ljava/lang/String; + public final fun getSecretKeyPatterns ()Ljava/util/List; + public final fun getValuePatterns ()Ljava/util/List; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/FlagCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Ljava/lang/String;Z)V - public synthetic fun (Ljava/lang/String;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Z - public final fun copy (Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/checks/builtin/FlagCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/FlagCheck;Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/FlagCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getEnabled ()Z - public final fun getFlag ()Ljava/lang/String; - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration; + public final fun exclude (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder; + public final fun redactValueRegex (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder; + public final fun secretKeyRegex (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/ItemCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V - public synthetic fun (Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()I - public final fun component3 ()Ljava/lang/String; - public final fun component4 ()Ljava/lang/String; - public final fun component5 ()Ljava/lang/String; - public final fun component6 ()Z - public final fun copy (Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/checks/builtin/ItemCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/ItemCheck;Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/ItemCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getAmount ()I - public final fun getIgnoreCase ()Z - public final fun getLoreContains ()Ljava/lang/String; - public final fun getMaterial ()Ljava/lang/String; - public final fun getName ()Ljava/lang/String; - public final fun getNameContains ()Ljava/lang/String; - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Companion { + public final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/LengthCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Ljava/lang/String;II)V - public synthetic fun (Ljava/lang/String;IIILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()I - public final fun component3 ()I - public final fun copy (Ljava/lang/String;II)Lorg/pnfolder/pnlibrary/api/checks/builtin/LengthCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/LengthCheck;Ljava/lang/String;IIILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/LengthCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getInput ()Ljava/lang/String; - public final fun getMax ()I - public final fun getMin ()I - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticRegistration : java/lang/AutoCloseable { + public abstract fun close ()V + public fun isClosed ()Z } -public final class org/pnfolder/pnlibrary/api/checks/builtin/NamedCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Ljava/lang/String;)V - public synthetic fun (Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/checks/builtin/NamedCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/NamedCheck;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/NamedCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getName ()Ljava/lang/String; - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticsContributor { + public abstract fun collect ()Ljava/util/Map; + public fun configurationFiles ()Ljava/util/Collection; + public fun configurations ()Ljava/util/Collection; + public fun getId ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/NearCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Ljava/lang/String;D)V - public synthetic fun (Ljava/lang/String;DILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()D - public final fun copy (Ljava/lang/String;D)Lorg/pnfolder/pnlibrary/api/checks/builtin/NearCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/NearCheck;Ljava/lang/String;DILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/NearCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getDistance ()D - public final fun getLocation ()Ljava/lang/String; - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService { + public static final field API_VERSION I + public static final field Companion Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService$Companion; + public fun clearPlugin (Ljava/lang/String;)V + public abstract fun clearStatus (Ljava/lang/String;Ljava/lang/String;)V + public fun getApiVersion ()I + public abstract fun record (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticLevel;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;Ljava/util/Map;)V + public static synthetic fun record$default (Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticLevel;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;Ljava/util/Map;ILjava/lang/Object;)V + public abstract fun register (Ljava/lang/String;Ljava/nio/file/Path;Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticsContributor;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticRegistration; + public abstract fun register (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticsContributor;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticRegistration; + public abstract fun status (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)V + public static synthetic fun status$default (Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)V } -public final class org/pnfolder/pnlibrary/api/checks/builtin/NotCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Lorg/pnfolder/pnlibrary/api/checks/Check;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/checks/Check;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/checks/Check; - public final fun copy (Lorg/pnfolder/pnlibrary/api/checks/Check;)Lorg/pnfolder/pnlibrary/api/checks/builtin/NotCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/NotCheck;Lorg/pnfolder/pnlibrary/api/checks/Check;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/NotCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getCheck ()Lorg/pnfolder/pnlibrary/api/checks/Check; - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService$Companion { + public static final field API_VERSION I } -public final class org/pnfolder/pnlibrary/api/checks/builtin/PermissionCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Ljava/lang/String;)V - public synthetic fun (Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/checks/builtin/PermissionCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/PermissionCheck;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/PermissionCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getPermission ()Ljava/lang/String; - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer : org/pnfolder/pnlibrary/api/diagnostics/DiagnosticsContributor { + public static final field Companion Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer$Builder; + public fun collect ()Ljava/util/Map; + public fun configurationFiles ()Ljava/util/Collection; + public fun configurations ()Ljava/util/Collection; + public fun getId ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/PermissionsCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Ljava/util/List;Ljava/lang/Integer;)V - public synthetic fun (Ljava/util/List;Ljava/lang/Integer;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/util/List; - public final fun component2 ()Ljava/lang/Integer; - public final fun copy (Ljava/util/List;Ljava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/checks/builtin/PermissionsCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/PermissionsCheck;Ljava/util/List;Ljava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/PermissionsCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getMinimum ()Ljava/lang/Integer; - public final fun getPermissions ()Ljava/util/List; - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer; + public final fun configuration (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer$Builder; + public final fun configuration (Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration;)Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer$Builder; + public final fun snapshot (Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer$Builder; + public final fun value (Ljava/lang/String;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer$Builder; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/RegexCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Ljava/lang/String;Ljava/lang/String;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/checks/builtin/RegexCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/RegexCheck;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/RegexCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getInput ()Ljava/lang/String; - public final fun getRegex ()Ljava/lang/String; - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer$Companion { + public final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer$Builder; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/TypeCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueType;)V - public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueType;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueType; - public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueType;)Lorg/pnfolder/pnlibrary/api/checks/builtin/TypeCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/TypeCheck;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueType;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/TypeCheck; - public fun equals (Ljava/lang/Object;)Z - public final fun getInput ()Ljava/lang/String; - public final fun getType ()Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueType; - public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticLevel : java/lang/Enum { + public static final field ERROR Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticLevel; + public static final field INFO Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticLevel; + public static final field WARNING Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticLevel; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticLevel; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticLevel; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/ValueCheck : org/pnfolder/pnlibrary/api/checks/Check { - public fun ()V - public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison;Ljava/lang/String;Z)V - public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison;Ljava/lang/String;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; +public final class org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticReport { + public fun (Ljava/nio/file/Path;ZLjava/lang/String;Ljava/lang/String;)V + public final fun component1 ()Ljava/nio/file/Path; + public final fun component2 ()Z public final fun component3 ()Ljava/lang/String; - public final fun component4 ()Z - public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueCheck; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueCheck;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison;Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueCheck; + public final fun component4 ()Ljava/lang/String; + public final fun copy (Ljava/nio/file/Path;ZLjava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticReport; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticReport;Ljava/nio/file/Path;ZLjava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticReport; public fun equals (Ljava/lang/Object;)Z - public final fun getIgnoreCase ()Z - public final fun getOperator ()Lorg/pnfolder/pnlibrary/api/checks/builtin/Comparison; - public final fun getSource ()Ljava/lang/String; - public final fun getValue ()Ljava/lang/String; + public final fun getEncrypted ()Z + public final fun getLocalFile ()Ljava/nio/file/Path; + public final fun getUploadError ()Ljava/lang/String; + public final fun getUploadedUrl ()Ljava/lang/String; public fun hashCode ()I - public fun matches (Lorg/pnfolder/pnlibrary/api/checks/CheckContext;)Z public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/checks/builtin/ValueType : java/lang/Enum { - public static final field DOUBLE Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueType; - public static final field INT Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueType; - public static final field UUID Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueType; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueType; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/checks/builtin/ValueType; -} - -public final class org/pnfolder/pnlibrary/api/checks/internal/CheckSerializer : org/pnfolder/pnlibrary/api/config/ConfigSerializer { - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/checks/internal/CheckSerializer; - public final fun describe (Lorg/pnfolder/pnlibrary/api/checks/Check;)Ljava/util/Map; - public synthetic fun deserialize (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Ljava/lang/Object; - public fun deserialize (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Lorg/pnfolder/pnlibrary/api/checks/Check; - public final fun parse (Ljava/util/Map;Ljava/util/Set;)Lorg/pnfolder/pnlibrary/api/checks/Check; - public static synthetic fun parse$default (Lorg/pnfolder/pnlibrary/api/checks/internal/CheckSerializer;Ljava/util/Map;Ljava/util/Set;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/checks/Check; - public final fun read (Ljava/lang/Object;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/checks/Check; - public synthetic fun serialize (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Ljava/lang/Object; - public fun serialize (Lorg/pnfolder/pnlibrary/api/checks/Check;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Ljava/lang/Object; - public final fun write (Lorg/pnfolder/pnlibrary/api/checks/Check;)Ljava/lang/Object; -} - -public final class org/pnfolder/pnlibrary/api/checks/internal/RequirementEntrySerializer : org/pnfolder/pnlibrary/api/config/ConfigSerializer { - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/checks/internal/RequirementEntrySerializer; - public synthetic fun deserialize (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Ljava/lang/Object; - public fun deserialize (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Lorg/pnfolder/pnlibrary/api/checks/Requirement$Entry; - public synthetic fun serialize (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Ljava/lang/Object; - public fun serialize (Lorg/pnfolder/pnlibrary/api/checks/Requirement$Entry;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Ljava/lang/Object; -} - -public final class org/pnfolder/pnlibrary/api/checks/internal/RequirementSerializer : org/pnfolder/pnlibrary/api/config/ConfigSerializer { - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/checks/internal/RequirementSerializer; - public synthetic fun deserialize (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Ljava/lang/Object; - public fun deserialize (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Lorg/pnfolder/pnlibrary/api/checks/Requirement; - public synthetic fun serialize (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Ljava/lang/Object; - public fun serialize (Lorg/pnfolder/pnlibrary/api/checks/Requirement;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Ljava/lang/Object; -} - -public final class org/pnfolder/pnlibrary/api/commands/ArgumentSpec { - public static final field BOOLEAN Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static final field Companion Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Companion; - public static final field GREEDY Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static final field TEXT Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public synthetic fun (Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Kind;Ljava/lang/Double;Ljava/lang/Double;Ljava/util/List;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun choice (Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static final fun decimal ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static final fun decimal (D)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static final fun decimal (DD)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public final fun getChoices ()Ljava/util/List; - public final fun getKind ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Kind; - public final fun getMaximum ()Ljava/lang/Double; - public final fun getMinimum ()Ljava/lang/Double; - public static final fun integer ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static final fun integer (I)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static final fun integer (II)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static final fun long ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static final fun long (J)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static final fun long (JJ)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; -} - -public final class org/pnfolder/pnlibrary/api/commands/ArgumentSpec$Companion { - public final fun choice (Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public final fun decimal ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public final fun decimal (D)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public final fun decimal (DD)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static synthetic fun decimal$default (Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Companion;DDILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public final fun integer ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public final fun integer (I)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public final fun integer (II)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static synthetic fun integer$default (Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Companion;IIILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public final fun long ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public final fun long (J)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public final fun long (JJ)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static synthetic fun long$default (Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Companion;JJILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; -} - -public final class org/pnfolder/pnlibrary/api/commands/ArgumentSpec$Kind : java/lang/Enum { - public static final field BOOLEAN Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Kind; - public static final field CHOICE Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Kind; - public static final field DECIMAL Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Kind; - public static final field GREEDY Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Kind; - public static final field INTEGER Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Kind; - public static final field LONG Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Kind; - public static final field TEXT Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Kind; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Kind; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec$Kind; -} - -public abstract interface class org/pnfolder/pnlibrary/api/commands/ArgumentType { - public static final field Companion Lorg/pnfolder/pnlibrary/api/commands/ArgumentType$Companion; - public static fun boolean ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public static fun choice ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public static fun decimal ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public static fun decimal (DD)Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public static fun enumeration (Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public fun error (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandError; - public fun getSpec ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentSpec; - public static fun greedyString ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public static fun integer ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public static fun integer (II)Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public static fun long ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public static fun long (JJ)Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public abstract fun parse (Ljava/lang/String;)Ljava/lang/Object; - public static fun player (Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public static fun string ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; -} - -public final class org/pnfolder/pnlibrary/api/commands/ArgumentType$Companion { - public final fun boolean ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public final fun choice ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public final fun decimal ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public final fun decimal (DD)Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public final fun enumeration (Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public final fun greedyString ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public final fun integer ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public final fun integer (II)Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public final fun long ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public final fun long (JJ)Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public final fun player (Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public final fun string ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; -} - -public class org/pnfolder/pnlibrary/api/commands/BadUsage : org/pnfolder/pnlibrary/api/commands/CommandError { - public fun (Ljava/lang/String;)V - public final fun getUsage ()Ljava/lang/String; - public fun placeholders ()Ljava/util/Map; +public final class org/pnfolder/pnlibrary/api/downloads/DirectDownloadSource { + public static final field Companion Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun builder ()Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; + public final fun getMaxBytes ()Ljava/lang/Long; + public final fun getMaximumJava ()Ljava/lang/Integer; + public final fun getMinimumJava ()I + public final fun getMirrors ()Ljava/util/List; + public final fun getPlatform ()Lorg/pnfolder/pnlibrary/api/platform/PlatformType; + public final fun getSha256 ()Ljava/lang/String; + public final fun getSize ()Ljava/lang/Long; + public final fun getUri ()Ljava/net/URI; + public final fun supports (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;I)Z } -public abstract interface class org/pnfolder/pnlibrary/api/commands/CommandAvailability { - public abstract fun isAvailable (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;)Z +public final class org/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource; + public final fun integrity (JLjava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; + public final fun java (I)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; + public final fun java (ILjava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; + public static synthetic fun java$default (Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder;ILjava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; + public final fun maxBytes (J)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; + public final fun mirror (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; + public final fun platform (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; + public final fun sha256 (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; + public final fun url (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; } -public final class org/pnfolder/pnlibrary/api/commands/CommandBuilder { - public final fun acceptsExtraArguments ()Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun aliases ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun argument (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/commands/ArgumentType;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final synthetic fun argument (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/commands/ArgumentType;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun availableIf (Lorg/pnfolder/pnlibrary/api/commands/CommandAvailability;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun build ()Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition; - public final fun consoleBypassesPermission ()Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun consoleBypassesPermission (Z)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public static synthetic fun consoleBypassesPermission$default (Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun consoleOnly ()Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun executes (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun executesAsync (Lorg/pnfolder/pnlibrary/api/commands/CommandHandler;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun getErrorHandlers ()Ljava/util/LinkedHashMap; - public final fun literal (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final synthetic fun literal (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun mount (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun noPermissionMessage (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun onError (Ljava/lang/Class;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun onError (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/commands/CommandErrorHandler;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun permission (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun permission (Ljava/lang/String;[Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun playerOnly ()Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun suggests (Ljava/util/function/Function;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun suggestsAsync (Lorg/pnfolder/pnlibrary/api/commands/SuggestionHandler;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; +public final class org/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Companion { + public final fun builder ()Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; } -public final class org/pnfolder/pnlibrary/api/commands/CommandContext { - public fun (Lorg/pnfolder/pnlibrary/api/commands/CommandSender;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/commands/CommandSender;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/commands/CommandSender; - public final fun component2 ()Ljava/util/List; +public final class org/pnfolder/pnlibrary/api/downloads/DownloadDestination : java/lang/Enum { + public static final field CACHE Lorg/pnfolder/pnlibrary/api/downloads/DownloadDestination; + public static final field DATA_FOLDER Lorg/pnfolder/pnlibrary/api/downloads/DownloadDestination; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/DownloadDestination; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/downloads/DownloadDestination; +} + +public abstract interface class org/pnfolder/pnlibrary/api/downloads/DownloadRegistration : java/lang/AutoCloseable { + public abstract fun close ()V + public abstract fun downloadNow ()Ljava/util/concurrent/CompletionStage; + public fun isClosed ()Z + public abstract fun snapshots ()Ljava/util/List; +} + +public final class org/pnfolder/pnlibrary/api/downloads/DownloadSnapshot { + public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/downloads/DownloadState;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/downloads/DownloadState;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; public final fun component3 ()Ljava/lang/String; - public final fun component4 ()Ljava/lang/String; - public final fun component5 ()Ljava/util/Map; - public final fun contains (Ljava/lang/String;)Z - public final fun copy (Lorg/pnfolder/pnlibrary/api/commands/CommandSender;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/commands/CommandContext; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;Lorg/pnfolder/pnlibrary/api/commands/CommandSender;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/commands/CommandContext; + public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/downloads/DownloadState;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/DownloadSnapshot; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/downloads/DownloadSnapshot;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/downloads/DownloadState;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/downloads/DownloadSnapshot; public fun equals (Ljava/lang/Object;)Z - public final fun get (Ljava/lang/String;)Ljava/lang/Object; - public final fun getArguments ()Ljava/util/List; - public final fun getCurrentInput ()Ljava/lang/String; - public final fun getInvokedAlias ()Ljava/lang/String; - public final fun getParsedValues ()Ljava/util/Map; - public final fun getSender ()Lorg/pnfolder/pnlibrary/api/commands/CommandSender; + public final fun getKey ()Ljava/lang/String; + public final fun getMessage ()Ljava/lang/String; + public final fun getState ()Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/commands/CommandDefinition { - public static final field Companion Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition$Companion; - public static final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; - public final fun getAliases ()Ljava/util/Set; - public final fun getConsoleBypassesPermission ()Z - public final fun getExecution ()Lorg/pnfolder/pnlibrary/api/commands/CommandHandler; - public final fun getName ()Ljava/lang/String; - public final fun getNoPermissionMessage ()Ljava/lang/String; - public final fun getPermission ()Ljava/lang/String; - public final fun getRoot ()Lorg/pnfolder/pnlibrary/api/commands/CommandNode; - public final fun getSuggestions ()Lorg/pnfolder/pnlibrary/api/commands/SuggestionHandler; +public final class org/pnfolder/pnlibrary/api/downloads/DownloadState : java/lang/Enum { + public static final field BLOCKED Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; + public static final field CLOSED Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; + public static final field CURRENT Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; + public static final field DECLARED Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; + public static final field DOWNLOADING Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; + public static final field FAILED Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; + public static final field STAGED Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; } -public final class org/pnfolder/pnlibrary/api/commands/CommandDefinition$Companion { - public final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandBuilder; +public final class org/pnfolder/pnlibrary/api/downloads/FileDownload { + public static final field Companion Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Companion; + public final fun getAutomatic ()Z + public final fun getDestination ()Lorg/pnfolder/pnlibrary/api/downloads/DownloadDestination; + public final fun getForceAutomaticDownload ()Z + public final fun getKey ()Ljava/lang/String; + public final fun getRelativePath ()Ljava/lang/String; + public final fun getRequired ()Z + public final fun getSource ()Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource; } -public final class org/pnfolder/pnlibrary/api/commands/CommandDefinitionKt { - public static final synthetic fun command (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition; - public static final fun completedExecution ()Ljava/util/concurrent/CompletionStage; - public static final fun completedSuggestions (Ljava/util/List;)Ljava/util/concurrent/CompletionStage; +public final class org/pnfolder/pnlibrary/api/downloads/FileDownload$Builder { + public final fun automaticDownload (Z)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; + public final fun destination (Lorg/pnfolder/pnlibrary/api/downloads/DownloadDestination;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; + public final fun forceAutomaticDownload (Z)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; + public final fun integrity (JLjava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; + public final fun java (I)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; + public final fun java (ILjava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; + public static synthetic fun java$default (Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder;ILjava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; + public final fun maxBytes (J)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; + public final fun mirror (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; + public final fun platform (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; + public final fun required (Z)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; + public final fun sha256 (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; + public final fun url (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; } -public class org/pnfolder/pnlibrary/api/commands/CommandError { - public fun ()V - public fun (Ljava/lang/String;)V - public synthetic fun (Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun format (Ljava/lang/String;)Ljava/lang/String; - public final fun getDefaultMessage ()Ljava/lang/String; - public fun placeholders ()Ljava/util/Map; +public final class org/pnfolder/pnlibrary/api/downloads/FileDownload$Companion { } -public abstract interface class org/pnfolder/pnlibrary/api/commands/CommandErrorHandler { - public abstract fun handle (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;Lorg/pnfolder/pnlibrary/api/commands/CommandError;)V -} +public final class org/pnfolder/pnlibrary/api/downloads/FileDownloads { + public static final field Companion Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun builder ()Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads$Builder; + public final fun getDataDirectory ()Ljava/nio/file/Path; + public final fun getFiles ()Ljava/util/List; +} -public final class org/pnfolder/pnlibrary/api/commands/CommandErrorKt { - public static final fun ensure (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;ZLkotlin/jvm/functions/Function0;)V - public static final fun fail (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;Lorg/pnfolder/pnlibrary/api/commands/CommandError;)Ljava/lang/Void; +public final class org/pnfolder/pnlibrary/api/downloads/FileDownloads$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads; + public final fun dataDirectory (Ljava/nio/file/Path;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads$Builder; + public final fun file (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads$Builder; +} + +public final class org/pnfolder/pnlibrary/api/downloads/FileDownloads$Companion { + public final fun builder ()Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads$Builder; } -public class org/pnfolder/pnlibrary/api/commands/CommandFailed : org/pnfolder/pnlibrary/api/commands/CommandError { +public abstract class org/pnfolder/pnlibrary/api/events/Event { public fun ()V - public fun (Ljava/lang/String;)V - public synthetic fun (Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun bindDispatch (Lorg/pnfolder/pnlibrary/api/events/bus/DispatchMode;Ljava/lang/Thread;)V + public final fun callEvent ()Z + public final fun callEventAsync ()Ljava/util/concurrent/CompletionStage; + public final fun callEventAsync (Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun callEventAsync$default (Lorg/pnfolder/pnlibrary/api/events/Event;Ljava/util/concurrent/Executor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public final fun getDenyReason ()Lnet/kyori/adventure/text/Component; + public final fun getDispatchMode ()Lorg/pnfolder/pnlibrary/api/events/bus/DispatchMode; + public final fun getDispatchThread ()Ljava/lang/Thread; + public fun getEventName ()Ljava/lang/String; + public final fun isAllowed ()Z + public final fun isAsync ()Z } -public final class org/pnfolder/pnlibrary/api/commands/CommandFailure : java/lang/RuntimeException { - public fun (Lorg/pnfolder/pnlibrary/api/commands/CommandError;)V - public final fun getError ()Lorg/pnfolder/pnlibrary/api/commands/CommandError; +public abstract interface annotation class org/pnfolder/pnlibrary/api/events/EventDescription : java/lang/annotation/Annotation { + public abstract fun purpose ()Ljava/lang/String; + public abstract fun usage ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/commands/CommandHandler { - public abstract fun execute (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;)Ljava/util/concurrent/CompletionStage; +public abstract interface annotation class org/pnfolder/pnlibrary/api/events/InternalEventApi : java/lang/annotation/Annotation { } -public final class org/pnfolder/pnlibrary/api/commands/CommandNode { - public final fun getAcceptsExtraArguments ()Z - public final fun getAlsoPermissions ()Ljava/util/List; - public final fun getArgumentType ()Lorg/pnfolder/pnlibrary/api/commands/ArgumentType; - public final fun getAvailability ()Lorg/pnfolder/pnlibrary/api/commands/CommandAvailability; - public final fun getChildren ()Ljava/util/List; - public final fun getConsoleBypassesPermission ()Z - public final fun getDescription ()Ljava/util/List; - public final fun getErrorHandlers ()Ljava/util/Map; - public final fun getExecution ()Lorg/pnfolder/pnlibrary/api/commands/CommandHandler; - public final fun getKind ()Lorg/pnfolder/pnlibrary/api/commands/CommandNodeKind; - public final fun getName ()Ljava/lang/String; - public final fun getNoPermissionMessage ()Ljava/lang/String; - public final fun getPermission ()Ljava/lang/String; - public final fun getSenderRule ()Lorg/pnfolder/pnlibrary/api/commands/SenderRule; - public final fun getSuggestions ()Lorg/pnfolder/pnlibrary/api/commands/SuggestionHandler; - public final fun isExecutable ()Z +public abstract class org/pnfolder/pnlibrary/api/events/ResultedEvent : org/pnfolder/pnlibrary/api/events/Event { + public fun ()V + public final fun callResult ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$Result; + public abstract fun getResult ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$Result; + public abstract fun setResult (Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$Result;)V } -public final class org/pnfolder/pnlibrary/api/commands/CommandNodeBuilder { - public final fun acceptsExtraArguments ()Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun argument (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/commands/ArgumentType;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final synthetic fun argument (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/commands/ArgumentType;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun availableIf (Lorg/pnfolder/pnlibrary/api/commands/CommandAvailability;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun consoleBypassesPermission ()Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun consoleBypassesPermission (Z)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public static synthetic fun consoleBypassesPermission$default (Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun consoleOnly ()Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun description ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun executes (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun executesAsync (Lorg/pnfolder/pnlibrary/api/commands/CommandHandler;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun getErrorHandlers ()Ljava/util/LinkedHashMap; - public final fun literal (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final synthetic fun literal (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun noPermissionMessage (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun onError (Ljava/lang/Class;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun onError (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/commands/CommandErrorHandler;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun permission (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun permission (Ljava/lang/String;[Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun playerOnly ()Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun suggests (Ljava/util/function/Function;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; - public final fun suggestsAsync (Lorg/pnfolder/pnlibrary/api/commands/SuggestionHandler;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeBuilder; -} - -public final class org/pnfolder/pnlibrary/api/commands/CommandNodeKind : java/lang/Enum { - public static final field ARGUMENT Lorg/pnfolder/pnlibrary/api/commands/CommandNodeKind; - public static final field LITERAL Lorg/pnfolder/pnlibrary/api/commands/CommandNodeKind; - public static final field ROOT Lorg/pnfolder/pnlibrary/api/commands/CommandNodeKind; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandNodeKind; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/commands/CommandNodeKind; +public final class org/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult : org/pnfolder/pnlibrary/api/events/ResultedEvent$Result { + public static final field Companion Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult$Companion; + public synthetic fun (ZLnet/kyori/adventure/text/Component;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun allowed ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult; + public static final fun denied (Lnet/kyori/adventure/text/Component;)Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult; + public final fun getReasonComponent ()Ljava/util/Optional; + public final fun getReasonComponent ()Lnet/kyori/adventure/text/Component; + public fun isAllowed ()Z + public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/commands/CommandRegistration : java/lang/AutoCloseable { - public abstract fun close ()V - public abstract fun getCommand ()Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition; - public abstract fun isClosed ()Z +public final class org/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult$Companion { + public final fun allowed ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult; + public final fun denied (Lnet/kyori/adventure/text/Component;)Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult; } -public abstract interface class org/pnfolder/pnlibrary/api/commands/CommandSender : org/pnfolder/pnlibrary/api/audiences/AudienceSender { - public fun actionBar (Lnet/kyori/adventure/text/Component;)V - public abstract fun getId ()Ljava/lang/String; - public abstract fun getName ()Ljava/lang/String; - public fun getSupportsInteraction ()Z - public abstract fun hasPermission (Ljava/lang/String;)Z - public abstract fun isConsole ()Z - public fun playSound (Lnet/kyori/adventure/sound/Sound;)Lorg/pnfolder/pnlibrary/api/audiences/Delivery; - public abstract fun send (Lnet/kyori/adventure/text/Component;)V - public fun sendMessage (Lnet/kyori/adventure/text/Component;)V +public final class org/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult : org/pnfolder/pnlibrary/api/events/ResultedEvent$Result { + public static final field Companion Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult$Companion; + public static final fun allowed ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult; + public static final fun denied ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult; + public fun isAllowed ()Z + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/commands/ConsoleOnly : org/pnfolder/pnlibrary/api/commands/CommandError { - public fun ()V +public final class org/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult$Companion { + public final fun allowed ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult; + public final fun denied ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult; } -public class org/pnfolder/pnlibrary/api/commands/IncompleteCommand : org/pnfolder/pnlibrary/api/commands/BadUsage { - public fun (Ljava/lang/String;)V +public abstract interface class org/pnfolder/pnlibrary/api/events/ResultedEvent$Result { + public abstract fun isAllowed ()Z } -public class org/pnfolder/pnlibrary/api/commands/InvalidArgument : org/pnfolder/pnlibrary/api/commands/BadUsage { - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public final fun getArgument ()Ljava/lang/String; - public final fun getValue ()Ljava/lang/String; - public fun placeholders ()Ljava/util/Map; +public final class org/pnfolder/pnlibrary/api/events/bus/DispatchMode : java/lang/Enum { + public static final field ASYNC Lorg/pnfolder/pnlibrary/api/events/bus/DispatchMode; + public static final field SYNC Lorg/pnfolder/pnlibrary/api/events/bus/DispatchMode; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/events/bus/DispatchMode; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/events/bus/DispatchMode; } -public class org/pnfolder/pnlibrary/api/commands/NoPermission : org/pnfolder/pnlibrary/api/commands/CommandError { - public fun (Ljava/lang/String;)V - public final fun getPermission ()Ljava/lang/String; - public fun placeholders ()Ljava/util/Map; +public abstract interface class org/pnfolder/pnlibrary/api/events/bus/EventScope : java/lang/AutoCloseable { + public abstract fun callEvent (Lorg/pnfolder/pnlibrary/api/events/Event;)Lorg/pnfolder/pnlibrary/api/events/Event; + public abstract fun close ()V + public abstract fun getPluginId ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public abstract fun isClosed ()Z + public abstract fun register (Lorg/pnfolder/pnlibrary/api/events/listener/Listener;)Lorg/pnfolder/pnlibrary/api/events/listener/EventListenerRegistration; + public fun subscribe (Ljava/lang/Class;ILjava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/listener/EventSubscription; + public abstract fun subscribe (Ljava/lang/Class;IZLjava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/listener/EventSubscription; + public fun subscribe (Ljava/lang/Class;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/listener/EventSubscription; } -public class org/pnfolder/pnlibrary/api/commands/OnCooldown : org/pnfolder/pnlibrary/api/commands/CommandError { - public fun (Ljava/time/Duration;)V - public final fun getRemaining ()Ljava/time/Duration; - public fun placeholders ()Ljava/util/Map; +public abstract interface class org/pnfolder/pnlibrary/api/events/bus/EventService : java/lang/AutoCloseable { + public abstract fun callEvent (Lorg/pnfolder/pnlibrary/api/events/Event;)Lorg/pnfolder/pnlibrary/api/events/Event; + public abstract fun callEventAsync (Lorg/pnfolder/pnlibrary/api/events/Event;)Ljava/util/concurrent/CompletionStage; + public abstract fun callEventAsync (Lorg/pnfolder/pnlibrary/api/events/Event;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletionStage; + public abstract fun close ()V + public abstract fun getInspector ()Lorg/pnfolder/pnlibrary/api/events/inspect/EventInspector; + public fun register (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/events/listener/Listener;)Lorg/pnfolder/pnlibrary/api/events/listener/EventListenerRegistration; + public abstract fun scope (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Lorg/pnfolder/pnlibrary/api/events/bus/EventScope; + public abstract fun scope (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)Lorg/pnfolder/pnlibrary/api/events/bus/EventScope; + public fun subscribe (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/lang/Class;IZLjava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/listener/EventSubscription; + public fun subscribe (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/lang/Class;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/listener/EventSubscription; + public abstract fun unregisterAll (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)V } -public class org/pnfolder/pnlibrary/api/commands/PlayerNotFound : org/pnfolder/pnlibrary/api/commands/InvalidArgument { - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V +public final class org/pnfolder/pnlibrary/api/events/inspect/EventInfo { + public fun (Ljava/lang/String;IJJLjava/time/Instant;)V + public synthetic fun (Ljava/lang/String;IJJLjava/time/Instant;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()I + public final fun component3 ()J + public final fun component4 ()J + public final fun component5 ()Ljava/time/Instant; + public final fun copy (Ljava/lang/String;IJJLjava/time/Instant;)Lorg/pnfolder/pnlibrary/api/events/inspect/EventInfo; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/events/inspect/EventInfo;Ljava/lang/String;IJJLjava/time/Instant;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/events/inspect/EventInfo; + public fun equals (Ljava/lang/Object;)Z + public final fun getCalls ()J + public final fun getDenied ()J + public final fun getEventType ()Ljava/lang/String; + public final fun getLastCalledAt ()Ljava/time/Instant; + public final fun getListeners ()I + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/commands/PlayerOnly : org/pnfolder/pnlibrary/api/commands/CommandError { - public fun ()V +public abstract interface class org/pnfolder/pnlibrary/api/events/inspect/EventInspector { + public abstract fun asyncQueued ()I + public abstract fun clearTraces ()V + public abstract fun disableTracing (Ljava/lang/Class;)V + public abstract fun enableTracing (Ljava/lang/Class;I)V + public static synthetic fun enableTracing$default (Lorg/pnfolder/pnlibrary/api/events/inspect/EventInspector;Ljava/lang/Class;IILjava/lang/Object;)V + public fun event (Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/events/inspect/EventInfo; + public abstract fun eventType (Ljava/lang/String;)Ljava/lang/Class; + public abstract fun events ()Ljava/util/List; + public abstract fun exportHistory (Z)Ljava/nio/file/Path; + public static synthetic fun exportHistory$default (Lorg/pnfolder/pnlibrary/api/events/inspect/EventInspector;ZILjava/lang/Object;)Ljava/nio/file/Path; + public abstract fun getHistoryDays ()I + public abstract fun history (Ljava/lang/String;)Ljava/util/List; + public static synthetic fun history$default (Lorg/pnfolder/pnlibrary/api/events/inspect/EventInspector;Ljava/lang/String;ILjava/lang/Object;)Ljava/util/List; + public abstract fun hourly (Ljava/lang/String;)Ljava/util/List; + public static synthetic fun hourly$default (Lorg/pnfolder/pnlibrary/api/events/inspect/EventInspector;Ljava/lang/String;ILjava/lang/Object;)Ljava/util/List; + public fun listenerCount (Ljava/lang/Class;)I + public abstract fun listeners ()Ljava/util/List; + public abstract fun listeners (Ljava/lang/Class;)Ljava/util/List; + public fun listeners (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)Ljava/util/List; + public static synthetic fun listeners$default (Lorg/pnfolder/pnlibrary/api/events/inspect/EventInspector;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;ILjava/lang/Object;)Ljava/util/List; + public fun plugins (Ljava/lang/Class;)Ljava/util/List; + public abstract fun tracedEvents ()Ljava/util/List; + public abstract fun traces ()Ljava/util/List; } -public final class org/pnfolder/pnlibrary/api/commands/SenderRule : java/lang/Enum { - public static final field ANY Lorg/pnfolder/pnlibrary/api/commands/SenderRule; - public static final field CONSOLE Lorg/pnfolder/pnlibrary/api/commands/SenderRule; - public static final field PLAYER Lorg/pnfolder/pnlibrary/api/commands/SenderRule; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/SenderRule; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/commands/SenderRule; +public final class org/pnfolder/pnlibrary/api/events/inspect/ListenerInfo { + public fun (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;IZLjava/lang/String;JJ)V + public fun (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;IZLjava/lang/String;JJJJ)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;IZLjava/lang/String;JJJJILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun component10 ()J + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()I + public final fun component5 ()Z + public final fun component6 ()Ljava/lang/String; + public final fun component7 ()J + public final fun component8 ()J + public final fun component9 ()J + public final fun copy (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;IZLjava/lang/String;JJJJ)Lorg/pnfolder/pnlibrary/api/events/inspect/ListenerInfo; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/events/inspect/ListenerInfo;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;IZLjava/lang/String;JJJJILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/events/inspect/ListenerInfo; + public fun equals (Ljava/lang/Object;)Z + public final fun getAverageNanos ()J + public final fun getEventType ()Ljava/lang/String; + public final fun getFailures ()J + public final fun getIgnoreDenied ()Z + public final fun getInvocations ()J + public final fun getMaxNanos ()J + public final fun getModule ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public final fun getPlugin ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun getPriority ()I + public final fun getSource ()Ljava/lang/String; + public final fun getTotalNanos ()J + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/commands/SuggestionHandler { - public abstract fun suggest (Lorg/pnfolder/pnlibrary/api/commands/CommandContext;)Ljava/util/concurrent/CompletionStage; +public final class org/pnfolder/pnlibrary/api/events/inspect/history/EventDay { + public fun (Ljava/time/LocalDate;Ljava/lang/String;JJ)V + public final fun component1 ()Ljava/time/LocalDate; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()J + public final fun component4 ()J + public final fun copy (Ljava/time/LocalDate;Ljava/lang/String;JJ)Lorg/pnfolder/pnlibrary/api/events/inspect/history/EventDay; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/events/inspect/history/EventDay;Ljava/time/LocalDate;Ljava/lang/String;JJILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/events/inspect/history/EventDay; + public fun equals (Ljava/lang/Object;)Z + public final fun getCalls ()J + public final fun getDate ()Ljava/time/LocalDate; + public final fun getDenied ()J + public final fun getEventType ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public class org/pnfolder/pnlibrary/api/commands/UnknownArgument : org/pnfolder/pnlibrary/api/commands/BadUsage { - public fun (Ljava/lang/String;Ljava/lang/String;)V - public final fun getValue ()Ljava/lang/String; - public fun placeholders ()Ljava/util/Map; +public final class org/pnfolder/pnlibrary/api/events/inspect/history/EventHour { + public fun (Ljava/time/LocalDateTime;Ljava/lang/String;JJ)V + public final fun component1 ()Ljava/time/LocalDateTime; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()J + public final fun component4 ()J + public final fun copy (Ljava/time/LocalDateTime;Ljava/lang/String;JJ)Lorg/pnfolder/pnlibrary/api/events/inspect/history/EventHour; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/events/inspect/history/EventHour;Ljava/time/LocalDateTime;Ljava/lang/String;JJILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/events/inspect/history/EventHour; + public fun equals (Ljava/lang/Object;)Z + public final fun getCalls ()J + public final fun getDenied ()J + public final fun getEventType ()Ljava/lang/String; + public final fun getHour ()Ljava/time/LocalDateTime; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/cooldowns/CooldownResult { - public static final field Companion Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownResult$Companion; - public synthetic fun (ZLjava/time/Duration;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun allowed ()Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownResult; - public static final fun denied (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownResult; +public final class org/pnfolder/pnlibrary/api/events/inspect/trace/EventTrace { + public fun (Ljava/lang/String;ZLjava/lang/String;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/events/bus/DispatchMode;Ljava/lang/String;Ljava/time/Instant;)V + public synthetic fun (Ljava/lang/String;ZLjava/lang/String;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/events/bus/DispatchMode;Ljava/lang/String;Ljava/time/Instant;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Z + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Ljava/util/List; + public final fun component5 ()Lorg/pnfolder/pnlibrary/api/events/bus/DispatchMode; + public final fun component6 ()Ljava/lang/String; + public final fun component7 ()Ljava/time/Instant; + public final fun copy (Ljava/lang/String;ZLjava/lang/String;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/events/bus/DispatchMode;Ljava/lang/String;Ljava/time/Instant;)Lorg/pnfolder/pnlibrary/api/events/inspect/trace/EventTrace; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/events/inspect/trace/EventTrace;Ljava/lang/String;ZLjava/lang/String;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/events/bus/DispatchMode;Ljava/lang/String;Ljava/time/Instant;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/events/inspect/trace/EventTrace; + public fun equals (Ljava/lang/Object;)Z public final fun getAllowed ()Z - public final fun getRemaining ()Ljava/time/Duration; + public final fun getAt ()Ljava/time/Instant; + public final fun getEventName ()Ljava/lang/String; + public final fun getMode ()Lorg/pnfolder/pnlibrary/api/events/bus/DispatchMode; + public final fun getResult ()Ljava/lang/String; + public final fun getSteps ()Ljava/util/List; + public final fun getThread ()Ljava/lang/String; + public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/cooldowns/CooldownResult$Companion { - public final fun allowed ()Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownResult; - public final fun denied (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownResult; +public final class org/pnfolder/pnlibrary/api/events/inspect/trace/EventTrace$Step { + public fun (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;IZZJLjava/lang/String;Ljava/lang/String;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public final fun component3 ()I + public final fun component4 ()Z + public final fun component5 ()Z + public final fun component6 ()J + public final fun component7 ()Ljava/lang/String; + public final fun component8 ()Ljava/lang/String; + public final fun copy (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;IZZJLjava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/events/inspect/trace/EventTrace$Step; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/events/inspect/trace/EventTrace$Step;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;IZZJLjava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/events/inspect/trace/EventTrace$Step; + public fun equals (Ljava/lang/Object;)Z + public final fun getChangedResult ()Z + public final fun getFailed ()Z + public final fun getModule ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public final fun getNanos ()J + public final fun getPlugin ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun getPriority ()I + public final fun getResultAfter ()Ljava/lang/String; + public final fun getResultBefore ()Ljava/lang/String; + public final fun getSkipped ()Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/cooldowns/CooldownService : java/lang/AutoCloseable { - public abstract fun acquire (Ljava/util/UUID;Ljava/lang/String;Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownResult; - public abstract fun clear ()V - public abstract fun extend (Ljava/util/UUID;Ljava/lang/String;Ljava/time/Duration;)Ljava/time/Duration; - public abstract fun getSize ()I - public abstract fun has (Ljava/util/UUID;Ljava/lang/String;)Z - public abstract fun remaining (Ljava/util/UUID;Ljava/lang/String;)Ljava/time/Duration; - public abstract fun reset (Ljava/util/UUID;Ljava/lang/String;)Z - public abstract fun set (Ljava/util/UUID;Ljava/lang/String;Ljava/time/Duration;)V +public abstract interface annotation class org/pnfolder/pnlibrary/api/events/listener/EventHandler : java/lang/annotation/Annotation { + public abstract fun ignoreDenied ()Z + public abstract fun priority ()I } -public final class org/pnfolder/pnlibrary/api/dependencies/Dependencies { - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/dependencies/Dependencies; - public static final fun managed (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static final fun managed (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static final fun managed (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static final fun managed (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static synthetic fun managed$default (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JLjava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JLjava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JLjava/lang/String;ZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JLjava/lang/String;ZZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZ)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static synthetic fun plugin$default (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;JLjava/lang/String;ZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; - public static synthetic fun plugin$default (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency; +public final class org/pnfolder/pnlibrary/api/events/listener/EventListenerBuilder { + public final fun ignoreDenied ()Lorg/pnfolder/pnlibrary/api/events/listener/EventListenerBuilder; + public final fun listen (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/listener/EventSubscription; + public final fun listenOnce (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/listener/EventSubscription; + public final fun priority (I)Lorg/pnfolder/pnlibrary/api/events/listener/EventListenerBuilder; } -public final class org/pnfolder/pnlibrary/api/dependencies/DependencyBuilder { - public fun ()V - public final fun build ()Ljava/util/List; - public final fun plugin (Ljava/lang/String;Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder; - public final fun plugin (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder; - public final fun product (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder; +public final class org/pnfolder/pnlibrary/api/events/listener/EventListenerBuilderKt { + public static final fun on (Lorg/pnfolder/pnlibrary/api/events/bus/EventScope;Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/events/listener/EventListenerBuilder; } -public final class org/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder { - public final fun artifact (Ljava/lang/String;JLjava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; - public final fun automaticDownload (Z)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; - public final fun downloadPage (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; - public final fun downloadPolicy (Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; - public final fun forceAutomaticDownload (Z)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; - public final fun maximumVersion (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; - public final fun maximumVersionExclusive (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; - public final fun minimumVersion (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; - public final fun required (Z)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; - public final fun url (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; - public final fun verifyPluginId (Z)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; - public final fun verifyVersion (Z)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ExternalBuilder; +public abstract interface class org/pnfolder/pnlibrary/api/events/listener/EventListenerRegistration : java/lang/AutoCloseable { + public abstract fun close ()V + public abstract fun getHandlerCount ()I + public abstract fun getListener ()Lorg/pnfolder/pnlibrary/api/events/listener/Listener; + public abstract fun isClosed ()Z } -public final class org/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder { - public final fun downloadPolicy (Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder; - public final fun github (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder; - public final fun maximumVersion (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder; - public final fun maximumVersionExclusive (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder; - public final fun minimumVersion (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder; - public final fun required (Z)Lorg/pnfolder/pnlibrary/api/dependencies/DependencyBuilder$ProductBuilder; +public final class org/pnfolder/pnlibrary/api/events/listener/EventPriority { + public static final field HIGH I + public static final field HIGHEST I + public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/events/listener/EventPriority; + public static final field LOW I + public static final field LOWEST I + public static final field MONITOR I + public static final field NORMAL I } -public final class org/pnfolder/pnlibrary/api/dependencies/DownloadPolicy : java/lang/Enum { - public static final field AUTOMATIC Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; - public static final field FORCED Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; - public static final field MANUAL Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; +public abstract interface class org/pnfolder/pnlibrary/api/events/listener/EventSubscription : java/lang/AutoCloseable { + public abstract fun close ()V + public abstract fun isClosed ()Z } -public final class org/pnfolder/pnlibrary/api/dependencies/ExternalArtifact { - public static final field Companion Lorg/pnfolder/pnlibrary/api/dependencies/ExternalArtifact$Companion; - public fun (Ljava/net/URI;Ljava/lang/Long;Ljava/lang/String;)V - public final fun getSha256 ()Ljava/lang/String; - public final fun getSize ()Ljava/lang/Long; - public final fun getUri ()Ljava/net/URI; +public abstract interface class org/pnfolder/pnlibrary/api/events/listener/Listener { } -public final class org/pnfolder/pnlibrary/api/dependencies/ExternalArtifact$Companion { +public final class org/pnfolder/pnlibrary/api/events/player/PlayerJoinedEvent : org/pnfolder/pnlibrary/api/events/player/PlayerLifecycleEvent { + public fun (Ljava/util/UUID;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer;)V } -public final class org/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency : org/pnfolder/pnlibrary/api/dependencies/PluginDependency { - public static final field Companion Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Companion; - public synthetic fun (Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun builder (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; - public final fun getArtifact ()Lorg/pnfolder/pnlibrary/api/dependencies/ExternalArtifact; - public final fun getDownloadPage ()Ljava/net/URI; - public fun getDownloadPolicy ()Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; - public fun getExternal ()Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency; - public final fun getMinimumVersion ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun getPlugin ()Ljava/lang/String; - public fun getRequired ()Z - public final fun getVerifyPluginId ()Z - public final fun getVerifyVersion ()Z - public fun getVersions ()Lorg/pnfolder/pnlibrary/api/dependencies/VersionConstraint; +public final class org/pnfolder/pnlibrary/api/events/player/PlayerLeftEvent : org/pnfolder/pnlibrary/api/events/player/PlayerLifecycleEvent { + public fun (Ljava/util/UUID;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer;)V } -public final class org/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder { - public final fun artifact (Ljava/lang/String;JLjava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; - public final fun automaticDownload (Z)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; - public final fun build ()Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency; - public final fun downloadPage (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; - public final fun downloadPolicy (Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; - public final fun forceAutomaticDownload (Z)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; - public final fun maximumVersion (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; - public final fun maximumVersionExclusive (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; - public final fun required (Z)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; - public final fun url (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; - public final fun verifyPluginId (Z)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; - public final fun verifyVersion (Z)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; +public abstract class org/pnfolder/pnlibrary/api/events/player/PlayerLifecycleEvent : org/pnfolder/pnlibrary/api/events/Event { + public fun (Ljava/util/UUID;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer;)V + public final fun getName ()Ljava/lang/String; + public final fun getPlayer ()Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer; + public final fun getUniqueId ()Ljava/util/UUID; } -public final class org/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Companion { - public final fun builder (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency$Builder; +public abstract class org/pnfolder/pnlibrary/api/expansions/AbstractExpansion : org/pnfolder/pnlibrary/api/expansions/Expansion { + protected fun (Ljava/lang/String;)V + public final fun close ()V + public final fun disable ()V + public final fun enable ()V + public final fun getId ()Ljava/lang/String; + public final fun getState ()Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; + protected fun onClose ()V + protected abstract fun onDisable ()V + protected abstract fun onEnable ()V } -public final class org/pnfolder/pnlibrary/api/dependencies/ManagedProductDependency : org/pnfolder/pnlibrary/api/dependencies/PluginDependency { - public static final field Companion Lorg/pnfolder/pnlibrary/api/dependencies/ManagedProductDependency$Companion; - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/dependencies/VersionConstraint;Ljava/lang/String;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/dependencies/VersionConstraint;Ljava/lang/String;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Ljava/lang/String;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Ljava/lang/String;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public fun getDownloadPolicy ()Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; - public fun getManaged ()Lorg/pnfolder/pnlibrary/api/dependencies/ManagedProductDependency; - public final fun getMinimumVersion ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public final fun getRepositoryName ()Ljava/lang/String; - public final fun getRepositoryOwner ()Ljava/lang/String; - public fun getRequired ()Z - public fun getVersions ()Lorg/pnfolder/pnlibrary/api/dependencies/VersionConstraint; +public abstract interface class org/pnfolder/pnlibrary/api/expansions/Expansion : java/lang/AutoCloseable { + public abstract fun close ()V + public abstract fun disable ()V + public abstract fun enable ()V + public abstract fun getId ()Ljava/lang/String; + public abstract fun getState ()Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; } -public final class org/pnfolder/pnlibrary/api/dependencies/ManagedProductDependency$Companion { +public abstract interface class org/pnfolder/pnlibrary/api/expansions/ExpansionManager { + public abstract fun all ()Ljava/util/List; + public abstract fun get (Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/expansions/Expansion; + public abstract fun get (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/expansions/Expansion; + public abstract fun register (Lorg/pnfolder/pnlibrary/api/expansions/Expansion;)Ljava/lang/AutoCloseable; } -public abstract interface class org/pnfolder/pnlibrary/api/dependencies/PluginDependency { - public fun getAutomaticDownload ()Z - public fun getDownloadPolicy ()Lorg/pnfolder/pnlibrary/api/dependencies/DownloadPolicy; - public fun getExternal ()Lorg/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency; - public fun getForceAutomaticDownload ()Z - public fun getManaged ()Lorg/pnfolder/pnlibrary/api/dependencies/ManagedProductDependency; - public fun getRequired ()Z - public abstract fun getVersions ()Lorg/pnfolder/pnlibrary/api/dependencies/VersionConstraint; +public final class org/pnfolder/pnlibrary/api/expansions/ExpansionState : java/lang/Enum { + public static final field CLOSED Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; + public static final field DISABLED Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; + public static final field ENABLED Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; + public static final field FAILED Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; } -public final class org/pnfolder/pnlibrary/api/dependencies/VersionConstraint { - public fun (Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun accepts (Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)Z - public final fun getMaximumExclusive ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun getMaximumInclusive ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun getMinimum ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; +public final class org/pnfolder/pnlibrary/api/libraries/LibraryScope : java/lang/Enum { + public static final field ISOLATED Lorg/pnfolder/pnlibrary/api/libraries/LibraryScope; + public static final field LIBRARY Lorg/pnfolder/pnlibrary/api/libraries/LibraryScope; + public static final field PLUGIN Lorg/pnfolder/pnlibrary/api/libraries/LibraryScope; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/LibraryScope; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/libraries/LibraryScope; } -public final class org/pnfolder/pnlibrary/api/diagnostics/DebugRequest { - public static final field Companion Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest$Companion; - public fun (Ljava/lang/String;ZZZ)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Z - public final fun component3 ()Z - public final fun component4 ()Z - public final fun copy (Ljava/lang/String;ZZZ)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest;Ljava/lang/String;ZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; +public final class org/pnfolder/pnlibrary/api/libraries/LibrarySource { + public static final field Companion Lorg/pnfolder/pnlibrary/api/libraries/LibrarySource$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/libraries/LibrarySource$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun builder ()Lorg/pnfolder/pnlibrary/api/libraries/LibrarySource$Builder; public fun equals (Ljava/lang/Object;)Z - public final fun getConfigs ()Z - public final fun getLocal ()Z - public final fun getLogs ()Z - public final fun getTarget ()Ljava/lang/String; + public final fun getDescription ()Ljava/lang/String; + public final fun getDirect ()Z + public final fun getName ()Ljava/lang/String; + public final fun getSha256 ()Ljava/lang/String; + public final fun getUrl ()Ljava/lang/String; public fun hashCode ()I - public static final fun parse ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; - public static final fun parse ([Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/diagnostics/DebugRequest$Companion { - public final fun parse ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; - public final fun parse ([Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; - public static synthetic fun parse$default (Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest$Companion;[Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest; -} - -public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration { - public static final field Companion Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Companion; - public synthetic fun (Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder; - public final fun getExcludedPaths ()Ljava/util/List; - public final fun getPath ()Ljava/lang/String; - public final fun getSecretKeyPatterns ()Ljava/util/List; - public final fun getValuePatterns ()Ljava/util/List; +public final class org/pnfolder/pnlibrary/api/libraries/LibrarySource$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/api/libraries/LibrarySource; + public final fun description (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/LibrarySource$Builder; + public final fun link (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/LibrarySource$Builder; + public final fun name (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/LibrarySource$Builder; + public final fun repository (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/LibrarySource$Builder; + public final fun sha256 (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/LibrarySource$Builder; } -public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder { - public final fun build ()Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration; - public final fun exclude (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder; - public final fun redactValueRegex (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder; - public final fun secretKeyRegex (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder; +public final class org/pnfolder/pnlibrary/api/libraries/LibrarySource$Companion { + public final fun builder ()Lorg/pnfolder/pnlibrary/api/libraries/LibrarySource$Builder; } -public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Companion { - public final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration$Builder; +public final class org/pnfolder/pnlibrary/api/libraries/LibraryUsage { + public fun (Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun component3 ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public final fun copy (Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)Lorg/pnfolder/pnlibrary/api/libraries/LibraryUsage; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/libraries/LibraryUsage;Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/libraries/LibraryUsage; + public fun equals (Ljava/lang/Object;)Z + public final fun getLibrary ()Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary; + public final fun getModule ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public final fun getOwner ()Ljava/lang/String; + public final fun getPlugin ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer : org/pnfolder/pnlibrary/api/diagnostics/DiagnosticsContributor { - public static final field Companion Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer$Companion; - public synthetic fun (Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer$Builder; - public fun collect ()Ljava/util/Map; - public fun configurationFiles ()Ljava/util/Collection; - public fun configurations ()Ljava/util/Collection; - public fun getId ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/libraries/ModuleLibraries { + public fun find (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary; + public fun getAvailable ()Ljava/util/List; + public abstract fun getClassLoader ()Ljava/lang/ClassLoader; + public abstract fun getLoaded ()Ljava/util/List; + public fun isLoaded (Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary;)Z + public fun load (Ljava/lang/String;)V + public abstract fun load (Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary;)V + public abstract fun loadClass (Ljava/lang/String;)Ljava/lang/Class; + public abstract fun remove (Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary;)Z +} + +public final class org/pnfolder/pnlibrary/api/libraries/ModuleLibrary { + public static final field CENTRAL Ljava/lang/String; + public static final field Companion Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun appliesTo (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;)Z + public static final fun builder (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder; + public fun equals (Ljava/lang/Object;)Z + public final fun getAllSources ()Ljava/util/List; + public final fun getArtifact ()Ljava/lang/String; + public final fun getClassifier ()Ljava/lang/String; + public final fun getCoordinates ()Ljava/lang/String; + public final fun getDescription ()Ljava/lang/String; + public final fun getGroup ()Ljava/lang/String; + public final fun getIsolated ()Z + public final fun getMavenCentral ()Z + public final fun getPlatforms ()Ljava/util/Set; + public final fun getRequired ()Z + public final fun getScope ()Lorg/pnfolder/pnlibrary/api/libraries/LibraryScope; + public final fun getSources ()Ljava/util/List; + public final fun getTitle ()Ljava/lang/String; + public final fun getVersion ()Ljava/lang/String; + public fun hashCode ()I + public static final fun of (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer$Builder { - public final fun build ()Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer; - public final fun configuration (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer$Builder; - public final fun configuration (Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticConfiguration;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer$Builder; - public final fun snapshot (Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer$Builder; - public final fun value (Ljava/lang/String;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer$Builder; +public final class org/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary; + public final fun classifier (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder; + public final fun description (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder; + public final fun mavenCentral (Z)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder; + public final fun optional ()Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder; + public final fun platforms ([Lorg/pnfolder/pnlibrary/api/platform/PlatformType;)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder; + public final fun scope (Lorg/pnfolder/pnlibrary/api/libraries/LibraryScope;)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder; + public final fun source (Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder; + public final fun source (Lorg/pnfolder/pnlibrary/api/libraries/LibrarySource;)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder; + public final fun title (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder; } -public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer$Companion { - public final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer$Builder; +public final class org/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Companion { + public final fun builder (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary$Builder; + public final fun of (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibrary; } -public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticLevel : java/lang/Enum { - public static final field ERROR Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticLevel; - public static final field INFO Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticLevel; - public static final field WARNING Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticLevel; +public final class org/pnfolder/pnlibrary/api/logging/LogLevel : java/lang/Enum { + public static final field CRITICAL Lorg/pnfolder/pnlibrary/api/logging/LogLevel; + public static final field DEBUG Lorg/pnfolder/pnlibrary/api/logging/LogLevel; + public static final field ERROR Lorg/pnfolder/pnlibrary/api/logging/LogLevel; + public static final field INFO Lorg/pnfolder/pnlibrary/api/logging/LogLevel; + public static final field SUCCESS Lorg/pnfolder/pnlibrary/api/logging/LogLevel; + public static final field WARNING Lorg/pnfolder/pnlibrary/api/logging/LogLevel; public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticLevel; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticLevel; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/LogLevel; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/logging/LogLevel; } -public abstract interface class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticRegistration : java/lang/AutoCloseable { - public abstract fun close ()V - public fun isClosed ()Z +public abstract interface class org/pnfolder/pnlibrary/api/logging/LoggingService { + public abstract fun box (Ljava/lang/Object;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; + public fun box (Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; + public abstract fun logger (Ljava/lang/Object;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/PnLogger; + public abstract fun shutdownBox (Ljava/lang/Object;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; + public fun shutdownBox (Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; } -public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticReport { - public fun (Ljava/nio/file/Path;ZLjava/lang/String;Ljava/lang/String;)V - public final fun component1 ()Ljava/nio/file/Path; - public final fun component2 ()Z - public final fun component3 ()Ljava/lang/String; - public final fun component4 ()Ljava/lang/String; - public final fun copy (Ljava/nio/file/Path;ZLjava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticReport; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticReport;Ljava/nio/file/Path;ZLjava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticReport; - public fun equals (Ljava/lang/Object;)Z - public final fun getEncrypted ()Z - public final fun getLocalFile ()Ljava/nio/file/Path; - public final fun getUploadError ()Ljava/lang/String; - public final fun getUploadedUrl ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/logging/MessageBox { + public abstract fun fail (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; + public static synthetic fun fail$default (Lorg/pnfolder/pnlibrary/api/logging/MessageBox;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; + public fun hide ([Lorg/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; + public abstract fun ok (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; + public abstract fun show ()V + public abstract fun skip (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; + public abstract fun warn (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; } -public abstract interface class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticsContributor { - public abstract fun collect ()Ljava/util/Map; - public fun configurationFiles ()Ljava/util/Collection; - public fun configurations ()Ljava/util/Collection; - public fun getId ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/logging/PnLogger { + public fun critical (Ljava/lang/String;Ljava/lang/Throwable;)V + public fun critical (Ljava/lang/String;Ljava/lang/Throwable;Ljava/util/Map;)V + public static synthetic fun critical$default (Lorg/pnfolder/pnlibrary/api/logging/PnLogger;Ljava/lang/String;Ljava/lang/Throwable;ILjava/lang/Object;)V + public fun debug (Ljava/lang/String;)V + public fun debug (Ljava/lang/String;Ljava/lang/Throwable;)V + public fun debug (Ljava/lang/String;Ljava/util/Map;)V + public fun error (Ljava/lang/String;)V + public fun error (Ljava/lang/String;Ljava/lang/Throwable;)V + public fun error (Ljava/lang/String;Ljava/lang/Throwable;Ljava/util/Map;)V + public fun info (Ljava/lang/String;)V + public fun info (Ljava/lang/String;Ljava/lang/Throwable;)V + public fun info (Ljava/lang/String;Ljava/util/Map;)V + public abstract fun log (Lorg/pnfolder/pnlibrary/api/logging/LogLevel;Ljava/lang/String;Ljava/lang/Throwable;Ljava/util/Map;)V + public static synthetic fun log$default (Lorg/pnfolder/pnlibrary/api/logging/PnLogger;Lorg/pnfolder/pnlibrary/api/logging/LogLevel;Ljava/lang/String;Ljava/lang/Throwable;Ljava/util/Map;ILjava/lang/Object;)V + public fun record (Lorg/pnfolder/pnlibrary/api/logging/LogLevel;Ljava/lang/String;Ljava/lang/Throwable;)V + public static synthetic fun record$default (Lorg/pnfolder/pnlibrary/api/logging/PnLogger;Lorg/pnfolder/pnlibrary/api/logging/LogLevel;Ljava/lang/String;Ljava/lang/Throwable;ILjava/lang/Object;)V + public fun success (Ljava/lang/String;)V + public fun success (Ljava/lang/String;Ljava/util/Map;)V + public fun warning (Ljava/lang/String;)V + public fun warning (Ljava/lang/String;Ljava/lang/Throwable;)V + public fun warning (Ljava/lang/String;Ljava/lang/Throwable;Ljava/util/Map;)V + public fun warning (Ljava/lang/String;Ljava/util/Map;)V } -public abstract interface class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService { - public static final field API_VERSION I - public static final field Companion Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService$Companion; - public fun clearPlugin (Ljava/lang/String;)V - public abstract fun clearStatus (Ljava/lang/String;Ljava/lang/String;)V - public fun getApiVersion ()I - public abstract fun record (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticLevel;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;Ljava/util/Map;)V - public static synthetic fun record$default (Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticLevel;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;Ljava/util/Map;ILjava/lang/Object;)V - public fun register (Ljava/lang/String;Ljava/nio/file/Path;Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticsContributor;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticRegistration; - public abstract fun register (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticsContributor;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticRegistration; - public abstract fun status (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;)V - public static synthetic fun status$default (Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)V +public abstract interface class org/pnfolder/pnlibrary/api/metrics/MetricsController : java/lang/AutoCloseable { + public abstract fun close ()V + public abstract fun configure (Ljava/util/function/Consumer;)V + public abstract fun disable ()V + public abstract fun enable ()V + public fun errorReporterOrNull ()Lorg/pnfolder/pnlibrary/api/metrics/error/ErrorReporter; + public fun getProviderConfigurations ()Ljava/util/List; + public fun isClosed ()Z + public abstract fun isEnabled ()Z + public abstract fun update (Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProviderConfiguration;)V } -public final class org/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService$Companion { - public static final field API_VERSION I +public abstract interface class org/pnfolder/pnlibrary/api/metrics/MetricsService { + public fun getProviders ()Ljava/util/Set; + public abstract fun open (Ljava/lang/Object;Ljava/util/Collection;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; + public fun openErrorReporter (Ljava/lang/Object;Ljava/util/Collection;)Lorg/pnfolder/pnlibrary/api/metrics/error/ErrorReporter; } -public final class org/pnfolder/pnlibrary/api/downloads/DirectDownloadSource { - public static final field Companion Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Companion; - public synthetic fun (Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun builder ()Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; - public final fun getMaximumJava ()Ljava/lang/Integer; - public final fun getMinimumJava ()I - public final fun getPlatform ()Lorg/pnfolder/pnlibrary/api/platform/PlatformType; - public final fun getSha256 ()Ljava/lang/String; - public final fun getSize ()Ljava/lang/Long; - public final fun getUri ()Ljava/net/URI; - public final fun supports (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;I)Z +public abstract interface class org/pnfolder/pnlibrary/api/metrics/PluginMetrics : java/lang/AutoCloseable { + public abstract fun advancedBarChart (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; + public abstract fun advancedPie (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; + public abstract fun close ()V + public abstract fun drilldownPie (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; + public fun getErrorReporter ()Lorg/pnfolder/pnlibrary/api/metrics/error/ErrorReporter; + public abstract fun getProviders ()Ljava/util/Set; + public abstract fun multiLineChart (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; + public abstract fun simpleBarChart (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; + public abstract fun simplePie (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; + public abstract fun singleLineChart (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; + public fun start ()V } -public final class org/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder { - public final fun build ()Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource; - public final fun integrity (JLjava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; - public final fun java (I)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; - public final fun java (ILjava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; - public static synthetic fun java$default (Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder;ILjava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; - public final fun platform (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; - public final fun url (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; +public abstract interface class org/pnfolder/pnlibrary/api/metrics/error/ErrorReporter : java/lang/AutoCloseable { + public fun capture (Ljava/lang/Throwable;Ljava/lang/String;ZLjava/util/Map;)V + public abstract fun capture (Lorg/pnfolder/pnlibrary/api/metrics/error/TelemetryError;)V + public static synthetic fun capture$default (Lorg/pnfolder/pnlibrary/api/metrics/error/ErrorReporter;Ljava/lang/Throwable;Ljava/lang/String;ZLjava/util/Map;ILjava/lang/Object;)V + public abstract fun close ()V + public fun installGlobalHandler ()V } -public final class org/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Companion { - public final fun builder ()Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource$Builder; +public final class org/pnfolder/pnlibrary/api/metrics/error/TelemetryError { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZLjava/lang/String;Ljava/util/Map;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZLjava/lang/String;Ljava/util/Map;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/util/List; + public final fun component4 ()Z + public final fun component5 ()Ljava/lang/String; + public final fun component6 ()Ljava/util/Map; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZLjava/lang/String;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/metrics/error/TelemetryError; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/metrics/error/TelemetryError;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZLjava/lang/String;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/metrics/error/TelemetryError; + public fun equals (Ljava/lang/Object;)Z + public final fun getAttributes ()Ljava/util/Map; + public final fun getHandled ()Z + public final fun getMessage ()Ljava/lang/String; + public final fun getOperation ()Ljava/lang/String; + public final fun getStackTrace ()Ljava/util/List; + public final fun getType ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/downloads/DownloadDestination : java/lang/Enum { - public static final field CACHE Lorg/pnfolder/pnlibrary/api/downloads/DownloadDestination; - public static final field DATA_FOLDER Lorg/pnfolder/pnlibrary/api/downloads/DownloadDestination; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/DownloadDestination; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/downloads/DownloadDestination; +public final class org/pnfolder/pnlibrary/api/metrics/provider/MetricsBuilder { + public fun ()V + public final fun bStats (I)Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsBuilder; + public final fun bStats (Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsBuilder; + public final fun bStats (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;I)Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsBuilder; + public final fun build ()Ljava/util/List; + public final fun charts (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsBuilder; + public final fun configure (Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics;)V + public final fun enabled (Z)Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsBuilder; + public final fun fastStats (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsBuilder; + public final fun getEnabled ()Z } -public abstract interface class org/pnfolder/pnlibrary/api/downloads/DownloadRegistration : java/lang/AutoCloseable { - public abstract fun close ()V - public abstract fun downloadNow ()Ljava/util/concurrent/CompletionStage; - public fun isClosed ()Z - public abstract fun snapshots ()Ljava/util/List; +public abstract class org/pnfolder/pnlibrary/api/metrics/provider/MetricsCredentials : java/lang/AutoCloseable { + public fun close ()V + public abstract fun getProvider ()Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider; + public abstract fun useValue (Lkotlin/jvm/functions/Function1;)Ljava/lang/Object; } -public final class org/pnfolder/pnlibrary/api/downloads/DownloadSnapshot { - public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/downloads/DownloadState;Ljava/lang/String;)V - public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/downloads/DownloadState;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; - public final fun component3 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/downloads/DownloadState;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/DownloadSnapshot; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/downloads/DownloadSnapshot;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/downloads/DownloadState;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/downloads/DownloadSnapshot; +public final class org/pnfolder/pnlibrary/api/metrics/provider/MetricsCredentials$BStats : org/pnfolder/pnlibrary/api/metrics/provider/MetricsCredentials { + public fun (I)V + public final fun component1 ()I + public final fun copy (I)Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsCredentials$BStats; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsCredentials$BStats;IILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsCredentials$BStats; public fun equals (Ljava/lang/Object;)Z - public final fun getKey ()Ljava/lang/String; - public final fun getMessage ()Ljava/lang/String; - public final fun getState ()Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; + public final fun getProjectId ()I + public fun getProvider ()Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider; public fun hashCode ()I public fun toString ()Ljava/lang/String; + public fun useValue (Lkotlin/jvm/functions/Function1;)Ljava/lang/Object; } -public final class org/pnfolder/pnlibrary/api/downloads/DownloadState : java/lang/Enum { - public static final field BLOCKED Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; - public static final field CLOSED Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; - public static final field CURRENT Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; - public static final field DECLARED Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; - public static final field DOWNLOADING Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; - public static final field FAILED Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; - public static final field STAGED Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; +public final class org/pnfolder/pnlibrary/api/metrics/provider/MetricsCredentials$FastStats : org/pnfolder/pnlibrary/api/metrics/provider/MetricsCredentials { + public fun ([C)V + public fun close ()V + public fun getProvider ()Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider; + public fun toString ()Ljava/lang/String; + public final fun useToken (Lkotlin/jvm/functions/Function1;)Ljava/lang/Object; + public fun useValue (Lkotlin/jvm/functions/Function1;)Ljava/lang/Object; +} + +public final class org/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider : java/lang/Enum { + public static final field BSTATS Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider; + public static final field FASTSTATS Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider; public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/downloads/DownloadState; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider; } -public final class org/pnfolder/pnlibrary/api/downloads/FileDownload { - public static final field Companion Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Companion; - public final fun getAutomatic ()Z - public final fun getDestination ()Lorg/pnfolder/pnlibrary/api/downloads/DownloadDestination; - public final fun getForceAutomaticDownload ()Z - public final fun getKey ()Ljava/lang/String; - public final fun getRelativePath ()Ljava/lang/String; - public final fun getRequired ()Z - public final fun getSource ()Lorg/pnfolder/pnlibrary/api/downloads/DirectDownloadSource; +public final class org/pnfolder/pnlibrary/api/metrics/provider/MetricsProviderConfiguration { + public fun (Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider;ZLjava/lang/Integer;Ljava/util/Map;Ljava/lang/String;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider;ZLjava/lang/Integer;Ljava/util/Map;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider; + public final fun component2 ()Z + public final fun component3 ()Ljava/lang/Integer; + public final fun component4 ()Ljava/util/Map; + public final fun component5 ()Ljava/lang/String; + public final fun copy (Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider;ZLjava/lang/Integer;Ljava/util/Map;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProviderConfiguration; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProviderConfiguration;Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider;ZLjava/lang/Integer;Ljava/util/Map;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProviderConfiguration; + public final fun credentials ()Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsCredentials; + public fun equals (Ljava/lang/Object;)Z + public final fun forPlatform (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;)Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProviderConfiguration; + public final fun getEnabled ()Z + public final fun getPlatformProjectIds ()Ljava/util/Map; + public final fun getProjectId ()Ljava/lang/Integer; + public final fun getProvider ()Lorg/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider; + public final fun getToken ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/downloads/FileDownload$Builder { - public final fun automaticDownload (Z)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; - public final fun destination (Lorg/pnfolder/pnlibrary/api/downloads/DownloadDestination;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; - public final fun forceAutomaticDownload (Z)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; - public final fun integrity (JLjava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; - public final fun java (I)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; - public final fun java (ILjava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; - public static synthetic fun java$default (Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder;ILjava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; - public final fun platform (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; - public final fun required (Z)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; - public final fun url (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownload$Builder; +public abstract interface class org/pnfolder/pnlibrary/api/network/NetworkPlayer : org/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer { + public abstract fun disconnect (Ljava/lang/String;)V + public abstract fun getAddress ()Ljava/net/InetSocketAddress; + public abstract fun getCurrentServer ()Lorg/pnfolder/pnlibrary/api/network/NetworkServer; + public abstract fun getPing ()J } -public final class org/pnfolder/pnlibrary/api/downloads/FileDownload$Companion { +public abstract interface class org/pnfolder/pnlibrary/api/network/NetworkProxy { + public abstract fun broadcast (Ljava/lang/String;)V + public abstract fun getName ()Ljava/lang/String; + public abstract fun getPlayerCount ()I + public abstract fun getPlayers ()Ljava/util/Collection; + public abstract fun getServers ()Ljava/util/List; + public abstract fun getVersion ()Ljava/lang/String; + public abstract fun player (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/network/NetworkPlayer; + public abstract fun player (Ljava/util/UUID;)Lorg/pnfolder/pnlibrary/api/network/NetworkPlayer; + public abstract fun registerChannel (Ljava/lang/String;)V + public abstract fun server (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/network/NetworkServer; + public abstract fun stop (Ljava/lang/String;)V + public static synthetic fun stop$default (Lorg/pnfolder/pnlibrary/api/network/NetworkProxy;Ljava/lang/String;ILjava/lang/Object;)V + public abstract fun unregisterChannel (Ljava/lang/String;)V +} + +public abstract interface class org/pnfolder/pnlibrary/api/network/NetworkServer { + public abstract fun broadcast (Ljava/lang/String;)V + public fun canAccess (Lorg/pnfolder/pnlibrary/api/network/NetworkPlayer;)Z + public abstract fun getAddress ()Ljava/net/InetSocketAddress; + public fun getMotd ()Ljava/lang/String; + public abstract fun getName ()Ljava/lang/String; + public abstract fun getOnlinePlayers ()I + public abstract fun getPing ()Ljava/lang/Long; + public fun isRestricted ()Z + public abstract fun send (Ljava/lang/String;[B)Z } -public final class org/pnfolder/pnlibrary/api/downloads/FileDownloads { - public static final field Companion Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads$Companion; - public synthetic fun (Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun builder ()Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads$Builder; - public final fun getDataDirectory ()Ljava/nio/file/Path; - public final fun getFiles ()Ljava/util/List; +public abstract interface class org/pnfolder/pnlibrary/api/observability/ObservabilityService : java/lang/AutoCloseable { + public fun capture (Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/observability/observation/Observation; + public abstract fun createReport (Lorg/pnfolder/pnlibrary/api/observability/report/ObservabilityReportRequest;)Lorg/pnfolder/pnlibrary/api/observability/report/ObservabilityReport; + public static synthetic fun createReport$default (Lorg/pnfolder/pnlibrary/api/observability/ObservabilityService;Lorg/pnfolder/pnlibrary/api/observability/report/ObservabilityReportRequest;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/report/ObservabilityReport; + public fun failure (Ljava/lang/Throwable;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/observability/observation/Observation; + public static synthetic fun failure$default (Lorg/pnfolder/pnlibrary/api/observability/ObservabilityService;Ljava/lang/Throwable;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/observation/Observation; + public abstract fun recent (Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationQuery;)Ljava/util/List; + public static synthetic fun recent$default (Lorg/pnfolder/pnlibrary/api/observability/ObservabilityService;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationQuery;ILjava/lang/Object;)Ljava/util/List; + public abstract fun record (Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationRequest;)Lorg/pnfolder/pnlibrary/api/observability/observation/Observation; + public abstract fun status (Lorg/pnfolder/pnlibrary/api/observability/report/ComponentStatus;)Lorg/pnfolder/pnlibrary/api/observability/report/ComponentStatus; +} + +public final class org/pnfolder/pnlibrary/api/observability/observation/Observation { + public static final field Companion Lorg/pnfolder/pnlibrary/api/observability/observation/Observation$Companion; + public fun (Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()J + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Ljava/lang/String; + public final fun component5 ()Ljava/lang/String; + public final fun component6 ()Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; + public final fun component7 ()Ljava/util/Map; + public final fun component8 ()Ljava/lang/String; + public final fun component9 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/observability/observation/Observation; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/observability/observation/Observation;Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/observation/Observation; + public fun equals (Ljava/lang/Object;)Z + public static final fun from (Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationRequest;)Lorg/pnfolder/pnlibrary/api/observability/observation/Observation; + public static final fun from (Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationRequest;J)Lorg/pnfolder/pnlibrary/api/observability/observation/Observation; + public final fun getData ()Ljava/util/Map; + public final fun getErrorMessage ()Ljava/lang/String; + public final fun getErrorType ()Ljava/lang/String; + public final fun getId ()Ljava/lang/String; + public final fun getLevel ()Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; + public final fun getMessage ()Ljava/lang/String; + public final fun getPlugin ()Ljava/lang/String; + public final fun getSource ()Ljava/lang/String; + public final fun getTimestamp ()J + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/downloads/FileDownloads$Builder { - public final fun build ()Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads; - public final fun dataDirectory (Ljava/nio/file/Path;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads$Builder; - public final fun file (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads$Builder; +public final class org/pnfolder/pnlibrary/api/observability/observation/Observation$Companion { + public final fun from (Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationRequest;)Lorg/pnfolder/pnlibrary/api/observability/observation/Observation; + public final fun from (Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationRequest;J)Lorg/pnfolder/pnlibrary/api/observability/observation/Observation; + public static synthetic fun from$default (Lorg/pnfolder/pnlibrary/api/observability/observation/Observation$Companion;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationRequest;JILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/observation/Observation; } -public final class org/pnfolder/pnlibrary/api/downloads/FileDownloads$Companion { - public final fun builder ()Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads$Builder; +public final class org/pnfolder/pnlibrary/api/observability/observation/ObservationKeys { + public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationKeys; + public static final field KEEP_FOR_MS Ljava/lang/String; + public static final field KEEP_UNTIL_MS Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/events/DispatchMode : java/lang/Enum { - public static final field ASYNC Lorg/pnfolder/pnlibrary/api/events/DispatchMode; - public static final field SYNC Lorg/pnfolder/pnlibrary/api/events/DispatchMode; +public final class org/pnfolder/pnlibrary/api/observability/observation/ObservationLevel : java/lang/Enum { + public static final field CRITICAL Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; + public static final field ERROR Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; + public static final field INFO Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; + public static final field NOTICE Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; + public static final field TRACE Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; + public static final field WARNING Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/events/DispatchMode; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/events/DispatchMode; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; } -public abstract class org/pnfolder/pnlibrary/api/events/Event { +public final class org/pnfolder/pnlibrary/api/observability/observation/ObservationQuery { public fun ()V - public final fun bindDispatch (Lorg/pnfolder/pnlibrary/api/events/DispatchMode;Ljava/lang/Thread;)V - public final fun callEvent ()Z - public final fun callEventAsync ()Ljava/util/concurrent/CompletionStage; - public final fun callEventAsync (Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletionStage; - public static synthetic fun callEventAsync$default (Lorg/pnfolder/pnlibrary/api/events/Event;Ljava/util/concurrent/Executor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; - public final fun getDenyReason ()Lnet/kyori/adventure/text/Component; - public final fun getDispatchMode ()Lorg/pnfolder/pnlibrary/api/events/DispatchMode; - public final fun getDispatchThread ()Ljava/lang/Thread; - public fun getEventName ()Ljava/lang/String; - public final fun isAllowed ()Z - public final fun isAsync ()Z + public fun (ILjava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel;Ljava/lang/Long;Ljava/lang/Long;)V + public synthetic fun (ILjava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel;Ljava/lang/Long;Ljava/lang/Long;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()I + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; + public final fun component4 ()Ljava/lang/Long; + public final fun component5 ()Ljava/lang/Long; + public final fun copy (ILjava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel;Ljava/lang/Long;Ljava/lang/Long;)Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationQuery; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationQuery;ILjava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel;Ljava/lang/Long;Ljava/lang/Long;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationQuery; + public fun equals (Ljava/lang/Object;)Z + public final fun getLimit ()I + public final fun getMinimumLevel ()Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; + public final fun getPlugin ()Ljava/lang/String; + public final fun getSince ()Ljava/lang/Long; + public final fun getUntil ()Ljava/lang/Long; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/events/EventDay { - public fun (Ljava/time/LocalDate;Ljava/lang/String;JJ)V - public final fun component1 ()Ljava/time/LocalDate; +public final class org/pnfolder/pnlibrary/api/observability/observation/ObservationRequest { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel;Ljava/util/Map;Ljava/util/List;Ljava/lang/Throwable;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel;Ljava/util/Map;Ljava/util/List;Ljava/lang/Throwable;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; public final fun component2 ()Ljava/lang/String; - public final fun component3 ()J - public final fun component4 ()J - public final fun copy (Ljava/time/LocalDate;Ljava/lang/String;JJ)Lorg/pnfolder/pnlibrary/api/events/EventDay; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/events/EventDay;Ljava/time/LocalDate;Ljava/lang/String;JJILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/events/EventDay; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; + public final fun component5 ()Ljava/util/Map; + public final fun component6 ()Ljava/util/List; + public final fun component7 ()Ljava/lang/Throwable; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel;Ljava/util/Map;Ljava/util/List;Ljava/lang/Throwable;)Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationRequest; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationRequest;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel;Ljava/util/Map;Ljava/util/List;Ljava/lang/Throwable;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationRequest; public fun equals (Ljava/lang/Object;)Z - public final fun getCalls ()J - public final fun getDate ()Ljava/time/LocalDate; - public final fun getDenied ()J - public final fun getEventType ()Ljava/lang/String; + public final fun getData ()Ljava/util/Map; + public final fun getError ()Ljava/lang/Throwable; + public final fun getFiles ()Ljava/util/List; + public final fun getLevel ()Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel; + public final fun getMessage ()Ljava/lang/String; + public final fun getPlugin ()Ljava/lang/String; + public final fun getSource ()Ljava/lang/String; public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public abstract interface annotation class org/pnfolder/pnlibrary/api/events/EventDescription : java/lang/annotation/Annotation { - public abstract fun purpose ()Ljava/lang/String; - public abstract fun usage ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/observability/observation/ObservationScope { + public static final field MAX_KEEP_DAYS J + public final fun data ([Lkotlin/Pair;)Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationScope; + public final fun files ([Ljava/nio/file/Path;)Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationScope; + public final fun keepFor (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationScope; + public final fun level (Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationLevel;)Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationScope; + public final fun message (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationScope; + public final fun plugin (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationScope; + public final fun source (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/observability/observation/ObservationScope; } -public abstract interface annotation class org/pnfolder/pnlibrary/api/events/EventHandler : java/lang/annotation/Annotation { - public abstract fun ignoreDenied ()Z - public abstract fun priority ()I +public final class org/pnfolder/pnlibrary/api/observability/report/ComponentStatus { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;J)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;JILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Ljava/lang/String; + public final fun component5 ()Ljava/util/Map; + public final fun component6 ()J + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;J)Lorg/pnfolder/pnlibrary/api/observability/report/ComponentStatus; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/observability/report/ComponentStatus;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;JILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/report/ComponentStatus; + public fun equals (Ljava/lang/Object;)Z + public final fun getComponent ()Ljava/lang/String; + public final fun getData ()Ljava/util/Map; + public final fun getDetail ()Ljava/lang/String; + public final fun getPlugin ()Ljava/lang/String; + public final fun getState ()Ljava/lang/String; + public final fun getUpdatedAt ()J + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/events/EventHour { - public fun (Ljava/time/LocalDateTime;Ljava/lang/String;JJ)V - public final fun component1 ()Ljava/time/LocalDateTime; - public final fun component2 ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/observability/report/ObservabilityReport { + public fun (Ljava/lang/String;Ljava/nio/file/Path;J)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/nio/file/Path; public final fun component3 ()J - public final fun component4 ()J - public final fun copy (Ljava/time/LocalDateTime;Ljava/lang/String;JJ)Lorg/pnfolder/pnlibrary/api/events/EventHour; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/events/EventHour;Ljava/time/LocalDateTime;Ljava/lang/String;JJILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/events/EventHour; + public final fun copy (Ljava/lang/String;Ljava/nio/file/Path;J)Lorg/pnfolder/pnlibrary/api/observability/report/ObservabilityReport; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/observability/report/ObservabilityReport;Ljava/lang/String;Ljava/nio/file/Path;JILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/report/ObservabilityReport; public fun equals (Ljava/lang/Object;)Z - public final fun getCalls ()J - public final fun getDenied ()J - public final fun getEventType ()Ljava/lang/String; - public final fun getHour ()Ljava/time/LocalDateTime; + public final fun getCreatedAt ()J + public final fun getFile ()Ljava/nio/file/Path; + public final fun getId ()Ljava/lang/String; public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/events/EventInfo { - public fun (Ljava/lang/String;IJJLjava/time/Instant;)V - public synthetic fun (Ljava/lang/String;IJJLjava/time/Instant;ILkotlin/jvm/internal/DefaultConstructorMarker;)V +public final class org/pnfolder/pnlibrary/api/observability/report/ObservabilityReportRequest { + public fun ()V + public fun (Ljava/lang/String;ZZ)V + public synthetic fun (Ljava/lang/String;ZZILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Ljava/lang/String; - public final fun component2 ()I - public final fun component3 ()J - public final fun component4 ()J - public final fun component5 ()Ljava/time/Instant; - public final fun copy (Ljava/lang/String;IJJLjava/time/Instant;)Lorg/pnfolder/pnlibrary/api/events/EventInfo; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/events/EventInfo;Ljava/lang/String;IJJLjava/time/Instant;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/events/EventInfo; + public final fun component2 ()Z + public final fun component3 ()Z + public final fun copy (Ljava/lang/String;ZZ)Lorg/pnfolder/pnlibrary/api/observability/report/ObservabilityReportRequest; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/observability/report/ObservabilityReportRequest;Ljava/lang/String;ZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/report/ObservabilityReportRequest; public fun equals (Ljava/lang/Object;)Z - public final fun getCalls ()J - public final fun getDenied ()J - public final fun getEventType ()Ljava/lang/String; - public final fun getLastCalledAt ()Ljava/time/Instant; - public final fun getListeners ()I + public final fun getIncludeConfigurations ()Z + public final fun getIncludeLogs ()Z + public final fun getTarget ()Ljava/lang/String; public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/events/EventInspector { - public fun asyncQueued ()I - public abstract fun clearTraces ()V - public abstract fun disableTracing (Ljava/lang/Class;)V - public abstract fun enableTracing (Ljava/lang/Class;I)V - public static synthetic fun enableTracing$default (Lorg/pnfolder/pnlibrary/api/events/EventInspector;Ljava/lang/Class;IILjava/lang/Object;)V - public fun event (Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/events/EventInfo; - public abstract fun eventType (Ljava/lang/String;)Ljava/lang/Class; - public abstract fun events ()Ljava/util/List; - public fun exportHistory (Z)Ljava/nio/file/Path; - public static synthetic fun exportHistory$default (Lorg/pnfolder/pnlibrary/api/events/EventInspector;ZILjava/lang/Object;)Ljava/nio/file/Path; - public abstract fun getHistoryDays ()I - public abstract fun history (Ljava/lang/String;)Ljava/util/List; - public static synthetic fun history$default (Lorg/pnfolder/pnlibrary/api/events/EventInspector;Ljava/lang/String;ILjava/lang/Object;)Ljava/util/List; - public fun hourly (Ljava/lang/String;)Ljava/util/List; - public static synthetic fun hourly$default (Lorg/pnfolder/pnlibrary/api/events/EventInspector;Ljava/lang/String;ILjava/lang/Object;)Ljava/util/List; - public fun listenerCount (Ljava/lang/Class;)I - public abstract fun listeners ()Ljava/util/List; - public abstract fun listeners (Ljava/lang/Class;)Ljava/util/List; - public fun listeners (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)Ljava/util/List; - public static synthetic fun listeners$default (Lorg/pnfolder/pnlibrary/api/events/EventInspector;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;ILjava/lang/Object;)Ljava/util/List; - public fun plugins (Ljava/lang/Class;)Ljava/util/List; - public abstract fun tracedEvents ()Ljava/util/List; - public abstract fun traces ()Ljava/util/List; +public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder { + public abstract fun access (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public abstract fun access (Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public abstract fun cache (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public fun defaultFormat (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public abstract fun fallback (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public abstract fun format (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderFormatter;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public abstract fun publish (Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderPublication;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public fun publishToPlaceholderApi ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public fun publishToPlaceholderApi (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public fun publishToPlaceholderApi (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public abstract fun resolve (Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderResolver;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public abstract fun resolveAsync (Lorg/pnfolder/pnlibrary/api/placeholders/model/AsyncPlaceholderResolver;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public abstract fun update (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderUpdater;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public abstract fun updateAccess (Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; } -public final class org/pnfolder/pnlibrary/api/events/EventListenerBuilder { - public final fun ignoreDenied ()Lorg/pnfolder/pnlibrary/api/events/EventListenerBuilder; - public final fun listen (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/EventSubscription; - public final fun priority (I)Lorg/pnfolder/pnlibrary/api/events/EventListenerBuilder; +public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderFormatter { + public abstract fun format (Ljava/lang/Object;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderRequest;)Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/events/EventListenerBuilderKt { - public static final fun on (Lorg/pnfolder/pnlibrary/api/events/EventScope;Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/events/EventListenerBuilder; +public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderProvider { + public abstract fun getPluginId ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public abstract fun keys ()Ljava/util/Set; + public abstract fun resolve (Ljava/lang/String;Ljava/util/UUID;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun resolve$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderProvider;Ljava/lang/String;Ljava/util/UUID;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; } -public abstract interface class org/pnfolder/pnlibrary/api/events/EventListenerRegistration : java/lang/AutoCloseable { - public abstract fun close ()V - public abstract fun getHandlerCount ()I - public abstract fun getListener ()Lorg/pnfolder/pnlibrary/api/events/Listener; - public abstract fun isClosed ()Z +public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderRegistration : java/lang/AutoCloseable { + public abstract fun disable ()V + public abstract fun enable ()V + public abstract fun getKey ()Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey; + public abstract fun getOwner ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public abstract fun getPublications ()Ljava/util/List; + public abstract fun invalidateCache ()V + public fun isClosed ()Z + public abstract fun isEnabled ()Z } -public final class org/pnfolder/pnlibrary/api/events/EventPriority { - public static final field HIGH I - public static final field HIGHEST I - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/events/EventPriority; - public static final field LOW I - public static final field LOWEST I - public static final field MONITOR I - public static final field NORMAL I +public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderService : java/lang/AutoCloseable { + public abstract fun adapters ()Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderAdapterRegistry; + public abstract fun contains (Ljava/lang/String;)Z + public abstract fun formatter (Ljava/lang/String;Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderFormatter;)V + public abstract fun provider (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderProvider; + public fun register (Ljava/lang/String;Ljava/lang/Class;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderRegistration; + public abstract fun register (Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderRegistration; + public abstract fun render (Ljava/lang/String;Ljava/util/UUID;Ljava/util/Map;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun render$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService;Ljava/lang/String;Ljava/util/UUID;Ljava/util/Map;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public abstract fun resolve (Ljava/lang/String;Ljava/util/UUID;Ljava/util/Map;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun resolve$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService;Ljava/lang/String;Ljava/util/UUID;Ljava/util/Map;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public abstract fun update (Ljava/lang/String;Ljava/lang/String;Ljava/util/UUID;Ljava/util/Map;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun update$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService;Ljava/lang/String;Ljava/lang/String;Ljava/util/UUID;Ljava/util/Map;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; } -public abstract interface class org/pnfolder/pnlibrary/api/events/EventScope : java/lang/AutoCloseable { - public abstract fun callEvent (Lorg/pnfolder/pnlibrary/api/events/Event;)Lorg/pnfolder/pnlibrary/api/events/Event; - public abstract fun close ()V - public abstract fun getPluginId ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public abstract fun isClosed ()Z - public abstract fun register (Lorg/pnfolder/pnlibrary/api/events/Listener;)Lorg/pnfolder/pnlibrary/api/events/EventListenerRegistration; - public fun subscribe (Ljava/lang/Class;ILjava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/EventSubscription; - public abstract fun subscribe (Ljava/lang/Class;IZLjava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/EventSubscription; - public fun subscribe (Ljava/lang/Class;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/EventSubscription; +public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderUpdater { + public abstract fun update (Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderRequest;Ljava/lang/String;)Ljava/lang/Object; } -public abstract interface class org/pnfolder/pnlibrary/api/events/EventService : java/lang/AutoCloseable { - public abstract fun callEvent (Lorg/pnfolder/pnlibrary/api/events/Event;)Lorg/pnfolder/pnlibrary/api/events/Event; - public abstract fun callEventAsync (Lorg/pnfolder/pnlibrary/api/events/Event;)Ljava/util/concurrent/CompletionStage; - public abstract fun callEventAsync (Lorg/pnfolder/pnlibrary/api/events/Event;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletionStage; - public abstract fun close ()V - public abstract fun getInspector ()Lorg/pnfolder/pnlibrary/api/events/EventInspector; - public fun register (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/events/Listener;)Lorg/pnfolder/pnlibrary/api/events/EventListenerRegistration; - public abstract fun scope (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Lorg/pnfolder/pnlibrary/api/events/EventScope; - public abstract fun scope (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)Lorg/pnfolder/pnlibrary/api/events/EventScope; - public fun subscribe (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/lang/Class;IZLjava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/EventSubscription; - public fun subscribe (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/lang/Class;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/events/EventSubscription; - public abstract fun unregisterAll (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)V +public abstract interface class org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapter { + public static final field Companion Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapter$Companion; + public static final field WAIT_MILLIS_KEY Ljava/lang/String; + public abstract fun getCapabilities ()Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterCapabilities; + public abstract fun getId ()Ljava/lang/String; + public abstract fun getState ()Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState; + public abstract fun publish (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderResolver;Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderPublication;)Lorg/pnfolder/pnlibrary/api/placeholders/model/ExternalPlaceholderRegistration; + public fun render (Ljava/util/UUID;Ljava/lang/String;)Ljava/lang/String; + public fun resolve (Ljava/util/UUID;Ljava/lang/String;)Ljava/lang/Object; } -public abstract interface class org/pnfolder/pnlibrary/api/events/EventSubscription : java/lang/AutoCloseable { - public abstract fun close ()V - public abstract fun isClosed ()Z +public final class org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapter$Companion { + public static final field WAIT_MILLIS_KEY Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/events/EventTrace { - public fun (Ljava/lang/String;ZLjava/lang/String;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/events/DispatchMode;Ljava/lang/String;Ljava/time/Instant;)V - public synthetic fun (Ljava/lang/String;ZLjava/lang/String;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/events/DispatchMode;Ljava/lang/String;Ljava/time/Instant;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterCapabilities { + public fun ()V + public fun (ZZZZZ)V + public synthetic fun (ZZZZZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Z public final fun component2 ()Z - public final fun component3 ()Ljava/lang/String; - public final fun component4 ()Ljava/util/List; - public final fun component5 ()Lorg/pnfolder/pnlibrary/api/events/DispatchMode; - public final fun component6 ()Ljava/lang/String; - public final fun component7 ()Ljava/time/Instant; - public final fun copy (Ljava/lang/String;ZLjava/lang/String;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/events/DispatchMode;Ljava/lang/String;Ljava/time/Instant;)Lorg/pnfolder/pnlibrary/api/events/EventTrace; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/events/EventTrace;Ljava/lang/String;ZLjava/lang/String;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/events/DispatchMode;Ljava/lang/String;Ljava/time/Instant;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/events/EventTrace; - public fun equals (Ljava/lang/Object;)Z - public final fun getAllowed ()Z - public final fun getAt ()Ljava/time/Instant; - public final fun getEventName ()Ljava/lang/String; - public final fun getMode ()Lorg/pnfolder/pnlibrary/api/events/DispatchMode; - public final fun getResult ()Ljava/lang/String; - public final fun getSteps ()Ljava/util/List; - public final fun getThread ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/events/EventTrace$Step { - public fun (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;IZZJLjava/lang/String;Ljava/lang/String;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; - public final fun component3 ()I + public final fun component3 ()Z public final fun component4 ()Z public final fun component5 ()Z - public final fun component6 ()J - public final fun component7 ()Ljava/lang/String; - public final fun component8 ()Ljava/lang/String; - public final fun copy (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;IZZJLjava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/events/EventTrace$Step; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/events/EventTrace$Step;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;IZZJLjava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/events/EventTrace$Step; + public final fun copy (ZZZZZ)Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterCapabilities; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterCapabilities;ZZZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterCapabilities; public fun equals (Ljava/lang/Object;)Z - public final fun getChangedResult ()Z - public final fun getFailed ()Z - public final fun getModule ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; - public final fun getNanos ()J - public final fun getPlugin ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public final fun getPriority ()I - public final fun getResultAfter ()Ljava/lang/String; - public final fun getResultBefore ()Ljava/lang/String; - public final fun getSkipped ()Z + public final fun getAsynchronous ()Z + public final fun getComponents ()Z + public final fun getOfflinePlayers ()Z + public final fun getParameters ()Z + public final fun getPlayers ()Z public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public abstract interface annotation class org/pnfolder/pnlibrary/api/events/InternalEventApi : java/lang/annotation/Annotation { -} - -public abstract interface class org/pnfolder/pnlibrary/api/events/Listener { +public final class org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState : java/lang/Enum { + public static final field AVAILABLE Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState; + public static final field CLOSED Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState; + public static final field FAILED Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState; + public static final field REGISTERED Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState; + public static final field UNAVAILABLE Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState; } -public final class org/pnfolder/pnlibrary/api/events/ListenerInfo { - public fun (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;IZLjava/lang/String;JJ)V - public fun (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;IZLjava/lang/String;JJJJ)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;IZLjava/lang/String;JJJJILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public final fun component10 ()J - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; - public final fun component3 ()Ljava/lang/String; - public final fun component4 ()I - public final fun component5 ()Z - public final fun component6 ()Ljava/lang/String; - public final fun component7 ()J - public final fun component8 ()J - public final fun component9 ()J - public final fun copy (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;IZLjava/lang/String;JJJJ)Lorg/pnfolder/pnlibrary/api/events/ListenerInfo; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/events/ListenerInfo;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;IZLjava/lang/String;JJJJILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/events/ListenerInfo; +public final class org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy { + public static final field Companion Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy$Companion; + public fun ()V + public fun (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope;)V + public fun (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope;I)V + public fun (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope;ILjava/time/Duration;)V + public fun (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope;ILjava/time/Duration;Z)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope;ILjava/time/Duration;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope; + public final fun component2 ()I + public final fun component3 ()Ljava/time/Duration; + public final fun component4 ()Z + public final fun copy (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope;ILjava/time/Duration;Z)Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy;Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope;ILjava/time/Duration;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy; public fun equals (Ljava/lang/Object;)Z - public final fun getAverageNanos ()J - public final fun getEventType ()Ljava/lang/String; - public final fun getFailures ()J - public final fun getIgnoreDenied ()Z - public final fun getInvocations ()J - public final fun getMaxNanos ()J - public final fun getModule ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; - public final fun getPlugin ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public final fun getPriority ()I - public final fun getSource ()Ljava/lang/String; - public final fun getTotalNanos ()J + public final fun getCacheNullValues ()Z + public final fun getExpireAfterWrite ()Ljava/time/Duration; + public final fun getMaximumEntries ()I + public final fun getScope ()Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope; public fun hashCode ()I + public static final fun none ()Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy; + public static final fun player (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy; public fun toString ()Ljava/lang/String; } -public abstract class org/pnfolder/pnlibrary/api/events/ResultedEvent : org/pnfolder/pnlibrary/api/events/Event { - public fun ()V - public final fun callResult ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$Result; - public abstract fun getResult ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$Result; - public abstract fun setResult (Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$Result;)V +public final class org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy$Companion { + public final fun none ()Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy; + public final fun player (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy; } -public final class org/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult : org/pnfolder/pnlibrary/api/events/ResultedEvent$Result { - public static final field Companion Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult$Companion; - public synthetic fun (ZLnet/kyori/adventure/text/Component;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun allowed ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult; - public static final fun denied (Lnet/kyori/adventure/text/Component;)Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult; - public final fun getReasonComponent ()Ljava/util/Optional; - public final fun getReasonComponent ()Lnet/kyori/adventure/text/Component; - public fun isAllowed ()Z - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope : java/lang/Enum { + public static final field ARGUMENTS Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope; + public static final field GLOBAL Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope; + public static final field NONE Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope; + public static final field PLAYER Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope; + public static final field PLUGIN Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope; } -public final class org/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult$Companion { - public final fun allowed ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult; - public final fun denied (Lnet/kyori/adventure/text/Component;)Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$ComponentResult; +public final class org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueScope : java/lang/Enum { + public static final field GLOBAL Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueScope; + public static final field PLAYER Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueScope; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueScope; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueScope; } -public final class org/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult : org/pnfolder/pnlibrary/api/events/ResultedEvent$Result { - public static final field Companion Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult$Companion; - public static final fun allowed ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult; - public static final fun denied ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult; - public fun isAllowed ()Z - public fun toString ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueStore { + public abstract fun contains (Ljava/lang/String;)Z + public abstract fun create (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueScope;Ljava/lang/String;)Z + public static synthetic fun create$default (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueStore;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueScope;Ljava/lang/String;ILjava/lang/Object;)Z + public abstract fun decrement (Ljava/lang/String;JLjava/util/UUID;)Ljava/lang/String; + public static synthetic fun decrement$default (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueStore;Ljava/lang/String;JLjava/util/UUID;ILjava/lang/Object;)Ljava/lang/String; + public abstract fun get (Ljava/lang/String;Ljava/util/UUID;)Ljava/lang/String; + public static synthetic fun get$default (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueStore;Ljava/lang/String;Ljava/util/UUID;ILjava/lang/Object;)Ljava/lang/String; + public abstract fun increment (Ljava/lang/String;JLjava/util/UUID;)Ljava/lang/String; + public static synthetic fun increment$default (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueStore;Ljava/lang/String;JLjava/util/UUID;ILjava/lang/Object;)Ljava/lang/String; + public abstract fun parameters ()Ljava/util/Set; + public abstract fun remove (Ljava/lang/String;Ljava/util/UUID;)Z + public static synthetic fun remove$default (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueStore;Ljava/lang/String;Ljava/util/UUID;ILjava/lang/Object;)Z + public abstract fun set (Ljava/lang/String;Ljava/lang/String;Ljava/util/UUID;)Ljava/lang/String; + public static synthetic fun set$default (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueStore;Ljava/lang/String;Ljava/lang/String;Ljava/util/UUID;ILjava/lang/Object;)Ljava/lang/String; + public abstract fun update (Ljava/lang/String;Ljava/util/UUID;Ljava/util/function/UnaryOperator;)Ljava/lang/String; + public static synthetic fun update$default (Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueStore;Ljava/lang/String;Ljava/util/UUID;Ljava/util/function/UnaryOperator;ILjava/lang/Object;)Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult$Companion { - public final fun allowed ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult; - public final fun denied ()Lorg/pnfolder/pnlibrary/api/events/ResultedEvent$GenericResult; +public abstract interface class org/pnfolder/pnlibrary/api/placeholders/model/AsyncPlaceholderResolver { + public abstract fun resolve (Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderRequest;)Ljava/util/concurrent/CompletionStage; } -public abstract interface class org/pnfolder/pnlibrary/api/events/ResultedEvent$Result { - public abstract fun isAllowed ()Z +public abstract interface class org/pnfolder/pnlibrary/api/placeholders/model/ExternalPlaceholderRegistration : java/lang/AutoCloseable { + public abstract fun getState ()Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState; + public fun isClosed ()Z } -public final class org/pnfolder/pnlibrary/api/events/player/PlayerJoinedEvent : org/pnfolder/pnlibrary/api/events/player/PlayerLifecycleEvent { - public fun (Ljava/util/UUID;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer;)V +public abstract interface class org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderAdapterRegistry { + public abstract fun all ()Ljava/util/List; + public abstract fun get (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapter; + public abstract fun register (Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapter;)Ljava/lang/AutoCloseable; + public fun require (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapter; } -public final class org/pnfolder/pnlibrary/api/events/player/PlayerLeftEvent : org/pnfolder/pnlibrary/api/events/player/PlayerLifecycleEvent { - public fun (Ljava/util/UUID;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer;)V +public final class org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey { + public static final field Companion Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey$Companion; + public fun (Ljava/lang/String;Ljava/lang/Class;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/Class; + public final fun copy (Ljava/lang/String;Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey;Ljava/lang/String;Ljava/lang/Class;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey; + public fun equals (Ljava/lang/Object;)Z + public final fun getType ()Ljava/lang/Class; + public final fun getValue ()Ljava/lang/String; + public fun hashCode ()I + public static final fun of (Ljava/lang/String;Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey; + public fun toString ()Ljava/lang/String; } -public abstract class org/pnfolder/pnlibrary/api/events/player/PlayerLifecycleEvent : org/pnfolder/pnlibrary/api/events/Event { - public fun (Ljava/util/UUID;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer;)V +public final class org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey$Companion { + public final fun of (Ljava/lang/String;Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey; +} + +public final class org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderPublication { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderPublication; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderPublication;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderPublication; + public fun equals (Ljava/lang/Object;)Z + public final fun getAdapterId ()Ljava/lang/String; public final fun getName ()Ljava/lang/String; - public final fun getPlayer ()Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer; - public final fun getUniqueId ()Ljava/util/UUID; + public final fun getNamespace ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public abstract class org/pnfolder/pnlibrary/api/expansions/AbstractExpansion : org/pnfolder/pnlibrary/api/expansions/Expansion { - protected fun (Ljava/lang/String;)V - public final fun close ()V - public final fun disable ()V - public final fun enable ()V - public final fun getId ()Ljava/lang/String; - public final fun getState ()Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; - protected fun onClose ()V - protected abstract fun onDisable ()V - protected abstract fun onEnable ()V +public final class org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderRequest { + public fun (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/util/UUID;Ljava/util/Map;Ljava/util/Map;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun component3 ()Ljava/util/UUID; + public final fun component4 ()Ljava/util/Map; + public final fun component5 ()Ljava/util/Map; + public final fun copy (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/util/UUID;Ljava/util/Map;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderRequest; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderRequest;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/util/UUID;Ljava/util/Map;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderRequest; + public fun equals (Ljava/lang/Object;)Z + public final fun getConsumer ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun getOwner ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun getParameters ()Ljava/util/Map; + public final fun getPlayerId ()Ljava/util/UUID; + public final fun getValues ()Ljava/util/Map; + public fun hashCode ()I + public final fun parameter (Ljava/lang/String;)Ljava/lang/String; + public final fun requirePlayerId ()Ljava/util/UUID; + public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/expansions/Expansion : java/lang/AutoCloseable { - public abstract fun close ()V - public abstract fun disable ()V - public abstract fun enable ()V - public abstract fun getId ()Ljava/lang/String; - public abstract fun getState ()Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; +public abstract interface class org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderResolver { + public abstract fun resolve (Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderRequest;)Ljava/lang/Object; } -public abstract interface class org/pnfolder/pnlibrary/api/expansions/ExpansionManager { - public abstract fun all ()Ljava/util/List; - public abstract fun get (Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/expansions/Expansion; - public abstract fun get (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/expansions/Expansion; - public abstract fun register (Lorg/pnfolder/pnlibrary/api/expansions/Expansion;)Ljava/lang/AutoCloseable; +public abstract class org/pnfolder/pnlibrary/api/placeholders/tree/AccessRule { } -public final class org/pnfolder/pnlibrary/api/expansions/ExpansionState : java/lang/Enum { - public static final field CLOSED Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; - public static final field DISABLED Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; - public static final field ENABLED Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; - public static final field FAILED Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/expansions/ExpansionState; -} - -public abstract interface annotation class org/pnfolder/pnlibrary/api/internal/InternalPnLibraryApi : java/lang/annotation/Annotation { -} - -public final class org/pnfolder/pnlibrary/api/logging/LogLevel : java/lang/Enum { - public static final field CRITICAL Lorg/pnfolder/pnlibrary/api/logging/LogLevel; - public static final field DEBUG Lorg/pnfolder/pnlibrary/api/logging/LogLevel; - public static final field ERROR Lorg/pnfolder/pnlibrary/api/logging/LogLevel; - public static final field INFO Lorg/pnfolder/pnlibrary/api/logging/LogLevel; - public static final field SUCCESS Lorg/pnfolder/pnlibrary/api/logging/LogLevel; - public static final field WARNING Lorg/pnfolder/pnlibrary/api/logging/LogLevel; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/LogLevel; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/logging/LogLevel; +public final class org/pnfolder/pnlibrary/api/placeholders/tree/AccessScope { + public final fun allowAll ()V + public final fun allowOnly ([Ljava/lang/String;)V + public final fun deny ([Ljava/lang/String;)V + public final fun denyAll ()V } -public abstract interface class org/pnfolder/pnlibrary/api/logging/LoggingService { - public abstract fun box (Ljava/lang/Object;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; - public fun box (Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; - public abstract fun logger (Ljava/lang/Object;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/PnLogger; - public abstract fun shutdownBox (Ljava/lang/Object;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; - public fun shutdownBox (Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; +public abstract class org/pnfolder/pnlibrary/api/placeholders/tree/ArgType { + public fun (Ljava/lang/String;)V + public fun getChoices ()Ljava/util/List; + public final fun getLabel ()Ljava/lang/String; + public abstract fun parse (Ljava/lang/String;)Ljava/lang/Object; } -public abstract interface class org/pnfolder/pnlibrary/api/logging/MessageBox { - public abstract fun fail (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; - public static synthetic fun fail$default (Lorg/pnfolder/pnlibrary/api/logging/MessageBox;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; - public fun hide ([Lorg/pnfolder/pnlibrary/api/plugin/LifecycleRow;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; - public abstract fun ok (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; - public abstract fun show ()V - public abstract fun skip (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; - public abstract fun warn (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; +public final class org/pnfolder/pnlibrary/api/placeholders/tree/ArgTypes { + public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgTypes; + public final fun choice ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; + public final fun getBool ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; + public final fun getInt ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; + public final fun getNumber ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; + public final fun getPlayer ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; + public final fun getText ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; + public final fun int (Lkotlin/ranges/IntRange;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; } -public abstract interface class org/pnfolder/pnlibrary/api/logging/PnLogger { - public fun critical (Ljava/lang/String;Ljava/lang/Throwable;)V - public static synthetic fun critical$default (Lorg/pnfolder/pnlibrary/api/logging/PnLogger;Ljava/lang/String;Ljava/lang/Throwable;ILjava/lang/Object;)V - public fun debug (Ljava/lang/String;)V - public fun debug (Ljava/lang/String;Ljava/lang/Throwable;)V - public fun error (Ljava/lang/String;)V - public fun error (Ljava/lang/String;Ljava/lang/Throwable;)V - public fun error (Ljava/lang/String;Ljava/lang/Throwable;Z)V - public fun info (Ljava/lang/String;)V - public fun info (Ljava/lang/String;Ljava/lang/Throwable;)V - public fun info (Ljava/lang/String;Z)V - public abstract fun log (Lorg/pnfolder/pnlibrary/api/logging/LogLevel;Ljava/lang/String;Ljava/lang/Throwable;Z)V - public static synthetic fun log$default (Lorg/pnfolder/pnlibrary/api/logging/PnLogger;Lorg/pnfolder/pnlibrary/api/logging/LogLevel;Ljava/lang/String;Ljava/lang/Throwable;ZILjava/lang/Object;)V - public fun success (Ljava/lang/String;)V - public fun success (Ljava/lang/String;Z)V - public fun warning (Ljava/lang/String;)V - public fun warning (Ljava/lang/String;Ljava/lang/Throwable;)V - public fun warning (Ljava/lang/String;Ljava/lang/Throwable;Z)V - public fun warning (Ljava/lang/String;Z)V +public final class org/pnfolder/pnlibrary/api/placeholders/tree/FormatScope { + public fun (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService;)V + public final fun getService ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService; } -public abstract interface class org/pnfolder/pnlibrary/api/metrics/ErrorReporter : java/lang/AutoCloseable { - public fun capture (Ljava/lang/Throwable;Ljava/lang/String;ZLjava/util/Map;)V - public abstract fun capture (Lorg/pnfolder/pnlibrary/api/metrics/TelemetryError;)V - public static synthetic fun capture$default (Lorg/pnfolder/pnlibrary/api/metrics/ErrorReporter;Ljava/lang/Throwable;Ljava/lang/String;ZLjava/util/Map;ILjava/lang/Object;)V - public abstract fun close ()V - public fun installGlobalHandler ()V +public final class org/pnfolder/pnlibrary/api/placeholders/tree/Generated { + public final fun exclude ([Lkotlin/reflect/KProperty1;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/Generated; + public final fun only ([Lkotlin/reflect/KProperty1;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/Generated; + public final fun rename (Lkotlin/reflect/KProperty1;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/Generated; } -public final class org/pnfolder/pnlibrary/api/metrics/MetricsBuilder { - public fun ()V - public final fun bStats (I)Lorg/pnfolder/pnlibrary/api/metrics/MetricsBuilder; - public final fun bStats (Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/metrics/MetricsBuilder; - public final fun bStats (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;I)Lorg/pnfolder/pnlibrary/api/metrics/MetricsBuilder; - public final fun build ()Ljava/util/List; - public final fun charts (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/metrics/MetricsBuilder; - public final fun configure (Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics;)V - public final fun enabled (Z)Lorg/pnfolder/pnlibrary/api/metrics/MetricsBuilder; - public final fun fastStats (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/metrics/MetricsBuilder; - public final fun getEnabled ()Z +public final class org/pnfolder/pnlibrary/api/placeholders/tree/ModuleFormatsKt { + public static final fun formats (Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext;Lkotlin/jvm/functions/Function1;)V } -public abstract interface class org/pnfolder/pnlibrary/api/metrics/MetricsController : java/lang/AutoCloseable { - public abstract fun close ()V - public abstract fun configure (Ljava/util/function/Consumer;)V - public abstract fun disable ()V - public abstract fun enable ()V - public fun errorReporterOrNull ()Lorg/pnfolder/pnlibrary/api/metrics/ErrorReporter; - public fun getProviderConfigurations ()Ljava/util/List; - public fun isClosed ()Z - public abstract fun isEnabled ()Z - public abstract fun update (Lorg/pnfolder/pnlibrary/api/metrics/MetricsProviderConfiguration;)V +public final class org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderCall { + public final fun argOf (Ljava/lang/String;)Ljava/lang/Object; + public final fun getArg ()Ljava/lang/Object; + public final fun getCaller ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun getPlayer ()Ljava/util/UUID; + public final fun getRequest ()Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderRequest; + public final fun getValues ()Ljava/util/Map; } -public abstract class org/pnfolder/pnlibrary/api/metrics/MetricsCredentials : java/lang/AutoCloseable { - public fun close ()V - public abstract fun getProvider ()Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider; - public abstract fun useValue (Lkotlin/jvm/functions/Function1;)Ljava/lang/Object; +public final class org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderGenerationKt { + public static final fun generateFrom (Lorg/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope;Ljava/lang/String;Ljava/lang/Class;Ljava/lang/String;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/Generated; + public static final fun placesOf (Lorg/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope;Ljava/lang/String;Ljava/lang/Class;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function2;)V + public static final fun tableOf (Lorg/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope;Ljava/lang/String;Ljava/lang/Class;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function2;)V } -public final class org/pnfolder/pnlibrary/api/metrics/MetricsCredentials$BStats : org/pnfolder/pnlibrary/api/metrics/MetricsCredentials { - public fun (I)V - public final fun component1 ()I - public final fun copy (I)Lorg/pnfolder/pnlibrary/api/metrics/MetricsCredentials$BStats; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/metrics/MetricsCredentials$BStats;IILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/metrics/MetricsCredentials$BStats; - public fun equals (Ljava/lang/Object;)Z - public final fun getProjectId ()I - public fun getProvider ()Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; - public fun useValue (Lkotlin/jvm/functions/Function1;)Ljava/lang/Object; +public final class org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderRulesKt { + public static final fun allowAll ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/AccessRule; + public static final fun allowOnly ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/AccessRule; + public static final fun deny ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/AccessRule; + public static final fun denyAll ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/AccessRule; } -public final class org/pnfolder/pnlibrary/api/metrics/MetricsCredentials$FastStats : org/pnfolder/pnlibrary/api/metrics/MetricsCredentials { - public fun ([C)V - public fun close ()V - public fun getProvider ()Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider; +public final class org/pnfolder/pnlibrary/api/placeholders/tree/PlayerArg { + public fun (Ljava/lang/String;)V + public final fun getId ()Ljava/util/UUID; + public final fun getText ()Ljava/lang/String; public fun toString ()Ljava/lang/String; - public final fun useToken (Lkotlin/jvm/functions/Function1;)Ljava/lang/Object; - public fun useValue (Lkotlin/jvm/functions/Function1;)Ljava/lang/Object; } -public final class org/pnfolder/pnlibrary/api/metrics/MetricsProvider : java/lang/Enum { - public static final field BSTATS Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider; - public static final field FASTSTATS Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider; +public final class org/pnfolder/pnlibrary/api/placeholders/tree/none { + public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/placeholders/tree/none; } -public final class org/pnfolder/pnlibrary/api/metrics/MetricsProviderConfiguration { - public fun (Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider;ZLjava/lang/Integer;Ljava/util/Map;Ljava/lang/String;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider;ZLjava/lang/Integer;Ljava/util/Map;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider; - public final fun component2 ()Z - public final fun component3 ()Ljava/lang/Integer; - public final fun component4 ()Ljava/util/Map; - public final fun component5 ()Ljava/lang/String; - public final fun copy (Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider;ZLjava/lang/Integer;Ljava/util/Map;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/metrics/MetricsProviderConfiguration; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/metrics/MetricsProviderConfiguration;Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider;ZLjava/lang/Integer;Ljava/util/Map;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/metrics/MetricsProviderConfiguration; - public final fun credentials ()Lorg/pnfolder/pnlibrary/api/metrics/MetricsCredentials; - public fun equals (Ljava/lang/Object;)Z - public final fun forPlatform (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;)Lorg/pnfolder/pnlibrary/api/metrics/MetricsProviderConfiguration; - public final fun getEnabled ()Z - public final fun getPlatformProjectIds ()Ljava/util/Map; - public final fun getProjectId ()Ljava/lang/Integer; - public final fun getProvider ()Lorg/pnfolder/pnlibrary/api/metrics/MetricsProvider; - public final fun getToken ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public abstract class org/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope { + public final fun bool (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V + public static synthetic fun bool$default (Lorg/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope;Ljava/lang/String;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V + public final fun choice (Ljava/lang/String;[Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V + public final fun getBool ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; + public final fun getInt ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; + public final fun getNumber ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; + public final fun getText ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; + public final fun int (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V + public static synthetic fun int$default (Lorg/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope;Ljava/lang/String;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V + public final fun number (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V + public static synthetic fun number$default (Lorg/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope;Ljava/lang/String;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V + public final fun param (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType;Lkotlin/jvm/functions/Function1;)V + public final fun param (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType;Lkotlin/ranges/IntRange;Lkotlin/jvm/functions/Function1;)V + public final fun player (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V + public final fun text (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V + public static synthetic fun text$default (Lorg/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope;Ljava/lang/String;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V + public final fun value (Ljava/lang/String;Ljava/lang/Class;Lkotlin/jvm/functions/Function1;)V + public static synthetic fun value$default (Lorg/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope;Ljava/lang/String;Ljava/lang/Class;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V } -public abstract interface class org/pnfolder/pnlibrary/api/metrics/MetricsService { - public fun getProviders ()Ljava/util/Set; - public abstract fun open (Ljava/lang/Object;Ljava/util/Collection;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; - public fun openErrorReporter (Ljava/lang/Object;Ljava/util/Collection;)Lorg/pnfolder/pnlibrary/api/metrics/ErrorReporter; +public final class org/pnfolder/pnlibrary/api/placeholders/tree/scope/GroupScope : org/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope { + public final fun access (Lkotlin/jvm/functions/Function1;)V + public final fun format (Ljava/lang/String;)V + public final fun format (Lorg/pnfolder/pnlibrary/api/placeholders/tree/none;)V } -public abstract interface class org/pnfolder/pnlibrary/api/metrics/PluginMetrics : java/lang/AutoCloseable { - public abstract fun advancedBarChart (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; - public abstract fun advancedPie (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; - public abstract fun close ()V - public abstract fun drilldownPie (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; - public fun getErrorReporter ()Lorg/pnfolder/pnlibrary/api/metrics/ErrorReporter; - public abstract fun getProviders ()Ljava/util/Set; - public abstract fun multiLineChart (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; - public abstract fun simpleBarChart (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; - public abstract fun simplePie (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; - public abstract fun singleLineChart (Ljava/lang/String;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; - public fun start ()V +public final class org/pnfolder/pnlibrary/api/placeholders/tree/scope/GroupScopeKt { + public static final fun placeholders (Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext;Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V + public static synthetic fun placeholders$default (Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext;Ljava/lang/String;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V } -public final class org/pnfolder/pnlibrary/api/metrics/TelemetryError { - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZLjava/lang/String;Ljava/util/Map;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZLjava/lang/String;Ljava/util/Map;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Ljava/util/List; - public final fun component4 ()Z - public final fun component5 ()Ljava/lang/String; - public final fun component6 ()Ljava/util/Map; - public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZLjava/lang/String;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/metrics/TelemetryError; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/metrics/TelemetryError;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZLjava/lang/String;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/metrics/TelemetryError; - public fun equals (Ljava/lang/Object;)Z - public final fun getAttributes ()Ljava/util/Map; - public final fun getHandled ()Z - public final fun getMessage ()Ljava/lang/String; - public final fun getOperation ()Ljava/lang/String; - public final fun getStackTrace ()Ljava/util/List; - public final fun getType ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/placeholders/tree/scope/NodeScope : org/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope { + public final fun access (Lkotlin/jvm/functions/Function1;)V + public final fun format (Ljava/lang/String;)V + public final fun format (Lorg/pnfolder/pnlibrary/api/placeholders/tree/none;)V + public final fun inside ()V + public final fun update (Lorg/pnfolder/pnlibrary/api/placeholders/tree/AccessRule;Lkotlin/jvm/functions/Function2;)V + public final fun value (Lkotlin/jvm/functions/Function1;)V + public final fun valueAsync (Lkotlin/jvm/functions/Function1;)V } -public final class org/pnfolder/pnlibrary/api/observability/ComponentStatus { - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;J)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;JILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Ljava/lang/String; - public final fun component4 ()Ljava/lang/String; - public final fun component5 ()Ljava/util/Map; - public final fun component6 ()J - public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;J)Lorg/pnfolder/pnlibrary/api/observability/ComponentStatus; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/observability/ComponentStatus;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;JILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/ComponentStatus; - public fun equals (Ljava/lang/Object;)Z - public final fun getComponent ()Ljava/lang/String; - public final fun getData ()Ljava/util/Map; - public final fun getDetail ()Ljava/lang/String; - public final fun getPlugin ()Ljava/lang/String; - public final fun getState ()Ljava/lang/String; - public final fun getUpdatedAt ()J - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/platform/PlatformProvider { + public abstract fun get (Ljava/lang/Class;)Ljava/lang/Object; + public abstract fun require (Ljava/lang/Class;)Ljava/lang/Object; } -public final class org/pnfolder/pnlibrary/api/observability/ObservabilityReport { - public fun (Ljava/lang/String;Ljava/nio/file/Path;J)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/nio/file/Path; - public final fun component3 ()J - public final fun copy (Ljava/lang/String;Ljava/nio/file/Path;J)Lorg/pnfolder/pnlibrary/api/observability/ObservabilityReport; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/observability/ObservabilityReport;Ljava/lang/String;Ljava/nio/file/Path;JILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/ObservabilityReport; - public fun equals (Ljava/lang/Object;)Z - public final fun getCreatedAt ()J - public final fun getFile ()Ljava/nio/file/Path; +public final class org/pnfolder/pnlibrary/api/platform/PlatformType : java/lang/Enum { + public static final field BUKKIT Lorg/pnfolder/pnlibrary/api/platform/PlatformType; + public static final field BUNGEECORD Lorg/pnfolder/pnlibrary/api/platform/PlatformType; + public static final field UNIVERSAL Lorg/pnfolder/pnlibrary/api/platform/PlatformType; + public static final field VELOCITY Lorg/pnfolder/pnlibrary/api/platform/PlatformType; + public final fun getDisplayName ()Ljava/lang/String; + public static fun getEntries ()Lkotlin/enums/EnumEntries; public final fun getId ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; + public final fun isProxy ()Z + public final fun isServer ()Z + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/platform/PlatformType; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/platform/PlatformType; } -public final class org/pnfolder/pnlibrary/api/observability/ObservabilityReportRequest { - public fun ()V - public fun (Ljava/lang/String;ZZ)V - public synthetic fun (Ljava/lang/String;ZZILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Z - public final fun component3 ()Z - public final fun copy (Ljava/lang/String;ZZ)Lorg/pnfolder/pnlibrary/api/observability/ObservabilityReportRequest; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/observability/ObservabilityReportRequest;Ljava/lang/String;ZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/ObservabilityReportRequest; - public fun equals (Ljava/lang/Object;)Z - public final fun getIncludeConfigurations ()Z - public final fun getIncludeLogs ()Z - public final fun getTarget ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/plugin/ModuleContext : java/lang/AutoCloseable { + public abstract fun close ()V + public abstract fun getActions ()Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionService; + public abstract fun getComponents ()Lorg/pnfolder/pnlibrary/api/text/ComponentService; + public abstract fun getConfigs ()Lorg/pnfolder/pnlibrary/api/config/ConfigScope; + public abstract fun getControl ()Lorg/pnfolder/pnlibrary/api/plugin/control/ModuleControl; + public abstract fun getCooldowns ()Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownService; + public abstract fun getDiagnostics ()Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticRegistration; + public abstract fun getDownloads ()Lorg/pnfolder/pnlibrary/api/downloads/DownloadRegistration; + public abstract fun getErrors ()Lorg/pnfolder/pnlibrary/api/metrics/error/ErrorReporter; + public abstract fun getEvents ()Lorg/pnfolder/pnlibrary/api/events/bus/EventScope; + public abstract fun getExpansions ()Lorg/pnfolder/pnlibrary/api/expansions/ExpansionManager; + public abstract fun getId ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public abstract fun getKey ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public abstract fun getLibraries ()Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibraries; + public abstract fun getLifecycle ()Lorg/pnfolder/pnlibrary/api/plugin/lifecycle/PluginLifecycle; + public abstract fun getLocalization ()Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization; + public abstract fun getLogger ()Lorg/pnfolder/pnlibrary/api/logging/PnLogger; + public abstract fun getMessages ()Lorg/pnfolder/pnlibrary/api/plugin/metadata/PluginMessages; + public abstract fun getMetadata ()Lorg/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadata; + public abstract fun getMetrics ()Lorg/pnfolder/pnlibrary/api/metrics/MetricsController; + public abstract fun getPlaceholders ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService; + public abstract fun getServices ()Lorg/pnfolder/pnlibrary/api/services/ServiceManager; + public abstract fun getTasks ()Lorg/pnfolder/pnlibrary/api/tasks/TaskScope; + public abstract fun getUpdates ()Lorg/pnfolder/pnlibrary/api/updates/UpdateRegistration; + public abstract fun isClosed ()Z + public fun onCommandError (Ljava/lang/Class;Ljava/lang/String;)V + public abstract fun onCommandError (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/commands/error/CommandErrorHandler;)V + public fun registerCommand (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/CommandRegistration; + public abstract fun registerCommand (Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition;)Lorg/pnfolder/pnlibrary/api/commands/CommandRegistration; } -public abstract interface class org/pnfolder/pnlibrary/api/observability/ObservabilityService : java/lang/AutoCloseable { - public fun capture (Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/observability/Observation; - public abstract fun createReport (Lorg/pnfolder/pnlibrary/api/observability/ObservabilityReportRequest;)Lorg/pnfolder/pnlibrary/api/observability/ObservabilityReport; - public static synthetic fun createReport$default (Lorg/pnfolder/pnlibrary/api/observability/ObservabilityService;Lorg/pnfolder/pnlibrary/api/observability/ObservabilityReportRequest;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/ObservabilityReport; - public fun failure (Ljava/lang/Throwable;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/observability/Observation; - public static synthetic fun failure$default (Lorg/pnfolder/pnlibrary/api/observability/ObservabilityService;Ljava/lang/Throwable;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/Observation; - public abstract fun recent (Lorg/pnfolder/pnlibrary/api/observability/ObservationQuery;)Ljava/util/List; - public static synthetic fun recent$default (Lorg/pnfolder/pnlibrary/api/observability/ObservabilityService;Lorg/pnfolder/pnlibrary/api/observability/ObservationQuery;ILjava/lang/Object;)Ljava/util/List; - public abstract fun record (Lorg/pnfolder/pnlibrary/api/observability/ObservationRequest;)Lorg/pnfolder/pnlibrary/api/observability/Observation; - public abstract fun status (Lorg/pnfolder/pnlibrary/api/observability/ComponentStatus;)Lorg/pnfolder/pnlibrary/api/observability/ComponentStatus; -} - -public final class org/pnfolder/pnlibrary/api/observability/Observation { - public static final field Companion Lorg/pnfolder/pnlibrary/api/observability/Observation$Companion; - public fun (Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()J - public final fun component3 ()Ljava/lang/String; - public final fun component4 ()Ljava/lang/String; - public final fun component5 ()Ljava/lang/String; - public final fun component6 ()Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public final fun component7 ()Ljava/util/Map; - public final fun component8 ()Ljava/lang/String; - public final fun component9 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/observability/Observation; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/observability/Observation;Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel;Ljava/util/Map;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/Observation; - public fun equals (Ljava/lang/Object;)Z - public static final fun from (Lorg/pnfolder/pnlibrary/api/observability/ObservationRequest;)Lorg/pnfolder/pnlibrary/api/observability/Observation; - public static final fun from (Lorg/pnfolder/pnlibrary/api/observability/ObservationRequest;J)Lorg/pnfolder/pnlibrary/api/observability/Observation; - public final fun getData ()Ljava/util/Map; - public final fun getErrorMessage ()Ljava/lang/String; - public final fun getErrorType ()Ljava/lang/String; - public final fun getId ()Ljava/lang/String; - public final fun getLevel ()Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public final fun getMessage ()Ljava/lang/String; - public final fun getPlugin ()Ljava/lang/String; - public final fun getSource ()Ljava/lang/String; - public final fun getTimestamp ()J - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/observability/Observation$Companion { - public final fun from (Lorg/pnfolder/pnlibrary/api/observability/ObservationRequest;)Lorg/pnfolder/pnlibrary/api/observability/Observation; - public final fun from (Lorg/pnfolder/pnlibrary/api/observability/ObservationRequest;J)Lorg/pnfolder/pnlibrary/api/observability/Observation; - public static synthetic fun from$default (Lorg/pnfolder/pnlibrary/api/observability/Observation$Companion;Lorg/pnfolder/pnlibrary/api/observability/ObservationRequest;JILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/Observation; -} - -public final class org/pnfolder/pnlibrary/api/observability/ObservationLevel : java/lang/Enum { - public static final field CRITICAL Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public static final field ERROR Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public static final field INFO Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public static final field NOTICE Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public static final field TRACE Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public static final field WARNING Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; +public abstract interface class org/pnfolder/pnlibrary/api/plugin/PluginBuilder { + public fun dependencies (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public abstract fun depends (Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public fun depends ([Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public abstract fun diagnostics (Ljava/nio/file/Path;Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public fun downloads (Ljava/nio/file/Path;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public fun downloads (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public abstract fun downloads (Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public abstract fun metadata (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public abstract fun metrics (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public abstract fun options (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public abstract fun product (Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public abstract fun remotePolicy (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public fun updates (Ljava/lang/String;Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public fun updates (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; + public abstract fun updates (Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; } -public final class org/pnfolder/pnlibrary/api/observability/ObservationQuery { - public fun ()V - public fun (ILjava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel;Ljava/lang/Long;Ljava/lang/Long;)V - public synthetic fun (ILjava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel;Ljava/lang/Long;Ljava/lang/Long;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()I - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public final fun component4 ()Ljava/lang/Long; - public final fun component5 ()Ljava/lang/Long; - public final fun copy (ILjava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel;Ljava/lang/Long;Ljava/lang/Long;)Lorg/pnfolder/pnlibrary/api/observability/ObservationQuery; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/observability/ObservationQuery;ILjava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel;Ljava/lang/Long;Ljava/lang/Long;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/ObservationQuery; - public fun equals (Ljava/lang/Object;)Z - public final fun getLimit ()I - public final fun getMinimumLevel ()Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public final fun getPlugin ()Ljava/lang/String; - public final fun getSince ()Ljava/lang/Long; - public final fun getUntil ()Ljava/lang/Long; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/plugin/PluginRegistration : java/lang/AutoCloseable { + public abstract fun all ()Ljava/util/List; + public abstract fun close ()V + public fun configs ()Ljava/util/List; + public fun getAllLibraries ()Ljava/util/List; + public abstract fun getId ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public abstract fun getLibraries ()Lorg/pnfolder/pnlibrary/api/libraries/ModuleLibraries; + public fun getModule (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; + public abstract fun getModule (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; + public abstract fun getOwner ()Ljava/lang/Object; + public abstract fun isClosed ()Z + public fun onCommandError (Ljava/lang/Class;Ljava/lang/String;)V + public abstract fun onCommandError (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/commands/error/CommandErrorHandler;)V + public fun registerModule (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; + public fun registerModule (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/plugin/control/PluginModule;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; + public abstract fun registerModule (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; + public abstract fun registerModule (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Lorg/pnfolder/pnlibrary/api/plugin/control/PluginModule;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; + public static synthetic fun registerModule$default (Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration;Ljava/lang/String;Ljava/util/function/Consumer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; + public static synthetic fun registerModule$default (Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/plugin/control/PluginModule;Ljava/util/function/Consumer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; + public static synthetic fun registerModule$default (Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/util/function/Consumer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; + public static synthetic fun registerModule$default (Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Lorg/pnfolder/pnlibrary/api/plugin/control/PluginModule;Ljava/util/function/Consumer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; + public fun requireModule (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; + public fun requireModule (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; + public fun unregisterModule (Ljava/lang/String;)V + public abstract fun unregisterModule (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)V } -public final class org/pnfolder/pnlibrary/api/observability/ObservationRequest { - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel;Ljava/util/Map;Ljava/util/List;Ljava/lang/Throwable;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel;Ljava/util/Map;Ljava/util/List;Ljava/lang/Throwable;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Ljava/lang/String; - public final fun component4 ()Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public final fun component5 ()Ljava/util/Map; - public final fun component6 ()Ljava/util/List; - public final fun component7 ()Ljava/lang/Throwable; - public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel;Ljava/util/Map;Ljava/util/List;Ljava/lang/Throwable;)Lorg/pnfolder/pnlibrary/api/observability/ObservationRequest; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/observability/ObservationRequest;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel;Ljava/util/Map;Ljava/util/List;Ljava/lang/Throwable;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/observability/ObservationRequest; - public fun equals (Ljava/lang/Object;)Z - public final fun getData ()Ljava/util/Map; - public final fun getError ()Ljava/lang/Throwable; - public final fun getFiles ()Ljava/util/List; - public final fun getLevel ()Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel; - public final fun getMessage ()Ljava/lang/String; - public final fun getPlugin ()Ljava/lang/String; - public final fun getSource ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public abstract interface class org/pnfolder/pnlibrary/api/plugin/PluginRegistry : java/lang/AutoCloseable { + public abstract fun all ()Ljava/util/List; + public fun allModules ()Ljava/util/List; + public abstract fun close ()V + public abstract fun get (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration; + public fun getById (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration; + public fun getById (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration; + public fun libraryUsage ()Ljava/util/List; + public abstract fun register (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration; + public fun require (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration; + public fun requireById (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration; + public fun requireById (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration; + public abstract fun unregister (Ljava/lang/Object;)V } -public final class org/pnfolder/pnlibrary/api/observability/ObservationScope { - public final fun data ([Lkotlin/Pair;)Lorg/pnfolder/pnlibrary/api/observability/ObservationScope; - public final fun files ([Ljava/nio/file/Path;)Lorg/pnfolder/pnlibrary/api/observability/ObservationScope; - public final fun level (Lorg/pnfolder/pnlibrary/api/observability/ObservationLevel;)Lorg/pnfolder/pnlibrary/api/observability/ObservationScope; - public final fun message (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/observability/ObservationScope; - public final fun plugin (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/observability/ObservationScope; - public final fun source (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/observability/ObservationScope; +public abstract interface class org/pnfolder/pnlibrary/api/plugin/control/ModuleControl { + public abstract fun disable ()Ljava/util/concurrent/CompletionStage; + public abstract fun enable ()Ljava/util/concurrent/CompletionStage; + public abstract fun getAutoStart ()Z + public abstract fun getLastError ()Ljava/lang/Throwable; + public abstract fun getState ()Lorg/pnfolder/pnlibrary/api/plugin/control/ModuleState; + public abstract fun isControllable ()Z + public abstract fun reload ()Ljava/util/concurrent/CompletionStage; + public abstract fun restart ()Ljava/util/concurrent/CompletionStage; + public abstract fun setAutoStart (Z)V } -public abstract interface class org/pnfolder/pnlibrary/api/placeholders/AsyncPlaceholderResolver { - public abstract fun resolve (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderRequest;)Ljava/util/concurrent/CompletionStage; +public final class org/pnfolder/pnlibrary/api/plugin/control/ModuleState : java/lang/Enum { + public static final field DISABLED Lorg/pnfolder/pnlibrary/api/plugin/control/ModuleState; + public static final field ENABLED Lorg/pnfolder/pnlibrary/api/plugin/control/ModuleState; + public static final field FAILED Lorg/pnfolder/pnlibrary/api/plugin/control/ModuleState; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/control/ModuleState; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/plugin/control/ModuleState; +} + +public abstract interface class org/pnfolder/pnlibrary/api/plugin/control/PluginModule { + public fun libraries ()Ljava/util/List; + public fun onDisable (Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext;)V + public fun onEnable (Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext;)V + public fun onReload (Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext;)Z +} + +public final class org/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow : java/lang/Enum { + public static final field DIAGNOSTICS Lorg/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow; + public static final field IDENTIFIER Lorg/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow; + public static final field METRICS Lorg/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow; + public static final field NOT_CONFIGURED Lorg/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow; + public static final field PLACEHOLDER_API Lorg/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow; + public static final field PLATFORM Lorg/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow; + public static final field RESOURCES Lorg/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow; + public static final field UPDATES Lorg/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow; } -public abstract interface class org/pnfolder/pnlibrary/api/placeholders/ExternalPlaceholderRegistration : java/lang/AutoCloseable { - public abstract fun getState ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState; - public fun isClosed ()Z +public abstract interface class org/pnfolder/pnlibrary/api/plugin/lifecycle/PluginLifecycle { + public abstract fun disabled ()Lorg/pnfolder/pnlibrary/api/logging/MessageBox; + public abstract fun enabled ()Lorg/pnfolder/pnlibrary/api/logging/MessageBox; + public abstract fun getMetadata ()Lorg/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadata; } -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess { - public static final field Companion Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess$Companion; - public synthetic fun (ZZLjava/util/Set;Ljava/util/Set;Ljava/util/Set;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun allows (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Z - public static final fun builder ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess$Builder; - public final fun getAllLibraryPlugins ()Z - public final fun getAllowedPatterns ()Ljava/util/Set; - public final fun getAllowedPlugins ()Ljava/util/Set; - public final fun getDeniedPlugins ()Ljava/util/Set; - public final fun getOwnerAllowed ()Z - public static final fun ownerOnly ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess; - public static final fun shared ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess; +public abstract interface class org/pnfolder/pnlibrary/api/plugin/metadata/PluginMessages { + public abstract fun box (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; } -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess$Builder { - public final fun allow ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess$Builder; - public final fun allowAllLibraryPlugins ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess$Builder; - public final fun allowMatching ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess$Builder; - public final fun build ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess; - public final fun deny ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess$Builder; - public final fun owner ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess$Builder; +public final class org/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadata { + public fun (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun getAuthors ()Ljava/lang/String; + public final fun getDescription ()Ljava/lang/String; + public final fun getId ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public final fun getJavaFeature ()I + public final fun getJavaVersion ()Ljava/lang/String; + public final fun getName ()Ljava/lang/String; + public final fun getPlatform ()Lorg/pnfolder/pnlibrary/api/platform/PlatformType; + public final fun getPlatformImplementation ()Ljava/lang/String; + public final fun getVersion ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess$Companion { - public final fun builder ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess$Builder; - public final fun ownerOnly ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess; - public final fun shared ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess; +public abstract interface class org/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadataBuilder { + public abstract fun authors (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadataBuilder; + public fun description (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadataBuilder; + public abstract fun name (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadataBuilder; + public abstract fun version (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadataBuilder; } -public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapter { - public static final field Companion Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapter$Companion; - public static final field WAIT_MILLIS_KEY Ljava/lang/String; - public abstract fun getCapabilities ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterCapabilities; - public abstract fun getId ()Ljava/lang/String; - public abstract fun getState ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState; - public abstract fun publish (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderResolver;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderPublication;)Lorg/pnfolder/pnlibrary/api/placeholders/ExternalPlaceholderRegistration; - public fun render (Ljava/util/UUID;Ljava/lang/String;)Ljava/lang/String; - public fun resolve (Ljava/util/UUID;Ljava/lang/String;)Ljava/lang/Object; +public abstract interface class org/pnfolder/pnlibrary/api/plugin/metadata/PluginOptions { + public abstract fun placeholderApi (Z)Lorg/pnfolder/pnlibrary/api/plugin/metadata/PluginOptions; } -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapter$Companion { - public static final field WAIT_MILLIS_KEY Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/remote/DenyAction : java/lang/Enum { + public static final field DISABLE_MODULE Lorg/pnfolder/pnlibrary/api/remote/DenyAction; + public static final field DISABLE_PLUGIN Lorg/pnfolder/pnlibrary/api/remote/DenyAction; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/DenyAction; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/remote/DenyAction; } -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterCapabilities { - public fun ()V - public fun (ZZZZZ)V - public synthetic fun (ZZZZZILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Z - public final fun component2 ()Z - public final fun component3 ()Z - public final fun component4 ()Z - public final fun component5 ()Z - public final fun copy (ZZZZZ)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterCapabilities; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterCapabilities;ZZZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterCapabilities; +public final class org/pnfolder/pnlibrary/api/remote/PlatformInfo { + public fun (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;Ljava/lang/String;Ljava/lang/String;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/platform/PlatformType; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun copy (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/PlatformInfo; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/remote/PlatformInfo;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/remote/PlatformInfo; public fun equals (Ljava/lang/Object;)Z - public final fun getAsynchronous ()Z - public final fun getComponents ()Z - public final fun getOfflinePlayers ()Z - public final fun getParameters ()Z - public final fun getPlayers ()Z + public final fun getKey ()Ljava/lang/String; + public final fun getName ()Ljava/lang/String; + public final fun getType ()Lorg/pnfolder/pnlibrary/api/platform/PlatformType; + public final fun getVersion ()Ljava/lang/String; public fun hashCode ()I + public final fun isNamed (Ljava/lang/String;)Z public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterRegistry { - public abstract fun all ()Ljava/util/List; - public abstract fun get (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapter; - public abstract fun register (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapter;)Ljava/lang/AutoCloseable; - public fun require (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapter; -} - -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState : java/lang/Enum { - public static final field AVAILABLE Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState; - public static final field CLOSED Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState; - public static final field FAILED Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState; - public static final field REGISTERED Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState; - public static final field UNAVAILABLE Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState; +public final class org/pnfolder/pnlibrary/api/remote/PolicyErrorAction : java/lang/Enum { + public static final field DENY Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; + public static final field DENY_UNTIL_CHECKED Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; + public static final field KEEP_RUNNING Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState; -} - -public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder { - public abstract fun access (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public abstract fun access (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public abstract fun cache (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public fun defaultFormat (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public abstract fun fallback (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public abstract fun format (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderFormatter;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public abstract fun publish (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderPublication;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public fun publishToPlaceholderApi ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public fun publishToPlaceholderApi (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public fun publishToPlaceholderApi (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public abstract fun resolve (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderResolver;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public abstract fun resolveAsync (Lorg/pnfolder/pnlibrary/api/placeholders/AsyncPlaceholderResolver;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public abstract fun update (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderUpdater;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; - public abstract fun updateAccess (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; } -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy { - public static final field Companion Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy$Companion; - public fun ()V - public fun (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope;)V - public fun (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope;I)V - public fun (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope;ILjava/time/Duration;)V - public fun (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope;ILjava/time/Duration;Z)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope;ILjava/time/Duration;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope; - public final fun component2 ()I - public final fun component3 ()Ljava/time/Duration; - public final fun component4 ()Z - public final fun copy (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope;ILjava/time/Duration;Z)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope;ILjava/time/Duration;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy; +public final class org/pnfolder/pnlibrary/api/remote/ProductInfo { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/ProductInfo; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/remote/ProductInfo;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/remote/ProductInfo; public fun equals (Ljava/lang/Object;)Z - public final fun getCacheNullValues ()Z - public final fun getExpireAfterWrite ()Ljava/time/Duration; - public final fun getMaximumEntries ()I - public final fun getScope ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope; + public final fun getId ()Ljava/lang/String; + public final fun getName ()Ljava/lang/String; + public final fun getVersion ()Ljava/lang/String; public fun hashCode ()I - public static final fun none ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy; - public static final fun player (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy; public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy$Companion { - public final fun none ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy; - public final fun player (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy; -} - -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope : java/lang/Enum { - public static final field ARGUMENTS Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope; - public static final field GLOBAL Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope; - public static final field NONE Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope; - public static final field PLAYER Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope; - public static final field PLUGIN Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope; +public abstract interface class org/pnfolder/pnlibrary/api/remote/RemotePolicy { + public abstract fun check (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; } -public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderFormatter { - public abstract fun format (Ljava/lang/Object;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderRequest;)Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyContext { + public static final field Companion Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun builder ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; + public final fun getPlatform ()Lorg/pnfolder/pnlibrary/api/remote/PlatformInfo; + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/remote/ProductInfo; + public final fun getServer ()Lorg/pnfolder/pnlibrary/api/remote/ServerInfo; + public final fun getValues ()Ljava/util/Map; + public final fun nativeHandle (Ljava/lang/Class;)Ljava/lang/Object; + public final fun requireNative (Ljava/lang/Class;)Ljava/lang/Object; } -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderKey { - public static final field Companion Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderKey$Companion; - public fun (Ljava/lang/String;Ljava/lang/Class;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/lang/Class; - public final fun copy (Ljava/lang/String;Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderKey; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderKey;Ljava/lang/String;Ljava/lang/Class;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderKey; - public fun equals (Ljava/lang/Object;)Z - public final fun getType ()Ljava/lang/Class; - public final fun getValue ()Ljava/lang/String; - public fun hashCode ()I - public static final fun of (Ljava/lang/String;Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderKey; - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext; + public final fun nativeHandle (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; + public final fun platform (Lorg/pnfolder/pnlibrary/api/remote/PlatformInfo;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; + public final fun product (Lorg/pnfolder/pnlibrary/api/remote/ProductInfo;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; + public final fun server (Lorg/pnfolder/pnlibrary/api/remote/ServerInfo;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; + public final fun value (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; + public final fun values (Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; } -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderKey$Companion { - public final fun of (Ljava/lang/String;Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderKey; +public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Companion { + public final fun builder ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; } -public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderProvider { - public abstract fun getPluginId ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public abstract fun keys ()Ljava/util/Set; - public abstract fun resolve (Ljava/lang/String;Ljava/util/UUID;)Ljava/util/concurrent/CompletionStage; - public static synthetic fun resolve$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderProvider;Ljava/lang/String;Ljava/util/UUID;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; +public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation { + public static final field Companion Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder; + public final fun getChildren ()Ljava/util/List; + public final fun getText ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderPublication { - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderPublication; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderPublication;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderPublication; - public fun equals (Ljava/lang/Object;)Z - public final fun getAdapterId ()Ljava/lang/String; - public final fun getName ()Ljava/lang/String; - public final fun getNamespace ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder { + public final fun branch (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder; + public final fun build ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation; + public final fun child (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder; + public final fun child (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder; } -public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderRegistration : java/lang/AutoCloseable { - public abstract fun disable ()V - public abstract fun enable ()V - public abstract fun getKey ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderKey; - public abstract fun getOwner ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public abstract fun getPublications ()Ljava/util/List; - public abstract fun invalidateCache ()V - public fun isClosed ()Z - public abstract fun isEnabled ()Z +public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Companion { + public final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder; } -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderRequest { - public fun (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/util/UUID;Ljava/util/Map;Ljava/util/Map;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public final fun component3 ()Ljava/util/UUID; - public final fun component4 ()Ljava/util/Map; - public final fun component5 ()Ljava/util/Map; - public final fun copy (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/util/UUID;Ljava/util/Map;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderRequest; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderRequest;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/util/UUID;Ljava/util/Map;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderRequest; - public fun equals (Ljava/lang/Object;)Z - public final fun getConsumer ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public final fun getOwner ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public final fun getParameters ()Ljava/util/Map; - public final fun getPlayerId ()Ljava/util/UUID; +public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyResult { + public static final field Companion Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Companion; + public synthetic fun (ZLorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;Ljava/util/List;Ljava/util/Map;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun allow ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; + public static final fun allowing (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; + public static final fun deny (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; + public static final fun deny (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; + public static final fun denying (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; + public final fun getAllowed ()Z + public final fun getDetails ()Ljava/util/Map; + public final fun getExplanation ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation; + public final fun getHeadline ()Ljava/lang/String; + public final fun getLinks ()Ljava/util/Map; + public final fun getMessage ()Ljava/lang/String; + public final fun getStatus ()Ljava/lang/String; + public final fun getSteps ()Ljava/util/List; +} + +public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; + public final fun detail (Ljava/lang/String;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; + public final fun headline (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; + public final fun link (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; + public final fun reason (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; + public final fun reason (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; + public final fun status (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; + public final fun step (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; +} + +public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Companion { + public final fun allow ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; + public final fun allowing (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; + public final fun deny (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; + public final fun deny (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; + public final fun denying (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; +} + +public final class org/pnfolder/pnlibrary/api/remote/RemotePolicySettings { + public static final field Companion Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Companion; + public fun (Ljava/lang/String;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/remote/DenyAction;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction;Ljava/lang/String;Ljava/time/Duration;)V + public synthetic fun (Ljava/lang/String;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/remote/DenyAction;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction;Ljava/lang/String;Ljava/time/Duration;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun builder ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/time/Duration; + public final fun component3 ()Lorg/pnfolder/pnlibrary/api/remote/DenyAction; + public final fun component4 ()Ljava/util/Map; + public final fun component5 ()Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; + public final fun component6 ()Ljava/lang/String; + public final fun component7 ()Ljava/time/Duration; + public final fun copy (Ljava/lang/String;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/remote/DenyAction;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction;Ljava/lang/String;Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings;Ljava/lang/String;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/remote/DenyAction;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction;Ljava/lang/String;Ljava/time/Duration;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings; + public fun equals (Ljava/lang/Object;)Z + public final fun getCheckEvery ()Ljava/time/Duration; + public final fun getOnDeny ()Lorg/pnfolder/pnlibrary/api/remote/DenyAction; + public final fun getOnError ()Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; + public final fun getSource ()Ljava/lang/String; + public final fun getStartupTimeout ()Ljava/time/Duration; + public final fun getSupportUrl ()Ljava/lang/String; public final fun getValues ()Ljava/util/Map; public fun hashCode ()I - public final fun parameter (Ljava/lang/String;)Ljava/lang/String; - public final fun requirePlayerId ()Ljava/util/UUID; public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderResolver { - public abstract fun resolve (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderRequest;)Ljava/lang/Object; +public final class org/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings; + public final fun checkEvery (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; + public final fun onDeny (Lorg/pnfolder/pnlibrary/api/remote/DenyAction;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; + public final fun onError (Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; + public final fun source (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; + public final fun startupTimeout (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; + public final fun support (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; + public final fun value (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; + public final fun values (Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; } -public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderService : java/lang/AutoCloseable { - public abstract fun adapters ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterRegistry; - public abstract fun contains (Ljava/lang/String;)Z - public abstract fun formatter (Ljava/lang/String;Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderFormatter;)V - public abstract fun provider (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderProvider; - public fun register (Ljava/lang/String;Ljava/lang/Class;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderRegistration; - public abstract fun register (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderKey;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderRegistration; - public abstract fun render (Ljava/lang/String;Ljava/util/UUID;Ljava/util/Map;)Ljava/util/concurrent/CompletionStage; - public static synthetic fun render$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService;Ljava/lang/String;Ljava/util/UUID;Ljava/util/Map;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; - public abstract fun resolve (Ljava/lang/String;Ljava/util/UUID;Ljava/util/Map;)Ljava/util/concurrent/CompletionStage; - public static synthetic fun resolve$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService;Ljava/lang/String;Ljava/util/UUID;Ljava/util/Map;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; - public abstract fun update (Ljava/lang/String;Ljava/lang/String;Ljava/util/UUID;Ljava/util/Map;)Ljava/util/concurrent/CompletionStage; - public static synthetic fun update$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService;Ljava/lang/String;Ljava/lang/String;Ljava/util/UUID;Ljava/util/Map;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; +public final class org/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Companion { + public final fun builder ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; } -public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderUpdater { - public abstract fun update (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderRequest;Ljava/lang/String;)Ljava/lang/Object; +public final class org/pnfolder/pnlibrary/api/remote/ServerInfo { + public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersionInfo;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersionInfo; + public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersionInfo;)Lorg/pnfolder/pnlibrary/api/remote/ServerInfo; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/remote/ServerInfo;Ljava/lang/String;Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersionInfo;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/remote/ServerInfo; + public fun equals (Ljava/lang/Object;)Z + public final fun getMinecraft ()Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersionInfo; + public final fun getMinecraftVersion ()Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersion; + public final fun getVersion ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/placeholders/PlaceholderValueScope : java/lang/Enum { - public static final field GLOBAL Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueScope; - public static final field PLAYER Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueScope; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueScope; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueScope; +public abstract interface class org/pnfolder/pnlibrary/api/runtime/PnLibrary : java/io/Closeable { + public abstract fun close ()V + public abstract fun createDiagnosticReport (Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest;)Lorg/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticReport; + public abstract fun getAudiences ()Lorg/pnfolder/pnlibrary/api/audiences/AudienceService; + public abstract fun getConfiguration ()Lorg/pnfolder/pnlibrary/api/runtime/PnLibraryConfig; + public abstract fun getConfigurations ()Lorg/pnfolder/pnlibrary/api/config/ConfigurationService; + public abstract fun getDiagnostics ()Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService; + public abstract fun getEvents ()Lorg/pnfolder/pnlibrary/api/events/bus/EventService; + public abstract fun getExpansions ()Lorg/pnfolder/pnlibrary/api/expansions/ExpansionManager; + public abstract fun getLogging ()Lorg/pnfolder/pnlibrary/api/logging/LoggingService; + public abstract fun getMetrics ()Lorg/pnfolder/pnlibrary/api/metrics/MetricsService; + public abstract fun getObservability ()Lorg/pnfolder/pnlibrary/api/observability/ObservabilityService; + public abstract fun getOwner ()Ljava/lang/Object; + public abstract fun getPlaceholderAdapters ()Lorg/pnfolder/pnlibrary/api/placeholders/model/PlaceholderAdapterRegistry; + public abstract fun getPlaceholderValues ()Lorg/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueStore; + public abstract fun getPlatforms ()Lorg/pnfolder/pnlibrary/api/platform/PlatformProvider; + public abstract fun getPlugins ()Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistry; + public abstract fun getProxy ()Lorg/pnfolder/pnlibrary/api/network/NetworkProxy; + public abstract fun getServices ()Lorg/pnfolder/pnlibrary/api/services/ServiceManager; + public abstract fun getUpdates ()Lorg/pnfolder/pnlibrary/api/updates/UpdateService; + public abstract fun getVersion ()Ljava/lang/String; + public abstract fun isAtLeastVersion (Ljava/lang/String;)Z + public abstract fun isClosed ()Z } -public abstract interface class org/pnfolder/pnlibrary/api/placeholders/PlaceholderValueStore { - public abstract fun contains (Ljava/lang/String;)Z - public abstract fun create (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueScope;Ljava/lang/String;)Z - public static synthetic fun create$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueStore;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueScope;Ljava/lang/String;ILjava/lang/Object;)Z - public abstract fun decrement (Ljava/lang/String;JLjava/util/UUID;)Ljava/lang/String; - public static synthetic fun decrement$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueStore;Ljava/lang/String;JLjava/util/UUID;ILjava/lang/Object;)Ljava/lang/String; - public abstract fun get (Ljava/lang/String;Ljava/util/UUID;)Ljava/lang/String; - public static synthetic fun get$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueStore;Ljava/lang/String;Ljava/util/UUID;ILjava/lang/Object;)Ljava/lang/String; - public abstract fun increment (Ljava/lang/String;JLjava/util/UUID;)Ljava/lang/String; - public static synthetic fun increment$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueStore;Ljava/lang/String;JLjava/util/UUID;ILjava/lang/Object;)Ljava/lang/String; - public abstract fun parameters ()Ljava/util/Set; - public abstract fun remove (Ljava/lang/String;Ljava/util/UUID;)Z - public static synthetic fun remove$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueStore;Ljava/lang/String;Ljava/util/UUID;ILjava/lang/Object;)Z - public abstract fun set (Ljava/lang/String;Ljava/lang/String;Ljava/util/UUID;)Ljava/lang/String; - public static synthetic fun set$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueStore;Ljava/lang/String;Ljava/lang/String;Ljava/util/UUID;ILjava/lang/Object;)Ljava/lang/String; - public abstract fun update (Ljava/lang/String;Ljava/util/UUID;Ljava/util/function/UnaryOperator;)Ljava/lang/String; - public static synthetic fun update$default (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueStore;Ljava/lang/String;Ljava/util/UUID;Ljava/util/function/UnaryOperator;ILjava/lang/Object;)Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/runtime/PnLibraryConfig { + public fun ()V + public fun (Z)V + public fun (ZLjava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZ)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZ)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZI)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZII)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIII)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;I)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;II)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;III)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIII)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Z)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZI)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZII)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIII)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;Z)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V + public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V + public synthetic fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Z + public final fun component10 ()Z + public final fun component11 ()I + public final fun component12 ()I + public final fun component13 ()I + public final fun component14 ()Ljava/time/Duration; + public final fun component15 ()I + public final fun component16 ()I + public final fun component17 ()I + public final fun component18 ()I + public final fun component19 ()Ljava/util/List; + public final fun component2 ()Ljava/lang/String; + public final fun component20 ()Ljava/util/List; + public final fun component21 ()Z + public final fun component22 ()I + public final fun component23 ()I + public final fun component24 ()I + public final fun component25 ()Ljava/lang/String; + public final fun component26 ()Z + public final fun component27 ()Ljava/lang/String; + public final fun component28 ()Ljava/lang/String; + public final fun component29 ()Ljava/lang/String; + public final fun component3 ()Ljava/util/List; + public final fun component30 ()Ljava/lang/String; + public final fun component31 ()Ljava/lang/String; + public final fun component32 ()Ljava/lang/String; + public final fun component33 ()Ljava/lang/String; + public final fun component34 ()Ljava/lang/String; + public final fun component35 ()Ljava/lang/String; + public final fun component36 ()I + public final fun component37 ()I + public final fun component4 ()Ljava/lang/String; + public final fun component5 ()Ljava/lang/String; + public final fun component6 ()Ljava/lang/String; + public final fun component7 ()Ljava/lang/String; + public final fun component8 ()Z + public final fun component9 ()Z + public final fun copy (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)Lorg/pnfolder/pnlibrary/api/runtime/PnLibraryConfig; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/runtime/PnLibraryConfig;ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/runtime/PnLibraryConfig; + public fun equals (Ljava/lang/Object;)Z + public final fun getAllowPlaintext ()Z + public final fun getCommandFailedMessage ()Ljava/lang/String; + public final fun getConfigs ()Z + public final fun getConsoleOnlyMessage ()Ljava/lang/String; + public final fun getCooldown ()Ljava/time/Duration; + public final fun getCooldownMessage ()Ljava/lang/String; + public final fun getDeleteAfterDays ()I + public final fun getEventHistoryDays ()I + public final fun getHistoryMaxBytes ()I + public final fun getHistoryRetentionDays ()I + public final fun getInvalidArgumentMessage ()Ljava/lang/String; + public final fun getJournalErrorDays ()I + public final fun getJournalForeignPlugins ()Z + public final fun getJournalInfoDays ()I + public final fun getJournalJoinNoticeHours ()I + public final fun getJournalWarningDays ()I + public final fun getKeepReports ()I + public final fun getLogRecords ()I + public final fun getLogs ()Z + public final fun getMaxReportBytes ()I + public final fun getNoPermissionMessage ()Ljava/lang/String; + public final fun getNoPermissionSound ()Ljava/lang/String; + public final fun getPlayerNotFoundMessage ()Ljava/lang/String; + public final fun getPlayerOnlyMessage ()Ljava/lang/String; + public final fun getPrivacy ()Z + public final fun getRedactValuePatterns ()Ljava/util/List; + public final fun getSecretKeyPatterns ()Ljava/util/List; + public final fun getTaskHistoryCapacity ()I + public final fun getTimeZone ()Ljava/lang/String; + public final fun getUpload ()Z + public final fun getUploadEndpoint ()Ljava/lang/String; + public final fun getUploadKeyId ()Ljava/lang/String; + public final fun getUploadMode ()Ljava/lang/String; + public final fun getUploadProviders ()Ljava/util/List; + public final fun getUploadPublicBase ()Ljava/lang/String; + public final fun getUploadPublicKey ()Ljava/lang/String; + public final fun getUsageMessage ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public abstract class org/pnfolder/pnlibrary/api/placeholders/tree/AccessRule { +public final class org/pnfolder/pnlibrary/api/runtime/PnLibraryIdentity { + public static final field AUTHOR Ljava/lang/String; + public static final field DESCRIPTION Ljava/lang/String; + public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/runtime/PnLibraryIdentity; + public static final field NAME Ljava/lang/String; + public static final field ORGANIZATION Ljava/lang/String; + public static final field PRODUCT_ID Ljava/lang/String; + public static final field REPOSITORY Ljava/lang/String; + public static final field REPOSITORY_URL Ljava/lang/String; + public static final field SUPPORT_URL Ljava/lang/String; + public static final field VERSION Ljava/lang/String; + public final fun getAUTHORS ()Ljava/util/List; } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/AccessScope { - public final fun allowAll ()V - public final fun allowOnly ([Ljava/lang/String;)V - public final fun deny ([Ljava/lang/String;)V - public final fun denyAll ()V +public final class org/pnfolder/pnlibrary/api/runtime/PnLibraryProvider { + public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/runtime/PnLibraryProvider; + public static final fun clear (Lorg/pnfolder/pnlibrary/api/runtime/PnLibrary;)V + public static final fun get ()Lorg/pnfolder/pnlibrary/api/runtime/PnLibrary; + public static final fun getOrNull ()Lorg/pnfolder/pnlibrary/api/runtime/PnLibrary; + public static final fun install (Lorg/pnfolder/pnlibrary/api/runtime/PnLibrary;)V } -public abstract class org/pnfolder/pnlibrary/api/placeholders/tree/ArgType { - public fun (Ljava/lang/String;)V - public fun getChoices ()Ljava/util/List; - public final fun getLabel ()Ljava/lang/String; - public abstract fun parse (Ljava/lang/String;)Ljava/lang/Object; +public abstract interface class org/pnfolder/pnlibrary/api/scenario/actions/Action { + public abstract fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/ArgTypes { - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgTypes; - public final fun choice ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; - public final fun getBool ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; - public final fun getInt ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; - public final fun getNumber ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; - public final fun getPlayer ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; - public final fun getText ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; - public final fun int (Lkotlin/ranges/IntRange;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; +public final class org/pnfolder/pnlibrary/api/scenario/actions/ActionContext : org/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext { + public static final field EXTERNAL_ADAPTER Ljava/lang/String; + public fun (Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer;Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience;Lorg/pnfolder/pnlibrary/api/text/ComponentService;Lorg/pnfolder/pnlibrary/api/logging/PnLogger;Lorg/pnfolder/pnlibrary/api/tasks/TaskScope;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Ljava/util/Map;Ljava/util/Map;Lkotlin/jvm/functions/Function1;Lorg/pnfolder/pnlibrary/api/scenario/actions/ScenarioLookup;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer;Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience;Lorg/pnfolder/pnlibrary/api/text/ComponentService;Lorg/pnfolder/pnlibrary/api/logging/PnLogger;Lorg/pnfolder/pnlibrary/api/tasks/TaskScope;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Ljava/util/Map;Ljava/util/Map;Lkotlin/jvm/functions/Function1;Lorg/pnfolder/pnlibrary/api/scenario/actions/ScenarioLookup;Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun action (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/actions/Action; + public final fun component (Ljava/lang/Iterable;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;)Lnet/kyori/adventure/text/Component; + public final fun component (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;)Lnet/kyori/adventure/text/Component; + public static synthetic fun component$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;Ljava/lang/Iterable;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;ILjava/lang/Object;)Lnet/kyori/adventure/text/Component; + public static synthetic fun component$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;ILjava/lang/Object;)Lnet/kyori/adventure/text/Component; + public final fun discardUndo (I)V + public final fun execute (Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public final fun format (Ljava/lang/String;)Ljava/lang/String; + public fun function (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/expression/ExpressionFunction; + public final fun getAllPlayers ()Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience; + public final fun getComponents ()Lorg/pnfolder/pnlibrary/api/text/ComponentService; + public fun getLogger ()Lorg/pnfolder/pnlibrary/api/logging/PnLogger; + public final fun getPlaceholders ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService; + public fun getPlayer ()Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer; + public final fun getSerializerType ()Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public final fun getTasks ()Lorg/pnfolder/pnlibrary/api/tasks/TaskScope; + public final fun onUndo (Ljava/lang/String;Lkotlin/jvm/functions/Function0;)V + public fun read (Ljava/lang/String;)Ljava/lang/Object; + public final fun requireService (Ljava/lang/Class;)Ljava/lang/Object; + public fun requirement (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement; + public final fun resolve (Ljava/lang/String;)Ljava/lang/Object; + public final fun rollbackTo (I)V + public final fun runLater (Ljava/time/Duration;Ljava/util/List;)V + public final fun runList (Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public final fun scoped (Ljava/util/Map;Lkotlin/jvm/functions/Function0;)Ljava/lang/Object; + public fun service (Ljava/lang/Class;)Ljava/lang/Object; + public final fun setValue (Ljava/lang/String;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext; + public final fun target (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;)Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience; + public fun text (Ljava/lang/String;)Ljava/lang/String; + public final fun undoMark ()I + public final fun updatePlaceholder (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object; + public fun value (Ljava/lang/String;)Ljava/lang/Object; + public final fun values ()Ljava/util/Map; } -public abstract class org/pnfolder/pnlibrary/api/placeholders/tree/BranchScope { - public final fun bool (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V - public static synthetic fun bool$default (Lorg/pnfolder/pnlibrary/api/placeholders/tree/BranchScope;Ljava/lang/String;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V - public final fun choice (Ljava/lang/String;[Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V - public final fun getBool ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; - public final fun getInt ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; - public final fun getNumber ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; - public final fun getText ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType; - public final fun int (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V - public static synthetic fun int$default (Lorg/pnfolder/pnlibrary/api/placeholders/tree/BranchScope;Ljava/lang/String;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V - public final fun number (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V - public static synthetic fun number$default (Lorg/pnfolder/pnlibrary/api/placeholders/tree/BranchScope;Ljava/lang/String;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V - public final fun param (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType;Lkotlin/jvm/functions/Function1;)V - public final fun param (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/placeholders/tree/ArgType;Lkotlin/ranges/IntRange;Lkotlin/jvm/functions/Function1;)V - public final fun player (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V - public final fun text (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V - public static synthetic fun text$default (Lorg/pnfolder/pnlibrary/api/placeholders/tree/BranchScope;Ljava/lang/String;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V - public final fun value (Ljava/lang/String;Ljava/lang/Class;Lkotlin/jvm/functions/Function1;)V - public static synthetic fun value$default (Lorg/pnfolder/pnlibrary/api/placeholders/tree/BranchScope;Ljava/lang/String;Ljava/lang/Class;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V +public abstract interface class org/pnfolder/pnlibrary/api/scenario/actions/ActionResult { } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/FormatScope { - public fun (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService;)V - public final fun getService ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService; +public final class org/pnfolder/pnlibrary/api/scenario/actions/ActionResult$Done : org/pnfolder/pnlibrary/api/scenario/actions/ActionResult { + public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult$Done; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/Generated { - public final fun exclude ([Lkotlin/reflect/KProperty1;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/Generated; - public final fun only ([Lkotlin/reflect/KProperty1;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/Generated; - public final fun rename (Lkotlin/reflect/KProperty1;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/Generated; +public final class org/pnfolder/pnlibrary/api/scenario/actions/ActionResult$Failed : org/pnfolder/pnlibrary/api/scenario/actions/ActionResult { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/Throwable; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult$Failed; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult$Failed;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult$Failed; + public fun equals (Ljava/lang/Object;)Z + public final fun getCause ()Ljava/lang/Throwable; + public final fun getCode ()Ljava/lang/String; + public final fun getMessage ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/GroupScope : org/pnfolder/pnlibrary/api/placeholders/tree/BranchScope { - public final fun access (Lkotlin/jvm/functions/Function1;)V - public final fun format (Ljava/lang/String;)V - public final fun format (Lorg/pnfolder/pnlibrary/api/placeholders/tree/none;)V +public final class org/pnfolder/pnlibrary/api/scenario/actions/ActionResult$Stopped : org/pnfolder/pnlibrary/api/scenario/actions/ActionResult { + public fun ()V + public fun (Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult$Stopped; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult$Stopped;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult$Stopped; + public fun equals (Ljava/lang/Object;)Z + public final fun getReason ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/GroupScopeKt { - public static final fun placeholders (Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext;Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V - public static synthetic fun placeholders$default (Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext;Ljava/lang/String;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)V +public abstract interface class org/pnfolder/pnlibrary/api/scenario/actions/ActionService { + public abstract fun context (Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer;Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext; + public static synthetic fun context$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionService;Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer;Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext; + public abstract fun define (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/actions/Action;Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope;Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionConflict;)Ljava/lang/AutoCloseable; + public static synthetic fun define$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionService;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/actions/Action;Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope;Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionConflict;ILjava/lang/Object;)Ljava/lang/AutoCloseable; + public abstract fun defineFunction (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/expression/ExpressionFunction;Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope;Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionConflict;)Ljava/lang/AutoCloseable; + public static synthetic fun defineFunction$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionService;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/expression/ExpressionFunction;Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope;Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionConflict;ILjava/lang/Object;)Ljava/lang/AutoCloseable; + public abstract fun defineRequirement (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope;Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionConflict;)Ljava/lang/AutoCloseable; + public static synthetic fun defineRequirement$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionService;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope;Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionConflict;ILjava/lang/Object;)Ljava/lang/AutoCloseable; + public fun execute (Ljava/util/List;Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer;Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public static synthetic fun execute$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionService;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer;Lorg/pnfolder/pnlibrary/api/audiences/LibraryAudience;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/ModuleFormatsKt { - public static final fun formats (Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext;Lkotlin/jvm/functions/Function1;)V +public final class org/pnfolder/pnlibrary/api/scenario/actions/ActionTarget : java/lang/Enum { + public static final field ALL_PLAYERS Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget; + public static final field PLAYER Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget; } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/NodeScope : org/pnfolder/pnlibrary/api/placeholders/tree/BranchScope { - public final fun access (Lkotlin/jvm/functions/Function1;)V - public final fun format (Ljava/lang/String;)V - public final fun format (Lorg/pnfolder/pnlibrary/api/placeholders/tree/none;)V - public final fun inside ()V - public final fun update (Lorg/pnfolder/pnlibrary/api/placeholders/tree/AccessRule;Lkotlin/jvm/functions/Function2;)V - public final fun value (Lkotlin/jvm/functions/Function1;)V - public final fun valueAsync (Lkotlin/jvm/functions/Function1;)V +public final class org/pnfolder/pnlibrary/api/scenario/actions/DefinitionConflict : java/lang/Enum { + public static final field FAIL Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionConflict; + public static final field KEEP Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionConflict; + public static final field REPLACE Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionConflict; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionConflict; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionConflict; } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderCall { - public final fun argOf (Ljava/lang/String;)Ljava/lang/Object; - public final fun getArg ()Ljava/lang/Object; - public final fun getCaller ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public final fun getPlayer ()Ljava/util/UUID; - public final fun getRequest ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderRequest; - public final fun getValues ()Ljava/util/Map; +public final class org/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope : java/lang/Enum { + public static final field LIBRARY Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope; + public static final field MODULE Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope; } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderGenerationKt { - public static final fun generateFrom (Lorg/pnfolder/pnlibrary/api/placeholders/tree/BranchScope;Ljava/lang/String;Ljava/lang/Class;Ljava/lang/String;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/Generated; - public static final fun placesOf (Lorg/pnfolder/pnlibrary/api/placeholders/tree/BranchScope;Ljava/lang/String;Ljava/lang/Class;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function2;)V - public static final fun tableOf (Lorg/pnfolder/pnlibrary/api/placeholders/tree/BranchScope;Ljava/lang/String;Ljava/lang/Class;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function2;)V +public abstract interface class org/pnfolder/pnlibrary/api/scenario/actions/ScenarioLookup { + public static final field Companion Lorg/pnfolder/pnlibrary/api/scenario/actions/ScenarioLookup$Companion; + public static final field NONE Lorg/pnfolder/pnlibrary/api/scenario/actions/ScenarioLookup; + public fun action (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/actions/Action; + public fun function (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/expression/ExpressionFunction; + public fun requirement (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement; } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderRulesKt { - public static final fun allowAll ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/AccessRule; - public static final fun allowOnly ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/AccessRule; - public static final fun deny ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/placeholders/tree/AccessRule; - public static final fun denyAll ()Lorg/pnfolder/pnlibrary/api/placeholders/tree/AccessRule; +public final class org/pnfolder/pnlibrary/api/scenario/actions/ScenarioLookup$Companion { } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/PlayerArg { - public fun (Ljava/lang/String;)V - public final fun getId ()Ljava/util/UUID; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/ActionBarAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;)V + public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public final fun component3 ()Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget; + public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/ActionBarAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/ActionBarAction;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/ActionBarAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getSerializerType ()Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public final fun getTarget ()Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget; public final fun getText ()Ljava/lang/String; + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/placeholders/tree/none { - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/placeholders/tree/none; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/AttemptAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/util/List;Ljava/util/List;Ljava/util/List;ZZ)V + public synthetic fun (Ljava/util/List;Ljava/util/List;Ljava/util/List;ZZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/util/List; + public final fun component2 ()Ljava/util/List; + public final fun component3 ()Ljava/util/List; + public final fun component4 ()Z + public final fun component5 ()Z + public final fun copy (Ljava/util/List;Ljava/util/List;Ljava/util/List;ZZ)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/AttemptAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/AttemptAction;Ljava/util/List;Ljava/util/List;Ljava/util/List;ZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/AttemptAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getFail ()Ljava/util/List; + public final fun getHandlers ()Ljava/util/List; + public final fun getResume ()Z + public final fun getSteps ()Ljava/util/List; + public final fun getUndo ()Z + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/platform/PlatformProvider { - public abstract fun get (Ljava/lang/Class;)Ljava/lang/Object; - public abstract fun require (Ljava/lang/Class;)Ljava/lang/Object; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/CallAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public static final field Companion Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CallAction$Companion; + public static final field MAX_DEPTH I + public fun ()V + public fun (Ljava/lang/String;Ljava/util/Map;)V + public synthetic fun (Ljava/lang/String;Ljava/util/Map;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/util/Map; + public final fun copy (Ljava/lang/String;Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CallAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CallAction;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CallAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getArgs ()Ljava/util/Map; + public final fun getName ()Ljava/lang/String; + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/platform/PlatformType : java/lang/Enum { - public static final field BUKKIT Lorg/pnfolder/pnlibrary/api/platform/PlatformType; - public static final field BUNGEECORD Lorg/pnfolder/pnlibrary/api/platform/PlatformType; - public static final field UNIVERSAL Lorg/pnfolder/pnlibrary/api/platform/PlatformType; - public static final field VELOCITY Lorg/pnfolder/pnlibrary/api/platform/PlatformType; - public final fun getDisplayName ()Ljava/lang/String; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public final fun getId ()Ljava/lang/String; - public final fun isProxy ()Z - public final fun isServer ()Z - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/platform/PlatformType; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/platform/PlatformType; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/CallAction$Companion { } -public final class org/pnfolder/pnlibrary/api/plugin/LifecycleRow : java/lang/Enum { - public static final field DIAGNOSTICS Lorg/pnfolder/pnlibrary/api/plugin/LifecycleRow; - public static final field IDENTIFIER Lorg/pnfolder/pnlibrary/api/plugin/LifecycleRow; - public static final field METRICS Lorg/pnfolder/pnlibrary/api/plugin/LifecycleRow; - public static final field NOT_CONFIGURED Lorg/pnfolder/pnlibrary/api/plugin/LifecycleRow; - public static final field PLACEHOLDER_API Lorg/pnfolder/pnlibrary/api/plugin/LifecycleRow; - public static final field PLATFORM Lorg/pnfolder/pnlibrary/api/plugin/LifecycleRow; - public static final field RESOURCES Lorg/pnfolder/pnlibrary/api/plugin/LifecycleRow; - public static final field UPDATES Lorg/pnfolder/pnlibrary/api/plugin/LifecycleRow; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandRunner;)V + public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandRunner;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandRunner; + public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandRunner;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandAction;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandRunner;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getCommand ()Ljava/lang/String; + public final fun getRunner ()Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandRunner; + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandRunner : java/lang/Enum { + public static final field CONSOLE Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandRunner; + public static final field PLAYER Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandRunner; public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/LifecycleRow; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/plugin/LifecycleRow; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandRunner; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/CommandRunner; } -public abstract interface class org/pnfolder/pnlibrary/api/plugin/ModuleContext : java/lang/AutoCloseable { - public abstract fun close ()V - public abstract fun getActions ()Lorg/pnfolder/pnlibrary/api/actions/ActionService; - public abstract fun getComponents ()Lorg/pnfolder/pnlibrary/api/text/ComponentService; - public abstract fun getConfigs ()Lorg/pnfolder/pnlibrary/api/config/ConfigScope; - public abstract fun getCooldowns ()Lorg/pnfolder/pnlibrary/api/cooldowns/CooldownService; - public abstract fun getDiagnostics ()Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticRegistration; - public abstract fun getDownloads ()Lorg/pnfolder/pnlibrary/api/downloads/DownloadRegistration; - public abstract fun getErrors ()Lorg/pnfolder/pnlibrary/api/metrics/ErrorReporter; - public abstract fun getEvents ()Lorg/pnfolder/pnlibrary/api/events/EventScope; - public fun getExpansions ()Lorg/pnfolder/pnlibrary/api/expansions/ExpansionManager; - public abstract fun getId ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; - public abstract fun getKey ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; - public abstract fun getLifecycle ()Lorg/pnfolder/pnlibrary/api/plugin/PluginLifecycle; - public fun getLocalization ()Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization; - public abstract fun getLogger ()Lorg/pnfolder/pnlibrary/api/logging/PnLogger; - public abstract fun getMessages ()Lorg/pnfolder/pnlibrary/api/plugin/PluginMessages; - public abstract fun getMetadata ()Lorg/pnfolder/pnlibrary/api/plugin/PluginMetadata; - public abstract fun getMetrics ()Lorg/pnfolder/pnlibrary/api/metrics/MetricsController; - public abstract fun getPlaceholders ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderService; - public abstract fun getServices ()Lorg/pnfolder/pnlibrary/api/services/ServiceManager; - public abstract fun getTasks ()Lorg/pnfolder/pnlibrary/api/tasks/TaskScope; - public abstract fun getUpdates ()Lorg/pnfolder/pnlibrary/api/updates/UpdateRegistration; - public abstract fun isClosed ()Z - public fun onCommandError (Ljava/lang/Class;Ljava/lang/String;)V - public fun onCommandError (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/commands/CommandErrorHandler;)V - public fun registerCommand (Ljava/lang/String;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/commands/CommandRegistration; - public fun registerCommand (Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition;)Lorg/pnfolder/pnlibrary/api/commands/CommandRegistration; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/DelayAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/time/Duration;Ljava/util/List;)V + public synthetic fun (Ljava/time/Duration;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/time/Duration; + public final fun component2 ()Ljava/util/List; + public final fun copy (Ljava/time/Duration;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/DelayAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/DelayAction;Ljava/time/Duration;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/DelayAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getAfter ()Ljava/time/Duration; + public final fun getSteps ()Ljava/util/List; + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/EffectAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/lang/String;Ljava/time/Duration;IZZZ)V + public synthetic fun (Ljava/lang/String;Ljava/time/Duration;IZZZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/time/Duration; + public final fun component3 ()I + public final fun component4 ()Z + public final fun component5 ()Z + public final fun component6 ()Z + public final fun copy (Ljava/lang/String;Ljava/time/Duration;IZZZ)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/EffectAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/EffectAction;Ljava/lang/String;Ljava/time/Duration;IZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/EffectAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getAmbient ()Z + public final fun getAmplifier ()I + public final fun getDuration ()Ljava/time/Duration; + public final fun getIcon ()Z + public final fun getKey ()Ljava/lang/String; + public final fun getParticles ()Z + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/plugin/ModuleId { - public static final field Companion Lorg/pnfolder/pnlibrary/api/plugin/ModuleId$Companion; - public synthetic fun (Ljava/lang/String;Lkotlin/jvm/internal/DefaultConstructorMarker;)V +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/ErrorHandler { + public fun ()V + public fun (Ljava/util/List;Ljava/util/List;)V + public synthetic fun (Ljava/util/List;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/util/List; + public final fun component2 ()Ljava/util/List; + public final fun copy (Ljava/util/List;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/ErrorHandler; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/ErrorHandler;Ljava/util/List;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/ErrorHandler; public fun equals (Ljava/lang/Object;)Z - public final fun getValue ()Ljava/lang/String; + public final fun getCodes ()Ljava/util/List; + public final fun getSteps ()Ljava/util/List; public fun hashCode ()I - public static final fun of (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public final fun matches (Ljava/lang/String;)Z public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/plugin/ModuleId$Companion { - public final fun of (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; -} - -public abstract interface class org/pnfolder/pnlibrary/api/plugin/PluginBuilder { - public fun dependencies (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public abstract fun depends (Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public fun depends ([Lorg/pnfolder/pnlibrary/api/dependencies/PluginDependency;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public abstract fun diagnostics (Ljava/nio/file/Path;Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public fun downloads (Ljava/nio/file/Path;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public fun downloads (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public abstract fun downloads (Lorg/pnfolder/pnlibrary/api/downloads/FileDownloads;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public abstract fun metadata (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public abstract fun metrics (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public abstract fun options (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public abstract fun product (Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public abstract fun remotePolicy (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public fun updates (Ljava/lang/String;Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public fun updates (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; - public abstract fun updates (Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest;)Lorg/pnfolder/pnlibrary/api/plugin/PluginBuilder; -} - -public abstract interface class org/pnfolder/pnlibrary/api/plugin/PluginLifecycle { - public abstract fun disabled ()Lorg/pnfolder/pnlibrary/api/logging/MessageBox; - public abstract fun enabled ()Lorg/pnfolder/pnlibrary/api/logging/MessageBox; - public abstract fun getMetadata ()Lorg/pnfolder/pnlibrary/api/plugin/PluginMetadata; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/IfAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;Ljava/util/List;Ljava/util/List;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;Ljava/util/List;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement; + public final fun component2 ()Ljava/util/List; + public final fun component3 ()Ljava/util/List; + public final fun copy (Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;Ljava/util/List;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/IfAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/IfAction;Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;Ljava/util/List;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/IfAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getElseActions ()Ljava/util/List; + public final fun getRequirement ()Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement; + public final fun getThenActions ()Ljava/util/List; + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/plugin/PluginMessages { - public abstract fun box (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/logging/MessageBox; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/LogAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/logging/LogLevel;)V + public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/logging/LogLevel;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/logging/LogLevel; + public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/logging/LogLevel;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/LogAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/LogAction;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/logging/LogLevel;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/LogAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getLevel ()Lorg/pnfolder/pnlibrary/api/logging/LogLevel; + public final fun getText ()Ljava/lang/String; + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/plugin/PluginMetadata { - public fun (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;Ljava/lang/String;Ljava/lang/String;I)V - public final fun getAuthors ()Ljava/lang/String; - public final fun getId ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; - public final fun getJavaFeature ()I - public final fun getJavaVersion ()Ljava/lang/String; - public final fun getName ()Ljava/lang/String; - public final fun getPlatform ()Lorg/pnfolder/pnlibrary/api/platform/PlatformType; - public final fun getPlatformImplementation ()Ljava/lang/String; - public final fun getVersion ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/MessageAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/util/List;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;)V + public synthetic fun (Ljava/util/List;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/util/List; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public final fun component3 ()Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget; + public final fun copy (Ljava/util/List;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/MessageAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/MessageAction;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/MessageAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getMessages ()Ljava/util/List; + public final fun getSerializerType ()Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public final fun getTarget ()Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget; + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/plugin/PluginMetadataBuilder { - public abstract fun authors (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/PluginMetadataBuilder; - public abstract fun name (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/PluginMetadataBuilder; - public abstract fun version (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/PluginMetadataBuilder; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/ParticleAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/lang/String;IDDDD)V + public synthetic fun (Ljava/lang/String;IDDDDILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()I + public final fun component3 ()D + public final fun component4 ()D + public final fun component5 ()D + public final fun component6 ()D + public final fun copy (Ljava/lang/String;IDDDD)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/ParticleAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/ParticleAction;Ljava/lang/String;IDDDDILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/ParticleAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getCount ()I + public final fun getKey ()Ljava/lang/String; + public final fun getOffsetX ()D + public final fun getOffsetY ()D + public final fun getOffsetZ ()D + public final fun getSpeed ()D + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/plugin/PluginOptions { - public abstract fun placeholderApi (Z)Lorg/pnfolder/pnlibrary/api/plugin/PluginOptions; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/RandomAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/util/List;)V + public synthetic fun (Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/util/List; + public final fun copy (Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RandomAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RandomAction;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RandomAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getOptions ()Ljava/util/List; + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/plugin/PluginRegistration : java/lang/AutoCloseable { - public abstract fun all ()Ljava/util/List; - public abstract fun close ()V - public fun getModule (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; - public abstract fun getModule (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; - public abstract fun getOwner ()Ljava/lang/Object; - public abstract fun isClosed ()Z - public fun onCommandError (Ljava/lang/Class;Ljava/lang/String;)V - public fun onCommandError (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/commands/CommandErrorHandler;)V - public fun registerModule (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; - public abstract fun registerModule (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; - public static synthetic fun registerModule$default (Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration;Ljava/lang/String;Ljava/util/function/Consumer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; - public static synthetic fun registerModule$default (Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Ljava/util/function/Consumer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; - public fun requireModule (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; - public fun requireModule (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleContext; - public fun unregisterModule (Ljava/lang/String;)V - public abstract fun unregisterModule (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)V +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/RandomOption { + public fun ()V + public fun (DLjava/util/List;)V + public synthetic fun (DLjava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()D + public final fun component2 ()Ljava/util/List; + public final fun copy (DLjava/util/List;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RandomOption; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RandomOption;DLjava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RandomOption; + public fun equals (Ljava/lang/Object;)Z + public final fun getSteps ()Ljava/util/List; + public final fun getWeight ()D + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/plugin/PluginRegistry : java/lang/AutoCloseable { - public abstract fun all ()Ljava/util/List; - public abstract fun close ()V - public abstract fun get (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration; - public abstract fun register (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration; - public fun require (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistration; - public abstract fun unregister (Ljava/lang/Object;)V +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/RepeatAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public static final field Companion Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RepeatAction$Companion; + public static final field MAX_TIMES I + public fun ()V + public fun (ILjava/time/Duration;Ljava/util/List;)V + public synthetic fun (ILjava/time/Duration;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()I + public final fun component2 ()Ljava/time/Duration; + public final fun component3 ()Ljava/util/List; + public final fun copy (ILjava/time/Duration;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RepeatAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RepeatAction;ILjava/time/Duration;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RepeatAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getEvery ()Ljava/time/Duration; + public final fun getSteps ()Ljava/util/List; + public final fun getTimes ()I + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/remote/DenyAction : java/lang/Enum { - public static final field DISABLE_MODULE Lorg/pnfolder/pnlibrary/api/remote/DenyAction; - public static final field DISABLE_PLUGIN Lorg/pnfolder/pnlibrary/api/remote/DenyAction; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/DenyAction; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/remote/DenyAction; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/RepeatAction$Companion { } -public final class org/pnfolder/pnlibrary/api/remote/PlatformInfo { - public fun (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;Ljava/lang/String;Ljava/lang/String;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/platform/PlatformType; - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Ljava/lang/String; - public final fun copy (Lorg/pnfolder/pnlibrary/api/platform/PlatformType;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/PlatformInfo; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/remote/PlatformInfo;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/remote/PlatformInfo; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/RequireAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;Ljava/util/List;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement; + public final fun component2 ()Ljava/util/List; + public final fun copy (Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RequireAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RequireAction;Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/RequireAction; public fun equals (Ljava/lang/Object;)Z - public final fun getKey ()Ljava/lang/String; - public final fun getName ()Ljava/lang/String; - public final fun getType ()Lorg/pnfolder/pnlibrary/api/platform/PlatformType; - public final fun getVersion ()Ljava/lang/String; + public final fun getDeny ()Ljava/util/List; + public final fun getRequirement ()Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement; public fun hashCode ()I - public final fun isNamed (Ljava/lang/String;)Z + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/remote/PolicyErrorAction : java/lang/Enum { - public static final field DENY Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; - public static final field DENY_UNTIL_CHECKED Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; - public static final field KEEP_RUNNING Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; -} - -public final class org/pnfolder/pnlibrary/api/remote/ProductInfo { +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/SetAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Ljava/lang/String; public final fun component2 ()Ljava/lang/String; public final fun component3 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/ProductInfo; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/remote/ProductInfo;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/remote/ProductInfo; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/SetAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/SetAction;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/SetAction; public fun equals (Ljava/lang/Object;)Z - public final fun getId ()Ljava/lang/String; + public final fun getExpression ()Ljava/lang/String; public final fun getName ()Ljava/lang/String; - public final fun getVersion ()Ljava/lang/String; + public final fun getValue ()Ljava/lang/String; public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/remote/RemotePolicy { - public abstract fun check (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/SoundAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/lang/String;Lnet/kyori/adventure/sound/Sound$Source;FFLorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;)V + public synthetic fun (Ljava/lang/String;Lnet/kyori/adventure/sound/Sound$Source;FFLorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Lnet/kyori/adventure/sound/Sound$Source; + public final fun component3 ()F + public final fun component4 ()F + public final fun component5 ()Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget; + public final fun copy (Ljava/lang/String;Lnet/kyori/adventure/sound/Sound$Source;FFLorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/SoundAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/SoundAction;Ljava/lang/String;Lnet/kyori/adventure/sound/Sound$Source;FFLorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/SoundAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getKey ()Ljava/lang/String; + public final fun getPitch ()F + public final fun getSource ()Lnet/kyori/adventure/sound/Sound$Source; + public final fun getTarget ()Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget; + public final fun getVolume ()F + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyContext { - public static final field Companion Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Companion; - public synthetic fun (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun builder ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; - public final fun getPlatform ()Lorg/pnfolder/pnlibrary/api/remote/PlatformInfo; - public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/remote/ProductInfo; - public final fun getServer ()Lorg/pnfolder/pnlibrary/api/remote/ServerInfo; - public final fun getValues ()Ljava/util/Map; - public final fun nativeHandle (Ljava/lang/Class;)Ljava/lang/Object; - public final fun requireNative (Ljava/lang/Class;)Ljava/lang/Object; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/StopAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/StopAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/StopAction;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/StopAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getReason ()Ljava/lang/String; + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder { - public final fun build ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext; - public final fun nativeHandle (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; - public final fun platform (Lorg/pnfolder/pnlibrary/api/remote/PlatformInfo;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; - public final fun product (Lorg/pnfolder/pnlibrary/api/remote/ProductInfo;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; - public final fun server (Lorg/pnfolder/pnlibrary/api/remote/ServerInfo;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; - public final fun value (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; - public final fun values (Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; +public final class org/pnfolder/pnlibrary/api/scenario/actions/builtin/TitleAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/time/Duration; + public final fun component4 ()Ljava/time/Duration; + public final fun component5 ()Ljava/time/Duration; + public final fun component6 ()Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public final fun component7 ()Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/TitleAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/TitleAction;Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/actions/builtin/TitleAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getFadeIn ()Ljava/time/Duration; + public final fun getFadeOut ()Ljava/time/Duration; + public final fun getSerializerType ()Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public final fun getStay ()Ljava/time/Duration; + public final fun getSubtitle ()Ljava/lang/String; + public final fun getTarget ()Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionTarget; + public final fun getTitle ()Ljava/lang/String; + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Companion { - public final fun builder ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyContext$Builder; +public final class org/pnfolder/pnlibrary/api/scenario/expression/Expression { + public static final field Companion Lorg/pnfolder/pnlibrary/api/scenario/expression/Expression$Companion; + public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/expression/Expression$Node;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun evaluate (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Ljava/lang/Object; + public static final fun format (Ljava/lang/Object;)Ljava/lang/String; + public final fun getSource ()Ljava/lang/String; + public static final fun isBuiltin (Ljava/lang/String;)Z + public static final fun parse (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/expression/Expression; + public final fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Z + public final fun text (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Ljava/lang/String; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation { - public static final field Companion Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Companion; - public synthetic fun (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder; - public final fun getChildren ()Ljava/util/List; - public final fun getText ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/scenario/expression/Expression$Companion { + public final fun format (Ljava/lang/Object;)Ljava/lang/String; + public final fun isBuiltin (Ljava/lang/String;)Z + public final fun parse (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/expression/Expression; } -public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder { - public final fun branch (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder; - public final fun build ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation; - public final fun child (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder; - public final fun child (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder; +public final class org/pnfolder/pnlibrary/api/scenario/expression/ExpressionException : java/lang/IllegalArgumentException { + public fun (Ljava/lang/String;)V } -public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Companion { - public final fun builder (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation$Builder; +public abstract interface class org/pnfolder/pnlibrary/api/scenario/expression/ExpressionFunction { + public abstract fun call (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;Ljava/util/List;)Ljava/lang/Object; } -public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyResult { - public static final field Companion Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Companion; - public synthetic fun (ZLorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation;Ljava/lang/String;Ljava/lang/String;Ljava/util/Map;Ljava/util/List;Ljava/util/Map;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun allow ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; - public static final fun allowing (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; - public static final fun deny (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; - public static final fun deny (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; - public static final fun denying (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; - public final fun getAllowed ()Z - public final fun getDetails ()Ljava/util/Map; - public final fun getExplanation ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation; - public final fun getHeadline ()Ljava/lang/String; - public final fun getLinks ()Ljava/util/Map; - public final fun getMessage ()Ljava/lang/String; - public final fun getStatus ()Ljava/lang/String; - public final fun getSteps ()Ljava/util/List; +public abstract interface class org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { + public abstract fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; +} + +public abstract interface class org/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext { + public fun function (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/expression/ExpressionFunction; + public abstract fun getLogger ()Lorg/pnfolder/pnlibrary/api/logging/PnLogger; + public abstract fun getPlayer ()Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer; + public abstract fun read (Ljava/lang/String;)Ljava/lang/Object; + public fun requirement (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement; + public abstract fun service (Ljava/lang/Class;)Ljava/lang/Object; + public abstract fun text (Ljava/lang/String;)Ljava/lang/String; + public abstract fun value (Ljava/lang/String;)Ljava/lang/Object; } -public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder { - public final fun build ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; - public final fun detail (Ljava/lang/String;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; - public final fun headline (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; - public final fun link (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; - public final fun reason (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; - public final fun reason (Ljava/lang/String;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; - public final fun status (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; - public final fun step (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; +public abstract interface class org/pnfolder/pnlibrary/api/scenario/requirements/Verdict { + public static final field Companion Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict$Companion; + public fun isMet ()Z + public static fun of (ZLjava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; } -public final class org/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Companion { - public final fun allow ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; - public final fun allowing (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; - public final fun deny (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; - public final fun deny (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult; - public final fun denying (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicyResult$Builder; +public final class org/pnfolder/pnlibrary/api/scenario/requirements/Verdict$Companion { + public final fun of (ZLjava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; } -public final class org/pnfolder/pnlibrary/api/remote/RemotePolicySettings { - public static final field Companion Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Companion; - public fun (Ljava/lang/String;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/remote/DenyAction;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction;Ljava/lang/String;Ljava/time/Duration;)V - public synthetic fun (Ljava/lang/String;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/remote/DenyAction;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction;Ljava/lang/String;Ljava/time/Duration;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun builder ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; +public final class org/pnfolder/pnlibrary/api/scenario/requirements/Verdict$Met : org/pnfolder/pnlibrary/api/scenario/requirements/Verdict { + public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict$Met; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/scenario/requirements/Verdict$Unmet : org/pnfolder/pnlibrary/api/scenario/requirements/Verdict { + public fun (Ljava/lang/String;)V public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/time/Duration; - public final fun component3 ()Lorg/pnfolder/pnlibrary/api/remote/DenyAction; - public final fun component4 ()Ljava/util/Map; - public final fun component5 ()Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; - public final fun component6 ()Ljava/lang/String; - public final fun component7 ()Ljava/time/Duration; - public final fun copy (Ljava/lang/String;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/remote/DenyAction;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction;Ljava/lang/String;Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings;Ljava/lang/String;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/remote/DenyAction;Ljava/util/Map;Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction;Ljava/lang/String;Ljava/time/Duration;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings; + public final fun copy (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict$Unmet; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict$Unmet;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict$Unmet; public fun equals (Ljava/lang/Object;)Z - public final fun getCheckEvery ()Ljava/time/Duration; - public final fun getOnDeny ()Lorg/pnfolder/pnlibrary/api/remote/DenyAction; - public final fun getOnError ()Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction; - public final fun getSource ()Ljava/lang/String; - public final fun getStartupTimeout ()Ljava/time/Duration; - public final fun getSupportUrl ()Ljava/lang/String; - public final fun getValues ()Ljava/util/Map; + public final fun getReason ()Ljava/lang/String; public fun hashCode ()I public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder { - public final fun build ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings; - public final fun checkEvery (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; - public final fun onDeny (Lorg/pnfolder/pnlibrary/api/remote/DenyAction;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; - public final fun onError (Lorg/pnfolder/pnlibrary/api/remote/PolicyErrorAction;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; - public final fun source (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; - public final fun startupTimeout (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; - public final fun support (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; - public final fun value (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; - public final fun values (Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; +public final class org/pnfolder/pnlibrary/api/scenario/requirements/builtin/AllRequirement : org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { + public fun ()V + public fun (Ljava/util/List;)V + public synthetic fun (Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/util/List; + public final fun copy (Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/AllRequirement; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/AllRequirement;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/AllRequirement; + public fun equals (Ljava/lang/Object;)Z + public final fun getRequirements ()Ljava/util/List; + public fun hashCode ()I + public fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Companion { - public final fun builder ()Lorg/pnfolder/pnlibrary/api/remote/RemotePolicySettings$Builder; +public final class org/pnfolder/pnlibrary/api/scenario/requirements/builtin/AnyRequirement : org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { + public fun ()V + public fun (Ljava/util/List;)V + public synthetic fun (Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/util/List; + public final fun copy (Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/AnyRequirement; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/AnyRequirement;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/AnyRequirement; + public fun equals (Ljava/lang/Object;)Z + public final fun getRequirements ()Ljava/util/List; + public fun hashCode ()I + public fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/remote/ServerInfo { - public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersionInfo;)V +public final class org/pnfolder/pnlibrary/api/scenario/requirements/builtin/ChanceRequirement : org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { + public fun ()V + public fun (D)V + public synthetic fun (DILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()D + public final fun copy (D)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/ChanceRequirement; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/ChanceRequirement;DILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/ChanceRequirement; + public fun equals (Ljava/lang/Object;)Z + public final fun getProbability ()D + public fun hashCode ()I + public fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator : java/lang/Enum { + public static final field CONTAINS Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public static final field ENDS_WITH Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public static final field EQUALS Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public static final field GREATER Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public static final field GREATER_OR_EQUAL Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public static final field LESS Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public static final field LESS_OR_EQUAL Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public static final field MATCHES Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public static final field NOT_EQUALS Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public static final field STARTS_WITH Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; +} + +public final class org/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareRequirement : org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { + public fun ()V + public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator;Ljava/lang/String;Z)V + public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator;Ljava/lang/String;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersionInfo; - public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersionInfo;)Lorg/pnfolder/pnlibrary/api/remote/ServerInfo; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/remote/ServerInfo;Ljava/lang/String;Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersionInfo;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/remote/ServerInfo; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Z + public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareRequirement; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareRequirement;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator;Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareRequirement; public fun equals (Ljava/lang/Object;)Z - public final fun getMinecraft ()Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersionInfo; - public final fun getMinecraftVersion ()Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersion; - public final fun getVersion ()Ljava/lang/String; + public final fun getIgnoreCase ()Z + public final fun getLeft ()Ljava/lang/String; + public final fun getOperator ()Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/CompareOperator; + public final fun getRight ()Ljava/lang/String; public fun hashCode ()I + public fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; public fun toString ()Ljava/lang/String; } -public abstract interface class org/pnfolder/pnlibrary/api/runtime/PnLibrary : java/io/Closeable { - public abstract fun close ()V - public abstract fun createDiagnosticReport (Lorg/pnfolder/pnlibrary/api/diagnostics/DebugRequest;)Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticReport; - public abstract fun getActivity ()Lorg/pnfolder/pnlibrary/api/activity/ActivityService; - public abstract fun getAudiences ()Lorg/pnfolder/pnlibrary/api/audiences/AudienceService; - public abstract fun getConfiguration ()Lorg/pnfolder/pnlibrary/api/runtime/PnLibraryConfig; - public abstract fun getConfigurations ()Lorg/pnfolder/pnlibrary/api/config/ConfigurationService; - public abstract fun getDiagnostics ()Lorg/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService; - public abstract fun getEvents ()Lorg/pnfolder/pnlibrary/api/events/EventService; - public abstract fun getExpansions ()Lorg/pnfolder/pnlibrary/api/expansions/ExpansionManager; - public abstract fun getLogging ()Lorg/pnfolder/pnlibrary/api/logging/LoggingService; - public abstract fun getMetrics ()Lorg/pnfolder/pnlibrary/api/metrics/MetricsService; - public abstract fun getObservability ()Lorg/pnfolder/pnlibrary/api/observability/ObservabilityService; - public abstract fun getOwner ()Ljava/lang/Object; - public abstract fun getPlaceholderAdapters ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterRegistry; - public abstract fun getPlaceholderValues ()Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderValueStore; - public abstract fun getPlatforms ()Lorg/pnfolder/pnlibrary/api/platform/PlatformProvider; - public abstract fun getPlugins ()Lorg/pnfolder/pnlibrary/api/plugin/PluginRegistry; - public abstract fun getServices ()Lorg/pnfolder/pnlibrary/api/services/ServiceManager; - public abstract fun getUpdates ()Lorg/pnfolder/pnlibrary/api/updates/UpdateService; - public abstract fun getVersion ()Ljava/lang/String; - public abstract fun isAtLeastVersion (Ljava/lang/String;)Z - public abstract fun isClosed ()Z +public final class org/pnfolder/pnlibrary/api/scenario/requirements/builtin/ExperienceRequirement : org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { + public fun ()V + public fun (IZ)V + public synthetic fun (IZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()I + public final fun component2 ()Z + public final fun copy (IZ)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/ExperienceRequirement; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/ExperienceRequirement;IZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/ExperienceRequirement; + public fun equals (Ljava/lang/Object;)Z + public final fun getAmount ()I + public final fun getLevel ()Z + public fun hashCode ()I + public fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/runtime/PnLibraryConfig { +public final class org/pnfolder/pnlibrary/api/scenario/requirements/builtin/ExpressionRequirement : org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { public fun ()V - public fun (Z)V - public fun (ZLjava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZ)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZ)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZI)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZII)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIII)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;I)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;II)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;III)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIII)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;Z)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZI)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZII)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIII)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;Z)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V - public fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)V - public synthetic fun (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Z - public final fun component10 ()Z - public final fun component11 ()I - public final fun component12 ()I - public final fun component13 ()I - public final fun component14 ()Ljava/time/Duration; - public final fun component15 ()I - public final fun component16 ()I - public final fun component17 ()I - public final fun component18 ()I - public final fun component19 ()Ljava/util/List; - public final fun component2 ()Ljava/lang/String; - public final fun component20 ()Ljava/util/List; - public final fun component21 ()Ljava/util/List; - public final fun component22 ()Z - public final fun component23 ()I - public final fun component24 ()I - public final fun component25 ()I - public final fun component26 ()Ljava/lang/String; - public final fun component27 ()Z - public final fun component28 ()Ljava/lang/String; - public final fun component29 ()Ljava/lang/String; - public final fun component3 ()Ljava/util/List; - public final fun component30 ()Ljava/lang/String; - public final fun component31 ()Ljava/lang/String; - public final fun component32 ()Ljava/lang/String; - public final fun component33 ()Ljava/lang/String; - public final fun component34 ()Ljava/lang/String; - public final fun component35 ()I - public final fun component36 ()I + public fun (Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/ExpressionRequirement; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/ExpressionRequirement;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/ExpressionRequirement; + public fun equals (Ljava/lang/Object;)Z + public final fun getExpression ()Ljava/lang/String; + public fun hashCode ()I + public fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/scenario/requirements/builtin/ItemRequirement : org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { + public fun ()V + public fun (Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V + public synthetic fun (Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()I + public final fun component3 ()Ljava/lang/String; public final fun component4 ()Ljava/lang/String; public final fun component5 ()Ljava/lang/String; - public final fun component6 ()Ljava/lang/String; - public final fun component7 ()Ljava/lang/String; - public final fun component8 ()Z - public final fun component9 ()Z - public final fun copy (ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)Lorg/pnfolder/pnlibrary/api/runtime/PnLibraryConfig; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/runtime/PnLibraryConfig;ZLjava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZIIILjava/time/Duration;IIIILjava/util/List;Ljava/util/List;Ljava/util/List;ZIIILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/runtime/PnLibraryConfig; + public final fun component6 ()Z + public final fun copy (Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/ItemRequirement; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/ItemRequirement;Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/ItemRequirement; public fun equals (Ljava/lang/Object;)Z - public final fun getAllowPlaintext ()Z - public final fun getConfigs ()Z - public final fun getConsoleOnlyMessage ()Ljava/lang/String; - public final fun getCooldown ()Ljava/time/Duration; - public final fun getDeleteAfterDays ()I - public final fun getEventHistoryDays ()I - public final fun getExcludedPaths ()Ljava/util/List; - public final fun getHistoryMaxBytes ()I - public final fun getHistoryRetentionDays ()I - public final fun getInvalidArgumentMessage ()Ljava/lang/String; - public final fun getJournalErrorDays ()I - public final fun getJournalForeignPlugins ()Z - public final fun getJournalInfoDays ()I - public final fun getJournalJoinNoticeHours ()I - public final fun getJournalWarningDays ()I - public final fun getKeepReports ()I - public final fun getLogRecords ()I - public final fun getLogs ()Z - public final fun getMaxReportBytes ()I - public final fun getNoPermissionMessage ()Ljava/lang/String; - public final fun getNoPermissionSound ()Ljava/lang/String; - public final fun getPlayerNotFoundMessage ()Ljava/lang/String; - public final fun getPlayerOnlyMessage ()Ljava/lang/String; - public final fun getPrivacy ()Z - public final fun getRedactValuePatterns ()Ljava/util/List; - public final fun getSecretKeyPatterns ()Ljava/util/List; - public final fun getTaskHistoryCapacity ()I - public final fun getTimeZone ()Ljava/lang/String; - public final fun getUpload ()Z - public final fun getUploadEndpoint ()Ljava/lang/String; - public final fun getUploadKeyId ()Ljava/lang/String; - public final fun getUploadMode ()Ljava/lang/String; - public final fun getUploadProviders ()Ljava/util/List; - public final fun getUploadPublicBase ()Ljava/lang/String; - public final fun getUploadPublicKey ()Ljava/lang/String; - public final fun getUsageMessage ()Ljava/lang/String; + public final fun getAmount ()I + public final fun getIgnoreCase ()Z + public final fun getLoreContains ()Ljava/lang/String; + public final fun getMaterial ()Ljava/lang/String; + public final fun getName ()Ljava/lang/String; + public final fun getNameContains ()Ljava/lang/String; public fun hashCode ()I + public fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/runtime/PnLibraryIdentity { - public static final field AUTHOR Ljava/lang/String; - public static final field DESCRIPTION Ljava/lang/String; - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/runtime/PnLibraryIdentity; - public static final field NAME Ljava/lang/String; - public static final field ORGANIZATION Ljava/lang/String; - public static final field PRODUCT_ID Ljava/lang/String; - public static final field REPOSITORY Ljava/lang/String; - public static final field REPOSITORY_URL Ljava/lang/String; - public static final field SUPPORT_URL Ljava/lang/String; - public static final field VERSION Ljava/lang/String; - public final fun getAUTHORS ()Ljava/util/List; +public final class org/pnfolder/pnlibrary/api/scenario/requirements/builtin/NearRequirement : org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { + public fun ()V + public fun (Ljava/lang/String;D)V + public synthetic fun (Ljava/lang/String;DILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()D + public final fun copy (Ljava/lang/String;D)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/NearRequirement; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/NearRequirement;Ljava/lang/String;DILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/NearRequirement; + public fun equals (Ljava/lang/Object;)Z + public final fun getDistance ()D + public final fun getLocation ()Ljava/lang/String; + public fun hashCode ()I + public fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/scenario/requirements/builtin/NotRequirement : org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { + public fun ()V + public fun (Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement; + public final fun copy (Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/NotRequirement; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/NotRequirement;Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/NotRequirement; + public fun equals (Ljava/lang/Object;)Z + public final fun getRequirement ()Lorg/pnfolder/pnlibrary/api/scenario/requirements/Requirement; + public fun hashCode ()I + public fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/runtime/PnLibraryProvider { - public static final field INSTANCE Lorg/pnfolder/pnlibrary/api/runtime/PnLibraryProvider; - public static final fun clear (Lorg/pnfolder/pnlibrary/api/runtime/PnLibrary;)V - public static final fun get ()Lorg/pnfolder/pnlibrary/api/runtime/PnLibrary; - public static final fun getOrNull ()Lorg/pnfolder/pnlibrary/api/runtime/PnLibrary; - public static final fun install (Lorg/pnfolder/pnlibrary/api/runtime/PnLibrary;)V +public final class org/pnfolder/pnlibrary/api/scenario/requirements/builtin/PermissionRequirement : org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { + public fun ()V + public fun (Ljava/lang/String;Ljava/util/List;Z)V + public synthetic fun (Ljava/lang/String;Ljava/util/List;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/util/List; + public final fun component3 ()Z + public final fun copy (Ljava/lang/String;Ljava/util/List;Z)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/PermissionRequirement; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/PermissionRequirement;Ljava/lang/String;Ljava/util/List;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/PermissionRequirement; + public fun equals (Ljava/lang/Object;)Z + public final fun getAny ()Z + public final fun getPermission ()Ljava/lang/String; + public final fun getPermissions ()Ljava/util/List; + public fun hashCode ()I + public fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/scenario/requirements/builtin/RefRequirement : org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { + public fun ()V + public fun (Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/RefRequirement; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/RefRequirement;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/builtin/RefRequirement; + public fun equals (Ljava/lang/Object;)Z + public final fun getName ()Ljava/lang/String; + public fun hashCode ()I + public fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; + public fun toString ()Ljava/lang/String; } public final class org/pnfolder/pnlibrary/api/security/SecretValue : java/lang/AutoCloseable { @@ -3526,138 +3610,117 @@ public abstract interface class org/pnfolder/pnlibrary/api/services/ServiceManag public abstract fun unregister (Ljava/lang/Class;)V } -public abstract interface class org/pnfolder/pnlibrary/api/tasks/TaskAction { - public abstract fun run (Lorg/pnfolder/pnlibrary/api/tasks/TaskContext;)V -} - -public final class org/pnfolder/pnlibrary/api/tasks/TaskConflictPolicy : java/lang/Enum { - public static final field KEEP_EXISTING Lorg/pnfolder/pnlibrary/api/tasks/TaskConflictPolicy; - public static final field REJECT Lorg/pnfolder/pnlibrary/api/tasks/TaskConflictPolicy; - public static final field REPLACE Lorg/pnfolder/pnlibrary/api/tasks/TaskConflictPolicy; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskConflictPolicy; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/tasks/TaskConflictPolicy; -} - -public abstract interface class org/pnfolder/pnlibrary/api/tasks/TaskContext { - public abstract fun cancel ()V - public abstract fun getId ()Lorg/pnfolder/pnlibrary/api/tasks/TaskId; - public abstract fun getName ()Ljava/lang/String; - public abstract fun getRunNumber ()J - public abstract fun getScheduledAt ()Ljava/time/Instant; - public abstract fun getStartedAt ()Ljava/time/Instant; -} - -public final class org/pnfolder/pnlibrary/api/tasks/TaskExecution { - public static final field Companion Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Companion; - public synthetic fun (Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind;Ljava/lang/Object;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun async ()Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution; - public static final fun entity (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution; - public final fun getKind ()Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind; - public final fun getTarget ()Ljava/lang/Object; - public static final fun global ()Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution; -} - -public final class org/pnfolder/pnlibrary/api/tasks/TaskExecution$Companion { - public final fun async ()Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution; - public final fun entity (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution; - public final fun global ()Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution; -} - -public final class org/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind : java/lang/Enum { - public static final field ASYNC Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind; - public static final field ENTITY Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind; - public static final field GLOBAL Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind; -} - public abstract interface class org/pnfolder/pnlibrary/api/tasks/TaskHandle : java/lang/AutoCloseable { public abstract fun cancel ()V public fun cancelIfActive ()Z public fun close ()V - public abstract fun getId ()Lorg/pnfolder/pnlibrary/api/tasks/TaskId; - public abstract fun getStatus ()Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus; + public abstract fun getId ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; + public abstract fun getStatus ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus; public abstract fun isCancelled ()Z - public abstract fun snapshot ()Lorg/pnfolder/pnlibrary/api/tasks/TaskSnapshot; + public abstract fun snapshot ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskSnapshot; +} + +public abstract interface class org/pnfolder/pnlibrary/api/tasks/TaskScope : java/lang/AutoCloseable { + public fun cancel (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;)Z + public abstract fun cancelAll ()V + public fun close ()V + public abstract fun get (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; + public abstract fun getByKey (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; + public abstract fun getOwner ()Ljava/lang/Object; + public abstract fun query (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery;)Ljava/util/List; + public static synthetic fun query$default (Lorg/pnfolder/pnlibrary/api/tasks/TaskScope;Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery;ILjava/lang/Object;)Ljava/util/List; + public fun require (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; + public fun schedule (Lorg/pnfolder/pnlibrary/api/tasks/spec/ScheduledTask;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; + public abstract fun schedule (Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; +} + +public final class org/pnfolder/pnlibrary/api/tasks/TaskServiceSettings { + public fun ()V + public fun (I)V + public synthetic fun (IILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()I + public final fun copy (I)Lorg/pnfolder/pnlibrary/api/tasks/TaskServiceSettings; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/tasks/TaskServiceSettings;IILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/tasks/TaskServiceSettings; + public fun equals (Ljava/lang/Object;)Z + public final fun getHistoryCapacity ()I + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/tasks/TaskId { - public static final field Companion Lorg/pnfolder/pnlibrary/api/tasks/TaskId$Companion; +public final class org/pnfolder/pnlibrary/api/tasks/info/TaskId { + public static final field Companion Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId$Companion; public fun (Ljava/lang/String;)V public final fun component1 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskId; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/tasks/TaskId;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/tasks/TaskId; + public final fun copy (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; public fun equals (Ljava/lang/Object;)Z public final fun getValue ()Ljava/lang/String; public fun hashCode ()I - public static final fun random ()Lorg/pnfolder/pnlibrary/api/tasks/TaskId; + public static final fun random ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/tasks/TaskId$Companion { - public final fun random ()Lorg/pnfolder/pnlibrary/api/tasks/TaskId; +public final class org/pnfolder/pnlibrary/api/tasks/info/TaskId$Companion { + public final fun random ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; +} + +public final class org/pnfolder/pnlibrary/api/tasks/info/TaskLag { + public fun (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/lang/String;JLjava/time/Instant;Ljava/time/Instant;Ljava/time/Duration;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()J + public final fun component4 ()Ljava/time/Instant; + public final fun component5 ()Ljava/time/Instant; + public final fun component6 ()Ljava/time/Duration; + public final fun copy (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/lang/String;JLjava/time/Instant;Ljava/time/Instant;Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskLag; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskLag;Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/lang/String;JLjava/time/Instant;Ljava/time/Instant;Ljava/time/Duration;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskLag; + public fun equals (Ljava/lang/Object;)Z + public final fun getInterval ()Ljava/time/Duration; + public final fun getLag ()Ljava/time/Duration; + public final fun getMissedRuns ()J + public final fun getPlanned ()Ljava/time/Instant; + public final fun getRunNumber ()J + public final fun getStarted ()Ljava/time/Instant; + public final fun getTaskId ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; + public final fun getTaskName ()Ljava/lang/String; + public fun hashCode ()I + public final fun isOver (Ljava/time/Duration;)Z + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/tasks/TaskQuery { - public static final field Companion Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery$Companion; - public synthetic fun (Lorg/pnfolder/pnlibrary/api/tasks/TaskId;Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/util/Set;Ljava/util/Set;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun all ()Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery; - public static final fun builder ()Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery$Builder; +public final class org/pnfolder/pnlibrary/api/tasks/info/TaskQuery { + public static final field Companion Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/lang/String;Ljava/lang/String;Ljava/util/Set;Ljava/util/Set;Ljava/util/Set;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun all ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery; + public static final fun builder ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery$Builder; public final fun getExecutionKinds ()Ljava/util/Set; - public final fun getId ()Lorg/pnfolder/pnlibrary/api/tasks/TaskId; + public final fun getId ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; public final fun getKey ()Ljava/lang/String; public final fun getNameContains ()Ljava/lang/String; public final fun getStatuses ()Ljava/util/Set; public final fun getTags ()Ljava/util/Set; + public final fun matches (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskSnapshot;)Z } -public final class org/pnfolder/pnlibrary/api/tasks/TaskQuery$Builder { - public final fun build ()Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery; - public final fun execution ([Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind;)Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery$Builder; - public final fun id (Lorg/pnfolder/pnlibrary/api/tasks/TaskId;)Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery$Builder; - public final fun key (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery$Builder; - public final fun nameContains (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery$Builder; - public final fun status ([Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus;)Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery$Builder; - public final fun tag (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery$Builder; -} - -public final class org/pnfolder/pnlibrary/api/tasks/TaskQuery$Companion { - public final fun all ()Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery; - public final fun builder ()Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery$Builder; -} - -public abstract interface class org/pnfolder/pnlibrary/api/tasks/TaskScope : java/lang/AutoCloseable { - public fun cancel (Lorg/pnfolder/pnlibrary/api/tasks/TaskId;)Z - public abstract fun cancelAll ()V - public fun close ()V - public abstract fun get (Lorg/pnfolder/pnlibrary/api/tasks/TaskId;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; - public abstract fun getByKey (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; - public abstract fun getOwner ()Ljava/lang/Object; - public abstract fun query (Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery;)Ljava/util/List; - public static synthetic fun query$default (Lorg/pnfolder/pnlibrary/api/tasks/TaskScope;Lorg/pnfolder/pnlibrary/api/tasks/TaskQuery;ILjava/lang/Object;)Ljava/util/List; - public fun require (Lorg/pnfolder/pnlibrary/api/tasks/TaskId;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; - public abstract fun schedule (Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; +public final class org/pnfolder/pnlibrary/api/tasks/info/TaskQuery$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery; + public final fun execution ([Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind;)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery$Builder; + public final fun id (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery$Builder; + public final fun key (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery$Builder; + public final fun nameContains (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery$Builder; + public final fun status ([Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus;)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery$Builder; + public final fun tag (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery$Builder; } -public final class org/pnfolder/pnlibrary/api/tasks/TaskServiceSettings { - public fun ()V - public fun (I)V - public synthetic fun (IILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()I - public final fun copy (I)Lorg/pnfolder/pnlibrary/api/tasks/TaskServiceSettings; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/tasks/TaskServiceSettings;IILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/tasks/TaskServiceSettings; - public fun equals (Ljava/lang/Object;)Z - public final fun getHistoryCapacity ()I - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/tasks/info/TaskQuery$Companion { + public final fun all ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery; + public final fun builder ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskQuery$Builder; } -public final class org/pnfolder/pnlibrary/api/tasks/TaskSnapshot { - public fun (Lorg/pnfolder/pnlibrary/api/tasks/TaskId;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind;Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus;Ljava/util/Set;Ljava/time/Instant;Ljava/time/Instant;JJLjava/time/Instant;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;ZZZ)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/tasks/TaskId;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind;Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus;Ljava/util/Set;Ljava/time/Instant;Ljava/time/Instant;JJLjava/time/Instant;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;ZZZILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/tasks/TaskId; +public final class org/pnfolder/pnlibrary/api/tasks/info/TaskSnapshot { + public fun (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind;Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus;Ljava/util/Set;Ljava/time/Instant;Ljava/time/Instant;JJLjava/time/Instant;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;ZZJLorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/time/Duration;Ljava/time/Duration;Z)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind;Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus;Ljava/util/Set;Ljava/time/Instant;Ljava/time/Instant;JJLjava/time/Instant;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;ZZJLorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/time/Duration;Ljava/time/Duration;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; public final fun component10 ()J public final fun component11 ()J public final fun component12 ()Ljava/time/Instant; @@ -3671,494 +3734,417 @@ public final class org/pnfolder/pnlibrary/api/tasks/TaskSnapshot { public final fun component2 ()Ljava/lang/String; public final fun component20 ()Z public final fun component21 ()Z - public final fun component22 ()Z + public final fun component22 ()J + public final fun component23 ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; + public final fun component24 ()Ljava/time/Duration; + public final fun component25 ()Ljava/time/Duration; + public final fun component26 ()Z public final fun component3 ()Ljava/lang/String; public final fun component4 ()Ljava/lang/String; - public final fun component5 ()Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind; - public final fun component6 ()Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus; + public final fun component5 ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind; + public final fun component6 ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus; public final fun component7 ()Ljava/util/Set; public final fun component8 ()Ljava/time/Instant; public final fun component9 ()Ljava/time/Instant; - public final fun copy (Lorg/pnfolder/pnlibrary/api/tasks/TaskId;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind;Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus;Ljava/util/Set;Ljava/time/Instant;Ljava/time/Instant;JJLjava/time/Instant;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;ZZZ)Lorg/pnfolder/pnlibrary/api/tasks/TaskSnapshot; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/tasks/TaskSnapshot;Lorg/pnfolder/pnlibrary/api/tasks/TaskId;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind;Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus;Ljava/util/Set;Ljava/time/Instant;Ljava/time/Instant;JJLjava/time/Instant;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;ZZZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSnapshot; + public final fun copy (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind;Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus;Ljava/util/Set;Ljava/time/Instant;Ljava/time/Instant;JJLjava/time/Instant;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;ZZJLorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/time/Duration;Ljava/time/Duration;Z)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskSnapshot; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskSnapshot;Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind;Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus;Ljava/util/Set;Ljava/time/Instant;Ljava/time/Instant;JJLjava/time/Instant;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/time/Duration;Ljava/time/Duration;ZZJLorg/pnfolder/pnlibrary/api/tasks/info/TaskId;Ljava/time/Duration;Ljava/time/Duration;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskSnapshot; public fun equals (Ljava/lang/Object;)Z public final fun getCancellable ()Z public final fun getCreatedAt ()Ljava/time/Instant; public final fun getDescription ()Ljava/lang/String; - public final fun getExecutionKind ()Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind; + public final fun getExecutionKind ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind; + public final fun getFailedCount ()J public final fun getHidden ()Z - public final fun getId ()Lorg/pnfolder/pnlibrary/api/tasks/TaskId; + public final fun getId ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; public final fun getInterval ()Ljava/time/Duration; public final fun getKey ()Ljava/lang/String; public final fun getLastCompletedAt ()Ljava/time/Instant; public final fun getLastDuration ()Ljava/time/Duration; public final fun getLastFailure ()Ljava/lang/String; + public final fun getLastLag ()Ljava/time/Duration; public final fun getLastStartedAt ()Ljava/time/Instant; public final fun getName ()Ljava/lang/String; public final fun getNextRunAt ()Ljava/time/Instant; public final fun getOwnerName ()Ljava/lang/String; + public final fun getParentId ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; public final fun getRunCount ()J public final fun getRunnableNow ()Z public final fun getSkippedCount ()J public final fun getSource ()Ljava/lang/String; - public final fun getStatus ()Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus; + public final fun getStatus ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus; public final fun getTags ()Ljava/util/Set; public final fun getUsage ()Ljava/lang/String; + public final fun getWorstLag ()Ljava/time/Duration; public fun hashCode ()I + public final fun isActive ()Z public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/tasks/TaskSpec { - public static final field Companion Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Companion; - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZLjava/lang/String;Lorg/pnfolder/pnlibrary/api/tasks/TaskConflictPolicy;Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution;Ljava/time/Duration;Ljava/time/Duration;Ljava/util/List;Ljava/util/List;Ljava/util/Set;Lorg/pnfolder/pnlibrary/api/tasks/TaskAction;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public static final fun builder ()Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun getAction ()Lorg/pnfolder/pnlibrary/api/tasks/TaskAction; +public final class org/pnfolder/pnlibrary/api/tasks/info/TaskStatus : java/lang/Enum { + public static final field CANCELLED Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus; + public static final field COMPLETED Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus; + public static final field FAILED Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus; + public static final field RUNNING Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus; + public static final field SCHEDULED Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public final fun isTerminal ()Z + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/tasks/info/TaskStatus; +} + +public final class org/pnfolder/pnlibrary/api/tasks/run/LagResponse : java/lang/Enum { + public static final field CANCEL Lorg/pnfolder/pnlibrary/api/tasks/run/LagResponse; + public static final field RUN Lorg/pnfolder/pnlibrary/api/tasks/run/LagResponse; + public static final field SKIP Lorg/pnfolder/pnlibrary/api/tasks/run/LagResponse; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/run/LagResponse; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/tasks/run/LagResponse; +} + +public abstract interface class org/pnfolder/pnlibrary/api/tasks/run/TaskContext { + public static final field Companion Lorg/pnfolder/pnlibrary/api/tasks/run/TaskContext$Companion; + public static final field SUBTASK_TAG Ljava/lang/String; + public abstract fun cancel ()V + public fun cancelAfter (J)Z + public fun every (J)Z + public fun getElapsed ()Ljava/time/Duration; + public abstract fun getExecution ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution; + public abstract fun getExecutionKind ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind; + public abstract fun getId ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; + public abstract fun getInterval ()Ljava/time/Duration; + public abstract fun getKey ()Ljava/lang/String; + public fun getLag ()Ljava/time/Duration; + public fun getMissedRuns ()J + public abstract fun getName ()Ljava/lang/String; + public abstract fun getParentId ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskId; + public abstract fun getPreviousStartedAt ()Ljava/time/Instant; + public abstract fun getRunNumber ()J + public abstract fun getScheduledAt ()Ljava/time/Instant; + public abstract fun getSkippedCount ()J + public abstract fun getStartedAt ()Ljava/time/Instant; + public abstract fun getTags ()Ljava/util/Set; + public abstract fun isCancelled ()Z + public fun isFirstRun ()Z + public fun isLate (Ljava/time/Duration;)Z + public fun isRepeating ()Z + public fun later (Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskAction;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; + public fun later (Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskAction;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; + public fun repeat (JLjava/time/Duration;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskAction;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; + public abstract fun snapshot ()Lorg/pnfolder/pnlibrary/api/tasks/info/TaskSnapshot; + public fun spawn (Lorg/pnfolder/pnlibrary/api/tasks/spec/ScheduledTask;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; + public abstract fun spawn (Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; +} + +public final class org/pnfolder/pnlibrary/api/tasks/run/TaskContext$Companion { + public static final field SUBTASK_TAG Ljava/lang/String; +} + +public abstract interface class org/pnfolder/pnlibrary/api/tasks/run/TaskLagHandler { + public abstract fun handle (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskLag;)Lorg/pnfolder/pnlibrary/api/tasks/run/LagResponse; +} + +public abstract class org/pnfolder/pnlibrary/api/tasks/spec/ScheduledTask : org/pnfolder/pnlibrary/api/tasks/spec/TaskAction { + public fun ()V + public fun getCancelWithParent ()Z + public fun getCancellable ()Z + public fun getConflictPolicy ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy; + public fun getDelay ()Ljava/time/Duration; + public fun getDescription ()Ljava/lang/String; + public fun getExecution ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution; + public fun getHidden ()Z + public fun getInterval ()Ljava/time/Duration; + public fun getKey ()Ljava/lang/String; + public fun getLagThreshold ()Ljava/time/Duration; + public fun getMaxLag ()Ljava/time/Duration; + public fun getName ()Ljava/lang/String; + public fun getRunnableNow ()Z + public fun getTags ()Ljava/util/Set; + public fun getTolerateFailures ()I + public fun getUsage ()Ljava/lang/String; + public fun onLag (Lorg/pnfolder/pnlibrary/api/tasks/info/TaskLag;)Lorg/pnfolder/pnlibrary/api/tasks/run/LagResponse; + public fun shouldRun ()Z + public fun shouldStop ()Z + public final fun toSpec ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec; +} + +public abstract interface class org/pnfolder/pnlibrary/api/tasks/spec/TaskAction { + public abstract fun run (Lorg/pnfolder/pnlibrary/api/tasks/run/TaskContext;)V +} + +public final class org/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy : java/lang/Enum { + public static final field KEEP_EXISTING Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy; + public static final field REJECT Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy; + public static final field REPLACE Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy; +} + +public final class org/pnfolder/pnlibrary/api/tasks/spec/TaskExecution { + public static final field Companion Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind;Ljava/lang/Object;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun async ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution; + public static final fun entity (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution; + public final fun getKind ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind; + public final fun getTarget ()Ljava/lang/Object; + public static final fun global ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Companion { + public final fun async ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution; + public final fun entity (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution; + public final fun global ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution; +} + +public final class org/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind : java/lang/Enum { + public static final field ASYNC Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind; + public static final field ENTITY Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind; + public static final field GLOBAL Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind; +} + +public final class org/pnfolder/pnlibrary/api/tasks/spec/TaskSpec { + public static final field Companion Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Companion; + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZLjava/lang/String;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution;Ljava/time/Duration;Ljava/time/Duration;Ljava/time/Duration;ILjava/time/Duration;Lorg/pnfolder/pnlibrary/api/tasks/run/TaskLagHandler;ZLjava/util/List;Ljava/util/List;Ljava/util/Set;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskAction;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun builder ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun getAction ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskAction; + public final fun getCancelWithParent ()Z public final fun getCancellable ()Z public final fun getCancellationConditions ()Ljava/util/List; public final fun getConditions ()Ljava/util/List; - public final fun getConflictPolicy ()Lorg/pnfolder/pnlibrary/api/tasks/TaskConflictPolicy; + public final fun getConflictPolicy ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy; public final fun getDelay ()Ljava/time/Duration; public final fun getDescription ()Ljava/lang/String; - public final fun getExecution ()Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution; + public final fun getExecution ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution; public final fun getHidden ()Z public final fun getInterval ()Ljava/time/Duration; public final fun getKey ()Ljava/lang/String; + public final fun getLagHandler ()Lorg/pnfolder/pnlibrary/api/tasks/run/TaskLagHandler; + public final fun getLagThreshold ()Ljava/time/Duration; + public final fun getMaxLag ()Ljava/time/Duration; public final fun getName ()Ljava/lang/String; public final fun getRunnableNow ()Z public final fun getTags ()Ljava/util/Set; + public final fun getTolerateFailures ()I public final fun getUsage ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder { - public final fun action (Lorg/pnfolder/pnlibrary/api/tasks/TaskAction;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun build ()Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec; - public final fun cancelWhen (Ljava/util/function/BooleanSupplier;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun cancellable (Z)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun condition (Ljava/util/function/BooleanSupplier;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun conflictPolicy (Lorg/pnfolder/pnlibrary/api/tasks/TaskConflictPolicy;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun delay (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun delayTicks (J)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun description (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun execution (Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun hidden (Z)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun interval (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun intervalTicks (J)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun key (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun name (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun runnableNow (Z)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun tag (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun tags (Ljava/util/Collection;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; - public final fun usage (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; -} - -public final class org/pnfolder/pnlibrary/api/tasks/TaskSpec$Companion { - public final fun builder ()Lorg/pnfolder/pnlibrary/api/tasks/TaskSpec$Builder; -} - -public final class org/pnfolder/pnlibrary/api/tasks/TaskSpecBuilder { +public final class org/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder { + public final fun action (Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskAction;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun build ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec; + public final fun cancelWhen (Ljava/util/function/BooleanSupplier;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun cancelWithParent (Z)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun cancellable (Z)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun condition (Ljava/util/function/BooleanSupplier;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun conflictPolicy (Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun delay (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun delayTicks (J)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun description (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun execution (Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun hidden (Z)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun interval (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun intervalTicks (J)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun key (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun maxLag (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun name (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun onLag (Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/tasks/run/TaskLagHandler;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun runnableNow (Z)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun tag (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun tags (Ljava/util/Collection;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun tolerateFailures (I)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun usage (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; + public final fun whenLate (Ljava/time/Duration;Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; +} + +public final class org/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Companion { + public final fun builder ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskSpec$Builder; +} + +public final class org/pnfolder/pnlibrary/api/tasks/spec/TaskSpecBuilder { public final fun cancelWhen (Lkotlin/jvm/functions/Function0;)V public final fun condition (Lkotlin/jvm/functions/Function0;)V public final fun delayTicks (J)V + public final fun getCancelWithParent ()Z public final fun getCancellable ()Z - public final fun getConflictPolicy ()Lorg/pnfolder/pnlibrary/api/tasks/TaskConflictPolicy; + public final fun getConflictPolicy ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy; public final fun getDelay ()Ljava/time/Duration; public final fun getDescription ()Ljava/lang/String; - public final fun getExecution ()Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution; + public final fun getExecution ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution; public final fun getHidden ()Z public final fun getInterval ()Ljava/time/Duration; public final fun getKey ()Ljava/lang/String; + public final fun getMaxLag ()Ljava/time/Duration; public final fun getName ()Ljava/lang/String; public final fun getRunnableNow ()Z public final fun getTags ()Ljava/util/Set; + public final fun getTolerateFailures ()I public final fun getUsage ()Ljava/lang/String; public final fun intervalTicks (J)V - public final fun run (Lorg/pnfolder/pnlibrary/api/tasks/TaskAction;)V + public final fun onLag (Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/tasks/run/TaskLagHandler;)V + public final fun run (Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskAction;)V + public final fun setCancelWithParent (Z)V public final fun setCancellable (Z)V - public final fun setConflictPolicy (Lorg/pnfolder/pnlibrary/api/tasks/TaskConflictPolicy;)V + public final fun setConflictPolicy (Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy;)V public final fun setDelay (Ljava/time/Duration;)V public final fun setDescription (Ljava/lang/String;)V - public final fun setExecution (Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution;)V + public final fun setExecution (Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution;)V public final fun setHidden (Z)V public final fun setInterval (Ljava/time/Duration;)V public final fun setKey (Ljava/lang/String;)V - public final fun setName (Ljava/lang/String;)V - public final fun setRunnableNow (Z)V - public final fun setTags (Ljava/util/Set;)V - public final fun setUsage (Ljava/lang/String;)V -} - -public final class org/pnfolder/pnlibrary/api/tasks/TaskSpecKt { - public static final synthetic fun schedule (Lorg/pnfolder/pnlibrary/api/tasks/TaskScope;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; -} - -public final class org/pnfolder/pnlibrary/api/tasks/TaskStatus : java/lang/Enum { - public static final field CANCELLED Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus; - public static final field COMPLETED Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus; - public static final field FAILED Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus; - public static final field RUNNING Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus; - public static final field SCHEDULED Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/tasks/TaskStatus; -} - -public final class org/pnfolder/pnlibrary/api/text/ComponentCachePolicy { - public fun ()V - public fun (Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope;)V - public fun (Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope;I)V - public fun (Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope;ILjava/time/Duration;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope;ILjava/time/Duration;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope; - public final fun component2 ()I - public final fun component3 ()Ljava/time/Duration; - public final fun copy (Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope;ILjava/time/Duration;)Lorg/pnfolder/pnlibrary/api/text/ComponentCachePolicy; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/text/ComponentCachePolicy;Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope;ILjava/time/Duration;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/text/ComponentCachePolicy; - public fun equals (Ljava/lang/Object;)Z - public final fun getExpireAfterAccess ()Ljava/time/Duration; - public final fun getMaximumEntries ()I - public final fun getScope ()Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/text/ComponentCacheScope : java/lang/Enum { - public static final field GLOBAL Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope; - public static final field NONE Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope; - public static final field PLUGIN Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/text/ComponentCacheScope; -} - -public final class org/pnfolder/pnlibrary/api/text/ComponentCacheStatistics { - public fun (JJJI)V - public final fun component1 ()J - public final fun component2 ()J - public final fun component3 ()J - public final fun component4 ()I - public final fun copy (JJJI)Lorg/pnfolder/pnlibrary/api/text/ComponentCacheStatistics; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/text/ComponentCacheStatistics;JJJIILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/text/ComponentCacheStatistics; - public fun equals (Ljava/lang/Object;)Z - public final fun getEvictions ()J - public final fun getHitRate ()D - public final fun getHits ()J - public final fun getMisses ()J - public final fun getSize ()I - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public abstract interface class org/pnfolder/pnlibrary/api/text/ComponentSerializer { - public abstract fun deserialize (Ljava/lang/String;)Lnet/kyori/adventure/text/Component; - public fun deserializeAll (Ljava/lang/Iterable;)Ljava/util/List; - public fun deserializeLines (Ljava/lang/Iterable;)Lnet/kyori/adventure/text/Component; - public fun deserializeLines ([Ljava/lang/String;)Lnet/kyori/adventure/text/Component; - public abstract fun getType ()Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public abstract fun serialize (Lnet/kyori/adventure/text/Component;)Ljava/lang/String; - public fun serializeAll (Ljava/lang/Iterable;)Ljava/util/List; -} - -public final class org/pnfolder/pnlibrary/api/text/ComponentSerializerType : java/lang/Enum { - public static final field ADAPTIVE Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public static final field ADVENTURE_JSON Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public static final field LEGACY_AMPERSAND Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public static final field LEGACY_SECTION Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public static final field MINI_MESSAGE Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public static final field PLAIN_TEXT Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; -} - -public abstract interface class org/pnfolder/pnlibrary/api/text/ComponentService { - public abstract fun cacheStatistics ()Lorg/pnfolder/pnlibrary/api/text/ComponentCacheStatistics; - public abstract fun clearCache ()V - public abstract fun configureCache (Lorg/pnfolder/pnlibrary/api/text/ComponentCachePolicy;)V - public abstract fun deserialize (Ljava/lang/String;)Lnet/kyori/adventure/text/Component; - public abstract fun deserialize (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;)Lnet/kyori/adventure/text/Component; - public abstract fun deserializeAll (Ljava/lang/Iterable;)Ljava/util/List; - public abstract fun deserializeAll (Ljava/lang/Iterable;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;)Ljava/util/List; - public abstract fun deserializeLines (Ljava/lang/Iterable;)Lnet/kyori/adventure/text/Component; - public abstract fun deserializeLines (Ljava/lang/Iterable;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;)Lnet/kyori/adventure/text/Component; - public fun deserializeLines ([Ljava/lang/String;)Lnet/kyori/adventure/text/Component; - public abstract fun getDefaultSerializerType ()Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType; - public abstract fun serialize (Lnet/kyori/adventure/text/Component;)Ljava/lang/String; - public fun serializeAll (Ljava/lang/Iterable;)Ljava/util/List; - public abstract fun serializer (Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;)Lorg/pnfolder/pnlibrary/api/text/ComponentSerializer; - public abstract fun setDefaultSerializerType (Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;)V - public abstract fun template (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/text/ComponentTemplate; - public fun template (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/ComponentSerializerType;)Lorg/pnfolder/pnlibrary/api/text/ComponentTemplate; -} - -public abstract interface class org/pnfolder/pnlibrary/api/text/ComponentTemplate { - public abstract fun player (Ljava/util/UUID;)Lorg/pnfolder/pnlibrary/api/text/ComponentTemplate; - public fun render ()Lnet/kyori/adventure/text/Component; - public abstract fun renderAsync ()Ljava/util/concurrent/CompletionStage; - public abstract fun value (Ljava/lang/String;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/text/ComponentTemplate; -} - -public abstract class org/pnfolder/pnlibrary/api/updates/BlockedReason { -} - -public final class org/pnfolder/pnlibrary/api/updates/BlockedReason$ApiMismatch : org/pnfolder/pnlibrary/api/updates/BlockedReason { - public fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;ILjava/lang/String;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;ILjava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; - public final fun component3 ()I - public final fun component4 ()Ljava/lang/String; - public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;ILjava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$ApiMismatch; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$ApiMismatch;Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;ILjava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$ApiMismatch; - public fun equals (Ljava/lang/Object;)Z - public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public final fun getRepository ()Ljava/lang/String; - public final fun getRequiredApi ()I - public final fun getSupportedApi ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/updates/BlockedReason$Frozen : org/pnfolder/pnlibrary/api/updates/BlockedReason { - public fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/ProductId;)Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$Frozen; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$Frozen;Lorg/pnfolder/pnlibrary/api/updates/ProductId;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$Frozen; - public fun equals (Ljava/lang/Object;)Z - public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/updates/BlockedReason$MissingDependency : org/pnfolder/pnlibrary/api/updates/BlockedReason { - public fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public final fun component3 ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$MissingDependency; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$MissingDependency;Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$MissingDependency; - public fun equals (Ljava/lang/Object;)Z - public final fun getDependency ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public final fun getMinimumVersion ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/updates/BlockedReason$MissingExternalPluginDependency : org/pnfolder/pnlibrary/api/updates/BlockedReason { - public fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Ljava/lang/String;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun component4 ()Ljava/lang/String; - public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$MissingExternalPluginDependency; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$MissingExternalPluginDependency;Lorg/pnfolder/pnlibrary/api/updates/ProductId;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$MissingExternalPluginDependency; - public fun equals (Ljava/lang/Object;)Z - public final fun getDownloadPage ()Ljava/lang/String; - public final fun getMinimumVersion ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun getPlugin ()Ljava/lang/String; - public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/updates/BlockedReason$NoCompatibleRelease : org/pnfolder/pnlibrary/api/updates/BlockedReason { - public fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;I)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public final fun component2 ()I - public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/ProductId;I)Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$NoCompatibleRelease; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$NoCompatibleRelease;Lorg/pnfolder/pnlibrary/api/updates/ProductId;IILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/BlockedReason$NoCompatibleRelease; - public fun equals (Ljava/lang/Object;)Z - public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public final fun getRequiredApi ()I - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/updates/CatalogSource { - public static final field Companion Lorg/pnfolder/pnlibrary/api/updates/CatalogSource$Companion; - public static final field DEFAULT_BRANCH Ljava/lang/String; - public static final field DEFAULT_PATH Ljava/lang/String; - public fun (Ljava/lang/String;Ljava/lang/String;)V - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/CatalogSource$RefType;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/CatalogSource$RefType;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public fun equals (Ljava/lang/Object;)Z - public final fun getApiUrl ()Ljava/lang/String; - public final fun getBranch ()Ljava/lang/String; - public final fun getCdnUrl ()Ljava/lang/String; - public final fun getOwner ()Ljava/lang/String; - public final fun getPath ()Ljava/lang/String; - public final fun getRawUrl ()Ljava/lang/String; - public final fun getRefType ()Lorg/pnfolder/pnlibrary/api/updates/CatalogSource$RefType; - public final fun getRepository ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; -} - -public final class org/pnfolder/pnlibrary/api/updates/CatalogSource$Companion { + public final fun setMaxLag (Ljava/time/Duration;)V + public final fun setName (Ljava/lang/String;)V + public final fun setRunnableNow (Z)V + public final fun setTags (Ljava/util/Set;)V + public final fun setTolerateFailures (I)V + public final fun setUsage (Ljava/lang/String;)V + public final fun tag (Ljava/lang/String;)V + public final fun whenLate (Ljava/time/Duration;Lkotlin/jvm/functions/Function1;)V } -public final class org/pnfolder/pnlibrary/api/updates/CatalogSource$RefType : java/lang/Enum { - public static final field BRANCH Lorg/pnfolder/pnlibrary/api/updates/CatalogSource$RefType; - public static final field COMMIT Lorg/pnfolder/pnlibrary/api/updates/CatalogSource$RefType; - public static final field TAG Lorg/pnfolder/pnlibrary/api/updates/CatalogSource$RefType; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/CatalogSource$RefType; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/updates/CatalogSource$RefType; +public final class org/pnfolder/pnlibrary/api/tasks/spec/TaskSpecBuilderKt { + public static final synthetic fun schedule (Lorg/pnfolder/pnlibrary/api/tasks/TaskScope;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; + public static final synthetic fun spawn (Lorg/pnfolder/pnlibrary/api/tasks/run/TaskContext;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/tasks/TaskHandle; } -public final class org/pnfolder/pnlibrary/api/updates/PluginUpdateArtifact { - public fun (Ljava/lang/String;ILjava/lang/Integer;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;)V - public synthetic fun (Ljava/lang/String;ILjava/lang/Integer;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun getMaximumJava ()Ljava/lang/Integer; - public final fun getMinimumJava ()I - public final fun getPattern ()Ljava/lang/String; - public final fun getPlatform ()Lorg/pnfolder/pnlibrary/api/platform/PlatformType; - public final fun supports (I)Z +public abstract interface class org/pnfolder/pnlibrary/api/text/ComponentService { + public abstract fun cacheStatistics ()Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheStatistics; + public abstract fun clearCache ()V + public abstract fun configureCache (Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCachePolicy;)V + public abstract fun deserialize (Ljava/lang/String;)Lnet/kyori/adventure/text/Component; + public abstract fun deserialize (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;)Lnet/kyori/adventure/text/Component; + public abstract fun deserializeAll (Ljava/lang/Iterable;)Ljava/util/List; + public abstract fun deserializeAll (Ljava/lang/Iterable;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;)Ljava/util/List; + public abstract fun deserializeLines (Ljava/lang/Iterable;)Lnet/kyori/adventure/text/Component; + public abstract fun deserializeLines (Ljava/lang/Iterable;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;)Lnet/kyori/adventure/text/Component; + public fun deserializeLines ([Ljava/lang/String;)Lnet/kyori/adventure/text/Component; + public abstract fun getDefaultSerializerType ()Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public abstract fun serialize (Lnet/kyori/adventure/text/Component;)Ljava/lang/String; + public fun serializeAll (Ljava/lang/Iterable;)Ljava/util/List; + public abstract fun serializer (Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;)Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializer; + public abstract fun setDefaultSerializerType (Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;)V + public abstract fun template (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/text/ComponentTemplate; + public fun template (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType;)Lorg/pnfolder/pnlibrary/api/text/ComponentTemplate; } -public final class org/pnfolder/pnlibrary/api/updates/PluginUpdateRequest { - public static final field Companion Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Companion; - public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun artifactFor (I)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateArtifact; - public final fun artifactFor (ILorg/pnfolder/pnlibrary/api/platform/PlatformType;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateArtifact; - public static final fun builder ()Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun getArtifacts ()Ljava/util/List; - public final fun getAutomaticDownload ()Z - public final fun getCatalog ()Lorg/pnfolder/pnlibrary/api/updates/CatalogSource; - public final fun getChannel ()Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; - public final fun getConfigurationBackup ()Lorg/pnfolder/pnlibrary/api/updates/backup/UpdateConfigurationBackup; - public final fun getRepositoryName ()Ljava/lang/String; - public final fun getRepositoryOwner ()Ljava/lang/String; - public final fun getSupportedApi ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; +public abstract interface class org/pnfolder/pnlibrary/api/text/ComponentTemplate { + public abstract fun player (Ljava/util/UUID;)Lorg/pnfolder/pnlibrary/api/text/ComponentTemplate; + public fun render ()Lnet/kyori/adventure/text/Component; + public abstract fun renderAsync ()Ljava/util/concurrent/CompletionStage; + public abstract fun value (Ljava/lang/String;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/text/ComponentTemplate; + public fun values (Ljava/util/Map;)Lorg/pnfolder/pnlibrary/api/text/ComponentTemplate; } -public final class org/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder { - public final fun artifact (Ljava/lang/String;I)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun artifact (Ljava/lang/String;ILjava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun artifact (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;I)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun artifact (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;ILjava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public static synthetic fun artifact$default (Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder;Ljava/lang/String;ILjava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public static synthetic fun artifact$default (Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;ILjava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun automaticDownload (Z)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun branch (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun build ()Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest; - public final fun catalogPath (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun channel (Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun channel (Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun commit (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun configurationBackup (Ljava/nio/file/Path;[Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun exactArtifact (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun exactArtifact (Ljava/lang/String;I)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun exactArtifact (Ljava/lang/String;ILjava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public static synthetic fun exactArtifact$default (Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder;Ljava/lang/String;ILjava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun repository (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun supportedApi (II)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; - public final fun tag (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; -} - -public final class org/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Companion { - public final fun builder ()Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest$Builder; -} - -public final class org/pnfolder/pnlibrary/api/updates/ProductDescriptor { - public static final field Companion Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor$Companion; - public final fun bindTo (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor; - public static final fun builder ()Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor$Builder; - public final fun getChannel ()Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; - public final fun getId ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; - public final fun getMaximumJava ()Ljava/lang/Integer; - public final fun getMinimumJava ()I - public final fun getSupportedApi ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; - public final fun getVersion ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun isBound ()Z - public static final fun library (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor; +public final class org/pnfolder/pnlibrary/api/text/cache/ComponentCachePolicy { + public static final field Companion Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCachePolicy$Companion; + public static final field DISABLED Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCachePolicy; + public fun ()V + public fun (Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope;)V + public fun (Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope;I)V + public fun (Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope;ILjava/time/Duration;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope;ILjava/time/Duration;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope; + public final fun component2 ()I + public final fun component3 ()Ljava/time/Duration; + public final fun copy (Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope;ILjava/time/Duration;)Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCachePolicy; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCachePolicy;Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope;ILjava/time/Duration;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCachePolicy; + public fun equals (Ljava/lang/Object;)Z + public final fun getExpireAfterAccess ()Ljava/time/Duration; + public final fun getMaximumEntries ()I + public final fun getScope ()Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/updates/ProductDescriptor$Builder { - public final fun build ()Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor; - public final fun channel (Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;)Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor$Builder; - public final fun java (I)Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor$Builder; - public final fun java (ILjava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor$Builder; - public static synthetic fun java$default (Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor$Builder;ILjava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor$Builder; - public final fun pnLibraryApi (II)Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor$Builder; - public final fun version (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor$Builder; +public final class org/pnfolder/pnlibrary/api/text/cache/ComponentCachePolicy$Companion { } -public final class org/pnfolder/pnlibrary/api/updates/ProductDescriptor$Companion { - public final fun builder ()Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor$Builder; - public final fun library (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor; +public final class org/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope : java/lang/Enum { + public static final field GLOBAL Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope; + public static final field NONE Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope; + public static final field PLUGIN Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope; } -public final class org/pnfolder/pnlibrary/api/updates/ProductId : java/lang/Comparable { - public static final field Companion Lorg/pnfolder/pnlibrary/api/updates/ProductId$Companion; - public synthetic fun (Ljava/lang/String;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public synthetic fun compareTo (Ljava/lang/Object;)I - public fun compareTo (Lorg/pnfolder/pnlibrary/api/updates/ProductId;)I +public final class org/pnfolder/pnlibrary/api/text/cache/ComponentCacheStatistics { + public fun (JJJI)V + public final fun component1 ()J + public final fun component2 ()J + public final fun component3 ()J + public final fun component4 ()I + public final fun copy (JJJI)Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheStatistics; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheStatistics;JJJIILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/text/cache/ComponentCacheStatistics; public fun equals (Ljava/lang/Object;)Z - public final fun getValue ()Ljava/lang/String; + public final fun getEvictions ()J + public final fun getHitRate ()D + public final fun getHits ()J + public final fun getLookups ()J + public final fun getMisses ()J + public final fun getSize ()I public fun hashCode ()I - public static final fun of (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/ProductId; public fun toString ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/updates/ProductId$Companion { - public final fun of (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/ProductId; +public abstract interface class org/pnfolder/pnlibrary/api/text/serializer/ComponentSerializer { + public abstract fun deserialize (Ljava/lang/String;)Lnet/kyori/adventure/text/Component; + public fun deserializeAll (Ljava/lang/Iterable;)Ljava/util/List; + public fun deserializeLines (Ljava/lang/Iterable;)Lnet/kyori/adventure/text/Component; + public fun deserializeLines ([Ljava/lang/String;)Lnet/kyori/adventure/text/Component; + public abstract fun getType ()Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public abstract fun serialize (Lnet/kyori/adventure/text/Component;)Ljava/lang/String; + public fun serializeAll (Ljava/lang/Iterable;)Ljava/util/List; } -public final class org/pnfolder/pnlibrary/api/updates/UpdateActor { - public static final field Companion Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Companion; - public static final field SYSTEM Lorg/pnfolder/pnlibrary/api/updates/UpdateActor; - public static final field UNKNOWN Lorg/pnfolder/pnlibrary/api/updates/UpdateActor; - public fun (Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Kind;Ljava/lang/String;Ljava/lang/String;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Kind; - public final fun component2 ()Ljava/lang/String; - public final fun component3 ()Ljava/lang/String; - public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Kind;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/UpdateActor; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateActor;Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Kind;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/UpdateActor; - public fun equals (Ljava/lang/Object;)Z - public final fun getId ()Ljava/lang/String; - public final fun getKind ()Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Kind; - public final fun getName ()Ljava/lang/String; - public fun hashCode ()I - public fun toString ()Ljava/lang/String; +public final class org/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType : java/lang/Enum { + public static final field ADAPTIVE Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public static final field ADVENTURE_JSON Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public static final field LEGACY_AMPERSAND Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public static final field LEGACY_SECTION Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public static final field MINI_MESSAGE Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public static final field PLAIN_TEXT Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType; } -public final class org/pnfolder/pnlibrary/api/updates/UpdateActor$Companion { +public abstract interface class org/pnfolder/pnlibrary/api/updates/UpdateBackups { + public abstract fun delete (Ljava/util/UUID;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun delete$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateBackups;Ljava/util/UUID;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public abstract fun extract (Ljava/util/UUID;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun extract$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateBackups;Ljava/util/UUID;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public abstract fun list ()Ljava/util/concurrent/CompletionStage; + public abstract fun restoreDatabase (Ljava/util/UUID;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun restoreDatabase$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateBackups;Ljava/util/UUID;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public abstract fun rollback (Ljava/util/UUID;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;Z)Ljava/util/concurrent/CompletionStage; + public abstract fun rollback (Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun rollback$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateBackups;Ljava/util/UUID;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ZILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun rollback$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateBackups;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; } -public final class org/pnfolder/pnlibrary/api/updates/UpdateActor$Kind : java/lang/Enum { - public static final field CONSOLE Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Kind; - public static final field INTEGRATION Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Kind; - public static final field PLAYER Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Kind; - public static final field SYSTEM Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Kind; - public static final field UNKNOWN Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Kind; - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Kind; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/updates/UpdateActor$Kind; +public abstract interface class org/pnfolder/pnlibrary/api/updates/UpdateHistory { + public abstract fun count (Ljava/lang/String;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun count$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateHistory;Ljava/lang/String;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public abstract fun page (ILjava/lang/String;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun page$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateHistory;ILjava/lang/String;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; } -public final class org/pnfolder/pnlibrary/api/updates/UpdateChannel : java/lang/Enum { - public static final field ALPHA Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; - public static final field BETA Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; - public static final field DEV Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; - public static final field RC Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; - public static final field STABLE Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; - public final fun accepts (Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;)Z - public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; +public abstract interface class org/pnfolder/pnlibrary/api/updates/UpdatePlans { + public abstract fun check (Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun check$default (Lorg/pnfolder/pnlibrary/api/updates/UpdatePlans;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public abstract fun current ()Ljava/util/Optional; + public abstract fun recent ()Ljava/util/List; + public abstract fun stage (Ljava/util/UUID;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun stage$default (Lorg/pnfolder/pnlibrary/api/updates/UpdatePlans;Ljava/util/UUID;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; } -public final class org/pnfolder/pnlibrary/api/updates/UpdatePlanSnapshot { - public fun (Ljava/util/UUID;JLorg/pnfolder/pnlibrary/api/updates/UpdateState;Lorg/pnfolder/pnlibrary/api/updates/release/UpdatePlan;Ljava/util/List;Ljava/lang/String;)V - public final fun getBlockers ()Ljava/util/List; - public final fun getId ()Ljava/util/UUID; - public final fun getMessage ()Ljava/lang/String; - public final fun getPlan ()Lorg/pnfolder/pnlibrary/api/updates/release/UpdatePlan; - public final fun getRevision ()J - public final fun getState ()Lorg/pnfolder/pnlibrary/api/updates/UpdateState; +public abstract interface class org/pnfolder/pnlibrary/api/updates/UpdateProducts { + public abstract fun all ()Ljava/util/List; + public abstract fun get (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/UpdateRegistration; + public fun require (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/UpdateRegistration; } public abstract interface class org/pnfolder/pnlibrary/api/updates/UpdateRegistration : java/lang/AutoCloseable { @@ -4166,115 +4152,189 @@ public abstract interface class org/pnfolder/pnlibrary/api/updates/UpdateRegistr public abstract fun close ()V public abstract fun downloadNow ()V public abstract fun getRepository ()Ljava/lang/String; - public abstract fun getSnapshot ()Lorg/pnfolder/pnlibrary/api/updates/UpdateSnapshot; + public abstract fun getSnapshot ()Lorg/pnfolder/pnlibrary/api/updates/state/UpdateSnapshot; public fun isClosed ()Z } public abstract interface class org/pnfolder/pnlibrary/api/updates/UpdateService { - public abstract fun all ()Ljava/util/List; - public fun backups ()Ljava/util/concurrent/CompletionStage; - public fun checkNow ()Ljava/util/concurrent/CompletionStage; - public fun checkNow (Lorg/pnfolder/pnlibrary/api/updates/UpdateActor;)Ljava/util/concurrent/CompletionStage; - public fun confirm (Ljava/util/UUID;Ljava/lang/String;)Ljava/util/concurrent/CompletionStage; - public fun currentPlan ()Ljava/util/Optional; - public abstract fun get (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/UpdateRegistration; - public fun heldUntil (Ljava/lang/String;)Ljava/time/Instant; - public fun history ()Ljava/util/List; - public fun historyCount (Ljava/lang/String;)Ljava/util/concurrent/CompletionStage; - public static synthetic fun historyCount$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateService;Ljava/lang/String;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; - public fun historyPage (ILjava/lang/String;)Ljava/util/concurrent/CompletionStage; - public static synthetic fun historyPage$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateService;ILjava/lang/String;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; - public fun register (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor;Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest;)Lorg/pnfolder/pnlibrary/api/updates/UpdateRegistration; - public abstract fun register (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor;Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/updates/UpdateRegistration; - public static synthetic fun register$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateService;Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/updates/ProductDescriptor;Lorg/pnfolder/pnlibrary/api/updates/PluginUpdateRequest;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/UpdateRegistration; - public fun require (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/UpdateRegistration; - public fun rollback ()Ljava/util/concurrent/CompletionStage; - public fun rollback (Ljava/util/UUID;Lorg/pnfolder/pnlibrary/api/updates/UpdateActor;)Ljava/util/concurrent/CompletionStage; - public fun rollback (Ljava/util/UUID;ZLorg/pnfolder/pnlibrary/api/updates/UpdateActor;)Ljava/util/concurrent/CompletionStage; - public fun rollback (Lorg/pnfolder/pnlibrary/api/updates/UpdateActor;)Ljava/util/concurrent/CompletionStage; - public fun setAutomaticDownload (Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/updates/UpdateActor;)Ljava/util/concurrent/CompletionStage; - public fun setChannel (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;Lorg/pnfolder/pnlibrary/api/updates/UpdateActor;)Ljava/util/concurrent/CompletionStage; - public fun setHeld (Ljava/lang/String;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/updates/UpdateActor;)Ljava/util/concurrent/CompletionStage; - public fun setHeld (Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/updates/UpdateActor;)Ljava/util/concurrent/CompletionStage; - public fun stage (Ljava/util/UUID;)Ljava/util/concurrent/CompletionStage; - public fun stage (Ljava/util/UUID;Lorg/pnfolder/pnlibrary/api/updates/UpdateActor;)Ljava/util/concurrent/CompletionStage; -} - -public final class org/pnfolder/pnlibrary/api/updates/UpdateSnapshot { - public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;Lorg/pnfolder/pnlibrary/api/updates/UpdateState;IIZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/util/List;)V - public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;Lorg/pnfolder/pnlibrary/api/updates/UpdateState;IIZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun getAutomaticDownload ()Z - public final fun getAvailableReleases ()Ljava/util/List; - public final fun getChannel ()Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; - public final fun getCurrentJava ()I - public final fun getCurrentVersion ()Ljava/lang/String; - public final fun getLatestChangelogUrl ()Ljava/lang/String; - public final fun getLatestVersion ()Ljava/lang/String; - public final fun getMessage ()Ljava/lang/String; - public final fun getProduct ()Ljava/lang/String; - public final fun getReleaseUrl ()Ljava/lang/String; - public final fun getRequiredJava ()I - public final fun getState ()Lorg/pnfolder/pnlibrary/api/updates/UpdateState; - public final fun getSupportedApi ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; + public abstract fun getBackups ()Lorg/pnfolder/pnlibrary/api/updates/UpdateBackups; + public abstract fun getHistory ()Lorg/pnfolder/pnlibrary/api/updates/UpdateHistory; + public abstract fun getPlans ()Lorg/pnfolder/pnlibrary/api/updates/UpdatePlans; + public abstract fun getProducts ()Lorg/pnfolder/pnlibrary/api/updates/UpdateProducts; + public abstract fun getSettings ()Lorg/pnfolder/pnlibrary/api/updates/UpdateSettings; + public abstract fun register (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor;Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/updates/UpdateRegistration; + public static synthetic fun register$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateService;Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor;Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/UpdateRegistration; +} + +public abstract interface class org/pnfolder/pnlibrary/api/updates/UpdateSettings { + public abstract fun automaticDownload (Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun automaticDownload$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateSettings;Ljava/lang/String;ZLorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public abstract fun automaticDownloadForAll (ZLorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun automaticDownloadForAll$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateSettings;ZLorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public abstract fun channel (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun channel$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateSettings;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public abstract fun heldUntil (Ljava/lang/String;)Ljava/time/Instant; + public abstract fun hold (Ljava/lang/String;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun hold$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateSettings;Ljava/lang/String;Ljava/time/Duration;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public abstract fun javaBuild (Ljava/lang/String;Ljava/lang/Integer;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun javaBuild$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateSettings;Ljava/lang/String;Ljava/lang/Integer;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; + public abstract fun release (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;)Ljava/util/concurrent/CompletionStage; + public static synthetic fun release$default (Lorg/pnfolder/pnlibrary/api/updates/UpdateSettings;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;ILjava/lang/Object;)Ljava/util/concurrent/CompletionStage; +} + +public final class org/pnfolder/pnlibrary/api/updates/backup/BackupExport { + public fun (Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind;Ljava/lang/String;Ljava/lang/String;Lkotlin/jvm/functions/Function1;)V + public final fun getExport ()Lkotlin/jvm/functions/Function1; + public final fun getFileName ()Ljava/lang/String; + public final fun getKind ()Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind; + public final fun getName ()Ljava/lang/String; } -public final class org/pnfolder/pnlibrary/api/updates/UpdateState : java/lang/Enum { - public static final field BLOCKED Lorg/pnfolder/pnlibrary/api/updates/UpdateState; - public static final field CHECKING Lorg/pnfolder/pnlibrary/api/updates/UpdateState; - public static final field DOWNLOADING Lorg/pnfolder/pnlibrary/api/updates/UpdateState; - public static final field FAILED Lorg/pnfolder/pnlibrary/api/updates/UpdateState; - public static final field FROZEN Lorg/pnfolder/pnlibrary/api/updates/UpdateState; - public static final field INCOMPATIBLE Lorg/pnfolder/pnlibrary/api/updates/UpdateState; - public static final field ROLLED_BACK Lorg/pnfolder/pnlibrary/api/updates/UpdateState; - public static final field UPDATE_AVAILABLE Lorg/pnfolder/pnlibrary/api/updates/UpdateState; - public static final field UPDATE_STAGED Lorg/pnfolder/pnlibrary/api/updates/UpdateState; - public static final field UP_TO_DATE Lorg/pnfolder/pnlibrary/api/updates/UpdateState; +public final class org/pnfolder/pnlibrary/api/updates/backup/BackupKind : java/lang/Enum { + public static final field CONFIGURATION Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind; + public static final field DATABASE Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind; + public static final field OTHER Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind; + public static final field PLAYER_DATA Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind; public static fun getEntries ()Lkotlin/enums/EnumEntries; - public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/UpdateState; - public static fun values ()[Lorg/pnfolder/pnlibrary/api/updates/UpdateState; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind; +} + +public final class org/pnfolder/pnlibrary/api/updates/backup/BackupLabel { + public fun (Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind;Ljava/lang/String;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind; + public final fun component2 ()Ljava/lang/String; + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/backup/BackupLabel; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/backup/BackupLabel;Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/backup/BackupLabel; + public fun equals (Ljava/lang/Object;)Z + public final fun getKind ()Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind; + public final fun getName ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } public final class org/pnfolder/pnlibrary/api/updates/backup/UpdateBackup { public fun (Ljava/util/UUID;Ljava/time/Instant;Ljava/util/UUID;Ljava/util/List;I)V public synthetic fun (Ljava/util/UUID;Ljava/time/Instant;Ljava/util/UUID;Ljava/util/List;IILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Ljava/util/UUID;Ljava/time/Instant;Ljava/util/UUID;Ljava/util/List;ILjava/util/List;)V + public synthetic fun (Ljava/util/UUID;Ljava/time/Instant;Ljava/util/UUID;Ljava/util/List;ILjava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun getComponents ()Ljava/util/List; public final fun getConfigurationFiles ()I public final fun getCreatedAt ()Ljava/time/Instant; public final fun getId ()Ljava/util/UUID; + public final fun getItems ()Ljava/util/List; public final fun getPlanId ()Ljava/util/UUID; } public final class org/pnfolder/pnlibrary/api/updates/backup/UpdateBackupComponent { - public fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Ljava/lang/String;Ljava/lang/String;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Ljava/lang/String;Ljava/lang/String;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; public final fun component2 ()Ljava/lang/String; public final fun component3 ()Ljava/lang/String; - public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/backup/UpdateBackupComponent; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/backup/UpdateBackupComponent;Lorg/pnfolder/pnlibrary/api/updates/ProductId;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/backup/UpdateBackupComponent; + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/backup/UpdateBackupComponent; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/backup/UpdateBackupComponent;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/backup/UpdateBackupComponent; public fun equals (Ljava/lang/Object;)Z public final fun getBackupVersion ()Ljava/lang/String; - public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; public final fun getUpdatedVersion ()Ljava/lang/String; public fun hashCode ()I public fun toString ()Ljava/lang/String; } +public final class org/pnfolder/pnlibrary/api/updates/backup/UpdateBackupItem { + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind;Ljava/lang/String;J)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()J + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind;Ljava/lang/String;J)Lorg/pnfolder/pnlibrary/api/updates/backup/UpdateBackupItem; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/backup/UpdateBackupItem;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind;Ljava/lang/String;JILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/backup/UpdateBackupItem; + public fun equals (Ljava/lang/Object;)Z + public final fun getBytes ()J + public final fun getKind ()Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind; + public final fun getName ()Ljava/lang/String; + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class org/pnfolder/pnlibrary/api/updates/backup/UpdateConfigurationBackup { public fun (Ljava/nio/file/Path;Ljava/util/List;)V + public fun (Ljava/nio/file/Path;Ljava/util/List;Ljava/util/Map;)V public final fun getFiles ()Ljava/util/List; + public final fun getLabels ()Ljava/util/Map; public final fun getRoot ()Ljava/nio/file/Path; + public final fun labelOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/backup/BackupLabel; } -public final class org/pnfolder/pnlibrary/api/updates/backup/UpdateHistoryEntry { - public fun (Ljava/util/UUID;Ljava/time/Instant;Ljava/util/UUID;Lorg/pnfolder/pnlibrary/api/updates/UpdateState;Lorg/pnfolder/pnlibrary/api/updates/UpdateActor;Ljava/lang/String;Ljava/util/List;Ljava/lang/String;)V - public final fun getActor ()Lorg/pnfolder/pnlibrary/api/updates/UpdateActor; +public final class org/pnfolder/pnlibrary/api/updates/history/UpdateHistoryEntry { + public fun (Ljava/util/UUID;Ljava/time/Instant;Ljava/util/UUID;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;Ljava/lang/String;Ljava/util/List;Ljava/lang/String;)V + public final fun getActor ()Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor; public final fun getChanges ()Ljava/util/List; public final fun getId ()Ljava/util/UUID; public final fun getMessage ()Ljava/lang/String; public final fun getOccurredAt ()Ljava/time/Instant; public final fun getOperation ()Ljava/lang/String; public final fun getPlanId ()Ljava/util/UUID; - public final fun getState ()Lorg/pnfolder/pnlibrary/api/updates/UpdateState; + public final fun getState ()Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; +} + +public final class org/pnfolder/pnlibrary/api/updates/product/ProductDescriptor { + public static final field Companion Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor$Companion; + public final fun bindTo (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor; + public static final fun builder ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor$Builder; + public final fun getChannel ()Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; + public final fun getId ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public final fun getMaximumJava ()Ljava/lang/Integer; + public final fun getMinimumJava ()I + public final fun getSupportedApi ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; + public final fun getVersion ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; + public final fun isBound ()Z + public static final fun library (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor; +} + +public final class org/pnfolder/pnlibrary/api/updates/product/ProductDescriptor$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor; + public final fun channel (Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;)Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor$Builder; + public final fun java (I)Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor$Builder; + public final fun java (ILjava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor$Builder; + public static synthetic fun java$default (Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor$Builder;ILjava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor$Builder; + public final fun pnLibraryApi (II)Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor$Builder; + public final fun version (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor$Builder; +} + +public final class org/pnfolder/pnlibrary/api/updates/product/ProductDescriptor$Companion { + public final fun builder ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor$Builder; + public final fun library (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/product/ProductDescriptor; +} + +public final class org/pnfolder/pnlibrary/api/updates/product/ProductId : java/lang/Comparable { + public static final field Companion Lorg/pnfolder/pnlibrary/api/updates/product/ProductId$Companion; + public synthetic fun (Ljava/lang/String;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public synthetic fun compareTo (Ljava/lang/Object;)I + public fun compareTo (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;)I + public fun equals (Ljava/lang/Object;)Z + public final fun getValue ()Ljava/lang/String; + public fun hashCode ()I + public static final fun of (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/updates/product/ProductId$Companion { + public final fun of (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; +} + +public final class org/pnfolder/pnlibrary/api/updates/product/UpdateChannel : java/lang/Enum { + public static final field ALPHA Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; + public static final field BETA Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; + public static final field DEV Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; + public static final field RC Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; + public static final field STABLE Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; + public final fun accepts (Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;)Z + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; } public final class org/pnfolder/pnlibrary/api/updates/release/ArtifactDescriptor { @@ -4296,16 +4356,16 @@ public final class org/pnfolder/pnlibrary/api/updates/release/ArtifactDescriptor } public final class org/pnfolder/pnlibrary/api/updates/release/InstalledProduct { - public fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; public final fun component2 ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; public final fun component3 ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; public final fun component4 ()Ljava/lang/Integer; - public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/updates/release/InstalledProduct; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/release/InstalledProduct;Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/release/InstalledProduct; + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/updates/release/InstalledProduct; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/release/InstalledProduct;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/release/InstalledProduct; public fun equals (Ljava/lang/Object;)Z - public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; public final fun getProvidesApi ()Ljava/lang/Integer; public final fun getSupportedApi ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; public final fun getVersion ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; @@ -4314,58 +4374,58 @@ public final class org/pnfolder/pnlibrary/api/updates/release/InstalledProduct { } public final class org/pnfolder/pnlibrary/api/updates/release/ProductChange { - public fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; public final fun component2 ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; public final fun component3 ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)Lorg/pnfolder/pnlibrary/api/updates/release/ProductChange; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/release/ProductChange;Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/release/ProductChange; + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)Lorg/pnfolder/pnlibrary/api/updates/release/ProductChange; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/release/ProductChange;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/release/ProductChange; public fun equals (Ljava/lang/Object;)Z public final fun getFrom ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; public final fun getTo ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; public fun hashCode ()I public fun toString ()Ljava/lang/String; } public final class org/pnfolder/pnlibrary/api/updates/release/ProductDependency { - public fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; public final fun component2 ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)Lorg/pnfolder/pnlibrary/api/updates/release/ProductDependency; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/release/ProductDependency;Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/release/ProductDependency; + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)Lorg/pnfolder/pnlibrary/api/updates/release/ProductDependency; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/release/ProductDependency;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/release/ProductDependency; public fun equals (Ljava/lang/Object;)Z public final fun getMinimumVersion ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; public fun hashCode ()I public fun toString ()Ljava/lang/String; } public final class org/pnfolder/pnlibrary/api/updates/release/ProductRelease { - public fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;Ljava/util/List;Ljava/lang/String;Ljava/util/List;Ljava/util/List;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;Ljava/util/List;Ljava/lang/String;Ljava/util/List;Ljava/util/List;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;Ljava/util/List;Ljava/lang/String;Ljava/util/List;Ljava/util/List;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;Ljava/util/List;Ljava/lang/String;Ljava/util/List;Ljava/util/List;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; public final fun component10 ()Ljava/time/Instant; public final fun component11 ()Ljava/lang/String; public final fun component12 ()Ljava/lang/String; public final fun component2 ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; - public final fun component3 ()Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; + public final fun component3 ()Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; public final fun component4 ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; public final fun component5 ()Ljava/lang/Integer; public final fun component6 ()Ljava/util/List; public final fun component7 ()Ljava/lang/String; public final fun component8 ()Ljava/util/List; public final fun component9 ()Ljava/util/List; - public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;Ljava/util/List;Ljava/lang/String;Ljava/util/List;Ljava/util/List;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/release/ProductRelease; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/release/ProductRelease;Lorg/pnfolder/pnlibrary/api/updates/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;Ljava/util/List;Ljava/lang/String;Ljava/util/List;Ljava/util/List;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/release/ProductRelease; + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;Ljava/util/List;Ljava/lang/String;Ljava/util/List;Ljava/util/List;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/release/ProductRelease; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/release/ProductRelease;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/lang/Integer;Ljava/util/List;Ljava/lang/String;Ljava/util/List;Ljava/util/List;Ljava/time/Instant;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/release/ProductRelease; public fun equals (Ljava/lang/Object;)Z public final fun getArtifacts ()Ljava/util/List; public final fun getChangelogUrl ()Ljava/lang/String; - public final fun getChannel ()Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; + public final fun getChannel ()Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; public final fun getDependencies ()Ljava/util/List; public final fun getDescription ()Ljava/lang/String; public final fun getExternalPluginDependencies ()Ljava/util/List; - public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/ProductId; + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; public final fun getProvidesApi ()Ljava/lang/Integer; public final fun getPublishedAt ()Ljava/time/Instant; public final fun getRepository ()Ljava/lang/String; @@ -4376,17 +4436,17 @@ public final class org/pnfolder/pnlibrary/api/updates/release/ProductRelease { } public final class org/pnfolder/pnlibrary/api/updates/release/ReleaseSummary { - public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;Ljava/time/Instant;Ljava/lang/String;)V - public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;Ljava/time/Instant;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;Ljava/time/Instant;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;Ljava/time/Instant;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; public final fun component3 ()Ljava/time/Instant; public final fun component4 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;Ljava/time/Instant;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/release/ReleaseSummary; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/release/ReleaseSummary;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel;Ljava/time/Instant;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/release/ReleaseSummary; + public final fun copy (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;Ljava/time/Instant;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/release/ReleaseSummary; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/release/ReleaseSummary;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;Ljava/time/Instant;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/release/ReleaseSummary; public fun equals (Ljava/lang/Object;)Z public final fun getChangelogUrl ()Ljava/lang/String; - public final fun getChannel ()Lorg/pnfolder/pnlibrary/api/updates/UpdateChannel; + public final fun getChannel ()Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; public final fun getPublishedAt ()Ljava/time/Instant; public final fun getVersion ()Ljava/lang/String; public fun hashCode ()I @@ -4408,6 +4468,253 @@ public final class org/pnfolder/pnlibrary/api/updates/release/UpdatePlan { public fun toString ()Ljava/lang/String; } +public final class org/pnfolder/pnlibrary/api/updates/request/CatalogSource { + public static final field Companion Lorg/pnfolder/pnlibrary/api/updates/request/CatalogSource$Companion; + public static final field DEFAULT_BRANCH Ljava/lang/String; + public static final field DEFAULT_PATH Ljava/lang/String; + public fun (Ljava/lang/String;Ljava/lang/String;)V + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/request/CatalogSource$RefType;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/request/CatalogSource$RefType;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun equals (Ljava/lang/Object;)Z + public final fun getApiUrl ()Ljava/lang/String; + public final fun getBranch ()Ljava/lang/String; + public final fun getCdnUrl ()Ljava/lang/String; + public final fun getOwner ()Ljava/lang/String; + public final fun getPath ()Ljava/lang/String; + public final fun getRawUrl ()Ljava/lang/String; + public final fun getRefType ()Lorg/pnfolder/pnlibrary/api/updates/request/CatalogSource$RefType; + public final fun getRepository ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/updates/request/CatalogSource$Companion { +} + +public final class org/pnfolder/pnlibrary/api/updates/request/CatalogSource$RefType : java/lang/Enum { + public static final field BRANCH Lorg/pnfolder/pnlibrary/api/updates/request/CatalogSource$RefType; + public static final field COMMIT Lorg/pnfolder/pnlibrary/api/updates/request/CatalogSource$RefType; + public static final field TAG Lorg/pnfolder/pnlibrary/api/updates/request/CatalogSource$RefType; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/request/CatalogSource$RefType; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/updates/request/CatalogSource$RefType; +} + +public final class org/pnfolder/pnlibrary/api/updates/request/PluginUpdateArtifact { + public fun (Ljava/lang/String;ILjava/lang/Integer;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;)V + public synthetic fun (Ljava/lang/String;ILjava/lang/Integer;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun getMaximumJava ()Ljava/lang/Integer; + public final fun getMinimumJava ()I + public final fun getPattern ()Ljava/lang/String; + public final fun getPlatform ()Lorg/pnfolder/pnlibrary/api/platform/PlatformType; + public final fun supports (I)Z +} + +public final class org/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest { + public static final field Companion Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun artifactFor (I)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateArtifact; + public final fun artifactFor (ILorg/pnfolder/pnlibrary/api/platform/PlatformType;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateArtifact; + public static final fun builder ()Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun getArtifacts ()Ljava/util/List; + public final fun getAutomaticDownload ()Z + public final fun getCatalog ()Lorg/pnfolder/pnlibrary/api/updates/request/CatalogSource; + public final fun getChannel ()Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; + public final fun getConfigurationBackup ()Lorg/pnfolder/pnlibrary/api/updates/backup/UpdateConfigurationBackup; + public final fun getExports ()Ljava/util/List; + public final fun getRepositoryName ()Ljava/lang/String; + public final fun getRepositoryOwner ()Ljava/lang/String; + public final fun getSupportedApi ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; +} + +public final class org/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder { + public final fun artifact (Ljava/lang/String;I)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun artifact (Ljava/lang/String;ILjava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun artifact (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;I)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun artifact (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;ILjava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public static synthetic fun artifact$default (Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder;Ljava/lang/String;ILjava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public static synthetic fun artifact$default (Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/platform/PlatformType;ILjava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun automaticDownload (Z)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun backup (Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind;Ljava/lang/String;Ljava/nio/file/Path;[Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun backupExport (Lorg/pnfolder/pnlibrary/api/updates/backup/BackupKind;Ljava/lang/String;Ljava/lang/String;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun branch (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun build ()Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest; + public final fun catalogPath (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun channel (Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun channel (Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun commit (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun configurationBackup (Ljava/nio/file/Path;[Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun exactArtifact (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun exactArtifact (Ljava/lang/String;I)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun exactArtifact (Ljava/lang/String;ILjava/lang/Integer;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public static synthetic fun exactArtifact$default (Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder;Ljava/lang/String;ILjava/lang/Integer;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun repository (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun supportedApi (II)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; + public final fun tag (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; +} + +public final class org/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Companion { + public final fun builder ()Lorg/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest$Builder; +} + +public abstract class org/pnfolder/pnlibrary/api/updates/state/BlockedReason { +} + +public final class org/pnfolder/pnlibrary/api/updates/state/BlockedReason$ApiMismatch : org/pnfolder/pnlibrary/api/updates/state/BlockedReason { + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;ILjava/lang/String;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;ILjava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; + public final fun component3 ()I + public final fun component4 ()Ljava/lang/String; + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;ILjava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$ApiMismatch; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$ApiMismatch;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;ILjava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$ApiMismatch; + public fun equals (Ljava/lang/Object;)Z + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public final fun getRepository ()Ljava/lang/String; + public final fun getRequiredApi ()I + public final fun getSupportedApi ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/updates/state/BlockedReason$Frozen : org/pnfolder/pnlibrary/api/updates/state/BlockedReason { + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;)Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$Frozen; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$Frozen;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$Frozen; + public fun equals (Ljava/lang/Object;)Z + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/updates/state/BlockedReason$MissingDependency : org/pnfolder/pnlibrary/api/updates/state/BlockedReason { + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public final fun component3 ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;)Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$MissingDependency; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$MissingDependency;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$MissingDependency; + public fun equals (Ljava/lang/Object;)Z + public final fun getDependency ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public final fun getMinimumVersion ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/updates/state/BlockedReason$MissingExternalPluginDependency : org/pnfolder/pnlibrary/api/updates/state/BlockedReason { + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Ljava/lang/String;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; + public final fun component4 ()Ljava/lang/String; + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$MissingExternalPluginDependency; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$MissingExternalPluginDependency;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/version/SemanticVersion;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$MissingExternalPluginDependency; + public fun equals (Ljava/lang/Object;)Z + public final fun getDownloadPage ()Ljava/lang/String; + public final fun getMinimumVersion ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; + public final fun getPlugin ()Ljava/lang/String; + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/updates/state/BlockedReason$NoCompatibleRelease : org/pnfolder/pnlibrary/api/updates/state/BlockedReason { + public fun (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;I)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public final fun component2 ()I + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;I)Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$NoCompatibleRelease; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$NoCompatibleRelease;Lorg/pnfolder/pnlibrary/api/updates/product/ProductId;IILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/state/BlockedReason$NoCompatibleRelease; + public fun equals (Ljava/lang/Object;)Z + public final fun getProduct ()Lorg/pnfolder/pnlibrary/api/updates/product/ProductId; + public final fun getRequiredApi ()I + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/updates/state/UpdateActor { + public static final field Companion Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Companion; + public static final field SYSTEM Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor; + public static final field UNKNOWN Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor; + public fun (Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind;Ljava/lang/String;Ljava/lang/String;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun copy (Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor; + public fun equals (Ljava/lang/Object;)Z + public final fun getId ()Ljava/lang/String; + public final fun getKind ()Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind; + public final fun getName ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/updates/state/UpdateActor$Companion { +} + +public final class org/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind : java/lang/Enum { + public static final field CONSOLE Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind; + public static final field INTEGRATION Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind; + public static final field PLAYER Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind; + public static final field SYSTEM Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind; + public static final field UNKNOWN Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/updates/state/UpdateActor$Kind; +} + +public final class org/pnfolder/pnlibrary/api/updates/state/UpdatePlanSnapshot { + public fun (Ljava/util/UUID;JLorg/pnfolder/pnlibrary/api/updates/state/UpdateState;Lorg/pnfolder/pnlibrary/api/updates/release/UpdatePlan;Ljava/util/List;Ljava/lang/String;)V + public final fun getBlockers ()Ljava/util/List; + public final fun getId ()Ljava/util/UUID; + public final fun getMessage ()Ljava/lang/String; + public final fun getPlan ()Lorg/pnfolder/pnlibrary/api/updates/release/UpdatePlan; + public final fun getRevision ()J + public final fun getState ()Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; +} + +public final class org/pnfolder/pnlibrary/api/updates/state/UpdateSnapshot { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState;IIZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/util/List;Ljava/util/List;Ljava/lang/Integer;Ljava/lang/Integer;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel;Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState;IIZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange;Ljava/util/List;Ljava/util/List;Ljava/lang/Integer;Ljava/lang/Integer;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun getAutomaticDownload ()Z + public final fun getAvailableReleases ()Ljava/util/List; + public final fun getChannel ()Lorg/pnfolder/pnlibrary/api/updates/product/UpdateChannel; + public final fun getCurrentJava ()I + public final fun getCurrentVersion ()Ljava/lang/String; + public final fun getJavaBuild ()Ljava/lang/Integer; + public final fun getJavaBuilds ()Ljava/util/List; + public final fun getLatestChangelogUrl ()Ljava/lang/String; + public final fun getLatestVersion ()Ljava/lang/String; + public final fun getMessage ()Ljava/lang/String; + public final fun getProduct ()Ljava/lang/String; + public final fun getRecommendedJava ()Ljava/lang/Integer; + public final fun getReleaseUrl ()Ljava/lang/String; + public final fun getRequiredJava ()I + public final fun getState ()Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; + public final fun getSupportedApi ()Lorg/pnfolder/pnlibrary/api/version/ApiVersionRange; +} + +public final class org/pnfolder/pnlibrary/api/updates/state/UpdateState : java/lang/Enum { + public static final field BLOCKED Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; + public static final field CHECKING Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; + public static final field DOWNLOADING Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; + public static final field FAILED Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; + public static final field FROZEN Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; + public static final field INCOMPATIBLE Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; + public static final field ROLLED_BACK Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; + public static final field UPDATE_AVAILABLE Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; + public static final field UPDATE_STAGED Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; + public static final field UP_TO_DATE Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/updates/state/UpdateState; +} + public final class org/pnfolder/pnlibrary/api/version/ApiVersionRange { public fun (II)V public final fun component1 ()I @@ -4464,6 +4771,7 @@ public final class org/pnfolder/pnlibrary/api/version/VersionRange { public final fun getMaximum ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; public final fun getMinimum ()Lorg/pnfolder/pnlibrary/api/version/SemanticVersion; public static final fun greaterThan (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/version/VersionRange; + public fun toString ()Ljava/lang/String; public static final fun until (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/version/VersionRange; } diff --git a/modules/api/build.gradle.kts b/modules/api/build.gradle.kts index bc9c0baf6..7e979008b 100644 --- a/modules/api/build.gradle.kts +++ b/modules/api/build.gradle.kts @@ -45,8 +45,13 @@ val generateIdentity by tasks.registering { | const val ORGANIZATION = "$organization" | const val DESCRIPTION = "$description" | const val REPOSITORY = "$repository" - | const val REPOSITORY_URL = "https://github.com/$repository" - | const val SUPPORT_URL = "$supportUrl" + | @JvmField val REPOSITORY_URL: String = runtimeValue("https://github.com/$repository") + | /** + | * Where to get help. Not `const` on purpose: a constant is copied into the bytecode of every plugin built against this API, + | * so a new link would reach only rebuilt plugins. A plain field is read from the running library instead. + | */ + | @JvmField val SUPPORT_URL: String = runtimeValue("$supportUrl") + | private fun runtimeValue(value: String): String = value | /** Single display string for platforms that accept one author. */ | const val AUTHOR = "${authors.joinToString(", ")}" | /** Every author, in declaration order, for platforms that accept a list. */ @@ -67,7 +72,7 @@ tasks.matching { it.name == "sourcesJar" }.configureEach { dependsOn(generateIde dependencies { api(project(":modules:common")) api(project(":modules:features:config-api")) - api(project(":modules:features:minecraft-localization-api")) + api(project(":modules:features:localization-api")) // Pure stdlib — no server-platform compile deps api(libs.kotlin.stdlib) api(libs.adventure.api) @@ -80,7 +85,8 @@ dependencies { // through GitHub Releases and are intentionally not published to Maven Central. mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates( groupId = "io.github.pnfolder", diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/Action.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/Action.kt deleted file mode 100644 index dc9840896..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/Action.kt +++ /dev/null @@ -1,70 +0,0 @@ -@file:OptIn(org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi::class) - -package org.pnfolder.pnlibrary.api.actions - -import org.pnfolder.pnlibrary.api.actions.builtin.ActionBarAction -import org.pnfolder.pnlibrary.api.actions.builtin.CommandAction -import org.pnfolder.pnlibrary.api.actions.builtin.DelayAction -import org.pnfolder.pnlibrary.api.actions.builtin.EffectAction -import org.pnfolder.pnlibrary.api.actions.builtin.GroupAction -import org.pnfolder.pnlibrary.api.actions.builtin.IfAction -import org.pnfolder.pnlibrary.api.actions.builtin.LogAction -import org.pnfolder.pnlibrary.api.actions.builtin.MessageAction -import org.pnfolder.pnlibrary.api.actions.builtin.ParticleAction -import org.pnfolder.pnlibrary.api.actions.builtin.RepeatAction -import org.pnfolder.pnlibrary.api.actions.builtin.RequireAction -import org.pnfolder.pnlibrary.api.actions.builtin.RunAction -import org.pnfolder.pnlibrary.api.actions.builtin.SoundAction -import org.pnfolder.pnlibrary.api.actions.builtin.StopAction -import org.pnfolder.pnlibrary.api.actions.builtin.TitleAction -import org.pnfolder.pnlibrary.api.actions.internal.ActionNode -import org.pnfolder.pnlibrary.api.actions.internal.ActionText -import org.pnfolder.pnlibrary.api.config.ConfigNodeForm -import org.pnfolder.pnlibrary.api.config.ConfigPolymorphic -import org.pnfolder.pnlibrary.api.config.ConfigTextForm -import org.pnfolder.pnlibrary.api.config.ConfigType -import org.pnfolder.pnlibrary.api.config.ConfigTypes - -@ConfigPolymorphic(discriminator = "type") -@ConfigTextForm(ActionText::class) -@ConfigNodeForm(ActionNode::class) -@ConfigTypes( - ConfigType(MessageAction::class, "message", aliases = ["messages", "msg"]), - ConfigType(ActionBarAction::class, "actionbar", aliases = ["action-bar"]), - ConfigType(TitleAction::class, "title"), - ConfigType(SoundAction::class, "sound"), - ConfigType(CommandAction::class, "command", aliases = ["cmd"]), - ConfigType(LogAction::class, "log"), - ConfigType(EffectAction::class, "effect", aliases = ["potion-effect"]), - ConfigType(ParticleAction::class, "particle", aliases = ["particles"]), - ConfigType(DelayAction::class, "delay", aliases = ["wait", "pause", "later"]), - ConfigType(IfAction::class, "if", aliases = ["when"]), - ConfigType(RequireAction::class, "require"), - ConfigType(RepeatAction::class, "repeat"), - ConfigType(GroupAction::class, "group", aliases = ["sequence"]), - ConfigType(RunAction::class, "run", aliases = ["template"]), - ConfigType(StopAction::class, "stop", aliases = ["return"]), -) -/** - * One executable operation in a configured action graph. - * - * Actions are polymorphic configuration values. The `type` discriminator selects - * one of the built-in implementations declared by [ConfigTypes], while plugins may - * publish additional implementations through the configuration type registry. - * Implementations execute synchronously unless their contract explicitly delegates - * work to [ActionContext.tasks], as [DelayAction] does. - * - * An action should use only services exposed by [ActionContext]. This keeps action - * definitions independent from a particular server platform and makes one parsed - * action reusable for multiple executions. - */ -fun interface Action { - /** - * Executes this operation using the data and plugin-owned services in [context]. - * - * Implementations may throw when their configuration is invalid or a required - * context object is absent. Callers that execute user-authored action graphs - * should define their own failure-reporting boundary around this method. - */ - fun execute(context: ActionContext) -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/ActionContext.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/ActionContext.kt deleted file mode 100644 index 94686c976..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/ActionContext.kt +++ /dev/null @@ -1,272 +0,0 @@ -@file:Suppress("DEPRECATION") - -package org.pnfolder.pnlibrary.api.actions - -import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.actions.builtin.DelayAction -import org.pnfolder.pnlibrary.api.audiences.LibraryAudience -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.checks.CheckContext -import org.pnfolder.pnlibrary.api.checks.Requirement -import org.pnfolder.pnlibrary.api.internal.Suggestions -import org.pnfolder.pnlibrary.api.logging.PnLogger -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterState -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskScope -import org.pnfolder.pnlibrary.api.tasks.TaskSpec -import org.pnfolder.pnlibrary.api.text.ComponentSerializerType -import org.pnfolder.pnlibrary.api.text.ComponentService -import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import java.time.Duration -import java.util.Collections - -/** - * Execution dependencies and per-invocation values shared by an action graph. - * - * The context separates portable [Action] implementations from native platform APIs. - * [player] identifies the subject of the invocation, while [allPlayers] is the wider - * audience selected by [ActionTarget.ALL_PLAYERS]. Text parsing, logging, and delayed - * execution remain bound to the plugin that created this context. - * - * [values] contains loosely typed values intended for configuration-facing conditions. - * The map is copied when the context is created and can be changed by value actions - * while the graph executes. - * [initialObjects] is a type-safe extension map for integrations that need richer - * runtime objects. The object map is private to this context but remains mutable through - * [put] and [remove], so callers should not share one context between concurrent action - * graphs without external synchronization. - * - * @property player player that caused or owns this execution - * @property allPlayers dynamic audience representing all currently eligible players - * @property components component parser used by text-producing actions - * @property logger plugin-bound logger used for warnings and diagnostics - * @property tasks plugin-bound task scope used for deferred work - * @property serializerType default text serializer for this invocation - * @property values named scalar-like values consumed by [org.pnfolder.pnlibrary.api.checks.Check] implementations - * @property placeholders plugin-scoped placeholder service used for controlled updates, or `null` - * @property templates named action lists that `[run]` actions can call - * @property checks named requirements from the `checks:` block, used by `if` and `require` actions - * @param initialObjects objects initially available from [get] and [require] - */ -class ActionContext( - override val player: LibraryPlayer, - val allPlayers: LibraryAudience, - val components: ComponentService, - override val logger: PnLogger, - val tasks: TaskScope, - val serializerType: ComponentSerializerType = ComponentSerializerType.ADAPTIVE, - val values: Map = emptyMap(), - initialObjects: Map, Any> = emptyMap(), - val placeholders: PlaceholderService? = null, - val templates: Map> = emptyMap(), - val checks: Map = emptyMap(), -) : CheckContext { - private val runtimeValues = LinkedHashMap(values) - private val objects = HashMap(initialObjects) - - /** Fills in the placeholders of [text] (see [format]), then parses it with [type] or [serializerType]. */ - fun component(text: String, type: ComponentSerializerType? = null): Component = - components.deserialize(format(text), type ?: serializerType) - - /** Parses [lines] as one component using the explicit or context-default serializer. */ - fun component(lines: Iterable, type: ComponentSerializerType? = null): Component { - val iterator = lines.iterator() - if (!iterator.hasNext()) return Component.empty() - var result = component(iterator.next(), type) - while (iterator.hasNext()) { - result = result.append(Component.newline()).append(component(iterator.next(), type)) - } - return result - } - - /** Resolves an action [target] to the corresponding audience for this invocation. */ - fun target(target: ActionTarget): LibraryAudience = if (target == ActionTarget.PLAYER) player else allPlayers - - /** Whether a `stop` action has ended this invocation; no later action of it runs. */ - var stopped: Boolean = false - private set - - /** Ends this invocation: actions that have not started yet are skipped. */ - fun stop() { - stopped = true - } - - private var templateDepth = 0 - - override fun requirement(name: String): Requirement? = checks[name] - - override fun requirementNames(): Set = checks.keys - - /** - * Executes [actions] in iteration order with this same context, until [stop] is called. - * - * A [DelayAction] without actions of its own pauses the actions after it: they run once its duration has - * passed, scheduled through [tasks]. The caller does not wait for them. - */ - fun execute(actions: Iterable) { - val list = actions as? List ?: actions.toList() - for ((index, action) in list.withIndex()) { - if (stopped) return - if (action is DelayAction && action.thenActions.isEmpty()) { - val rest = list.subList(index + 1, list.size) - if (rest.isNotEmpty()) later(action.duration) { execute(rest) } - return - } - action.execute(this) - } - } - - /** - * Runs the template called [name], or writes a warning when there is none or templates call each other - * more than [MAX_TEMPLATE_DEPTH] levels deep. - */ - fun runTemplate(name: String) { - val list = templates[name] - if (list == null) { - val hint = Suggestions.closest(name, templates.keys) - ?.let { " Did you mean '$it'?" }.orEmpty() - logger.warning("Template '$name' is not defined.$hint") - return - } - if (templateDepth >= MAX_TEMPLATE_DEPTH) { - logger.warning("Template '$name' is called too deeply; check that templates do not call each other in a loop") - return - } - templateDepth++ - try { - execute(list) - } finally { - templateDepth-- - } - } - - private fun later(duration: Duration, block: () -> Unit) { - tasks.schedule(TaskSpec.builder() - .execution(TaskExecution.global()) - .delay(duration) - .action { block() } - .build()) - } - - /** - * Reads [expression] as a value: one `[value]`, `{placeholder}` or `%external%`, text that contains them, or a - * bare name (a context value first, then a pnLibrary placeholder). Returns `null` when nothing matches. - */ - override fun read(expression: String): Any? { - val trimmed = expression.trim() - TOKEN.matchEntire(trimmed)?.let { return valueOf(it) } - if (TOKEN.containsMatchIn(trimmed)) return format(trimmed) - return resolve(trimmed) - } - - /** Like [read], but returns [expression] itself, with its tokens replaced, when nothing matches. */ - override fun textOf(expression: String): String = - runCatchingNonFatal { read(expression) }.getOrNull()?.toString() ?: format(expression) - - /** - * Replaces the placeholders in plain [text], each kind in its own brackets, in one pass: - * - * | Written | Taken from | - * |---|---| - * | `[name]` | a value of this context (and `player`) | - * | `{name}`, `{plugin:key}` | pnLibrary placeholders: the plugin's own, the library's, another plugin's | - * | `%name%` | the external PlaceholderAPI only | - * - * Any of the first two takes a chain of formats after a bar, such as `{money|group}`. - * `player` and `player_name` are always the player's name. Text that a placeholder produced is not read again. - * Unknown names stay as written, so a typo is visible instead of silently empty. - */ - fun format(text: String): String = TOKEN.replace(text) { match -> - runCatchingNonFatal { valueOf(match) }.getOrNull()?.toString() ?: match.value - } - - private fun valueOf(match: MatchResult): Any? { - val localGroup = match.groups[1] - val libraryGroup = match.groups[3] - return when { - localGroup != null -> named(localGroup.value.trim()) { local(it, match.groupValues[2]) } - libraryGroup != null -> named(libraryGroup.value.trim()) { library(it) } - else -> named(requireNotNull(match.groups[4]) { "Token matched no placeholder group" }.value) { external(it) } - } - } - - private inline fun named(name: String, lookup: (String) -> Any?): Any? = - if (name == "player" || name == "player_name") player.name else lookup(name) - - /** A value of this context; a `|format` chain is applied by the placeholder service. */ - private fun local(name: String, pipeline: String): Any? { - val value = runtimeValues[name] ?: return null - val service = placeholders - if (pipeline.isEmpty() || service == null) return value - return service.render("[$name$pipeline]", player.uniqueId, runtimeValues).toCompletableFuture().join() - } - - /** A pnLibrary placeholder, looked up without this context's values so the two kinds never mix. */ - private fun library(expression: String): Any? = - placeholders?.resolve(expression, player.uniqueId)?.toCompletableFuture()?.join() - - /** A PlaceholderAPI placeholder, or `null` when that bridge is not available. */ - private fun external(name: String): Any? { - val adapter = placeholders?.adapters()?.get(EXTERNAL_ADAPTER) ?: return null - if (adapter.state != PlaceholderAdapterState.AVAILABLE && adapter.state != PlaceholderAdapterState.REGISTERED) return null - return adapter.resolve(player.uniqueId, name) - } - - /** Returns the named condition value, or `null` when it is absent or explicitly null. */ - override fun value(name: String): Any? = runtimeValues[name] - - /** Resolves a local `[name|formatters]` or regular placeholder expression. */ - fun resolve(reference: String): Any? { - val expression = reference.trim().let { - if (it.startsWith('[') && it.endsWith(']')) it.substring(1, it.length - 1) else it - } - runtimeValues[expression.substringBefore('|').trim()]?.let { return it } - return placeholders?.resolve(expression, player.uniqueId, runtimeValues)?.toCompletableFuture()?.join() - } - - /** Returns a snapshot of values currently available to conditions and actions. */ - fun values(): Map = - Collections.unmodifiableMap(LinkedHashMap(runtimeValues)) - - /** Stores a configuration-facing value for later actions and conditions. */ - fun setValue(name: String, value: Any?): ActionContext = apply { - require(name.isNotBlank()) { "Action context value name must not be blank" } - runtimeValues[name] = value - } - - /** Removes a configuration-facing value and returns its previous value. */ - fun removeValue(name: String): Any? = runtimeValues.remove(name) - - /** Updates a writable registered placeholder and returns its resulting value. */ - fun updatePlaceholder(reference: String, value: String): Any? { - val service = placeholders ?: error("This action context has no placeholder service") - return service.update(reference, value, player.uniqueId, runtimeValues).toCompletableFuture().join() - } - - /** Associates [value] with [type] and returns this context for fluent setup. */ - fun put(type: Class, value: T): ActionContext = apply { objects[type] = value } - - /** Returns the object registered under the exact [type], or `null` when absent. */ - fun get(type: Class): T? = objects[type]?.let(type::cast) - - /** Returns the object registered under [type], failing when the dependency is absent. */ - fun require(type: Class): T = get(type) ?: error("Missing action context value: ${type.name}") - - /** Returns whether an object is registered under the exact [type]. */ - fun has(type: Class<*>): Boolean = objects.containsKey(type) - - /** Removes and returns the object registered under [type], if present. */ - fun remove(type: Class): T? = objects.remove(type)?.let(type::cast) - - /** Limits shared by every action context. */ - companion object { - /** Deepest chain of templates calling templates before the next call is refused. */ - const val MAX_TEMPLATE_DEPTH = 16 - - private const val EXTERNAL_ADAPTER = "placeholderapi" - - /** `[value]`, `{placeholder}` and `%external%`, each with its own capture groups. */ - private val TOKEN = Regex("\\[([^\\[\\]{}|%]+)((?:\\|[^\\[\\]{}]*)?)]|\\{(?![?:/])([^{}]+)}|%([A-Za-z0-9_.:-]+)%") - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/ActionService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/ActionService.kt deleted file mode 100644 index c20ed331b..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/ActionService.kt +++ /dev/null @@ -1,46 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions - -import org.pnfolder.pnlibrary.api.audiences.LibraryAudience -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.checks.Requirement -import org.pnfolder.pnlibrary.api.text.ComponentSerializerType - -/** - * Creates plugin-bound action contexts and executes already deserialized action graphs. - * - * Implementations supply infrastructure such as text parsing, logging, and task scope. - * The service does not own action definitions and does not catch execution failures. - */ -interface ActionService { - /** - * Creates a fresh context for one logical invocation. - * - * @param player player that triggered or owns the invocation - * @param allPlayers wider dynamic audience available to targeted actions - * @param values named values exposed to conditions - * @param serializerType default parser for text-producing actions - * @param templates named action lists that `[run]` actions can call - * @param checks named requirements from the plugin's `checks:` block, used by `if` and `require` - */ - fun context( - player: LibraryPlayer, - allPlayers: LibraryAudience, - values: Map = emptyMap(), - serializerType: ComponentSerializerType = ComponentSerializerType.ADAPTIVE, - templates: Map> = emptyMap(), - checks: Map = emptyMap(), - ): ActionContext - - /** Executes one [action] immediately with [context]. */ - fun execute(context: ActionContext, action: Action) = action.execute(context) - - /** Executes [actions] immediately and sequentially with [context]. */ - fun execute(context: ActionContext, actions: Iterable) = context.execute(actions) - - fun execute( - player: LibraryPlayer, - allPlayers: LibraryAudience, - actions: Iterable, - values: Map = emptyMap(), - ) = execute(context(player, allPlayers, values), actions) -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/ActionTarget.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/ActionTarget.kt deleted file mode 100644 index 1cb58fedc..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/ActionTarget.kt +++ /dev/null @@ -1,12 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions - -/** - * Built-in audience selectors used by configurable actions. - */ -enum class ActionTarget { - /** The player that triggered the action execution. */ - PLAYER, - - /** Every player exposed by the current [ActionContext]. */ - ALL_PLAYERS, -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/ActionBarAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/ActionBarAction.kt deleted file mode 100644 index f6d5a4a50..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/ActionBarAction.kt +++ /dev/null @@ -1,24 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.actions.ActionTarget -import org.pnfolder.pnlibrary.api.text.ComponentSerializerType - -/** - * Parses and displays one action-bar component to the selected audience. - * - * @property text serialized component text; an empty string clears or replaces the - * current action bar according to platform behavior - * @property serializerType parser override, or `null` to inherit [ActionContext.serializerType] - * @property target audience that receives the component - */ -data class ActionBarAction( - val text: String = "", - val serializerType: ComponentSerializerType? = null, - val target: ActionTarget = ActionTarget.PLAYER, -) : Action { - override fun execute(context: ActionContext) { - context.target(target).actionBar(context.component(text, serializerType)) - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/CommandAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/CommandAction.kt deleted file mode 100644 index b72bb8c3a..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/CommandAction.kt +++ /dev/null @@ -1,37 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.config.ConfigKey - -/** Who runs the command of a [CommandAction]. */ -enum class CommandRunner { - /** The player that triggered the action. */ - PLAYER, - - /** The server console, with full permissions. */ - CONSOLE, -} - -/** - * Runs a server command. - * - * `[player]` and other `[name]`, `{name}` and `%name%` placeholders are replaced in the text before it runs. If the - * platform refuses the command, a warning is written to the action logger and execution continues. - * - * @property command command line without the leading slash - * @property runner who runs the command - */ -data class CommandAction( - val command: String = "", - @field:ConfigKey("as") - val runner: CommandRunner = CommandRunner.CONSOLE, -) : Action { - override fun execute(context: ActionContext) { - val line = context.format(command).trim().removePrefix("/") - if (line.isEmpty()) return - if (!context.player.runCommand(line, runner == CommandRunner.CONSOLE).isDelivered) { - context.logger.warning("Command action was not accepted by the current platform: $line") - } - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/DelayAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/DelayAction.kt deleted file mode 100644 index dc8708ec3..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/DelayAction.kt +++ /dev/null @@ -1,39 +0,0 @@ -@file:Suppress("DEPRECATION") - -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.config.ConfigKey -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskSpec -import java.time.Duration - -/** - * Waits [duration], then runs [thenActions] (written under `do`), without blocking the calling thread. - * - * Without actions of its own (`[wait 2s]`, or `type: delay` with no `do`) it pauses the rest of the list - * instead. The original [ActionContext] is retained until then, so custom objects placed in it must remain - * valid for at least [duration]. Put an [IfAction] in [thenActions] when a check must run after the delay. - * - * @property duration how long to wait; zero schedules immediately - * @property thenActions actions executed after the delay - * @throws IllegalArgumentException when [duration] is negative - */ -data class DelayAction( - val duration: Duration = Duration.ZERO, - @field:ConfigKey("then") - val thenActions: List = emptyList(), -) : Action { - init { - require(!duration.isNegative) { "Action delay must not be negative" } - } - - override fun execute(context: ActionContext) { - context.tasks.schedule(TaskSpec.builder() - .execution(TaskExecution.global()) - .delay(duration) - .action { context.execute(thenActions) } - .build()) - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/EffectAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/EffectAction.kt deleted file mode 100644 index 8d36c8efe..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/EffectAction.kt +++ /dev/null @@ -1,36 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.audiences.PlayerEffect -import java.time.Duration - -/** - * Applies a temporary status effect to the player that triggered the action. - * - * The action delegates platform-specific effect resolution to - * [org.pnfolder.pnlibrary.api.audiences.LibraryPlayer.applyEffect]. If the platform adapter cannot resolve or apply - * the effect, execution continues and a warning is written to the action logger. - * - * @property key namespaced or platform-native effect key - * @property duration amount of time the effect should stay active - * @property amplifier zero-based effect amplifier, where `0` means level I - * @property ambient whether the effect should be marked as ambient - * @property particles whether regular effect particles should be visible - * @property icon whether the client-side effect icon should be visible - */ -data class EffectAction( - val key: String = "speed", - val duration: Duration = Duration.ofSeconds(30), - val amplifier: Int = 0, - val ambient: Boolean = true, - val particles: Boolean = true, - val icon: Boolean = true, -) : Action { - override fun execute(context: ActionContext) { - val effect = PlayerEffect(key, duration, amplifier, ambient, particles, icon) - if (!context.player.applyEffect(effect).isDelivered) { - context.logger.warning("Effect action is unsupported by the current platform: $key") - } - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/GroupAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/GroupAction.kt deleted file mode 100644 index 8cbf82306..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/GroupAction.kt +++ /dev/null @@ -1,23 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.config.ConfigKey - -/** - * Executes a group of actions in declaration order. - * - * A sequence is the explicit composition primitive for configuration files. It - * does not create a new execution context and it does not schedule work by - * itself; nested [DelayAction] values are responsible for asynchronous steps. - * - * @property steps nested actions executed from first to last - */ -data class GroupAction( - @field:ConfigKey("steps") - val steps: List = emptyList(), -) : Action { - override fun execute(context: ActionContext) { - context.execute(steps) - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/IfAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/IfAction.kt deleted file mode 100644 index 1e96ec0af..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/IfAction.kt +++ /dev/null @@ -1,40 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.checks.Check -import org.pnfolder.pnlibrary.api.config.ConfigKey - -/** - * Runs [thenActions] when [check] matches, otherwise [elseActions]. The rest of the list continues either way. - * - * ```yaml - * - type: if - * check: vip # a name from checks:, or an object with a type - * do: - * - type: message - * message: VIP bonus - * else: - * - type: message - * message: Buy VIP - * ``` - * - * A named check is only asked: its own `deny` and `success` do not run. Use [RequireAction] for that. - * A missing [check] never matches. - * - * @property check the question - * @property thenActions actions on "yes", written under `do` - * @property elseActions actions on "no" - */ -data class IfAction( - val check: Check? = null, - @field:ConfigKey("then") - val thenActions: List = emptyList(), - @field:ConfigKey("else") - val elseActions: List = emptyList(), -) : Action { - override fun execute(context: ActionContext) { - val matches = check?.matches(context) ?: false - context.execute(if (matches) thenActions else elseActions) - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/LogAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/LogAction.kt deleted file mode 100644 index ab9467dd3..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/LogAction.kt +++ /dev/null @@ -1,28 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.logging.LogLevel - -/** - * Writes plain text through the logger associated with the action invocation. - * - * The text is not parsed as an Adventure component and no placeholder substitution is - * performed by this action. - * - * @property text message passed to the logger - * @property level logging method selected for the message - */ -data class LogAction( - val text: String = "", - val level: LogLevel = LogLevel.INFO, -) : Action { - override fun execute(context: ActionContext) = when (level) { - LogLevel.DEBUG -> context.logger.debug(text) - LogLevel.INFO -> context.logger.info(text) - LogLevel.SUCCESS -> context.logger.success(text) - LogLevel.WARNING -> context.logger.warning(text) - LogLevel.ERROR -> context.logger.error(text) - LogLevel.CRITICAL -> context.logger.critical(text) - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/MessageAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/MessageAction.kt deleted file mode 100644 index 1b2c8d565..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/MessageAction.kt +++ /dev/null @@ -1,26 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.actions.ActionTarget -import org.pnfolder.pnlibrary.api.text.ComponentSerializerType - -/** - * Parses a sequence of text lines and sends it as one component to an audience. - * - * Line joining and empty-list behavior are defined by [ActionContext.components], so - * every action uses the same text rules as the rest of the owning plugin. - * - * @property messages serialized component lines in display order - * @property serializerType parser override, or `null` to inherit [ActionContext.serializerType] - * @property target audience that receives the resulting component - */ -data class MessageAction( - val messages: List = emptyList(), - val serializerType: ComponentSerializerType? = null, - val target: ActionTarget = ActionTarget.PLAYER, -) : Action { - override fun execute(context: ActionContext) { - context.target(target).sendMessage(context.component(messages, serializerType)) - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/ParticleAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/ParticleAction.kt deleted file mode 100644 index 34f85d2fe..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/ParticleAction.kt +++ /dev/null @@ -1,35 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.audiences.PlayerParticle - -/** - * Spawns particles around the player that triggered the action. - * - * The action is intentionally small and delegates particle lookup to - * [org.pnfolder.pnlibrary.api.audiences.LibraryPlayer.spawnParticle] so platform modules can handle version-specific - * names and native particle data. - * - * @property key namespaced or platform-native particle key - * @property count number of particles to spawn - * @property offsetX maximum horizontal X-axis spread - * @property offsetY maximum vertical Y-axis spread - * @property offsetZ maximum horizontal Z-axis spread - * @property speed particle speed or additional particle-specific data - */ -data class ParticleAction( - val key: String = "flame", - val count: Int = 1, - val offsetX: Double = 0.0, - val offsetY: Double = 0.0, - val offsetZ: Double = 0.0, - val speed: Double = 0.0, -) : Action { - override fun execute(context: ActionContext) { - val particle = PlayerParticle(key, count, offsetX, offsetY, offsetZ, speed) - if (!context.player.spawnParticle(particle).isDelivered) { - context.logger.warning("Particle action is unsupported by the current platform: $key") - } - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/RepeatAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/RepeatAction.kt deleted file mode 100644 index 61eb3f167..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/RepeatAction.kt +++ /dev/null @@ -1,49 +0,0 @@ -@file:Suppress("DEPRECATION") - -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.config.ConfigKey -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskSpec -import java.time.Duration - -/** - * Runs a list of actions several times, [every] interval apart. - * - * The first run happens immediately; each later run is scheduled without blocking the calling thread. - * - * @property times how many runs, at least one - * @property every pause between two runs - * @property thenActions actions executed on every run - * @throws IllegalArgumentException when [times] is below one or [every] is negative - */ -data class RepeatAction( - val times: Int = 1, - val every: Duration = Duration.ZERO, - @field:ConfigKey("then") - val thenActions: List = emptyList(), -) : Action { - init { - require(times in 1..MAX_TIMES) { "Repeat times must be from 1 to $MAX_TIMES" } - require(!every.isNegative) { "Repeat interval must not be negative" } - } - - override fun execute(context: ActionContext) { - context.execute(thenActions) - for (run in 1 until times) { - context.tasks.schedule(TaskSpec.builder() - .execution(TaskExecution.global()) - .delay(every.multipliedBy(run.toLong())) - .action { context.execute(thenActions) } - .build()) - } - } - - /** Limits for repeat actions. */ - companion object { - /** The most runs one repeat may schedule. */ - const val MAX_TIMES = 1000 - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/RequireAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/RequireAction.kt deleted file mode 100644 index acf8e9cee..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/RequireAction.kt +++ /dev/null @@ -1,60 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.checks.Check -import org.pnfolder.pnlibrary.api.checks.Requirement -import org.pnfolder.pnlibrary.api.checks.builtin.NamedCheck -import org.pnfolder.pnlibrary.api.internal.Suggestions - -/** - * Stops the whole chain unless a check passes: the actions after it run only on "yes". - * - * ```yaml - * - type: require - * check: has-100 # a name from checks: runs that check's own deny and success - * - type: require - * check: # or a check written in place, with its own deny - * type: permission - * permission: shop.use - * deny: - * - type: message - * message: No access - * ``` - * - * The DeluxeMenus block (`requirements:`, `minimum_requirements`, `deny_commands`, …) is read into [requirement]. - * - * @property check a named or written-in-place check - * @property requirement a full requirement written in place - * @property deny actions run on "no" before the chain stops, after the named check's own `deny` - */ -data class RequireAction( - val check: Check? = null, - val requirement: Requirement? = null, - val deny: List = emptyList(), -) : Action { - override fun execute(context: ActionContext) { - val passed = when { - requirement != null -> requirement.test(context) - check is NamedCheck -> named(context, check.name) - check != null -> check.matches(context) - else -> { - context.logger.warning("A require action has no check and stops the chain") - false - } - } - if (!passed) { - context.execute(deny) - context.stop() - } - } - - private fun named(context: ActionContext, name: String): Boolean { - val found = context.requirement(name) - if (found == null) { - context.logger.warning("Unknown check '$name'.${Suggestions.hint(name, context.requirementNames())}") - return false - } - return found.test(context) - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/RunAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/RunAction.kt deleted file mode 100644 index b9129b7df..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/RunAction.kt +++ /dev/null @@ -1,22 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext - -/** - * Runs a named list of actions that the plugin defined once in its configuration. - * - * Use it to avoid repeating the same lines, for example a refusal sound and message used by many buttons. - * The plugin gives the lists to [org.pnfolder.pnlibrary.api.actions.ActionService.context] as `templates`. A template may call another one, - * up to [ActionContext.MAX_TEMPLATE_DEPTH] levels deep. An unknown name is a warning in the action logger - * and execution continues. - * - * @property name template name, written as `[run] name` - */ -data class RunAction( - val name: String = "", -) : Action { - override fun execute(context: ActionContext) { - context.runTemplate(name) - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/SoundAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/SoundAction.kt deleted file mode 100644 index 474398fd4..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/SoundAction.kt +++ /dev/null @@ -1,34 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import net.kyori.adventure.key.Key -import net.kyori.adventure.sound.Sound -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.actions.ActionTarget - -/** - * Builds an Adventure [Sound] and plays it for the selected audience. - * - * Unsupported platform operations do not abort the action graph; they produce a - * warning through [ActionContext.logger]. Invalid Adventure keys fail during execution. - * - * @property key namespaced Adventure sound key - * @property source mixer category used by the client - * @property volume relative playback volume - * @property pitch playback pitch multiplier - * @property target audience that hears the sound - */ -data class SoundAction( - val key: String = "minecraft:entity.experience_orb.pickup", - val source: Sound.Source = Sound.Source.MASTER, - val volume: Float = 1f, - val pitch: Float = 1f, - val target: ActionTarget = ActionTarget.PLAYER, -) : Action { - override fun execute(context: ActionContext) { - val sound = Sound.sound(Key.key(key), source, volume, pitch) - if (!context.target(target).playSound(sound).isDelivered) { - context.logger.warning("Sound action is unsupported by the current platform: $key") - } - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/StopAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/StopAction.kt deleted file mode 100644 index dd5275288..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/StopAction.kt +++ /dev/null @@ -1,16 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext - -/** - * Ends the current invocation: no action after this one runs, including the rest of any outer list. - * - * Use it inside the `then` or `else` branch of an `if` to leave early, the way a failed check - * ends a menu click. - */ -class StopAction : Action { - override fun execute(context: ActionContext) { - context.stop() - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/TitleAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/TitleAction.kt deleted file mode 100644 index aebfb2a5a..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/builtin/TitleAction.kt +++ /dev/null @@ -1,46 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.builtin - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.actions.ActionTarget -import org.pnfolder.pnlibrary.api.text.ComponentSerializerType -import java.time.Duration - -/** - * Shows a large title and a smaller subtitle in the middle of the screen. - * - * Platforms that cannot show titles (the proxies) write a warning to the action logger and execution - * continues. - * - * @property title main line; may be empty - * @property subtitle second line; may be empty - * @property fadeIn how long the title takes to appear - * @property stay how long it stays fully visible - * @property fadeOut how long it takes to disappear - * @property serializerType parser override, or `null` to inherit [ActionContext.serializerType] - * @property target audience that sees the title - */ -data class TitleAction( - val title: String = "", - val subtitle: String = "", - val fadeIn: Duration = Duration.ofMillis(500), - val stay: Duration = Duration.ofMillis(3500), - val fadeOut: Duration = Duration.ofMillis(1000), - val serializerType: ComponentSerializerType? = null, - val target: ActionTarget = ActionTarget.PLAYER, -) : Action { - init { - require(!fadeIn.isNegative && !stay.isNegative && !fadeOut.isNegative) { "Title times must not be negative" } - } - - override fun execute(context: ActionContext) { - val delivery = context.target(target).showTitle( - context.component(title, serializerType), - context.component(subtitle, serializerType), - fadeIn, - stay, - fadeOut, - ) - if (!delivery.isDelivered) context.logger.warning("Title action is unsupported by the current platform") - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/internal/ActionNode.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/internal/ActionNode.kt deleted file mode 100644 index b77cb3e10..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/internal/ActionNode.kt +++ /dev/null @@ -1,103 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.internal - -import org.pnfolder.pnlibrary.api.config.ConfigNodeRewriter -import org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi - -/** - * Turns the friendly action objects into the fields of the action classes before they are read. - * - * | Written | Read as | - * |---|---| - * | `type: message`, `message: text` | [org.pnfolder.pnlibrary.api.actions.builtin.MessageAction] with one line | - * | `type: sound`, `sound: entity.villager.no` | [org.pnfolder.pnlibrary.api.actions.builtin.SoundAction]; Bukkit names such as `ENTITY_VILLAGER_NO` work too | - * | `type: title`, `fade-in`, `stay`, `fade-out` | [org.pnfolder.pnlibrary.api.actions.builtin.TitleAction] | - * | `type: delay`, `duration`, `do` | [org.pnfolder.pnlibrary.api.actions.builtin.DelayAction]; without `do` it pauses the rest of the list | - * | `type: repeat`, `times`, `every`, `do` | [org.pnfolder.pnlibrary.api.actions.builtin.RepeatAction] | - * | `type: group`, `do` | [org.pnfolder.pnlibrary.api.actions.builtin.GroupAction] | - * | `type: if`, `check`, `do`, `else` | [org.pnfolder.pnlibrary.api.actions.builtin.IfAction]; a list under `check` means all of them | - * | `type: chance`, `probability: 10%`, `do`, `else` | [org.pnfolder.pnlibrary.api.actions.builtin.IfAction] with a chance check | - * | `type: console` or `type: player`, `command` | [org.pnfolder.pnlibrary.api.actions.builtin.CommandAction] run by the console or the player | - * | `type: requirements` with the DeluxeMenus block | [org.pnfolder.pnlibrary.api.actions.builtin.RequireAction] | - * - * The older `if` form with `all`, `any` and `then` is read as well. - */ -@InternalPnLibraryApi -object ActionNode : ConfigNodeRewriter { - /** Rewrites the older `if` form into the current action node shape. */ - override fun rewrite(node: Map, path: String): Map { - val key = node.keys.firstOrNull { it.equals("type", ignoreCase = true) } - ?: return if (node.keys.any { it.equals("requirements", ignoreCase = true) }) requirements(node, null) else node - val type = node[key]?.toString()?.trim()?.lowercase()?.replace('_', '-') ?: return node - return when (type) { - "message", "messages", "msg" -> lines(renamed(node, "message", "messages")) - "sound" -> sound(renamed(node, "sound", "key")) - "title" -> renamed(renamed(node, "fade-in", "fadeIn"), "fade-out", "fadeOut") - "delay", "wait", "pause", "later", "repeat" -> renamed(node, "do", "then") - "group", "sequence" -> renamed(node, "do", "steps") - "if", "when" -> condition(node, key) - "chance" -> chance(node, key) - "console", "player", "commandevent" -> command(node, key, if (type == "console") "console" else "player") - "requirements" -> requirements(node, key) - else -> node - } - } - - /** A message written as one text stands for a list of one line. */ - private fun lines(node: Map): Map { - val value = node["messages"] - return if (value == null || value is List<*>) node else node + ("messages" to listOf(value)) - } - - /** Turns `ENTITY_VILLAGER_NO` into `entity.villager.no`; keys with a `:` or `.` stay as written. */ - private fun sound(node: Map): Map { - val key = node["key"]?.toString() ?: return node - val normalized = if (':' in key || '.' in key) key.lowercase() else key.lowercase().replace('_', '.') - return node + ("key" to normalized) - } - - private fun renamed(node: Map, from: String, to: String): Map { - if (from !in node) return node - require(to !in node) { "Use either '$from' or '$to', not both" } - return node.entries.associate { (if (it.key == from) to else it.key) to it.value } - } - - private fun condition(node: Map, typeKey: String): Map { - require(listOf("check", "all", "any").count { it in node } <= 1) { "Use one of 'check', 'all' or 'any'" } - require(!("do" in node && "then" in node)) { "Use either 'do' or 'then', not both" } - val out = linkedMapOf() - node.forEach { (key, value) -> - when (key) { - typeKey -> out["type"] = "if" - "do" -> out["then"] = value - "check" -> out["check"] = if (value is List<*>) mapOf("type" to "all", "checks" to value) else value - "all", "any" -> out["check"] = mapOf("type" to key, "checks" to value) - else -> out[key] = value - } - } - return out - } - - private fun chance(node: Map, typeKey: String): Map { - val probability = node["probability"] ?: node["chance"] - ?: throw IllegalArgumentException("A chance needs a 'probability' such as 10%") - val out = linkedMapOf("type" to "if", "check" to mapOf("type" to "chance", "probability" to probability)) - node.forEach { (key, value) -> - when (key) { - typeKey, "probability", "chance" -> Unit - "do", "then" -> out["then"] = value - "else" -> out["else"] = value - else -> throw IllegalArgumentException("Unknown key '$key' for a chance. Valid keys: probability, do, else") - } - } - return out - } - - private fun command(node: Map, typeKey: String, runner: String): Map { - val out = linkedMapOf("type" to "command", "as" to runner) - node.forEach { (key, value) -> if (key != typeKey) out[key] = value } - return out - } - - private fun requirements(node: Map, typeKey: String?): Map = - linkedMapOf("type" to "require", "requirement" to node.filterKeys { it != typeKey }) -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/internal/ActionText.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/internal/ActionText.kt deleted file mode 100644 index 1fae6510f..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/actions/internal/ActionText.kt +++ /dev/null @@ -1,39 +0,0 @@ -package org.pnfolder.pnlibrary.api.actions.internal - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.config.ConfigSerializationContext -import org.pnfolder.pnlibrary.api.config.ConfigTextParser -import org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi - -/** - * Rejects an action written as one line of text and explains how to write it with a `type`. - * - * Actions are only written as objects. A line such as `[console] give %player_name% apple` is reported with - * the object it stands for, so moving an old configuration is a matter of copying the suggestion. - */ -@InternalPnLibraryApi -object ActionText : ConfigTextParser { - private val tag = Regex("""^\[([A-Za-z]+)]\s*(.*)$""") - - /** Parses a tagged action line such as `[message] text` into an [Action]. */ - override fun parse(text: String, context: ConfigSerializationContext): Action { - val match = tag.find(text.trim()) - val example = match?.let { suggestion(it.groupValues[1].lowercase(), it.groupValues[2]) } - ?: "- type: message\n message: Hello" - throw IllegalArgumentException("An action is written with a 'type', not as a line of text. Write it as:\n$example") - } - - private fun suggestion(tag: String, argument: String): String? = when (tag) { - "message", "broadcast", "minimessage", "minibroadcast", "json", "jsonbroadcast" -> - "- type: message\n message: $argument" - "console" -> "- type: console\n command: $argument" - "player", "commandevent" -> "- type: player\n command: $argument" - "actionbar" -> "- type: actionbar\n text: $argument" - "sound", "broadcastsound" -> "- type: sound\n sound: ${argument.substringBefore(' ')}" - "title", "broadcasttitle" -> "- type: title\n title: ${argument.substringBefore(';')}" - "log" -> "- type: log\n text: $argument" - "run" -> "- type: run\n name: $argument" - "stop" -> "- type: stop" - else -> null - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityAttachment.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityAttachment.kt deleted file mode 100644 index 60c496813..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityAttachment.kt +++ /dev/null @@ -1,20 +0,0 @@ -package org.pnfolder.pnlibrary.api.activity - -/** - * Metadata describing a file or byte payload attached to an activity event. - * - * @property id unique attachment identifier - * @property eventId identifier of the owning event - * @property name caller-visible attachment name - * @property contentType media type recorded for the payload - * @property size payload size in bytes - * @property sha256 lowercase SHA-256 digest used to verify payload integrity - */ -data class ActivityAttachment( - val id: String, - val eventId: String, - val name: String, - val contentType: String, - val size: Long, - val sha256: String, -) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityBundle.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityBundle.kt deleted file mode 100644 index 1eeaa4767..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityBundle.kt +++ /dev/null @@ -1,26 +0,0 @@ -package org.pnfolder.pnlibrary.api.activity - -/** - * One inspectable activity snapshot submitted as a single unit. - * - * @property files files to attach after the event is persisted - * @property type stable application-defined event type - * @property category broad subsystem classification - * @property severity importance used for filtering and retention - * @property sessionId optional runtime-session identifier - * @property correlationId optional identifier joining related operations - * @property source component or class that produced the snapshot - * @property pluginId plugin responsible for the snapshot, when applicable - * @property metadata bounded structured details safe to include in diagnostics - */ -data class ActivityBundle( - val files: List = emptyList(), - val type: String = "DIAGNOSTIC", - val category: ActivityCategory = ActivityCategory.SYSTEM, - val severity: ActivitySeverity = ActivitySeverity.INFO, - val sessionId: String? = null, - val correlationId: String? = null, - val source: String? = null, - val pluginId: String? = null, - val metadata: Map = emptyMap(), -) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityCategory.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityCategory.kt deleted file mode 100644 index 34c2a42f0..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityCategory.kt +++ /dev/null @@ -1,14 +0,0 @@ -package org.pnfolder.pnlibrary.api.activity - -/** Broad subsystem classification assigned to an activity event. */ -enum class ActivityCategory { - LIFECYCLE, - USER_ACTION, - UPDATE, - DIAGNOSTICS, - COMMAND, - FEATURE, - SECURITY, - ERROR, - SYSTEM -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityEvent.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityEvent.kt deleted file mode 100644 index 214176459..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityEvent.kt +++ /dev/null @@ -1,30 +0,0 @@ -package org.pnfolder.pnlibrary.api.activity - -import java.util.UUID - -/** - * Immutable record of one noteworthy library or plugin operation. - * - * @property eventId unique identifier used to associate attachments with this event - * @property timestamp creation time expressed as Unix epoch milliseconds - * @property type stable application-defined event type - * @property category broad subsystem classification - * @property severity importance used for filtering and retention - * @property sessionId optional runtime-session identifier - * @property correlationId optional identifier joining related operations - * @property source component or class that produced the event - * @property pluginId plugin responsible for the event, when applicable - * @property metadata bounded structured details safe to include in diagnostics - */ -data class ActivityEvent( - val eventId: String = UUID.randomUUID().toString(), - val timestamp: Long = System.currentTimeMillis(), - val type: String, - val category: ActivityCategory = ActivityCategory.SYSTEM, - val severity: ActivitySeverity = ActivitySeverity.INFO, - val sessionId: String? = null, - val correlationId: String? = null, - val source: String? = null, - val pluginId: String? = null, - val metadata: Map = emptyMap(), -) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityQuery.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityQuery.kt deleted file mode 100644 index 6810fe463..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityQuery.kt +++ /dev/null @@ -1,20 +0,0 @@ -package org.pnfolder.pnlibrary.api.activity - -/** - * Filters applied when reading recent activity. - * - * @property limit maximum number of events to return - * @property pluginId optional plugin identifier to match - * @property category optional category to match - * @property minimumSeverity least severe event to include - * @property since inclusive lower timestamp bound in Unix epoch milliseconds - * @property until inclusive upper timestamp bound in Unix epoch milliseconds - */ -data class ActivityQuery( - val limit: Int = 50, - val pluginId: String? = null, - val category: ActivityCategory? = null, - val minimumSeverity: ActivitySeverity? = null, - val since: Long? = null, - val until: Long? = null, -) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityService.kt deleted file mode 100644 index ddca57525..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/activity/ActivityService.kt +++ /dev/null @@ -1,104 +0,0 @@ -package org.pnfolder.pnlibrary.api.activity - -import java.nio.file.Path - -/** Relative importance used for filtering and retaining recorded activity. */ -enum class ActivitySeverity { - TRACE, - INFO, - NOTICE, - WARNING, - ERROR, - CRITICAL -} - -/** Files selected for one activity record before they are persisted. */ -typealias ActivityFile = Path - -/** Records bounded operational history and attachments for diagnostic reports. */ -interface ActivityService : AutoCloseable { - /** Persists [event] and returns the normalized stored representation. */ - fun record(event: ActivityEvent): ActivityEvent - - /** - * Creates and records an event from individual fields. - * - * @return the normalized stored event - */ - fun record( - type: String, - category: ActivityCategory = ActivityCategory.SYSTEM, - severity: ActivitySeverity = ActivitySeverity.INFO, - sessionId: String? = null, - correlationId: String? = null, - source: String? = null, - pluginId: String? = null, - metadata: Map = emptyMap(), - ): ActivityEvent = record(ActivityEvent(type = type, category = category, severity = severity, - sessionId = sessionId, correlationId = correlationId, source = source, - pluginId = pluginId, metadata = metadata)) - - /** Returns recent events matching [query], ordered by the implementation's recency policy. */ - fun recent(query: ActivityQuery = ActivityQuery()): List - - /** Records [bundle] and attaches each selected file to the resulting event. */ - fun record(bundle: ActivityBundle): ActivityEvent { - val event = record( - type = bundle.type, - category = bundle.category, - severity = bundle.severity, - sessionId = bundle.sessionId, - correlationId = bundle.correlationId, - source = bundle.source, - pluginId = bundle.pluginId, - metadata = bundle.metadata, - ) - bundle.files.forEach { file -> attachFile(event.eventId, file) } - return event - } - - /** Records a diagnostic snapshot without requiring callers to name its type. */ - fun diagnostic( - files: List = emptyList(), - metadata: Map = emptyMap(), - pluginId: String? = null, - source: String? = null, - ): ActivityEvent = record(ActivityBundle(files = files, metadata = metadata, pluginId = pluginId, source = source)) - - /** Attaches in-memory [bytes] to an existing event and returns their stored metadata. */ - fun attach(eventId: String, name: String, contentType: String, bytes: ByteArray): ActivityAttachment - - /** Attaches the file at [path] to an existing event. */ - fun attachFile(eventId: String, path: Path, contentType: String = "application/octet-stream"): ActivityAttachment - - /** Records an event and attaches [path] to it through one caller-facing operation. */ - fun recordWithFile( - path: Path, - type: String = "DIAGNOSTIC", - category: ActivityCategory = ActivityCategory.SYSTEM, - severity: ActivitySeverity = ActivitySeverity.INFO, - sessionId: String? = null, - correlationId: String? = null, - source: String? = null, - pluginId: String? = null, - metadata: Map = emptyMap(), - ): ActivityEvent { - val event = record(type, category, severity, sessionId, correlationId, source, pluginId, metadata) - attachFile(event.eventId, path) - return event - } - /** Exports the persisted event journal in the implementation-defined report format. */ - fun exportJournal(): ByteArray - - /** Exports attachment payloads keyed by their stable archive paths. */ - fun exportAttachments(): Map - - /** Exports metadata required to inspect and verify the attachment payloads. */ - fun exportAttachmentManifest(): ByteArray = ByteArray(0) - - /** Removes all retained events and attachments owned by this service. */ - fun clear() - - /** Flushes pending state and releases storage resources. */ - override fun close() -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/AudienceSender.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/AudienceSender.kt new file mode 100644 index 000000000..beade6258 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/AudienceSender.kt @@ -0,0 +1,37 @@ +package org.pnfolder.pnlibrary.api.audiences + +/** + * A [LibraryAudience] that has an identity and permissions: the console or a player. + * + * This is the base of every sender in the library, the way `CommandSender` is in Bukkit: + * + * ``` + * LibraryAudience what can be shown + * └ AudienceSender who it is and what they may do + * ├ CommandSender who ran a command + * └ LibraryPlayer an online player + * └ NetworkPlayer a player seen through a proxy + * ``` + * + * ```kotlin + * fun greet(sender: AudienceSender) { + * if (sender.hasPermission("shop.use")) sender.sendMessage(Component.text("Welcome, ${sender.name}")) + * } + * ``` + */ +interface AudienceSender : LibraryAudience { + /** Stable platform-independent identifier: the player UUID as text, or a fixed value for the console. */ + val id: String + + /** Current human-readable name. */ + val name: String + + /** Whether this sender is the server console. */ + val isConsole: Boolean + + /** Whether this sender is a connected player; the opposite of [isConsole]. */ + val isPlayer: Boolean get() = !isConsole + + /** Returns whether the active platform grants this sender [permission]. */ + fun hasPermission(permission: String): Boolean +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/AudienceService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/AudienceService.kt index 34e500d57..52757c755 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/AudienceService.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/AudienceService.kt @@ -1,38 +1,34 @@ package org.pnfolder.pnlibrary.api.audiences +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer import java.util.UUID -/** A message receiver with identity and platform-backed permission checks. */ -interface AudienceSender : LibraryAudience { - /** Stable platform-independent identifier for this sender. */ - val id: String - /** Current human-readable sender name. */ - val name: String - /** Whether this sender represents the server console. */ - val isConsole: Boolean - /** Whether this sender represents a connected player. */ - val isPlayer: Boolean get() = !isConsole - /** Returns whether this sender is granted [permission] by the active platform. */ - fun hasPermission(permission: String): Boolean -} - -/** Resolves and combines audiences supplied by the active platform runtime. */ +/** + * Finds and combines audiences of the active platform: the console, players, and groups of them. + * + * ```kotlin + * val audiences = library.audiences + * audiences.console().sendMessage(Component.text("Started")) + * audiences.player(uuid)?.sendMessage(Component.text("Hello")) + * audiences.all().actionBar(Component.text("Restart in 5 minutes")) + * ``` + */ interface AudienceService { - /** Returns the server-console audience. */ + /** Returns the server console. */ fun console(): AudienceSender - /** Returns the online player identified by [uniqueId], or `null` when absent. */ + /** Returns the online player with [uniqueId], or `null` when absent. */ fun player(uniqueId: UUID): LibraryPlayer? - /** Adapts a platform-native sender object, or returns `null` when unsupported. */ + /** Adapts a platform-native sender object (such as a Bukkit `CommandSender`), or `null` when unsupported. */ fun sender(native: Any): AudienceSender? /** Returns a snapshot of all players currently online. */ fun onlinePlayers(): List - /** Returns a dynamic audience containing every receiver exposed by the platform. */ + /** Returns a dynamic audience of every online player, re-evaluated on each operation. */ fun all(): LibraryAudience - /** Combines [audiences] into one receiver that forwards every operation. */ + /** Combines [audiences] into one that forwards every operation to each of them. */ fun combine(audiences: Iterable): LibraryAudience } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/LibraryAudience.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/LibraryAudience.kt index 4e5690c96..75aab44cd 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/LibraryAudience.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/LibraryAudience.kt @@ -2,6 +2,7 @@ package org.pnfolder.pnlibrary.api.audiences import net.kyori.adventure.sound.Sound import net.kyori.adventure.text.Component +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer import java.time.Duration import java.util.function.Supplier diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/PlayerEffects.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/PlayerEffects.kt deleted file mode 100644 index 3778e4388..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/PlayerEffects.kt +++ /dev/null @@ -1,66 +0,0 @@ -package org.pnfolder.pnlibrary.api.audiences - -import java.time.Duration - -/** - * Immutable description of a temporary player status effect. - * - * The [key] is intentionally stored as a string so the API does not expose - * Bukkit, BungeeCord, Velocity, or version-specific Minecraft types. Platform - * adapters are responsible for resolving the key to the native effect object. - * - * @property key namespaced or platform-native effect key, for example - * `minecraft:speed` or `speed` - * @property duration amount of time the effect should stay active; must be - * positive - * @property amplifier zero-based effect amplifier, where `0` means level I - * @property ambient whether the effect should be marked as ambient by the - * platform - * @property particles whether regular effect particles should be visible - * @property icon whether the client-side effect icon should be visible - */ -data class PlayerEffect( - val key: String, - val duration: Duration = Duration.ofSeconds(30), - val amplifier: Int = 0, - val ambient: Boolean = true, - val particles: Boolean = true, - val icon: Boolean = true, -) { - init { - require(key.isNotBlank()) { "Effect key must not be blank" } - require(!duration.isNegative && !duration.isZero) { "Effect duration must be positive" } - require(amplifier >= 0) { "Effect amplifier must not be negative" } - } -} - -/** - * Immutable description of a particle burst displayed around a player. - * - * Particle keys remain textual for the same reason as [PlayerEffect.key]: the - * API module is platform-neutral, while runtime adapters translate the key into - * native server objects. - * - * @property key namespaced or platform-native particle key, for example - * `minecraft:flame` or `flame` - * @property count number of particles to spawn; `0` is allowed and represents - * a no-op request - * @property offsetX maximum horizontal X-axis spread - * @property offsetY maximum vertical Y-axis spread - * @property offsetZ maximum horizontal Z-axis spread - * @property speed particle speed or additional particle-specific data, depending - * on the native particle type - */ -data class PlayerParticle( - val key: String, - val count: Int = 1, - val offsetX: Double = 0.0, - val offsetY: Double = 0.0, - val offsetZ: Double = 0.0, - val speed: Double = 0.0, -) { - init { - require(key.isNotBlank()) { "Particle key must not be blank" } - require(count >= 0) { "Particle count must not be negative" } - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/ItemQuery.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/ItemQuery.kt similarity index 93% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/ItemQuery.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/ItemQuery.kt index b3ada852c..0f79f5eb1 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/ItemQuery.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/ItemQuery.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.audiences +package org.pnfolder.pnlibrary.api.audiences.player /** * Describes which items a player inventory check counts. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/LibraryPlayer.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer.kt similarity index 54% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/LibraryPlayer.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer.kt index 48cdf57ca..5a949b818 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/LibraryPlayer.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer.kt @@ -1,49 +1,39 @@ -package org.pnfolder.pnlibrary.api.audiences +package org.pnfolder.pnlibrary.api.audiences.player +import org.pnfolder.pnlibrary.api.audiences.AudienceSender +import org.pnfolder.pnlibrary.api.audiences.Delivery import java.util.UUID -/** Operations that may be implemented by a platform player adapter. */ -enum class PlayerCapability { - MESSAGE, - ACTION_BAR, - SOUND, - EFFECT, - PARTICLE, -} - /** - * Platform-neutral representation of an online player. + * Platform-neutral online player. Platform modules implement it; feature code never touches Bukkit, BungeeCord or + * Velocity player classes. + * + * ```kotlin + * val player = library.audiences.player(uuid) ?: return + * player.applyEffect(PlayerEffect("minecraft:speed", Duration.ofSeconds(10))) + * val diamonds = player.countItems(ItemQuery("diamond")) ?: 0 + * ``` * - * Platform modules implement this contract; feature code must not depend on - * Bukkit, BungeeCord, or Velocity player classes. + * Optional operations return [Delivery.Unsupported] or `null` on platforms that lack them; see [capabilities]. */ interface LibraryPlayer : AudienceSender { /** Stable player UUID supplied by the server platform. */ val uniqueId: UUID - /** Operations supported by this adapter. */ + /** Operations this adapter supports; chat and action bar by default. */ val capabilities: Set get() = setOf(PlayerCapability.MESSAGE, PlayerCapability.ACTION_BAR) - /** Stable textual sender identifier derived from [uniqueId]. */ override val id: String get() = uniqueId.toString() - - /** Always `false` because this audience represents a player. */ override val isConsole: Boolean get() = false - - /** Always `true` because this audience represents a player. */ override val isPlayer: Boolean get() = true - - /** Current visible player name. */ override val name: String - - /** Checks whether the player has a platform permission. */ override fun hasPermission(permission: String): Boolean /** Applies a temporary status effect to the player. */ fun applyEffect(effect: PlayerEffect): Delivery - /** Spawns a particle effect around the player. */ + /** Spawns a particle burst around the player. */ fun spawnParticle(particle: PlayerParticle): Delivery /** @@ -54,21 +44,18 @@ interface LibraryPlayer : AudienceSender { */ fun runCommand(command: String, asConsole: Boolean): Delivery = Delivery.Unsupported - /** - * Returns how many items matching [query] the player carries, or `null` when the platform has - * no player inventory. - */ + /** Returns how many items matching [query] the player carries, or `null` when the platform has no inventory. */ fun countItems(query: ItemQuery): Int? = null /** - * Returns the player's experience, as levels when [asLevels] is `true` and as points otherwise, + * Returns the player's experience as levels when [asLevels] is `true` and as points otherwise, * or `null` when the platform has no experience. */ fun experience(asLevels: Boolean): Double? = null /** - * Returns the distance in blocks to the point [x], [y], [z] in [world], or `null` when the - * player is in another world or the platform has no positions. + * Returns the distance in blocks to the point [x], [y], [z] in [world], or `null` when the player is in + * another world or the platform has no positions. */ fun distanceTo(world: String, x: Double, y: Double, z: Double): Double? = null } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/PlayerCapability.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/PlayerCapability.kt new file mode 100644 index 000000000..aa2092b4c --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/PlayerCapability.kt @@ -0,0 +1,18 @@ +package org.pnfolder.pnlibrary.api.audiences.player + +/** + * An operation a platform player adapter may or may not support, listed in [LibraryPlayer.capabilities]. + * + * Check it before relying on an optional operation: + * + * ```kotlin + * if (PlayerCapability.PARTICLE in player.capabilities) player.spawnParticle(PlayerParticle("flame", count = 10)) + * ``` + */ +enum class PlayerCapability { + MESSAGE, + ACTION_BAR, + SOUND, + EFFECT, + PARTICLE, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/PlayerEffect.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/PlayerEffect.kt new file mode 100644 index 000000000..98fabbfa0 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/PlayerEffect.kt @@ -0,0 +1,36 @@ +package org.pnfolder.pnlibrary.api.audiences.player + +import java.time.Duration + +/** + * Immutable description of a temporary status effect on a player. + * + * The [key] is text so the API never exposes Bukkit, BungeeCord, Velocity or version-specific Minecraft types; + * platform adapters resolve it to the native effect. + * + * ```kotlin + * val speed = PlayerEffect("minecraft:speed", Duration.ofSeconds(10), amplifier = 1) + * player.applyEffect(speed) + * ``` + * + * @property key namespaced or platform-native effect key, such as `minecraft:speed` or `speed` + * @property duration how long the effect stays; must be positive + * @property amplifier zero-based level, where `0` is level I + * @property ambient whether the platform marks the effect as ambient + * @property particles whether the regular effect particles are visible + * @property icon whether the client shows the effect icon + */ +data class PlayerEffect( + val key: String, + val duration: Duration = Duration.ofSeconds(30), + val amplifier: Int = 0, + val ambient: Boolean = true, + val particles: Boolean = true, + val icon: Boolean = true, +) { + init { + require(key.isNotBlank()) { "Effect key must not be blank" } + require(!duration.isNegative && !duration.isZero) { "Effect duration must be positive" } + require(amplifier >= 0) { "Effect amplifier must not be negative" } + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/PlayerParticle.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/PlayerParticle.kt new file mode 100644 index 000000000..33fc2fd74 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/audiences/player/PlayerParticle.kt @@ -0,0 +1,30 @@ +package org.pnfolder.pnlibrary.api.audiences.player + +/** + * Immutable description of a particle burst around a player. The [key] is text for the same reason as + * [PlayerEffect.key]. + * + * ```kotlin + * player.spawnParticle(PlayerParticle("minecraft:flame", count = 20, offsetX = 0.5, offsetY = 1.0, offsetZ = 0.5)) + * ``` + * + * @property key namespaced or platform-native particle key, such as `minecraft:flame` or `flame` + * @property count how many particles to spawn; `0` is a no-op + * @property offsetX maximum spread along the X axis + * @property offsetY maximum spread along the Y axis + * @property offsetZ maximum spread along the Z axis + * @property speed particle speed, or extra data for particle types that use it + */ +data class PlayerParticle( + val key: String, + val count: Int = 1, + val offsetX: Double = 0.0, + val offsetY: Double = 0.0, + val offsetZ: Double = 0.0, + val speed: Double = 0.0, +) { + init { + require(key.isNotBlank()) { "Particle key must not be blank" } + require(count >= 0) { "Particle count must not be negative" } + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatKit.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatKit.kt index 769726ab2..7bb7b9f64 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatKit.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatKit.kt @@ -5,32 +5,12 @@ import net.kyori.adventure.text.event.ClickEvent import net.kyori.adventure.text.event.HoverEvent import net.kyori.adventure.text.format.TextColor import net.kyori.adventure.text.format.TextDecoration -import org.pnfolder.pnlibrary.api.commands.CommandSender +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.color import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import java.net.URI -/** - * Who reads a message and what their client can do. - * - * @property interactive whether the reader can click and hover; without it buttons are left out and pages list the - * commands to type instead - * @property ascii whether to avoid characters outside ASCII and Cyrillic, for consoles with a legacy code page - */ -data class ChatReader(val interactive: Boolean = true, val ascii: Boolean = false) { - /** Ready-made readers for the common cases and the factory for a command sender. */ - companion object { - /** A player whose client shows buttons and hover cards. */ - @JvmField val PLAYER = ChatReader() - - /** A server console: plain text in ASCII. */ - @JvmField val CONSOLE = ChatReader(interactive = false, ascii = true) - - /** The reader behind a command [sender]: buttons only while its transport keeps them, ASCII on the console. */ - @JvmStatic - fun of(sender: CommandSender): ChatReader = ChatReader(sender.supportsInteraction, sender.isConsole) - } -} - /** * Building blocks of every pnLibrary chat page, so all of them share one look. * diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatNotice.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatNotice.kt index 78c86e606..e972c6d30 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatNotice.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatNotice.kt @@ -1,24 +1,6 @@ package org.pnfolder.pnlibrary.api.chat -import net.kyori.adventure.text.format.TextColor - -/** What a short message reports, which decides its mark and color. */ -enum class ChatTone { - /** Work has started or is still running. */ - PROGRESS, - - /** A neutral fact, such as an available update. */ - INFO, - - /** The requested work is done. */ - SUCCESS, - - /** Nothing failed, but the reader should act or wait. */ - WARNING, - - /** The requested work failed or was refused. */ - FAILURE, -} +import org.pnfolder.pnlibrary.api.chat.style.ChatTone /** * One short message of a command, rendered by [ChatKit.notice]. @@ -28,13 +10,3 @@ enum class ChatTone { * @property detail an optional second line, such as the reason of a failure */ data class ChatNotice(val tone: ChatTone, val text: String, val detail: String? = null) - -/** The color of this tone: lavender progress, aqua facts, green success, yellow warnings and red failures. */ -val ChatTone.color: TextColor - get() = when (this) { - ChatTone.PROGRESS -> ChatPalette.ACCENT - ChatTone.INFO -> ChatPalette.INFO - ChatTone.SUCCESS -> ChatPalette.OK - ChatTone.WARNING -> ChatPalette.WARN - ChatTone.FAILURE -> ChatPalette.DANGER - } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatReader.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatReader.kt new file mode 100644 index 000000000..7a23441e5 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatReader.kt @@ -0,0 +1,25 @@ +package org.pnfolder.pnlibrary.api.chat + +import org.pnfolder.pnlibrary.api.commands.CommandSender + +/** + * Who reads a message and what their client can do. + * + * @property interactive whether the reader can click and hover; without it buttons are left out and pages list the + * commands to type instead + * @property ascii whether to avoid characters outside ASCII and Cyrillic, for consoles with a legacy code page + */ +data class ChatReader(val interactive: Boolean = true, val ascii: Boolean = false) { + /** Ready-made readers for the common cases and the factory for a command sender. */ + companion object { + /** A player whose client shows buttons and hover cards. */ + @JvmField val PLAYER = ChatReader() + + /** A server console: plain text in ASCII. */ + @JvmField val CONSOLE = ChatReader(interactive = false, ascii = true) + + /** The reader behind a command [sender]: buttons only while its transport keeps them, ASCII on the console. */ + @JvmStatic + fun of(sender: CommandSender): ChatReader = ChatReader(sender.supportsInteraction, sender.isConsole) + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatPalette.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/style/ChatPalette.kt similarity index 97% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatPalette.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/style/ChatPalette.kt index d3074c641..885445b45 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/ChatPalette.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/style/ChatPalette.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.chat +package org.pnfolder.pnlibrary.api.chat.style import net.kyori.adventure.text.format.TextColor diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/style/ChatTone.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/style/ChatTone.kt new file mode 100644 index 000000000..f032bf1eb --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/chat/style/ChatTone.kt @@ -0,0 +1,31 @@ +package org.pnfolder.pnlibrary.api.chat.style + +import net.kyori.adventure.text.format.TextColor + +/** What a short message reports, which decides its mark and color. */ +enum class ChatTone { + /** Work has started or is still running. */ + PROGRESS, + + /** A neutral fact, such as an available update. */ + INFO, + + /** The requested work is done. */ + SUCCESS, + + /** Nothing failed, but the reader should act or wait. */ + WARNING, + + /** The requested work failed or was refused. */ + FAILURE, +} + +/** The color of this tone: lavender progress, aqua facts, green success, yellow warnings and red failures. */ +val ChatTone.color: TextColor + get() = when (this) { + ChatTone.PROGRESS -> ChatPalette.ACCENT + ChatTone.INFO -> ChatPalette.INFO + ChatTone.SUCCESS -> ChatPalette.OK + ChatTone.WARNING -> ChatPalette.WARN + ChatTone.FAILURE -> ChatPalette.DANGER + } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/Check.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/Check.kt deleted file mode 100644 index 0e084055e..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/Check.kt +++ /dev/null @@ -1,19 +0,0 @@ -@file:OptIn(org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi::class) - -package org.pnfolder.pnlibrary.api.checks - -import org.pnfolder.pnlibrary.api.checks.internal.CheckSerializer -import org.pnfolder.pnlibrary.api.config.ConfigSerializeWith - -/** - * A question about a player or a value: "yes" or "no". Checks never change anything. - * - * In configuration a check is an object with a `type` and the fields of that type, such as - * `type: permission` with `permission: shop.use`. A text names a [Requirement] declared under `checks:`. - * Implementations should be free of side effects, because one check may run many times. - */ -@ConfigSerializeWith(CheckSerializer::class) -fun interface Check { - /** Returns whether [context] satisfies this check. */ - fun matches(context: CheckContext): Boolean -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/CheckContext.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/CheckContext.kt deleted file mode 100644 index 5e03f8262..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/CheckContext.kt +++ /dev/null @@ -1,33 +0,0 @@ -package org.pnfolder.pnlibrary.api.checks - -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.logging.PnLogger - -/** - * What a [Check] may look at: the player, placeholders and values, and the named checks of the plugin. - * - * [org.pnfolder.pnlibrary.api.actions.ActionContext] implements it, so the same check works inside - * actions and on its own. - */ -interface CheckContext { - /** The player being checked. */ - val player: LibraryPlayer - - /** Logger for warnings about checks that cannot be evaluated. */ - val logger: PnLogger - - /** Resolves `[value]`, `{placeholder}`, `%external%` or a plain value name, or returns `null`. */ - fun read(expression: String): Any? - - /** Returns [expression] with every placeholder and value replaced, as text. */ - fun textOf(expression: String): String - - /** Returns the value stored under [name], or `null`. */ - fun value(name: String): Any? - - /** Returns the requirement declared under `checks:` with [name], or `null`. */ - fun requirement(name: String): Requirement? - - /** Names of every requirement declared under `checks:`, used in "Did you mean" hints. */ - fun requirementNames(): Set = emptySet() -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/Requirement.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/Requirement.kt deleted file mode 100644 index 9cec6883c..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/Requirement.kt +++ /dev/null @@ -1,127 +0,0 @@ -@file:OptIn(org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi::class) - -package org.pnfolder.pnlibrary.api.checks - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.checks.internal.RequirementEntrySerializer -import org.pnfolder.pnlibrary.api.checks.internal.RequirementSerializer -import org.pnfolder.pnlibrary.api.config.ConfigSerializeWith - -/** - * A check with what to do on "yes" and "no": one entry of the `checks:` block of a plugin. - * - * The short form is one [Check] under `check:`. The DeluxeMenus form lists named [entries] under - * `requirements:`, where every entry must match unless it is `optional`, and at least [minimum] optional - * entries must match. - * - * ```yaml - * checks: - * has-100: - * check: - * type: '>=' - * input: '%vault_eco_balance%' - * output: 100 - * deny: - * - type: message - * message: '&cNeed 100 coins' - * ``` - * - * @property entries checks in the order they are evaluated - * @property minimum how many optional entries must match, zero or more - * @property stopAtSuccess whether optional entries are skipped once [minimum] of them matched - * @property success actions run after a pass, after the `success` of the matched entries - * @property deny actions run after a failure, after the `deny` of the failed entry - */ -@ConfigSerializeWith(RequirementSerializer::class) -data class Requirement( - val entries: Map = emptyMap(), - val minimum: Int = 0, - val stopAtSuccess: Boolean = false, - val success: List = emptyList(), - val deny: List = emptyList(), -) { - /** A requirement made of the single [check]. */ - constructor(check: Check, deny: List = emptyList(), success: List = emptyList()) : - this(mapOf(SINGLE to Entry(check)), success = success, deny = deny) - - init { - require(minimum >= 0) { "minimum_requirements must not be negative" } - } - - /** - * One named check of a [Requirement]. - * - * @property check the check; `null` counts as failed with a warning - * @property optional whether the entry only counts toward [Requirement.minimum] - * @property success actions run when the whole requirement passes and this entry matched - * @property deny actions run when this entry fails; ignored for optional entries - */ - @ConfigSerializeWith(RequirementEntrySerializer::class) - data class Entry( - val check: Check? = null, - val optional: Boolean = false, - val success: List = emptyList(), - val deny: List = emptyList(), - ) - - /** Answers "yes" or "no" without running anything. */ - fun check(context: CheckContext): Boolean = evaluate(context).passed - - /** - * Answers "yes" or "no" and runs the matching actions: on "yes" the `success` of the matched entries and - * then [success]; on "no" the `deny` of the failed entry and then [deny]. The caller decides what else stops. - */ - fun test(context: ActionContext): Boolean { - val result = evaluate(context) - if (result.passed) { - result.matched.forEach { context.execute(it.success) } - context.execute(success) - } else { - context.execute(result.failed?.deny.orEmpty()) - context.execute(deny) - } - return result.passed - } - - private class Result(val passed: Boolean, val matched: List, val failed: Entry?) - - private fun evaluate(context: CheckContext): Result { - val optionalCount = entries.values.count(Entry::optional) - if (minimum > optionalCount) { - context.logger.warning( - "minimum_requirements ($minimum) is more than the number of optional checks ($optionalCount); it can never pass", - ) - } - val matched = ArrayList() - var optionalMatched = 0 - for ((name, entry) in entries) { - if (stopAtSuccess && minimum > 0 && optionalMatched >= minimum && entry.optional) continue - if (matches(context, name, entry)) { - matched += entry - if (entry.optional) optionalMatched++ - } else if (!entry.optional) { - return Result(false, matched, entry) - } - } - return Result(optionalMatched >= minimum, matched, null) - } - - private fun matches(context: CheckContext, name: String, entry: Entry): Boolean { - val check = entry.check - if (check == null) { - context.logger.warning("Check '$name' has no type and counts as failed") - return false - } - return try { - check.matches(context) - } catch (error: RuntimeException) { - context.logger.warning("Check '$name' could not be evaluated: ${error.message}") - false - } - } - - private companion object { - const val SINGLE = "check" - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/builtin/BasicChecks.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/builtin/BasicChecks.kt deleted file mode 100644 index a26780f65..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/builtin/BasicChecks.kt +++ /dev/null @@ -1,153 +0,0 @@ -@file:OptIn(org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi::class) - -package org.pnfolder.pnlibrary.api.checks.builtin - -import org.pnfolder.pnlibrary.api.checks.Check -import org.pnfolder.pnlibrary.api.checks.CheckContext -import org.pnfolder.pnlibrary.api.checks.internal.CheckSerializer -import org.pnfolder.pnlibrary.api.config.ConfigKey -import org.pnfolder.pnlibrary.api.config.ConfigSerializeWith - -/** - * Interprets a named context value as a boolean and compares it with [enabled]. - * - * Boolean values are used directly, numeric zero is false, and strings are true when - * equal to `true`, `yes`, `on`, `1`, or `enabled` ignoring case. Missing and all other - * values are false. - * - * @property flag key read from `ActionContext.values` - * @property enabled boolean state required for a match - */ -@ConfigSerializeWith(CheckSerializer::class) -data class FlagCheck( - @field:ConfigKey("name") - val flag: String = "", - @field:ConfigKey("equals") - val enabled: Boolean = true, -) : Check { - override fun matches(context: CheckContext): Boolean { - val actual = when (val value = context.value(flag)) { - is Boolean -> value - is Number -> value.toInt() != 0 - else -> value?.toString()?.trim()?.lowercase() in setOf("true", "yes", "on", "1", "enabled") - } - return actual == enabled - } -} - -/** - * Matches when the invoking player has [permission]. - * - * A blank permission is always rejected and is never passed to the platform adapter. - * - * @property permission platform permission node required from the invoking player - */ -@ConfigSerializeWith(CheckSerializer::class) -data class PermissionCheck( - @field:ConfigKey("node") - val permission: String = "", -) : Check { - override fun matches(context: CheckContext): Boolean = - permission.isNotBlank() && context.player.hasPermission(permission) -} - -/** - * Matches randomly with the configured [probability]. - * - * @property probability inclusive configuration range from `0.0` to `1.0`; `0.0` - * never matches and `1.0` always matches - * @throws IllegalArgumentException when [probability] is outside the supported range - */ -@ConfigSerializeWith(CheckSerializer::class) -data class ChanceCheck( - val probability: Double = 1.0, -) : Check { - init { require(probability in 0.0..1.0) { "Chance must be from 0% to 100%" } } - override fun matches(context: CheckContext): Boolean = Math.random() < probability -} - -/** - * Negates [check]; a missing check is treated as false and therefore matches. - * - * @property check predicate to negate, or `null` for an always-matching condition - */ -@ConfigSerializeWith(CheckSerializer::class) -data class NotCheck( - @field:ConfigKey("check") - val check: Check? = null, -) : Check { - override fun matches(context: CheckContext): Boolean = !(check?.matches(context) ?: false) -} - -/** Comparison operation used by [ValueCheck]. */ -enum class Comparison { - /** String equality after applying the configured case policy. */ - EQUALS, - /** String inequality after applying the configured case policy. */ - NOT_EQUALS, - /** Whether the actual string contains the expected string. */ - CONTAINS, - /** Numeric greater-than comparison. */ - GREATER_THAN, - /** Numeric greater-than-or-equal comparison. */ - GREATER_OR_EQUAL, - /** Numeric less-than comparison. */ - LESS_THAN, - /** Numeric less-than-or-equal comparison. */ - LESS_OR_EQUAL, - /** Numeric equality, so `5` equals `5.0`. */ - NUMBER_EQUALS, - /** Numeric inequality. */ - NUMBER_NOT_EQUALS, - /** Whether a nonblank value exists; does not use [ValueCheck.value]. */ - PRESENT, - /** Whether the value is missing or blank; does not use [ValueCheck.value]. */ - ABSENT, -} - -/** - * Compares one named runtime value with an expected string representation. - * - * Equality and containment operate on strings. Ordering comparisons require both the - * actual and configured values to parse as [Double] and return false otherwise. [Comparison.PRESENT] - * requires a nonblank value; [Comparison.ABSENT] accepts either a missing or blank value. - * - * @property source key read from `ActionContext.values` - * @property operator operation applied to the context value - * @property value right-hand operand, ignored for presence checks - * @property ignoreCase whether textual comparisons use case-insensitive matching - */ -@ConfigSerializeWith(CheckSerializer::class) -data class ValueCheck( - val source: String = "", - @field:ConfigKey("operator") - val operator: Comparison = Comparison.EQUALS, - val value: String = "", - val ignoreCase: Boolean = true, -) : Check { - override fun matches(context: CheckContext): Boolean { - val raw = context.read(source) - if (operator == Comparison.PRESENT) return raw != null && raw.toString().isNotBlank() - if (operator == Comparison.ABSENT) return raw == null || raw.toString().isBlank() - val actual = raw?.toString() ?: return false - val left = if (ignoreCase) actual.lowercase() else actual - val right = if (ignoreCase) value.lowercase() else value - fun numeric(predicate: (Double, Double) -> Boolean): Boolean { - val a = actual.toDoubleOrNull() ?: return false - val b = context.read(value)?.toString()?.toDoubleOrNull() ?: value.toDoubleOrNull() ?: return false - return predicate(a, b) - } - return when (operator) { - Comparison.EQUALS -> left == right - Comparison.NOT_EQUALS -> left != right - Comparison.CONTAINS -> right in left - Comparison.GREATER_THAN -> numeric { a, b -> a > b } - Comparison.GREATER_OR_EQUAL -> numeric { a, b -> a >= b } - Comparison.LESS_THAN -> numeric { a, b -> a < b } - Comparison.LESS_OR_EQUAL -> numeric { a, b -> a <= b } - Comparison.NUMBER_EQUALS -> numeric { a, b -> a == b } - Comparison.NUMBER_NOT_EQUALS -> numeric { a, b -> a != b } - Comparison.PRESENT, Comparison.ABSENT -> false - } - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/builtin/LogicChecks.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/builtin/LogicChecks.kt deleted file mode 100644 index cc0d1a7f9..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/builtin/LogicChecks.kt +++ /dev/null @@ -1,70 +0,0 @@ -@file:OptIn(org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi::class) - -package org.pnfolder.pnlibrary.api.checks.builtin - -import org.pnfolder.pnlibrary.api.checks.Check -import org.pnfolder.pnlibrary.api.checks.CheckContext -import org.pnfolder.pnlibrary.api.checks.internal.CheckSerializer -import org.pnfolder.pnlibrary.api.config.ConfigSerializeWith -import org.pnfolder.pnlibrary.api.internal.Suggestions - -/** - * Matches when every check in [checks] matches; an empty list matches. Written as `type: all`. - * - * @property checks checks that must all match - */ -@ConfigSerializeWith(CheckSerializer::class) -data class AllCheck(val checks: List = emptyList()) : Check { - override fun matches(context: CheckContext): Boolean = checks.all { it.matches(context) } -} - -/** - * Matches when at least one check in [checks] matches; an empty list does not. Written as `type: any`. - * - * @property checks checks of which at least one must match - */ -@ConfigSerializeWith(CheckSerializer::class) -data class AnyCheck(val checks: List = emptyList()) : Check { - override fun matches(context: CheckContext): Boolean = checks.any { it.matches(context) } -} - -/** - * Matches when at least [count] of [checks] match. Written as `type: at-least` with `count`. - * - * @property count minimum number of matching checks - * @property checks checks that are counted - * @throws IllegalArgumentException when [count] is negative or above the number of checks - */ -@ConfigSerializeWith(CheckSerializer::class) -data class AtLeastCheck(val count: Int = 1, val checks: List = emptyList()) : Check { - init { - require(count in 0..checks.size) { "at-least count ($count) must be from 0 to the number of checks (${checks.size})" } - } - - override fun matches(context: CheckContext): Boolean { - var matched = 0 - for (check in checks) { - if (check.matches(context) && ++matched >= count) return true - } - return matched >= count - } -} - -/** - * Asks the requirement declared under `checks:` with [name], without running its `deny` or `success`. - * - * Written as the name alone: `check: has-100`. An unknown name does not match and logs a warning. - * - * @property name key of the requirement to ask - */ -@ConfigSerializeWith(CheckSerializer::class) -data class NamedCheck(val name: String = "") : Check { - override fun matches(context: CheckContext): Boolean { - val requirement = context.requirement(name) - if (requirement == null) { - context.logger.warning("Unknown check '$name'.${Suggestions.hint(name, context.requirementNames())}") - return false - } - return requirement.check(context) - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/builtin/PlayerChecks.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/builtin/PlayerChecks.kt deleted file mode 100644 index 18718c0ad..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/builtin/PlayerChecks.kt +++ /dev/null @@ -1,120 +0,0 @@ -@file:OptIn(org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi::class) - -package org.pnfolder.pnlibrary.api.checks.builtin - -import org.pnfolder.pnlibrary.api.audiences.ItemQuery -import org.pnfolder.pnlibrary.api.checks.Check -import org.pnfolder.pnlibrary.api.checks.CheckContext -import org.pnfolder.pnlibrary.api.checks.internal.CheckSerializer -import org.pnfolder.pnlibrary.api.config.ConfigKey -import org.pnfolder.pnlibrary.api.config.ConfigSerializeWith - -/** - * Matches when the player has at least [minimum] of the listed [permissions]. - * - * Without [minimum] every listed permission is required. Blank entries are ignored, and an empty - * list never matches. - * - * @property permissions permission nodes to check - * @property minimum how many of them are enough, or `null` for all - */ -@ConfigSerializeWith(CheckSerializer::class) -data class PermissionsCheck( - val permissions: List = emptyList(), - val minimum: Int? = null, -) : Check { - override fun matches(context: CheckContext): Boolean { - val nodes = permissions.filter(String::isNotBlank) - if (nodes.isEmpty()) return false - return nodes.count(context.player::hasPermission) >= (minimum ?: nodes.size) - } -} - -/** - * Matches when the player carries at least [amount] items that fit the description. - * - * A platform without player inventories, or an unknown [material], never matches. - * - * @property material platform item name such as `diamond` - * @property amount required count, at least one - * @property name full display name the item must have, or `null` - * @property nameContains text the display name must contain, or `null` - * @property loreContains text a lore line must contain, or `null` - * @property ignoreCase whether text is compared without case sensitivity - * @throws IllegalArgumentException when [amount] is below one - */ -@ConfigSerializeWith(CheckSerializer::class) -data class ItemCheck( - val material: String = "", - val amount: Int = 1, - val name: String? = null, - @field:ConfigKey("name-contains") - val nameContains: String? = null, - @field:ConfigKey("lore-contains") - val loreContains: String? = null, - val ignoreCase: Boolean = true, -) : Check { - init { require(amount >= 1) { "Required item amount must be at least 1" } } - - override fun matches(context: CheckContext): Boolean { - if (material.isBlank()) return false - val query = ItemQuery(material, name, nameContains, loreContains, ignoreCase) - return (context.player.countItems(query) ?: 0) >= amount - } -} - -/** - * Matches when the player has at least [amount] experience points, or levels when [level] is true. - * - * @property amount required experience, not negative - * @property level whether [amount] counts levels instead of points - * @throws IllegalArgumentException when [amount] is negative - */ -@ConfigSerializeWith(CheckSerializer::class) -data class ExperienceCheck( - val amount: Int = 0, - val level: Boolean = false, -) : Check { - init { require(amount >= 0) { "Required experience must not be negative" } } - - override fun matches(context: CheckContext): Boolean { - val current = context.player.experience(level) ?: return false - return current >= amount - } -} - -/** - * Matches when the player is within [distance] blocks of [location]. - * - * @property location point written as `world,x,y,z` - * @property distance largest allowed distance in blocks, not negative - * @throws IllegalArgumentException when [location] is not `world,x,y,z` or [distance] is negative - */ -@ConfigSerializeWith(CheckSerializer::class) -data class NearCheck( - val location: String = "world,0,0,0", - val distance: Double = 5.0, -) : Check { - private val world: String - private val x: Double - private val y: Double - private val z: Double - - init { - require(distance >= 0) { "Distance must not be negative" } - val parts = location.split(',').map(String::trim) - val numbers = parts.drop(1).map(String::toDoubleOrNull) - require(parts.size == 4 && parts[0].isNotEmpty() && numbers.none { it == null }) { - "Location must be written as world,x,y,z but was '$location'" - } - world = parts[0] - x = numbers[0] ?: 0.0 - y = numbers[1] ?: 0.0 - z = numbers[2] ?: 0.0 - } - - override fun matches(context: CheckContext): Boolean { - val current = context.player.distanceTo(world, x, y, z) ?: return false - return current <= distance - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/builtin/TextChecks.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/builtin/TextChecks.kt deleted file mode 100644 index 7153b23f1..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/builtin/TextChecks.kt +++ /dev/null @@ -1,86 +0,0 @@ -@file:OptIn(org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi::class) - -package org.pnfolder.pnlibrary.api.checks.builtin - -import org.pnfolder.pnlibrary.api.checks.Check -import org.pnfolder.pnlibrary.api.checks.CheckContext -import org.pnfolder.pnlibrary.api.checks.internal.CheckSerializer -import org.pnfolder.pnlibrary.api.config.ConfigSerializeWith -import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import java.util.UUID -import java.util.regex.PatternSyntaxException - -/** - * Matches when the whole [input] fits the regular expression [regex]. - * - * [input] is a context value or placeholder name, or plain text with `[name]`, `{name}` or `%name%` parts. - * - * @property input value to test - * @property regex Java regular expression the entire value must match - * @throws IllegalArgumentException when [regex] is not a valid expression - */ -@ConfigSerializeWith(CheckSerializer::class) -data class RegexCheck( - val input: String = "", - val regex: String = ".*", -) : Check { - private val pattern: Regex = try { - Regex(regex) - } catch (error: PatternSyntaxException) { - throw IllegalArgumentException("Invalid regular expression '$regex': ${error.description}", error) - } - - override fun matches(context: CheckContext): Boolean = pattern.matches(context.textOf(input)) -} - -/** - * Matches when the length of [input] is from [min] to [max] characters. - * - * @property input value to measure - * @property min shortest allowed length - * @property max longest allowed length - * @throws IllegalArgumentException when [min] is negative or above [max] - */ -@ConfigSerializeWith(CheckSerializer::class) -data class LengthCheck( - val input: String = "", - val min: Int = 0, - val max: Int = Int.MAX_VALUE, -) : Check { - init { require(min in 0..max) { "Length range must satisfy 0 <= min <= max" } } - - override fun matches(context: CheckContext): Boolean = context.textOf(input).length in min..max -} - -/** Kinds of value recognized by [TypeCheck]. */ -enum class ValueType { - /** A whole number. */ - INT, - - /** Any number, with or without a fraction. */ - DOUBLE, - - /** A UUID in the usual dashed form. */ - UUID, -} - -/** - * Matches when [input] can be read as a [type]. - * - * @property input value to test - * @property type expected kind of value - */ -@ConfigSerializeWith(CheckSerializer::class) -data class TypeCheck( - val input: String = "", - val type: ValueType = ValueType.INT, -) : Check { - override fun matches(context: CheckContext): Boolean { - val text = context.textOf(input).trim() - return when (type) { - ValueType.INT -> text.toLongOrNull() != null - ValueType.DOUBLE -> text.toDoubleOrNull() != null - ValueType.UUID -> runCatchingNonFatal { UUID.fromString(text) }.isSuccess - } - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/internal/CheckExpression.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/internal/CheckExpression.kt deleted file mode 100644 index cafb9b110..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/internal/CheckExpression.kt +++ /dev/null @@ -1,70 +0,0 @@ -@file:OptIn(org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi::class) - -package org.pnfolder.pnlibrary.api.checks.internal - -import org.pnfolder.pnlibrary.api.checks.Check -import org.pnfolder.pnlibrary.api.checks.builtin.Comparison -import org.pnfolder.pnlibrary.api.checks.builtin.NotCheck -import org.pnfolder.pnlibrary.api.checks.builtin.PermissionCheck -import org.pnfolder.pnlibrary.api.checks.builtin.RegexCheck -import org.pnfolder.pnlibrary.api.checks.builtin.ValueCheck - -/** - * Reads a requirement written as one line of text. - * - * | Text | Meaning | - * |---|---| - * | `%vault_eco_balance% >= 100` | number comparison with `==`, `!=`, `>=`, `<=`, `>`, `<` | - * | `%rank% is vip` | text equal, ignoring case | - * | `%player_name% contains Al` | text contains | - * | `%code% matches [A-Z]{2}-\d+` | the whole text fits a regular expression | - * | `permission shop.use` | the player has the permission | - * - * A `!` or `not` before the text turns it around. - */ -internal object CheckExpression { - private val symbol = Regex("""^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$""") - private val word = Regex("""^(.+?)\s+(is|contains|matches)\s+(.+)$""", RegexOption.IGNORE_CASE) - private val permission = Regex("""^permission\s+(\S+)$""", RegexOption.IGNORE_CASE) - - /** - * Builds the condition written in [text]. - * - * @throws IllegalArgumentException when [text] is none of the supported forms - */ - fun parse(text: String): Check { - var body = text.trim() - var negated = false - if (body.startsWith("!")) { - negated = true - body = body.substring(1).trim() - } else if (body.startsWith("not ", ignoreCase = true)) { - negated = true - body = body.substring(4).trim() - } - val condition = permission.matchEntire(body)?.let { PermissionCheck(it.groupValues[1]) } - ?: word.matchEntire(body)?.let { match -> wordCondition(match) } - ?: symbol.matchEntire(body)?.let { match -> - ValueCheck( - match.groupValues[1].trim(), - CheckSerializer.comparators.getValue(match.groupValues[2]), - match.groupValues[3].trim(), - ) - } - ?: throw IllegalArgumentException( - "Cannot read requirement '$text'. Write a comparison such as '%vault_eco_balance% >= 100', " + - "'%rank% is vip' or 'permission shop.use', or use 'type:'", - ) - return if (negated) NotCheck(condition) else condition - } - - private fun wordCondition(match: MatchResult): Check { - val left = match.groupValues[1].trim() - val right = match.groupValues[3].trim() - return when (match.groupValues[2].lowercase()) { - "is" -> ValueCheck(left, Comparison.EQUALS, right, ignoreCase = true) - "contains" -> ValueCheck(left, Comparison.CONTAINS, right, ignoreCase = false) - else -> RegexCheck(left, right) - } - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/internal/CheckFields.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/internal/CheckFields.kt deleted file mode 100644 index 3618b67f3..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/internal/CheckFields.kt +++ /dev/null @@ -1,68 +0,0 @@ -package org.pnfolder.pnlibrary.api.checks.internal - -import org.pnfolder.pnlibrary.api.checks.Check -import org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi -import java.util.Locale - -/** Reads the keys of one object ignoring case, `_`, `-` and spaces in their spelling. */ -@OptIn(InternalPnLibraryApi::class) -internal class Fields(source: Map) { - private val byKey = source.entries.associate { normalize(it.key) to it.value } - - fun raw(vararg keys: String): Any? = keys.firstNotNullOfOrNull { byKey[normalize(it)] } - - fun text(vararg keys: String): String? = raw(*keys)?.toString() - - fun required(vararg keys: String): String = - text(*keys) ?: throw IllegalArgumentException("Missing '${keys.first()}'") - - fun input(): String = required("input") - - fun output(): String = text("output") ?: "" - - fun int(key: String): Int? = raw(key)?.let { - (it as? Number)?.toInt() ?: it.toString().trim().toIntOrNull() - ?: throw IllegalArgumentException("'$key' must be a whole number but was '$it'") - } - - fun double(key: String): Double? = raw(key)?.let { - (it as? Number)?.toDouble() ?: it.toString().trim().toDoubleOrNull() - ?: throw IllegalArgumentException("'$key' must be a number but was '$it'") - } - - fun bool(key: String): Boolean? = raw(key)?.let { - it as? Boolean ?: it.toString().trim().lowercase(Locale.ROOT).let { text -> - when (text) { - "true", "yes", "on" -> true - "false", "no", "off" -> false - else -> throw IllegalArgumentException("'$key' must be true or false but was '$it'") - } - } - } - - fun list(key: String): List = when (val value = raw(key)) { - null -> emptyList() - is Iterable<*> -> value.map { it.toString() } - else -> listOf(value.toString()) - } - - fun condition(key: String): Check? = raw(key)?.let { CheckSerializer.read(it, key) } - - fun checks(key: String): List = when (val value = raw(key)) { - null -> emptyList() - is Iterable<*> -> value.map { CheckSerializer.read(it, key) } - else -> throw IllegalArgumentException("'$key' must be a list of checks") - } - - /** A probability as `0.25` or `25%`. */ - fun probability(key: String): Double? = raw(key)?.let { - val text = it.toString().trim() - val number = if (text.endsWith("%")) text.dropLast(1).trim().toDoubleOrNull()?.div(100) else text.toDoubleOrNull() - number ?: throw IllegalArgumentException("'$key' must be a probability such as 0.25 or 25% but was '$it'") - } - - companion object { - fun normalize(key: String): String = - key.lowercase(Locale.ROOT).filter { it != '_' && it != '-' && it != ' ' } - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/internal/CheckSerializer.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/internal/CheckSerializer.kt deleted file mode 100644 index ada1bde05..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/internal/CheckSerializer.kt +++ /dev/null @@ -1,244 +0,0 @@ -package org.pnfolder.pnlibrary.api.checks.internal - -import org.pnfolder.pnlibrary.api.checks.Check -import org.pnfolder.pnlibrary.api.checks.builtin.AllCheck -import org.pnfolder.pnlibrary.api.checks.builtin.AnyCheck -import org.pnfolder.pnlibrary.api.checks.builtin.AtLeastCheck -import org.pnfolder.pnlibrary.api.checks.builtin.ChanceCheck -import org.pnfolder.pnlibrary.api.checks.builtin.Comparison -import org.pnfolder.pnlibrary.api.checks.builtin.ExperienceCheck -import org.pnfolder.pnlibrary.api.checks.builtin.FlagCheck -import org.pnfolder.pnlibrary.api.checks.builtin.ItemCheck -import org.pnfolder.pnlibrary.api.checks.builtin.LengthCheck -import org.pnfolder.pnlibrary.api.checks.builtin.NamedCheck -import org.pnfolder.pnlibrary.api.checks.builtin.NearCheck -import org.pnfolder.pnlibrary.api.checks.builtin.NotCheck -import org.pnfolder.pnlibrary.api.checks.builtin.PermissionCheck -import org.pnfolder.pnlibrary.api.checks.builtin.PermissionsCheck -import org.pnfolder.pnlibrary.api.checks.builtin.RegexCheck -import org.pnfolder.pnlibrary.api.checks.builtin.TypeCheck -import org.pnfolder.pnlibrary.api.checks.builtin.ValueCheck -import org.pnfolder.pnlibrary.api.checks.builtin.ValueType -import org.pnfolder.pnlibrary.api.config.ConfigSerializationContext -import org.pnfolder.pnlibrary.api.config.ConfigSerializer -import org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi -import org.pnfolder.pnlibrary.api.internal.Suggestions -import java.util.Locale - -/** - * Reads and writes conditions in the requirement format used by menu plugins. - * - * A condition is an object with a `type` and the fields of that type. A `!` before the type negates it. - * Key spelling does not matter: `name_contains`, `name-contains` and `nameContains` are the same key. - * - * | `type` | Fields | - * |---|---| - * | `has permission` | `permission` | - * | `has permissions` | `permissions`, `minimum` | - * | `has item` | `material`, `amount`, `name`, `name_contains`, `lore_contains`, `name_ignorecase` | - * | `has exp` | `amount`, `level` | - * | `is near` | `location` as `world,x,y,z`, `distance` | - * | `string equals`, `string equals ignorecase`, `string contains` | `input`, `output` | - * | `string length` | `input`, `min`, `max` | - * | `is object` | `input`, `object` as `INT`, `DOUBLE` or `UUID` | - * | `regex matches` | `input`, `regex` | - * | `==`, `!=`, `>=`, `<=`, `>`, `<` | `input`, `output`, compared as numbers | - */ -@InternalPnLibraryApi -object CheckSerializer : ConfigSerializer { - internal val comparators = mapOf( - "==" to Comparison.NUMBER_EQUALS, - "!=" to Comparison.NUMBER_NOT_EQUALS, - ">=" to Comparison.GREATER_OR_EQUAL, - "<=" to Comparison.LESS_OR_EQUAL, - ">" to Comparison.GREATER_THAN, - "<" to Comparison.LESS_THAN, - ) - - /** Reads a [Check] from its configuration form. */ - override fun deserialize(value: Any?, context: ConfigSerializationContext): Check = read(value, context.path) - - /** - * Reads one check: an object with a `type`, or a text naming a requirement declared under `checks:`. - * - * @throws IllegalArgumentException when [value] is neither, or the object is invalid - */ - fun read(value: Any?, key: String): Check = when (value) { - is Map<*, *> -> parse(value.entries.associate { it.key.toString() to it.value }) - is String -> { - require(value.isNotBlank()) { "'$key' must name a check or be an object with a 'type'" } - NamedCheck(value.trim()) - } - else -> throw IllegalArgumentException("'$key' must name a check or be an object with a 'type'") - } - - /** Writes [check] as its configuration form: the name for a [NamedCheck], otherwise an object. */ - fun write(check: Check): Any = if (check is NamedCheck) check.name else describe(check) - ?: throw UnsupportedOperationException("${check.javaClass.simpleName} cannot be written to configuration") - - /** Writes [value] in its configuration form. */ - override fun serialize(value: Check, context: ConfigSerializationContext): Any? = write(value) - - /** - * Builds a condition from the fields of one object, including its `type`. - * - * @throws IllegalArgumentException when the type is missing or unknown or a field is invalid - */ - fun parse(fields: Map, alsoValid: Set = emptySet()): Check { - val reader = Fields(fields) - val rawType = reader.text("type") ?: throw IllegalArgumentException("A condition needs a 'type'") - val negated = rawType.trim().startsWith("!") - val type = rawType.trim().removePrefix("!").trim().let(::normalizeType) - checkKeys(type, fields.keys, alsoValid) - val condition = build(type, reader) - return if (negated) NotCheck(condition) else condition - } - - /** Writes [condition] as an object with a `type`, or returns `null` when it has no such form. */ - fun describe(condition: Check): Map? = when (condition) { - is PermissionCheck -> mapOf("type" to "has permission", "permission" to condition.permission) - is PermissionsCheck -> mapOf( - "type" to "has permissions", - "permissions" to condition.permissions, - "minimum" to condition.minimum, - ).filterValues { it != null } - is ItemCheck -> linkedMapOf( - "type" to "has item", "material" to condition.material, "amount" to condition.amount, - "name" to condition.name, "name_contains" to condition.nameContains, - "lore_contains" to condition.loreContains, "name_ignorecase" to condition.ignoreCase, - ).filterValues { it != null } - is ExperienceCheck -> mapOf("type" to "has exp", "amount" to condition.amount, "level" to condition.level) - is NearCheck -> mapOf("type" to "is near", "location" to condition.location, "distance" to condition.distance) - is RegexCheck -> mapOf("type" to "regex matches", "input" to condition.input, "regex" to condition.regex) - is LengthCheck -> mapOf( - "type" to "string length", "input" to condition.input, "min" to condition.min, "max" to condition.max, - ) - is TypeCheck -> mapOf("type" to "is object", "input" to condition.input, "object" to condition.type.name) - is ValueCheck -> describeValue(condition) - is FlagCheck -> mapOf("type" to "flag", "name" to condition.flag, "equals" to condition.enabled) - is ChanceCheck -> mapOf("type" to "chance", "probability" to condition.probability) - is AllCheck -> mapOf("type" to "all", "checks" to condition.checks.map(::write)) - is AnyCheck -> mapOf("type" to "any", "checks" to condition.checks.map(::write)) - is AtLeastCheck -> mapOf("type" to "at-least", "count" to condition.count, "checks" to condition.checks.map(::write)) - is NotCheck -> condition.check?.let(::describe)?.let { inner -> - val type = inner["type"].toString() - inner + ("type" to if (type.startsWith("!")) type.removePrefix("!") else "!$type") - } - else -> null - } - - private fun describeValue(condition: ValueCheck): Map { - val symbol = comparators.entries.firstOrNull { it.value == condition.operator }?.key - if (symbol != null) { - return mapOf("type" to symbol, "input" to condition.source, "output" to condition.value) - } - val named = when { - condition.operator == Comparison.EQUALS && condition.ignoreCase -> "string equals ignorecase" - condition.operator == Comparison.EQUALS -> "string equals" - condition.operator == Comparison.CONTAINS && !condition.ignoreCase -> "string contains" - else -> null - } - if (named != null) return mapOf("type" to named, "input" to condition.source, "output" to condition.value) - return mapOf( - "type" to "compare", "source" to condition.source, "operator" to condition.operator.name, - "value" to condition.value, "ignore_case" to condition.ignoreCase, - ) - } - - private val typeNames = listOf( - "permission", "all", "any", "not", "at-least", "chance", - "has permission", "has permissions", "has item", "has exp", "is near", "string equals", - "string equals ignorecase", "string contains", "string length", "is object", "regex matches", - ) + comparators.keys - - private fun allowedKeys(type: String): Set? = when (type) { - "has permission", "permission", "perm" -> setOf("permission", "node") - "has permissions", "permissions" -> setOf("permissions", "minimum") - "has item", "item" -> - setOf("material", "amount", "name", "name_contains", "lore_contains", "name_ignorecase", "lore_ignorecase") - "has exp", "exp" -> setOf("amount", "level") - "is near", "near" -> setOf("location", "distance") - "string equals", "string equals ignorecase", "string contains" -> setOf("input", "output") - "string length", "length" -> setOf("input", "min", "max") - "is object" -> setOf("input", "object") - "regex matches", "regex" -> setOf("input", "regex") - "compare", "value" -> setOf("source", "input", "operator", "value", "output", "ignore_case") - "flag", "enabled" -> setOf("name", "equals") - "chance" -> setOf("probability") - "not" -> setOf("check") - "all", "any" -> setOf("checks") - "at least" -> setOf("count", "checks") - in comparators -> setOf("input", "output") - else -> null - } - - /** Rejects a key the [type] does not use, so a typo such as `permision` is not silently ignored. */ - private fun checkKeys(type: String, keys: Set, alsoValid: Set) { - val allowed = allowedKeys(type) ?: return - val valid = allowed + "type" + alsoValid - val known = valid.map(Fields::normalize).toSet() - for (key in keys) { - if (Fields.normalize(key) in known) continue - throw IllegalArgumentException( - "Unknown key '$key' for type '$type'.${Suggestions.hint(key, valid)} " + - "Valid keys: ${(allowed + alsoValid).joinToString()}.", - ) - } - } - - private fun normalizeType(type: String): String { - val lower = type.lowercase(Locale.ROOT) - return if (lower in comparators) lower else lower.replace('_', ' ').replace('-', ' ').trim().replace(Regex("\\s+"), " ") - } - - private fun build(type: String, fields: Fields): Check = when (type) { - "has permission", "permission", "perm" -> - PermissionCheck(fields.required("permission", "node")) - "has permissions", "permissions" -> - PermissionsCheck(fields.list("permissions"), fields.int("minimum")) - "has item", "item" -> ItemCheck( - material = fields.required("material"), - amount = fields.int("amount") ?: 1, - name = fields.text("name"), - nameContains = fields.text("name_contains"), - loreContains = fields.text("lore_contains"), - ignoreCase = fields.bool("name_ignorecase") ?: fields.bool("lore_ignorecase") ?: false, - ) - "has exp", "exp" -> ExperienceCheck(fields.int("amount") ?: 0, fields.bool("level") ?: false) - "is near", "near" -> NearCheck(fields.required("location"), fields.double("distance") ?: 5.0) - "string equals" -> ValueCheck(fields.input(), Comparison.EQUALS, fields.output(), ignoreCase = false) - "string equals ignorecase" -> ValueCheck(fields.input(), Comparison.EQUALS, fields.output(), ignoreCase = true) - "string contains" -> ValueCheck(fields.input(), Comparison.CONTAINS, fields.output(), ignoreCase = false) - "string length", "length" -> LengthCheck( - fields.input(), fields.int("min") ?: 0, fields.int("max") ?: Int.MAX_VALUE, - ) - "is object" -> TypeCheck(fields.input(), valueType(fields.required("object"))) - "regex matches", "regex" -> RegexCheck(fields.input(), fields.required("regex")) - "compare", "value" -> ValueCheck( - source = fields.required("source", "input"), - operator = comparison(fields.text("operator") ?: "EQUALS"), - value = fields.text("value", "output") ?: "", - ignoreCase = fields.bool("ignore_case") ?: true, - ) - "flag", "enabled" -> FlagCheck(fields.required("name"), fields.bool("equals") ?: true) - "chance" -> ChanceCheck(fields.probability("probability") ?: 1.0) - "not" -> NotCheck(fields.condition("check")) - "all" -> AllCheck(fields.checks("checks")) - "any" -> AnyCheck(fields.checks("checks")) - "at least" -> fields.checks("checks").let { AtLeastCheck(fields.int("count") ?: 1, it) } - in comparators -> ValueCheck(fields.input(), comparators.getValue(type), fields.output()) - else -> throw IllegalArgumentException( - "Unknown condition type '$type'.${Suggestions.hint(type, typeNames)} Types: ${typeNames.joinToString()}.", - ) - } - - private fun valueType(name: String): ValueType = - ValueType.values().firstOrNull { it.name.equals(name, ignoreCase = true) } - ?: throw IllegalArgumentException("Unknown object type '$name'. Use INT, DOUBLE or UUID") - - private fun comparison(name: String): Comparison { - val wanted = name.uppercase(Locale.ROOT).replace('-', '_').replace(' ', '_') - return Comparison.values().firstOrNull { it.name == wanted } - ?: throw IllegalArgumentException("Unknown comparison '$name'") - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/internal/RequirementSerializer.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/internal/RequirementSerializer.kt deleted file mode 100644 index 3a625197d..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/checks/internal/RequirementSerializer.kt +++ /dev/null @@ -1,188 +0,0 @@ -package org.pnfolder.pnlibrary.api.checks.internal - -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.checks.Requirement -import org.pnfolder.pnlibrary.api.config.ConfigSerializationContext -import org.pnfolder.pnlibrary.api.config.ConfigSerializer -import org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi -import org.pnfolder.pnlibrary.api.internal.Suggestions - -/** - * Reads and writes a [Requirement]. - * - * - Short: `check:` with one check, plus `deny` and `success`. - * - DeluxeMenus: `requirements:` with named entries, `minimum_requirements`, `stop_at_success`, - * `deny_commands` and `success_commands`. - * - One entry: the fields of a check (`type`, …) or `if: "%x% >= 5"`, plus `optional`, `deny` and `success`. - * - Text: `"%vault_eco_balance% >= 100"`, a check with nothing to run. - * - * `deny` and `success` hold actions written with a `type`. `deny_commands` and `success_commands` are their - * DeluxeMenus names. - */ -@InternalPnLibraryApi -object RequirementSerializer : ConfigSerializer { - private val shortKeys = listOf("check", "deny", "success", "deny_commands", "success_commands") - private val groupKeys = listOf( - "requirements", "minimum_requirements", "stop_at_success", "deny", "success", "deny_commands", "success_commands", - ) - private val entryKeys = listOf("optional", "deny_commands", "success_commands", "deny", "success", "if") - - /** Reads a [Requirement] from a single expression or an object with `checks`. */ - override fun deserialize(value: Any?, context: ConfigSerializationContext): Requirement { - if (value is String) return Requirement(CheckExpression.parse(value)) - require(value is Map<*, *>) { - "A check must be an object with 'check:', 'requirements:' or a 'type', or a text such as '%x% >= 5'" - } - val fields = value.entries.associate { it.key.toString() to it.value } - val lower = fields.mapKeys { it.key.lowercase() } - return when { - "requirements" in lower -> group(fields, lower, context) - "check" in lower -> short(fields, lower, context) - else -> Requirement(mapOf("check" to entry(fields, context, context.path))) - } - } - - private fun short(fields: Map, lower: Map, context: ConfigSerializationContext): Requirement { - unknownKeys(fields.keys, shortKeys, "check") - return Requirement( - CheckSerializer.read(lower["check"], "check"), - deny = actions(lower, "deny_commands", "deny", context), - success = actions(lower, "success_commands", "success", context), - ) - } - - private fun group(fields: Map, lower: Map, context: ConfigSerializationContext): Requirement { - unknownKeys(fields.keys, groupKeys, "requirements") - val raw = lower["requirements"] - require(raw is Map<*, *>) { "'requirements' must hold named checks" } - val entries = LinkedHashMap() - raw.forEach { (name, item) -> - val path = "${context.path}.requirements.$name" - entries[name.toString()] = when (item) { - is String -> Requirement.Entry(CheckExpression.parse(item)) - is Map<*, *> -> if (context.decoder != null) { - context.decode(item, Requirement.Entry::class.java, path) - } else { - entry(item.entries.associate { it.key.toString() to it.value }, context, path) - } - else -> throw IllegalArgumentException("Check '$name' must be an object with a 'type'") - } - } - return Requirement( - entries = entries, - minimum = whole(lower["minimum_requirements"], "minimum_requirements") ?: 0, - stopAtSuccess = bool(lower["stop_at_success"], "stop_at_success") ?: false, - success = actions(lower, "success_commands", "success", context), - deny = actions(lower, "deny_commands", "deny", context), - ) - } - - /** Reads one entry of a `requirements:` block; used through [RequirementEntrySerializer] so errors carry its path. */ - internal fun entry(fields: Map, context: ConfigSerializationContext, path: String): Requirement.Entry { - val lower = fields.mapKeys { it.key.lowercase() } - val expression = lower["if"] - val check = if (expression != null) { - require(!lower.containsKey("type")) { "Use either 'if' or 'type', not both" } - unknownKeys(fields.keys, entryKeys, "if") - CheckExpression.parse(expression.toString()) - } else { - CheckSerializer.parse(fields.filterKeys { it.lowercase() !in entryKeys }, entryKeys.toSet()) - } - val at = context.copy(path = path) - return Requirement.Entry( - check = check, - optional = bool(lower["optional"], "optional") ?: false, - success = actions(lower, "success_commands", "success", at), - deny = actions(lower, "deny_commands", "deny", at), - ) - } - - /** Writes [value] in the shortest configuration form that keeps its meaning. */ - override fun serialize(value: Requirement, context: ConfigSerializationContext): Any? { - val single = value.entries.entries.singleOrNull() - if (single != null && single.key == "check" && !single.value.optional && value.minimum == 0 && - single.value.deny.isEmpty() && single.value.success.isEmpty() - ) { - val out = linkedMapOf("check" to CheckSerializer.write(checkOf(single.value))) - if (value.deny.isNotEmpty()) out["deny"] = written(value.deny, context, "deny") - if (value.success.isNotEmpty()) out["success"] = written(value.success, context, "success") - return out - } - val entries = linkedMapOf() - value.entries.forEach { (name, entry) -> - val written = CheckSerializer.describe(checkOf(entry)) - ?: throw UnsupportedOperationException("Check '$name' cannot be written to configuration") - val out = LinkedHashMap(written) - if (entry.optional) out["optional"] = true - if (entry.success.isNotEmpty()) out["success"] = written(entry.success, context, "requirements.$name.success") - if (entry.deny.isNotEmpty()) out["deny"] = written(entry.deny, context, "requirements.$name.deny") - entries[name] = out - } - val out = linkedMapOf("requirements" to entries) - if (value.minimum > 0) out["minimum_requirements"] = value.minimum - if (value.stopAtSuccess) out["stop_at_success"] = true - if (value.success.isNotEmpty()) out["success"] = written(value.success, context, "success") - if (value.deny.isNotEmpty()) out["deny"] = written(value.deny, context, "deny") - return out - } - - private fun checkOf(entry: Requirement.Entry) = - entry.check ?: throw UnsupportedOperationException("A check without a type cannot be saved") - - private fun unknownKeys(keys: Set, valid: List, next: String) { - keys.firstOrNull { it.lowercase() !in valid }?.let { key -> - throw IllegalArgumentException( - "Unknown key '$key' next to '$next'.${Suggestions.hint(key, valid)} Valid keys: ${valid.joinToString()}.", - ) - } - } - - /** Reads `deny`/`success` (or their DeluxeMenus names) as a list of actions written with a `type`. */ - private fun actions( - fields: Map, long: String, short: String, context: ConfigSerializationContext, - ): List { - require(!(fields.containsKey(long) && fields.containsKey(short))) { "Use either '$short' or '$long', not both" } - val key = if (fields.containsKey(long)) long else short - return when (val source = fields[key]) { - null -> emptyList() - is Iterable<*> -> source.mapIndexed { index, item -> action(item, context, "${context.path}.$key[$index]") } - else -> listOf(action(source, context, "${context.path}.$key")) - } - } - - private fun action(item: Any?, context: ConfigSerializationContext, path: String): Action { - checkNotNull(context.decoder) { "Actions can only be read while a configuration loads" } - return context.decode(item, Action::class.java, path) - } - - private fun written(actions: List, context: ConfigSerializationContext, key: String): List = - actions.mapIndexed { index, action -> context.encode(action, Action::class.java, "${context.path}.$key[$index]") } - - private fun whole(raw: Any?, key: String): Int? = raw?.let { - (it as? Number)?.toInt() ?: it.toString().trim().toIntOrNull() - ?: throw IllegalArgumentException("'$key' must be a whole number but was '$it'") - } - - private fun bool(raw: Any?, key: String): Boolean? = raw?.let { - it as? Boolean ?: when (it.toString().trim().lowercase()) { - "true", "yes", "on" -> true - "false", "no", "off" -> false - else -> throw IllegalArgumentException("'$key' must be true or false but was '$it'") - } - } -} - -/** Reads one entry of a DeluxeMenus `requirements:` block: the fields of a check plus `optional`, `deny` and `success`. */ -@InternalPnLibraryApi -object RequirementEntrySerializer : ConfigSerializer { - /** Reads one check entry from an expression or an object with a `type`. */ - override fun deserialize(value: Any?, context: ConfigSerializationContext): Requirement.Entry { - if (value is String) return Requirement.Entry(CheckExpression.parse(value)) - require(value is Map<*, *>) { "A check must be an object with a 'type'" } - return RequirementSerializer.entry(value.entries.associate { it.key.toString() to it.value }, context, context.path) - } - - /** Always fails: an entry is written by its [Requirement]. */ - override fun serialize(value: Requirement.Entry, context: ConfigSerializationContext): Any? = - throw UnsupportedOperationException("A requirement entry is written by its requirement") -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandContext.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandContext.kt index 2c762647f..43ed74ebf 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandContext.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandContext.kt @@ -23,7 +23,4 @@ data class CommandContext( /** Returns whether a parsed argument named [name] is available. */ fun contains(name: String): Boolean = parsedValues.containsKey(name) - - internal fun withParsedValues(values: Map, input: String = currentInput): CommandContext = - copy(parsedValues = values, currentInput = input) } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandRegistration.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandRegistration.kt index e40d89772..98607e602 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandRegistration.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandRegistration.kt @@ -1,5 +1,7 @@ package org.pnfolder.pnlibrary.api.commands +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition + /** Closeable handle for one live native command registration. */ interface CommandRegistration : AutoCloseable { /** Portable definition represented by this registration. */ diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandSender.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandSender.kt index 6e34f664d..2f4953749 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandSender.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandSender.kt @@ -5,38 +5,33 @@ import net.kyori.adventure.text.Component import org.pnfolder.pnlibrary.api.audiences.AudienceSender import org.pnfolder.pnlibrary.api.audiences.Delivery -/** Platform-neutral command sender exposed to command handlers. */ +/** + * Whoever ran a command: the console or a player. It is an [AudienceSender] with output suited to commands. + * + * ```kotlin + * command("ping") { + * execute { ctx -> ctx.sender.send(Component.text("pong")) } + * } + * ``` + */ interface CommandSender : AudienceSender { - /** Stable identity used for cooldowns and audit records. */ - override val id: String - - /** Human-readable sender name. */ - override val name: String - - /** Whether this sender represents the server console. */ - override val isConsole: Boolean - /** * Whether clickable and hoverable chat components reach this sender intact. * - * False for the console, and for players on a server whose chat transport fell back to plain text. Senders - * for which it is false should be shown text that does not rely on buttons. + * `false` for the console, and for players on a server whose chat fell back to plain text; show such senders + * text that does not rely on buttons. */ val supportsInteraction: Boolean get() = !isConsole - /** Returns whether this sender has [permission]. */ - override fun hasPermission(permission: String): Boolean - /** Sends one Adventure component to this sender. */ fun send(message: Component) - /** Sends [text] as a normal chat message. */ override fun sendMessage(text: Component) = send(text) - /** Falls back to chat output when the platform has no specialized action bar adapter. */ + // Falls back to chat when the platform has no action bar for generic senders. override fun actionBar(text: Component) = send(text) - /** Returns [Delivery.Unsupported] because generic command senders cannot play sounds. */ + // Generic command senders cannot play sounds. override fun playSound(sound: Sound): Delivery = Delivery.Unsupported } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec.kt new file mode 100644 index 000000000..36afe6014 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/definition/ArgumentSpec.kt @@ -0,0 +1,59 @@ +package org.pnfolder.pnlibrary.api.commands.definition + +/** + * What a platform needs to know about an [ArgumentType] to validate and suggest it natively, such as the + * Brigadier tree of a modern Paper server, before the portable parser runs. + * + * @property kind the shape of the accepted token + * @property minimum lowest accepted number for numeric kinds, or `null` for no bound + * @property maximum highest accepted number for numeric kinds, or `null` for no bound + * @property choices the accepted values of a [Kind.CHOICE], also offered as suggestions + */ +class ArgumentSpec private constructor( + val kind: Kind, + val minimum: Double?, + val maximum: Double?, + choices: List, +) { + /** The shape of a token. */ + enum class Kind { TEXT, INTEGER, LONG, DECIMAL, BOOLEAN, CHOICE, GREEDY } + + val choices: List = choices.toList() + + /** Specs of the built-in argument shapes. */ + companion object { + /** Any single word. */ + @JvmField + val TEXT: ArgumentSpec = ArgumentSpec(Kind.TEXT, null, null, emptyList()) + + /** Every remaining word of the line, joined by single spaces. */ + @JvmField + val GREEDY: ArgumentSpec = ArgumentSpec(Kind.GREEDY, null, null, emptyList()) + + /** A true/false token. */ + @JvmField + val BOOLEAN: ArgumentSpec = ArgumentSpec(Kind.BOOLEAN, null, null, emptyList()) + + /** A whole number between [minimum] and [maximum]. */ + @JvmStatic + @JvmOverloads + fun integer(minimum: Int = Int.MIN_VALUE, maximum: Int = Int.MAX_VALUE): ArgumentSpec = + ArgumentSpec(Kind.INTEGER, minimum.toDouble(), maximum.toDouble(), emptyList()) + + /** A 64-bit whole number between [minimum] and [maximum]. */ + @JvmStatic + @JvmOverloads + fun long(minimum: Long = Long.MIN_VALUE, maximum: Long = Long.MAX_VALUE): ArgumentSpec = + ArgumentSpec(Kind.LONG, minimum.toDouble(), maximum.toDouble(), emptyList()) + + /** A decimal number between [minimum] and [maximum]. */ + @JvmStatic + @JvmOverloads + fun decimal(minimum: Double = -Double.MAX_VALUE, maximum: Double = Double.MAX_VALUE): ArgumentSpec = + ArgumentSpec(Kind.DECIMAL, minimum, maximum, emptyList()) + + /** One of [choices]. */ + @JvmStatic + fun choice(choices: List): ArgumentSpec = ArgumentSpec(Kind.CHOICE, null, null, choices) + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/ArgumentType.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/definition/ArgumentType.kt similarity index 71% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/ArgumentType.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/definition/ArgumentType.kt index 6f33283ca..48398df1a 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/ArgumentType.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/definition/ArgumentType.kt @@ -1,67 +1,12 @@ -package org.pnfolder.pnlibrary.api.commands +package org.pnfolder.pnlibrary.api.commands.definition -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.commands.error.CommandError +import org.pnfolder.pnlibrary.api.commands.error.InvalidArgument +import org.pnfolder.pnlibrary.api.commands.error.PlayerNotFound import java.math.BigDecimal import java.util.Locale -/** - * What a platform needs to know about an [ArgumentType] to validate and suggest it natively, such as the - * Brigadier tree of a modern Paper server, before the portable parser runs. - * - * @property kind the shape of the accepted token - * @property minimum lowest accepted number for numeric kinds, or `null` for no bound - * @property maximum highest accepted number for numeric kinds, or `null` for no bound - * @property choices the accepted values of a [Kind.CHOICE], also offered as suggestions - */ -class ArgumentSpec private constructor( - val kind: Kind, - val minimum: Double?, - val maximum: Double?, - choices: List, -) { - /** The shape of a token. */ - enum class Kind { TEXT, INTEGER, LONG, DECIMAL, BOOLEAN, CHOICE, GREEDY } - - val choices: List = choices.toList() - - /** Specs of the built-in argument shapes. */ - companion object { - /** Any single word. */ - @JvmField - val TEXT: ArgumentSpec = ArgumentSpec(Kind.TEXT, null, null, emptyList()) - - /** Every remaining word of the line, joined by single spaces. */ - @JvmField - val GREEDY: ArgumentSpec = ArgumentSpec(Kind.GREEDY, null, null, emptyList()) - - /** A true/false token. */ - @JvmField - val BOOLEAN: ArgumentSpec = ArgumentSpec(Kind.BOOLEAN, null, null, emptyList()) - - /** A whole number between [minimum] and [maximum]. */ - @JvmStatic - @JvmOverloads - fun integer(minimum: Int = Int.MIN_VALUE, maximum: Int = Int.MAX_VALUE): ArgumentSpec = - ArgumentSpec(Kind.INTEGER, minimum.toDouble(), maximum.toDouble(), emptyList()) - - /** A 64-bit whole number between [minimum] and [maximum]. */ - @JvmStatic - @JvmOverloads - fun long(minimum: Long = Long.MIN_VALUE, maximum: Long = Long.MAX_VALUE): ArgumentSpec = - ArgumentSpec(Kind.LONG, minimum.toDouble(), maximum.toDouble(), emptyList()) - - /** A decimal number between [minimum] and [maximum]. */ - @JvmStatic - @JvmOverloads - fun decimal(minimum: Double = -Double.MAX_VALUE, maximum: Double = Double.MAX_VALUE): ArgumentSpec = - ArgumentSpec(Kind.DECIMAL, minimum, maximum, emptyList()) - - /** One of [choices]. */ - @JvmStatic - fun choice(choices: List): ArgumentSpec = ArgumentSpec(Kind.CHOICE, null, null, choices) - } -} - /** Converts one command token into a typed value. */ fun interface ArgumentType { /** Parses one raw command token, returning `null` when it is invalid. */ diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandDefinition.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/definition/CommandDefinition.kt similarity index 93% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandDefinition.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/definition/CommandDefinition.kt index 6d5adcbbb..d399dc42f 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandDefinition.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/definition/CommandDefinition.kt @@ -1,6 +1,9 @@ -package org.pnfolder.pnlibrary.api.commands +package org.pnfolder.pnlibrary.api.commands.definition import net.kyori.adventure.text.Component +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.error.CommandError +import org.pnfolder.pnlibrary.api.commands.error.CommandErrorHandler import java.util.Collections import java.util.LinkedHashSet import java.util.Locale @@ -46,6 +49,7 @@ class CommandDefinition internal constructor( val aliases: Set = Collections.unmodifiableSet(LinkedHashSet(aliases)) companion object { + /** Starts a command builder for the root label [name]; the entry point for Java callers. */ @JvmStatic fun builder(name: String): CommandBuilder = CommandBuilder(name) } @@ -69,6 +73,7 @@ class CommandBuilder internal constructor(name: String) { private val children = mutableListOf() private val mounted = mutableListOf() + /** Adds alternative root labels that run the same command. */ fun aliases(vararg values: String): CommandBuilder = apply { values.forEach { value -> val alias = normalizeCommandName(value, "command alias", ALIAS_NAME) @@ -172,14 +177,17 @@ class CommandBuilder internal constructor(name: String) { /** Restricts root availability using [rule]. */ fun availableIf(rule: CommandAvailability): CommandBuilder = apply { availability = rule } + /** Adds a fixed-word subcommand configured by the Kotlin receiver [configure]. */ @JvmSynthetic fun literal(name: String, configure: CommandNodeBuilder.() -> Unit): CommandBuilder = literal(name, Consumer { builder -> builder.configure() }) + /** Adds a fixed-word subcommand configured by the Java [configure] callback. */ fun literal(name: String, configure: Consumer): CommandBuilder = apply { children += CommandNodeBuilder(CommandNodeKind.LITERAL, name).also(configure::accept) } + /** Adds a typed argument node configured by the Kotlin receiver [configure]. */ @JvmSynthetic fun argument( name: String, @@ -187,6 +195,7 @@ class CommandBuilder internal constructor(name: String) { configure: CommandNodeBuilder.() -> Unit, ): CommandBuilder = argument(name, type, Consumer { builder -> builder.configure() }) + /** Adds a typed argument node configured by the Java [configure] callback. */ fun argument( name: String, type: ArgumentType, @@ -239,6 +248,7 @@ class CommandBuilder internal constructor(name: String) { } } +/** Builds a [CommandDefinition] for the root label [name] with the Kotlin receiver [configure]. */ @JvmSynthetic fun command(name: String, configure: CommandBuilder.() -> Unit): CommandDefinition = CommandDefinition.builder(name).apply(configure).build() diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandNode.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/definition/CommandNode.kt similarity index 95% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandNode.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/definition/CommandNode.kt index 2884055a0..7fa78f48f 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandNode.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/definition/CommandNode.kt @@ -1,6 +1,9 @@ -package org.pnfolder.pnlibrary.api.commands +package org.pnfolder.pnlibrary.api.commands.definition import net.kyori.adventure.text.Component +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.error.CommandError +import org.pnfolder.pnlibrary.api.commands.error.CommandErrorHandler import java.util.Collections import java.util.Locale import java.util.function.Consumer @@ -188,14 +191,17 @@ class CommandNodeBuilder internal constructor( /** Installs an asynchronous suggestion [handler]. */ fun suggestsAsync(handler: SuggestionHandler): CommandNodeBuilder = apply { suggestions = handler } + /** Adds a fixed-word child node configured by the Kotlin receiver [configure]. */ @JvmSynthetic fun literal(name: String, configure: CommandNodeBuilder.() -> Unit): CommandNodeBuilder = literal(name, Consumer { builder -> builder.configure() }) + /** Adds a fixed-word child node configured by the Java [configure] callback. */ fun literal(name: String, configure: Consumer): CommandNodeBuilder = apply { children += CommandNodeBuilder(CommandNodeKind.LITERAL, name).also(configure::accept) } + /** Adds a typed argument child node configured by the Kotlin receiver [configure]. */ @JvmSynthetic fun argument( name: String, @@ -203,6 +209,7 @@ class CommandNodeBuilder internal constructor( configure: CommandNodeBuilder.() -> Unit, ): CommandNodeBuilder = argument(name, type, Consumer { builder -> builder.configure() }) + /** Adds a typed argument child node configured by the Java [configure] callback. */ fun argument( name: String, type: ArgumentType, diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandError.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/error/CommandError.kt similarity index 97% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandError.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/error/CommandError.kt index 1e36050df..ff67cc94a 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/CommandError.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/commands/error/CommandError.kt @@ -1,5 +1,6 @@ -package org.pnfolder.pnlibrary.api.commands +package org.pnfolder.pnlibrary.api.commands.error +import org.pnfolder.pnlibrary.api.commands.CommandContext import java.time.Duration /** @@ -11,7 +12,7 @@ import java.time.Duration * an unknown word and an unfinished command alike, until something more specific is set. * * Handlers are attached at five levels, and the most specific level that has one wins: a subcommand, a command, a - * plugin module, the whole plugin, and last the library's standard answer from `config.yml`. + * plugin module, the whole plugin, and last the library's standard answer from the library's settings. * * @property defaultMessage what the library says when no handler answers, or `null` to use the standard text of the * nearest built-in base class. It may contain `{name}` placeholders from [placeholders]. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/cooldowns/CooldownResult.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/cooldowns/CooldownResult.kt new file mode 100644 index 000000000..1ae4e1cdf --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/cooldowns/CooldownResult.kt @@ -0,0 +1,29 @@ +package org.pnfolder.pnlibrary.api.cooldowns + +import java.time.Duration + +/** + * Result of an atomic cooldown acquisition attempt. Create it with [allowed] or [denied]. + * + * @property allowed whether the caller acquired a new cooldown + * @property remaining time left on the existing cooldown when denied, otherwise zero + */ +class CooldownResult private constructor( + val allowed: Boolean, + val remaining: Duration, +) { + /** Renders as `allowed` or `denied: `. */ + override fun toString(): String = if (allowed) "allowed" else "denied: $remaining" + + companion object { + private val ALLOWED = CooldownResult(true, Duration.ZERO) + + /** Returns the shared result meaning no cooldown is active. */ + @JvmStatic + fun allowed(): CooldownResult = ALLOWED + + /** Returns a denied result with the time left on the active cooldown. */ + @JvmStatic + fun denied(remaining: Duration): CooldownResult = CooldownResult(false, remaining) + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/cooldowns/CooldownService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/cooldowns/CooldownService.kt index e513e8139..229a920f1 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/cooldowns/CooldownService.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/cooldowns/CooldownService.kt @@ -3,37 +3,13 @@ package org.pnfolder.pnlibrary.api.cooldowns import java.time.Duration import java.util.UUID -/** - * Result of an atomic cooldown acquisition attempt. Create it with [allowed] or [denied]. - * - * @property allowed whether the caller acquired a new cooldown - * @property remaining time left on the existing cooldown when denied, otherwise zero - */ -class CooldownResult private constructor( - val allowed: Boolean, - val remaining: Duration, -) { - /** Renders as `allowed` or `denied: `. */ - override fun toString(): String = if (allowed) "allowed" else "denied: $remaining" - - companion object { - private val ALLOWED = CooldownResult(true, Duration.ZERO) - - @JvmStatic - fun allowed(): CooldownResult = ALLOWED - - /** Returns a denied result with the time left on the active cooldown. */ - @JvmStatic - fun denied(remaining: Duration): CooldownResult = CooldownResult(false, remaining) - } -} - /** * Plugin-scoped, thread-safe cooldown storage based on monotonic elapsed time. * * Action names are trimmed and compared case-insensitively. Durations must not be * negative; a zero duration removes or immediately expires an entry. Methods that read - * or create cooldowns fail after [close], while cleanup operations remain idempotent. + * or create cooldowns fail after [close], while cleanup operations remain idempotent. Expired entries are dropped + * as the service is used, so a subject that is never asked again does not stay in memory. */ interface CooldownService : AutoCloseable { @@ -58,6 +34,12 @@ interface CooldownService : AutoCloseable { /** Removes every entry owned by this service. */ fun clear() + /** Removes every entry of [subject], such as when a player leaves; returns how many were removed. */ + fun clear(subject: UUID): Int + + /** The active cooldowns of [subject] by action with the time left, longest first; expired ones are not listed. */ + fun active(subject: UUID): Map + /** Number of active entries after opportunistic expiry cleanup. */ val size: Int } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/Dependencies.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/Dependencies.kt new file mode 100644 index 000000000..571949e7b --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/Dependencies.kt @@ -0,0 +1,89 @@ +package org.pnfolder.pnlibrary.api.dependencies + +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ManagedProductDependency + +/** Short factories for the unified dependency DSL. */ +object Dependencies { + /** Declares a pnLibrary-managed product dependency downloaded from a GitHub repository. */ + @JvmStatic + @JvmOverloads + fun managed( + component: String, + minimumVersion: String, + repositoryOwner: String, + repositoryName: String, + required: Boolean = true, + automaticDownload: Boolean = false, + forceAutomaticDownload: Boolean = false, + ): PluginDependency = ManagedProductDependency( + component, + minimumVersion, + repositoryOwner, + repositoryName, + required, + downloadPolicy(automaticDownload, forceAutomaticDownload), + ) + + /** Declares an external plugin dependency with a manual download page. */ + @JvmStatic + @JvmOverloads + fun plugin( + plugin: String, + minimumVersion: String, + downloadPage: String, + required: Boolean = true, + automaticDownload: Boolean = false, + forceAutomaticDownload: Boolean = false, + ): PluginDependency = ExternalPluginDependency.builder(plugin, minimumVersion) + .downloadPage(downloadPage) + .required(required) + .downloadPolicy(downloadPolicy(automaticDownload, forceAutomaticDownload)) + .build() + + /** Declares an external plugin dependency with a direct download checked by its SHA-256. */ + @JvmStatic + @JvmOverloads + fun plugin( + plugin: String, + minimumVersion: String, + downloadUrl: String, + sha256: String, + required: Boolean = true, + automaticDownload: Boolean = true, + forceAutomaticDownload: Boolean = false, + ): PluginDependency = ExternalPluginDependency.builder(plugin, minimumVersion) + .artifact(downloadUrl, sha256) + .required(required) + .downloadPolicy(downloadPolicy(automaticDownload, forceAutomaticDownload)) + .build() + + /** + * Declares an external plugin with several download addresses and no checksum. The first address is tried first, + * the others are mirrors tried in order when the one before does not answer; the file is taken as it came. + */ + @JvmStatic + @JvmOverloads + fun plugin( + plugin: String, + minimumVersion: String, + sources: List, + required: Boolean = true, + automaticDownload: Boolean = true, + forceAutomaticDownload: Boolean = false, + ): PluginDependency { + require(sources.isNotEmpty()) { "At least one download address is required" } + return ExternalPluginDependency.builder(plugin, minimumVersion) + .url(sources.first()) + .also { builder -> sources.drop(1).forEach(builder::mirror) } + .required(required) + .downloadPolicy(downloadPolicy(automaticDownload, forceAutomaticDownload)) + .build() + } + + private fun downloadPolicy(automatic: Boolean, forced: Boolean): DownloadPolicy = when { + forced -> DownloadPolicy.FORCED + automatic -> DownloadPolicy.AUTOMATIC + else -> DownloadPolicy.MANUAL + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/DependencyBuilder.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/DependencyBuilder.kt index 1ecd677b7..130e20286 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/DependencyBuilder.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/DependencyBuilder.kt @@ -1,6 +1,8 @@ package org.pnfolder.pnlibrary.api.dependencies -import org.pnfolder.pnlibrary.api.updates.ProductId +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ManagedProductDependency +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.version.SemanticVersion import java.util.Collections import java.util.function.Consumer @@ -9,6 +11,7 @@ import java.util.function.Consumer class DependencyBuilder { private val dependencies = mutableListOf() + /** Declares a dependency on another pnLibrary product. */ fun product(id: String, configure: Consumer): DependencyBuilder = apply { val builder = ProductBuilder(ProductId.of(id)) configure.accept(builder) @@ -19,6 +22,7 @@ class DependencyBuilder { dependencies += dependency } + /** Declares a dependency on an external plugin without a version bound. */ fun plugin(name: String, configure: Consumer): DependencyBuilder = apply { val builder = ExternalBuilder(name) configure.accept(builder) @@ -29,6 +33,7 @@ class DependencyBuilder { dependencies += dependency } + /** Declares a dependency on an external plugin with a minimum version. */ fun plugin(name: String, minimumVersion: String, configure: Consumer): DependencyBuilder = plugin(name) { builder -> builder.minimumVersion(minimumVersion) @@ -48,14 +53,20 @@ class DependencyBuilder { private var required = true private var policy = DownloadPolicy.MANUAL + /** Sets the lowest accepted product version, inclusive. */ fun minimumVersion(value: String): ProductBuilder = apply { minimum = SemanticVersion.parse(value) } + /** Sets the highest accepted product version, inclusive. */ fun maximumVersion(value: String): ProductBuilder = apply { maximumInclusive = SemanticVersion.parse(value) } + /** Sets the upper version bound, exclusive. */ fun maximumVersionExclusive(value: String): ProductBuilder = apply { maximumExclusive = SemanticVersion.parse(value) } + /** Sets the GitHub repository the product is downloaded from. */ fun github(owner: String, repository: String): ProductBuilder = apply { repositoryOwner = owner repositoryName = repository } + /** Sets whether the plugin refuses to start without this product; `true` by default. */ fun required(value: Boolean): ProductBuilder = apply { required = value } + /** Sets how a missing or outdated product is downloaded. */ fun downloadPolicy(value: DownloadPolicy): ProductBuilder = apply { policy = value } internal fun build(): ManagedProductDependency { @@ -75,28 +86,58 @@ class DependencyBuilder { init { require(name.isNotBlank()) { "External plugin name must not be blank" } } + /** Sets the lowest accepted plugin version, inclusive. */ fun minimumVersion(value: String): ExternalBuilder = apply { SemanticVersion.parse(value) minimum = value } + /** Sets the highest accepted plugin version, inclusive. */ fun maximumVersion(value: String): ExternalBuilder { SemanticVersion.parse(value) return add { it.maximumVersion(value) } } + /** Sets the upper version bound, exclusive. */ fun maximumVersionExclusive(value: String): ExternalBuilder { SemanticVersion.parse(value) return add { it.maximumVersionExclusive(value) } } + /** Sets the page where the administrator can download the plugin by hand. */ fun downloadPage(url: String): ExternalBuilder = add { it.downloadPage(url) } - fun artifact(url: String, size: Long, sha256: String): ExternalBuilder = add { it.artifact(url, size, sha256) } + /** Sets a direct download with the SHA-256 checksum the file must match. */ + fun artifact(url: String, sha256: String): ExternalBuilder = add { it.artifact(url, sha256) } + /** Sets a direct download URL without an integrity check. */ fun url(value: String): ExternalBuilder = add { it.url(value) } + /** Sets the short name people read in the notice about the missing plugin. */ + fun title(value: String): ExternalBuilder = add { it.title(value) } + /** Says why the plugin is needed, in a sentence or two. */ + fun description(value: String): ExternalBuilder = add { it.description(value) } + /** Adds another HTTPS address of the general file. */ + fun mirror(value: String): ExternalBuilder = add { it.mirror(value) } + /** Adds a file for some servers only; see [ExternalPluginDependency.Builder.variant]. */ + @JvmOverloads + fun variant( + url: String, + sha256: String? = null, + platforms: Set = emptySet(), + minecraftFrom: String? = null, + minecraftBefore: String? = null, + mirrors: List = emptyList(), + label: String? = null, + maxBytes: Long? = null, + ): ExternalBuilder = add { it.variant(url, sha256, platforms, minecraftFrom, minecraftBefore, mirrors, label, maxBytes) } + /** Sets the largest accepted size in bytes of the general file. */ + fun maxBytes(value: Long): ExternalBuilder = add { it.maxBytes(value) } + /** Sets whether the plugin refuses to start without this dependency; `true` by default. */ fun required(value: Boolean): ExternalBuilder = add { it.required(value) } /** Enables or disables staged plugin-ID verification. */ fun verifyPluginId(value: Boolean): ExternalBuilder = add { it.verifyPluginId(value) } /** Enables or disables staged plugin-version verification. */ fun verifyVersion(value: Boolean): ExternalBuilder = add { it.verifyVersion(value) } + /** Sets how a missing or outdated plugin is downloaded. */ fun downloadPolicy(value: DownloadPolicy): ExternalBuilder = add { it.downloadPolicy(value) } + /** Sets whether a missing plugin may be downloaded automatically. */ fun automaticDownload(value: Boolean): ExternalBuilder = add { it.automaticDownload(value) } + /** Sets whether the automatic download runs without asking an administrator. */ fun forceAutomaticDownload(value: Boolean): ExternalBuilder = add { it.forceAutomaticDownload(value) } private fun add(step: Consumer): ExternalBuilder = apply { settings += step } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/DownloadPolicy.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/DownloadPolicy.kt new file mode 100644 index 000000000..13094570a --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/DownloadPolicy.kt @@ -0,0 +1,8 @@ +package org.pnfolder.pnlibrary.api.dependencies + +/** Controls whether pnLibrary may stage a missing dependency. */ +enum class DownloadPolicy { + MANUAL, + AUTOMATIC, + FORCED +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/ExternalArtifact.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/ExternalArtifact.kt deleted file mode 100644 index f462a5d93..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/ExternalArtifact.kt +++ /dev/null @@ -1,30 +0,0 @@ -package org.pnfolder.pnlibrary.api.dependencies - -import org.pnfolder.pnlibrary.api.internal.isHttps -import org.pnfolder.pnlibrary.api.updates.requirePositiveSize -import org.pnfolder.pnlibrary.api.updates.requireSha256 -import java.net.URI - -/** - * Exact external artifact allowed only under server-side trust policy. - * - * @property uri verified HTTPS artifact location - * @property size expected byte length, when known - * @property sha256 expected SHA-256 digest, when known - */ -class ExternalArtifact( - val uri: URI, - val size: Long?, - val sha256: String?, -) { - init { - require(uri.isHttps()) { "External artifact must use HTTPS" } - requirePositiveSize(size, "External artifact") - requireSha256(sha256, "External artifact") - } - - /** Integrity validation constants. */ - companion object { - private val SHA_256 = Regex("[0-9a-fA-F]{64}") - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency.kt deleted file mode 100644 index eba99770a..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/ExternalPluginDependency.kt +++ /dev/null @@ -1,98 +0,0 @@ -package org.pnfolder.pnlibrary.api.dependencies - -import org.pnfolder.pnlibrary.api.internal.requireHttpsUri -import org.pnfolder.pnlibrary.api.version.SemanticVersion -import java.net.URI - -/** Required third-party plugin which may be manual-only or have an exact verified artifact. */ -class ExternalPluginDependency private constructor(builder: Builder) : PluginDependency { - /** Returns this dependency as its external representation. */ - override val external: ExternalPluginDependency get() = this - /** Third-party plugin name expected from the native platform. */ - val plugin: String = builder.plugin - /** Oldest accepted plugin version. */ - val minimumVersion: SemanticVersion = builder.minimumVersion - /** Accepted semantic-version interval. */ - override val versions: VersionConstraint = builder.versions() - /** Administrator-facing download page, when declared. */ - val downloadPage: URI? = builder.downloadPage - /** Exact downloadable artifact, when automatic installation is possible. */ - val artifact: ExternalArtifact? = builder.artifact - /** Whether staged JAR metadata must match [plugin]. */ - val verifyPluginId: Boolean = builder.verifyPluginId - /** Whether staged JAR metadata must satisfy [versions]. */ - val verifyVersion: Boolean = builder.verifyVersion - /** Whether absence blocks the declaring product. */ - override val required: Boolean = builder.required - /** Administrator/automatic download policy. */ - override val downloadPolicy: DownloadPolicy = builder.downloadPolicy - - /** Fluent builder for an [ExternalPluginDependency]. */ - class Builder internal constructor( - internal val plugin: String, - internal val minimumVersion: SemanticVersion, - ) { - internal var downloadPage: URI? = null - internal var artifact: ExternalArtifact? = null - internal var required = true - internal var maximumInclusive: SemanticVersion? = null - internal var maximumExclusive: SemanticVersion? = null - internal var downloadPolicy = DownloadPolicy.MANUAL - internal var verifyPluginId = true - internal var verifyVersion = true - - fun downloadPage(url: String): Builder = apply { - downloadPage = requireHttpsUri(url, "Download page must use HTTPS") - } - - fun artifact(url: String, size: Long, sha256: String): Builder = apply { - artifact = ExternalArtifact(URI.create(url), size, sha256) - } - fun url(value: String): Builder = apply { artifact = ExternalArtifact(URI.create(value), null, null) } - - fun required(value: Boolean): Builder = apply { required = value } - - fun maximumVersion(value: String): Builder = apply { maximumInclusive = SemanticVersion.parse(value) } - - fun maximumVersionExclusive(value: String): Builder = apply { maximumExclusive = SemanticVersion.parse(value) } - - fun downloadPolicy(value: DownloadPolicy): Builder = apply { downloadPolicy = value } - - /** Selects automatic or manual download policy. */ - fun automaticDownload(value: Boolean): Builder = apply { - downloadPolicy = if (value) DownloadPolicy.AUTOMATIC else DownloadPolicy.MANUAL - } - /** Enables or disables staged plugin-ID verification. */ - fun verifyPluginId(value: Boolean): Builder = apply { verifyPluginId = value } - - /** Enables or disables staged plugin-version verification. */ - fun verifyVersion(value: Boolean): Builder = apply { verifyVersion = value } - - /** Enables or disables mandatory automatic installation. */ - fun forceAutomaticDownload(value: Boolean): Builder = apply { - if (value) downloadPolicy = DownloadPolicy.FORCED - else if (downloadPolicy == DownloadPolicy.FORCED) downloadPolicy = DownloadPolicy.MANUAL - } - - internal fun versions() = VersionConstraint(minimumVersion, maximumInclusive, maximumExclusive) - - /** Validates and creates the immutable dependency. */ - fun build(): ExternalPluginDependency { - require(downloadPage != null || artifact != null) { "External dependency requires a download page or artifact" } - require(artifact != null || downloadPolicy == DownloadPolicy.MANUAL) { - "A download page cannot be installed automatically" - } - versions() - return ExternalPluginDependency(this) - } - } - - companion object { - /** Starts a dependency for [plugin] with the supplied minimum version. */ - @JvmStatic - fun builder(plugin: String, minimumVersion: String): Builder { - require(plugin.isNotBlank()) { "External plugin name must not be blank" } - return Builder(plugin.trim(), SemanticVersion.parse(minimumVersion)) - } - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/PluginDependency.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/PluginDependency.kt index c336d92bd..589fcdbaa 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/PluginDependency.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/PluginDependency.kt @@ -1,44 +1,7 @@ package org.pnfolder.pnlibrary.api.dependencies -import org.pnfolder.pnlibrary.api.version.SemanticVersion - -/** Controls whether pnLibrary may stage a missing dependency. */ -enum class DownloadPolicy { - MANUAL, - AUTOMATIC, - FORCED -} - -/** - * Inclusive lower bound plus one optional upper bound for a dependency version. - * - * @property minimum oldest accepted version - * @property maximumInclusive newest accepted version, inclusive - * @property maximumExclusive newest boundary, exclusive - */ -class VersionConstraint( - val minimum: SemanticVersion, - val maximumInclusive: SemanticVersion? = null, - val maximumExclusive: SemanticVersion? = null, -) { - init { - require(maximumInclusive == null || maximumExclusive == null) { - "Only one maximum version bound may be declared" - } - require(maximumInclusive == null || maximumInclusive >= minimum) { - "Inclusive maximum version must be >= minimum version" - } - require(maximumExclusive == null || maximumExclusive > minimum) { - "Exclusive maximum version must be > minimum version" - } - } - - /** Returns whether [version] lies inside this interval. */ - fun accepts(version: SemanticVersion): Boolean = - version >= minimum && - (maximumInclusive == null || version <= maximumInclusive) && - (maximumExclusive == null || version < maximumExclusive) -} +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ManagedProductDependency /** One dependency accepted by `PluginBuilder.depends`. */ interface PluginDependency { @@ -59,63 +22,3 @@ interface PluginDependency { /** Native/third-party plugin dependency, when this is an external dependency. */ val external: ExternalPluginDependency? get() = null } - -/** Short factories for the unified dependency DSL. */ -object Dependencies { - @JvmStatic - @JvmOverloads - fun managed( - component: String, - minimumVersion: String, - repositoryOwner: String, - repositoryName: String, - required: Boolean = true, - automaticDownload: Boolean = false, - forceAutomaticDownload: Boolean = false, - ): PluginDependency = ManagedProductDependency( - component, - minimumVersion, - repositoryOwner, - repositoryName, - required, - downloadPolicy(automaticDownload, forceAutomaticDownload), - ) - - @JvmStatic - @JvmOverloads - fun plugin( - plugin: String, - minimumVersion: String, - downloadPage: String, - required: Boolean = true, - automaticDownload: Boolean = false, - forceAutomaticDownload: Boolean = false, - ): PluginDependency = ExternalPluginDependency.builder(plugin, minimumVersion) - .downloadPage(downloadPage) - .required(required) - .downloadPolicy(downloadPolicy(automaticDownload, forceAutomaticDownload)) - .build() - - @JvmStatic - @JvmOverloads - fun plugin( - plugin: String, - minimumVersion: String, - downloadUrl: String, - size: Long, - sha256: String, - required: Boolean = true, - automaticDownload: Boolean = false, - forceAutomaticDownload: Boolean = false, - ): PluginDependency = ExternalPluginDependency.builder(plugin, minimumVersion) - .artifact(downloadUrl, size, sha256) - .required(required) - .downloadPolicy(downloadPolicy(automaticDownload, forceAutomaticDownload)) - .build() - - private fun downloadPolicy(automatic: Boolean, forced: Boolean): DownloadPolicy = when { - forced -> DownloadPolicy.FORCED - automatic -> DownloadPolicy.AUTOMATIC - else -> DownloadPolicy.MANUAL - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/VersionConstraint.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/VersionConstraint.kt new file mode 100644 index 000000000..f52a2249d --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/VersionConstraint.kt @@ -0,0 +1,34 @@ +package org.pnfolder.pnlibrary.api.dependencies + +import org.pnfolder.pnlibrary.api.version.SemanticVersion + +/** + * Inclusive lower bound plus one optional upper bound for a dependency version. + * + * @property minimum oldest accepted version + * @property maximumInclusive newest accepted version, inclusive + * @property maximumExclusive newest boundary, exclusive + */ +class VersionConstraint( + val minimum: SemanticVersion, + val maximumInclusive: SemanticVersion? = null, + val maximumExclusive: SemanticVersion? = null, +) { + init { + require(maximumInclusive == null || maximumExclusive == null) { + "Only one maximum version bound may be declared" + } + require(maximumInclusive == null || maximumInclusive >= minimum) { + "Inclusive maximum version must be >= minimum version" + } + require(maximumExclusive == null || maximumExclusive > minimum) { + "Exclusive maximum version must be > minimum version" + } + } + + /** Returns whether [version] lies inside this interval. */ + fun accepts(version: SemanticVersion): Boolean = + version >= minimum && + (maximumInclusive == null || version <= maximumInclusive) && + (maximumExclusive == null || version < maximumExclusive) +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/external/ExternalArtifact.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/external/ExternalArtifact.kt new file mode 100644 index 000000000..e631b12ca --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/external/ExternalArtifact.kt @@ -0,0 +1,66 @@ +package org.pnfolder.pnlibrary.api.dependencies.external + +import org.pnfolder.pnlibrary.api.internal.isHttps +import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.api.updates.requireSha256 +import java.net.URI + +/** + * One downloadable file of an external plugin, with its own checksum and the servers it is meant for. + * + * The checksum belongs to this file only: when this variant is chosen, exactly this file is downloaded and checked against + * exactly this SHA-256. Variants for other platforms or versions are never touched. + * + * @property uri verified HTTPS artifact location + * @property sha256 expected SHA-256 digest, when known + * @property mirrors other HTTPS addresses of the same file, tried in order when the one before does not answer + * @property platforms platforms this file fits; empty means every platform + * @property minecraftFrom oldest Minecraft version this file fits (inclusive), such as `1.16`; null means no lower bound + * @property minecraftBefore first Minecraft version this file no longer fits (exclusive), such as `1.21`; null means no upper bound + * @property label short name of the variant for people, such as `для Paper 1.21` + * @property maxBytes largest accepted size of this file in bytes; null means the library-wide limit + */ +class ExternalArtifact( + val uri: URI, + val sha256: String?, + val mirrors: List = emptyList(), + val platforms: Set = emptySet(), + val minecraftFrom: String? = null, + val minecraftBefore: String? = null, + val label: String? = null, + val maxBytes: Long? = null, +) { + init { + require(uri.isHttps()) { "External artifact must use HTTPS" } + requireSha256(sha256, "External artifact") + require(maxBytes == null || maxBytes in 1..Int.MAX_VALUE.toLong()) { "Size limit must be between 1 byte and 2 GB" } + require(mirrors.all { it.isHttps() }) { "External artifact mirrors must use HTTPS" } + minecraftFrom?.let { requireNotNull(numbers(it)) { "Minecraft version must look like 1.20.4: $it" } } + minecraftBefore?.let { requireNotNull(numbers(it)) { "Minecraft version must look like 1.20.4: $it" } } + } + + /** Whether this file fits a server of [platform] running Minecraft [minecraft] (null when unknown). */ + fun fits(platform: PlatformType, minecraft: String?): Boolean { + if (platforms.isNotEmpty() && platform !in platforms) return false + if (minecraftFrom == null && minecraftBefore == null) return true + val current = minecraft?.let(::numbers) ?: return false + minecraftFrom?.let { if (compare(current, numbers(it)!!) < 0) return false } + minecraftBefore?.let { if (compare(current, numbers(it)!!) >= 0) return false } + return true + } + + private companion object { + fun numbers(text: String): List? { + val parts = Regex("^\\d+(\\.\\d+)*").find(text.trim())?.value?.split('.') ?: return null + return parts.map { it.toIntOrNull() ?: return null } + } + + fun compare(left: List, right: List): Int { + for (i in 0 until maxOf(left.size, right.size)) { + val order = (left.getOrElse(i) { 0 }).compareTo(right.getOrElse(i) { 0 }) + if (order != 0) return order + } + return 0 + } + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency.kt new file mode 100644 index 000000000..78aab972c --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/external/ExternalPluginDependency.kt @@ -0,0 +1,165 @@ +package org.pnfolder.pnlibrary.api.dependencies.external + +import org.pnfolder.pnlibrary.api.dependencies.DownloadPolicy +import org.pnfolder.pnlibrary.api.dependencies.PluginDependency +import org.pnfolder.pnlibrary.api.dependencies.VersionConstraint +import org.pnfolder.pnlibrary.api.internal.requireHttpsUri +import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.api.version.SemanticVersion +import java.net.URI + +/** Required third-party plugin which may be manual-only or have an exact verified artifact. */ +class ExternalPluginDependency private constructor(builder: Builder) : PluginDependency { + /** Returns this dependency as its external representation. */ + override val external: ExternalPluginDependency get() = this + /** Third-party plugin name expected from the native platform. */ + val plugin: String = builder.plugin + /** Short name for people, such as `Vault economy`; the plugin name when not given. */ + val title: String = builder.title ?: builder.plugin + /** One or two sentences on why the plugin is needed, shown to the administrator when it is missing. */ + val description: String? = builder.description + /** Oldest accepted plugin version. */ + val minimumVersion: SemanticVersion = builder.minimumVersion + /** Accepted semantic-version interval. */ + override val versions: VersionConstraint = builder.versions() + /** Administrator-facing download page, when declared. */ + val downloadPage: URI? = builder.downloadPage + /** Every downloadable file, specific variants first and the general one last; empty when only a page is given. */ + val artifacts: List = builder.allArtifacts() + /** The general downloadable file (or the first variant), when automatic installation is possible. */ + val artifact: ExternalArtifact? = artifacts.firstOrNull { it.platforms.isEmpty() && it.minecraftFrom == null && it.minecraftBefore == null } + ?: artifacts.firstOrNull() + + /** The file meant for this server: the first variant that fits [platform] and [minecraft], or null when none does. */ + fun artifactFor(platform: PlatformType, minecraft: String?): ExternalArtifact? = artifacts.firstOrNull { it.fits(platform, minecraft) } + /** Whether staged JAR metadata must match [plugin]. */ + val verifyPluginId: Boolean = builder.verifyPluginId + /** Whether staged JAR metadata must satisfy [versions]. */ + val verifyVersion: Boolean = builder.verifyVersion + /** Whether absence blocks the declaring product. */ + override val required: Boolean = builder.required + /** Administrator/automatic download policy. */ + override val downloadPolicy: DownloadPolicy = builder.downloadPolicy + ?: if (artifacts.isNotEmpty()) DownloadPolicy.AUTOMATIC else DownloadPolicy.MANUAL + + /** Fluent builder for an [ExternalPluginDependency]. */ + class Builder internal constructor( + internal val plugin: String, + internal val minimumVersion: SemanticVersion, + ) { + internal var downloadPage: URI? = null + internal var artifact: ExternalArtifact? = null + internal var required = true + internal var maximumInclusive: SemanticVersion? = null + internal var maximumExclusive: SemanticVersion? = null + internal var downloadPolicy: DownloadPolicy? = null + internal val mirrors = mutableListOf() + internal var verifyPluginId = true + internal var verifyVersion = true + internal val variants = mutableListOf() + internal var title: String? = null + internal var generalMaxBytes: Long? = null + internal var description: String? = null + + /** Sets the largest accepted size in bytes of the general file (`artifact` or `url`); variants take their own `maxBytes`. */ + fun maxBytes(value: Long): Builder = apply { generalMaxBytes = value } + + /** Sets the short name people read in the notice about the missing plugin. */ + fun title(value: String): Builder = apply { title = value.trim().ifEmpty { null } } + + /** Says why the plugin is needed, in a sentence or two. */ + fun description(value: String): Builder = apply { description = value.trim().ifEmpty { null } } + + /** Sets the page where the administrator can download the plugin by hand. */ + fun downloadPage(url: String): Builder = apply { + downloadPage = requireHttpsUri(url, "Download page must use HTTPS") + } + + /** Sets a direct download with the SHA-256 checksum the file must match. */ + fun artifact(url: String, sha256: String): Builder = apply { + artifact = ExternalArtifact(URI.create(url), sha256) + } + /** Sets a direct download URL without an integrity check. */ + fun url(value: String): Builder = apply { artifact = ExternalArtifact(URI.create(value), null) } + + /** + * Adds a file meant only for some servers: other [platforms] (empty means all) and/or a range of Minecraft versions + * from [minecraftFrom] (inclusive) up to [minecraftBefore] (exclusive). It has its own [sha256] and [mirrors]; the + * first variant that fits the server is the one downloaded, and only that one is checked. + */ + @JvmOverloads + fun variant( + url: String, + sha256: String? = null, + platforms: Set = emptySet(), + minecraftFrom: String? = null, + minecraftBefore: String? = null, + mirrors: List = emptyList(), + label: String? = null, + maxBytes: Long? = null, + ): Builder = apply { + variants += ExternalArtifact( + URI.create(url), sha256, mirrors.map { requireHttpsUri(it, "Mirror must use HTTPS") }, + platforms, minecraftFrom, minecraftBefore, label, maxBytes, + ) + } + + internal fun allArtifacts(): List = variants + listOfNotNull(artifact) + + /** Adds another HTTPS address of the same file; tried when the one before does not answer. */ + fun mirror(value: String): Builder = apply { mirrors += requireHttpsUri(value, "Mirror must use HTTPS") } + + /** Sets whether the plugin refuses to start without this dependency. */ + fun required(value: Boolean): Builder = apply { required = value } + + /** Sets the highest accepted plugin version, inclusive. */ + fun maximumVersion(value: String): Builder = apply { maximumInclusive = SemanticVersion.parse(value) } + + /** Sets the upper version bound, exclusive. */ + fun maximumVersionExclusive(value: String): Builder = apply { maximumExclusive = SemanticVersion.parse(value) } + + /** Sets how a missing or outdated plugin is downloaded. */ + fun downloadPolicy(value: DownloadPolicy): Builder = apply { downloadPolicy = value } + + /** Selects automatic or manual download policy. */ + fun automaticDownload(value: Boolean): Builder = apply { + downloadPolicy = if (value) DownloadPolicy.AUTOMATIC else DownloadPolicy.MANUAL + } + /** Enables or disables staged plugin-ID verification. */ + fun verifyPluginId(value: Boolean): Builder = apply { verifyPluginId = value } + + /** Enables or disables staged plugin-version verification. */ + fun verifyVersion(value: Boolean): Builder = apply { verifyVersion = value } + + /** Enables or disables mandatory automatic installation. */ + fun forceAutomaticDownload(value: Boolean): Builder = apply { + if (value) downloadPolicy = DownloadPolicy.FORCED + else if (downloadPolicy == DownloadPolicy.FORCED) downloadPolicy = null + } + + internal fun versions() = VersionConstraint(minimumVersion, maximumInclusive, maximumExclusive) + + /** Validates and creates the immutable dependency. */ + fun build(): ExternalPluginDependency { + require(downloadPage != null || artifact != null || variants.isNotEmpty()) { "External dependency requires a download page or artifact" } + require(artifact != null || variants.isNotEmpty() || downloadPolicy == null || downloadPolicy == DownloadPolicy.MANUAL) { + "A download page cannot be installed automatically" + } + artifact = artifact?.let { ExternalArtifact(it.uri, it.sha256, mirrors.toList(), maxBytes = generalMaxBytes) } + check(variants.size + (if (artifact != null) 1 else 0) <= MAX_FILES) { "Too many files for one dependency" } + versions() + return ExternalPluginDependency(this) + } + } + + companion object { + private const val MAX_FILES = 16 + + /** Starts a dependency for [plugin] with the supplied minimum version. */ + @JvmStatic + fun builder(plugin: String, minimumVersion: String): Builder { + require(plugin.isNotBlank()) { "External plugin name must not be blank" } + return Builder(plugin.trim(), SemanticVersion.parse(minimumVersion)) + } + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/ManagedProductDependency.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/external/ManagedProductDependency.kt similarity index 87% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/ManagedProductDependency.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/external/ManagedProductDependency.kt index df577bf62..8539159f7 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/ManagedProductDependency.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/dependencies/external/ManagedProductDependency.kt @@ -1,6 +1,9 @@ -package org.pnfolder.pnlibrary.api.dependencies +package org.pnfolder.pnlibrary.api.dependencies.external -import org.pnfolder.pnlibrary.api.updates.ProductId +import org.pnfolder.pnlibrary.api.dependencies.DownloadPolicy +import org.pnfolder.pnlibrary.api.dependencies.PluginDependency +import org.pnfolder.pnlibrary.api.dependencies.VersionConstraint +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.version.SemanticVersion /** diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService.kt index 05ff0c4cf..164868dbb 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticsService.kt @@ -1,5 +1,6 @@ package org.pnfolder.pnlibrary.api.diagnostics +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticLevel import java.nio.file.Path /** @@ -38,13 +39,11 @@ interface DiagnosticsService { fun register(plugin: String, contributor: DiagnosticsContributor): DiagnosticRegistration /** - * Registers [contributor] and associates it with [dataDirectory] when supported. + * Registers [contributor] and associates it with the plugin data directory [dataDirectory]. * - * The default implementation preserves compatibility with service implementations predating - * per-plugin directories and delegates to [register] without using [dataDirectory]. + * The library uses [dataDirectory] to locate plugin-owned files that belong in diagnostic reports. */ - fun register(plugin: String, dataDirectory: Path, contributor: DiagnosticsContributor): DiagnosticRegistration = - register(plugin, contributor) + fun register(plugin: String, dataDirectory: Path, contributor: DiagnosticsContributor): DiagnosticRegistration /** * Updates or creates a component status entry visible in diagnostic reports. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer.kt similarity index 90% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer.kt index 38fe56a9a..622d8a6b6 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticContainer.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticContainer.kt @@ -1,5 +1,7 @@ -package org.pnfolder.pnlibrary.api.diagnostics +package org.pnfolder.pnlibrary.api.diagnostics.report +import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticConfiguration +import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsContributor import java.util.Collections import java.util.LinkedHashMap import java.util.function.Supplier @@ -69,12 +71,15 @@ class DiagnosticContainer private constructor(builder: Builder) : DiagnosticsCon snapshotProvider = provider } + /** Adds a fixed value shown in the diagnostics under [name]. */ fun value(name: String, v: Any?): Builder = apply { fixed[name] = v } + /** Adds the entries of a configuration object to the diagnostics. */ fun configuration(config: DiagnosticConfiguration): Builder = apply { configurations.add(config) } + /** Adds the configuration file at [path] to the diagnostics. */ fun configuration(path: String): Builder = apply { configurations.add(DiagnosticConfiguration.builder(path).build()) } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticLevel.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticLevel.kt similarity index 86% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticLevel.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticLevel.kt index 3aa4e7aae..503476d83 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticLevel.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticLevel.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.diagnostics +package org.pnfolder.pnlibrary.api.diagnostics.report /** Severity level for diagnostic events recorded via [DiagnosticsService]. */ enum class DiagnosticLevel { diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticReport.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticReport.kt similarity index 91% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticReport.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticReport.kt index 71669cd35..a3b1e77b4 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticReport.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/diagnostics/report/DiagnosticReport.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.diagnostics +package org.pnfolder.pnlibrary.api.diagnostics.report import java.nio.file.Path diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/DirectDownloadSource.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/DirectDownloadSource.kt index 7c4f72181..9d722d1ba 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/DirectDownloadSource.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/DirectDownloadSource.kt @@ -14,6 +14,7 @@ import java.util.Locale * @property maximumJava newest supported Java feature version, or `null` when unbounded * @property size expected byte length, when integrity metadata is available * @property sha256 expected lowercase SHA-256 digest, when available + * @property mirrors other addresses of the same file */ class DirectDownloadSource private constructor(builder: Builder) { val uri: URI = requireNotNull(builder.uri) { "Download URL is required" } @@ -23,6 +24,12 @@ class DirectDownloadSource private constructor(builder: Builder) { val size: Long? = builder.size val sha256: String? = builder.sha256 + /** Largest accepted file in bytes for this file only; `null` means the library-wide limit (512 MB). */ + val maxBytes: Long? = builder.maxBytes + + /** Other HTTPS addresses of the same file, tried in order after [uri] when it does not answer; with a checksum, the first file that matches wins. */ + val mirrors: List = builder.mirrors.toList() + /** Returns whether this source supports [platform] on [javaFeature]. */ fun supports(platform: PlatformType, javaFeature: Int): Boolean = (this.platform == null || this.platform == platform) && javaFeature >= minimumJava && @@ -36,11 +43,19 @@ class DirectDownloadSource private constructor(builder: Builder) { internal var maximumJava: Int? = null internal var size: Long? = null internal var sha256: String? = null + internal var maxBytes: Long? = null + internal val mirrors = mutableListOf() + /** Sets the HTTPS URL to download from. */ fun url(value: String): Builder = apply { uri = requireHttpsUri(value, "Download URL must use HTTPS") } + /** Adds another HTTPS address of the same file. */ + fun mirror(value: String): Builder = apply { + mirrors += requireHttpsUri(value, "Mirror URL must use HTTPS") + } + /** Restricts the source to [value]. */ fun platform(value: PlatformType): Builder = apply { platform = value } @@ -52,6 +67,7 @@ class DirectDownloadSource private constructor(builder: Builder) { maximumJava = maximum } + /** Sets the expected size and SHA-256 checksum the downloaded file must match. */ fun integrity(size: Long, sha256: String): Builder = apply { require(size > 0) { "Download size must be positive" } require(sha256.matches(Regex("[0-9a-fA-F]{64}"))) { "SHA-256 must contain 64 hexadecimal characters" } @@ -59,11 +75,24 @@ class DirectDownloadSource private constructor(builder: Builder) { this.sha256 = sha256.lowercase(Locale.ROOT) } + /** Sets the largest accepted size of this file in bytes, smaller or larger than the library-wide limit (up to 2 GB). */ + fun maxBytes(value: Long): Builder = apply { + require(value in 1..Int.MAX_VALUE.toLong()) { "Size limit must be between 1 byte and 2 GB" } + maxBytes = value + } + + /** Sets the SHA-256 checksum the downloaded file must match; the size is not checked. */ + fun sha256(sha256: String): Builder = apply { + require(sha256.matches(Regex("[0-9a-fA-F]{64}"))) { "SHA-256 must contain 64 hexadecimal characters" } + this.sha256 = sha256.lowercase(Locale.ROOT) + } + /** Validates this configuration and creates an immutable source. */ fun build(): DirectDownloadSource = DirectDownloadSource(this) } companion object { + /** Creates a new [Builder]. */ @JvmStatic fun builder(): Builder = Builder() } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/DownloadDestination.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/DownloadDestination.kt new file mode 100644 index 000000000..f25ba225d --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/DownloadDestination.kt @@ -0,0 +1,4 @@ +package org.pnfolder.pnlibrary.api.downloads + +/** Root used to resolve a downloaded file's relative destination path. */ +enum class DownloadDestination { DATA_FOLDER, CACHE } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/DownloadState.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/DownloadState.kt new file mode 100644 index 000000000..164df955e --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/DownloadState.kt @@ -0,0 +1,12 @@ +package org.pnfolder.pnlibrary.api.downloads + +/** Lifecycle state reported for one managed file download. */ +enum class DownloadState { + DECLARED, + CURRENT, + DOWNLOADING, + STAGED, + BLOCKED, + FAILED, + CLOSED +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/FileDownload.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/FileDownload.kt index cacd73355..3adc17dc7 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/FileDownload.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/FileDownload.kt @@ -32,6 +32,7 @@ class FileDownload internal constructor(builder: Builder) { internal var destination = DownloadDestination.DATA_FOLDER internal var relativePath = "" + /** Sets whether a failed download stops the whole batch. */ fun required(value: Boolean): Builder = apply { required = value } /** Enables or disables ordinary automatic downloading. */ @@ -40,8 +41,12 @@ class FileDownload internal constructor(builder: Builder) { /** Enables or disables mandatory automatic downloading. */ fun forceAutomaticDownload(value: Boolean): Builder = apply { forceAutomatic = value } + /** Sets the HTTPS URL to download from. */ fun url(value: String): Builder = apply { source.url(value) } + /** Adds another HTTPS address of the same file; tried in order when the one before does not answer. */ + fun mirror(value: String): Builder = apply { source.mirror(value) } + /** Restricts the source to [value]. */ fun platform(value: PlatformType): Builder = apply { source.platform(value) } @@ -49,8 +54,15 @@ class FileDownload internal constructor(builder: Builder) { @JvmOverloads fun java(minimum: Int, maximum: Int? = null): Builder = apply { source.java(minimum, maximum) } + /** Sets the expected size and SHA-256 checksum the downloaded file must match. */ fun integrity(size: Long, sha256: String): Builder = apply { source.integrity(size, sha256) } + /** Sets the largest accepted size of this file in bytes; without it the library-wide limit applies. */ + fun maxBytes(value: Long): Builder = apply { source.maxBytes(value) } + + /** Sets the SHA-256 checksum the downloaded file must match. */ + fun sha256(value: String): Builder = apply { source.sha256(value) } + /** Selects the destination root and confined relative path. */ fun destination(value: DownloadDestination, relativePath: String): Builder = apply { destination = value diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/FileDownloads.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/FileDownloads.kt index e2de75aac..70961cd9f 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/FileDownloads.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/downloads/FileDownloads.kt @@ -4,20 +4,6 @@ import java.nio.file.Path import java.util.Collections import java.util.function.Consumer -/** Lifecycle state reported for one managed file download. */ -enum class DownloadState { - DECLARED, - CURRENT, - DOWNLOADING, - STAGED, - BLOCKED, - FAILED, - CLOSED -} - -/** Root used to resolve a downloaded file's relative destination path. */ -enum class DownloadDestination { DATA_FOLDER, CACHE } - /** * Immutable collection of files registered as one download unit. * @@ -53,6 +39,7 @@ class FileDownloads private constructor(builder: Builder) { } companion object { + /** Creates a new [Builder]. */ @JvmStatic fun builder(): Builder = Builder() } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/Event.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/Event.kt index 5302aeaee..b158099e1 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/Event.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/Event.kt @@ -1,6 +1,7 @@ package org.pnfolder.pnlibrary.api.events import net.kyori.adventure.text.Component +import org.pnfolder.pnlibrary.api.events.bus.DispatchMode import org.pnfolder.pnlibrary.api.runtime.PnLibraryProvider import java.util.concurrent.CompletionStage import java.util.concurrent.Executor diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/ResultedEvent.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/ResultedEvent.kt index 815b840d1..54caf6265 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/ResultedEvent.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/ResultedEvent.kt @@ -47,9 +47,11 @@ abstract class ResultedEvent : Event() { private val ALLOWED = GenericResult(true) private val DENIED = GenericResult(false) + /** Returns the shared allowed result. */ @JvmStatic fun allowed(): GenericResult = ALLOWED + /** Returns the shared denied result. */ @JvmStatic fun denied(): GenericResult = DENIED } @@ -77,6 +79,7 @@ abstract class ResultedEvent : Event() { companion object { private val ALLOWED = ComponentResult(true, null) + /** Returns the shared allowed result that carries no reason. */ @JvmStatic fun allowed(): ComponentResult = ALLOWED diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/DispatchMode.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/bus/DispatchMode.kt similarity index 84% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/DispatchMode.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/bus/DispatchMode.kt index 1b21ab1e8..dc39c7826 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/DispatchMode.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/bus/DispatchMode.kt @@ -1,4 +1,6 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.bus + +import org.pnfolder.pnlibrary.api.events.inspect.trace.EventTrace /** * How an event was dispatched, shown by [EventTrace] and `/pn bus`. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventScope.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/bus/EventScope.kt similarity index 81% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventScope.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/bus/EventScope.kt index bde0596d5..03ad7f367 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventScope.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/bus/EventScope.kt @@ -1,5 +1,11 @@ -package org.pnfolder.pnlibrary.api.events - +package org.pnfolder.pnlibrary.api.events.bus + +import org.pnfolder.pnlibrary.api.events.Event +import org.pnfolder.pnlibrary.api.events.listener.EventHandler +import org.pnfolder.pnlibrary.api.events.listener.EventListenerRegistration +import org.pnfolder.pnlibrary.api.events.listener.EventPriority +import org.pnfolder.pnlibrary.api.events.listener.EventSubscription +import org.pnfolder.pnlibrary.api.events.listener.Listener import org.pnfolder.pnlibrary.api.plugin.PluginId import java.util.function.Consumer diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/bus/EventService.kt similarity index 88% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventService.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/bus/EventService.kt index 852ffb90c..dfcff11ea 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventService.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/bus/EventService.kt @@ -1,5 +1,11 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.bus +import org.pnfolder.pnlibrary.api.events.Event +import org.pnfolder.pnlibrary.api.events.inspect.EventInspector +import org.pnfolder.pnlibrary.api.events.inspect.trace.EventTrace +import org.pnfolder.pnlibrary.api.events.listener.EventListenerRegistration +import org.pnfolder.pnlibrary.api.events.listener.EventSubscription +import org.pnfolder.pnlibrary.api.events.listener.Listener import org.pnfolder.pnlibrary.api.plugin.ModuleId import org.pnfolder.pnlibrary.api.plugin.PluginId import java.util.concurrent.CompletionStage diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventInfo.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/EventInfo.kt similarity index 87% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventInfo.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/EventInfo.kt index 29dcad445..8861f810b 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventInfo.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/EventInfo.kt @@ -1,5 +1,6 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.inspect +import org.pnfolder.pnlibrary.api.events.Event import java.time.Instant /** diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventInspector.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/EventInspector.kt similarity index 89% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventInspector.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/EventInspector.kt index a22c24d67..e87ea775b 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventInspector.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/EventInspector.kt @@ -1,5 +1,11 @@ -package org.pnfolder.pnlibrary.api.events - +package org.pnfolder.pnlibrary.api.events.inspect + +import org.pnfolder.pnlibrary.api.events.Event +import org.pnfolder.pnlibrary.api.events.ResultedEvent +import org.pnfolder.pnlibrary.api.events.bus.EventService +import org.pnfolder.pnlibrary.api.events.inspect.history.EventDay +import org.pnfolder.pnlibrary.api.events.inspect.history.EventHour +import org.pnfolder.pnlibrary.api.events.inspect.trace.EventTrace import org.pnfolder.pnlibrary.api.plugin.ModuleId import org.pnfolder.pnlibrary.api.plugin.PluginId @@ -62,10 +68,10 @@ interface EventInspector { * @param eventType class name of one event, or `null` for all * @return one entry per hour and event that was called */ - fun hourly(eventType: String? = null): List = emptyList() + fun hourly(eventType: String? = null): List /** How many asynchronous events were accepted and still wait for a free thread. */ - fun asyncQueued(): Int = 0 + fun asyncQueued(): Int /** * Writes the per-day and per-hour counters to a file next to the history file. @@ -73,7 +79,7 @@ interface EventInspector { * @param json `true` for a JSON file, `false` for CSV * @return the file written, or `null` when the history is off or cannot be written */ - fun exportHistory(json: Boolean = false): java.nio.file.Path? = null + fun exportHistory(json: Boolean = false): java.nio.file.Path? /** * Starts recording every dispatch of [eventType] and its subclasses, keeping the latest diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/ListenerInfo.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/ListenerInfo.kt similarity index 95% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/ListenerInfo.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/ListenerInfo.kt index 3768ed982..ea3200619 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/ListenerInfo.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/ListenerInfo.kt @@ -1,5 +1,6 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.inspect +import org.pnfolder.pnlibrary.api.events.bus.EventService import org.pnfolder.pnlibrary.api.plugin.ModuleId import org.pnfolder.pnlibrary.api.plugin.PluginId diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventDay.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/history/EventDay.kt similarity index 74% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventDay.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/history/EventDay.kt index f93a38123..013dd16f7 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventDay.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/history/EventDay.kt @@ -1,5 +1,7 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.inspect.history +import org.pnfolder.pnlibrary.api.events.Event +import org.pnfolder.pnlibrary.api.events.inspect.EventInspector import java.time.LocalDate /** diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventHour.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/history/EventHour.kt similarity index 75% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventHour.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/history/EventHour.kt index 8bd3c991c..9e98050a4 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventHour.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/history/EventHour.kt @@ -1,5 +1,7 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.inspect.history +import org.pnfolder.pnlibrary.api.events.Event +import org.pnfolder.pnlibrary.api.events.inspect.EventInspector import java.time.LocalDateTime /** diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventTrace.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/trace/EventTrace.kt similarity index 92% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventTrace.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/trace/EventTrace.kt index 8e1cb2d74..b6aa12e3f 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventTrace.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/inspect/trace/EventTrace.kt @@ -1,5 +1,8 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.inspect.trace +import org.pnfolder.pnlibrary.api.events.Event +import org.pnfolder.pnlibrary.api.events.ResultedEvent +import org.pnfolder.pnlibrary.api.events.bus.DispatchMode import org.pnfolder.pnlibrary.api.plugin.ModuleId import org.pnfolder.pnlibrary.api.plugin.PluginId import java.time.Instant diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventExtensions.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventExtensions.kt similarity index 79% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventExtensions.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventExtensions.kt index bdfb92440..3343e3a49 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventExtensions.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventExtensions.kt @@ -1,7 +1,10 @@ @file:JvmName("EventDsl") -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.listener +import org.pnfolder.pnlibrary.api.events.Event +import org.pnfolder.pnlibrary.api.events.bus.EventScope +import org.pnfolder.pnlibrary.api.events.bus.EventService import org.pnfolder.pnlibrary.api.plugin.PluginId import java.util.function.Consumer diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventHandler.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventHandler.kt similarity index 85% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventHandler.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventHandler.kt index 87452d99e..79477193c 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventHandler.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventHandler.kt @@ -1,4 +1,6 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.listener + +import org.pnfolder.pnlibrary.api.events.Event /** * Marks a method as an event handler. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventListenerBuilder.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventListenerBuilder.kt similarity index 62% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventListenerBuilder.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventListenerBuilder.kt index 233a29f41..24aa60134 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventListenerBuilder.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventListenerBuilder.kt @@ -1,5 +1,9 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.listener +import org.pnfolder.pnlibrary.api.events.Event +import org.pnfolder.pnlibrary.api.events.bus.EventScope +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference import java.util.function.Consumer /** @@ -30,6 +34,24 @@ class EventListenerBuilder internal constructor( /** Registers [listener] with the configured options and returns the live subscription. */ fun listen(listener: Consumer): EventSubscription = scope.subscribe(eventType, priority, ignoreDenied, listener) + + /** + * Registers [listener] to run for the first matching event only, then removes it. + * Closing the returned subscription before that cancels it. + */ + fun listenOnce(listener: Consumer): EventSubscription { + val fired = AtomicBoolean() + val self = AtomicReference() + val subscription = scope.subscribe(eventType, priority, ignoreDenied) { event: E -> + if (fired.compareAndSet(false, true)) { + self.get()?.close() + listener.accept(event) + } + } + self.set(subscription) + if (fired.get()) subscription.close() + return subscription + } } /** Starts building a subscription to [E] in this scope. */ diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventListenerRegistration.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventListenerRegistration.kt similarity index 90% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventListenerRegistration.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventListenerRegistration.kt index 7c301acf2..908f24e3e 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventListenerRegistration.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventListenerRegistration.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.listener /** Registration containing every annotated handler discovered on one listener. */ interface EventListenerRegistration : AutoCloseable { diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventPriority.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventPriority.kt similarity index 95% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventPriority.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventPriority.kt index 4acaf187f..7298f3c72 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventPriority.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventPriority.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.listener /** * Suggested numeric listener priorities. Lower numbers run first. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventSubscription.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventSubscription.kt similarity index 86% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventSubscription.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventSubscription.kt index fd5e807bb..b004f0067 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/EventSubscription.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/EventSubscription.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.listener /** * Handle for one typed listener registration. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/Listener.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/Listener.kt similarity index 64% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/Listener.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/Listener.kt index d588dec19..44096a0b3 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/Listener.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/listener/Listener.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.events +package org.pnfolder.pnlibrary.api.events.listener /** Marker interface for classes containing [EventHandler] methods. */ interface Listener diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/player/PlayerLifecycleEvents.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/player/PlayerLifecycleEvents.kt index 2085db6b4..8e46e4387 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/player/PlayerLifecycleEvents.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/events/player/PlayerLifecycleEvents.kt @@ -1,6 +1,6 @@ package org.pnfolder.pnlibrary.api.events.player -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer import org.pnfolder.pnlibrary.api.events.Event import java.util.UUID diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/expansions/AbstractExpansion.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/expansions/AbstractExpansion.kt new file mode 100644 index 000000000..17d3a4cf1 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/expansions/AbstractExpansion.kt @@ -0,0 +1,55 @@ +package org.pnfolder.pnlibrary.api.expansions + +/** + * Base class that implements the [Expansion] state machine, so subclasses only acquire and release resources. + * + * Example: + * ```kotlin + * class WeatherExpansion : AbstractExpansion("weather") { + * override fun onEnable() { /* acquire resources */ } + * override fun onDisable() { /* release them */ } + * } + * ``` + */ +abstract class AbstractExpansion protected constructor(final override val id: String) : Expansion { + @Volatile + final override var state: ExpansionState = ExpansionState.DISABLED + private set + + /** Acquires the resources of this expansion; an exception marks the expansion [ExpansionState.FAILED]. */ + protected abstract fun onEnable() + + /** Releases everything [onEnable] acquired. Called only for an enabled expansion. */ + protected abstract fun onDisable() + + /** Releases what outlives [onDisable]; called once when the expansion is closed for good, after [onDisable] if it was enabled. */ + protected open fun onClose() {} + + @Synchronized + final override fun enable() { + if (state == ExpansionState.ENABLED || state == ExpansionState.CLOSED) return + try { + onEnable() + state = ExpansionState.ENABLED + } catch (error: Throwable) { + state = ExpansionState.FAILED + throw error + } + } + + @Synchronized + final override fun disable() = release(ExpansionState.DISABLED) + + @Synchronized + final override fun close() = release(ExpansionState.CLOSED) + + private fun release(target: ExpansionState) { + if (state == ExpansionState.CLOSED) return + try { + if (state == ExpansionState.ENABLED) onDisable() + } finally { + state = target + if (target == ExpansionState.CLOSED) onClose() + } + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/expansions/Expansion.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/expansions/Expansion.kt index f1ed89906..09650ac08 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/expansions/Expansion.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/expansions/Expansion.kt @@ -1,8 +1,5 @@ package org.pnfolder.pnlibrary.api.expansions -/** Lifecycle of an [Expansion]. [CLOSED] is terminal; a [FAILED] expansion may be started again with [Expansion.enable]. */ -enum class ExpansionState { DISABLED, ENABLED, FAILED, CLOSED } - /** * A shared feature that pnLibrary starts, stops, and finally closes as one unit, in the manner of a * PlaceholderAPI expansion. Register it with [ExpansionManager.register]. @@ -25,57 +22,3 @@ interface Expansion : AutoCloseable { /** Disables the expansion for good. */ override fun close() } - -/** - * Base class that implements the [Expansion] state machine, so subclasses only acquire and release resources. - * - * Example: - * ```kotlin - * class WeatherExpansion : AbstractExpansion("weather") { - * override fun onEnable() { /* acquire resources */ } - * override fun onDisable() { /* release them */ } - * } - * ``` - */ -abstract class AbstractExpansion protected constructor(final override val id: String) : Expansion { - @Volatile - final override var state: ExpansionState = ExpansionState.DISABLED - private set - - /** Acquires the resources of this expansion; an exception marks the expansion [ExpansionState.FAILED]. */ - protected abstract fun onEnable() - - /** Releases everything [onEnable] acquired. Called only for an enabled expansion. */ - protected abstract fun onDisable() - - /** Releases what outlives [onDisable]; called once when the expansion is closed for good, after [onDisable] if it was enabled. */ - protected open fun onClose() {} - - @Synchronized - final override fun enable() { - if (state == ExpansionState.ENABLED || state == ExpansionState.CLOSED) return - try { - onEnable() - state = ExpansionState.ENABLED - } catch (error: Throwable) { - state = ExpansionState.FAILED - throw error - } - } - - @Synchronized - final override fun disable() = release(ExpansionState.DISABLED) - - @Synchronized - final override fun close() = release(ExpansionState.CLOSED) - - private fun release(target: ExpansionState) { - if (state == ExpansionState.CLOSED) return - try { - if (state == ExpansionState.ENABLED) onDisable() - } finally { - state = target - if (target == ExpansionState.CLOSED) onClose() - } - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/expansions/ExpansionState.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/expansions/ExpansionState.kt new file mode 100644 index 000000000..28eb5fc99 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/expansions/ExpansionState.kt @@ -0,0 +1,4 @@ +package org.pnfolder.pnlibrary.api.expansions + +/** Lifecycle of an [Expansion]. [CLOSED] is terminal; a [FAILED] expansion may be started again with [Expansion.enable]. */ +enum class ExpansionState { DISABLED, ENABLED, FAILED, CLOSED } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/internal/InternalPnLibraryApi.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/internal/InternalPnLibraryApi.kt deleted file mode 100644 index 71b9cf790..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/internal/InternalPnLibraryApi.kt +++ /dev/null @@ -1,10 +0,0 @@ -package org.pnfolder.pnlibrary.api.internal - -/** - * Marks public declarations that exist only so pnLibrary's own modules can reach them, such as the serializers - * behind [org.pnfolder.pnlibrary.api.checks.Check]. They may change or disappear in any release, so using one - * without `@OptIn(InternalPnLibraryApi::class)` is a compile error in Kotlin. - */ -@RequiresOptIn(level = RequiresOptIn.Level.ERROR, message = "This is internal to pnLibrary and may change without notice.") -@Retention(AnnotationRetention.BINARY) -annotation class InternalPnLibraryApi diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/internal/Suggestions.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/internal/Suggestions.kt deleted file mode 100644 index 6f2c4de4c..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/internal/Suggestions.kt +++ /dev/null @@ -1,39 +0,0 @@ -package org.pnfolder.pnlibrary.api.internal - -/** Finds the closest valid spelling for a mistyped key, tag or type so errors can say what was meant. */ -internal object Suggestions { - /** Returns the option most like [word], or `null` when nothing is close enough to be a typo. */ - fun closest(word: String, options: Collection): String? { - val wanted = simplify(word) - var best: String? = null - var bestDistance = Int.MAX_VALUE - for (option in options) { - val distance = distance(wanted, simplify(option)) - if (distance < bestDistance) { - best = option - bestDistance = distance - } - } - return best?.takeIf { bestDistance <= maxOf(2, wanted.length / 3) } - } - - /** Returns ` Did you mean 'x'?` for the closest option, or an empty string. */ - fun hint(word: String, options: Collection): String = - closest(word, options)?.let { " Did you mean '$it'?" }.orEmpty() - - private fun simplify(text: String): String = text.lowercase().filter { it != '_' && it != '-' && it != ' ' } - - private fun distance(a: String, b: String): Int { - var previous = IntArray(b.length + 1) { it } - for (i in 1..a.length) { - val current = IntArray(b.length + 1) - current[0] = i - for (j in 1..b.length) { - val substitution = previous[j - 1] + if (a[i - 1] == b[j - 1]) 0 else 1 - current[j] = minOf(previous[j] + 1, current[j - 1] + 1, substitution) - } - previous = current - } - return previous[b.length] - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/LibraryScope.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/LibraryScope.kt new file mode 100644 index 000000000..677f434f2 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/LibraryScope.kt @@ -0,0 +1,22 @@ +package org.pnfolder.pnlibrary.api.libraries + +/** Where the classes of a [ModuleLibrary] become visible. */ +enum class LibraryScope { + /** + * The class loader of the plugin that owns the module: its own code sees the library directly. The default. On a + * platform that cannot add to a plugin's loader (Velocity) the library joins pnLibrary's loader instead. + */ + PLUGIN, + + /** + * A class loader of its own for this module ([ModuleLibraries.classLoader]). Two modules can use two versions of the + * same library without clashing; the price is that the plugin's own code reaches it only through [ModuleLibraries.loadClass]. + */ + ISOLATED, + + /** + * pnLibrary's own class loader, visible to every plugin that depends on pnLibrary. Rarely wanted: a second version of the + * same library from another plugin clashes. Use it only for a library that plugins must share on purpose. + */ + LIBRARY, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/LibrarySource.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/LibrarySource.kt new file mode 100644 index 000000000..dd78a8278 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/LibrarySource.kt @@ -0,0 +1,74 @@ +package org.pnfolder.pnlibrary.api.libraries + +import java.net.URI + +/** + * One place a library's jar can come from, with the settings of that place only. A library lists any number of sources; + * they are tried in order until one gives a jar that passes its check. + * + * ```kotlin + * LibrarySource.builder().link("https://cdn.example.org/a-1.0.jar").sha256("3c0e…").name("CDN").build() + * LibrarySource.builder().repository("https://repo.example.org/maven2/").build() // Maven path under this repository + * ``` + * + * @property url HTTPS address: a direct link to the jar, or the root of a Maven repository, see [direct] + * @property direct `true` for a link to the jar itself, `false` for a Maven repository the path is built under + * @property sha256 sum the jar from this source must have; `null` means the jar from this source is not checked + * @property name short label shown in errors and in the menu; the host of [url] when absent + * @property description a sentence on what this place is, such as `the main repository of the company`; `null` when not given + */ +class LibrarySource private constructor(builder: Builder) { + val url: String = builder.url ?: error("A source needs a link or a repository") + val direct: Boolean = builder.direct + val sha256: String? = builder.sha256 + val name: String = builder.name ?: URI.create(url).host + val description: String? = builder.description + + override fun toString(): String = "$name ($url)" + override fun equals(other: Any?): Boolean = other is LibrarySource && other.url == url && other.direct == direct && other.sha256 == sha256 + override fun hashCode(): Int = (url.hashCode() * 31 + direct.hashCode()) * 31 + (sha256?.hashCode() ?: 0) + + /** Java-friendly builder; [build] checks that an address was given. */ + class Builder internal constructor() { + internal var url: String? = null + internal var direct = false + internal var sha256: String? = null + internal var name: String? = null + internal var description: String? = null + + /** The jar lies at this exact HTTPS link. */ + fun link(url: String): Builder = apply { this.url = https(url, "Library link"); direct = true } + + /** The jar is looked up by its Maven path under this HTTPS repository. */ + fun repository(url: String): Builder = apply { this.url = https(url, "Repository"); direct = false } + + /** The sum the jar from this source must have, 64 hexadecimal characters. */ + fun sha256(hex: String): Builder = apply { + require(hex.matches(SHA256)) { "SHA-256 must be 64 hexadecimal characters" } + sha256 = hex.lowercase() + } + + /** Gives the source a short label. */ + fun name(value: String): Builder = apply { name = value.trim().ifEmpty { null } } + + /** Says in a sentence what this place is. */ + fun description(value: String): Builder = apply { description = value.trim().ifEmpty { null } } + + /** Creates the source. */ + fun build(): LibrarySource = LibrarySource(this) + } + + companion object { + private val SHA256 = Regex("[0-9A-Fa-f]{64}") + + /** Starts a source; set a [Builder.link] or a [Builder.repository]. */ + @JvmStatic + fun builder(): Builder = Builder() + + internal fun https(value: String, what: String): String { + val uri = URI.create(value.trim()) + require(uri.scheme.equals("https", true) && !uri.host.isNullOrBlank()) { "$what must be an HTTPS link: $value" } + return uri.toASCIIString() + } + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/LibraryUsage.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/LibraryUsage.kt new file mode 100644 index 000000000..d1d9e61f2 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/LibraryUsage.kt @@ -0,0 +1,16 @@ +package org.pnfolder.pnlibrary.api.libraries + +import org.pnfolder.pnlibrary.api.plugin.ModuleId +import org.pnfolder.pnlibrary.api.plugin.PluginId + +/** + * Who registered a library: a plugin for all its modules, or one module. + * + * @property library the library + * @property plugin the plugin that owns it + * @property module the module that registered it, or `null` when the whole plugin did + */ +data class LibraryUsage(val library: ModuleLibrary, val plugin: PluginId, val module: ModuleId?) { + /** `plugin` or `plugin:module`, the text used in commands. */ + val owner: String get() = if (module == null) plugin.value else "${plugin.value}:${module.value}" +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/ModuleLibraries.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/ModuleLibraries.kt new file mode 100644 index 000000000..871f5715c --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/ModuleLibraries.kt @@ -0,0 +1,49 @@ +package org.pnfolder.pnlibrary.api.libraries + +/** + * The libraries of one module, or of a whole plugin (`PluginRegistration.libraries`). + * + * A module lists its libraries in `PluginModule.libraries()`; they are downloaded and verified before `onEnable` runs. A + * plugin may register libraries on itself too: every module of the plugin sees them as [available]. Either may also ask + * for one later with [load]. The library that fails to load stops the module (state `FAILED`) unless it was declared + * optional. + */ +interface ModuleLibraries { + /** + * Class loader of the [LibraryScope.ISOLATED] libraries registered here; its classes are not visible to the plugin's own code, so load + * their classes through this loader or find them with a `ServiceLoader` that uses it. A library declared + * [LibraryScope.PLUGIN] is not here. [loadClass] is easier: it also looks in the plugin's libraries. + */ + val classLoader: ClassLoader + + /** The libraries registered here, not counting the ones a plugin gives its modules. */ + val loaded: List + + /** The libraries this module can use: its own and the plugin's. For a plugin it is the same as [loaded]. */ + val available: List get() = loaded + + /** Downloads, verifies and loads [library] unless it is loaded already. Throws [IllegalStateException] with the reason when it fails. */ + fun load(library: ModuleLibrary) + + /** Loads a library given as `group:artifact:version` with default settings. */ + fun load(coordinates: String) = load(ModuleLibrary.of(coordinates)) + + /** Whether [library] is loaded here or, for a module, by its plugin. */ + fun isLoaded(library: ModuleLibrary): Boolean = library in available + + /** The available library with this [group] and [artifact], whatever its version, or `null`. */ + fun find(group: String, artifact: String): ModuleLibrary? = available.firstOrNull { it.group == group && it.artifact == artifact } + + /** + * Finds the class [name] in the libraries registered here, then, for a module, in the plugin's. Throws + * [ClassNotFoundException] when no library has it. + */ + fun loadClass(name: String): Class<*> + + /** + * Takes [library] off the list, so it is not shown any more and is not loaded again when a module starts. Java cannot + * unload a jar that is already in use: its classes stay available until the server restarts. Returns whether it was + * on the list. + */ + fun remove(library: ModuleLibrary): Boolean +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/ModuleLibrary.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/ModuleLibrary.kt new file mode 100644 index 000000000..f207fabae --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/libraries/ModuleLibrary.kt @@ -0,0 +1,134 @@ +package org.pnfolder.pnlibrary.api.libraries + +import org.pnfolder.pnlibrary.api.platform.PlatformType +import java.util.Collections + +/** + * A Maven library a module asks pnLibrary to download, verify and load, with every setting of that download. + * + * ```kotlin + * ModuleLibrary.builder("com.zaxxer", "HikariCP", "5.1.0") + * .source { link("https://cdn.example.org/HikariCP-5.1.0.jar").sha256("3c0e…").name("CDN") } // 1st place to try + * .source { repository("https://mirror.example.org/maven/").sha256("9f2a…") } // 2nd place + * .scope(LibraryScope.ISOLATED) // own class loader + * .build() + * ``` + * + * The one list of [sources] says where the jar comes from; each place has its own address, sum and name. They are tried in + * order, then Maven Central unless [Builder.mavenCentral] turns it off; the first that gives a jar passing its check wins. + * Transitive dependencies are not resolved: list every jar the library needs. + * + * @property group Maven group id + * @property artifact Maven artifact id + * @property version Maven version + * @property classifier optional classifier such as `shaded` + * @property sources the places the jar can come from, as many as you like, tried in the given order + * @property mavenCentral whether Maven Central is tried after the sources + * @property scope which class loader the library joins; the plugin's own by default + * @property platforms the platforms the library is loaded on; empty means every platform. The platform is detected by + * pnLibrary: on another platform the library is skipped, not an error + * @property title short name players and administrators read, such as `Hikari connection pool`; the artifact id when absent + * @property description one or two sentences on what the library is for, shown in `/pn modules` and the menu + * @property required `true`: the module fails to start when the library cannot be loaded; `false`: it starts without it + */ +class ModuleLibrary private constructor(builder: Builder) { + val group: String = builder.group + val artifact: String = builder.artifact + val version: String = builder.version + val classifier: String? = builder.classifier + val sources: List = Collections.unmodifiableList(ArrayList(builder.sources)) + val mavenCentral: Boolean = builder.mavenCentral + val scope: LibraryScope = builder.scope + val platforms: Set = Collections.unmodifiableSet(LinkedHashSet(builder.platforms)) + val required: Boolean = builder.required + val title: String = builder.title ?: builder.artifact + val description: String? = builder.description + + /** `true` when the library lives in a class loader of its own. */ + val isolated: Boolean get() = scope == LibraryScope.ISOLATED + + /** Whether the library is loaded on [platform]; always when no platforms were listed, or the platform is unknown. */ + fun appliesTo(platform: PlatformType?): Boolean = platforms.isEmpty() || platform == null || platform in platforms + + /** `group:artifact:version`, or `group:artifact:version:classifier`. */ + val coordinates: String get() = listOfNotNull(group, artifact, version, classifier).joinToString(":") + + /** Every place to try, in order: [sources], then Maven Central when it is on. */ + val allSources: List + get() = sources + listOfNotNull(CENTRAL_SOURCE.takeIf { mavenCentral }) + + override fun toString(): String = coordinates + override fun equals(other: Any?): Boolean = other is ModuleLibrary && other.coordinates == coordinates && other.scope == scope + override fun hashCode(): Int = coordinates.hashCode() * 31 + scope.hashCode() + + /** Java-friendly builder; [build] checks every value. */ + class Builder internal constructor(internal val group: String, internal val artifact: String, internal val version: String) { + internal var classifier: String? = null + internal val sources = mutableListOf() + internal var mavenCentral = true + internal var scope = LibraryScope.PLUGIN + internal val platforms = linkedSetOf() + internal var required = true + internal var title: String? = null + internal var description: String? = null + + /** Sets the short name shown to people instead of the artifact id. */ + fun title(value: String): Builder = apply { title = value.trim().ifEmpty { null } } + + /** Says what the library is for, in a sentence or two; players and administrators read it in the menu. */ + fun description(value: String): Builder = apply { description = value.trim().ifEmpty { null } } + + /** Adds an alternative; call it as many times as you like, the first added is tried first. */ + fun source(source: LibrarySource): Builder = apply { sources += source } + + /** Adds an alternative made in place: `.source { link("https://…").sha256("…") }`. */ + fun source(configure: LibrarySource.Builder.() -> Unit): Builder = source(LibrarySource.builder().apply(configure).build()) + + /** Sets the classifier of the jar, such as `shaded`. */ + fun classifier(value: String): Builder = apply { classifier = value.trim().ifEmpty { null } } + + /** Chooses which class loader the library joins; [LibraryScope.PLUGIN] by default. */ + fun scope(value: LibraryScope): Builder = apply { scope = value } + + /** Loads the library only on these platforms; without it every platform loads it. */ + fun platforms(vararg types: PlatformType): Builder = apply { + require(PlatformType.UNIVERSAL !in types) { "UNIVERSAL is not a runtime platform" } + platforms += types + } + + /** Turns Maven Central on or off after the sources; on by default. */ + fun mavenCentral(enabled: Boolean): Builder = apply { mavenCentral = enabled } + + /** Lets the module start even when this library cannot be loaded. */ + fun optional(): Builder = apply { required = false } + + /** Validates the library and creates it. */ + fun build(): ModuleLibrary { + require(group.matches(PART) && artifact.matches(PART)) { "Invalid library name: $group:$artifact" } + require(version.matches(VERSION)) { "Invalid library version: $version" } + require(classifier?.matches(PART) ?: true) { "Invalid classifier: $classifier" } + return ModuleLibrary(this) + } + } + + companion object { + /** Maven Central, the repository used last by default. */ + const val CENTRAL = "https://repo1.maven.org/maven2/" + private val CENTRAL_SOURCE = LibrarySource.builder().repository(CENTRAL).name("Maven Central").build() + private val PART = Regex("[A-Za-z0-9_.-]+") + private val VERSION = Regex("[A-Za-z0-9_.+-]+") + private val SHA256 = Regex("[0-9A-Fa-f]{64}") + + /** Starts a library `group:artifact:version`. */ + @JvmStatic + fun builder(group: String, artifact: String, version: String): Builder = Builder(group, artifact, version) + + /** A library from its `group:artifact:version` text with default settings. */ + @JvmStatic + fun of(coordinates: String): ModuleLibrary { + val parts = coordinates.trim().split(':') + require(parts.size == 3 || parts.size == 4) { "Expected group:artifact:version, got: $coordinates" } + return builder(parts[0], parts[1], parts[2]).apply { parts.getOrNull(3)?.let(::classifier) }.build() + } + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/LogLevel.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/LogLevel.kt new file mode 100644 index 000000000..a4acaf950 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/LogLevel.kt @@ -0,0 +1,19 @@ +package org.pnfolder.pnlibrary.api.logging + +/** Semantic severity and presentation category for plugin log messages. */ +enum class LogLevel { + /** Detail for a support report; the console does not show it. */ + DEBUG, + + /** Normal operational information. */ + INFO, + /** Positive completion or readiness information. */ + SUCCESS, + /** Recoverable problem that may require administrator attention. */ + WARNING, + /** Failed operation or unexpected exception. */ + ERROR, + + /** Failure that leaves the plugin or the server unable to do its job; always reaches the black box. */ + CRITICAL, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/LoggingService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/LoggingService.kt index a20a45949..9f2fab717 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/LoggingService.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/LoggingService.kt @@ -1,126 +1,21 @@ package org.pnfolder.pnlibrary.api.logging -import org.pnfolder.pnlibrary.api.plugin.LifecycleRow - -/** Semantic severity and presentation category for plugin log messages. */ -enum class LogLevel { - /** Detail for a support report; the console does not show it. */ - DEBUG, - - /** Normal operational information. */ - INFO, - /** Positive completion or readiness information. */ - SUCCESS, - /** Recoverable problem that may require administrator attention. */ - WARNING, - /** Failed operation or unexpected exception. */ - ERROR, - - /** Failure that leaves the plugin or the server unable to do its job; always reaches the black box. */ - CRITICAL, -} - +/** Creates plugin-bound loggers and console message boxes. */ interface LoggingService { + /** Returns the logger called [name] that belongs to the plugin [owner]. */ fun logger(owner: Any, name: String): PnLogger + /** Starts a startup summary block titled [title] for [owner]; nothing is printed until `show()`. */ fun box(owner: Any, title: String): MessageBox + /** Starts a shutdown summary block titled [title] for [owner]. */ fun shutdownBox(owner: Any, title: String): MessageBox + /** Same as [box] with the title `name version`. */ fun box(owner: Any, name: String, version: String): MessageBox = box(owner, "$name $version") + /** Same as [shutdownBox] with the title `name version`. */ fun shutdownBox(owner: Any, name: String, version: String): MessageBox = shutdownBox(owner, "$name $version") } - -/** - * Plugin-bound logger whose warnings and errors may be included in diagnostic reports. - * - * Messages are plain platform-console text. Implementations add the logger name and may - * aggregate repeated diagnostic incidents before writing to the native console. - */ -interface PnLogger { - /** - * Writes one line at [level] and decides where it goes. The console always gets it. With [record] `true` (what every - * short form below uses) it also goes into the black box: the diagnostics buffer, the journal and, for an - * error with an exception, the error report. With [record] `false` it is console only and leaves no trace. - */ - fun log(level: LogLevel, message: String, error: Throwable? = null, record: Boolean = true) - - /** Writes normal operational information to the console and the black box. */ - fun info(message: String) = log(LogLevel.INFO, message, null, true) - - /** Writes normal operational information; with [record] `false` it stays out of the black box. */ - fun info(message: String, record: Boolean) = log(LogLevel.INFO, message, null, record) - - /** Writes normal operational information together with the [error] that explains it, kept with its stack trace. */ - fun info(message: String, error: Throwable?) = log(LogLevel.INFO, message, error, true) - - /** Writes positive completion or readiness information to the console and the black box. */ - fun success(message: String) = log(LogLevel.SUCCESS, message, null, true) - - /** Writes positive completion information; with [record] `false` it stays out of the black box. */ - fun success(message: String, record: Boolean) = log(LogLevel.SUCCESS, message, null, record) - - /** Writes a recoverable problem requiring attention to the console and the black box. */ - fun warning(message: String) = log(LogLevel.WARNING, message, null, true) - - /** Writes a recoverable problem; with [record] `false` it stays out of the black box. */ - fun warning(message: String, record: Boolean) = log(LogLevel.WARNING, message, null, record) - - /** Writes a recoverable problem with the [error] that caused it, so the report keeps the stack trace. */ - fun warning(message: String, error: Throwable?) = log(LogLevel.WARNING, message, error, true) - - /** Writes a recoverable problem with its [error]; with [record] `false` it stays out of the black box. */ - fun warning(message: String, error: Throwable?, record: Boolean) = log(LogLevel.WARNING, message, error, record) - - /** Writes a failure to the console and the black box. */ - fun error(message: String) = log(LogLevel.ERROR, message, null, true) - - /** Writes a failure with its original [error], which the report keeps with the stack trace. */ - fun error(message: String, error: Throwable?) = log(LogLevel.ERROR, message, error, true) - - /** Writes a failure with its [error]; with [record] `false` it stays out of the black box. */ - fun error(message: String, error: Throwable?, record: Boolean) = log(LogLevel.ERROR, message, error, record) - - /** Writes a failure that stops the plugin from working, with the [error] behind it, to the console and the black box. */ - fun critical(message: String, error: Throwable? = null) = log(LogLevel.CRITICAL, message, error, true) - - /** - * Writes a detail for a support report only: the black box keeps it and the console stays quiet. Use it where the - * old code logged at `FINE`. - */ - fun debug(message: String) = log(LogLevel.DEBUG, message, null, true) - - /** Writes a detail for a support report together with its [error]; the console stays quiet. */ - fun debug(message: String, error: Throwable?) = log(LogLevel.DEBUG, message, error, true) -} - -/** - * Fluent startup, shutdown, or operation summary displayed as one console block. - * - * Rows may be added until [show] is called. A box can be displayed exactly once, and - * modifying or displaying it again fails with [IllegalStateException]. Failure rows - * preserve their exception in the diagnostic log buffer. - */ -interface MessageBox { - - fun ok(label: String, detail: String): MessageBox - - fun warn(label: String, detail: String): MessageBox - - fun skip(label: String, detail: String): MessageBox - - fun fail(label: String, detail: String, error: Throwable? = null): MessageBox - - /** - * Hides the rows pnLibrary adds by itself to a lifecycle card (enabled or disabled), for example - * `lifecycle.enabled().hide(LifecycleRow.IDENTIFIER, LifecycleRow.NOT_CONFIGURED)`. The plugin's own rows are - * never hidden, and on a generic box this does nothing. - */ - fun hide(vararg rows: LifecycleRow): MessageBox = this - - /** Writes the complete box to the owning plugin's native console. */ - fun show() -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/MessageBox.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/MessageBox.kt new file mode 100644 index 000000000..1ff6423d9 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/MessageBox.kt @@ -0,0 +1,35 @@ +package org.pnfolder.pnlibrary.api.logging + +import org.pnfolder.pnlibrary.api.plugin.lifecycle.LifecycleRow + +/** + * Fluent startup, shutdown, or operation summary displayed as one console block. + * + * Rows may be added until [show] is called. A box can be displayed exactly once, and + * modifying or displaying it again fails with [IllegalStateException]. Failure rows + * preserve their exception in the diagnostic log buffer. + */ +interface MessageBox { + + /** Adds a successful row. */ + fun ok(label: String, detail: String): MessageBox + + /** Adds a row for something that works but needs attention. */ + fun warn(label: String, detail: String): MessageBox + + /** Adds a row for a step that was skipped on purpose. */ + fun skip(label: String, detail: String): MessageBox + + /** Adds a failed row; [error], when given, is kept in the diagnostic log buffer. */ + fun fail(label: String, detail: String, error: Throwable? = null): MessageBox + + /** + * Hides the rows pnLibrary adds by itself to a lifecycle card (enabled or disabled), for example + * `lifecycle.enabled().hide(LifecycleRow.IDENTIFIER, LifecycleRow.NOT_CONFIGURED)`. The plugin's own rows are + * never hidden, and on a generic box this does nothing. + */ + fun hide(vararg rows: LifecycleRow): MessageBox = this + + /** Writes the complete box to the owning plugin's native console. */ + fun show() +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/PnLogger.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/PnLogger.kt new file mode 100644 index 000000000..ebc18c7a3 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/logging/PnLogger.kt @@ -0,0 +1,43 @@ +package org.pnfolder.pnlibrary.api.logging + +/** + * Plugin-bound logger that writes to the console and the black box (journal, diagnostics buffer, error report). + * + * Every line reaches the black box. Pass [context] to attach structured key-value facts that are stored alongside + * the message in the journal and appear in support reports. + */ +interface PnLogger { + /** Writes one line at [level] to the console and the black box. [context] is stored as extra key-value facts. */ + fun log(level: LogLevel, message: String, error: Throwable? = null, context: Map = emptyMap()) + + fun info(message: String) = log(LogLevel.INFO, message) + fun info(message: String, error: Throwable?) = log(LogLevel.INFO, message, error) + fun info(message: String, context: Map) = log(LogLevel.INFO, message, context = context) + + fun success(message: String) = log(LogLevel.SUCCESS, message) + fun success(message: String, context: Map) = log(LogLevel.SUCCESS, message, context = context) + + fun warning(message: String) = log(LogLevel.WARNING, message) + fun warning(message: String, error: Throwable?) = log(LogLevel.WARNING, message, error) + fun warning(message: String, context: Map) = log(LogLevel.WARNING, message, context = context) + fun warning(message: String, error: Throwable?, context: Map) = log(LogLevel.WARNING, message, error, context) + + fun error(message: String) = log(LogLevel.ERROR, message) + fun error(message: String, error: Throwable?) = log(LogLevel.ERROR, message, error) + fun error(message: String, error: Throwable?, context: Map) = log(LogLevel.ERROR, message, error, context) + + /** Writes a failure that stops the plugin from working; always reaches the black box regardless of retention. */ + fun critical(message: String, error: Throwable? = null) = log(LogLevel.CRITICAL, message, error) + fun critical(message: String, error: Throwable?, context: Map) = log(LogLevel.CRITICAL, message, error, context) + + /** Writes a detail for a support report only; the console stays quiet. */ + fun debug(message: String) = log(LogLevel.DEBUG, message) + fun debug(message: String, error: Throwable?) = log(LogLevel.DEBUG, message, error) + fun debug(message: String, context: Map) = log(LogLevel.DEBUG, message, context = context) + + /** + * Records a line in the black box at [level] without printing to the console. + * Use to replay buffered pre-startup entries after the library has initialised. + */ + fun record(level: LogLevel, message: String, error: Throwable? = null) = debug(message, error) +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsController.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsController.kt index 1e8c8a6a6..e4c06e436 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsController.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsController.kt @@ -1,8 +1,8 @@ package org.pnfolder.pnlibrary.api.metrics -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration import java.util.function.Consumer /** diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsService.kt index 061317303..650265858 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsService.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsService.kt @@ -1,6 +1,8 @@ package org.pnfolder.pnlibrary.api.metrics -import java.util.function.Supplier +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration /** Public pnLibrary abstraction over the platform-specific metrics providers. */ interface MetricsService { @@ -20,40 +22,3 @@ interface MetricsService { /** Opens the optional provider-backed error reporter for the same configuration. */ fun openErrorReporter(owner: Any, configurations: Collection): ErrorReporter? = null } - -/** - * Live plugin metrics session with fluent registration of standard charts. - * - * Suppliers are evaluated by the platform metrics implementation, potentially after - * registration and on a background thread. They should therefore be thread-safe, - * non-blocking, and free of destructive side effects. Closing a managed session is safe - * to repeat and prevents its registry from retaining the session. - */ -interface PluginMetrics : AutoCloseable { - /** Providers represented by this session; more than one when several are enabled. */ - val providers: Set - - /** Error reporter owned by this session; absent when no provider supports error tracking. */ - val errorReporter: ErrorReporter? - get() = null - - /** Starts provider submission after all configured charts and services are registered. */ - fun start() = Unit - - /** Registers a single categorical string value; `null` omits the current sample. */ - fun simplePie(id: String, value: Supplier): PluginMetrics - /** Registers category-to-count values for one pie chart. */ - fun advancedPie(id: String, values: Supplier>): PluginMetrics - /** Registers two-level category-to-count values for a drilldown chart. */ - fun drilldownPie(id: String, values: Supplier>>): PluginMetrics - /** Registers one integer sample for a line chart. */ - fun singleLineChart(id: String, value: Supplier): PluginMetrics - /** Registers named integer samples for a multiline chart. */ - fun multiLineChart(id: String, values: Supplier>): PluginMetrics - /** Registers named integer bars for a simple bar chart. */ - fun simpleBarChart(id: String, values: Supplier>): PluginMetrics - /** Registers named arrays of integer bars for an advanced bar chart. */ - fun advancedBarChart(id: String, values: Supplier>): PluginMetrics - /** Stops this metrics session and releases its registry ownership. */ - override fun close() -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/PluginMetrics.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/PluginMetrics.kt new file mode 100644 index 000000000..83009ea53 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/PluginMetrics.kt @@ -0,0 +1,42 @@ +package org.pnfolder.pnlibrary.api.metrics + +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import java.util.function.Supplier + +/** + * Live plugin metrics session with fluent registration of standard charts. + * + * Suppliers are evaluated by the platform metrics implementation, potentially after + * registration and on a background thread. They should therefore be thread-safe, + * non-blocking, and free of destructive side effects. Closing a managed session is safe + * to repeat and prevents its registry from retaining the session. + */ +interface PluginMetrics : AutoCloseable { + /** Providers represented by this session; more than one when several are enabled. */ + val providers: Set + + /** Error reporter owned by this session; absent when no provider supports error tracking. */ + val errorReporter: ErrorReporter? + get() = null + + /** Starts provider submission after all configured charts and services are registered. */ + fun start() = Unit + + /** Registers a single categorical string value; `null` omits the current sample. */ + fun simplePie(id: String, value: Supplier): PluginMetrics + /** Registers category-to-count values for one pie chart. */ + fun advancedPie(id: String, values: Supplier>): PluginMetrics + /** Registers two-level category-to-count values for a drilldown chart. */ + fun drilldownPie(id: String, values: Supplier>>): PluginMetrics + /** Registers one integer sample for a line chart. */ + fun singleLineChart(id: String, value: Supplier): PluginMetrics + /** Registers named integer samples for a multiline chart. */ + fun multiLineChart(id: String, values: Supplier>): PluginMetrics + /** Registers named integer bars for a simple bar chart. */ + fun simpleBarChart(id: String, values: Supplier>): PluginMetrics + /** Registers named arrays of integer bars for an advanced bar chart. */ + fun advancedBarChart(id: String, values: Supplier>): PluginMetrics + /** Stops this metrics session and releases its registry ownership. */ + override fun close() +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/TelemetryError.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/error/ErrorReporter.kt similarity index 55% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/TelemetryError.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/error/ErrorReporter.kt index 396684fae..5aa878007 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/TelemetryError.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/error/ErrorReporter.kt @@ -1,23 +1,4 @@ -package org.pnfolder.pnlibrary.api.metrics - -/** - * Provider-neutral, normalized error event suitable for local or remote reporting. - * - * @property type fully qualified exception type or another stable error identifier - * @property message human-readable error message, when one is available - * @property stackTrace rendered stack frames ordered from the failure site outward - * @property handled whether application code caught and handled the failure - * @property operation optional logical operation that was executing when the failure occurred - * @property attributes additional structured context associated with this occurrence - */ -data class TelemetryError( - val type: String, - val message: String?, - val stackTrace: List, - val handled: Boolean, - val operation: String? = null, - val attributes: Map = emptyMap(), -) +package org.pnfolder.pnlibrary.api.metrics.error /** Error reporting contract shared by local diagnostics and remote providers. */ interface ErrorReporter : AutoCloseable { diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/error/TelemetryError.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/error/TelemetryError.kt new file mode 100644 index 000000000..33060f461 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/error/TelemetryError.kt @@ -0,0 +1,20 @@ +package org.pnfolder.pnlibrary.api.metrics.error + +/** + * Provider-neutral, normalized error event suitable for local or remote reporting. + * + * @property type fully qualified exception type or another stable error identifier + * @property message human-readable error message, when one is available + * @property stackTrace rendered stack frames ordered from the failure site outward + * @property handled whether application code caught and handled the failure + * @property operation optional logical operation that was executing when the failure occurred + * @property attributes additional structured context associated with this occurrence + */ +data class TelemetryError( + val type: String, + val message: String?, + val stackTrace: List, + val handled: Boolean, + val operation: String? = null, + val attributes: Map = emptyMap(), +) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsBuilder.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/provider/MetricsBuilder.kt similarity index 94% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsBuilder.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/provider/MetricsBuilder.kt index 596720f7d..764860e21 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsBuilder.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/provider/MetricsBuilder.kt @@ -1,8 +1,8 @@ -package org.pnfolder.pnlibrary.api.metrics +package org.pnfolder.pnlibrary.api.metrics.provider -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.platform.PlatformType import java.util.function.Consumer diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsCredentials.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/provider/MetricsCredentials.kt similarity index 98% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsCredentials.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/provider/MetricsCredentials.kt index 6c011f331..fb2b1b809 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsCredentials.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/provider/MetricsCredentials.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.metrics +package org.pnfolder.pnlibrary.api.metrics.provider import org.pnfolder.pnlibrary.api.security.SecretValue diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider.kt new file mode 100644 index 000000000..3859686d3 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/provider/MetricsProvider.kt @@ -0,0 +1,7 @@ +package org.pnfolder.pnlibrary.api.metrics.provider + +/** Identifies a metrics transport without exposing its SDK classes to consumers. */ +enum class MetricsProvider { + BSTATS, + FASTSTATS, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsProvider.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/provider/MetricsProviderConfiguration.kt similarity index 92% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsProvider.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/provider/MetricsProviderConfiguration.kt index 9e2bdfa71..994d5f565 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsProvider.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/metrics/provider/MetricsProviderConfiguration.kt @@ -1,11 +1,6 @@ -package org.pnfolder.pnlibrary.api.metrics +package org.pnfolder.pnlibrary.api.metrics.provider import org.pnfolder.pnlibrary.api.platform.PlatformType -/** Identifies a metrics transport without exposing its SDK classes to consumers. */ -enum class MetricsProvider { - BSTATS, - FASTSTATS, -} /** * Provider-neutral credentials and enablement requested for one plugin module. @@ -34,6 +29,7 @@ data class MetricsProviderConfiguration( return copy(projectId = id, platformProjectIds = emptyMap()) } + /** Returns the provider credentials built from this configuration. */ fun credentials(): MetricsCredentials<*> = when (provider) { MetricsProvider.BSTATS -> MetricsCredentials.BStats( requireNotNull(projectId) { "Metrics project ID is required for bStats" }, diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/network/NetworkPlayer.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/network/NetworkPlayer.kt new file mode 100644 index 000000000..d347e2eea --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/network/NetworkPlayer.kt @@ -0,0 +1,30 @@ +package org.pnfolder.pnlibrary.api.network + +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import java.net.InetSocketAddress + +/** + * A player connected through a proxy: a [LibraryPlayer] plus what only a proxy knows, such as the backend server + * the player is on. + * + * ```kotlin + * val player = library.proxy?.player("Steve") + * player?.currentServer?.name // "lobby" + * player?.disconnect("Maintenance") + * ``` + * + * Obtain one from [NetworkProxy.player] or [NetworkProxy.players]. + */ +interface NetworkPlayer : LibraryPlayer { + /** Remote address of the client, or `null` when the platform does not expose it. */ + val address: InetSocketAddress? + + /** Last measured latency between the proxy and the client, in milliseconds. */ + val ping: Long + + /** The backend server the player is on, or `null` while connecting. */ + val currentServer: NetworkServer? + + /** Disconnects the player and shows [reason] on the disconnect screen. */ + fun disconnect(reason: String) +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/network/NetworkProxy.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/network/NetworkProxy.kt new file mode 100644 index 000000000..f48ebc8d8 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/network/NetworkProxy.kt @@ -0,0 +1,51 @@ +package org.pnfolder.pnlibrary.api.network + +import java.util.UUID + +/** + * The proxy itself: its players, backend servers and plugin-message channels. Available on Velocity and BungeeCord + * only; `library.proxy` is `null` on a game server. + * + * ```kotlin + * val proxy = library.proxy ?: return + * proxy.broadcast("Welcome to ${proxy.name}") + * proxy.server("lobby")?.onlinePlayers + * ``` + */ +interface NetworkProxy { + /** Proxy software name, such as `Velocity`. */ + val name: String + + /** Proxy software version. */ + val version: String + + /** Number of players connected to the proxy. */ + val playerCount: Int + + /** Every connected player. */ + val players: Collection + + /** Every registered backend server. */ + val servers: List + + /** Returns the connected player called [name], or `null`. */ + fun player(name: String): NetworkPlayer? + + /** Returns the connected player with [uuid], or `null`. */ + fun player(uuid: UUID): NetworkPlayer? + + /** Returns the backend server registered as [name], or `null`. */ + fun server(name: String): NetworkServer? + + /** Starts receiving plugin messages on [channel]. */ + fun registerChannel(channel: String) + + /** Stops receiving plugin messages on [channel]. */ + fun unregisterChannel(channel: String) + + /** Sends a text message to every player connected to this proxy. */ + fun broadcast(message: String) + + /** Shuts the proxy down, kicking players with [reason] when given. */ + fun stop(reason: String? = null) +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/network/NetworkServer.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/network/NetworkServer.kt new file mode 100644 index 000000000..50568d6f9 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/network/NetworkServer.kt @@ -0,0 +1,44 @@ +package org.pnfolder.pnlibrary.api.network + +import java.net.InetSocketAddress + +/** + * A backend game server registered behind the proxy. + * + * ```kotlin + * val lobby = library.proxy?.server("lobby") + * lobby?.broadcast("Restart in 5 minutes") + * lobby?.send("myplugin:sync", payload) + * ``` + * + * Properties the platform does not expose have neutral defaults: [motd] is `null` and [isRestricted] is `false` + * on Velocity. + */ +interface NetworkServer { + /** Name of the server as registered in the proxy configuration. */ + val name: String + + /** Address the proxy connects to. */ + val address: InetSocketAddress + + /** Number of players currently on this server. */ + val onlinePlayers: Int + + /** Last measured round-trip time to this server in milliseconds; `null` until the first measurement. */ + val ping: Long? + + /** Server MOTD; `null` on platforms that do not expose it. */ + val motd: String? get() = null + + /** Whether the server rejects players without explicit permission; `false` on platforms without that setting. */ + val isRestricted: Boolean get() = false + + /** Sends plugin-message [bytes] to this server over [channel]; `false` when the server cannot be reached. */ + fun send(channel: String, bytes: ByteArray): Boolean + + /** Whether [player] may connect to this server; `true` on platforms without an access list. */ + fun canAccess(player: NetworkPlayer): Boolean = true + + /** Sends a text message to every player currently on this server. */ + fun broadcast(message: String) +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ObservabilityService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ObservabilityService.kt index e5ae52f66..1f912b582 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ObservabilityService.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ObservabilityService.kt @@ -1,5 +1,13 @@ package org.pnfolder.pnlibrary.api.observability +import org.pnfolder.pnlibrary.api.observability.observation.Observation +import org.pnfolder.pnlibrary.api.observability.observation.ObservationQuery +import org.pnfolder.pnlibrary.api.observability.observation.ObservationRequest +import org.pnfolder.pnlibrary.api.observability.observation.ObservationScope +import org.pnfolder.pnlibrary.api.observability.report.ComponentStatus +import org.pnfolder.pnlibrary.api.observability.report.ObservabilityReport +import org.pnfolder.pnlibrary.api.observability.report.ObservabilityReportRequest + /** * Records operational history, tracks current component state, and creates * support reports from one consistent data source. @@ -33,5 +41,6 @@ interface ObservabilityService : AutoCloseable { /** Stores and returns the latest state for one plugin component. */ fun status(status: ComponentStatus): ComponentStatus + /** Builds a report of the current state of the monitored components, filtered by [request]. */ fun createReport(request: ObservabilityReportRequest = ObservabilityReportRequest()): ObservabilityReport } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/Observation.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/Observation.kt similarity index 56% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/Observation.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/Observation.kt index 3f842f08c..f0a1d050a 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/Observation.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/Observation.kt @@ -1,53 +1,7 @@ -package org.pnfolder.pnlibrary.api.observability +package org.pnfolder.pnlibrary.api.observability.observation -import java.nio.file.Path import java.util.UUID -/** Describes the operational importance and retention priority of an observation. */ -enum class ObservationLevel { - /** Detailed execution information intended for short-lived troubleshooting. */ - TRACE, - - /** Normal operational information. */ - INFO, - - /** A noteworthy state change that is not a failure. */ - NOTICE, - - /** A recoverable problem or degraded state. */ - WARNING, - - /** A failed operation that requires investigation. */ - ERROR, - - /** A severe incident retained independently of the normal history window. */ - CRITICAL, -} - -/** - * Complete input for recording one observation. - * - * Files are copied when the request is recorded. The journal stores generated - * attachment identifiers rather than the original absolute paths. - * - * @property plugin optional logical plugin name - * @property source optional component or operation that produced the event - * @property message concise human-readable description - * @property level severity and retention priority - * @property data bounded searchable metadata - * @property files local files to attach to this observation - * @property error optional failure captured as type and message - */ -data class ObservationRequest( - val plugin: String? = null, - val source: String? = null, - val message: String, - val level: ObservationLevel = ObservationLevel.INFO, - val data: Map = emptyMap(), - val files: List = emptyList(), - val error: Throwable? = null, -) - /** * Immutable event stored in the shared observability journal. * @@ -73,6 +27,7 @@ data class Observation( val errorMessage: String?, ) { companion object { + /** Creates an observation from [request] stamped with [timestamp] (epoch milliseconds). */ @JvmStatic @JvmOverloads fun from(request: ObservationRequest, timestamp: Long = System.currentTimeMillis()): Observation = Observation( diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationKeys.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationKeys.kt new file mode 100644 index 000000000..400bf13bd --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationKeys.kt @@ -0,0 +1,10 @@ +package org.pnfolder.pnlibrary.api.observability.observation + +/** Reserved [Observation.data] keys used by the library for retention. */ +object ObservationKeys { + /** Request: how long to keep the observation, in milliseconds; replaced by [KEEP_UNTIL_MS] when stored. */ + const val KEEP_FOR_MS: String = "pn.keepForMs" + + /** Stored: epoch milliseconds after which the observation is dropped. */ + const val KEEP_UNTIL_MS: String = "pn.keepUntilMs" +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationLevel.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationLevel.kt new file mode 100644 index 000000000..72f35a38b --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationLevel.kt @@ -0,0 +1,22 @@ +package org.pnfolder.pnlibrary.api.observability.observation + +/** Describes the operational importance and retention priority of an observation. */ +enum class ObservationLevel { + /** Detailed execution information intended for short-lived troubleshooting. */ + TRACE, + + /** Normal operational information. */ + INFO, + + /** A noteworthy state change that is not a failure. */ + NOTICE, + + /** A recoverable problem or degraded state. */ + WARNING, + + /** A failed operation that requires investigation. */ + ERROR, + + /** A severe incident retained independently of the normal history window. */ + CRITICAL, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ObservationQuery.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationQuery.kt similarity index 92% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ObservationQuery.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationQuery.kt index 37013b07d..b082b53a1 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ObservationQuery.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationQuery.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.observability +package org.pnfolder.pnlibrary.api.observability.observation /** * Selects observations from the shared chronological journal. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationRequest.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationRequest.kt new file mode 100644 index 000000000..ffe46cc5b --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationRequest.kt @@ -0,0 +1,27 @@ +package org.pnfolder.pnlibrary.api.observability.observation + +import java.nio.file.Path + +/** + * Complete input for recording one observation. + * + * Files are copied when the request is recorded. The journal stores generated + * attachment identifiers rather than the original absolute paths. + * + * @property plugin optional logical plugin name + * @property source optional component or operation that produced the event + * @property message concise human-readable description + * @property level severity and retention priority + * @property data bounded searchable metadata + * @property files local files to attach to this observation + * @property error optional failure captured as type and message + */ +data class ObservationRequest( + val plugin: String? = null, + val source: String? = null, + val message: String, + val level: ObservationLevel = ObservationLevel.INFO, + val data: Map = emptyMap(), + val files: List = emptyList(), + val error: Throwable? = null, +) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ObservationScope.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationScope.kt similarity index 53% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ObservationScope.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationScope.kt index 47e7655f3..59f14b27d 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ObservationScope.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/observation/ObservationScope.kt @@ -1,6 +1,7 @@ -package org.pnfolder.pnlibrary.api.observability +package org.pnfolder.pnlibrary.api.observability.observation import java.nio.file.Path +import java.time.Duration /** * Kotlin DSL used to assemble one [ObservationRequest]. @@ -15,38 +16,60 @@ class ObservationScope internal constructor() { private var level: ObservationLevel = ObservationLevel.INFO private val data = linkedMapOf() private val files = mutableListOf() + private var keepFor: Duration? = null + /** Overrides the plugin name the observation is attributed to. */ fun plugin(value: String): ObservationScope = apply { plugin = value } + /** Names the component that produced the observation. */ fun source(value: String): ObservationScope = apply { source = value } + /** Sets the observation text. */ fun message(value: String): ObservationScope = apply { message = value } + /** Sets the severity, `INFO` by default. */ fun level(value: ObservationLevel): ObservationScope = apply { level = value } + /** Attaches key-value details; values are stored as text. */ fun data(vararg values: Pair): ObservationScope = apply { values.forEach { (key, value) -> data[key] = value?.toString() ?: "null" } } + /** Attaches files to include with the observation. */ fun files(vararg paths: Path): ObservationScope = apply { files += paths } + /** + * Keeps the observation for [duration] regardless of its level, at most [MAX_KEEP_DAYS] days. + * + * The period is set by the plugin author in code; without it retention follows the level. + */ + fun keepFor(duration: Duration): ObservationScope = apply { + require(!duration.isNegative && !duration.isZero) { "Retention must be positive" } + require(duration <= Duration.ofDays(MAX_KEEP_DAYS)) { "Retention must not exceed $MAX_KEEP_DAYS days" } + keepFor = duration + } + internal fun build(error: Throwable? = null): ObservationRequest = ObservationRequest( plugin = plugin, source = source, - message = if (message == "Diagnostic observation" && error?.message != null) error.message!! else message, + message = error?.message?.takeIf { message == "Diagnostic observation" } ?: message, level = if (error == null) level else ObservationLevel.ERROR, - data = data.toMap(), + data = data.toMap() + listOfNotNull(keepFor?.let { ObservationKeys.KEEP_FOR_MS to it.toMillis().toString() }), files = files.toList(), error = error, ) + + private companion object { + const val MAX_KEEP_DAYS = 3650L + } } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ComponentStatus.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/report/ComponentStatus.kt similarity index 94% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ComponentStatus.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/report/ComponentStatus.kt index 1819833b8..1d599471e 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/ComponentStatus.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/report/ComponentStatus.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.observability +package org.pnfolder.pnlibrary.api.observability.report /** * Describes the latest known state of one runtime component. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/report/ObservabilityReport.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/report/ObservabilityReport.kt new file mode 100644 index 000000000..5b7bf1cfc --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/report/ObservabilityReport.kt @@ -0,0 +1,16 @@ +package org.pnfolder.pnlibrary.api.observability.report + +import java.nio.file.Path + +/** + * Identifies a support report stored on the local filesystem. + * + * @property id unique report identifier + * @property file path to the generated report archive + * @property createdAt creation time expressed as Unix epoch milliseconds + */ +data class ObservabilityReport( + val id: String, + val file: Path, + val createdAt: Long, +) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/Report.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/report/ObservabilityReportRequest.kt similarity index 53% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/Report.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/report/ObservabilityReportRequest.kt index d14a786ed..5115a2b7f 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/Report.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/observability/report/ObservabilityReportRequest.kt @@ -1,6 +1,4 @@ -package org.pnfolder.pnlibrary.api.observability - -import java.nio.file.Path +package org.pnfolder.pnlibrary.api.observability.report /** * Controls which support data is included in an observability report. @@ -14,16 +12,3 @@ data class ObservabilityReportRequest( val includeLogs: Boolean = true, val includeConfigurations: Boolean = true, ) - -/** - * Identifies a support report stored on the local filesystem. - * - * @property id unique report identifier - * @property file path to the generated report archive - * @property createdAt creation time expressed as Unix epoch milliseconds - */ -data class ObservabilityReport( - val id: String, - val file: Path, - val createdAt: Long, -) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess.kt deleted file mode 100644 index cb3746a9b..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess.kt +++ /dev/null @@ -1,80 +0,0 @@ -package org.pnfolder.pnlibrary.api.placeholders - -import org.pnfolder.pnlibrary.api.plugin.PluginId -import org.pnfolder.pnlibrary.common.text.Wildcards -import java.util.Collections - -/** - * Immutable access policy controlling which plugins may consume a placeholder. - * - * Explicit denials have highest priority. Owner access is checked next, followed by - * global library-plugin access, exact allow entries, and case-insensitive wildcard - * patterns where `*` matches any sequence of characters. - * - * ```java - * PlaceholderAccess access = PlaceholderAccess.builder() - * .owner() - * .allow("scoreboard") - * .allowMatching("admin-*") - * .deny("admin-untrusted") - * .build(); - * ``` - * - * @property ownerAllowed whether the plugin that registered the placeholder is allowed - * @property allLibraryPlugins whether every plugin registered with pnLibrary is allowed - * @property allowedPlugins exact plugin IDs explicitly allowed by the policy - * @property allowedPatterns case-insensitive plugin-ID patterns where `*` is a wildcard - * @property deniedPlugins exact plugin IDs denied before any allow rule is evaluated - */ -class PlaceholderAccess private constructor( - val ownerAllowed: Boolean, - val allLibraryPlugins: Boolean, - val allowedPlugins: Set, - val allowedPatterns: Set, - val deniedPlugins: Set, -) { - /** Evaluates [consumer] against this policy for a placeholder registered by [owner]. */ - fun allows(owner: PluginId, consumer: PluginId): Boolean { - if (consumer in deniedPlugins) return false - if (ownerAllowed && owner == consumer) return true - if (allLibraryPlugins || consumer in allowedPlugins) return true - return allowedPatterns.any { Wildcards.matches(it, consumer.value) } - } - /** Common policies and the Java-friendly custom-policy entry point. */ - companion object { - @JvmStatic - fun ownerOnly(): PlaceholderAccess = Builder().owner().build() - @JvmStatic - fun shared(): PlaceholderAccess = Builder().owner().allowAllLibraryPlugins().build() - @JvmStatic - fun builder(): Builder = Builder() - } - /** Mutable builder for composing an immutable [PlaceholderAccess] policy. */ - class Builder internal constructor() { - private var owner = false - private var all = false - private val allow = linkedSetOf() - private val patterns = linkedSetOf() - private val deny = linkedSetOf() - - /** Allows the plugin that owns the placeholder. */ - fun owner(): Builder = apply { owner = true } - /** Allows every plugin registered with pnLibrary. */ - fun allowAllLibraryPlugins(): Builder = apply { all = true } - fun allow(vararg ids: String): Builder = apply { ids.map(PluginId::of).forEach(allow::add) } - /** Adds case-insensitive plugin-ID patterns; `*` is the wildcard token. */ - fun allowMatching(vararg values: String): Builder = apply { - require(values.none(String::isBlank)) { "Placeholder access patterns must not be blank" } - values.map(String::trim).forEach(patterns::add) - } - /** Explicitly denies plugin IDs, overriding every allow rule. */ - fun deny(vararg ids: String): Builder = apply { ids.map(PluginId::of).forEach(deny::add) } - fun build(): PlaceholderAccess = PlaceholderAccess( - owner, - all, - Collections.unmodifiableSet(LinkedHashSet(allow)), - Collections.unmodifiableSet(LinkedHashSet(patterns)), - Collections.unmodifiableSet(LinkedHashSet(deny)), - ) - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder.kt index ac81f9223..57f3d914b 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderBuilder.kt @@ -1,5 +1,10 @@ package org.pnfolder.pnlibrary.api.placeholders +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderCachePolicy +import org.pnfolder.pnlibrary.api.placeholders.model.AsyncPlaceholderResolver +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderPublication +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderResolver +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import java.util.function.Consumer /** Fluent definition of one typed placeholder before it enters the service registry. */ @@ -11,18 +16,22 @@ interface PlaceholderBuilder { /** Selects an asynchronous resolver, replacing any previously configured resolver. */ fun resolveAsync(resolver: AsyncPlaceholderResolver): PlaceholderBuilder + /** Sets the callback that lets this placeholder be changed through the update API. */ fun update(updater: PlaceholderUpdater): PlaceholderBuilder - fun updateAccess(access: PlaceholderAccess): PlaceholderBuilder + /** Restricts which plugins may change this placeholder's value. */ + fun updateAccess(access: PluginAccess): PlaceholderBuilder - fun access(access: PlaceholderAccess): PlaceholderBuilder + /** Sets which plugins may read this placeholder. */ + fun access(access: PluginAccess): PlaceholderBuilder /** Builds and sets a consumer access policy with the Java-friendly callback. */ - fun access(configure: Consumer): PlaceholderBuilder + fun access(configure: Consumer): PlaceholderBuilder /** Configures result caching for this placeholder. */ fun cache(policy: PlaceholderCachePolicy): PlaceholderBuilder + /** Value used when the resolver returns null. */ fun fallback(value: T): PlaceholderBuilder /** diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderFormatter.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderFormatter.kt new file mode 100644 index 000000000..ccac408ec --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderFormatter.kt @@ -0,0 +1,9 @@ +package org.pnfolder.pnlibrary.api.placeholders + +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest + +/** Converts a resolved typed value into the string requested by a format expression. */ +fun interface PlaceholderFormatter { + /** Formats [value] using parsed [arguments] and the original [request]. */ + fun format(value: T, arguments: List, request: PlaceholderRequest): String +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderModel.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderModel.kt deleted file mode 100644 index 411906884..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderModel.kt +++ /dev/null @@ -1,35 +0,0 @@ -package org.pnfolder.pnlibrary.api.placeholders - -import java.util.concurrent.CompletionStage - -/** Resolves one placeholder synchronously; `null` selects its configured fallback. */ -fun interface PlaceholderResolver { - /** Produces a value for [request], or `null` when no value is available. */ - fun resolve(request: PlaceholderRequest): T? -} - -/** Resolves one placeholder asynchronously; a null result selects its fallback. */ -fun interface AsyncPlaceholderResolver { - /** Starts resolution and returns its eventual value. */ - fun resolve(request: PlaceholderRequest): CompletionStage -} - -/** Handle tracking one publication in an external placeholder system. */ -interface ExternalPlaceholderRegistration : AutoCloseable { - /** Current publication state, including unavailable and failed attempts. */ - val state: PlaceholderAdapterState - /** Whether this publication has been permanently closed. */ - val isClosed: Boolean get() = state == PlaceholderAdapterState.CLOSED -} - -/** Runtime registry of available external placeholder adapters. */ -interface PlaceholderAdapterRegistry { - /** Registers [adapter] and returns a handle that removes and closes it. */ - fun register(adapter: PlaceholderAdapter): AutoCloseable - /** Returns the adapter with case-insensitive [id], or `null`. */ - fun get(id: String): PlaceholderAdapter? - /** Returns an adapter or fails when it is unavailable. */ - fun require(id: String): PlaceholderAdapter = get(id) ?: error("Placeholder adapter $id is unavailable") - /** Returns a stable snapshot of adapters ordered by identifier. */ - fun all(): List -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderProvider.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderProvider.kt new file mode 100644 index 000000000..b672ba5f4 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderProvider.kt @@ -0,0 +1,15 @@ +package org.pnfolder.pnlibrary.api.placeholders + +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.util.UUID +import java.util.concurrent.CompletionStage + +/** Consumer view restricted to placeholders owned by one plugin. */ +interface PlaceholderProvider { + /** Plugin whose keys are addressed by this provider. */ + val pluginId: PluginId + /** Resolves [key] as the current service owner, applying its access policy. */ + fun resolve(key: String, playerId: UUID? = null): CompletionStage + /** Returns the target plugin's keys visible to the current consumer. */ + fun keys(): Set +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderRegistration.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderRegistration.kt index e7bdc8db4..836b25cb1 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderRegistration.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderRegistration.kt @@ -1,5 +1,7 @@ package org.pnfolder.pnlibrary.api.placeholders +import org.pnfolder.pnlibrary.api.placeholders.model.ExternalPlaceholderRegistration +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey import org.pnfolder.pnlibrary.api.plugin.PluginId /** diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderService.kt index a5c0121ed..8efadea64 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderService.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderService.kt @@ -1,27 +1,12 @@ package org.pnfolder.pnlibrary.api.placeholders +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderAdapterRegistry +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey import org.pnfolder.pnlibrary.api.plugin.PluginId import java.util.UUID import java.util.concurrent.CompletionStage import java.util.function.Consumer -/** Converts a resolved typed value into the string requested by a format expression. */ -fun interface PlaceholderFormatter { - /** Formats [value] using parsed [arguments] and the original [request]. */ - fun format(value: T, arguments: List, request: PlaceholderRequest): String -} - -/** - * Applies a textual assignment to a typed placeholder-owned value. - * - * The owner validates and converts the supplied value, persists it in its own storage, and - * returns the resulting typed value. Throwing rejects the update. - */ -fun interface PlaceholderUpdater { - /** Updates the backing value and returns its new typed representation. */ - fun update(request: PlaceholderRequest, value: String): T? -} - /** * Plugin-scoped registry and resolution facade for typed placeholders. * @@ -53,17 +38,8 @@ interface PlaceholderService : AutoCloseable { fun render(template: String, playerId: UUID? = null, values: Map = emptyMap()): CompletionStage /** Returns whether [expression] identifies a visible registered placeholder. */ fun contains(expression: String): Boolean + /** Returns the placeholder provider through which the plugin [pluginId] registers its placeholders. */ fun provider(pluginId: PluginId): PlaceholderProvider /** Returns the adapter registry owned by this plugin scope. */ fun adapters(): PlaceholderAdapterRegistry } - -/** Consumer view restricted to placeholders owned by one plugin. */ -interface PlaceholderProvider { - /** Plugin whose keys are addressed by this provider. */ - val pluginId: PluginId - /** Resolves [key] as the current service owner, applying its access policy. */ - fun resolve(key: String, playerId: UUID? = null): CompletionStage - /** Returns the target plugin's keys visible to the current consumer. */ - fun keys(): Set -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderUpdater.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderUpdater.kt new file mode 100644 index 000000000..e3c8e7579 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderUpdater.kt @@ -0,0 +1,14 @@ +package org.pnfolder.pnlibrary.api.placeholders + +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest + +/** + * Applies a textual assignment to a typed placeholder-owned value. + * + * The owner validates and converts the supplied value, persists it in its own storage, and + * returns the resulting typed value. Throwing rejects the update. + */ +fun interface PlaceholderUpdater { + /** Updates the backing value and returns its new typed representation. */ + fun update(request: PlaceholderRequest, value: String): T? +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapter.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapter.kt similarity index 81% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapter.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapter.kt index b3243bdfc..e9b45c801 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapter.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapter.kt @@ -1,5 +1,8 @@ -package org.pnfolder.pnlibrary.api.placeholders +package org.pnfolder.pnlibrary.api.placeholders.adapter +import org.pnfolder.pnlibrary.api.placeholders.model.ExternalPlaceholderRegistration +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderPublication +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderResolver import org.pnfolder.pnlibrary.api.plugin.PluginId import java.util.UUID diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterCapabilities.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterCapabilities.kt similarity index 92% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterCapabilities.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterCapabilities.kt index 801a8e795..116780c48 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterCapabilities.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterCapabilities.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.placeholders +package org.pnfolder.pnlibrary.api.placeholders.adapter /** * Features supported by one external adapter. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState.kt similarity index 89% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState.kt index cc9469b33..4d0847390 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAdapterState.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/adapter/PlaceholderAdapterState.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.placeholders +package org.pnfolder.pnlibrary.api.placeholders.adapter /** Current lifecycle state of an external placeholder adapter or publication. */ enum class PlaceholderAdapterState { diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy.kt similarity index 92% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy.kt index ca667a91c..e5efb4dc4 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderCachePolicy.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCachePolicy.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.placeholders +package org.pnfolder.pnlibrary.api.placeholders.cache import java.time.Duration @@ -22,6 +22,7 @@ data class PlaceholderCachePolicy @JvmOverloads constructor( } /** Factories for the most common cache policies. */ companion object { + /** Returns a policy that never caches. */ @JvmStatic fun none(): PlaceholderCachePolicy = PlaceholderCachePolicy() /** diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope.kt similarity index 88% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope.kt index 7b4d240e0..b604660f9 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderCacheScope.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderCacheScope.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.placeholders +package org.pnfolder.pnlibrary.api.placeholders.cache /** Values included when constructing a placeholder cache key. */ enum class PlaceholderCacheScope { diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueScope.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueScope.kt new file mode 100644 index 000000000..470ac2977 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueScope.kt @@ -0,0 +1,9 @@ +package org.pnfolder.pnlibrary.api.placeholders.cache + +/** Defines whether one stored placeholder value is shared or isolated by player. */ +enum class PlaceholderValueScope { + /** One value shared by the whole pnLibrary runtime. */ + GLOBAL, + /** A separate value for every player UUID. */ + PLAYER, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderValueStore.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueStore.kt similarity index 84% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderValueStore.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueStore.kt index fc420ea48..b25341cf6 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderValueStore.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/cache/PlaceholderValueStore.kt @@ -1,16 +1,8 @@ -package org.pnfolder.pnlibrary.api.placeholders +package org.pnfolder.pnlibrary.api.placeholders.cache import java.util.UUID import java.util.function.UnaryOperator -/** Defines whether one stored placeholder value is shared or isolated by player. */ -enum class PlaceholderValueScope { - /** One value shared by the whole pnLibrary runtime. */ - GLOBAL, - /** A separate value for every player UUID. */ - PLAYER, -} - /** * Process-wide string value store exposed through pnLibrary placeholders. * @@ -30,6 +22,7 @@ interface PlaceholderValueStore { /** Atomically transforms the current value and returns the result. */ fun update(parameter: String, playerId: UUID? = null, operator: UnaryOperator): String + /** Adds [amount] to the numeric value of [parameter] (for [playerId], or globally when `null`) and returns the new value. */ fun increment(parameter: String, amount: Long = 1, playerId: UUID? = null): String /** Subtracts [amount] from a numeric value and returns the result. */ diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/AsyncPlaceholderResolver.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/AsyncPlaceholderResolver.kt new file mode 100644 index 000000000..d6036750b --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/AsyncPlaceholderResolver.kt @@ -0,0 +1,9 @@ +package org.pnfolder.pnlibrary.api.placeholders.model + +import java.util.concurrent.CompletionStage + +/** Resolves one placeholder asynchronously; a null result selects its fallback. */ +fun interface AsyncPlaceholderResolver { + /** Starts resolution and returns its eventual value. */ + fun resolve(request: PlaceholderRequest): CompletionStage +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/ExternalPlaceholderRegistration.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/ExternalPlaceholderRegistration.kt new file mode 100644 index 000000000..fae7933f9 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/ExternalPlaceholderRegistration.kt @@ -0,0 +1,11 @@ +package org.pnfolder.pnlibrary.api.placeholders.model + +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapterState + +/** Handle tracking one publication in an external placeholder system. */ +interface ExternalPlaceholderRegistration : AutoCloseable { + /** Current publication state, including unavailable and failed attempts. */ + val state: PlaceholderAdapterState + /** Whether this publication has been permanently closed. */ + val isClosed: Boolean get() = state == PlaceholderAdapterState.CLOSED +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderAdapterRegistry.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderAdapterRegistry.kt new file mode 100644 index 000000000..c11944916 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderAdapterRegistry.kt @@ -0,0 +1,15 @@ +package org.pnfolder.pnlibrary.api.placeholders.model + +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapter + +/** Runtime registry of available external placeholder adapters. */ +interface PlaceholderAdapterRegistry { + /** Registers [adapter] and returns a handle that removes and closes it. */ + fun register(adapter: PlaceholderAdapter): AutoCloseable + /** Returns the adapter with case-insensitive [id], or `null`. */ + fun get(id: String): PlaceholderAdapter? + /** Returns an adapter or fails when it is unavailable. */ + fun require(id: String): PlaceholderAdapter = get(id) ?: error("Placeholder adapter $id is unavailable") + /** Returns a stable snapshot of adapters ordered by identifier. */ + fun all(): List +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderKey.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey.kt similarity index 84% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderKey.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey.kt index 8658d85be..3349775e8 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderKey.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderKey.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.placeholders +package org.pnfolder.pnlibrary.api.placeholders.model /** * Validated placeholder identifier and the value type produced by its resolver. @@ -15,6 +15,7 @@ data class PlaceholderKey(val value: String, val type: Class) { companion object { private val VALID_KEY = Regex("[a-z0-9_.{}-]+") + /** Creates a key named [value] whose values have the given [type]. */ @JvmStatic fun of(value: String, type: Class): PlaceholderKey = PlaceholderKey(value, type) } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderModel.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderModel.kt new file mode 100644 index 000000000..1c4c9a042 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderModel.kt @@ -0,0 +1,7 @@ +package org.pnfolder.pnlibrary.api.placeholders.model + +/** Resolves one placeholder synchronously; `null` selects its configured fallback. */ +fun interface PlaceholderResolver { + /** Produces a value for [request], or `null` when no value is available. */ + fun resolve(request: PlaceholderRequest): T? +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderPublication.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderPublication.kt similarity index 89% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderPublication.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderPublication.kt index fafdfdbc3..42a85cee7 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderPublication.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderPublication.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.placeholders +package org.pnfolder.pnlibrary.api.placeholders.model /** * Requested external name for a library placeholder. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderRequest.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderRequest.kt similarity index 95% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderRequest.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderRequest.kt index a126fffda..f030faf26 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderRequest.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/model/PlaceholderRequest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.placeholders +package org.pnfolder.pnlibrary.api.placeholders.model import org.pnfolder.pnlibrary.api.plugin.PluginId import java.util.UUID diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/ArgType.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/ArgType.kt new file mode 100644 index 000000000..1015075de --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/ArgType.kt @@ -0,0 +1,13 @@ +package org.pnfolder.pnlibrary.api.placeholders.tree + +/** Turns one path part of a placeholder into a typed value; `null` means the part does not fit. */ +abstract class ArgType( + /** Short word shown to the administrator, such as `int` or `player`. */ + val label: String, +) { + /** Parses [text], or returns `null` when it is not a valid value of this type. */ + abstract fun parse(text: String): T? + + /** Allowed values when the type has a fixed list, otherwise empty. */ + open val choices: List get() = emptyList() +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/ArgTypes.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/ArgTypes.kt new file mode 100644 index 000000000..af5fed8f8 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/ArgTypes.kt @@ -0,0 +1,37 @@ +package org.pnfolder.pnlibrary.api.placeholders.tree + +/** The argument types a placeholder branch can take. */ +object ArgTypes { + val int: ArgType = object : ArgType("int") { + override fun parse(text: String) = text.toIntOrNull() + } + val number: ArgType = object : ArgType("number") { + override fun parse(text: String) = text.toDoubleOrNull()?.takeIf { it.isFinite() } + } + val text: ArgType = object : ArgType("text") { + override fun parse(text: String) = text.takeIf { it.isNotEmpty() } + } + val bool: ArgType = object : ArgType("bool") { + override fun parse(text: String) = when (text.lowercase()) { + "true", "yes", "1" -> true + "false", "no", "0" -> false + else -> null + } + } + val player: ArgType = object : ArgType("player") { + override fun parse(text: String) = text.takeIf { it.matches(PLAYER_NAME) }?.let(::PlayerArg) + } + + /** An integer inside [range]. */ + fun int(range: IntRange): ArgType = object : ArgType("int ${range.first}..${range.last}") { + override fun parse(text: String) = text.toIntOrNull()?.takeIf { it in range } + } + + /** One of [values], compared without regard to case; the stored spelling is returned. */ + fun choice(vararg values: String): ArgType = object : ArgType("choice") { + override val choices = values.toList() + override fun parse(text: String) = values.firstOrNull { it.equals(text, ignoreCase = true) } + } + + private val PLAYER_NAME = Regex("[A-Za-z0-9_.-]{1,36}") +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/GroupData.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/GroupData.kt new file mode 100644 index 000000000..c70fc2db8 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/GroupData.kt @@ -0,0 +1,8 @@ +package org.pnfolder.pnlibrary.api.placeholders.tree + +/** The settings and branches of one `placeholders { }` block. */ +internal class GroupData(val papiPrefix: String?) { + val roots = mutableListOf() + var format: FormatChoice = FormatChoice.Inherit + var access: AccessRule = AccessRule.AllowAll +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/Node.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/Node.kt new file mode 100644 index 000000000..8931d67ef --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/Node.kt @@ -0,0 +1,13 @@ +package org.pnfolder.pnlibrary.api.placeholders.tree + +import java.util.concurrent.CompletionStage + +/** One branch of a placeholder tree before it is turned into registered placeholders. */ +internal class Node(var segment: Segment, val valueType: Class<*>) { + val children = mutableListOf() + var value: ((PlaceholderCall) -> CompletionStage)? = null + var format: FormatChoice = FormatChoice.Inherit + var access: AccessRule? = null + var inside: Boolean = false + var updater: Updater? = null +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderArguments.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderArguments.kt index 12fdb9729..dcd99234f 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderArguments.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderArguments.kt @@ -9,51 +9,3 @@ class PlayerArg(val text: String) { override fun toString(): String = text } - -/** Turns one path part of a placeholder into a typed value; `null` means the part does not fit. */ -abstract class ArgType( - /** Short word shown to the administrator, such as `int` or `player`. */ - val label: String, -) { - /** Parses [text], or returns `null` when it is not a valid value of this type. */ - abstract fun parse(text: String): T? - - /** Allowed values when the type has a fixed list, otherwise empty. */ - open val choices: List get() = emptyList() -} - -/** The argument types a placeholder branch can take. */ -object ArgTypes { - val int: ArgType = object : ArgType("int") { - override fun parse(text: String) = text.toIntOrNull() - } - val number: ArgType = object : ArgType("number") { - override fun parse(text: String) = text.toDoubleOrNull()?.takeIf { it.isFinite() } - } - val text: ArgType = object : ArgType("text") { - override fun parse(text: String) = text.takeIf { it.isNotEmpty() } - } - val bool: ArgType = object : ArgType("bool") { - override fun parse(text: String) = when (text.lowercase()) { - "true", "yes", "1" -> true - "false", "no", "0" -> false - else -> null - } - } - val player: ArgType = object : ArgType("player") { - override fun parse(text: String) = text.takeIf { it.matches(PLAYER_NAME) }?.let(::PlayerArg) - } - - /** An integer inside [range]. */ - fun int(range: IntRange): ArgType = object : ArgType("int ${range.first}..${range.last}") { - override fun parse(text: String) = text.toIntOrNull()?.takeIf { it in range } - } - - /** One of [values], compared without regard to case; the stored spelling is returned. */ - fun choice(vararg values: String): ArgType = object : ArgType("choice") { - override val choices = values.toList() - override fun parse(text: String) = values.firstOrNull { it.equals(text, ignoreCase = true) } - } - - private val PLAYER_NAME = Regex("[A-Za-z0-9_.-]{1,36}") -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderCall.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderCall.kt index 8ba51691a..5777d6c2c 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderCall.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderCall.kt @@ -1,6 +1,6 @@ package org.pnfolder.pnlibrary.api.placeholders.tree -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRequest +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest import org.pnfolder.pnlibrary.api.plugin.PluginId import java.util.UUID diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderGeneration.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderGeneration.kt index f08db5e37..b6a03fcb1 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderGeneration.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderGeneration.kt @@ -1,5 +1,8 @@ package org.pnfolder.pnlibrary.api.placeholders.tree +import org.pnfolder.pnlibrary.api.placeholders.tree.scope.BranchScope +import org.pnfolder.pnlibrary.api.placeholders.tree.scope.GroupScope +import org.pnfolder.pnlibrary.api.placeholders.tree.scope.checkPart import java.lang.reflect.Method import java.lang.reflect.Modifier import java.util.concurrent.CompletableFuture diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderInstaller.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderInstaller.kt index 93d7fa766..050eafa0c 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderInstaller.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderInstaller.kt @@ -1,11 +1,11 @@ package org.pnfolder.pnlibrary.api.placeholders.tree -import org.pnfolder.pnlibrary.api.placeholders.AsyncPlaceholderResolver import org.pnfolder.pnlibrary.api.placeholders.PlaceholderBuilder -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderPublication -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRequest import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService import org.pnfolder.pnlibrary.api.placeholders.PlaceholderUpdater +import org.pnfolder.pnlibrary.api.placeholders.model.AsyncPlaceholderResolver +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderPublication +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage import java.util.function.Consumer @@ -15,6 +15,7 @@ internal class PlaceholderInstaller( private val service: PlaceholderService, private val moduleId: String, ) { + /** Registers the placeholder group with the platform. */ fun install(group: GroupData) { val format = group.format.resolve(null) group.roots.forEach { walk(group, it, emptyList(), format, group.access, false) } @@ -47,7 +48,8 @@ internal class PlaceholderInstaller( private fun evaluate(node: Node, path: List, request: PlaceholderRequest): CompletionStage { val call = callFor(path, request) ?: return CompletableFuture.completedFuture(null) - return node.value!!(call) + val value = checkNotNull(node.value) { "A placeholder node without a value cannot be evaluated" } + return value(call) } private fun change(updater: Updater, path: List, request: PlaceholderRequest, text: String): Any? { diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderNode.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderNode.kt index 426421f44..deea6b50d 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderNode.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderNode.kt @@ -1,29 +1,7 @@ package org.pnfolder.pnlibrary.api.placeholders.tree -import java.util.concurrent.CompletionStage - /** One part of a placeholder path: a fixed word or an argument. */ internal sealed class Segment { class Literal(val name: String) : Segment() class Arg(val name: String, val type: ArgType<*>) : Segment() } - -/** The way to change a placeholder from outside, and who may do it. */ -internal class Updater(val rule: AccessRule, val run: (PlaceholderCall, String) -> Any?) - -/** One branch of a placeholder tree before it is turned into registered placeholders. */ -internal class Node(var segment: Segment, val valueType: Class<*>) { - val children = mutableListOf() - var value: ((PlaceholderCall) -> CompletionStage)? = null - var format: FormatChoice = FormatChoice.Inherit - var access: AccessRule? = null - var inside: Boolean = false - var updater: Updater? = null -} - -/** The settings and branches of one `placeholders { }` block. */ -internal class GroupData(val papiPrefix: String?) { - val roots = mutableListOf() - var format: FormatChoice = FormatChoice.Inherit - var access: AccessRule = AccessRule.AllowAll -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderRules.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderRules.kt index 77a80a4f1..b6e95454d 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderRules.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/PlaceholderRules.kt @@ -1,26 +1,26 @@ package org.pnfolder.pnlibrary.api.placeholders.tree -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAccess +import org.pnfolder.pnlibrary.api.plugin.PluginAccess /** Who may read (or change) a placeholder. A denial always beats an allowance. */ sealed class AccessRule { - internal abstract fun toAccess(): PlaceholderAccess + internal abstract fun toAccess(): PluginAccess internal object AllowAll : AccessRule() { - override fun toAccess(): PlaceholderAccess = PlaceholderAccess.shared() + override fun toAccess(): PluginAccess = PluginAccess.shared() } internal object DenyAll : AccessRule() { - override fun toAccess(): PlaceholderAccess = PlaceholderAccess.ownerOnly() + override fun toAccess(): PluginAccess = PluginAccess.ownerOnly() } internal class AllowOnly(private val ids: List) : AccessRule() { - override fun toAccess(): PlaceholderAccess = PlaceholderAccess.builder().owner().allow(*ids.toTypedArray()).build() + override fun toAccess(): PluginAccess = PluginAccess.builder().owner().allow(*ids.toTypedArray()).build() } internal class Deny(private val ids: List) : AccessRule() { - override fun toAccess(): PlaceholderAccess = - PlaceholderAccess.builder().owner().allowAllLibraryPlugins().deny(*ids.toTypedArray()).build() + override fun toAccess(): PluginAccess = + PluginAccess.builder().owner().allowAll().deny(*ids.toTypedArray()).build() } } @@ -40,12 +40,16 @@ fun deny(vararg plugins: String): AccessRule = AccessRule.Deny(plugins.toList()) class AccessScope internal constructor() { internal var rule: AccessRule? = null + /** Every plugin may read. */ fun allowAll() { rule = AccessRule.AllowAll } + /** Only the owner may read. */ fun denyAll() { rule = AccessRule.DenyAll } + /** The owner and the listed plugins may read. */ fun allowOnly(vararg plugins: String) { rule = AccessRule.AllowOnly(plugins.toList()) } + /** The owner and every plugin except the listed ones may read. */ fun deny(vararg plugins: String) { rule = AccessRule.Deny(plugins.toList()) } } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/Updater.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/Updater.kt new file mode 100644 index 000000000..e26230dcc --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/Updater.kt @@ -0,0 +1,4 @@ +package org.pnfolder.pnlibrary.api.placeholders.tree + +/** The way to change a placeholder from outside, and who may do it. */ +internal class Updater(val rule: AccessRule, val run: (PlaceholderCall, String) -> Any?) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/BranchScope.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope.kt similarity index 90% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/BranchScope.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope.kt index 36f16401f..6558ab989 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/BranchScope.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/scope/BranchScope.kt @@ -1,4 +1,10 @@ -package org.pnfolder.pnlibrary.api.placeholders.tree +package org.pnfolder.pnlibrary.api.placeholders.tree.scope + +import org.pnfolder.pnlibrary.api.placeholders.tree.ArgType +import org.pnfolder.pnlibrary.api.placeholders.tree.ArgTypes +import org.pnfolder.pnlibrary.api.placeholders.tree.Node +import org.pnfolder.pnlibrary.api.placeholders.tree.PlayerArg +import org.pnfolder.pnlibrary.api.placeholders.tree.Segment /** * Where branches can be added. A branch gets a word (`int("kills")`) or takes an argument from the path diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/GroupScope.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/scope/GroupScope.kt similarity index 78% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/GroupScope.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/scope/GroupScope.kt index 7785c4874..10f692db6 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/GroupScope.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/scope/GroupScope.kt @@ -1,5 +1,11 @@ -package org.pnfolder.pnlibrary.api.placeholders.tree +package org.pnfolder.pnlibrary.api.placeholders.tree.scope +import org.pnfolder.pnlibrary.api.placeholders.tree.AccessRule +import org.pnfolder.pnlibrary.api.placeholders.tree.AccessScope +import org.pnfolder.pnlibrary.api.placeholders.tree.FormatChoice +import org.pnfolder.pnlibrary.api.placeholders.tree.GroupData +import org.pnfolder.pnlibrary.api.placeholders.tree.PlaceholderInstaller +import org.pnfolder.pnlibrary.api.placeholders.tree.none import org.pnfolder.pnlibrary.api.plugin.ModuleContext /** diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/NodeScope.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/scope/NodeScope.kt similarity index 80% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/NodeScope.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/scope/NodeScope.kt index da9f15331..9e8dbdd01 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/NodeScope.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/placeholders/tree/scope/NodeScope.kt @@ -1,5 +1,12 @@ -package org.pnfolder.pnlibrary.api.placeholders.tree - +package org.pnfolder.pnlibrary.api.placeholders.tree.scope + +import org.pnfolder.pnlibrary.api.placeholders.tree.AccessRule +import org.pnfolder.pnlibrary.api.placeholders.tree.AccessScope +import org.pnfolder.pnlibrary.api.placeholders.tree.FormatChoice +import org.pnfolder.pnlibrary.api.placeholders.tree.Node +import org.pnfolder.pnlibrary.api.placeholders.tree.PlaceholderCall +import org.pnfolder.pnlibrary.api.placeholders.tree.Updater +import org.pnfolder.pnlibrary.api.placeholders.tree.none import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/CommandErrors.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/CommandErrors.kt index 213460783..0dea707fa 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/CommandErrors.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/CommandErrors.kt @@ -1,8 +1,8 @@ package org.pnfolder.pnlibrary.api.plugin import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandError -import org.pnfolder.pnlibrary.api.commands.CommandErrorHandler +import org.pnfolder.pnlibrary.api.commands.error.CommandError +import org.pnfolder.pnlibrary.api.commands.error.CommandErrorHandler /** * Kotlin form of [ModuleContext.onCommandError]: `context.onCommandError { error -> sender.send(...) }`. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/ModuleContext.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/ModuleContext.kt index 878f4458e..d53a55af7 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/ModuleContext.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/ModuleContext.kt @@ -1,44 +1,46 @@ package org.pnfolder.pnlibrary.api.plugin import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.actions.ActionService -import org.pnfolder.pnlibrary.api.commands.CommandBuilder -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.CommandError -import org.pnfolder.pnlibrary.api.commands.CommandErrorHandler import org.pnfolder.pnlibrary.api.commands.CommandRegistration +import org.pnfolder.pnlibrary.api.commands.definition.CommandBuilder +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command +import org.pnfolder.pnlibrary.api.commands.error.CommandError +import org.pnfolder.pnlibrary.api.commands.error.CommandErrorHandler import org.pnfolder.pnlibrary.api.config.ConfigScope import org.pnfolder.pnlibrary.api.cooldowns.CooldownService import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticRegistration import org.pnfolder.pnlibrary.api.downloads.DownloadRegistration -import org.pnfolder.pnlibrary.api.events.EventScope +import org.pnfolder.pnlibrary.api.events.bus.EventScope import org.pnfolder.pnlibrary.api.expansions.ExpansionManager +import org.pnfolder.pnlibrary.api.libraries.ModuleLibraries import org.pnfolder.pnlibrary.api.logging.PnLogger -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter import org.pnfolder.pnlibrary.api.metrics.MetricsController +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService +import org.pnfolder.pnlibrary.api.plugin.control.ModuleControl +import org.pnfolder.pnlibrary.api.plugin.lifecycle.PluginLifecycle +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMessages +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata +import org.pnfolder.pnlibrary.api.scenario.actions.ActionService import org.pnfolder.pnlibrary.api.services.ServiceManager import org.pnfolder.pnlibrary.api.tasks.TaskScope import org.pnfolder.pnlibrary.api.text.ComponentService import org.pnfolder.pnlibrary.api.updates.UpdateRegistration import org.pnfolder.pnlibrary.localization.MinecraftLocalization -import java.util.Locale /** Owns the isolated pnLibrary capabilities of one logical plugin module. */ interface ModuleContext : AutoCloseable { /** Registers a command released when this module closes. */ - fun registerCommand(command: CommandDefinition): CommandRegistration = - throw UnsupportedOperationException("Module commands are not available in this runtime") + fun registerCommand(command: CommandDefinition): CommandRegistration /** * Answers errors of class [type] for every command of this module with [handler]. The most specific level * wins: a handler on a command or subcommand over this one, this one over the plugin-wide answer of * [PluginRegistration.onCommandError], over the library's standard - * answer from `config.yml`. + * answer from the library's settings. */ - fun onCommandError(type: Class, handler: CommandErrorHandler) { - throw UnsupportedOperationException("Module commands are not available in this runtime") - } + fun onCommandError(type: Class, handler: CommandErrorHandler) /** Answers errors of class [type] for every command of this module with the plain [message]. */ fun onCommandError(type: Class, message: String) { @@ -48,7 +50,7 @@ interface ModuleContext : AutoCloseable { /** Builds a command whose lifecycle belongs to this module. */ fun registerCommand(name: String, configure: CommandBuilder.() -> Unit): CommandRegistration = - registerCommand(org.pnfolder.pnlibrary.api.commands.command(name, configure)) + registerCommand(command(name, configure)) /** Registry-wide stable identity used by shared services and diagnostics. */ val key: PluginId @@ -71,17 +73,15 @@ interface ModuleContext : AutoCloseable { * version and locale one plugin loaded is cached for all. Closing this view does nothing, and keyboard layouts * registered through its `layouts` are removed when this module closes; no handle needs closing. * - * Available on game servers only: on a proxy this throws [UnsupportedOperationException]. + * Backed by the library's localization expansion, which is made for game servers. */ val localization: MinecraftLocalization - get() = throw UnsupportedOperationException("Minecraft localization is not available on this platform") /** * The library's expansions with ownership: what this module registers through it is disabled and unregistered when * the module closes, with no handle to keep. Lookups read the same registry as `PnLibrary.expansions`, and ids stay * unique across the library. */ val expansions: ExpansionManager - get() = throw UnsupportedOperationException("Expansions are not available in this runtime") /** Module-bound structured logger. */ val logger: PnLogger /** Module-bound configuration scope. */ @@ -104,33 +104,12 @@ interface ModuleContext : AutoCloseable { val updates: UpdateRegistration? /** Auxiliary download registration, or `null` when none was configured. */ val downloads: DownloadRegistration? + /** The Maven libraries of this module; see `PluginModule.libraries()`. */ + val libraries: ModuleLibraries + /** Switches this module on and off; the same operations as `/pn modules` and the menu. */ + val control: ModuleControl /** Whether this module has released all owned resources. */ val isClosed: Boolean /** Releases every capability and registration owned by this module. */ override fun close() } - -/** Validated, case-insensitive local identity of a logical module. */ -class ModuleId private constructor( - /** Normalized lowercase module identifier. */ - val value: String, -) { - /** Returns whether [other] contains the same normalized identifier. */ - override fun equals(other: Any?): Boolean = other is ModuleId && value == other.value - /** Returns the normalized identifier hash. */ - override fun hashCode(): Int = value.hashCode() - /** Returns [value] without additional formatting. */ - override fun toString(): String = value - - companion object { - private val FORMAT = Regex("[a-z0-9][a-z0-9_.-]{0,63}") - - /** Normalizes and validates [value]. */ - @JvmStatic - fun of(value: String): ModuleId { - val normalized = value.trim().lowercase(Locale.ROOT) - require(FORMAT.matches(normalized)) { "Module ID must match ${FORMAT.pattern}" } - return ModuleId(normalized) - } - } -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginBuilder.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginBuilder.kt index 44f12307e..9aa9500ce 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginBuilder.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginBuilder.kt @@ -2,12 +2,14 @@ package org.pnfolder.pnlibrary.api.plugin import org.pnfolder.pnlibrary.api.dependencies.DependencyBuilder import org.pnfolder.pnlibrary.api.dependencies.PluginDependency -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticContainer +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticContainer import org.pnfolder.pnlibrary.api.downloads.FileDownloads -import org.pnfolder.pnlibrary.api.metrics.MetricsBuilder +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsBuilder +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadataBuilder +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginOptions import org.pnfolder.pnlibrary.api.remote.RemotePolicySettings -import org.pnfolder.pnlibrary.api.updates.PluginUpdateRequest -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest import java.nio.file.Path import java.util.function.Consumer @@ -18,8 +20,10 @@ import java.util.function.Consumer * callback returns and rolls back partial resources if any integration fails to initialize. */ interface PluginBuilder { + /** Declares one dependency of the plugin. */ fun depends(dependency: PluginDependency): PluginBuilder + /** Declares several dependencies of the plugin. */ fun depends(vararg dependencies: PluginDependency): PluginBuilder { dependencies.forEach(::depends) return this @@ -59,6 +63,7 @@ interface PluginBuilder { return updates(builder.build()) } + /** Declares dependencies with the dependency DSL. */ fun dependencies(configure: Consumer): PluginBuilder { val builder = DependencyBuilder() configure.accept(builder) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginMessages.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginMessages.kt deleted file mode 100644 index e56d6df8e..000000000 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginMessages.kt +++ /dev/null @@ -1,8 +0,0 @@ -package org.pnfolder.pnlibrary.api.plugin - -import org.pnfolder.pnlibrary.api.logging.MessageBox - -interface PluginMessages { - - fun box(title: String): MessageBox -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginRegistration.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginRegistration.kt index 9681ea0c8..5a656ed0e 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginRegistration.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginRegistration.kt @@ -1,25 +1,29 @@ package org.pnfolder.pnlibrary.api.plugin import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.commands.CommandError -import org.pnfolder.pnlibrary.api.commands.CommandErrorHandler +import org.pnfolder.pnlibrary.api.commands.error.CommandError +import org.pnfolder.pnlibrary.api.commands.error.CommandErrorHandler +import org.pnfolder.pnlibrary.api.config.ConfigInfo +import org.pnfolder.pnlibrary.api.libraries.ModuleLibraries +import org.pnfolder.pnlibrary.api.libraries.ModuleLibrary +import org.pnfolder.pnlibrary.api.plugin.control.PluginModule import java.util.function.Consumer /** Registration of one native platform plugin and all logical modules it owns. */ interface PluginRegistration : AutoCloseable { /** Native platform plugin owning this registration. */ val owner: Any + /** Identifier of the plugin, as in `quests/main:quests.yml`. */ + val id: PluginId /** Whether this registration has released its modules. */ val isClosed: Boolean /** * Answers errors of class [type] for every command of this plugin, in all of its modules, with [handler]. The most specific level * wins: a handler on a command or subcommand over this one, over the library's standard - * answer from `config.yml`. + * answer from the library's settings. */ - fun onCommandError(type: Class, handler: CommandErrorHandler) { - throw UnsupportedOperationException("Plugin commands are not available in this runtime") - } + fun onCommandError(type: Class, handler: CommandErrorHandler) /** Answers errors of class [type] for every command of this plugin, in all of its modules, with the plain [message]. */ fun onCommandError(type: Class, message: String) { @@ -27,12 +31,39 @@ interface PluginRegistration : AutoCloseable { onCommandError(type, CommandErrorHandler { context, error -> context.sender.send(Component.text(error.format(text))) }) } + /** + * The libraries of the whole plugin: what is registered here is available to every module of it, so a library several + * modules need is downloaded once. Modules keep their own in `ModuleContext.libraries`. + */ + val libraries: ModuleLibraries + + /** Every library of this plugin: its own and those of each module, without repeats. */ + val allLibraries: List + get() = (libraries.loaded + all().flatMap { it.libraries.loaded }).distinct() + /** Registers a logical module identified by [id]. */ fun registerModule( id: ModuleId, configure: Consumer = Consumer { }, ): ModuleContext + /** + * Registers a module that the library can switch: [module]'s `onEnable` runs right away (unless an administrator + * switched this module off for good), and later `/pn modules` and the menu call its hooks. + */ + fun registerModule( + id: ModuleId, + module: PluginModule, + configure: Consumer = Consumer { }, + ): ModuleContext + + /** Normalizes [id] and registers a switchable module; see [registerModule]. */ + fun registerModule( + id: String, + module: PluginModule, + configure: Consumer = Consumer { }, + ): ModuleContext = registerModule(ModuleId.of(id), module, configure) + /** Normalizes [id] and registers a logical module. */ fun registerModule( id: String, @@ -61,6 +92,9 @@ interface PluginRegistration : AutoCloseable { /** Returns an immutable snapshot of logical modules owned by this plugin. */ fun all(): List + /** Every configuration file of every module of this plugin. */ + fun configs(): List = all().flatMap { it.configs.list() } + /** Closes every owned module and releases this registration. */ override fun close() } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginRegistry.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginRegistry.kt index 2af85df6e..e5a22ae3c 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginRegistry.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginRegistry.kt @@ -1,5 +1,7 @@ package org.pnfolder.pnlibrary.api.plugin +import org.pnfolder.pnlibrary.api.libraries.LibraryUsage + /** * Registry of native platform plugins using one pnLibrary runtime. * @@ -19,12 +21,34 @@ interface PluginRegistry : AutoCloseable { fun require(owner: Any): PluginRegistration = get(owner) ?: error("Platform plugin ${owner.javaClass.name} is not registered in pnLibrary") + /** Returns the registration of the plugin with identifier [id], or `null` when no such plugin is registered. */ + fun getById(id: PluginId): PluginRegistration? = all().firstOrNull { it.id == id } + + /** Normalizes [id] and returns the matching registration, or `null`. */ + fun getById(id: String): PluginRegistration? = getById(PluginId.of(id)) + + /** Returns the registration of the plugin with identifier [id], or fails naming the registered plugins. */ + fun requireById(id: PluginId): PluginRegistration = + getById(id) ?: error("Plugin $id is not registered in pnLibrary; registered: ${all().joinToString { it.id.value }}") + + /** Normalizes [id] and returns the matching registration, or fails naming the registered plugins. */ + fun requireById(id: String): PluginRegistration = requireById(PluginId.of(id)) + /** Closes and removes [owner]'s registration when present. */ fun unregister(owner: Any) /** Returns an immutable snapshot of registered platform plugins. */ fun all(): List + /** Every module of every plugin registered in the library. */ + fun allModules(): List = all().flatMap { it.all() } + + /** Every library registered anywhere, and who registered it, so one used by many modules shows once per owner. */ + fun libraryUsage(): List = all().flatMap { plugin -> + plugin.libraries.loaded.map { LibraryUsage(it, plugin.id, null) } + + plugin.all().flatMap { module -> module.libraries.loaded.map { LibraryUsage(it, plugin.id, module.id) } } + } + /** Closes all registrations in reverse ownership order. */ override fun close() } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/control/ModuleControl.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/control/ModuleControl.kt new file mode 100644 index 000000000..cc9947ce0 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/control/ModuleControl.kt @@ -0,0 +1,38 @@ +package org.pnfolder.pnlibrary.api.plugin.control + +import java.util.concurrent.CompletionStage + +/** + * Switches one module on and off. The same operations are behind `/pn modules` and the module screens of the menu. + * + * A module registered without a [PluginModule] has nothing to switch: [state] stays [ModuleState.ENABLED] and every + * change fails with [UnsupportedOperationException]. + */ +interface ModuleControl { + /** Current state. */ + val state: ModuleState + + /** The error that put the module into [ModuleState.FAILED], or `null`. */ + val lastError: Throwable? + + /** Whether the module has hooks, that is, was registered with a [PluginModule]. */ + val isControllable: Boolean + + /** Whether the module starts when the server starts; an administrator's choice is saved and survives restarts. */ + val autoStart: Boolean + + /** Switches the module on. Does nothing when it already works. */ + fun enable(): CompletionStage + + /** Switches the module off for now; it starts again with the server unless [autoStart] is off. */ + fun disable(): CompletionStage + + /** Disables the module and enables it again. */ + fun restart(): CompletionStage + + /** Re-reads the module's settings; when the module cannot do that in place it is restarted. */ + fun reload(): CompletionStage + + /** Saves whether the module starts with the server. This does not switch it on or off right now. */ + fun setAutoStart(enabled: Boolean) +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/control/ModuleState.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/control/ModuleState.kt new file mode 100644 index 000000000..ae03ade09 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/control/ModuleState.kt @@ -0,0 +1,13 @@ +package org.pnfolder.pnlibrary.api.plugin.control + +/** Where a module is in its life: running, switched off, or stopped by an error of its own hook. */ +enum class ModuleState { + /** The module's `onEnable` ran and it is working. */ + ENABLED, + + /** The module was switched off; its commands and tasks are released and it can be switched on again. */ + DISABLED, + + /** A hook threw: the module is not working and [ModuleControl.lastError] says why. Enabling it tries again. */ + FAILED, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/control/PluginModule.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/control/PluginModule.kt new file mode 100644 index 000000000..37852f23d --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/control/PluginModule.kt @@ -0,0 +1,44 @@ +package org.pnfolder.pnlibrary.api.plugin.control + +import org.pnfolder.pnlibrary.api.libraries.ModuleLibrary +import org.pnfolder.pnlibrary.api.plugin.ModuleContext + +/** + * What a plugin gives one of its modules so that the library, an administrator's command or the menu can switch it. + * + * Every method has an empty default, so a module overrides only what it needs. The [ModuleContext] is the module's own, + * the same one `registerModule` returned, so a hook reaches the logger, configuration, services and everything else + * from it. + * + * ```kotlin + * class Shop : PluginModule { + * override fun onEnable(context: ModuleContext) { + * context.registerCommand("shop") { /* ... */ } + * } + * } + * registration.registerModule("shop", Shop()) + * ``` + * + * When a module is disabled the library cancels its tasks and removes its commands after [onDisable], so those need no + * clean-up. Listeners, open files and anything else the module opened itself belong in [onDisable]. + */ +interface PluginModule { + /** + * The Maven libraries this module needs, with where to download them and how to check them. They are loaded before + * [onEnable] each time the module starts; one already loaded is not downloaded again. A required library that cannot be + * loaded leaves the module in [ModuleState.FAILED] with the reason. + */ + fun libraries(): List = emptyList() + + /** Starts the module: registers its commands, listeners and tasks. Runs at registration and on every enable. */ + fun onEnable(context: ModuleContext) {} + + /** Stops the module and releases what it opened itself. Runs on disable, on restart and when the plugin shuts down. */ + fun onDisable(context: ModuleContext) {} + + /** + * Re-reads the module's settings without stopping it. A module that cannot do this in place returns `false`, + * and the library restarts it instead. + */ + fun onReload(context: ModuleContext): Boolean = false +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/LifecycleRow.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow.kt similarity index 93% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/LifecycleRow.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow.kt index df31eee39..b5c16ba1e 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/LifecycleRow.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/lifecycle/LifecycleRow.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.plugin +package org.pnfolder.pnlibrary.api.plugin.lifecycle /** A row pnLibrary adds by itself to the enabled and disabled cards; a plugin can leave any of them out. */ enum class LifecycleRow { diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginLifecycle.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/lifecycle/PluginLifecycle.kt similarity index 58% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginLifecycle.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/lifecycle/PluginLifecycle.kt index e4c79680d..a86259b23 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginLifecycle.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/lifecycle/PluginLifecycle.kt @@ -1,6 +1,7 @@ -package org.pnfolder.pnlibrary.api.plugin +package org.pnfolder.pnlibrary.api.plugin.lifecycle import org.pnfolder.pnlibrary.api.logging.MessageBox +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata /** * Symmetric, buffered startup and shutdown messages bound to one plugin. @@ -11,7 +12,9 @@ interface PluginLifecycle { /** Metadata rendered into lifecycle summaries. */ val metadata: PluginMetadata + /** Starts the "plugin enabled" card; call `show()` on it when startup is done. */ fun enabled(): MessageBox + /** Starts the "plugin disabled" card; call `show()` on it from `onDisable`. */ fun disabled(): MessageBox } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMessages.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMessages.kt new file mode 100644 index 000000000..92f808c96 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMessages.kt @@ -0,0 +1,10 @@ +package org.pnfolder.pnlibrary.api.plugin.metadata + +import org.pnfolder.pnlibrary.api.logging.MessageBox + +/** Console message boxes bound to one plugin. */ +interface PluginMessages { + + /** Starts a console block titled [title]; nothing is printed until `show()`. */ + fun box(title: String): MessageBox +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginMetadata.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadata.kt similarity index 77% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginMetadata.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadata.kt index 8eba471fd..9464f261a 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginMetadata.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadata.kt @@ -1,6 +1,7 @@ -package org.pnfolder.pnlibrary.api.plugin +package org.pnfolder.pnlibrary.api.plugin.metadata import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.api.plugin.ModuleId /** * Immutable runtime metadata resolved when a plugin context is registered. @@ -13,6 +14,7 @@ import org.pnfolder.pnlibrary.api.platform.PlatformType * @property platformImplementation concrete platform implementation and version description * @property javaVersion complete JVM version string from the running process * @property javaFeature JVM feature release, for example `21` + * @property description one or two sentences on what the plugin or module is for, read by administrators in the menu; `null` when not given */ class PluginMetadata( val id: ModuleId, @@ -23,4 +25,5 @@ class PluginMetadata( val platformImplementation: String, val javaVersion: String, val javaFeature: Int, + val description: String? = null, ) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginMetadataBuilder.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadataBuilder.kt similarity index 74% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginMetadataBuilder.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadataBuilder.kt index 8398f1c79..695db6704 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginMetadataBuilder.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/metadata/PluginMetadataBuilder.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.plugin +package org.pnfolder.pnlibrary.api.plugin.metadata /** * Optional display metadata overrides used during [PluginRegistry.register]. @@ -14,6 +14,9 @@ interface PluginMetadataBuilder { /** Overrides the plugin version shown in lifecycle and diagnostic output. */ fun version(value: String): PluginMetadataBuilder + /** Says in a sentence or two what the plugin or module is for; `/pn modules` and the menu show it. */ + fun description(value: String): PluginMetadataBuilder = this + /** Overrides the display-ready author text. */ fun authors(value: String): PluginMetadataBuilder } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginOptions.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/metadata/PluginOptions.kt similarity index 89% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginOptions.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/metadata/PluginOptions.kt index fbcf15793..efd7dfff0 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginOptions.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/metadata/PluginOptions.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.plugin +package org.pnfolder.pnlibrary.api.plugin.metadata /** Optional switches that change how pnLibrary integrates one registered plugin. */ interface PluginOptions { diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicy.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicy.kt index a716fb77f..2cb99762e 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicy.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicy.kt @@ -43,30 +43,38 @@ class RemotePolicyResult private constructor( private val steps = mutableListOf() private val links = linkedMapOf() + /** Sets the short status word shown to the administrator. */ fun status(value: String): Builder = apply { status = value.trim().ifEmpty { null } } + /** Sets the one-line summary of the decision. */ fun headline(value: String): Builder = apply { headline = value.trim().ifEmpty { null } } + /** Adds a reason without nested details. */ fun reason(text: String): Builder = apply { reasons.child(text) } + /** Adds a reason with nested details configured by [configure]. */ fun reason(text: String, configure: java.util.function.Consumer): Builder = apply { reasons.branch(text, configure) } + /** Adds a labelled detail line. */ fun detail(label: String, value: Any): Builder = apply { require(label.isNotBlank()) { "Detail label must not be blank" } details[label.trim()] = value.toString() } + /** Adds a step the administrator can take to resolve the denial. */ fun step(text: String): Builder = apply { require(text.isNotBlank()) { "Step must not be blank" } steps += text.trim() } + /** Adds a labelled link with more information. */ fun link(label: String, url: String): Builder = apply { require(label.isNotBlank() && url.isNotBlank()) { "Link label and address must not be blank" } links[label.trim()] = url.trim() } + /** Creates the immutable result. */ fun build(): RemotePolicyResult = RemotePolicyResult( allowed, reasons.build(), status, headline, java.util.Collections.unmodifiableMap(LinkedHashMap(details)), @@ -76,14 +84,17 @@ class RemotePolicyResult private constructor( } companion object { + /** Returns a result that lets the remote action proceed. */ @JvmStatic fun allow(): RemotePolicyResult = RemotePolicyResult(true, RemotePolicyExplanation.builder("Проверка пройдена").build()) + /** Returns a result that blocks the action with a plain message. */ @JvmStatic fun deny(message: String): RemotePolicyResult = deny(RemotePolicyExplanation.builder(message.trim().ifEmpty { "Запуск запрещён" }).build()) + /** Returns a result that blocks the action with a structured explanation. */ @JvmStatic fun deny(explanation: RemotePolicyExplanation): RemotePolicyResult = RemotePolicyResult(false, explanation) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicyContext.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicyContext.kt index 6647997d8..104e5fd3e 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicyContext.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicyContext.kt @@ -79,17 +79,22 @@ class RemotePolicyContext private constructor(builder: Builder) { internal var server: ServerInfo? = null internal val values = linkedMapOf() internal val nativeHandles = mutableListOf() + /** Sets the product the decision is about. */ fun product(value: ProductInfo): Builder = apply { product = value } + /** Sets the platform the server runs on. */ fun platform(value: PlatformInfo): Builder = apply { platform = value } + /** Sets the information about the server. */ fun server(value: ServerInfo): Builder = apply { server = value } + /** Adds one custom value for the policy. */ fun value(key: String, value: String): Builder = apply { val normalized = key.trim() require(normalized.isNotEmpty()) { "Remote policy context value key must not be blank" } values[normalized] = value } + /** Adds several custom values for the policy. */ fun values(value: Map): Builder = apply { val normalized = value.mapKeys { (key, _) -> key.trim().also { require(it.isNotEmpty()) { "Remote policy context value key must not be blank" } } @@ -104,6 +109,7 @@ class RemotePolicyContext private constructor(builder: Builder) { } companion object { + /** Creates a new [Builder]. */ @JvmStatic fun builder(): Builder = Builder() } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation.kt index d32af0103..df4e6c25e 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicyExplanation.kt @@ -18,14 +18,18 @@ class RemotePolicyExplanation private constructor(builder: Builder) { class Builder internal constructor(internal val text: String) { internal val children = mutableListOf() + /** Adds a nested line with plain text. */ fun child(text: String): Builder = apply { children += builder(text).build() } + /** Adds a nested line whose own children are configured by [configure]. */ fun branch(text: String, configure: Consumer): Builder = apply { children += builder(text).also(configure::accept).build() } + /** Adds an already built explanation as a nested line. */ fun child(value: RemotePolicyExplanation): Builder = apply { children += value } + /** Creates the immutable explanation. */ fun build(): RemotePolicyExplanation = RemotePolicyExplanation(this) } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicySettings.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicySettings.kt index db3c2b185..dde7aa475 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicySettings.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/remote/RemotePolicySettings.kt @@ -56,6 +56,7 @@ data class RemotePolicySettings( private var startupTimeout: Duration = DEFAULT_STARTUP_TIMEOUT private val values = linkedMapOf() + /** Sets the source the policy is fetched from. */ fun source(value: String): Builder = apply { val uri = URI.create(value) val https = uri.isHttps() @@ -81,6 +82,7 @@ data class RemotePolicySettings( startupTimeout = value } + /** Sets what happens when the policy denies an action. */ fun onDeny(value: DenyAction): Builder = apply { onDeny = value } /** Sets what a policy that cannot be checked means; [PolicyErrorAction.DENY] by default. */ @@ -92,11 +94,13 @@ data class RemotePolicySettings( supportUrl = url } + /** Adds one custom value sent to the policy. */ fun value(key: String, value: String): Builder = apply { val normalized = key.trim() require(normalized.isNotEmpty()) { "Remote policy value key must not be blank" } values[normalized] = value } + /** Adds several custom values sent to the policy. */ fun values(values: Map): Builder = apply { values.forEach(::value) } /** Validates required fields and creates the immutable policy. */ @@ -115,6 +119,7 @@ data class RemotePolicySettings( private val MINIMUM_CHECK_EVERY: Duration = Duration.ofMinutes(1) private val DEFAULT_STARTUP_TIMEOUT: Duration = Duration.ofSeconds(20) + /** Creates a new [Builder]. */ @JvmStatic fun builder(): Builder = Builder() } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/runtime/PnLibrary.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/runtime/PnLibrary.kt index c717c41fd..85af2652b 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/runtime/PnLibrary.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/runtime/PnLibrary.kt @@ -1,18 +1,18 @@ package org.pnfolder.pnlibrary.api.runtime -import org.pnfolder.pnlibrary.api.activity.ActivityService import org.pnfolder.pnlibrary.api.audiences.AudienceService import org.pnfolder.pnlibrary.api.config.ConfigurationService import org.pnfolder.pnlibrary.api.diagnostics.DebugRequest -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticReport import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsService -import org.pnfolder.pnlibrary.api.events.EventService +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticReport +import org.pnfolder.pnlibrary.api.events.bus.EventService import org.pnfolder.pnlibrary.api.expansions.ExpansionManager import org.pnfolder.pnlibrary.api.logging.LoggingService import org.pnfolder.pnlibrary.api.metrics.MetricsService +import org.pnfolder.pnlibrary.api.network.NetworkProxy import org.pnfolder.pnlibrary.api.observability.ObservabilityService -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterRegistry -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderValueStore +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderValueStore +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderAdapterRegistry import org.pnfolder.pnlibrary.api.platform.PlatformProvider import org.pnfolder.pnlibrary.api.plugin.PluginRegistry import org.pnfolder.pnlibrary.api.services.ServiceManager @@ -45,9 +45,6 @@ interface PnLibrary : Closeable { /** Observations, component status and support reports. */ val observability: ObservabilityService - /** Local bounded activity journal used by diagnostics and support reports. */ - val activity: ActivityService - /** Managed bStats sessions; every plugin supplies its own project ID. */ val metrics: MetricsService @@ -78,6 +75,9 @@ interface PnLibrary : Closeable { /** Type-safe native API for the active Bukkit, Bungee, or Velocity runtime. */ val platforms: PlatformProvider + /** The proxy layer; null when running on a game server instead of a proxy. */ + val proxy: NetworkProxy? + /** * Runtime-detected placeholder bridges such as PlaceholderAPI. * diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/runtime/PnLibraryConfig.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/runtime/PnLibraryConfig.kt index d7a9f7184..e2e531c5d 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/runtime/PnLibraryConfig.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/runtime/PnLibraryConfig.kt @@ -8,8 +8,7 @@ import java.util.regex.PatternSyntaxException /** * Immutable runtime policy for diagnostic collection, retention, and upload. * - * Paths in [excludedPaths] use dotted configuration notation, for example - * `database.password`. Regular expressions are compiled when this object is + * Regular expressions are compiled when this object is * created, so an invalid redaction policy fails during startup rather than while * a support report is being generated. * @@ -18,8 +17,7 @@ import java.util.regex.PatternSyntaxException * upload = false, * logs = true, * logRecords = 500, - * excludedPaths = listOf("database.password"), - * secretKeyPatterns = listOf("(?i).*(token|secret|password).*"), + * * secretKeyPatterns = listOf("(?i).*(token|secret|password).*"), * ) * ``` * @@ -48,7 +46,6 @@ import java.util.regex.PatternSyntaxException * age-based deletion * @property taskHistoryCapacity maximum number of completed task records retained in memory; * `0` disables task history - * @property excludedPaths dotted configuration paths omitted from every report * @property secretKeyPatterns regular expressions matched against configuration keys * whose values must be redacted * @property redactValuePatterns regular expressions whose matches are redacted inside @@ -73,7 +70,7 @@ import java.util.regex.PatternSyntaxException * expression is invalid */ data class PnLibraryConfig @JvmOverloads constructor( - val upload: Boolean = true, + val upload: Boolean = false, val uploadMode: String = "encrypted", val uploadProviders: List = listOf("catbox", "fileio"), val uploadEndpoint: String = "https://api.mclo.gs/1/log", @@ -91,7 +88,6 @@ data class PnLibraryConfig @JvmOverloads constructor( val maxReportBytes: Int = 8 * 1024 * 1024, val deleteAfterDays: Int = 90, val taskHistoryCapacity: Int = 256, - val excludedPaths: List = emptyList(), val secretKeyPatterns: List = emptyList(), val redactValuePatterns: List = emptyList(), val privacy: Boolean = false, @@ -107,6 +103,8 @@ data class PnLibraryConfig @JvmOverloads constructor( val playerNotFoundMessage: String = "Игрок {value} сейчас не в сети.", val playerOnlyMessage: String = "Эту команду можно использовать только в игре.", val consoleOnlyMessage: String = "Эту команду можно использовать только из консоли.", + val cooldownMessage: String = "Подождите {seconds} с перед повторным использованием.", + val commandFailedMessage: String = "Не удалось выполнить команду.", val journalJoinNoticeHours: Int = 24, val eventHistoryDays: Int = 30, ) { @@ -148,11 +146,10 @@ data class PnLibraryConfig @JvmOverloads constructor( require(maxReportBytes in 65_536..64 * 1024 * 1024) { "Setting maxReportBytes must be between 64 KiB and 64 MiB" } require(deleteAfterDays in 0..3_650) { "Setting deleteAfterDays must be between 0 and 3650" } require(taskHistoryCapacity in 0..10_000) { "Setting taskHistoryCapacity must be between 0 and 10000" } - require(excludedPaths.size <= 128 && secretKeyPatterns.size <= 64 && redactValuePatterns.size <= 64) { + require(secretKeyPatterns.size <= 64 && redactValuePatterns.size <= 64) { "Too many diagnostic redaction rules" } require(uploadKeyId.isNotBlank() && uploadKeyId.length <= 128) { "Setting uploadKeyId is invalid" } - excludedPaths.forEach { require(it.isNotBlank() && it.length <= 256) { "Invalid excluded path: $it" } } (secretKeyPatterns + redactValuePatterns).forEach { expression -> require(expression.isNotBlank() && expression.length <= 256) { "Invalid diagnostic regex" } try { diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/Action.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/Action.kt new file mode 100644 index 000000000..3f0846e25 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/Action.kt @@ -0,0 +1,81 @@ +package org.pnfolder.pnlibrary.api.scenario.actions + +import org.pnfolder.pnlibrary.api.config.ConfigPolymorphic +import org.pnfolder.pnlibrary.api.config.ConfigType +import org.pnfolder.pnlibrary.api.config.ConfigTypes +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.ActionBarAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.AttemptAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.CallAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.CommandAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.DelayAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.EffectAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.IfAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.LogAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.MessageAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.ParticleAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.RandomAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.RepeatAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.RequireAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.SetAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.SoundAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.StopAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.TitleAction + +/** + * One step of a configured scenario, such as sending a message, playing a sound or taking money. + * + * A scenario is a list of actions written in a configuration file; each action has a `type`. + * Actions run in order. Each one reports an [ActionResult]: the list goes on after [ActionResult.Done] and ends + * early after [ActionResult.Stopped] (a choice) or [ActionResult.Failed] (an error that undoes earlier steps). + * + * ```yaml + * on-buy: + * - type: require # stops quietly when the requirement is not met + * when: { type: permission, permission: shop.use } + * deny: + * - { type: message, messages: ['&cNo permission'] } + * - type: attempt # a failed charge shows a message instead of an error + * do: + * - { type: charge, currency: money, amount: 100 } + * - { type: command, command: 'give [player] diamond 1' } + * fail: + * - { type: message, messages: ['&cCannot pay: [error]'] } + * ``` + * + * Plugins may add their own types through the configuration type registry. In code an action is a lambda: + * + * ```kotlin + * val greet = Action { ctx -> + * ctx.player.sendMessage(Component.text("Hello, ${ctx.player.name}")) + * ActionResult.Done + * } + * ``` + * + * An action must keep to the services of [ActionContext] so that one parsed list can run many times, on any + * platform. It should report a problem as [ActionResult.Failed] rather than throw; a thrown exception is + * turned into a failure by the context. + */ +@ConfigPolymorphic(discriminator = "type") +@ConfigTypes( + ConfigType(MessageAction::class, "message", aliases = ["messages"]), + ConfigType(ActionBarAction::class, "actionbar", aliases = ["action-bar"]), + ConfigType(TitleAction::class, "title"), + ConfigType(SoundAction::class, "sound"), + ConfigType(CommandAction::class, "command"), + ConfigType(LogAction::class, "log"), + ConfigType(EffectAction::class, "effect"), + ConfigType(ParticleAction::class, "particle"), + ConfigType(DelayAction::class, "delay", aliases = ["wait"]), + ConfigType(RepeatAction::class, "repeat"), + ConfigType(IfAction::class, "if"), + ConfigType(RequireAction::class, "require"), + ConfigType(AttemptAction::class, "attempt"), + ConfigType(StopAction::class, "stop"), + ConfigType(SetAction::class, "set"), + ConfigType(CallAction::class, "call"), + ConfigType(RandomAction::class, "random"), +) +fun interface Action { + /** Performs the step with the data and services in [context] and reports how it went. */ + fun run(context: ActionContext): ActionResult +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionContext.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionContext.kt new file mode 100644 index 000000000..380180ff2 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionContext.kt @@ -0,0 +1,280 @@ +@file:Suppress("DEPRECATION") + +package org.pnfolder.pnlibrary.api.scenario.actions + +import net.kyori.adventure.text.Component +import org.pnfolder.pnlibrary.api.audiences.LibraryAudience +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.logging.PnLogger +import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapterState +import org.pnfolder.pnlibrary.api.scenario.expression.Expression +import org.pnfolder.pnlibrary.api.scenario.expression.ExpressionException +import org.pnfolder.pnlibrary.api.scenario.expression.ExpressionFunction +import org.pnfolder.pnlibrary.api.scenario.requirements.Requirement +import org.pnfolder.pnlibrary.api.scenario.requirements.RequirementContext +import org.pnfolder.pnlibrary.api.tasks.TaskScope +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec +import org.pnfolder.pnlibrary.api.text.ComponentService +import org.pnfolder.pnlibrary.api.text.serializer.ComponentSerializerType +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import java.time.Duration +import java.util.Collections + +/** + * One run of a scenario: who it is for, the values it knows, the services it may use, and what to undo. + * + * Create it with [ActionService.context], run a list with [execute], and read the [ActionResult]. + * A context belongs to one run and is not thread-safe: do not share it between concurrent runs. + * + * ```kotlin + * val context = module.actions.context(player, values = mapOf("item" to "diamond")) + * when (val result = context.execute(actions)) { + * ActionResult.Done -> Unit + * is ActionResult.Stopped -> Unit + * is ActionResult.Failed -> player.sendMessage(Component.text(result.message)) + * } + * ``` + * + * Every text an action prints may mention values, in three kinds of marks, see [format]. + * + * @property player player the run is for + * @property allPlayers wider audience for actions aimed at [ActionTarget.ALL_PLAYERS] + * @property components parser used by actions that print text + * @property logger plugin logger for warnings + * @property tasks task scope for delayed work + * @property serializerType default text format of printed text + * @param values named values texts and requirements read as `{name}` + * @param services services handed over directly, by exact type + * @param serviceLookup fallback for services registered elsewhere, such as in the module's service scope + * @param lookup actions, requirements and functions plugins defined by name + * @property placeholders placeholder service, or `null` when the runtime has none + */ +class ActionContext( + override val player: LibraryPlayer, + val allPlayers: LibraryAudience, + val components: ComponentService, + override val logger: PnLogger, + val tasks: TaskScope, + val serializerType: ComponentSerializerType = ComponentSerializerType.ADAPTIVE, + values: Map = emptyMap(), + private val services: Map, Any> = emptyMap(), + private val serviceLookup: (Class<*>) -> Any? = { null }, + private val lookup: ScenarioLookup = ScenarioLookup.NONE, + val placeholders: PlaceholderService? = null, +) : RequirementContext { + private val runtimeValues = LinkedHashMap(values) + private val undoSteps = ArrayList Unit>>() + + /** + * Runs [actions] as one scenario: in order, until one stops or fails. + * + * A failure undoes the steps that registered an [onUndo] and writes a warning; a thrown exception counts + * as a failure with the code `action.error`. Use this for the outermost list; actions that contain + * lists use [runList], so that the undo covers the whole scenario. + */ + fun execute(actions: List): ActionResult { + val result = runList(actions) + if (result is ActionResult.Failed) { + logger.warning("Scenario failed (${result.code}): ${result.message}", result.cause) + rollbackTo(0) + } + return result + } + + /** + * Runs [actions] in order and returns the first result that is not [ActionResult.Done], without undoing. + * It is the building block for actions that hold other actions. + */ + fun runList(actions: List): ActionResult { + for (action in actions) { + val result = try { + action.run(this) + } catch (error: Exception) { + ActionResult.Failed("action.error", error.message ?: error.javaClass.simpleName, error) + } + if (result !is ActionResult.Done) return result + } + return ActionResult.Done + } + + /** Runs [actions] as a separate scenario after [delay], without blocking the caller. */ + fun runLater(delay: Duration, actions: List) { + if (actions.isEmpty()) return + tasks.schedule(TaskSpec.builder() + .execution(TaskExecution.global()) + .delay(delay) + .action { execute(actions) } + .build()) + } + + /** + * Registers how to take back what the current step did, for example giving a charge back. + * + * When a later step fails, registered undo steps run in reverse order. [description] is for the log. + */ + fun onUndo(description: String, undo: () -> Unit) { + undoSteps += description to undo + } + + /** A bookmark of the undo list, for [rollbackTo]. */ + fun undoMark(): Int = undoSteps.size + + /** Forgets the undo steps registered after [mark] without running them: what they did stays. */ + fun discardUndo(mark: Int) { + while (undoSteps.size > mark) undoSteps.removeAt(undoSteps.lastIndex) + } + + /** Runs and removes the undo steps registered after [mark], newest first. One that throws is logged. */ + fun rollbackTo(mark: Int) { + while (undoSteps.size > mark) { + val (description, undo) = undoSteps.removeAt(undoSteps.lastIndex) + runCatchingNonFatal(undo).onFailure { logger.error("Could not undo: $description", it) } + } + } + + override fun service(type: Class): T? = (services[type] ?: serviceLookup(type))?.let(type::cast) + + /** Returns the service of [type], or throws when this run has none. */ + fun requireService(type: Class): T = + service(type) ?: error("${type.simpleName} is not available to this scenario") + + override fun value(name: String): Any? = runtimeValues[name] + + override fun requirement(name: String): Requirement? = lookup.requirement(name) + + override fun function(name: String): ExpressionFunction? = lookup.function(name) + + /** The action defined under [name] with [ActionService.define], or `null`. */ + fun action(name: String): Action? = lookup.action(name) + + /** + * Runs [block] with [extra] values added, then puts the values back as they were. + * Use it to give a called action its arguments without leaking them into the rest of the scenario. + */ + fun scoped(extra: Map, block: () -> T): T { + val saved = extra.keys.associateWith { runtimeValues[it] } + val had = extra.keys.filter { it in runtimeValues } + runtimeValues.putAll(extra) + try { + return block() + } finally { + extra.keys.forEach { if (it in had) runtimeValues[it] = saved[it] else runtimeValues.remove(it) } + } + } + + /** Makes [value] available as `[name]` to later steps. */ + fun setValue(name: String, value: Any?): ActionContext = apply { + require(name.isNotBlank()) { "Value name must not be blank" } + runtimeValues[name] = value + } + + /** A snapshot of the values known now. */ + fun values(): Map = Collections.unmodifiableMap(LinkedHashMap(runtimeValues)) + + /** The audience an action aimed at [target] sends to. */ + fun target(target: ActionTarget): LibraryAudience = if (target == ActionTarget.PLAYER) player else allPlayers + + /** Fills in the placeholders of [text] (see [format]), then parses it with [type] or [serializerType]. */ + fun component(text: String, type: ComponentSerializerType? = null): Component = + components.deserialize(format(text), type ?: serializerType) + + /** Parses [lines] as one component, one line under another. */ + fun component(lines: Iterable, type: ComponentSerializerType? = null): Component = + lines.map { component(it, type) }.reduceOrNull { all, line -> all.append(Component.newline()).append(line) } + ?: Component.empty() + + /** + * Replaces the placeholders in plain [text], each kind in its own brackets, in one pass: + * + * | Written | Taken from | + * |---|---| + * | `{name}` | a value of this run (and `player`), else a pnLibrary placeholder | + * | `{name}`, `{plugin:key}` | pnLibrary placeholders: the plugin's own, the library's, another plugin's | + * | `%name%` | the external PlaceholderAPI only | + * + * `{name}` takes a chain of formats after a bar, such as `{money|group}`. + * `player` and `player_name` are always the player's name. Text that a placeholder produced is not read again. + * Unknown names stay as written, so a typo is visible instead of silently empty. + */ + fun format(text: String): String = TOKEN.replace(text) { match -> + runCatchingNonFatal { valueOf(match) } + .onFailure { logger.error("Placeholder ${match.value} failed; it is left as written", it) } + .getOrNull()?.let { Expression.format(it) } ?: match.value + } + + override fun text(expression: String): String = + runCatchingNonFatal { read(expression) } + .onFailure { logger.error("Placeholder in '$expression' failed; the text is left as written", it) } + .getOrNull()?.toString() ?: format(expression) + + override fun read(expression: String): Any? { + val trimmed = expression.trim() + TOKEN.matchEntire(trimmed)?.let { return valueOf(it) } + if (TOKEN.containsMatchIn(trimmed)) return format(trimmed) + return resolve(trimmed) + } + + /** Resolves a bare `name` or `{name|formats}` as a run value first, then as a pnLibrary placeholder. */ + fun resolve(reference: String): Any? { + val expression = reference.trim().let { + if (it.startsWith("{") && it.endsWith("}")) it.substring(1, it.length - 1) else it + } + // Text with tags such as `[pnTest]` is a message, not a name: asking placeholders for it only logs a warning. + if ('<' in expression || '>' in expression) return null + runtimeValues[expression.substringBefore('|').trim()]?.let { return it } + return placeholders?.resolve(expression, player.uniqueId, runtimeValues)?.toCompletableFuture()?.join() + } + + /** Updates a writable registered placeholder and returns its resulting value. */ + fun updatePlaceholder(reference: String, value: String): Any? { + val service = placeholders ?: error("This scenario has no placeholder service") + return service.update(reference, value, player.uniqueId, runtimeValues).toCompletableFuture().join() + } + + private fun valueOf(match: MatchResult): Any? { + val braced = match.groups[1]?.value + if (braced != null && braced.startsWith("=")) return calculate(braced.substring(1)) + return when { + braced != null -> named(braced.substringBefore('|').trim()) { braced(braced.trim()) } + else -> named(requireNotNull(match.groups[2]) { "Token matched no placeholder group" }.value) { external(it) } + } + } + + /** `{= 2 * level}` in a text: the result of a calculation, see [Expression]. A mistake leaves the token as written. */ + private fun calculate(source: String): Any? = try { + Expression.format(Expression.parse(source).evaluate(this)) + } catch (error: ExpressionException) { + logger.warning("Calculation {=$source} failed: ${error.message}") + null + } + + private inline fun named(name: String, lookup: (String) -> Any?): Any? = + if (name == "player" || name == "player_name") player.name else lookup(name) + + /** + * `{name}`, `{name|format}`, `{plugin/module:path}`, `{papi:name}`: this run's value first, then a pnLibrary + * placeholder; `papi:` asks PlaceholderAPI. Without a placeholder service only this run's values are read. + */ + private fun braced(expression: String): Any? { + val name = expression.substringBefore('|').trim() + if (name.startsWith(PAPI_PREFIX)) return external(name.removePrefix(PAPI_PREFIX)) + val service = placeholders ?: return runtimeValues[name] + return service.resolve(expression, player.uniqueId, runtimeValues).toCompletableFuture().join() + } + + private fun external(name: String): Any? { + val adapter = placeholders?.adapters()?.get(EXTERNAL_ADAPTER) ?: return null + if (adapter.state != PlaceholderAdapterState.AVAILABLE && adapter.state != PlaceholderAdapterState.REGISTERED) return null + return adapter.resolve(player.uniqueId, name) + } + + private companion object { + const val EXTERNAL_ADAPTER = "placeholderapi" + private const val PAPI_PREFIX = "papi:" + + /** `{value-or-placeholder}` and `%external%`, each with its own capture group. */ + val TOKEN = Regex("\\{(?![?:/])([^{}]+)}|%([A-Za-z0-9_.:-]+)%") + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionDefinitions.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionDefinitions.kt new file mode 100644 index 000000000..a61a3dd7b --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionDefinitions.kt @@ -0,0 +1,13 @@ +package org.pnfolder.pnlibrary.api.scenario.actions + +/** What to do when a definition name is already taken, see [ActionService.define]. */ +enum class DefinitionConflict { + /** Refuse with an error; the default, so that a clash is never silent. */ + FAIL, + + /** Keep the existing definition and define nothing; the returned handle does nothing. */ + KEEP, + + /** Replace the existing definition of the same plugin or module; a definition of another owner is never replaced. */ + REPLACE, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionResult.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionResult.kt new file mode 100644 index 000000000..a176eee6e --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionResult.kt @@ -0,0 +1,34 @@ +package org.pnfolder.pnlibrary.api.scenario.actions + +/** + * How one [Action] went, and whether the rest of the list should run. + * + * ```kotlin + * when (val result = actions.execute(context)) { + * ActionResult.Done -> player.sendMessage(Component.text("Bought")) + * is ActionResult.Stopped -> Unit // a requirement said no, already explained + * is ActionResult.Failed -> logger.warning(result.message) + * } + * ``` + */ +sealed interface ActionResult { + /** The step finished; the next one runs. */ + data object Done : ActionResult + + /** + * The scenario ends on purpose, for example because a requirement was not met. Nothing is undone. + * + * @property reason short readable cause, or `null` + */ + data class Stopped(val reason: String? = null) : ActionResult + + /** + * The step could not do its job. The scenario ends and steps that registered an undo, such as a charge, + * give back what they took (see [ActionContext.onUndo]). + * + * @property code stable machine-readable cause such as `currency.insufficient-funds` + * @property message readable cause for logs and players + * @property cause original exception, when there was one + */ + data class Failed(val code: String, val message: String, val cause: Throwable? = null) : ActionResult +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionService.kt new file mode 100644 index 000000000..2956b169d --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionService.kt @@ -0,0 +1,80 @@ +package org.pnfolder.pnlibrary.api.scenario.actions + +import org.pnfolder.pnlibrary.api.audiences.LibraryAudience +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.scenario.expression.ExpressionFunction +import org.pnfolder.pnlibrary.api.scenario.requirements.Requirement +import org.pnfolder.pnlibrary.api.text.serializer.ComponentSerializerType + +/** + * Creates the contexts of one module's scenarios, and keeps the actions, requirements and functions the plugin + * defined by name. + * + * It holds no scenarios itself: the plugin keeps its parsed `List` and starts it for a player. + * + * ```kotlin + * module.actions.define("give-kit") { ctx -> // later: - { type: call, name: give-kit, args: { kit: starter } } + * kits.give(ctx.player, ctx.format("[kit]")) + * ActionResult.Done + * } + * module.actions.defineRequirement("is-vip", Requirement { ctx -> Verdict.of(ctx.player.hasPermission("vip"), "VIP only") }) + * module.actions.defineFunction("kills") { ctx, _ -> stats.kills(ctx.player.uniqueId) } // kills() in expressions + * + * val result = module.actions.execute(config.onBuy, player, values = mapOf("item" to "diamond")) + * ``` + */ +interface ActionService { + /** + * Creates a fresh context for one run. + * + * @param player player the run is for + * @param allPlayers audience for actions aimed at everyone; the player alone by default + * @param values named values texts and requirements can read as `[name]` + * @param serializerType default format of printed text + */ + fun context( + player: LibraryPlayer, + allPlayers: LibraryAudience = player, + values: Map = emptyMap(), + serializerType: ComponentSerializerType = ComponentSerializerType.ADAPTIVE, + ): ActionContext + + /** Creates a context and runs [actions] as one scenario; see [ActionContext.execute]. */ + fun execute( + actions: List, + player: LibraryPlayer, + allPlayers: LibraryAudience = player, + values: Map = emptyMap(), + ): ActionResult = context(player, allPlayers, values).execute(actions) + + /** + * Gives [action] a [name] so that scenarios can run it with `type: call`, passing `args` as values. + * Names are lowercase letters, digits, dots, hyphens and underscores. + * + * @param scope how far the name reaches + * @param conflict what to do when the name is taken + * @return a handle that removes the definition when closed + */ + fun define( + name: String, + action: Action, + scope: DefinitionScope = DefinitionScope.MODULE, + conflict: DefinitionConflict = DefinitionConflict.FAIL, + ): AutoCloseable + + /** Gives [requirement] a [name] for `type: ref` and for [org.pnfolder.pnlibrary.api.scenario.requirements.RequirementContext.requirement]. */ + fun defineRequirement( + name: String, + requirement: Requirement, + scope: DefinitionScope = DefinitionScope.MODULE, + conflict: DefinitionConflict = DefinitionConflict.FAIL, + ): AutoCloseable + + /** Adds [function] to the expression language under [name], for example `kills()`. Built-in names cannot be taken. */ + fun defineFunction( + name: String, + function: ExpressionFunction, + scope: DefinitionScope = DefinitionScope.MODULE, + conflict: DefinitionConflict = DefinitionConflict.FAIL, + ): AutoCloseable +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionTarget.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionTarget.kt new file mode 100644 index 000000000..5657993e4 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ActionTarget.kt @@ -0,0 +1,10 @@ +package org.pnfolder.pnlibrary.api.scenario.actions + +/** Who a message, title or sound of an action goes to. */ +enum class ActionTarget { + /** The player the scenario runs for. */ + PLAYER, + + /** Everyone the scenario was started for, see [ActionContext.allPlayers]. */ + ALL_PLAYERS, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope.kt new file mode 100644 index 000000000..e3f2d0e90 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/DefinitionScope.kt @@ -0,0 +1,10 @@ +package org.pnfolder.pnlibrary.api.scenario.actions + +/** How far a definition reaches, see [ActionService.define]. */ +enum class DefinitionScope { + /** Only scenarios of the module that defined it. */ + MODULE, + + /** Every module of every plugin; close the handle when your plugin is disabled. */ + LIBRARY, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ScenarioLookup.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ScenarioLookup.kt new file mode 100644 index 000000000..fae2d23c1 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/ScenarioLookup.kt @@ -0,0 +1,27 @@ +package org.pnfolder.pnlibrary.api.scenario.actions + +import org.pnfolder.pnlibrary.api.scenario.expression.ExpressionFunction +import org.pnfolder.pnlibrary.api.scenario.requirements.Requirement + +/** + * Finds the actions, requirements and functions that plugins defined by name, for `call`, `ref` and expressions. + * + * [ActionService] keeps the definitions of one module and passes them to every context it creates. + */ +interface ScenarioLookup { + /** The action defined under [name], or `null`. */ + fun action(name: String): Action? = null + + /** The requirement defined under [name], or `null`. */ + fun requirement(name: String): Requirement? = null + + /** The expression function defined under [name], or `null`. */ + fun function(name: String): ExpressionFunction? = null + + /** A lookup that knows nothing. */ + companion object { + /** Finds nothing. */ + @JvmField + val NONE: ScenarioLookup = object : ScenarioLookup {} + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/builtin/FlowActions.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/builtin/FlowActions.kt new file mode 100644 index 000000000..345e2d8fd --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/builtin/FlowActions.kt @@ -0,0 +1,289 @@ +package org.pnfolder.pnlibrary.api.scenario.actions.builtin + +import org.pnfolder.pnlibrary.api.config.ConfigKey +import org.pnfolder.pnlibrary.api.scenario.actions.Action +import org.pnfolder.pnlibrary.api.scenario.actions.ActionContext +import org.pnfolder.pnlibrary.api.scenario.actions.ActionResult +import org.pnfolder.pnlibrary.api.scenario.expression.Expression +import org.pnfolder.pnlibrary.api.scenario.requirements.Requirement +import org.pnfolder.pnlibrary.api.scenario.requirements.Verdict +import java.time.Duration +import java.util.concurrent.ThreadLocalRandom + +/** + * Runs [thenActions] when [requirement] is met, otherwise [elseActions]; the list goes on afterwards. + * A failure inside the chosen branch fails the whole scenario. + * + * ```yaml + * - type: if + * when: { type: expression, expression: "level() >= 10" } + * then: [ { type: message, messages: ['Veteran price'] } ] + * else: [ { type: message, messages: ['Normal price'] } ] + * ``` + * + * @property requirement the question; a missing one is never met + */ +data class IfAction( + @field:ConfigKey("when") + val requirement: Requirement? = null, + @field:ConfigKey("then") + val thenActions: List = emptyList(), + @field:ConfigKey("else") + val elseActions: List = emptyList(), +) : Action { + override fun run(context: ActionContext): ActionResult { + val met = requirement?.test(context)?.isMet ?: false + return context.runList(if (met) thenActions else elseActions) + } +} + +/** + * Ends the scenario quietly when [requirement] is not met, after running [deny]. + * + * Inside [deny] the reason is available as `[reason]`. + * + * ```yaml + * - type: require + * when: { type: permission, permission: shop.use } + * deny: [ { type: message, messages: ['&c[reason]'] } ] + * ``` + * + * @property requirement what must hold; a missing one is never met + * @property deny actions run when it does not + */ +data class RequireAction( + @field:ConfigKey("when") + val requirement: Requirement? = null, + val deny: List = emptyList(), +) : Action { + override fun run(context: ActionContext): ActionResult { + val verdict = requirement?.test(context) ?: Verdict.Unmet("no requirement is configured") + if (verdict !is Verdict.Unmet) return ActionResult.Done + context.setValue("reason", verdict.reason) + val denied = context.runList(deny) + return if (denied is ActionResult.Failed) denied else ActionResult.Stopped(verdict.reason) + } +} + +/** + * One reaction of an [AttemptAction] to a kind of failure. + * + * A code matches exactly (`currency.insufficient-funds`), as a family (`currency.*`), or everything (`*`). + * + * @property codes failure codes this handler takes; empty takes every failure + * @property steps actions run for it, written under `do` + */ +data class ErrorHandler( + val codes: List = emptyList(), + @field:ConfigKey("do") + val steps: List = emptyList(), +) { + /** Whether this handler takes a failure with [code]. */ + fun matches(code: String): Boolean = codes.isEmpty() || codes.any { pattern -> + pattern == "*" || pattern == code || (pattern.endsWith(".*") && code.startsWith(pattern.dropLast(1))) + } +} + +/** + * Runs [steps] as a unit that may fail. When a step fails, everything that unit did is undone (a charge is given + * back), then the first of [handlers] that takes the failure's code runs, or [fail] when none does. + * The scenario then ends, or goes on when [resume] is set. + * + * Inside a handler the cause is available as `[error]`, its code as `[error_code]`. + * + * ```yaml + * - type: attempt + * do: + * - { type: charge, currency: money, amount: 100 } + * - { type: command, command: 'give [player] diamond 1' } + * on: + * - codes: [currency.insufficient-funds] + * do: [ { type: message, messages: ['&cYou need 100 coins'] } ] + * - codes: ['currency.*'] + * do: [ { type: message, messages: ['&cThe bank is not answering, try later'] } ] + * fail: + * - { type: message, messages: ['&cCould not buy: [error]'] } + * ``` + * + * @property steps the actions that may fail + * @property handlers reactions by failure code, the first match wins + * @property fail actions run for a failure no handler takes + * @property resume whether the rest of the list runs after a handled failure + * @property undo whether the steps are undone on a failure; with `false` what they did stays, and an outer + * failure does not undo it either + */ +data class AttemptAction( + @field:ConfigKey("do") + val steps: List = emptyList(), + @field:ConfigKey("on") + val handlers: List = emptyList(), + val fail: List = emptyList(), + val resume: Boolean = false, + val undo: Boolean = true, +) : Action { + override fun run(context: ActionContext): ActionResult { + val mark = context.undoMark() + val result = context.runList(steps) + if (result !is ActionResult.Failed) return result + if (undo) context.rollbackTo(mark) else context.discardUndo(mark) + context.setValue("error", result.message).setValue("error_code", result.code) + val reaction = handlers.firstOrNull { it.matches(result.code) }?.steps ?: fail + val handled = context.runList(reaction) + return when { + handled is ActionResult.Failed -> handled + resume -> ActionResult.Done + else -> ActionResult.Stopped(result.message) + } + } +} + +/** + * Runs [steps] after [after] without waiting; the scenario goes on at once. + * + * The delayed part is its own scenario: a failure there is logged and undoes only its own steps. + * + * @property after the pause + * @property steps what runs afterwards + */ +data class DelayAction( + val after: Duration = Duration.ofSeconds(1), + @field:ConfigKey("then") + val steps: List = emptyList(), +) : Action { + init { require(!after.isNegative) { "Delay must not be negative" } } + + override fun run(context: ActionContext): ActionResult { + context.runLater(after, steps) + return ActionResult.Done + } +} + +/** + * Runs [steps] [times] times, [every] apart. The first run is immediate and part of the scenario; later runs + * are separate scenarios. + * + * @property times how many runs, from 1 to [MAX_TIMES] + * @property every pause between runs + * @property steps what runs each time + */ +data class RepeatAction( + val times: Int = 1, + val every: Duration = Duration.ZERO, + @field:ConfigKey("then") + val steps: List = emptyList(), +) : Action { + init { + require(times in 1..MAX_TIMES) { "Repeat times must be from 1 to $MAX_TIMES" } + require(!every.isNegative) { "Repeat interval must not be negative" } + } + + override fun run(context: ActionContext): ActionResult { + for (run in 1 until times) context.runLater(every.multipliedBy(run.toLong()), steps) + return context.runList(steps) + } + + /** Limits for repeat actions. */ + companion object { + /** The most runs one repeat may schedule. */ + const val MAX_TIMES = 1000 + } +} + +/** + * Ends the scenario here, quietly and without undoing anything. + * + * @property reason optional note for the result + */ +data class StopAction(val reason: String? = null) : Action { + override fun run(context: ActionContext): ActionResult = ActionResult.Stopped(reason) +} + +/** + * Stores a value for the steps after it, readable as `[name]`. Give either a [value] (text with placeholders) or + * an [expression] (a calculation, see [Expression]). + * + * ```yaml + * - { type: set, name: price, expression: "round(base * (1 - {shop:discount} / 100), 2)" } + * - { type: message, messages: ['Price: [price]'] } + * ``` + * + * @property name the value's name + * @property value text to store, with placeholders filled in + * @property expression calculation to store; wins over [value] + * @throws org.pnfolder.pnlibrary.api.scenario.expression.ExpressionException when [expression] cannot be parsed + */ +data class SetAction( + val name: String = "", + val value: String = "", + val expression: String? = null, +) : Action { + private val parsed = expression?.let(Expression::parse) + + override fun run(context: ActionContext): ActionResult { + if (name.isBlank()) return ActionResult.Failed("set.no-name", "A set action needs a name") + val result = parsed?.evaluate(context) ?: context.format(value) + context.setValue(name, result) + return ActionResult.Done + } +} + +/** + * Runs an action a plugin defined by name (see `ActionService.define`), giving it [args] as values for the call. + * The arguments are visible inside the call only. Calls may nest to [MAX_DEPTH] levels. + * + * ```yaml + * - { type: call, name: give-kit, args: { kit: starter, amount: '{= 2 * level()}' } } + * ``` + * + * @property name the defined name + * @property args values for the call; placeholders in them are filled in first + */ +data class CallAction( + val name: String = "", + val args: Map = emptyMap(), +) : Action { + override fun run(context: ActionContext): ActionResult { + val target = context.action(name) ?: return ActionResult.Failed("call.unknown", "Action '$name' is not defined") + val depth = (context.value(DEPTH) as? Number)?.toInt() ?: 0 + if (depth >= MAX_DEPTH) return ActionResult.Failed("call.too-deep", "Action '$name' is called too deeply; check for a loop") + val values = args.mapValues { context.format(it.value) } + (DEPTH to depth + 1) + return context.scoped(values) { target.run(context) } + } + + /** Limits for calls. */ + companion object { + /** The deepest chain of calls inside calls. */ + const val MAX_DEPTH = 16 + private const val DEPTH = "_call_depth" + } +} + +/** One choice of a [RandomAction]. */ +data class RandomOption( + val weight: Double = 1.0, + @field:ConfigKey("do") + val steps: List = emptyList(), +) { + init { require(weight > 0) { "A weight must be positive" } } +} + +/** + * Runs one of [options] chosen by chance; a bigger `weight` is chosen more often. + * + * ```yaml + * - type: random + * options: + * - { weight: 70, do: [ { type: message, messages: ['Common'] } ] } + * - { weight: 30, do: [ { type: message, messages: ['Rare'] } ] } + * ``` + * + * @property options the choices; with none, nothing happens + */ +data class RandomAction(val options: List = emptyList()) : Action { + override fun run(context: ActionContext): ActionResult { + if (options.isEmpty()) return ActionResult.Done + var roll = ThreadLocalRandom.current().nextDouble() * options.sumOf(RandomOption::weight) + val chosen = options.firstOrNull { roll -= it.weight; roll < 0 } ?: options.last() + return context.runList(chosen.steps) + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/builtin/OutputActions.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/builtin/OutputActions.kt new file mode 100644 index 000000000..efb1f2eda --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/actions/builtin/OutputActions.kt @@ -0,0 +1,215 @@ +package org.pnfolder.pnlibrary.api.scenario.actions.builtin + +import net.kyori.adventure.key.Key +import net.kyori.adventure.sound.Sound +import org.pnfolder.pnlibrary.api.audiences.Delivery +import org.pnfolder.pnlibrary.api.audiences.player.PlayerEffect +import org.pnfolder.pnlibrary.api.audiences.player.PlayerParticle +import org.pnfolder.pnlibrary.api.config.ConfigKey +import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.api.scenario.actions.Action +import org.pnfolder.pnlibrary.api.scenario.actions.ActionContext +import org.pnfolder.pnlibrary.api.scenario.actions.ActionResult +import org.pnfolder.pnlibrary.api.scenario.actions.ActionTarget +import org.pnfolder.pnlibrary.api.text.serializer.ComponentSerializerType +import java.time.Duration + +/** Writes a warning and carries on when the platform could not deliver; output never fails a scenario. */ +private fun ActionContext.warnUnless(delivery: Delivery, what: String): ActionResult { + if (!delivery.isDelivered) logger.warning("$what is not supported by the current platform") + return ActionResult.Done +} + +/** + * Sends chat text; the lines become one message, one under another. + * + * @property messages text lines; placeholders are filled in + * @property serializerType text format override, or `null` for the default + * @property target who receives it + */ +data class MessageAction( + val messages: List = emptyList(), + val serializerType: ComponentSerializerType? = null, + val target: ActionTarget = ActionTarget.PLAYER, +) : Action { + override fun run(context: ActionContext): ActionResult { + context.target(target).sendMessage(context.component(messages, serializerType)) + return ActionResult.Done + } +} + +/** + * Shows text above the hotbar. + * + * @property text the line; placeholders are filled in + * @property serializerType text format override, or `null` for the default + * @property target who sees it + */ +data class ActionBarAction( + val text: String = "", + val serializerType: ComponentSerializerType? = null, + val target: ActionTarget = ActionTarget.PLAYER, +) : Action { + override fun run(context: ActionContext): ActionResult { + context.target(target).actionBar(context.component(text, serializerType)) + return ActionResult.Done + } +} + +/** + * Shows a large title with a smaller subtitle. Proxies cannot show titles and write a warning instead. + * + * @property title main line + * @property subtitle second line + * @property fadeIn time to appear + * @property stay time fully visible + * @property fadeOut time to disappear + * @property serializerType text format override, or `null` for the default + * @property target who sees it + */ +data class TitleAction( + val title: String = "", + val subtitle: String = "", + val fadeIn: Duration = Duration.ofMillis(500), + val stay: Duration = Duration.ofMillis(3500), + val fadeOut: Duration = Duration.ofMillis(1000), + val serializerType: ComponentSerializerType? = null, + val target: ActionTarget = ActionTarget.PLAYER, +) : Action { + init { + require(!fadeIn.isNegative && !stay.isNegative && !fadeOut.isNegative) { "Title times must not be negative" } + } + + override fun run(context: ActionContext): ActionResult = context.warnUnless( + context.target(target).showTitle( + context.component(title, serializerType), + context.component(subtitle, serializerType), + fadeIn, stay, fadeOut, + ), + "Title", + ) +} + +/** + * Plays a sound. + * + * @property key namespaced sound key + * @property source volume category on the client + * @property volume relative volume + * @property pitch pitch multiplier + * @property target who hears it + */ +data class SoundAction( + val key: String = "minecraft:entity.experience_orb.pickup", + val source: Sound.Source = Sound.Source.MASTER, + val volume: Float = 1f, + val pitch: Float = 1f, + val target: ActionTarget = ActionTarget.PLAYER, +) : Action { + override fun run(context: ActionContext): ActionResult = + context.warnUnless(context.target(target).playSound(Sound.sound(Key.key(key), source, volume, pitch)), "Sound $key") +} + +/** Who runs the command of a [CommandAction]. */ +enum class CommandRunner { + /** The player the scenario is for. */ + PLAYER, + + /** The console, with every permission. */ + CONSOLE, +} + +/** + * Runs a server command. A command the platform refuses fails the scenario, because later steps usually + * depend on it. + * + * @property command command line without the leading slash; placeholders are filled in + * @property runner who runs it + */ +data class CommandAction( + val command: String = "", + @field:ConfigKey("as") + val runner: CommandRunner = CommandRunner.CONSOLE, +) : Action { + override fun run(context: ActionContext): ActionResult { + val line = context.format(command).trim().removePrefix("/") + if (line.isEmpty()) return ActionResult.Done + return if (context.player.runCommand(line, runner == CommandRunner.CONSOLE).isDelivered) { + ActionResult.Done + } else { + ActionResult.Failed("command.refused", "The platform did not accept the command '$line'") + } + } +} + +/** + * Writes a line to the plugin log. + * + * @property text the line; placeholders are filled in + * @property level severity + */ +data class LogAction( + val text: String = "", + val level: LogLevel = LogLevel.INFO, +) : Action { + override fun run(context: ActionContext): ActionResult { + val line = context.format(text) + when (level) { + LogLevel.DEBUG -> context.logger.debug(line) + LogLevel.INFO -> context.logger.info(line) + LogLevel.SUCCESS -> context.logger.success(line) + LogLevel.WARNING -> context.logger.warning(line) + LogLevel.ERROR -> context.logger.error(line) + LogLevel.CRITICAL -> context.logger.critical(line) + } + return ActionResult.Done + } +} + +/** + * Gives the player a temporary potion effect. + * + * @property key effect key + * @property duration how long it lasts + * @property amplifier zero-based level, `0` is level I + * @property ambient whether it counts as ambient + * @property particles whether its particles show + * @property icon whether its icon shows + */ +data class EffectAction( + val key: String = "speed", + val duration: Duration = Duration.ofSeconds(30), + val amplifier: Int = 0, + val ambient: Boolean = true, + val particles: Boolean = true, + val icon: Boolean = true, +) : Action { + override fun run(context: ActionContext): ActionResult = context.warnUnless( + context.player.applyEffect(PlayerEffect(key, duration, amplifier, ambient, particles, icon)), + "Effect $key", + ) +} + +/** + * Spawns particles around the player. + * + * @property key particle key + * @property count how many + * @property offsetX spread along X + * @property offsetY spread along Y + * @property offsetZ spread along Z + * @property speed speed or particle-specific data + */ +data class ParticleAction( + val key: String = "flame", + val count: Int = 1, + val offsetX: Double = 0.0, + val offsetY: Double = 0.0, + val offsetZ: Double = 0.0, + val speed: Double = 0.0, +) : Action { + override fun run(context: ActionContext): ActionResult = context.warnUnless( + context.player.spawnParticle(PlayerParticle(key, count, offsetX, offsetY, offsetZ, speed)), + "Particle $key", + ) +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/expression/Expression.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/expression/Expression.kt new file mode 100644 index 000000000..2c3be5836 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/expression/Expression.kt @@ -0,0 +1,139 @@ +package org.pnfolder.pnlibrary.api.scenario.expression + +import org.pnfolder.pnlibrary.api.audiences.player.ItemQuery +import org.pnfolder.pnlibrary.api.scenario.requirements.RequirementContext +import java.util.concurrent.ThreadLocalRandom + +/** + * A small, safe calculator for conditions and numbers in configuration. It cannot touch files or run code. + * + * ``` + * level >= 10 && (has_vip || chance(0.25)) + * clamp(balance / 100, 1, 10) * 5 + * contains(upper(rank), 'ADMIN') ? 1 : 0 + * ``` + * + * **Values.** A bare name reads a value of the run, then a pnLibrary placeholder. `{plugin:key}` reads a pnLibrary + * placeholder, `%name%` an external one, `[name]` a value of the run (use it for names with dashes). + * Text that looks like a number counts as a number. + * + * **Operators**, tightest first: `!` and unary `-`; `^` (power); `*` `/` `%`; `+` `-` (`+` joins text when a side is + * not a number); `<` `<=` `>` `>=`; `==` `!=`; `&&`; `||`; `condition ? a : b`. + * Numbers, `'text'`, `"text"`, `true`, `false`. + * + * **Functions:** `min`, `max`, `abs`, `round(x, digits)`, `floor`, `ceil`, `sqrt`, `pow`, `clamp(x, low, high)`, + * `random(low, high)`, `chance(p)`, `len`, `upper`, `lower`, `contains`, `startsWith`, `endsWith`, `has(name)`, + * `if(c, a, b)`, and about the player `permission(node)`, `level()`, `exp()`, `items(material)`, + * `distance(world, x, y, z)`. Plugins add more with `ActionService.defineFunction`. + * + * ```kotlin + * val expression = Expression.parse("level() >= 10 && permission('shop.use')") + * val allowed: Boolean = expression.test(context) + * ``` + */ +class Expression private constructor( + /** The text this expression was parsed from. */ + val source: String, + private val root: Node, +) { + internal fun interface Node { fun eval(context: RequirementContext): Any? } + + /** Computes the value: `Double`, `Boolean`, `String`, or `null` for an unknown name. */ + fun evaluate(context: RequirementContext): Any? = root.eval(context) + + /** Computes the value and reads it as a yes/no answer. */ + fun test(context: RequirementContext): Boolean = truthy(evaluate(context)) + + /** Computes the value as text, with whole numbers written without a decimal point. */ + fun text(context: RequirementContext): String = format(evaluate(context)) + + override fun toString(): String = source + + /** Parsing and shared value rules. */ + companion object { + /** Parses [text]; throws [ExpressionException] with the position of the mistake. */ + @JvmStatic + fun parse(text: String): Expression = Expression(text, Parser(text).parseAll()) + + /** Writes [value] as text: `5.0` becomes `5`, `null` becomes an empty text. */ + @JvmStatic + fun format(value: Any?): String = when (value) { + null -> "" + is Double -> if (value.isFinite() && value == Math.rint(value) && Math.abs(value) < 1e15) value.toLong().toString() else value.toString() + else -> value.toString() + } + + internal fun number(value: Any?): Double? = when (value) { + is Number -> value.toDouble() + is String -> value.trim().toDoubleOrNull() + is Boolean -> if (value) 1.0 else 0.0 + else -> null + } + + internal fun truthy(value: Any?): Boolean = when (value) { + null -> false + is Boolean -> value + is Number -> value.toDouble() != 0.0 + is String -> value.isNotBlank() && value.trim().lowercase() !in FALSE_WORDS + else -> true + } + + private val FALSE_WORDS = setOf("false", "0", "no", "off", "disabled") + + internal fun required(value: Any?): Double = + number(value) ?: throw ExpressionException("'${format(value)}' is not a number") + + internal fun normalize(value: Any?): Any? = when (value) { + is Number -> value.toDouble() + else -> value + } + + internal fun builtin(name: String): ExpressionFunction? = BUILTIN[name] + + /** Whether [name] is a function of the language itself, which plugins cannot redefine. */ + @JvmStatic + fun isBuiltin(name: String): Boolean = name in BUILTIN + + private val BUILTIN: Map = buildMap { + fun define(vararg names: String, function: ExpressionFunction) = names.forEach { put(it, function) } + fun ExpressionFunction.arity(count: IntRange, name: String) = ExpressionFunction { c, a -> + if (a.size !in count) throw ExpressionException("$name() takes ${count.first}..${count.last} arguments but got ${a.size}") + call(c, a) + } + define("min") { _, a -> a.minOfOrNull { required(it) } ?: throw ExpressionException("min() needs a value") } + define("max") { _, a -> a.maxOfOrNull { required(it) } ?: throw ExpressionException("max() needs a value") } + define("abs", function = ExpressionFunction { _, a -> Math.abs(required(a[0])) }.arity(1..1, "abs")) + define("floor", function = ExpressionFunction { _, a -> Math.floor(required(a[0])) }.arity(1..1, "floor")) + define("ceil", function = ExpressionFunction { _, a -> Math.ceil(required(a[0])) }.arity(1..1, "ceil")) + define("sqrt", function = ExpressionFunction { _, a -> Math.sqrt(required(a[0])) }.arity(1..1, "sqrt")) + define("pow", function = ExpressionFunction { _, a -> Math.pow(required(a[0]), required(a[1])) }.arity(2..2, "pow")) + define("round", function = ExpressionFunction { _, a -> + val scale = Math.pow(10.0, if (a.size > 1) required(a[1]) else 0.0) + Math.round(required(a[0]) * scale) / scale + }.arity(1..2, "round")) + define("clamp", function = ExpressionFunction { _, a -> required(a[0]).coerceIn(required(a[1]), required(a[2])) }.arity(3..3, "clamp")) + define("random", function = ExpressionFunction { _, a -> + val low = required(a[0]).toLong() + val high = required(a[1]).toLong() + if (high < low) throw ExpressionException("random() needs low <= high") + ThreadLocalRandom.current().nextLong(low, high + 1).toDouble() + }.arity(2..2, "random")) + define("chance", function = ExpressionFunction { _, a -> ThreadLocalRandom.current().nextDouble() < required(a[0]) }.arity(1..1, "chance")) + define("len", function = ExpressionFunction { _, a -> format(a[0]).length.toDouble() }.arity(1..1, "len")) + define("upper", function = ExpressionFunction { _, a -> format(a[0]).uppercase() }.arity(1..1, "upper")) + define("lower", function = ExpressionFunction { _, a -> format(a[0]).lowercase() }.arity(1..1, "lower")) + define("contains", function = ExpressionFunction { _, a -> format(a[0]).contains(format(a[1]), ignoreCase = true) }.arity(2..2, "contains")) + define("startsWith", function = ExpressionFunction { _, a -> format(a[0]).startsWith(format(a[1]), ignoreCase = true) }.arity(2..2, "startsWith")) + define("endsWith", function = ExpressionFunction { _, a -> format(a[0]).endsWith(format(a[1]), ignoreCase = true) }.arity(2..2, "endsWith")) + define("has", function = ExpressionFunction { c, a -> c.value(format(a[0])) != null }.arity(1..1, "has")) + define("if", function = ExpressionFunction { _, a -> if (truthy(a[0])) a[1] else a[2] }.arity(3..3, "if")) + define("permission", "perm", function = ExpressionFunction { c, a -> c.player.hasPermission(format(a[0])) }.arity(1..1, "permission")) + define("level", function = ExpressionFunction { c, _ -> c.player.experience(true) ?: 0.0 }) + define("exp", function = ExpressionFunction { c, _ -> c.player.experience(false) ?: 0.0 }) + define("items", function = ExpressionFunction { c, a -> (c.player.countItems(ItemQuery(format(a[0]))) ?: 0).toDouble() }.arity(1..1, "items")) + define("distance", function = ExpressionFunction { c, a -> + c.player.distanceTo(format(a[0]), required(a[1]), required(a[2]), required(a[3])) ?: Double.POSITIVE_INFINITY + }.arity(4..4, "distance")) + } + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/expression/ExpressionException.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/expression/ExpressionException.kt new file mode 100644 index 000000000..d2af44530 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/expression/ExpressionException.kt @@ -0,0 +1,4 @@ +package org.pnfolder.pnlibrary.api.scenario.expression + +/** A mistake in the text of an expression, or a value an expression cannot work with. */ +class ExpressionException(message: String) : IllegalArgumentException(message) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/expression/ExpressionFunction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/expression/ExpressionFunction.kt new file mode 100644 index 000000000..5bdabde49 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/expression/ExpressionFunction.kt @@ -0,0 +1,16 @@ +package org.pnfolder.pnlibrary.api.scenario.expression + +import org.pnfolder.pnlibrary.api.scenario.requirements.RequirementContext + +/** + * A function that expressions may call, such as `min(a, b)` or one a plugin adds with `ActionService.defineFunction`. + * + * ```kotlin + * module.actions.defineFunction("kills") { ctx, _ -> stats.kills(ctx.player.uniqueId) } + * // later, in a configuration: when: { type: expression, expression: 'kills() >= 100' } + * ``` + */ +fun interface ExpressionFunction { + /** Computes the result from [arguments]: numbers as `Double`, booleans, or text. */ + fun call(context: RequirementContext, arguments: List): Any? +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/expression/ExpressionParser.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/expression/ExpressionParser.kt new file mode 100644 index 000000000..e110ebcb4 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/expression/ExpressionParser.kt @@ -0,0 +1,243 @@ +package org.pnfolder.pnlibrary.api.scenario.expression + +import org.pnfolder.pnlibrary.api.scenario.expression.Expression.Companion.format +import org.pnfolder.pnlibrary.api.scenario.expression.Expression.Companion.normalize +import org.pnfolder.pnlibrary.api.scenario.expression.Expression.Companion.number +import org.pnfolder.pnlibrary.api.scenario.expression.Expression.Companion.required +import org.pnfolder.pnlibrary.api.scenario.expression.Expression.Companion.truthy + +/** Recursive-descent parser of [Expression]; every rule is one precedence level, loosest first. */ +internal class Parser(private val text: String) { + private var position = 0 + + fun parseAll(): Expression.Node { + if (text.isBlank()) throw ExpressionException("The expression is empty") + val node = ternary() + skipSpaces() + if (position < text.length) fail("Unexpected '${text[position]}'") + return node + } + + private fun fail(message: String): Nothing = throw ExpressionException("$message at position ${position + 1} of '$text'") + + private fun skipSpaces() { + while (position < text.length && text[position].isWhitespace()) position++ + } + + private fun accept(token: String): Boolean { + skipSpaces() + if (!text.startsWith(token, position)) return false + position += token.length + return true + } + + /** Accepts [token] only when no longer operator starts here, so `<` does not eat `<=`. */ + private fun acceptExact(token: String, vararg longer: String): Boolean { + skipSpaces() + if (longer.any { text.startsWith(it, position) }) return false + return accept(token) + } + + private fun ternary(): Expression.Node { + val condition = or() + if (!acceptExact("?")) return condition + val yes = ternary() + if (!accept(":")) fail("Expected ':' in a condition") + val no = ternary() + return Expression.Node { c -> if (truthy(condition.eval(c))) yes.eval(c) else no.eval(c) } + } + + private fun or(): Expression.Node { + var left = and() + while (accept("||")) { + val a = left + val b = and() + left = Expression.Node { c -> truthy(a.eval(c)) || truthy(b.eval(c)) } + } + return left + } + + private fun and(): Expression.Node { + var left = equality() + while (accept("&&")) { + val a = left + val b = equality() + left = Expression.Node { c -> truthy(a.eval(c)) && truthy(b.eval(c)) } + } + return left + } + + private fun equality(): Expression.Node { + var left = comparison() + while (true) { + val negate = when { + accept("==") -> false + accept("!=") -> true + else -> return left + } + val a = left + val b = comparison() + left = Expression.Node { c -> same(a.eval(c), b.eval(c)) != negate } + } + } + + private fun comparison(): Expression.Node { + var left = additive() + while (true) { + val op = listOf("<=", ">=", "<", ">").firstOrNull { if (it.length == 1) acceptExact(it, "<=", ">=") else accept(it) } ?: return left + val a = left + val b = additive() + left = Expression.Node { c -> + val x = a.eval(c) + val y = b.eval(c) + val order = compare(x, y) + when (op) { "<" -> order < 0; "<=" -> order <= 0; ">" -> order > 0; else -> order >= 0 } + } + } + } + + private fun additive(): Expression.Node { + var left = multiplicative() + while (true) { + val plus = when { + accept("+") -> true + acceptExact("-") -> false + else -> return left + } + val a = left + val b = multiplicative() + left = Expression.Node { c -> + val x = a.eval(c) + val y = b.eval(c) + when { + !plus -> required(x) - required(y) + number(x) == null || number(y) == null -> format(x) + format(y) + else -> required(x) + required(y) + } + } + } + } + + private fun multiplicative(): Expression.Node { + var left = power() + while (true) { + val op = listOf("*", "/", "%").firstOrNull { accept(it) } ?: return left + val a = left + val b = power() + left = Expression.Node { c -> + val x = required(a.eval(c)) + val y = required(b.eval(c)) + when (op) { + "*" -> x * y + "/" -> if (y == 0.0) throw ExpressionException("Division by zero") else x / y + else -> if (y == 0.0) throw ExpressionException("Division by zero") else x % y + } + } + } + } + + private fun power(): Expression.Node { + val base = unary() + if (!accept("^")) return base + val exponent = power() + return Expression.Node { c -> Math.pow(required(base.eval(c)), required(exponent.eval(c))) } + } + + private fun unary(): Expression.Node { + if (acceptExact("!", "!=")) { + val inner = unary() + return Expression.Node { c -> !truthy(inner.eval(c)) } + } + if (accept("-")) { + val inner = unary() + return Expression.Node { c -> -required(inner.eval(c)) } + } + return primary() + } + + private fun primary(): Expression.Node { + skipSpaces() + if (position >= text.length) fail("The expression ends too early") + val ch = text[position] + return when { + ch == '(' -> { + position++ + val inner = ternary() + if (!accept(")")) fail("Expected ')'") + inner + } + ch.isDigit() || (ch == '.' && text.getOrNull(position + 1)?.isDigit() == true) -> numberLiteral() + ch == '\'' || ch == '"' -> stringLiteral(ch) + ch == '{' -> bracketed('}') + ch == '%' -> bracketed('%') + ch.isLetter() || ch == '_' -> nameOrCall() + else -> fail("Unexpected '$ch'") + } + } + + private fun numberLiteral(): Expression.Node { + val start = position + while (position < text.length && (text[position].isDigit() || text[position] == '.')) position++ + val value = text.substring(start, position).toDoubleOrNull() ?: run { position = start; fail("Bad number") } + return Expression.Node { value } + } + + private fun stringLiteral(quote: Char): Expression.Node { + position++ + val start = position + while (position < text.length && text[position] != quote) position++ + if (position >= text.length) fail("A text is not closed") + val value = text.substring(start, position) + position++ + return Expression.Node { value } + } + + /** `{name}`, `{plugin:key}` or `%external%`: the whole token is read by the context, as in texts. */ + private fun bracketed(close: Char): Expression.Node { + val start = position + position++ + val end = text.indexOf(close, position) + if (end < 0) { position = start; fail("Expected '$close'") } + position = end + 1 + val token = text.substring(start, position) + return Expression.Node { c -> normalize(c.read(token)) } + } + + private fun nameOrCall(): Expression.Node { + val start = position + while (position < text.length && (text[position].isLetterOrDigit() || text[position] == '_' || text[position] == '.')) position++ + val name = text.substring(start, position) + skipSpaces() + if (position < text.length && text[position] == '(') { + position++ + val args = ArrayList() + if (!accept(")")) { + do args += ternary() while (accept(",")) + if (!accept(")")) fail("Expected ')' after the arguments of $name()") + } + return Expression.Node { c -> + val function = c.function(name) ?: Expression.builtin(name) ?: throw ExpressionException("Unknown function $name()") + normalize(function.call(c, args.map { normalize(it.eval(c)) })) + } + } + return when (name) { + "true" -> Expression.Node { true } + "false" -> Expression.Node { false } + "null" -> Expression.Node { null } + else -> Expression.Node { c -> normalize(c.read(name)) } + } + } + + private fun same(a: Any?, b: Any?): Boolean { + val x = number(a) + val y = number(b) + if (x != null && y != null && a !is Boolean && b !is Boolean) return x == y + return format(a) == format(b) + } + + private fun compare(a: Any?, b: Any?): Int { + val x = number(a) + val y = number(b) + return if (x != null && y != null) x.compareTo(y) else format(a).compareTo(format(b), ignoreCase = true) + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/requirements/Requirement.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/requirements/Requirement.kt new file mode 100644 index 000000000..147f4c124 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/requirements/Requirement.kt @@ -0,0 +1,65 @@ +package org.pnfolder.pnlibrary.api.scenario.requirements + +import org.pnfolder.pnlibrary.api.config.ConfigPolymorphic +import org.pnfolder.pnlibrary.api.config.ConfigType +import org.pnfolder.pnlibrary.api.config.ConfigTypes +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.AllRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.AnyRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.ChanceRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.CompareRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.ExperienceRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.ExpressionRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.ItemRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.NearRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.NotRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.PermissionRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.RefRequirement + +/** + * A condition that only looks: it answers [Verdict.Met] or [Verdict.Unmet] and changes nothing. + * + * A requirement is a configuration value with a `type`. Values it compares can come from anywhere + * [RequirementContext.text] reads: a literal, a context value `[name]`, a pnLibrary placeholder + * `{plugin:name}` or an external one `%name%`. + * + * ```yaml + * when: + * type: all + * requirements: + * - type: permission + * permission: shop.use + * - type: compare + * left: '%vault_eco_balance%' + * operator: greater-or-equal + * right: 100 + * ``` + * + * Money, items and other things that must be taken are not requirements: use an action that can fail, + * such as `charge`, so that the taking and the checking cannot disagree. + * + * Kotlin and Java code can implement the interface directly: + * + * ```kotlin + * val vip = Requirement { ctx -> Verdict.of(ctx.player.hasPermission("vip"), "VIP only") } + * ``` + * + * Implementations should be free of side effects, because one requirement may run many times. + */ +@ConfigPolymorphic(discriminator = "type") +@ConfigTypes( + ConfigType(PermissionRequirement::class, "permission", aliases = ["permissions"]), + ConfigType(CompareRequirement::class, "compare"), + ConfigType(ChanceRequirement::class, "chance"), + ConfigType(ItemRequirement::class, "item", aliases = ["items"]), + ConfigType(ExperienceRequirement::class, "experience", aliases = ["exp"]), + ConfigType(NearRequirement::class, "near"), + ConfigType(AllRequirement::class, "all", aliases = ["and"]), + ConfigType(AnyRequirement::class, "any", aliases = ["or"]), + ConfigType(NotRequirement::class, "not"), + ConfigType(ExpressionRequirement::class, "expression", aliases = ["expr", "calc"]), + ConfigType(RefRequirement::class, "ref", aliases = ["defined"]), +) +fun interface Requirement { + /** Judges [context]; an [Verdict.Unmet] carries the reason that can be shown to the player. */ + fun test(context: RequirementContext): Verdict +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext.kt new file mode 100644 index 000000000..e6556d62f --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext.kt @@ -0,0 +1,40 @@ +package org.pnfolder.pnlibrary.api.scenario.requirements + +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.logging.PnLogger +import org.pnfolder.pnlibrary.api.scenario.expression.ExpressionFunction + +/** + * What a [Requirement] may look at: the player, the values of the invocation, placeholders and services. + * + * [org.pnfolder.pnlibrary.api.scenario.actions.ActionContext] implements it, so the same requirement works inside + * an action list and on its own. + */ +interface RequirementContext { + /** The player being judged. */ + val player: LibraryPlayer + + /** Logger for requirements that cannot be evaluated. */ + val logger: PnLogger + + /** + * Reads [expression] as a value: one `[value]`, `{placeholder}` or `%external%`, text that contains them, + * or a bare name (a context value first, then a pnLibrary placeholder). Returns `null` when nothing matches. + */ + fun read(expression: String): Any? + + /** Returns [expression] with every placeholder and value replaced; unknown names stay as written. */ + fun text(expression: String): String + + /** Returns the context value called [name], or `null`. */ + fun value(name: String): Any? + + /** Returns the requirement a plugin defined under [name] with `ActionService.defineRequirement`, or `null`. */ + fun requirement(name: String): Requirement? = null + + /** Returns the expression function a plugin defined under [name] with `ActionService.defineFunction`, or `null`. */ + fun function(name: String): ExpressionFunction? = null + + /** Returns the service of [type] available to this invocation, such as the currency service, or `null`. */ + fun service(type: Class): T? +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/requirements/Verdict.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/requirements/Verdict.kt new file mode 100644 index 000000000..dea978611 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/requirements/Verdict.kt @@ -0,0 +1,29 @@ +package org.pnfolder.pnlibrary.api.scenario.requirements + +/** + * The answer of a [Requirement]: met, or not met with a reason. + * + * ```kotlin + * when (val verdict = requirement.test(context)) { + * Verdict.Met -> grant() + * is Verdict.Unmet -> player.sendMessage(Component.text(verdict.reason)) + * } + * ``` + */ +sealed interface Verdict { + /** Whether the requirement is satisfied. */ + val isMet: Boolean get() = this === Met + + /** The requirement is satisfied. */ + data object Met : Verdict + + /** The requirement is not satisfied; [reason] is short, readable text. */ + data class Unmet(val reason: String) : Verdict + + /** Helpers for building verdicts. */ + companion object { + /** [Met] when [condition] holds, otherwise [Unmet] with [reason]. */ + @JvmStatic + fun of(condition: Boolean, reason: String): Verdict = if (condition) Met else Unmet(reason) + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/requirements/builtin/Requirements.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/requirements/builtin/Requirements.kt new file mode 100644 index 000000000..a7da6e1eb --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/scenario/requirements/builtin/Requirements.kt @@ -0,0 +1,273 @@ +package org.pnfolder.pnlibrary.api.scenario.requirements.builtin + +import org.pnfolder.pnlibrary.api.audiences.player.ItemQuery +import org.pnfolder.pnlibrary.api.config.ConfigKey +import org.pnfolder.pnlibrary.api.scenario.expression.Expression +import org.pnfolder.pnlibrary.api.scenario.expression.ExpressionException +import org.pnfolder.pnlibrary.api.scenario.requirements.Requirement +import org.pnfolder.pnlibrary.api.scenario.requirements.RequirementContext +import org.pnfolder.pnlibrary.api.scenario.requirements.Verdict +import java.util.concurrent.ThreadLocalRandom + +/** + * Met when the player has the listed permissions: all of them, or any one with [any]. + * + * ```yaml + * type: permission + * permission: shop.use # or: permissions: [shop.use, shop.vip] + * ``` + * + * @property permission one permission node, may be blank when [permissions] is used + * @property permissions more permission nodes + * @property any whether one permission is enough instead of all of them + */ +data class PermissionRequirement( + val permission: String = "", + val permissions: List = emptyList(), + val any: Boolean = false, +) : Requirement { + override fun test(context: RequirementContext): Verdict { + val nodes = (listOf(permission) + permissions).filter(String::isNotBlank) + if (nodes.isEmpty()) { + context.logger.warning("A permission requirement lists no permission and is never met") + return Verdict.Unmet("no permission is configured") + } + val missing = nodes.filterNot(context.player::hasPermission) + val met = if (any) missing.size < nodes.size else missing.isEmpty() + return Verdict.of(met, "missing permission ${missing.joinToString()}") + } +} + +/** How [CompareRequirement] relates its two sides. */ +enum class CompareOperator(internal val numeric: Boolean) { + /** Equal; numbers are compared as numbers, anything else as text. */ + EQUALS(false), + /** Not equal. */ + NOT_EQUALS(false), + /** Left is greater than right; both must be numbers. */ + GREATER(true), + /** Left is greater than or equal to right; both must be numbers. */ + GREATER_OR_EQUAL(true), + /** Left is less than right; both must be numbers. */ + LESS(true), + /** Left is less than or equal to right; both must be numbers. */ + LESS_OR_EQUAL(true), + /** Left text contains right text. */ + CONTAINS(false), + /** Left text starts with right text. */ + STARTS_WITH(false), + /** Left text ends with right text. */ + ENDS_WITH(false), + /** Left text matches the regular expression on the right as a whole. */ + MATCHES(false), +} + +/** + * Compares two values. Each side is text with placeholders, so it can be a literal, a context value, + * a pnLibrary placeholder or an external one. + * + * ```yaml + * type: compare + * left: '%vault_eco_balance%' + * operator: greater-or-equal + * right: 100 + * ``` + * + * @property left first side + * @property operator relation between the sides + * @property right second side + * @property ignoreCase whether text is compared without case sensitivity + */ +data class CompareRequirement( + val left: String = "", + val operator: CompareOperator = CompareOperator.EQUALS, + val right: String = "", + val ignoreCase: Boolean = true, +) : Requirement { + override fun test(context: RequirementContext): Verdict { + val a = context.text(left).trim() + val b = context.text(right).trim() + val x = a.toBigDecimalOrNull() + val y = b.toBigDecimalOrNull() + if (operator.numeric && (x == null || y == null)) { + return Verdict.Unmet("'${if (x == null) a else b}' is not a number") + } + val met = when (operator) { + CompareOperator.EQUALS -> if (x != null && y != null) x.compareTo(y) == 0 else a.equals(b, ignoreCase) + CompareOperator.NOT_EQUALS -> if (x != null && y != null) x.compareTo(y) != 0 else !a.equals(b, ignoreCase) + CompareOperator.GREATER -> x!! > y!! + CompareOperator.GREATER_OR_EQUAL -> x!! >= y!! + CompareOperator.LESS -> x!! < y!! + CompareOperator.LESS_OR_EQUAL -> x!! <= y!! + CompareOperator.CONTAINS -> a.contains(b, ignoreCase) + CompareOperator.STARTS_WITH -> a.startsWith(b, ignoreCase) + CompareOperator.ENDS_WITH -> a.endsWith(b, ignoreCase) + CompareOperator.MATCHES -> matches(a, b, context) + } + return Verdict.of(met, "$a is not ${operator.name.lowercase().replace('_', ' ')} $b") + } + + private fun matches(text: String, pattern: String, context: RequirementContext): Boolean = try { + Regex(pattern, if (ignoreCase) setOf(RegexOption.IGNORE_CASE) else emptySet()).matches(text) + } catch (error: IllegalArgumentException) { + context.logger.warning("Invalid regular expression '$pattern': ${error.message}") + false + } +} + +/** + * Met by chance. + * + * @property probability from `0.0` (never) to `1.0` (always) + * @throws IllegalArgumentException when [probability] is outside that range + */ +data class ChanceRequirement(val probability: Double = 0.5) : Requirement { + init { require(probability in 0.0..1.0) { "Chance must be from 0.0 to 1.0" } } + + override fun test(context: RequirementContext): Verdict = + Verdict.of(ThreadLocalRandom.current().nextDouble() < probability, "bad luck") +} + +/** + * Met when the player carries at least [amount] items that fit the description. + * + * A platform without player inventories never meets it. + * + * @property material platform item name such as `diamond` + * @property amount required count, at least one + * @property name full display name the item must have, or `null` + * @property nameContains text the display name must contain, or `null` + * @property loreContains text a lore line must contain, or `null` + * @property ignoreCase whether text is compared without case sensitivity + */ +data class ItemRequirement( + val material: String = "", + val amount: Int = 1, + val name: String? = null, + @field:ConfigKey("name-contains") + val nameContains: String? = null, + @field:ConfigKey("lore-contains") + val loreContains: String? = null, + val ignoreCase: Boolean = true, +) : Requirement { + init { require(amount >= 1) { "Required item amount must be at least 1" } } + + override fun test(context: RequirementContext): Verdict { + if (material.isBlank()) return Verdict.Unmet("no item is configured") + val have = context.player.countItems(ItemQuery(material, name, nameContains, loreContains, ignoreCase)) ?: 0 + return Verdict.of(have >= amount, "need $amount $material, have $have") + } +} + +/** + * Met when the player has at least [amount] experience points, or levels with [level]. + * + * @property amount required experience, not negative + * @property level whether [amount] counts levels instead of points + */ +data class ExperienceRequirement(val amount: Int = 0, val level: Boolean = false) : Requirement { + init { require(amount >= 0) { "Required experience must not be negative" } } + + override fun test(context: RequirementContext): Verdict { + val have = context.player.experience(level) ?: return Verdict.Unmet("experience is not available here") + return Verdict.of(have >= amount, "need $amount ${if (level) "levels" else "experience"}") + } +} + +/** + * Met when the player is within [distance] blocks of [location]. + * + * @property location point written as `world,x,y,z` + * @property distance largest allowed distance in blocks, not negative + * @throws IllegalArgumentException when [location] is not `world,x,y,z` or [distance] is negative + */ +data class NearRequirement(val location: String = "world,0,0,0", val distance: Double = 5.0) : Requirement { + private val world: String + private val x: Double + private val y: Double + private val z: Double + + init { + require(distance >= 0) { "Distance must not be negative" } + val parts = location.split(',').map(String::trim) + val numbers = parts.drop(1).map(String::toDoubleOrNull) + require(parts.size == 4 && parts[0].isNotEmpty() && numbers.none { it == null }) { + "Location must be written as world,x,y,z but was '$location'" + } + world = parts[0] + x = numbers[0] ?: 0.0 + y = numbers[1] ?: 0.0 + z = numbers[2] ?: 0.0 + } + + override fun test(context: RequirementContext): Verdict { + val current = context.player.distanceTo(world, x, y, z) ?: return Verdict.Unmet("distance is not available here") + return Verdict.of(current <= distance, "too far from $location") + } +} + +/** Met when every requirement of [requirements] is met; the first one that is not decides the reason. */ +data class AllRequirement(val requirements: List = emptyList()) : Requirement { + override fun test(context: RequirementContext): Verdict = + requirements.firstNotNullOfOrNull { it.test(context) as? Verdict.Unmet } ?: Verdict.Met +} + +/** Met when at least one requirement of [requirements] is met; an empty list is never met. */ +data class AnyRequirement(val requirements: List = emptyList()) : Requirement { + override fun test(context: RequirementContext): Verdict { + val reasons = ArrayList() + for (requirement in requirements) { + when (val verdict = requirement.test(context)) { + Verdict.Met -> return verdict + is Verdict.Unmet -> reasons += verdict.reason + } + } + return Verdict.Unmet(reasons.joinToString(" / ").ifEmpty { "nothing to choose from" }) + } +} + +/** Met when [requirement] is not. */ +data class NotRequirement(val requirement: Requirement? = null) : Requirement { + override fun test(context: RequirementContext): Verdict { + val inner = requirement ?: return Verdict.Unmet("nothing to negate") + return if (inner.test(context).isMet) Verdict.Unmet("not allowed") else Verdict.Met + } +} + +/** + * Met when a calculation comes out true. This is the way to write anything the other types cannot: maths, the + * player's level, placeholders, and any mix of them. See [Expression] for the whole language. + * + * ```yaml + * type: expression + * expression: "level() >= 10 && (permission('shop.vip') || {shop:discount} > 20)" + * ``` + * + * A mistake in the text is reported when the configuration loads. A calculation that fails at run time + * (for example a text where a number is needed) is not met, and the reason says why. + * + * @property expression the calculation + * @throws org.pnfolder.pnlibrary.api.scenario.expression.ExpressionException when the text cannot be parsed + */ +data class ExpressionRequirement(val expression: String = "true") : Requirement { + private val parsed = Expression.parse(expression) + + override fun test(context: RequirementContext): Verdict = try { + Verdict.of(parsed.test(context), "'$expression' is false") + } catch (error: ExpressionException) { + context.logger.warning("Expression '$expression' failed: ${error.message}") + Verdict.Unmet("'$expression' could not be calculated: ${error.message}") + } +} + +/** + * Met when the requirement a plugin defined under [name] (see `ActionService.defineRequirement`) is met. + * + * @property name name given when the requirement was defined + */ +data class RefRequirement(val name: String = "") : Requirement { + override fun test(context: RequirementContext): Verdict { + val target = context.requirement(name) ?: return Verdict.Unmet("requirement '$name' is not defined") + return target.test(context) + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskHandle.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskHandle.kt new file mode 100644 index 000000000..ec25abf10 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskHandle.kt @@ -0,0 +1,36 @@ +package org.pnfolder.pnlibrary.api.tasks + +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus + +/** + * Cancellation handle for one scheduled action. + * + * Cancellation is idempotent. It prevents a pending invocation from starting, but does not + * interrupt an invocation that is already running. Closing the handle is equivalent to [cancel]. + */ +interface TaskHandle : AutoCloseable { + /** Stable identifier of the associated task. */ + val id: TaskId + /** Current task lifecycle state. */ + val status: TaskStatus + /** Whether this handle has been cancelled. */ + val isCancelled: Boolean + + /** Cancels future execution of the associated action. */ + fun cancel() + + /** Cancels this task when active and reports whether cancellation was requested. */ + fun cancelIfActive(): Boolean { + if (isCancelled) return false + cancel() + return true + } + + /** Returns a detached snapshot of this task's current state. */ + fun snapshot(): TaskSnapshot + + /** Cancels future execution of the associated action. */ + override fun close() = cancel() +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskScope.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskScope.kt index 0d321bcd6..95de2c95e 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskScope.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskScope.kt @@ -1,35 +1,10 @@ package org.pnfolder.pnlibrary.api.tasks -/** - * Cancellation handle for one scheduled action. - * - * Cancellation is idempotent. It prevents a pending invocation from starting, but does not - * interrupt an invocation that is already running. Closing the handle is equivalent to [cancel]. - */ -interface TaskHandle : AutoCloseable { - /** Stable identifier of the associated task. */ - val id: TaskId - /** Current task lifecycle state. */ - val status: TaskStatus - /** Whether this handle has been cancelled. */ - val isCancelled: Boolean - - /** Cancels future execution of the associated action. */ - fun cancel() - - /** Cancels this task when active and reports whether cancellation was requested. */ - fun cancelIfActive(): Boolean { - if (isCancelled) return false - cancel() - return true - } - - /** Returns a detached snapshot of this task's current state. */ - fun snapshot(): TaskSnapshot - - /** Cancels future execution of the associated action. */ - override fun close() = cancel() -} +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskQuery +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.spec.ScheduledTask +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec /** * Owner-bound group of tasks that are cancelled together. @@ -55,6 +30,9 @@ interface TaskScope : AutoCloseable { /** Schedules [spec] inside this owner-bound scope. */ fun schedule(spec: TaskSpec): TaskHandle + /** Schedules a task written as a class; see [ScheduledTask]. */ + fun schedule(task: ScheduledTask): TaskHandle = schedule(task.toSpec()) + /** Returns the task identified by [id], or `null` when it is unavailable. */ fun get(id: TaskId): TaskHandle? diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskId.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskId.kt new file mode 100644 index 000000000..5b37cbed1 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskId.kt @@ -0,0 +1,21 @@ +package org.pnfolder.pnlibrary.api.tasks.info + +import java.util.UUID + +/** Stable non-blank identifier assigned to one scheduled task. */ +data class TaskId( + /** Non-blank identifier value. */ + val value: String, +) { + init { + require(value.isNotBlank()) { "Task id must not be blank" } + } + + override fun toString(): String = value + + companion object { + /** Returns a new UUID-backed task identifier. */ + @JvmStatic + fun random(): TaskId = TaskId(UUID.randomUUID().toString()) + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskLag.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskLag.kt new file mode 100644 index 000000000..b75cd17cb --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskLag.kt @@ -0,0 +1,39 @@ +package org.pnfolder.pnlibrary.api.tasks.info + +import java.time.Duration +import java.time.Instant + +/** + * How late one run of a task started, such as after the server froze. + * + * @property taskId the task that is late + * @property taskName its name, when it has one + * @property runNumber the one-based number of the run that is about to start + * @property planned when the run should have started + * @property started when it actually starts + * @property interval the repeat interval of the task, or `null` for a one-shot task + */ +data class TaskLag( + val taskId: TaskId, + val taskName: String?, + val runNumber: Long, + val planned: Instant, + val started: Instant, + val interval: Duration?, +) { + /** How late the run is; never negative. */ + val lag: Duration get() = Duration.between(planned, started).takeUnless(Duration::isNegative) ?: Duration.ZERO + + /** How many whole runs of a repeating task fitted into the delay and were lost; `0` for a one-shot task. */ + val missedRuns: Long + get() = interval?.takeUnless { it.isZero }?.let { lag.toMillis() / it.toMillis() } ?: 0L + + /** Whether the run is late by more than [threshold]. */ + fun isOver(threshold: Duration): Boolean = lag > threshold + + /** A short description for logs and messages, such as `Autosave started 20s late (about 20 runs missed)`. */ + override fun toString(): String = buildString { + append(taskName ?: taskId.toString()).append(" started ").append(lag.seconds).append("s late") + if (missedRuns > 0) append(" (about ").append(missedRuns).append(" runs missed)") + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskQuery.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskQuery.kt similarity index 55% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskQuery.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskQuery.kt index ea7b988b0..3f82bf638 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskQuery.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskQuery.kt @@ -1,7 +1,6 @@ -package org.pnfolder.pnlibrary.api.tasks +package org.pnfolder.pnlibrary.api.tasks.info -import java.time.Duration -import java.time.Instant +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import java.util.Collections /** @@ -22,6 +21,15 @@ class TaskQuery private constructor( val executionKinds: Set, val tags: Set, ) { + /** Returns whether [snapshot] satisfies every populated criterion of this query. */ + fun matches(snapshot: TaskSnapshot): Boolean = + (id == null || snapshot.id == id) && + (key == null || snapshot.key == key) && + (nameContains == null || snapshot.name?.contains(nameContains, ignoreCase = true) == true) && + (statuses.isEmpty() || snapshot.status in statuses) && + (executionKinds.isEmpty() || snapshot.executionKind in executionKinds) && + snapshot.tags.containsAll(tags) + /** Fluent builder for a validated [TaskQuery]. */ class Builder internal constructor() { private var id: TaskId? = null @@ -40,8 +48,10 @@ class TaskQuery private constructor( /** Matches task names containing [value]. */ fun nameContains(value: String): Builder = apply { nameContains = value } + /** Accepts only tasks in one of the given lifecycle states. */ fun status(vararg value: TaskStatus): Builder = apply { statuses += value } + /** Accepts only tasks with one of the given execution kinds. */ fun execution(vararg value: TaskExecution.Kind): Builder = apply { executionKinds += value } /** Requires matching tasks to contain [value]. */ @@ -65,6 +75,7 @@ class TaskQuery private constructor( } } companion object { + /** Starts a new query builder. */ @JvmStatic fun builder(): Builder = Builder() @@ -73,54 +84,3 @@ class TaskQuery private constructor( fun all(): TaskQuery = Builder().build() } } - -/** - * Immutable detached view of a live or retained task. - * - * @property id stable task identifier - * @property name optional human-readable task name - * @property key optional conflict-resolution key - * @property ownerName diagnostic name of the owning object - * @property executionKind selected execution context - * @property status current or terminal lifecycle state - * @property tags immutable application-defined tags - * @property createdAt time at which the task was registered - * @property nextRunAt next planned invocation, or `null` when none remains - * @property runCount number of invocations that started - * @property skippedCount number of invocations skipped because a condition rejected them - * @property lastStartedAt most recent invocation start time - * @property lastCompletedAt most recent successful completion time - * @property lastFailure rendered most recent failure, when one occurred - * @property description optional sentence on what the task is for - * @property usage optional note on how the task is used - * @property source class of the task action, as far as it can be told - * @property interval repeat interval, or `null` for a one-shot task - * @property lastDuration how long the latest finished invocation took - * @property cancellable whether an administrator may stop the task from the commands and the menu - * @property runnableNow whether an administrator may start the task at once from the commands and the menu - * @property hidden whether the task asked to be left out of the commands and the menu - */ -data class TaskSnapshot( - val id: TaskId, - val name: String?, - val key: String?, - val ownerName: String, - val executionKind: TaskExecution.Kind, - val status: TaskStatus, - val tags: Set, - val createdAt: Instant, - val nextRunAt: Instant?, - val runCount: Long, - val skippedCount: Long, - val lastStartedAt: Instant?, - val lastCompletedAt: Instant?, - val lastFailure: String?, - val description: String? = null, - val usage: String? = null, - val source: String? = null, - val interval: Duration? = null, - val lastDuration: Duration? = null, - val cancellable: Boolean = true, - val runnableNow: Boolean = true, - val hidden: Boolean = false, -) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskSnapshot.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskSnapshot.kt new file mode 100644 index 000000000..07f1869c6 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskSnapshot.kt @@ -0,0 +1,67 @@ +package org.pnfolder.pnlibrary.api.tasks.info + +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import java.time.Duration +import java.time.Instant + +/** + * Immutable detached view of a live or retained task. + * + * @property id stable task identifier + * @property name optional human-readable task name + * @property key optional conflict-resolution key + * @property ownerName diagnostic name of the owning object + * @property executionKind selected execution context + * @property status current or terminal lifecycle state + * @property tags immutable application-defined tags + * @property createdAt time at which the task was registered + * @property nextRunAt next planned invocation, or `null` when none remains + * @property runCount number of invocations that started + * @property skippedCount number of invocations skipped because a condition rejected them + * @property lastStartedAt most recent invocation start time + * @property lastCompletedAt most recent successful completion time + * @property lastFailure rendered most recent failure, when one occurred + * @property description optional sentence on what the task is for + * @property usage optional note on how the task is used + * @property source class of the task action, as far as it can be told + * @property interval repeat interval, or `null` for a one-shot task + * @property lastDuration how long the latest finished invocation took + * @property cancellable whether an administrator may stop the task from the commands and the menu + * @property runnableNow whether an administrator may start the task at once from the commands and the menu + * @property hidden whether the task asked to be left out of the commands and the menu + * @property failedCount number of invocations that threw an error, including ones a task survived + * @property parentId the task that started this one, or `null` for a task scheduled directly + * @property lastLag how late the latest run started compared with its plan + * @property worstLag the largest delay of any run so far, such as from a server freeze + */ +data class TaskSnapshot( + val id: TaskId, + val name: String?, + val key: String?, + val ownerName: String, + val executionKind: TaskExecution.Kind, + val status: TaskStatus, + val tags: Set, + val createdAt: Instant, + val nextRunAt: Instant?, + val runCount: Long, + val skippedCount: Long, + val lastStartedAt: Instant?, + val lastCompletedAt: Instant?, + val lastFailure: String?, + val description: String? = null, + val usage: String? = null, + val source: String? = null, + val interval: Duration? = null, + val lastDuration: Duration? = null, + val cancellable: Boolean = true, + val runnableNow: Boolean = true, + val failedCount: Long = 0, + val parentId: TaskId? = null, + val lastLag: Duration? = null, + val worstLag: Duration? = null, + val hidden: Boolean = false, +) { + /** Whether the task can still run, that is, it has not reached a terminal [status]. */ + val isActive: Boolean get() = !status.isTerminal +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskStatus.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskStatus.kt new file mode 100644 index 000000000..05ec6ba47 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/info/TaskStatus.kt @@ -0,0 +1,23 @@ +package org.pnfolder.pnlibrary.api.tasks.info + +/** Current lifecycle state of a scheduled task. */ +enum class TaskStatus { + /** Waiting for its first or next invocation. */ + SCHEDULED, + + /** An invocation is running now. */ + RUNNING, + + /** A one-shot task ran to its end. */ + COMPLETED, + + /** The owner or an administrator stopped the task. */ + CANCELLED, + + /** The task stopped because an invocation failed. */ + FAILED, + ; + + /** Whether the task can no longer run: [COMPLETED], [CANCELLED] or [FAILED]. */ + val isTerminal: Boolean get() = this == COMPLETED || this == CANCELLED || this == FAILED +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/run/LagResponse.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/run/LagResponse.kt new file mode 100644 index 000000000..9e88cfc26 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/run/LagResponse.kt @@ -0,0 +1,13 @@ +package org.pnfolder.pnlibrary.api.tasks.run + +/** What to do with a run that started late. */ +enum class LagResponse { + /** Run it anyway, late. */ + RUN, + + /** Skip this run; a repeating task goes on with the next one. */ + SKIP, + + /** Skip this run and cancel the task for good: it is not worth running after such a delay. */ + CANCEL, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/run/TaskContext.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/run/TaskContext.kt new file mode 100644 index 000000000..8c39e5deb --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/run/TaskContext.kt @@ -0,0 +1,172 @@ +package org.pnfolder.pnlibrary.api.tasks.run + +import org.pnfolder.pnlibrary.api.tasks.TaskHandle +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.spec.ScheduledTask +import org.pnfolder.pnlibrary.api.tasks.spec.TaskAction +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec +import java.time.Duration +import java.time.Instant + +/** + * What a running task knows about itself: who it is, which run this is, and how to stop. + * + * It is handed to [TaskAction.run] for each invocation and is valid only during that invocation. + * + * ```kotlin + * override fun run(context: TaskContext) { + * if (context.isFirstRun) warmUp() + * if (context.every(10)) saveToDatabase() + * if (context.lag > Duration.ofSeconds(2)) log("Late by ${context.lag}") + * context.cancelAfter(100) + * } + * ``` + */ +interface TaskContext { + /** Stable identifier of the running task. */ + val id: TaskId + + /** Optional human-readable task name. */ + val name: String? + + /** Conflict-resolution key of the task, or `null` when it has none. */ + val key: String? + + /** Lookup tags of the task. */ + val tags: Set + + /** Platform execution context the invocation runs in. */ + val executionKind: TaskExecution.Kind + + /** Platform execution context of this task, handed on to follow-up work started with [later]. */ + val execution: TaskExecution + + /** Repeat interval, or `null` for a one-shot task. */ + val interval: Duration? + + /** One-based invocation number. */ + val runNumber: Long + + /** How many invocations were skipped so far because a condition rejected them or the previous run was still going. */ + val skippedCount: Long + + /** Time at which this invocation was intended to start. */ + val scheduledAt: Instant + + /** Time at which this invocation actually started. */ + val startedAt: Instant + + /** Start time of the previous invocation, or `null` on the first run. */ + val previousStartedAt: Instant? + + /** Whether the task has been cancelled, for example by an administrator while this run is going. */ + val isCancelled: Boolean + + /** The task that started this one with [spawn] or [later], or `null` for a task scheduled directly. */ + val parentId: TaskId? + + /** Cancels all future invocations of this task. */ + fun cancel() + + /** Returns a detached view of the whole task as it is right now. */ + fun snapshot(): TaskSnapshot + + /** + * Schedules [spec] as a separate task in the same scope as this one, so it shares the owner and is cancelled + * together with the scope. The new task is independent: cancelling this one does not stop it. + * + * @throws IllegalStateException when the scope is already closed + */ + fun spawn(spec: TaskSpec): TaskHandle + + /** Schedules a task written as a class as a separate task in the same scope; see [spawn]. */ + fun spawn(task: ScheduledTask): TaskHandle = spawn(task.toSpec()) + + /** + * Runs [action] once after [delay] in this task's execution context, without building a [TaskSpec]. + * + * ```kotlin + * context.later(Duration.ofSeconds(5)) { player.sendMessage("Five seconds later") } + * ``` + * + * The follow-up is a task of its own, named after this one with the tag `subtask`. + */ + fun later(delay: Duration, action: TaskAction): TaskHandle = later(delay, execution, action) + + /** Like [later], but in the given [execution] context, such as `TaskExecution.async()`. */ + fun later(delay: Duration, execution: TaskExecution, action: TaskAction): TaskHandle = spawn( + TaskSpec.builder() + .name("${name ?: id} / later") + .tag(SUBTASK_TAG) + .execution(execution) + .delay(delay) + .action(action) + .build(), + ) + + /** Whether this is the first invocation. */ + val isFirstRun: Boolean get() = runNumber == 1L + + /** Whether the task repeats, that is, has an [interval]. */ + val isRepeating: Boolean get() = interval != null + + /** How late this invocation started compared with its plan; never negative. A big value means the server is overloaded. */ + val lag: Duration get() = Duration.between(scheduledAt, startedAt).takeUnless(Duration::isNegative) ?: Duration.ZERO + + /** How many whole runs of a repeating task were lost to the delay, such as after a server freeze; `0` for a one-shot task. */ + val missedRuns: Long + get() = interval?.takeUnless { it.isZero }?.let { lag.toMillis() / it.toMillis() } ?: 0L + + /** Whether this invocation started more than [threshold] after its plan. */ + fun isLate(threshold: Duration): Boolean = lag > threshold + + /** How long this invocation has been running. */ + val elapsed: Duration get() = Duration.between(startedAt, Instant.now()) + + /** Whether this run is every [step]-th one: true on runs [step], 2 × [step] and so on. */ + fun every(step: Long): Boolean { + require(step > 0) { "Step must be positive" } + return runNumber % step == 0L + } + + /** Cancels the task when this run is the [limit]-th or later; returns whether it did. */ + fun cancelAfter(limit: Long): Boolean { + if (runNumber < limit) return false + cancel() + return true + } + + /** + * Runs [action] [times] times, [every] apart, as a task of its own under this one; the first run is after one + * [every]. It is cancelled together with this task, and stops by itself after the last run. + * + * ```kotlin + * context.repeat(5, Duration.ofSeconds(1)) { c -> broadcast("${5 - c.runNumber}") } + * ``` + */ + fun repeat(times: Long, every: Duration, action: TaskAction): TaskHandle { + require(times > 0) { "Times must be positive" } + return spawn( + TaskSpec.builder() + .name("${name ?: id} / repeat") + .tag(SUBTASK_TAG) + .execution(execution) + .delay(every) + .interval(every) + .cancelWithParent(true) + .action { child -> + action.run(child) + child.cancelAfter(times) + } + .build(), + ) + } + + /** Constants of task contexts. */ + companion object { + /** Tag put on every task started with [later]. */ + const val SUBTASK_TAG: String = "subtask" + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/run/TaskLagHandler.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/run/TaskLagHandler.kt new file mode 100644 index 000000000..1ee1ad64b --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/run/TaskLagHandler.kt @@ -0,0 +1,22 @@ +package org.pnfolder.pnlibrary.api.tasks.run + +import org.pnfolder.pnlibrary.api.tasks.info.TaskLag + +/** + * Reacts when a run starts later than the task's lag threshold, for example because the server froze. + * + * Use it to tell an administrator, to log, or to decide that a stale run is not worth doing: + * + * ```kotlin + * .onLag(Duration.ofSeconds(5)) { lag -> + * log("$lag") + * if (lag.missedRuns > 10) LagResponse.SKIP else LagResponse.RUN + * } + * ``` + * + * It runs on the task's own thread right before the run. An exception it throws is logged and the run goes on. + */ +fun interface TaskLagHandler { + /** Decides what happens to the late run described by [lag]. */ + fun handle(lag: TaskLag): LagResponse +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/ScheduledTask.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/ScheduledTask.kt new file mode 100644 index 000000000..f1508f3e1 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/ScheduledTask.kt @@ -0,0 +1,109 @@ +package org.pnfolder.pnlibrary.api.tasks.spec + +import org.pnfolder.pnlibrary.api.tasks.info.TaskLag +import org.pnfolder.pnlibrary.api.tasks.run.LagResponse +import java.time.Duration + +/** + * A task written as a class: the settings are overridable properties, the arguments are constructor parameters. + * + * It is the second way to describe a task next to [TaskSpec]: instead of a builder the task is its own type, so it + * can hold its arguments, be tested alone and be scheduled anywhere with `scope.schedule(MyTask(...))`. + * Every setting has the same meaning as the same-named field of [TaskSpec]. + * + * ```kotlin + * class Autosave(private val world: String) : ScheduledTask() { + * override val name = "Autosave $world" + * override val interval: Duration = Duration.ofMinutes(5) + * override val execution = TaskExecution.async() + * + * override fun run(context: TaskContext) = save(world) + * } + * + * tasks.schedule(Autosave("world")) + * ``` + */ +abstract class ScheduledTask : TaskAction { + /** Human-readable task name. */ + open val name: String? get() = null + + /** What the task is for, shown by `/pn tasks`. */ + open val description: String? get() = null + + /** How the task is used or what it changes. */ + open val usage: String? get() = null + + /** Conflict-resolution key within the owner scope. */ + open val key: String? get() = null + + /** Behavior when [key] is already registered. */ + open val conflictPolicy: TaskConflictPolicy get() = TaskConflictPolicy.REJECT + + /** Platform execution context. */ + open val execution: TaskExecution get() = TaskExecution.global() + + /** Delay before the first invocation. */ + open val delay: Duration get() = Duration.ZERO + + /** Repeat interval, or `null` for a one-shot task. */ + open val interval: Duration? get() = null + + /** Longest a run may start late (for example after the server froze) before it is skipped; `null` never skips. */ + open val maxLag: Duration? get() = null + + /** Failures in a row a repeating task survives before it is stopped; `0` stops it at the first. */ + open val tolerateFailures: Int get() = 0 + + /** How late a run may start before [onLag] is asked about it. */ + open val lagThreshold: Duration get() = Duration.ofSeconds(2) + + /** For a task started by another task: whether it is cancelled together with that task. */ + open val cancelWithParent: Boolean get() = false + + /** Lookup tags. */ + open val tags: Set get() = emptySet() + + /** Whether an administrator may stop the task. */ + open val cancellable: Boolean get() = true + + /** Whether an administrator may start the task at once. */ + open val runnableNow: Boolean get() = true + + /** Whether the task is left out of the commands and the menu. */ + open val hidden: Boolean get() = false + + /** + * Called right before a run that starts more than [lagThreshold] late, such as after the server froze. Override it + * to tell an administrator or to skip a stale run; the default runs it anyway. + */ + open fun onLag(lag: TaskLag): LagResponse = LagResponse.RUN + + /** Checked before each invocation; returning `false` skips that invocation. */ + open fun shouldRun(): Boolean = true + + /** Checked before each invocation; returning `true` cancels the task. */ + open fun shouldStop(): Boolean = false + + /** Builds the [TaskSpec] that describes this task as it is right now. */ + fun toSpec(): TaskSpec = TaskSpec.builder() + .name(name) + .description(description) + .usage(usage) + .key(key) + .conflictPolicy(conflictPolicy) + .execution(execution) + .delay(delay) + .interval(interval) + .maxLag(maxLag) + .tolerateFailures(tolerateFailures) + .onLag(lagThreshold, ::onLag) + .cancelWithParent(cancelWithParent) + .tags(tags) + .cancellable(cancellable) + .runnableNow(runnableNow) + .hidden(hidden) + .condition(::shouldRun) + .cancelWhen(::shouldStop) + .action(this) + .build() +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskAction.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskAction.kt new file mode 100644 index 000000000..703ca56aa --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskAction.kt @@ -0,0 +1,9 @@ +package org.pnfolder.pnlibrary.api.tasks.spec + +import org.pnfolder.pnlibrary.api.tasks.run.TaskContext + +/** Action invoked by a scheduled task. */ +fun interface TaskAction { + /** Performs one invocation using its live [context]. */ + fun run(context: TaskContext) +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy.kt new file mode 100644 index 000000000..def3ce796 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskConflictPolicy.kt @@ -0,0 +1,13 @@ +package org.pnfolder.pnlibrary.api.tasks.spec + +/** Policy applied when a scope already contains the requested task key. */ +enum class TaskConflictPolicy { + /** Fail the new schedule request. */ + REJECT, + + /** Keep the live task and return its handle. */ + KEEP_EXISTING, + + /** Cancel the live task and schedule the new one. */ + REPLACE, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskIdentity.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskExecution.kt similarity index 51% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskIdentity.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskExecution.kt index 11fea85d6..35c926224 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskIdentity.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskExecution.kt @@ -1,39 +1,4 @@ -package org.pnfolder.pnlibrary.api.tasks - -import java.util.UUID - -/** Stable non-blank identifier assigned to one scheduled task. */ -data class TaskId( - /** Non-blank identifier value. */ - val value: String, -) { - init { - require(value.isNotBlank()) { "Task id must not be blank" } - } - - override fun toString(): String = value - - companion object { - /** Returns a new UUID-backed task identifier. */ - @JvmStatic - fun random(): TaskId = TaskId(UUID.randomUUID().toString()) - } -} - -/** Current lifecycle state of a scheduled task. */ -enum class TaskStatus { - SCHEDULED, - RUNNING, - COMPLETED, - CANCELLED, - FAILED -} -/** Policy applied when a scope already contains the requested task key. */ -enum class TaskConflictPolicy { - REJECT, - KEEP_EXISTING, - REPLACE -} +package org.pnfolder.pnlibrary.api.tasks.spec /** * Platform execution context selected for a task. @@ -44,10 +9,18 @@ enum class TaskConflictPolicy { class TaskExecution private constructor(val kind: Kind, val target: Any?) { /** Supported execution-context categories. */ enum class Kind { + /** The platform's global (main) context. */ GLOBAL, + + /** pnLibrary's asynchronous executor. */ ASYNC, - ENTITY + + /** The context bound to one native entity, such as a Folia region. */ + ENTITY, } + + override fun toString(): String = if (target == null) kind.name else "$kind($target)" + companion object { /** Selects the platform's global execution context. */ @JvmStatic diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskSpec.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskSpec.kt similarity index 59% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskSpec.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskSpec.kt index f6d57c9c7..eda2d97c3 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskSpec.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskSpec.kt @@ -1,32 +1,12 @@ -package org.pnfolder.pnlibrary.api.tasks +package org.pnfolder.pnlibrary.api.tasks.spec +import org.pnfolder.pnlibrary.api.tasks.info.TaskLag +import org.pnfolder.pnlibrary.api.tasks.run.LagResponse +import org.pnfolder.pnlibrary.api.tasks.run.TaskLagHandler import java.time.Duration -import java.time.Instant import java.util.Collections import java.util.function.BooleanSupplier -/** Action invoked by a scheduled task. */ -fun interface TaskAction { - /** Performs one invocation using its live [context]. */ - fun run(context: TaskContext) -} - -/** Live metadata and cancellation control exposed to a running task action. */ -interface TaskContext { - /** Stable identifier of the running task. */ - val id: TaskId - /** Optional human-readable task name. */ - val name: String? - /** One-based invocation number. */ - val runNumber: Long - /** Time at which this invocation was intended to start. */ - val scheduledAt: Instant - /** Time at which this invocation actually started. */ - val startedAt: Instant - /** Cancels all future invocations of this task. */ - fun cancel() -} - /** * Immutable declaration used to schedule one task. * @@ -41,6 +21,11 @@ interface TaskContext { * @property execution platform execution context * @property delay delay before the first invocation * @property interval repeat interval, or `null` for a one-shot task + * @property maxLag longest a run may start late (for example after the server froze) before it is skipped instead; `null` runs it anyway + * @property tolerateFailures how many failures in a row a repeating task survives before it is stopped as failed; `0` stops it at the first + * @property lagThreshold how late a run may start before [lagHandler] is asked about it + * @property lagHandler reaction to a run that starts later than [lagThreshold], or `null` for none + * @property cancelWithParent for a task started by another task: whether it is cancelled when that task is cancelled * @property conditions predicates that must all pass before an invocation runs * @property cancellationConditions predicates that cancel the task when any passes * @property tags immutable application-defined lookup tags @@ -58,6 +43,11 @@ class TaskSpec private constructor( val execution: TaskExecution, val delay: Duration, val interval: Duration?, + val maxLag: Duration?, + val tolerateFailures: Int, + val lagThreshold: Duration, + val lagHandler: TaskLagHandler?, + val cancelWithParent: Boolean, val conditions: List, val cancellationConditions: List, val tags: Set, @@ -76,6 +66,11 @@ class TaskSpec private constructor( private var execution = TaskExecution.global() private var delay = Duration.ZERO private var interval: Duration? = null + private var maxLag: Duration? = null + private var tolerateFailures = 0 + private var lagThreshold: Duration = DEFAULT_LAG_THRESHOLD + private var lagHandler: TaskLagHandler? = null + private var cancelWithParent = false private val conditions = mutableListOf() private val cancellationConditions = mutableListOf() private val tags = linkedSetOf() @@ -92,12 +87,20 @@ class TaskSpec private constructor( internal val configuredExecution: TaskExecution get() = execution internal val configuredDelay: Duration get() = delay internal val configuredInterval: Duration? get() = interval + internal val configuredMaxLag: Duration? get() = maxLag + internal val configuredTolerateFailures: Int get() = tolerateFailures + internal val configuredLagThreshold: Duration get() = lagThreshold + internal val configuredLagHandler: TaskLagHandler? get() = lagHandler + internal val configuredCancelWithParent: Boolean get() = cancelWithParent internal val configuredTags: Set get() = tags.toSet() + /** Sets the optional human-readable task name. */ fun name(value: String?): Builder = apply { name = value } + /** Sets the optional sentence on what the task is for. */ fun description(value: String?): Builder = apply { description = value } + /** Sets the optional note on how the task is used or what it changes. */ fun usage(value: String?): Builder = apply { usage = value } /** Sets whether an administrator may stop the task from the commands and the menu; `true` by default. */ @@ -106,15 +109,19 @@ class TaskSpec private constructor( /** Sets whether an administrator may start the task at once from the commands and the menu; `true` by default. */ fun runnableNow(value: Boolean): Builder = apply { runnableNow = value } + /** Sets whether the task is left out of the commands and the menu; `false` by default. */ fun hidden(value: Boolean): Builder = apply { hidden = value } + /** Sets the conflict-resolution key within the owner scope; `null` means no key. */ fun key(value: String?): Builder = apply { key = value } + /** Sets the behavior when another live task already owns the key. */ fun conflictPolicy(value: TaskConflictPolicy): Builder = apply { conflictPolicy = value } /** Selects the platform execution context. */ fun execution(value: TaskExecution): Builder = apply { execution = value } + /** Sets the delay before the first invocation. */ fun delay(value: Duration): Builder = apply { delay = value } /** @@ -124,6 +131,7 @@ class TaskSpec private constructor( */ fun delayTicks(value: Long): Builder = apply { delay = ticksToDuration(value, "delay") } + /** Sets the repeat interval; `null` makes the task one-shot. */ fun interval(value: Duration?): Builder = apply { interval = value } /** @@ -133,14 +141,51 @@ class TaskSpec private constructor( */ fun intervalTicks(value: Long): Builder = apply { interval = ticksToDuration(value, "interval") } + /** + * Skips a run that starts more than [value] after its planned time, such as after the server froze, instead + * of running it late. A skipped run counts as skipped; a one-shot task that is too late simply ends. `null` (the + * default) never skips. + */ + fun maxLag(value: Duration?): Builder = apply { maxLag = value } + + /** + * Lets a repeating task survive up to [value] failures in a row: each is logged and the task tries again at the + * next interval. A successful run resets the count. `0` (the default) stops the task at the first failure. + */ + fun tolerateFailures(value: Int): Builder = apply { tolerateFailures = value } + + /** + * Calls [handler] right before a run that starts more than [threshold] after its planned time, such as after + * the server froze, and lets it run or skip that run. Without a handler late runs simply run late. + */ + fun onLag(threshold: Duration, handler: TaskLagHandler): Builder = apply { + lagThreshold = threshold + lagHandler = handler + } + + /** Like [onLag] for a handler that only wants to be told: the late run always goes on. */ + fun whenLate(threshold: Duration, listener: java.util.function.Consumer): Builder = + onLag(threshold) { lag -> listener.accept(lag); LagResponse.RUN } + + /** + * For a task started by another task: cancels it together with that task. Off by default, so a follow-up + * outlives its parent. + */ + fun cancelWithParent(value: Boolean): Builder = apply { cancelWithParent = value } + + /** Adds a predicate that must pass before each invocation runs. */ fun condition(value: BooleanSupplier): Builder = apply { conditions += value } + /** Adds a predicate that cancels the task as soon as it passes. */ fun cancelWhen(value: BooleanSupplier): Builder = apply { cancellationConditions += value } + /** Adds one lookup tag. */ fun tag(value: String): Builder = apply { tags += value } + /** Adds several lookup tags. */ fun tags(values: Collection): Builder = apply { tags += values } + /** Sets the required callback invoked for each accepted run. */ fun action(value: TaskAction): Builder = apply { action = value } /** Validates this declaration and creates an immutable task specification. */ @@ -148,9 +193,13 @@ class TaskSpec private constructor( require(!delay.isNegative) { "Task delay must not be negative" } interval?.let { require(!it.isNegative && !it.isZero) { "Task interval must be positive" } } key?.let { require(it.isNotBlank()) { "Task key must not be blank" } } + maxLag?.let { require(!it.isNegative && !it.isZero) { "Task max lag must be positive" } } + require(tolerateFailures >= 0) { "Tolerated failures must not be negative" } + require(!lagThreshold.isNegative) { "Task lag threshold must not be negative" } require(tags.none { it.isBlank() }) { "Task tags must not be blank" } return TaskSpec(name, description?.takeIf { it.isNotBlank() }, usage?.takeIf { it.isNotBlank() }, - cancellable, runnableNow, hidden, key, conflictPolicy, execution, delay, interval, + cancellable, runnableNow, hidden, key, conflictPolicy, execution, delay, interval, maxLag, tolerateFailures, + lagThreshold, lagHandler, cancelWithParent, Collections.unmodifiableList(ArrayList(conditions)), Collections.unmodifiableList(ArrayList(cancellationConditions)), Collections.unmodifiableSet(LinkedHashSet(tags)), @@ -160,84 +209,15 @@ class TaskSpec private constructor( companion object { private const val MILLIS_PER_TICK = 50L + private val DEFAULT_LAG_THRESHOLD: Duration = Duration.ofSeconds(2) private fun ticksToDuration(value: Long, label: String): Duration { require(value >= 0) { "Task $label ticks must not be negative" } return Duration.ofMillis(Math.multiplyExact(value, MILLIS_PER_TICK)) } + /** Creates a new [Builder]; the entry point for Java callers. */ @JvmStatic fun builder(): Builder = Builder() } } - -/** Kotlin property-based DSL for constructing a [TaskSpec]. */ -class TaskSpecBuilder internal constructor() { - private val delegate = TaskSpec.builder() - /** Optional human-readable task name. */ - var name: String? - get() = delegate.configuredName - set(value) { delegate.name(value) } - /** Optional sentence on what the task is for. */ - var description: String? - get() = delegate.configuredDescription - set(value) { delegate.description(value) } - /** Optional note on how the task is used or what it changes. */ - var usage: String? - get() = delegate.configuredUsage - set(value) { delegate.usage(value) } - /** Whether an administrator may stop the task from the commands and the menu; `true` by default. */ - var cancellable: Boolean - get() = delegate.configuredCancellable - set(value) { delegate.cancellable(value) } - /** Whether an administrator may start the task at once from the commands and the menu; `true` by default. */ - var runnableNow: Boolean - get() = delegate.configuredRunnableNow - set(value) { delegate.runnableNow(value) } - /** Whether the task is left out of the commands and the menu; `false` by default. */ - var hidden: Boolean - get() = delegate.configuredHidden - set(value) { delegate.hidden(value) } - /** Optional conflict-resolution key within the owner scope. */ - var key: String? - get() = delegate.configuredKey - set(value) { delegate.key(value) } - /** Behavior when another live task already owns [key]. */ - var conflictPolicy: TaskConflictPolicy - get() = delegate.configuredConflictPolicy - set(value) { delegate.conflictPolicy(value) } - /** Platform execution context used for invocations. */ - var execution: TaskExecution - get() = delegate.configuredExecution - set(value) { delegate.execution(value) } - /** Delay before the first invocation. */ - var delay: Duration - get() = delegate.configuredDelay - set(value) { delegate.delay(value) } - - fun delayTicks(value: Long) { delegate.delayTicks(value) } - - /** Repeat interval, or `null` for a one-shot task. */ - var interval: Duration? - get() = delegate.configuredInterval - set(value) { delegate.interval(value) } - - fun intervalTicks(value: Long) { delegate.intervalTicks(value) } - /** Application-defined lookup tags. */ - var tags: Set - get() = delegate.configuredTags - set(value) { delegate.tags(value) } - - fun condition(test: () -> Boolean) { delegate.condition(BooleanSupplier(test)) } - - fun cancelWhen(test: () -> Boolean) { delegate.cancelWhen(BooleanSupplier(test)) } - - fun run(action: TaskAction) { delegate.action(action) } - - internal fun build(): TaskSpec = delegate.build() -} - -/** Builds and schedules a task using the Kotlin receiver [configure]. */ -@JvmSynthetic -fun TaskScope.schedule(configure: TaskSpecBuilder.() -> Unit): TaskHandle = - schedule(TaskSpecBuilder().apply(configure).build()) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskSpecBuilder.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskSpecBuilder.kt new file mode 100644 index 000000000..74b61ff5f --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/tasks/spec/TaskSpecBuilder.kt @@ -0,0 +1,115 @@ +package org.pnfolder.pnlibrary.api.tasks.spec + +import org.pnfolder.pnlibrary.api.tasks.TaskHandle +import org.pnfolder.pnlibrary.api.tasks.TaskScope +import org.pnfolder.pnlibrary.api.tasks.info.TaskLag +import org.pnfolder.pnlibrary.api.tasks.run.TaskContext +import org.pnfolder.pnlibrary.api.tasks.run.TaskLagHandler +import java.time.Duration +import java.util.function.BooleanSupplier + +/** Kotlin property-based DSL for constructing a [TaskSpec]. */ +class TaskSpecBuilder internal constructor() { + private val delegate = TaskSpec.builder() + /** Optional human-readable task name. */ + var name: String? + get() = delegate.configuredName + set(value) { delegate.name(value) } + /** Optional sentence on what the task is for. */ + var description: String? + get() = delegate.configuredDescription + set(value) { delegate.description(value) } + /** Optional note on how the task is used or what it changes. */ + var usage: String? + get() = delegate.configuredUsage + set(value) { delegate.usage(value) } + /** Whether an administrator may stop the task from the commands and the menu; `true` by default. */ + var cancellable: Boolean + get() = delegate.configuredCancellable + set(value) { delegate.cancellable(value) } + /** Whether an administrator may start the task at once from the commands and the menu; `true` by default. */ + var runnableNow: Boolean + get() = delegate.configuredRunnableNow + set(value) { delegate.runnableNow(value) } + /** Whether the task is left out of the commands and the menu; `false` by default. */ + var hidden: Boolean + get() = delegate.configuredHidden + set(value) { delegate.hidden(value) } + /** Optional conflict-resolution key within the owner scope. */ + var key: String? + get() = delegate.configuredKey + set(value) { delegate.key(value) } + /** Behavior when another live task already owns [key]. */ + var conflictPolicy: TaskConflictPolicy + get() = delegate.configuredConflictPolicy + set(value) { delegate.conflictPolicy(value) } + /** Platform execution context used for invocations. */ + var execution: TaskExecution + get() = delegate.configuredExecution + set(value) { delegate.execution(value) } + /** Delay before the first invocation. */ + var delay: Duration + get() = delegate.configuredDelay + set(value) { delegate.delay(value) } + + /** Sets the delay before the first invocation in server ticks (50 ms each). */ + fun delayTicks(value: Long) { delegate.delayTicks(value) } + + /** Repeat interval, or `null` for a one-shot task. */ + var interval: Duration? + get() = delegate.configuredInterval + set(value) { delegate.interval(value) } + + /** Sets the repeat interval in server ticks (50 ms each). */ + fun intervalTicks(value: Long) { delegate.intervalTicks(value) } + + /** Longest a run may start late before it is skipped; `null` never skips. See [TaskSpec.Builder.maxLag]. */ + var maxLag: Duration? + get() = delegate.configuredMaxLag + set(value) { delegate.maxLag(value) } + + /** Failures in a row a repeating task survives; `0` stops it at the first. See [TaskSpec.Builder.tolerateFailures]. */ + var tolerateFailures: Int + get() = delegate.configuredTolerateFailures + set(value) { delegate.tolerateFailures(value) } + + /** For a task started by another task: whether it is cancelled together with that task. Off by default. */ + var cancelWithParent: Boolean + get() = delegate.configuredCancelWithParent + set(value) { delegate.cancelWithParent(value) } + + /** Reacts when a run starts later than [threshold], for example after the server froze; see [TaskLagHandler]. */ + fun onLag(threshold: Duration, handler: TaskLagHandler) { delegate.onLag(threshold, handler) } + + /** Like [onLag] for a listener that only wants to be told: the late run always goes on. */ + fun whenLate(threshold: Duration, listener: (TaskLag) -> Unit) { delegate.whenLate(threshold) { listener(it) } } + + /** Adds one lookup tag. */ + fun tag(value: String) { delegate.tag(value) } + + /** Application-defined lookup tags. */ + var tags: Set + get() = delegate.configuredTags + set(value) { delegate.tags(value) } + + /** Adds a predicate that must pass before each invocation runs. */ + fun condition(test: () -> Boolean) { delegate.condition(BooleanSupplier(test)) } + + /** Adds a predicate that cancels the task as soon as it passes. */ + fun cancelWhen(test: () -> Boolean) { delegate.cancelWhen(BooleanSupplier(test)) } + + /** Sets the callback invoked for each accepted run. */ + fun run(action: TaskAction) { delegate.action(action) } + + internal fun build(): TaskSpec = delegate.build() +} + +/** Builds and schedules a task using the Kotlin receiver [configure]. */ +@JvmSynthetic +fun TaskScope.schedule(configure: TaskSpecBuilder.() -> Unit): TaskHandle = + schedule(TaskSpecBuilder().apply(configure).build()) + +/** Builds and starts a task of its own under the running task, using the Kotlin receiver [configure]. */ +@JvmSynthetic +fun TaskContext.spawn(configure: TaskSpecBuilder.() -> Unit): TaskHandle = + spawn(TaskSpecBuilder().apply(configure).build()) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentService.kt index 95fe0323a..fe662c221 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentService.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentService.kt @@ -1,46 +1,10 @@ package org.pnfolder.pnlibrary.api.text import net.kyori.adventure.text.Component - -/** - * Bidirectional converter for one [ComponentSerializerType]. - * - * Implementations must be safe for repeated use. Unless stated by an implementation, - * malformed input may throw a format-specific runtime exception. - */ -interface ComponentSerializer { - - /** Syntax handled by this serializer. */ - val type: ComponentSerializerType - - /** Parses one [input] string into an Adventure component. */ - fun deserialize(input: String): Component - - /** Deserializes every input independently and preserves list boundaries. */ - fun deserializeAll(inputs: Iterable): List = inputs.map(::deserialize) - - /** Deserializes lines and joins them with real newline components, without a trailing newline. */ - fun deserializeLines(lines: Iterable): Component = joinComponentLines(deserializeAll(lines)) - - /** Vararg convenience overload for [deserializeLines]. */ - fun deserializeLines(vararg lines: String): Component = deserializeLines(lines.asList()) - - /** Serializes [component] using this serializer's syntax. */ - fun serialize(component: Component): String - - /** Serializes every component independently and preserves list boundaries. */ - fun serializeAll(components: Iterable): List = components.map(::serialize) -} - -/** Ownership boundary used for parsed-component cache entries. */ -enum class ComponentCacheScope { - /** Bypasses the cache and parses every request. */ - NONE, - /** Isolates entries by the plugin that owns the component service. */ - PLUGIN, - /** Allows compatible service instances to share cached entries. */ - GLOBAL, -} +import org.pnfolder.pnlibrary.api.text.cache.ComponentCachePolicy +import org.pnfolder.pnlibrary.api.text.cache.ComponentCacheStatistics +import org.pnfolder.pnlibrary.api.text.serializer.ComponentSerializer +import org.pnfolder.pnlibrary.api.text.serializer.ComponentSerializerType /** * Central text conversion, templating, and cache service. @@ -49,7 +13,6 @@ enum class ComponentCacheScope { * components are Adventure values and can be safely further composed by callers. */ interface ComponentService { - /** Serializer selected by overloads that do not accept an explicit type. */ var defaultSerializerType: ComponentSerializerType @@ -83,8 +46,10 @@ interface ComponentService { /** Serializes each component independently with [defaultSerializerType]. */ fun serializeAll(components: Iterable): List = components.map(::serialize) + /** Parses [input] into a reusable template using the default serializer. */ fun template(input: String): ComponentTemplate + /** Parses [input] into a reusable template; the serializer type is ignored. */ fun template(input: String, type: ComponentSerializerType): ComponentTemplate = template(input) /** Replaces the active parsed-component cache policy. */ @@ -96,13 +61,3 @@ interface ComponentService { /** Returns current cache counters and retained size. */ fun cacheStatistics(): ComponentCacheStatistics } - -private fun joinComponentLines(lines: Iterable): Component { - val iterator = lines.iterator() - if (!iterator.hasNext()) return Component.empty() - var result = iterator.next() - while (iterator.hasNext()) { - result = result.append(Component.newline()).append(iterator.next()) - } - return result -} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentTemplate.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentTemplate.kt index 1f3f7948a..f804266c1 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentTemplate.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentTemplate.kt @@ -6,10 +6,12 @@ import java.util.concurrent.CompletionStage /** Mutable rendering invocation created from one serialized component template. */ interface ComponentTemplate { - /** Associates a named template token with [value]. */ fun value(name: String, value: Any?): ComponentTemplate + /** Associates every entry of [values] with its named template token. */ + fun values(values: Map): ComponentTemplate = apply { values.forEach { (key, item) -> value(key, item) } } + /** Selects the player used by player-aware placeholder resolution. */ fun player(playerId: UUID): ComponentTemplate diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentCachePolicy.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/cache/ComponentCachePolicy.kt similarity index 74% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentCachePolicy.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/cache/ComponentCachePolicy.kt index ca64e083e..605cd778f 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentCachePolicy.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/cache/ComponentCachePolicy.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.text +package org.pnfolder.pnlibrary.api.text.cache import java.time.Duration @@ -20,4 +20,11 @@ data class ComponentCachePolicy @JvmOverloads constructor( require(maximumEntries > 0) { "Cache maximumEntries must be positive" } require(!expireAfterAccess.isZero && !expireAfterAccess.isNegative) { "Cache expireAfterAccess must be positive" } } + + /** Ready-made policies. */ + companion object { + /** A policy that never caches: every request is parsed again. */ + @JvmField + val DISABLED: ComponentCachePolicy = ComponentCachePolicy(scope = ComponentCacheScope.NONE) + } } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope.kt new file mode 100644 index 000000000..62ec77661 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/cache/ComponentCacheScope.kt @@ -0,0 +1,13 @@ +package org.pnfolder.pnlibrary.api.text.cache + +/** Ownership boundary used for parsed-component cache entries. */ +enum class ComponentCacheScope { + /** Bypasses the cache and parses every request. */ + NONE, + + /** Isolates entries by the plugin that owns the component service. */ + PLUGIN, + + /** Allows compatible service instances to share cached entries. */ + GLOBAL, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentCacheStatistics.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/cache/ComponentCacheStatistics.kt similarity index 67% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentCacheStatistics.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/cache/ComponentCacheStatistics.kt index 8ad5fd475..9aee59da2 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentCacheStatistics.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/cache/ComponentCacheStatistics.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.text +package org.pnfolder.pnlibrary.api.text.cache /** * Point-in-time component-cache counters. @@ -11,7 +11,9 @@ package org.pnfolder.pnlibrary.api.text data class ComponentCacheStatistics( val hits: Long, val misses: Long, val evictions: Long, val size: Int, ) { + /** Number of lookups: hits plus misses. */ + val lookups: Long get() = hits + misses /** Ratio of hits to all lookups, or `0.0` before the first lookup. */ - val hitRate: Double get() = if (hits + misses == 0L) 0.0 else hits.toDouble() / (hits + misses) + val hitRate: Double get() = if (lookups == 0L) 0.0 else hits.toDouble() / lookups } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/serializer/ComponentSerializer.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/serializer/ComponentSerializer.kt new file mode 100644 index 000000000..744ebf2fe --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/serializer/ComponentSerializer.kt @@ -0,0 +1,41 @@ +package org.pnfolder.pnlibrary.api.text.serializer + +import net.kyori.adventure.text.Component + +/** + * Bidirectional converter for one [ComponentSerializerType]. + * + * Implementations must be safe for repeated use. Unless stated by an implementation, + * malformed input may throw a format-specific runtime exception. + */ +interface ComponentSerializer { + /** Syntax handled by this serializer. */ + val type: ComponentSerializerType + + /** Parses one [input] string into an Adventure component. */ + fun deserialize(input: String): Component + + /** Deserializes every input independently and preserves list boundaries. */ + fun deserializeAll(inputs: Iterable): List = inputs.map(::deserialize) + + /** Deserializes lines and joins them with real newline components, without a trailing newline. */ + fun deserializeLines(lines: Iterable): Component = deserializeAll(lines).joinLines() + + /** Vararg convenience overload for [deserializeLines]. */ + fun deserializeLines(vararg lines: String): Component = deserializeLines(lines.asList()) + + /** Serializes [component] using this serializer's syntax. */ + fun serialize(component: Component): String + + /** Serializes every component independently and preserves list boundaries. */ + fun serializeAll(components: Iterable): List = components.map(::serialize) +} + +/** Joins components with `Component.newline()` between them, or returns an empty component for none. */ +internal fun Iterable.joinLines(): Component { + val iterator = iterator() + if (!iterator.hasNext()) return Component.empty() + var result = iterator.next() + while (iterator.hasNext()) result = result.append(Component.newline()).append(iterator.next()) + return result +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentSerializerType.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType.kt similarity index 98% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentSerializerType.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType.kt index 5b0fa6abb..4010f177d 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentSerializerType.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.text +package org.pnfolder.pnlibrary.api.text.serializer /** * Text syntax used to convert between strings and Adventure components. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateBackups.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateBackups.kt new file mode 100644 index 000000000..834f6da5c --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateBackups.kt @@ -0,0 +1,41 @@ +package org.pnfolder.pnlibrary.api.updates + +import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import java.util.UUID +import java.util.concurrent.CompletionStage + +/** The rollback sets kept before each update, and going back to them. */ +interface UpdateBackups { + /** The retained complete sets, newest first when their dates are known. */ + fun list(): CompletionStage> + + /** Prepares the newest set that can be rolled back for the next restart. */ + fun rollback(actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage + + /** + * Prepares exactly the set [transactionId] for the next restart and never substitutes another. With + * [restoreConfigurations] the saved settings are restored as well, which is an explicit choice. + */ + fun rollback( + transactionId: UUID, + actor: UpdateActor = UpdateActor.UNKNOWN, + restoreConfigurations: Boolean = false, + ): CompletionStage + + /** Permanently deletes the set [transactionId] with its saved files; a set a restart still verifies is refused. */ + fun delete(transactionId: UUID, actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage + + /** + * Puts the database [name] of [product] back as it was in the set [transactionId]: the tables in the copy replace the + * current ones and rows written since are lost, but the state it replaces is kept first. Runs at once. + */ + fun restoreDatabase(transactionId: UUID, product: String, name: String, actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage + + /** + * Copies the saved databases and exports of [product] from the set [transactionId] into a new folder under + * `plugins/pnLibrary/data/updates/handout`, for a plugin that cannot take them back itself, and returns its path. + */ + fun extract(transactionId: UUID, product: String, actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateHistory.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateHistory.kt new file mode 100644 index 000000000..9763aec65 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateHistory.kt @@ -0,0 +1,13 @@ +package org.pnfolder.pnlibrary.api.updates + +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import java.util.concurrent.CompletionStage + +/** The durable log of updates: checks, downloads, installs, rollbacks and changed settings. */ +interface UpdateHistory { + /** Ten events newest first; [page] counts from one, [product] limits them to one managed product id. */ + fun page(page: Int, product: String? = null): CompletionStage> + + /** How many events [page] pages through, for all products or for one [product]. */ + fun count(product: String? = null): CompletionStage +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdatePlans.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdatePlans.kt new file mode 100644 index 000000000..4bc2746bc --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdatePlans.kt @@ -0,0 +1,22 @@ +package org.pnfolder.pnlibrary.api.updates + +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import java.util.Optional +import java.util.UUID +import java.util.concurrent.CompletionStage + +/** Looking for releases and turning them into a plan that is downloaded, verified and applied at restart. */ +interface UpdatePlans { + /** Asks every catalogue for releases and resolves one plan that fits every registered product together. */ + fun check(actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage + + /** The newest plan, when one has been resolved. */ + fun current(): Optional + + /** The latest plans in memory, newest first, bounded. */ + fun recent(): List + + /** Downloads and verifies every file of the plan [planId], so it can be applied at the next restart. */ + fun stage(planId: UUID, actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateProducts.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateProducts.kt new file mode 100644 index 000000000..0840340ac --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateProducts.kt @@ -0,0 +1,14 @@ +package org.pnfolder.pnlibrary.api.updates + +/** The products registered for updates on this server. */ +interface UpdateProducts { + /** An immutable copy of the current registrations. */ + fun all(): List + + /** Finds a registration by product or repository name, ignoring case. */ + fun get(product: String): UpdateRegistration? + + /** Finds a registration or fails naming the product that is missing. */ + fun require(product: String): UpdateRegistration = + get(product) ?: error("Update registration '$product' is unavailable") +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateRegistration.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateRegistration.kt index ddd04a682..109dacc41 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateRegistration.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateRegistration.kt @@ -1,5 +1,7 @@ package org.pnfolder.pnlibrary.api.updates +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot + /** Lifecycle and manual controls for one updater registration. */ interface UpdateRegistration : AutoCloseable { diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateService.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateService.kt index 62785991b..6fe6a41ff 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateService.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateService.kt @@ -1,24 +1,27 @@ package org.pnfolder.pnlibrary.api.updates import org.pnfolder.pnlibrary.api.dependencies.PluginDependency -import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup -import org.pnfolder.pnlibrary.api.updates.backup.UpdateHistoryEntry -import java.time.Duration -import java.time.Instant -import java.util.Optional -import java.util.UUID -import java.util.concurrent.CompletableFuture -import java.util.concurrent.CompletionStage +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest /** - * Registers and queries plugin update monitors owned by this runtime. + * The entry to plugin updates: register a product, then use one of five focused parts. * - * Registration and lookup are safe from arbitrary threads. Graph checks are serialized by the - * runtime and concurrent [checkNow] calls share the active check. Completion stages finish on the - * update executor; callers must dispatch platform mutations through their platform/task API. + * | Part | What it is for | + * |---|---| + * | [products] | which products are registered, and their state | + * | [plans] | checking for releases and staging the resulting plan | + * | [settings] | per-product choices: channel, automatic download, hold, Java build | + * | [backups] | saved rollback sets, rolling back, restoring databases | + * | [history] | the durable log of what happened | + * + * Every part is always present and every method works: there are no optional operations. Registration and lookup are + * safe from any thread; checks are serialized by the runtime and concurrent checks share the one that is running. + * Completion stages finish on the update executor, so callers must hand platform changes over to their platform or + * task API. Passing an actor records who asked; it is audit information and grants no permission. */ interface UpdateService { - /** Registers and immediately starts monitoring [product] represented by [owner]. */ + /** Registers [owner]'s [product] and starts watching its releases at once. */ fun register( owner: Any, product: ProductDescriptor, @@ -26,109 +29,18 @@ interface UpdateService { dependencies: List = emptyList(), ): UpdateRegistration - /** Java-friendly overload for registering a product without dependencies. */ - fun register(owner: Any, product: ProductDescriptor, request: PluginUpdateRequest): UpdateRegistration = - register(owner, product, request, emptyList()) - - /** Returns an immutable snapshot of current registrations. */ - fun all(): List - - /** Finds a registration by product or repository name, ignoring case. */ - fun get(product: String): UpdateRegistration? - - /** Returns a registration or fails with the requested product in the message. */ - fun require(product: String): UpdateRegistration = - get(product) ?: error("Update registration '$product' is unavailable") - - /** Refreshes every registered catalogue and resolves one complete compatibility plan. */ - fun checkNow(): CompletionStage = unsupported("graph update checks") - - /** Checks releases with explicit audit attribution. Does not grant permissions. */ - fun checkNow(actor: UpdateActor): CompletionStage = checkNow() - - /** Returns the latest immutable graph plan, when one has been resolved. */ - fun currentPlan(): Optional = Optional.empty() - - /** Downloads and verifies every artifact in the selected plan. */ - fun stage(planId: UUID): CompletionStage = unsupported("graph update staging") - - /** Stages exactly [planId] and records its initiator. Does not grant permissions. */ - fun stage(planId: UUID, actor: UpdateActor): CompletionStage = stage(planId) - - /** Confirms a token-bound sensitive action for the selected plan. */ - fun confirm(planId: UUID, token: String): CompletionStage = unsupported("graph update confirmation") - - /** Returns a bounded, newest-first, immutable graph-plan snapshot. */ - fun history(): List = emptyList() - - /** - * Reads ten newest-first durable events on the update executor. - * [page] is one-based; [product] is an optional normalized managed product ID. - * Completion callbacks must dispatch platform operations to the appropriate platform thread. - */ - fun historyPage(page: Int, product: String? = null): CompletionStage> = - CompletableFuture>().also { - it.completeExceptionally(UnsupportedOperationException("Update service does not support durable history")) - } - - /** Counts the durable events [historyPage] pages through, optionally for one managed [product]. */ - fun historyCount(product: String? = null): CompletionStage = - CompletableFuture().also { - it.completeExceptionally(UnsupportedOperationException("Update service does not support durable history")) - } - - /** - * Switches the release [channel] of a managed [product] immediately. The choice is remembered across restarts - * and takes precedence over the channel the plugin declares itself. A `null` [channel] removes the choice, so - * the plugin's own channel applies again. Does not grant permissions. - */ - fun setChannel(product: String, channel: UpdateChannel?, actor: UpdateActor): CompletionStage = - unsupportedSetting("channel changes") - - /** Turns automatic download of verified updates for [product] on or off, with the same persistence as [setChannel]. */ - fun setAutomaticDownload(product: String, enabled: Boolean, actor: UpdateActor): CompletionStage = - unsupportedSetting("automatic download changes") - - /** Holds updates of [product] for seven days, or releases a hold. */ - fun setHeld(product: String, held: Boolean, actor: UpdateActor): CompletionStage = - setHeld(product, if (held) Duration.ofDays(7) else null, actor) - - /** - * Holds updates of [product] for [duration], from one minute to seven days, replacing any earlier hold; null - * releases it. A held component is neither offered nor downloaded until the hold ends by itself. - */ - fun setHeld(product: String, duration: Duration?, actor: UpdateActor): CompletionStage = - unsupportedSetting("holding updates") - - /** When the current hold of [product] ends, or null when its updates are not held. */ - fun heldUntil(product: String): Instant? = null - - /** Restores the previous JAR set from the newest rollback-capable transaction. */ - fun rollback(): CompletionStage = unsupported("manual update rollback") - - /** Requests rollback with explicit audit attribution. Does not grant permissions. */ - fun rollback(actor: UpdateActor): CompletionStage = rollback() - - /** Reads the retained complete rollback sets asynchronously, newest first when dates are known. */ - fun backups(): CompletionStage> = CompletableFuture>().also { - it.completeExceptionally(UnsupportedOperationException("Update service does not support saved rollback sets")) - } + /** Registered products: list, find, state. */ + val products: UpdateProducts - /** Prepares exactly [transactionId] for restart. Never substitutes another backup. */ - fun rollback(transactionId: UUID, actor: UpdateActor): CompletionStage = - unsupported("selected transaction rollback") + /** Release checks and update plans. */ + val plans: UpdatePlans - /** Explicitly opts into restoring the selected configuration snapshot at the next offline application. */ - fun rollback(transactionId: UUID, restoreConfigurations: Boolean, actor: UpdateActor): CompletionStage = - if (restoreConfigurations) unsupported("configuration rollback") else rollback(transactionId, actor) + /** Per-product update choices. */ + val settings: UpdateSettings - private fun unsupportedSetting(operation: String): CompletionStage = - CompletableFuture().also { - it.completeExceptionally(UnsupportedOperationException("Update service does not support $operation")) - } + /** Saved rollback sets and returning to them. */ + val backups: UpdateBackups - private fun unsupported(operation: String): CompletionStage = - CompletableFuture().also { - it.completeExceptionally(UnsupportedOperationException("Update service does not support $operation")) - } + /** What happened, newest first, kept across restarts. */ + val history: UpdateHistory } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateSettings.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateSettings.kt new file mode 100644 index 000000000..9219df0e5 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateSettings.kt @@ -0,0 +1,42 @@ +package org.pnfolder.pnlibrary.api.updates + +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import java.time.Duration +import java.time.Instant +import java.util.concurrent.CompletionStage + +/** + * What an administrator chooses for a product. A choice is remembered across restarts and wins over what the plugin + * declares; removing it hands the decision back to the plugin. Each change is recorded with its [UpdateActor]. + */ +interface UpdateSettings { + /** Switches [product] to the release [channel] now; `null` removes the choice, so the plugin's own channel applies. */ + fun channel(product: String, channel: UpdateChannel?, actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage + + /** Turns automatic download of verified updates of [product] on or off. */ + fun automaticDownload(product: String, enabled: Boolean, actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage + + /** Turns automatic download on or off for every plugin, also those registered later; single choices are dropped. */ + fun automaticDownloadForAll(enabled: Boolean, actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage> + + /** + * Holds the updates of [product] for [duration], from one minute to seven days, replacing an earlier hold: nothing is + * offered or downloaded until the hold ends by itself or [release] is called. + */ + fun hold(product: String, duration: Duration = Duration.ofDays(7), actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage + + /** Ends the hold of [product] at once. */ + fun release(product: String, actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage + + /** When the hold of [product] ends, or `null` when its updates are not held. */ + fun heldUntil(product: String): Instant? + + /** + * Chooses which Java build of [product] is installed when its release has several, such as one for Java 8 and one for + * Java 17. [java] must be one of [UpdateSnapshot.javaBuilds]; `null` removes the choice, so the build that matches the + * installed product (else the newest the server can run) is used. + */ + fun javaBuild(product: String, java: Int?, actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateChecks.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateValidation.kt similarity index 100% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateChecks.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateValidation.kt diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/BackupExport.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/BackupExport.kt new file mode 100644 index 000000000..060ac819c --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/BackupExport.kt @@ -0,0 +1,18 @@ +package org.pnfolder.pnlibrary.api.updates.backup + +import java.nio.file.Path + +/** + * A copy the plugin makes itself, for data the library cannot copy as a file, such as a MySQL database. + * Before an update the library calls [export] with the file to write; the file is kept with the backup set + * and is NOT restored by a rollback: the administrator loads it back by hand. + * @property fileName name of the exported file inside the set, without folders + */ +class BackupExport(val kind: BackupKind, val name: String, val fileName: String, val export: (Path) -> Unit) { + init { + BackupLabel(kind, name) + require(fileName.isNotBlank() && fileName.none { it == '/' || it == '\\' || it.isISOControl() } && fileName != "." && fileName != "..") { + "Export file name must be a plain file name" + } + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/BackupKind.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/BackupKind.kt new file mode 100644 index 000000000..9d2fd4bc3 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/BackupKind.kt @@ -0,0 +1,16 @@ +package org.pnfolder.pnlibrary.api.updates.backup + +/** What a backed-up file holds, so the menu and commands can tell an administrator what a copy contains. */ +enum class BackupKind { + /** Settings and messages; small files. */ + CONFIGURATION, + + /** A database kept in a file, such as SQLite or H2. */ + DATABASE, + + /** Data about players: balances, profiles, progress. */ + PLAYER_DATA, + + /** Anything else a plugin wants to be able to roll back. */ + OTHER, +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/BackupLabel.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/BackupLabel.kt new file mode 100644 index 000000000..74cba76a7 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/BackupLabel.kt @@ -0,0 +1,8 @@ +package org.pnfolder.pnlibrary.api.updates.backup + +/** The kind and the display name of one backed-up file. A blank [name] means the library shows the kind. */ +data class BackupLabel(val kind: BackupKind, val name: String = "") { + init { + require(name.length <= 64 && name.none(Char::isISOControl)) { "Backup name must be at most 64 characters without control characters" } + } +} diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateBackup.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateBackup.kt index f7832ff1e..df1fbf8f4 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateBackup.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateBackup.kt @@ -1,6 +1,5 @@ package org.pnfolder.pnlibrary.api.updates.backup -import org.pnfolder.pnlibrary.api.updates.ProductId import org.pnfolder.pnlibrary.api.updates.frozen import java.time.Instant import java.util.UUID @@ -18,15 +17,20 @@ class UpdateBackup( components: List, /** Number of validated configuration files retained with this set; zero when unavailable. */ val configurationFiles: Int = 0, + items: List, ) { + /** A backup that does not describe its files one by one. */ + constructor( + id: UUID, + createdAt: Instant?, + planId: UUID?, + components: List, + configurationFiles: Int = 0, + ) : this(id, createdAt, planId, components, configurationFiles, emptyList()) + + /** What the saved files are: kind, name and size, so a menu can show an administrator what a copy holds. */ + val items: List = items.frozen() + /** Immutable description of the complete component set restored together. */ val components: List = components.frozen() } - -/** - * Version information for a retained component backup. - * @property product managed component identity - * @property updatedVersion version originally prepared by this transaction, if known - * @property backupVersion version stored before that update, if known - */ -data class UpdateBackupComponent(val product: ProductId, val updatedVersion: String?, val backupVersion: String?) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateBackupComponent.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateBackupComponent.kt new file mode 100644 index 000000000..33f76ce17 --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateBackupComponent.kt @@ -0,0 +1,11 @@ +package org.pnfolder.pnlibrary.api.updates.backup + +import org.pnfolder.pnlibrary.api.updates.product.ProductId + +/** + * Version information for a retained component backup. + * @property product managed component identity + * @property updatedVersion version originally prepared by this transaction, if known + * @property backupVersion version stored before that update, if known + */ +data class UpdateBackupComponent(val product: ProductId, val updatedVersion: String?, val backupVersion: String?) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateBackupItem.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateBackupItem.kt new file mode 100644 index 000000000..3e4d8188c --- /dev/null +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateBackupItem.kt @@ -0,0 +1,6 @@ +package org.pnfolder.pnlibrary.api.updates.backup + +import org.pnfolder.pnlibrary.api.updates.product.ProductId + +/** One saved file of a backup: what it holds, what it is called and how large it is. */ +data class UpdateBackupItem(val product: ProductId, val kind: BackupKind, val name: String, val bytes: Long) diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateConfigurationBackup.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateConfigurationBackup.kt index 5c1f2f2ca..b91201615 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateConfigurationBackup.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateConfigurationBackup.kt @@ -5,13 +5,16 @@ import java.nio.file.Paths import java.util.Collections /** - * Explicit component-owned configuration files to preserve before updates. + * Explicit component-owned files (settings, databases, player data) to preserve before updates. * No directory recursion or wildcard selection is performed. Files may contain secrets: the * server data directory and its backups must remain private to the server administrator. * * @property root component data directory, resolved absolutely at declaration time */ -class UpdateConfigurationBackup(root: Path, files: List) { +class UpdateConfigurationBackup(root: Path, files: List, labels: Map) { + /** Declares plain configuration files with no labels. */ + constructor(root: Path, files: List) : this(root, files, emptyMap()) + val root: Path = root.toAbsolutePath().normalize() /** Immutable normalized paths relative to [root]. Missing files are recorded as absent. */ val files: List = Collections.unmodifiableList(files.map { value -> @@ -24,7 +27,14 @@ class UpdateConfigurationBackup(root: Path, files: List) { path.toString() }) + /** Kind and name of the files that were labelled, by their normalized path; the others are configuration. */ + val labels: Map = Collections.unmodifiableMap(labels.mapKeys { Paths.get(it.key).normalize().toString() }) + + /** The label of [file], or a configuration label when it has none. */ + fun labelOf(file: String): BackupLabel = labels[file] ?: BackupLabel(BackupKind.CONFIGURATION) + init { + require(this.labels.keys.all { it in this.files }) { "A backup label names a file that is not declared" } require(this.files.isNotEmpty() && this.files.size <= 100) { "Configuration backup must declare between 1 and 100 files" } require(this.files.map { Paths.get(it) }.distinct().size == this.files.size) { "Duplicate configuration paths" } } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateHistoryEntry.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/history/UpdateHistoryEntry.kt similarity index 86% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateHistoryEntry.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/history/UpdateHistoryEntry.kt index a66ced726..5136ac24d 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/backup/UpdateHistoryEntry.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/history/UpdateHistoryEntry.kt @@ -1,9 +1,9 @@ -package org.pnfolder.pnlibrary.api.updates.backup +package org.pnfolder.pnlibrary.api.updates.history -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdateState import org.pnfolder.pnlibrary.api.updates.frozen import org.pnfolder.pnlibrary.api.updates.release.ProductChange +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import java.time.Instant import java.util.UUID diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/ProductDescriptor.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/product/ProductDescriptor.kt similarity index 92% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/ProductDescriptor.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/product/ProductDescriptor.kt index 74a49fd58..5beab121f 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/ProductDescriptor.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/product/ProductDescriptor.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.updates +package org.pnfolder.pnlibrary.api.updates.product import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity import org.pnfolder.pnlibrary.api.version.ApiVersionRange @@ -47,6 +47,7 @@ class ProductDescriptor private constructor( internal var minimumJava: Int = 8 internal var maximumJava: Int? = null + /** Sets the range of pnLibrary API versions the product supports. */ fun pnLibraryApi(minimum: Int, maximum: Int): Builder = apply { supportedApi = ApiVersionRange(minimum, maximum) } @@ -54,8 +55,10 @@ class ProductDescriptor private constructor( /** Parses and sets the installed semantic [value]. */ fun version(value: String): Builder = apply { version = SemanticVersion.parse(value) } + /** Sets the update channel the product follows. */ fun channel(value: UpdateChannel): Builder = apply { channel = value } + /** Sets the supported Java range; the maximum is open when `null`. */ @JvmOverloads fun java(minimum: Int, maximum: Int? = null): Builder = apply { require(minimum >= 8) { "Minimum Java must be at least 8" } @@ -69,6 +72,7 @@ class ProductDescriptor private constructor( } companion object { + /** Creates a new [Builder]. */ @JvmStatic fun builder(): Builder = Builder() diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/ProductId.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/product/ProductId.kt similarity index 95% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/ProductId.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/product/ProductId.kt index 78bf034b9..ebeb04623 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/ProductId.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/product/ProductId.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.updates +package org.pnfolder.pnlibrary.api.updates.product import java.util.Locale diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateChannel.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/product/UpdateChannel.kt similarity index 93% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateChannel.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/product/UpdateChannel.kt index 33afcc7bf..7dd2f1e93 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateChannel.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/product/UpdateChannel.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.updates +package org.pnfolder.pnlibrary.api.updates.product /** Release maturity accepted by an updater. Each channel includes more stable releases. */ enum class UpdateChannel { diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/InstalledProduct.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/InstalledProduct.kt index af6b3a773..8d13282c2 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/InstalledProduct.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/InstalledProduct.kt @@ -1,6 +1,6 @@ package org.pnfolder.pnlibrary.api.updates.release -import org.pnfolder.pnlibrary.api.updates.ProductId +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.updates.requireProvidedApi import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ProductChange.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ProductChange.kt index 633a6fbe3..c8a695a72 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ProductChange.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ProductChange.kt @@ -1,6 +1,6 @@ package org.pnfolder.pnlibrary.api.updates.release -import org.pnfolder.pnlibrary.api.updates.ProductId +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.version.SemanticVersion /** diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ProductDependency.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ProductDependency.kt index dba615191..5a06a498d 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ProductDependency.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ProductDependency.kt @@ -1,6 +1,6 @@ package org.pnfolder.pnlibrary.api.updates.release -import org.pnfolder.pnlibrary.api.updates.ProductId +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.version.SemanticVersion /** diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ProductRelease.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ProductRelease.kt index 5adfe5900..3f6e73b44 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ProductRelease.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ProductRelease.kt @@ -1,8 +1,8 @@ package org.pnfolder.pnlibrary.api.updates.release -import org.pnfolder.pnlibrary.api.dependencies.ExternalPluginDependency -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdateChannel +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.requireProvidedApi import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ReleaseSummary.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ReleaseSummary.kt index a10404e56..f7942e8da 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ReleaseSummary.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/release/ReleaseSummary.kt @@ -1,6 +1,6 @@ package org.pnfolder.pnlibrary.api.updates.release -import org.pnfolder.pnlibrary.api.updates.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import java.time.Instant /** diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/CatalogSource.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/request/CatalogSource.kt similarity index 98% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/CatalogSource.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/request/CatalogSource.kt index 3fa451dc0..a53cfcaea 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/CatalogSource.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/request/CatalogSource.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.updates +package org.pnfolder.pnlibrary.api.updates.request /** * Where a plugin's release catalog (`releases.json`) lives on GitHub: repository, branch (or tag or commit) and folder. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/PluginUpdateArtifact.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/request/PluginUpdateArtifact.kt similarity index 88% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/PluginUpdateArtifact.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/request/PluginUpdateArtifact.kt index 50178997f..2759438b5 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/PluginUpdateArtifact.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/request/PluginUpdateArtifact.kt @@ -1,6 +1,7 @@ -package org.pnfolder.pnlibrary.api.updates +package org.pnfolder.pnlibrary.api.updates.request import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.api.updates.javaInRange /** * Release-asset name pattern bounded to a range of Java feature versions. diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/PluginUpdateRequest.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest.kt similarity index 72% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/PluginUpdateRequest.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest.kt index e560eafd9..7dbb3f492 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/PluginUpdateRequest.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/request/PluginUpdateRequest.kt @@ -1,7 +1,12 @@ -package org.pnfolder.pnlibrary.api.updates +package org.pnfolder.pnlibrary.api.updates.request import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.api.updates.backup.BackupExport +import org.pnfolder.pnlibrary.api.updates.backup.BackupKind +import org.pnfolder.pnlibrary.api.updates.backup.BackupLabel import org.pnfolder.pnlibrary.api.updates.backup.UpdateConfigurationBackup +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.request.CatalogSource import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.PnLibraryApi import java.nio.file.Path @@ -11,14 +16,26 @@ import java.util.function.Supplier /** * Validated GitHub release and artifact-selection policy for one plugin. * - * Use [builder] to configure the repository (and, when its main branch is not `main`, the [catalog] branch), channel, and at least one artifact. When + * Use [builder] to configure the repository (and, when its main branch is not `main`, the [catalog] branch), channel and, optionally, artifact rules. When * ranges overlap, [artifactFor] chooses the compatible artifact with the highest * [PluginUpdateArtifact.minimumJava], allowing newer runtimes to receive newer builds. * + * Which file fits a server is decided by the release catalogue (`releases.json`): every file there names its platform + * and Java range, so a plugin with one jar needs no artifact rule: + * * ```kotlin * val request = PluginUpdateRequest.builder() * .repository("example", "ExamplePlugin") * .channel(UpdateChannel.STABLE) + * .build() + * ``` + * + * Declare [Builder.artifact] only when one repository ships different builds for different Java versions and the + * plugin wants to refuse to register on an unsupported one: + * + * ```kotlin + * PluginUpdateRequest.builder() + * .repository("example", "ExamplePlugin") * .artifact("(?i)^example-java8-.*\\.jar$", 8, 16) * .artifact("(?i)^example-java17-.*\\.jar$", 17) * .build() @@ -64,6 +81,9 @@ class PluginUpdateRequest private constructor(builder: Builder) { /** Explicit opt-in configuration backup; absent by default. */ val configurationBackup: UpdateConfigurationBackup? = builder.configurationBackup + /** Copies the plugin makes itself before an update; kept with the backup set and restored by hand. */ + val exports: List = Collections.unmodifiableList(ArrayList(builder.exports)) + /** Returns the most specific artifact compatible with [javaFeature], or `null`. */ fun artifactFor(javaFeature: Int): PluginUpdateArtifact? = artifacts .filter { it.supports(javaFeature) } @@ -86,12 +106,34 @@ class PluginUpdateRequest private constructor(builder: Builder) { internal val artifacts = mutableListOf() internal var supportedApi = ApiVersionRange(PnLibraryApi.VERSION, PnLibraryApi.VERSION) internal var configurationBackup: UpdateConfigurationBackup? = null + internal val exports = mutableListOf() + + /** Adds a copy that [export] writes to a file before updating, for data such as a MySQL database. A rollback does not restore it. */ + fun backupExport(kind: BackupKind, name: String, fileName: String, export: (Path) -> Unit): Builder = apply { + require(exports.none { it.fileName == fileName }) { "Export file names must differ" } + exports += BackupExport(kind, name, fileName, export) + } /** Preserves only [files] relative to the component's own [dataDirectory] before updating. */ - fun configurationBackup(dataDirectory: Path, vararg files: String): Builder = apply { - configurationBackup = UpdateConfigurationBackup(dataDirectory, files.toList()) + fun configurationBackup(dataDirectory: Path, vararg files: String): Builder = + backup(BackupKind.CONFIGURATION, "", dataDirectory, *files) + + /** + * Preserves [files] of the component's own [dataDirectory] before updating, and says what they are: a + * [kind] such as [BackupKind.DATABASE] and a short [name] the menu and commands show. May be called + * several times, but every call must name the same [dataDirectory]; a file may be declared once. + */ + fun backup(kind: BackupKind, name: String, dataDirectory: Path, vararg files: String): Builder = apply { + val previous = configurationBackup + val label = BackupLabel(kind, name) + val added = UpdateConfigurationBackup(dataDirectory, files.toList(), files.associate { it to label }) + configurationBackup = if (previous == null) added else { + require(previous.root == added.root) { "All backups of one component must use the same data directory" } + UpdateConfigurationBackup(previous.root, previous.files + added.files, previous.labels + added.labels) + } } + /** Sets the GitHub repository (owner and name) releases are read from. */ fun repository(owner: String, name: String): Builder = apply { require(owner.matches(REPOSITORY_PART) && name.matches(REPOSITORY_PART)) { "Invalid GitHub repository: $owner/$name" @@ -146,16 +188,19 @@ class PluginUpdateRequest private constructor(builder: Builder) { /** Enables or disables automatic verified downloads. */ fun automaticDownload(enabled: Boolean): Builder = apply { automaticDownload = enabled } + /** Sets the range of pnLibrary API versions the plugin build supports. */ fun supportedApi(minimum: Int, maximum: Int): Builder = apply { supportedApi = ApiVersionRange(minimum, maximum) } + /** Selects the release file with exactly this name, for the given Java range. */ @JvmOverloads fun exactArtifact(name: String, minimumJava: Int = 8, maximumJava: Int? = null): Builder = apply { require(name.isNotBlank()) { "Artifact name must not be blank" } artifact("^${Regex.escape(name)}$", minimumJava, maximumJava) } + /** Selects release files whose name matches [regex], for the given Java range. */ @JvmOverloads fun artifact(regex: String, minimumJava: Int, maximumJava: Int? = null): Builder = apply { Regex(regex) @@ -164,6 +209,7 @@ class PluginUpdateRequest private constructor(builder: Builder) { artifacts += PluginUpdateArtifact(regex, minimumJava, maximumJava) } + /** Selects release files matching [regex] on one [platform], for the given Java range. */ @JvmOverloads fun artifact(regex: String, platform: PlatformType, minimumJava: Int, maximumJava: Int? = null): Builder = apply { Regex(regex) @@ -175,7 +221,6 @@ class PluginUpdateRequest private constructor(builder: Builder) { /** Validates the complete policy and creates its immutable request. */ fun build(): PluginUpdateRequest { require(repositoryOwner.isNotBlank() && repositoryName.isNotBlank()) { "Repository is required" } - require(artifacts.isNotEmpty()) { "At least one artifact is required" } return PluginUpdateRequest(this) } } @@ -184,6 +229,7 @@ class PluginUpdateRequest private constructor(builder: Builder) { companion object { private val REPOSITORY_PART = Regex("[A-Za-z0-9_.-]+") + /** Creates a new [Builder]. */ @JvmStatic fun builder(): Builder = Builder() } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/BlockedReason.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/BlockedReason.kt similarity index 95% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/BlockedReason.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/BlockedReason.kt index cf3febded..ff1efccd6 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/BlockedReason.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/BlockedReason.kt @@ -1,5 +1,6 @@ -package org.pnfolder.pnlibrary.api.updates +package org.pnfolder.pnlibrary.api.updates.state +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateActor.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/UpdateActor.kt similarity index 92% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateActor.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/UpdateActor.kt index 33a0c3516..463045e99 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateActor.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/UpdateActor.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.updates +package org.pnfolder.pnlibrary.api.updates.state import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity @@ -33,7 +33,7 @@ data class UpdateActor(val kind: Kind, val id: String, val name: String) { companion object { /** Internal scheduled work, not an administrator command. */ @JvmField val SYSTEM = UpdateActor(Kind.SYSTEM, "system", PnLibraryIdentity.NAME) - /** Compatibility calls which did not supply an initiator. */ + /** Calls that did not supply an initiator. */ @JvmField val UNKNOWN = UpdateActor(Kind.UNKNOWN, "unknown", "Unknown") } } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdatePlanSnapshot.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/UpdatePlanSnapshot.kt similarity index 93% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdatePlanSnapshot.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/UpdatePlanSnapshot.kt index 8753c3f0c..811479722 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdatePlanSnapshot.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/UpdatePlanSnapshot.kt @@ -1,5 +1,6 @@ -package org.pnfolder.pnlibrary.api.updates +package org.pnfolder.pnlibrary.api.updates.state +import org.pnfolder.pnlibrary.api.updates.frozen import org.pnfolder.pnlibrary.api.updates.release.UpdatePlan import java.util.UUID diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateSnapshot.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/UpdateSnapshot.kt similarity index 69% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateSnapshot.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/UpdateSnapshot.kt index 71bc7bf83..8a53d57b4 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateSnapshot.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/UpdateSnapshot.kt @@ -1,5 +1,7 @@ -package org.pnfolder.pnlibrary.api.updates +package org.pnfolder.pnlibrary.api.updates.state +import org.pnfolder.pnlibrary.api.updates.frozen +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ReleaseSummary import org.pnfolder.pnlibrary.api.version.ApiVersionRange @@ -14,6 +16,8 @@ import org.pnfolder.pnlibrary.api.version.ApiVersionRange * @property currentJava Java feature version running the server * @property requiredJava minimum Java version of the selected artifact * @property automaticDownload whether checks may download a verified artifact automatically + + * @property javaBuilds Java versions the newest release has a build for on this platform and server, ascending; empty when unknown * @property releaseUrl public release page, when one is known * @property message failure or status detail intended for diagnostics, when present */ @@ -33,7 +37,15 @@ class UpdateSnapshot( /** pnLibrary API generations supported by this registration, when declared. */ val supportedApi: ApiVersionRange? = null, availableReleases: List = emptyList(), + javaBuilds: List = emptyList(), + /** The build the administrator chose, or `null` when the recommended one is used. */ + val javaBuild: Int? = null, + /** The build used when nothing is chosen: the one matching the installed product, else the newest. */ + val recommendedJava: Int? = null, ) { /** Immutable copy of known catalog releases, including channels not selected for installation. */ val availableReleases: List = availableReleases.frozen() + + /** Java versions the newest release has a build for on this platform and server, ascending. */ + val javaBuilds: List = javaBuilds.frozen() } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateState.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/UpdateState.kt similarity index 95% rename from modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateState.kt rename to modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/UpdateState.kt index fef9a13f3..1b64c8a75 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateState.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/updates/state/UpdateState.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.updates +package org.pnfolder.pnlibrary.api.updates.state /** Current observable phase of an update registration. */ enum class UpdateState { diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/PnLibraryApi.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/PnLibraryApi.kt index 2746ca6db..31e63619d 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/PnLibraryApi.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/PnLibraryApi.kt @@ -3,5 +3,5 @@ package org.pnfolder.pnlibrary.api.version /** Binary/public compatibility generation provided by this pnLibrary runtime. */ object PnLibraryApi { /** Current integer API generation, independent of the library semantic version. */ - const val VERSION: Int = 1 + const val VERSION: Int = 2 } diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/SemanticVersion.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/SemanticVersion.kt index 4aef395d9..dd6ad626b 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/SemanticVersion.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/SemanticVersion.kt @@ -64,8 +64,10 @@ class SemanticVersion private constructor( /** Returns whether two versions have equal SemVer precedence. */ override fun equals(other: Any?): Boolean = other is SemanticVersion && compareTo(other) == 0 + /** Hashes exactly the fields that participate in [equals]. */ - override fun hashCode(): Int = listOf(major, minor, patch, prerelease).hashCode() + override fun hashCode(): Int = 31 * (31 * (31 * major + minor) + patch) + prerelease.hashCode() + /** Returns the normalized version with prerelease identifiers; build metadata is omitted. */ override fun toString(): String = "$major.$minor.$patch" + prerelease.takeIf(List::isNotEmpty)?.joinToString(".", prefix = "-").orEmpty() diff --git a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/VersionRange.kt b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/VersionRange.kt index 315398384..9aba64c58 100644 --- a/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/VersionRange.kt +++ b/modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/VersionRange.kt @@ -7,16 +7,12 @@ package org.pnfolder.pnlibrary.api.version * Java: `VersionRange.closed("2.0.0", "3.0.0").contains(version)`. */ class VersionRange private constructor( - /** Lower boundary, or `null` when unbounded below. */ val minimum: SemanticVersion?, - /** Upper boundary, or `null` when unbounded above. */ val maximum: SemanticVersion?, - /** Whether [minimum] itself is included. Ignored when no minimum exists. */ val includeMinimum: Boolean, - /** Whether [maximum] itself is included. Ignored when no maximum exists. */ val includeMaximum: Boolean, ) { @@ -36,23 +32,32 @@ class VersionRange private constructor( /** Parses and checks a version string. */ fun contains(version: String): Boolean = contains(SemanticVersion.parse(version)) + /** Interval notation such as `[2.0.0, 3.0.0)`; a missing boundary is shown as `*`. */ + override fun toString(): String = + (if (includeMinimum) "[" else "(") + (minimum ?: "*") + ", " + (maximum ?: "*") + (if (includeMaximum) "]" else ")") + /** Factories for unbounded, one-sided, and closed semantic-version ranges. */ companion object { + /** Returns a range that accepts every version. */ @JvmStatic fun any(): VersionRange = VersionRange(null, null, true, true) + /** Returns a range accepting versions from [minimum], inclusive. */ @JvmStatic fun atLeast(minimum: String): VersionRange = VersionRange(SemanticVersion.parse(minimum), null, true, true) + /** Returns a range accepting versions above [minimum], exclusive. */ @JvmStatic fun greaterThan(minimum: String): VersionRange = VersionRange(SemanticVersion.parse(minimum), null, false, true) + /** Returns a range accepting versions from [minimum] to [maximum], both inclusive. */ @JvmStatic fun closed(minimum: String, maximum: String): VersionRange = VersionRange(SemanticVersion.parse(minimum), SemanticVersion.parse(maximum), true, true) + /** Returns a range accepting versions below [maximum], exclusive. */ @JvmStatic fun until(maximum: String): VersionRange = VersionRange(null, SemanticVersion.parse(maximum), true, false) diff --git a/modules/api/src/test/java/org/pnfolder/pnlibrary/api/architecture/ApiStyleJavaTest.java b/modules/api/src/test/java/org/pnfolder/pnlibrary/api/architecture/ApiStyleJavaTest.java index 8f3cfc573..878e58b42 100644 --- a/modules/api/src/test/java/org/pnfolder/pnlibrary/api/architecture/ApiStyleJavaTest.java +++ b/modules/api/src/test/java/org/pnfolder/pnlibrary/api/architecture/ApiStyleJavaTest.java @@ -1,16 +1,17 @@ package org.pnfolder.pnlibrary.api.architecture; +import org.pnfolder.pnlibrary.api.plugin.PluginAccess; + import org.junit.jupiter.api.Test; import org.pnfolder.pnlibrary.api.downloads.FileDownloads; -import org.pnfolder.pnlibrary.api.commands.CommandDefinition; -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAccess; +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition; import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRegistration; import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService; import org.pnfolder.pnlibrary.api.remote.DenyAction; import org.pnfolder.pnlibrary.api.remote.RemotePolicySettings; -import org.pnfolder.pnlibrary.api.tasks.TaskExecution; -import org.pnfolder.pnlibrary.api.tasks.TaskSpec; -import org.pnfolder.pnlibrary.api.updates.PluginUpdateRequest; +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution; +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec; +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest; import java.nio.file.Paths; import java.time.Duration; @@ -22,7 +23,7 @@ class ApiStyleJavaTest { private static PlaceholderRegistration registerPlaceholder(PlaceholderService service) { return service.register("status", String.class, placeholder -> placeholder .resolve(request -> "online") - .access(PlaceholderAccess.ownerOnly()) + .access(PluginAccess.ownerOnly()) .fallback("offline")); } diff --git a/modules/api/src/test/java/org/pnfolder/pnlibrary/api/architecture/ApiValidationJavaTest.java b/modules/api/src/test/java/org/pnfolder/pnlibrary/api/architecture/ApiValidationJavaTest.java index c7b7cce09..feedfee12 100644 --- a/modules/api/src/test/java/org/pnfolder/pnlibrary/api/architecture/ApiValidationJavaTest.java +++ b/modules/api/src/test/java/org/pnfolder/pnlibrary/api/architecture/ApiValidationJavaTest.java @@ -1,8 +1,8 @@ package org.pnfolder.pnlibrary.api.architecture; import org.junit.jupiter.api.Test; -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderKey; -import org.pnfolder.pnlibrary.api.tasks.TaskSpec; +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey; +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec; import java.time.Duration; diff --git a/modules/api/src/test/java/org/pnfolder/pnlibrary/api/updates/UpdateApiJavaTest.java b/modules/api/src/test/java/org/pnfolder/pnlibrary/api/updates/UpdateApiJavaTest.java index 907067d42..98578005d 100644 --- a/modules/api/src/test/java/org/pnfolder/pnlibrary/api/updates/UpdateApiJavaTest.java +++ b/modules/api/src/test/java/org/pnfolder/pnlibrary/api/updates/UpdateApiJavaTest.java @@ -1,6 +1,7 @@ package org.pnfolder.pnlibrary.api.updates; import org.junit.jupiter.api.Test; +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/architecture/BuilderArchitectureTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/architecture/BuilderArchitectureTest.kt index 32b99a1b1..1ee9da3ea 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/architecture/BuilderArchitectureTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/architecture/BuilderArchitectureTest.kt @@ -2,19 +2,19 @@ package org.pnfolder.pnlibrary.api.architecture import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.commands.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition import org.pnfolder.pnlibrary.api.config.ConfigOptions -import org.pnfolder.pnlibrary.api.config.ConfigTypeAccess -import org.pnfolder.pnlibrary.api.dependencies.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticConfiguration -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticContainer +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticContainer import org.pnfolder.pnlibrary.api.downloads.FileDownloads +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.remote.RemotePolicyContext import org.pnfolder.pnlibrary.api.remote.RemotePolicySettings -import org.pnfolder.pnlibrary.api.tasks.TaskQuery -import org.pnfolder.pnlibrary.api.tasks.TaskSpec -import org.pnfolder.pnlibrary.api.updates.PluginUpdateRequest -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor +import org.pnfolder.pnlibrary.api.tasks.info.TaskQuery +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest import java.lang.reflect.Modifier class BuilderArchitectureTest { @@ -23,7 +23,7 @@ class BuilderArchitectureTest { val entryPoints = listOf( Triple(CommandDefinition::class.java, arrayOf(String::class.java), "command"), Triple(ConfigOptions::class.java, emptyArray(), "config options"), - Triple(ConfigTypeAccess::class.java, emptyArray(), "config access"), + Triple(PluginAccess::class.java, emptyArray(), "plugin access"), Triple(DiagnosticConfiguration::class.java, arrayOf(String::class.java), "diagnostic configuration"), Triple(DiagnosticContainer::class.java, arrayOf(String::class.java), "diagnostic container"), Triple(FileDownloads::class.java, emptyArray(), "file downloads"), diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/architecture/SourceConventionsTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/architecture/SourceConventionsTest.kt index d6c44d3ed..79a29406d 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/architecture/SourceConventionsTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/architecture/SourceConventionsTest.kt @@ -115,10 +115,10 @@ class SourceConventionsTest { * from reports, and KDoc describing accepted input. Example plugins are left out: they show plain Bukkit use. */ val LEGACY_TEXT_ALLOWED = setOf( - "modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/ComponentSerializerType.kt", + "modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/text/serializer/ComponentSerializerType.kt", "modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/CachedComponents.kt", - "modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticRedactor.kt", - "modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuColors.kt", + "modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/redaction/DiagnosticRedactor.kt", + "modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuColors.kt", "modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyCommandSettings.kt", "platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemText.kt", "platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/HexColors.kt", diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/audiences/AudienceContractsTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/audiences/AudienceContractsTest.kt index 25b6cb938..5e5667fc4 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/audiences/AudienceContractsTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/audiences/AudienceContractsTest.kt @@ -7,6 +7,10 @@ import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.audiences.Delivery +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.audiences.player.PlayerCapability +import org.pnfolder.pnlibrary.api.audiences.player.PlayerEffect +import org.pnfolder.pnlibrary.api.audiences.player.PlayerParticle import java.util.UUID class AudienceContractsTest { diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/chat/ChatKitTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/chat/ChatKitTest.kt new file mode 100644 index 000000000..d962b6b42 --- /dev/null +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/chat/ChatKitTest.kt @@ -0,0 +1,96 @@ +package org.pnfolder.pnlibrary.api.chat + +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.TextComponent +import net.kyori.adventure.text.event.ClickEvent +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone + +class ChatKitTest { + private val player = ChatKit(ChatReader.PLAYER) + private val console = ChatKit(ChatReader.CONSOLE) + + private fun plain(component: Component): String = + ((component as? TextComponent)?.content()?.toString().orEmpty()) + component.children().joinToString("") { plain(it) } + + @Test + fun `only https links without credentials are safe`() { + assertTrue(player.safeLink("https://example.org/page")) + assertFalse(player.safeLink("http://example.org/page")) + assertFalse(player.safeLink("https://user:pass@example.org/")) + assertFalse(player.safeLink("javascript:alert(1)")) + assertFalse(player.safeLink("https://")) + assertFalse(player.safeLink("not a link")) + assertFalse(player.safeLink("https://example.org/" + "a".repeat(5000))) + } + + @Test + fun `a link button is left out for an unsafe link or a reader that cannot click`() { + assertEquals(Component.empty(), player.linkButton("open", "http://example.org", "hint", ChatPalette.ACCENT)) + assertEquals(Component.empty(), console.linkButton("open", "https://example.org", "hint", ChatPalette.ACCENT)) + assertNotNull(player.linkButton("open", "https://example.org", "hint", ChatPalette.ACCENT).clickEvent()) + } + + @Test + fun `a command button runs its command and a console gets none`() { + val click = player.button("[Go]", "/pn go", "hint", ChatPalette.ACCENT).clickEvent() + + assertEquals(ClickEvent.Action.RUN_COMMAND, click?.action()) + assertEquals("[Go]", plain(player.button("[Go]", "/pn go", "hint", ChatPalette.ACCENT))) + assertEquals(Component.empty(), console.button("Go", "/pn go", "hint", ChatPalette.ACCENT)) + } + + @Test + fun `the console gets ascii stand-ins and keeps cyrillic`() { + assertEquals("a -> b - ok...", console.shown("a → b — ok…")) + assertEquals("Привет ёЁ", console.shown("Привет ёЁ")) + assertEquals("a?b", console.shown("a☃b")) + assertEquals("a → b", player.shown("a → b")) + } + + @Test + fun `a notice shows the mark, the text and a detail line`() { + val lines = player.notice(ChatNotice(ChatTone.FAILURE, "Не вышло", "причина")) + + assertEquals(2, lines.size) + assertTrue(plain(lines[0]).endsWith("Не вышло")) + assertEquals(" причина", plain(lines[1])) + assertEquals(1, player.notice(ChatNotice(ChatTone.INFO, "Готово", null)).size) + } + + @Test + fun `an overlong message is cut`() { + val line = plain(player.notice(ChatNotice(ChatTone.INFO, "x".repeat(2000), null)).single()) + + assertTrue(line.length < 600) + } + + @Test + fun `a confirmation tells a reader who cannot click which command to type`() { + val page = console.confirmation("Удалить", listOf("Это нельзя отменить."), "Да", "/pn delete 1", "hint") + val text = page.joinToString("\n") { plain(it) } + + assertTrue(text.contains("/pn delete 1")) + assertTrue(page.all { it.clickEvent() == null }) + } + + @Test + fun `command hints make the command clickable only for readers who can click`() { + val hint = player.commandHints("/pn give [amount]" to "выдать").last() + + assertEquals(ClickEvent.Action.SUGGEST_COMMAND, hint.clickEvent()?.action()) + assertEquals("/pn give ", hint.clickEvent()?.value()) + assertNull(console.commandHints("/pn give " to "выдать").last().clickEvent()) + } + + @Test + fun `a page starts with an empty line`() { + assertEquals(Component.empty(), player.framed(listOf(player.header("T"))).first()) + } +} diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/commands/CommandBuilderTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/commands/definition/CommandBuilderTest.kt similarity index 94% rename from modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/commands/CommandBuilderTest.kt rename to modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/commands/definition/CommandBuilderTest.kt index 23207ee34..886074d0f 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/commands/CommandBuilderTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/commands/definition/CommandBuilderTest.kt @@ -1,10 +1,12 @@ -package org.pnfolder.pnlibrary.api.commands +package org.pnfolder.pnlibrary.api.commands.definition import net.kyori.adventure.text.Component import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.CommandSender import java.util.Locale class CommandBuilderTest { diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/commands/CommandTreeBuilderTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/commands/definition/CommandTreeBuilderTest.kt similarity index 95% rename from modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/commands/CommandTreeBuilderTest.kt rename to modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/commands/definition/CommandTreeBuilderTest.kt index 92c927c88..fd8993d5d 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/commands/CommandTreeBuilderTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/commands/definition/CommandTreeBuilderTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.api.commands +package org.pnfolder.pnlibrary.api.commands.definition import net.kyori.adventure.text.Component import org.junit.jupiter.api.Assertions.assertEquals @@ -6,6 +6,8 @@ import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.CommandSender import java.math.BigDecimal import java.util.function.Consumer diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/dependencies/ExternalArtifactTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/dependencies/ExternalArtifactTest.kt new file mode 100644 index 000000000..705af06d5 --- /dev/null +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/dependencies/ExternalArtifactTest.kt @@ -0,0 +1,76 @@ +package org.pnfolder.pnlibrary.api.dependencies + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalArtifact +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.platform.PlatformType +import java.net.URI + +class ExternalArtifactTest { + private fun file(vararg extra: Pair): ExternalArtifact { + val options = extra.toMap() + @Suppress("UNCHECKED_CAST") + return ExternalArtifact( + URI("https://example.org/x.jar"), null, + platforms = options["platforms"] as? Set ?: emptySet(), + minecraftFrom = options["from"] as? String, + minecraftBefore = options["before"] as? String, + ) + } + + @Test + fun `a file without limits fits every server`() { + assertTrue(file().fits(PlatformType.VELOCITY, null)) + assertTrue(file().fits(PlatformType.BUKKIT, "1.21.4")) + } + + @Test + fun `the minecraft range includes its start and leaves out its end`() { + val range = file("from" to "1.20", "before" to "1.21") + + assertTrue(range.fits(PlatformType.BUKKIT, "1.20")) + assertTrue(range.fits(PlatformType.BUKKIT, "1.20.6")) + assertFalse(range.fits(PlatformType.BUKKIT, "1.21")) + assertFalse(range.fits(PlatformType.BUKKIT, "1.19.4")) + } + + @Test + fun `an unknown minecraft version fits no ranged file`() { + assertFalse(file("from" to "1.20").fits(PlatformType.BUKKIT, null)) + assertFalse(file("from" to "1.20").fits(PlatformType.VELOCITY, "not a version")) + } + + @Test + fun `a platform limit is respected`() { + val proxy = file("platforms" to setOf(PlatformType.VELOCITY)) + + assertTrue(proxy.fits(PlatformType.VELOCITY, null)) + assertFalse(proxy.fits(PlatformType.BUKKIT, "1.21")) + } + + @Test + fun `bad input is refused`() { + assertThrows(IllegalArgumentException::class.java) { ExternalArtifact(URI("http://example.org/x.jar"), null) } + assertThrows(IllegalArgumentException::class.java) { ExternalArtifact(URI("https://example.org/x.jar"), "short") } + assertThrows(IllegalArgumentException::class.java) { ExternalArtifact(URI("https://example.org/x.jar"), null, minecraftFrom = "latest") } + assertThrows(IllegalArgumentException::class.java) { ExternalArtifact(URI("https://example.org/x.jar"), null, maxBytes = 0) } + } + + @Test + fun `the first fitting variant wins and the general file is the fallback`() { + val dependency = ExternalPluginDependency.builder("Vault", "1.7.0") + .variant("https://example.org/old.jar", minecraftBefore = "1.20") + .variant("https://example.org/new.jar", minecraftFrom = "1.20") + .url("https://example.org/general.jar") + .build() + + assertEquals("old.jar", dependency.artifactFor(PlatformType.BUKKIT, "1.16.5")?.uri?.path?.substringAfterLast('/')) + assertEquals("new.jar", dependency.artifactFor(PlatformType.BUKKIT, "1.21.4")?.uri?.path?.substringAfterLast('/')) + assertEquals("general.jar", dependency.artifactFor(PlatformType.VELOCITY, null)?.uri?.path?.substringAfterLast('/')) + assertEquals("general.jar", dependency.artifact?.uri?.path?.substringAfterLast('/')) + } +} diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/dependencies/VersionConstraintTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/dependencies/VersionConstraintTest.kt new file mode 100644 index 000000000..f82eaf5d1 --- /dev/null +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/dependencies/VersionConstraintTest.kt @@ -0,0 +1,34 @@ +package org.pnfolder.pnlibrary.api.dependencies + +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.version.SemanticVersion + +class VersionConstraintTest { + private fun v(text: String) = SemanticVersion.parse(text) + + @Test + fun `the minimum is included and older versions are refused`() { + val constraint = VersionConstraint(v("1.7.0")) + + assertTrue(constraint.accepts(v("1.7.0"))) + assertTrue(constraint.accepts(v("9.0.0"))) + assertFalse(constraint.accepts(v("1.6.9"))) + } + + @Test + fun `an inclusive maximum keeps itself and an exclusive one does not`() { + assertTrue(VersionConstraint(v("1.0.0"), maximumInclusive = v("2.0.0")).accepts(v("2.0.0"))) + assertFalse(VersionConstraint(v("1.0.0"), maximumExclusive = v("2.0.0")).accepts(v("2.0.0"))) + assertTrue(VersionConstraint(v("1.0.0"), maximumExclusive = v("2.0.0")).accepts(v("1.9.9"))) + } + + @Test + fun `contradicting bounds are refused`() { + assertThrows(IllegalArgumentException::class.java) { VersionConstraint(v("1.0.0"), v("2.0.0"), v("3.0.0")) } + assertThrows(IllegalArgumentException::class.java) { VersionConstraint(v("2.0.0"), maximumInclusive = v("1.0.0")) } + assertThrows(IllegalArgumentException::class.java) { VersionConstraint(v("2.0.0"), maximumExclusive = v("2.0.0")) } + } +} diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticApiConsistencyTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticApiConsistencyTest.kt index 8d5b9f2c4..36bfc2f1e 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticApiConsistencyTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/diagnostics/DiagnosticApiConsistencyTest.kt @@ -3,6 +3,7 @@ package org.pnfolder.pnlibrary.api.diagnostics import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticContainer import java.util.function.Supplier class DiagnosticApiConsistencyTest { diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/expansions/AbstractExpansionTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/expansions/AbstractExpansionTest.kt new file mode 100644 index 000000000..4d2a37313 --- /dev/null +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/expansions/AbstractExpansionTest.kt @@ -0,0 +1,79 @@ +package org.pnfolder.pnlibrary.api.expansions + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test + +class AbstractExpansionTest { + private class Probe(var failEnable: Boolean = false, var failDisable: Boolean = false) : AbstractExpansion("probe") { + val calls = mutableListOf() + + override fun onEnable() { + calls += "enable" + if (failEnable) error("no enable") + } + + override fun onDisable() { + calls += "disable" + if (failDisable) error("no disable") + } + + override fun onClose() { + calls += "close" + } + } + + @Test + fun `enable and disable move the state and call hooks once`() { + val probe = Probe() + probe.enable() + probe.enable() + assertEquals(ExpansionState.ENABLED, probe.state) + probe.disable() + probe.disable() + + assertEquals(ExpansionState.DISABLED, probe.state) + assertEquals(listOf("enable", "disable"), probe.calls) + } + + @Test + fun `a failed enable marks the expansion failed and may be retried`() { + val probe = Probe(failEnable = true) + assertThrows(IllegalStateException::class.java) { probe.enable() } + assertEquals(ExpansionState.FAILED, probe.state) + + probe.failEnable = false + probe.enable() + assertEquals(ExpansionState.ENABLED, probe.state) + } + + @Test + fun `close releases an enabled expansion then closes it for good`() { + val probe = Probe() + probe.enable() + probe.close() + probe.close() + probe.enable() + + assertEquals(ExpansionState.CLOSED, probe.state) + assertEquals(listOf("enable", "disable", "close"), probe.calls) + } + + @Test + fun `closing a disabled expansion skips onDisable`() { + val probe = Probe() + probe.close() + + assertEquals(listOf("close"), probe.calls) + } + + @Test + fun `a failing onDisable still ends in the target state and closes`() { + val probe = Probe(failDisable = true) + probe.enable() + assertThrows(IllegalStateException::class.java) { probe.close() } + + assertEquals(ExpansionState.CLOSED, probe.state) + assertEquals(listOf("enable", "disable", "close"), probe.calls) + } +} diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/libraries/ModuleLibraryTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/libraries/ModuleLibraryTest.kt new file mode 100644 index 000000000..b6f449b8f --- /dev/null +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/libraries/ModuleLibraryTest.kt @@ -0,0 +1,88 @@ +package org.pnfolder.pnlibrary.api.libraries + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.platform.PlatformType + +class ModuleLibraryTest { + @Test + fun `sources are tried in the given order and Maven Central last`() { + val library = ModuleLibrary.builder("com.zaxxer", "HikariCP", "5.1.0") + .source { repository("https://one.example/maven/") }.source { link("https://files.example/a.jar") }.build() + + assertEquals(listOf("https://one.example/maven/", "https://files.example/a.jar", ModuleLibrary.CENTRAL), library.allSources.map { it.url }) + assertEquals(listOf(false, true, false), library.allSources.map { it.direct }) + assertEquals("com.zaxxer:HikariCP:5.1.0", library.coordinates) + assertEquals(LibraryScope.PLUGIN, library.scope) + assertTrue(library.required) + assertEquals(listOf(ModuleLibrary.CENTRAL), ModuleLibrary.of("g:a:1").allSources.map { it.url }) + } + + @Test + fun `Maven Central can be turned off`() { + val own = ModuleLibrary.builder("g", "a", "1").source { repository("https://one.example/") }.mavenCentral(false).build() + assertEquals(listOf("https://one.example/"), own.allSources.map { it.url }) + } + + @Test + fun `settings are checked when the library is built`() { + assertThrows(IllegalArgumentException::class.java) { ModuleLibrary.builder("g", "a", "1").source { repository("http://plain.example/") } } + assertThrows(IllegalArgumentException::class.java) { ModuleLibrary.builder("g", "a", "1").source { link("https://x.example/a.jar").sha256("abc") } } + assertThrows(IllegalArgumentException::class.java) { ModuleLibrary.builder("g /x", "a", "1").build() } + assertThrows(IllegalArgumentException::class.java) { ModuleLibrary.of("only:two") } + assertThrows(IllegalStateException::class.java) { LibrarySource.builder().build() } + } + + @Test + fun `scope and optional change how the library is loaded`() { + val library = ModuleLibrary.builder("g", "a", "1").scope(LibraryScope.ISOLATED).optional().build() + + assertTrue(library.isolated) + assertFalse(library.required) + assertEquals("g:a:1:shaded", ModuleLibrary.of("g:a:1:shaded").coordinates) + } + + @Test + fun `every source has an address, a sum and a name of its own`() { + val one = "A".repeat(64) + val library = ModuleLibrary.builder("g", "a", "1") + .source { link("https://cdn.example/a.jar").sha256(one).name("CDN").description(" Быстрый ") } + .source { repository("https://mirror.example/") }.build() + + val all = library.allSources + assertEquals("a".repeat(64), all[0].sha256) + assertEquals("CDN", all[0].name) + assertEquals("Быстрый", all[0].description) + assertEquals(null, all[1].description) + assertTrue(all[0].direct) + assertEquals("mirror.example", all[1].name) + assertEquals(null, all[1].sha256) + } + + @Test + fun `a library can be limited to some platforms`() { + val any = ModuleLibrary.of("g:a:1") + val bukkit = ModuleLibrary.builder("g", "a", "1").platforms(PlatformType.BUKKIT).build() + + assertTrue(any.appliesTo(PlatformType.VELOCITY)) + assertTrue(bukkit.appliesTo(PlatformType.BUKKIT)) + assertFalse(bukkit.appliesTo(PlatformType.VELOCITY)) + assertTrue(bukkit.appliesTo(null)) + assertThrows(IllegalArgumentException::class.java) { ModuleLibrary.builder("g", "a", "1").platforms(PlatformType.UNIVERSAL) } + } + + @Test + fun `a library has a readable title and description`() { + val plain = ModuleLibrary.of("com.zaxxer:HikariCP:5.1.0") + val named = ModuleLibrary.builder("com.zaxxer", "HikariCP", "5.1.0") + .title("Пул соединений").description(" Держит открытые соединения с базой. ").build() + + assertEquals("HikariCP", plain.title) + assertEquals(null, plain.description) + assertEquals("Пул соединений", named.title) + assertEquals("Держит открытые соединения с базой.", named.description) + } +} diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsCredentialsTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsCredentialsTest.kt index d35ab9760..c6489d93a 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsCredentialsTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/metrics/MetricsCredentialsTest.kt @@ -4,6 +4,9 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsCredentials +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration class MetricsCredentialsTest { diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/observability/ObservabilityDslTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/observability/ObservabilityDslTest.kt index f6dffb254..2c7e7f840 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/observability/ObservabilityDslTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/observability/ObservabilityDslTest.kt @@ -3,6 +3,13 @@ package org.pnfolder.pnlibrary.api.observability import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.observability.observation.Observation +import org.pnfolder.pnlibrary.api.observability.observation.ObservationLevel +import org.pnfolder.pnlibrary.api.observability.observation.ObservationQuery +import org.pnfolder.pnlibrary.api.observability.observation.ObservationRequest +import org.pnfolder.pnlibrary.api.observability.report.ComponentStatus +import org.pnfolder.pnlibrary.api.observability.report.ObservabilityReport +import org.pnfolder.pnlibrary.api.observability.report.ObservabilityReportRequest import java.nio.file.Paths class ObservabilityDslTest { diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAccessTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAccessTest.kt index af85a82b0..99c8c0639 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAccessTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/placeholders/PlaceholderAccessTest.kt @@ -5,12 +5,13 @@ import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId class PlaceholderAccessTest { @Test fun `patterns are trimmed and matched case-insensitively`() { - val access = PlaceholderAccess.builder().allowMatching(" admin-* ").deny("admin-untrusted").build() + val access = PluginAccess.builder().allowMatching(" admin-* ").deny("admin-untrusted").build() val owner = PluginId.of("owner") assertEquals(setOf("admin-*"), access.allowedPatterns) @@ -21,6 +22,6 @@ class PlaceholderAccessTest { @Test fun `blank patterns are rejected`() { - assertThrows(IllegalArgumentException::class.java) { PlaceholderAccess.builder().allowMatching(" ") } + assertThrows(IllegalArgumentException::class.java) { PluginAccess.builder().allowMatching(" ") } } } diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/plugin/DependencyBuilderTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/plugin/DependencyBuilderTest.kt index 5eb0cf4a2..8ca3be440 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/plugin/DependencyBuilderTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/plugin/DependencyBuilderTest.kt @@ -6,8 +6,8 @@ import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.dependencies.DependencyBuilder import org.pnfolder.pnlibrary.api.dependencies.DownloadPolicy -import org.pnfolder.pnlibrary.api.dependencies.ExternalPluginDependency -import org.pnfolder.pnlibrary.api.dependencies.ManagedProductDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ManagedProductDependency import org.pnfolder.pnlibrary.api.version.SemanticVersion class DependencyBuilderTest { @@ -21,7 +21,6 @@ class DependencyBuilderTest { }.build().single() as ExternalPluginDependency assertTrue(dependency.minimumVersion == SemanticVersion.parse("1.7.3")) - assertTrue(dependency.artifact?.size == null) assertTrue(dependency.artifact?.sha256 == null) assertTrue(dependency.downloadPolicy == DownloadPolicy.AUTOMATIC) } @@ -58,7 +57,7 @@ class DependencyBuilderTest { val builder = DependencyBuilder() builder.plugin("Legacy") { it.minimumVersion("2.0.0") - .artifact("https://example.org/Legacy-2.0.0.jar", 128, "a".repeat(64)) + .artifact("https://example.org/Legacy-2.0.0.jar", "a".repeat(64)) .downloadPolicy(DownloadPolicy.FORCED) } diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/plugin/MetricsBuilderTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/plugin/MetricsBuilderTest.kt index daf27b124..967409c15 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/plugin/MetricsBuilderTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/plugin/MetricsBuilderTest.kt @@ -4,9 +4,9 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.metrics.MetricsBuilder -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsBuilder +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider import org.pnfolder.pnlibrary.api.platform.PlatformType import java.util.function.Supplier diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginDependencyTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginDependencyTest.kt index 67c7308fd..7b167b9a4 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginDependencyTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginDependencyTest.kt @@ -22,7 +22,7 @@ class PluginDependencyTest { fun `dependency can explicitly override automatic download policy`() { val dependency = Dependencies.plugin( "OptionalPlugin", "1.0.0", "https://example.org/plugin.jar", - size = 4, sha256 = "00".repeat(32), required = false, + sha256 = "00".repeat(32), required = false, automaticDownload = true, forceAutomaticDownload = true, ) assertTrue(dependency.forceAutomaticDownload) diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/ScheduledTaskTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/ScheduledTaskTest.kt new file mode 100644 index 000000000..f21aae438 --- /dev/null +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/ScheduledTaskTest.kt @@ -0,0 +1,49 @@ +package org.pnfolder.pnlibrary.api.tasks + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.tasks.run.TaskContext +import org.pnfolder.pnlibrary.api.tasks.spec.ScheduledTask +import org.pnfolder.pnlibrary.api.tasks.spec.TaskConflictPolicy +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import java.time.Duration + +class ScheduledTaskTest { + private class Autosave(private val world: String) : ScheduledTask() { + var active = true + override val name get() = "Autosave $world" + override val key get() = "autosave-$world" + override val interval: Duration get() = Duration.ofMinutes(5) + override val execution get() = TaskExecution.async() + override val tags get() = setOf("save") + + override fun shouldRun() = active + + override fun run(context: TaskContext) = Unit + } + + @Test + fun `a task class becomes a spec with its own arguments`() { + val spec = Autosave("nether").toSpec() + + assertEquals("Autosave nether", spec.name) + assertEquals("autosave-nether", spec.key) + assertEquals(Duration.ofMinutes(5), spec.interval) + assertEquals(TaskExecution.Kind.ASYNC, spec.execution.kind) + assertEquals(setOf("save"), spec.tags) + assertEquals(TaskConflictPolicy.REJECT, spec.conflictPolicy) + } + + @Test + fun `the run conditions follow the task`() { + val task = Autosave("world") + val spec = task.toSpec() + + assertTrue(spec.conditions.all { it.asBoolean }) + task.active = false + assertFalse(spec.conditions.all { it.asBoolean }) + assertFalse(spec.cancellationConditions.any { it.asBoolean }) + } +} diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskContextTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskContextTest.kt new file mode 100644 index 000000000..1d73221b7 --- /dev/null +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskContextTest.kt @@ -0,0 +1,62 @@ +package org.pnfolder.pnlibrary.api.tasks + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.run.TaskContext +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec +import java.time.Duration +import java.time.Instant + +class TaskContextTest { + private class FakeContext( + override val runNumber: Long, + override val scheduledAt: Instant = Instant.EPOCH, + override val startedAt: Instant = Instant.EPOCH, + override val interval: Duration? = null, + ) : TaskContext { + var cancelled = false + override val id = TaskId("t") + override val name: String? = null + override val key: String? = null + override val parentId: TaskId? = null + override val tags: Set = emptySet() + override val executionKind = TaskExecution.Kind.GLOBAL + override val execution = TaskExecution.global() + override fun spawn(spec: TaskSpec): TaskHandle = error("not needed") + override val skippedCount = 0L + override val previousStartedAt: Instant? = null + override val isCancelled get() = cancelled + override fun cancel() { cancelled = true } + override fun snapshot(): TaskSnapshot = error("not needed") + } + + @Test + fun `run counters answer first, every and cancel after`() { + assertTrue(FakeContext(1).isFirstRun) + assertFalse(FakeContext(2).isFirstRun) + assertTrue(FakeContext(10).every(5)) + assertFalse(FakeContext(11).every(5)) + assertThrows(IllegalArgumentException::class.java) { FakeContext(1).every(0) } + + val early = FakeContext(2) + assertFalse(early.cancelAfter(3)) + assertFalse(early.cancelled) + val last = FakeContext(3) + assertTrue(last.cancelAfter(3)) + assertTrue(last.cancelled) + } + + @Test + fun `lag is never negative and repeating follows the interval`() { + assertEquals(Duration.ofMillis(300), FakeContext(1, Instant.EPOCH, Instant.ofEpochMilli(300)).lag) + assertEquals(Duration.ZERO, FakeContext(1, Instant.ofEpochMilli(500), Instant.EPOCH).lag) + assertTrue(FakeContext(1, interval = Duration.ofSeconds(1)).isRepeating) + assertFalse(FakeContext(1).isRepeating) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskQueryMatcherTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskQueryMatchTest.kt similarity index 51% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskQueryMatcherTest.kt rename to modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskQueryMatchTest.kt index 9960cdd2b..96ba9a790 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskQueryMatcherTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskQueryMatchTest.kt @@ -1,16 +1,17 @@ -package org.pnfolder.pnlibrary.core.tasks +package org.pnfolder.pnlibrary.api.tasks +import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskId -import org.pnfolder.pnlibrary.api.tasks.TaskQuery -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskQuery +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import java.time.Instant -class TaskQueryMatcherTest { +class TaskQueryMatchTest { private val snapshot = TaskSnapshot( id = TaskId("task-1"), name = "Refresh player cache", @@ -39,13 +40,23 @@ class TaskQueryMatcherTest { .tag("cache") .build() - assertTrue(TaskQueryMatcher.matches(snapshot, query)) + assertTrue(query.matches(snapshot)) } @Test fun `rejects snapshot when any criterion differs`() { - assertFalse(TaskQueryMatcher.matches(snapshot, TaskQuery.builder().key("other").build())) - assertFalse(TaskQueryMatcher.matches(snapshot, TaskQuery.builder().status(TaskStatus.FAILED).build())) - assertFalse(TaskQueryMatcher.matches(snapshot, TaskQuery.builder().tag("database").build())) + assertFalse(TaskQuery.builder().key("other").build().matches(snapshot)) + assertFalse(TaskQuery.builder().status(TaskStatus.FAILED).build().matches(snapshot)) + assertFalse(TaskQuery.builder().tag("database").build().matches(snapshot)) + } + + @Test + fun `terminal statuses and the active flag agree`() { + assertEquals( + setOf(TaskStatus.COMPLETED, TaskStatus.CANCELLED, TaskStatus.FAILED), + TaskStatus.entries.filter { it.isTerminal }.toSet(), + ) + assertTrue(snapshot.isActive) + assertFalse(snapshot.copy(status = TaskStatus.FAILED).isActive) } } diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskQueryTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskQueryTest.kt index 06b67e12b..3f7e2dfd5 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskQueryTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskQueryTest.kt @@ -3,6 +3,10 @@ package org.pnfolder.pnlibrary.api.tasks import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.tasks.info.TaskQuery +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec import java.util.function.BooleanSupplier class TaskQueryTest { diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskSpecTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskSpecTest.kt index b5f1025e6..1b033817b 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskSpecTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/tasks/TaskSpecTest.kt @@ -6,6 +6,9 @@ import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec import java.time.Duration class TaskSpecTest { diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/text/ComponentCacheTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/text/ComponentCacheTest.kt new file mode 100644 index 000000000..e16d3561a --- /dev/null +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/text/ComponentCacheTest.kt @@ -0,0 +1,24 @@ +package org.pnfolder.pnlibrary.api.text + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.text.cache.ComponentCachePolicy +import org.pnfolder.pnlibrary.api.text.cache.ComponentCacheScope +import org.pnfolder.pnlibrary.api.text.cache.ComponentCacheStatistics + +class ComponentCacheTest { + @Test + fun `statistics count lookups and the hit rate`() { + assertEquals(0.0, ComponentCacheStatistics(0, 0, 0, 0).hitRate) + val stats = ComponentCacheStatistics(hits = 3, misses = 1, evictions = 0, size = 4) + assertEquals(4, stats.lookups) + assertEquals(0.75, stats.hitRate) + } + + @Test + fun `the disabled policy never caches and limits must be positive`() { + assertEquals(ComponentCacheScope.NONE, ComponentCachePolicy.DISABLED.scope) + assertThrows(IllegalArgumentException::class.java) { ComponentCachePolicy(maximumEntries = 0) } + } +} diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/PluginUpdateRequestTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/PluginUpdateRequestTest.kt index ded7701cb..4d07774bc 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/PluginUpdateRequestTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/PluginUpdateRequestTest.kt @@ -5,6 +5,8 @@ import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.PnLibraryApi @@ -21,6 +23,13 @@ class PluginUpdateRequestTest { assertEquals(PlatformType.BUKKIT, request.artifacts.single().platform) } + @Test + fun `a plugin with one jar needs no artifact rule`() { + val request = PluginUpdateRequest.builder().repository("pnFolder", "pnCases").build() + + assertTrue(request.artifacts.isEmpty()) + } + @Test fun `channel defaults to stable and may be fixed or supplied by the plugin`() { fun request(configure: PluginUpdateRequest.Builder.() -> Unit) = PluginUpdateRequest.builder() diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/ProductModelTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/ProductModelTest.kt index 3cb866700..1039fc5a8 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/ProductModelTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/ProductModelTest.kt @@ -3,6 +3,8 @@ package org.pnfolder.pnlibrary.api.updates import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest class ProductModelTest { @Test diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateApiConsistencyTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateApiConsistencyTest.kt index cc537d420..68fd179da 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateApiConsistencyTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateApiConsistencyTest.kt @@ -5,7 +5,12 @@ import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.dependencies.PluginDependency +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ReleaseSummary +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import java.util.Collections class UpdateApiConsistencyTest { @@ -44,17 +49,23 @@ class UpdateApiConsistencyTest { dependencies: List, ) = registration - override fun all(): List = Collections.unmodifiableList(listOf(registration)) - override fun get(product: String): UpdateRegistration? = - registration.takeIf { product.equals("product", true) } + override val products = object : UpdateProducts { + override fun all(): List = Collections.unmodifiableList(listOf(registration)) + override fun get(product: String): UpdateRegistration? = + registration.takeIf { product.equals("product", true) } + } + override val plans: UpdatePlans get() = error("not used") + override val settings: UpdateSettings get() = error("not used") + override val backups: UpdateBackups get() = error("not used") + override val history: UpdateHistory get() = error("not used") } - assertSame(registration, service.get("PRODUCT")) - assertSame(registration, service.require("product")) - assertThrows(IllegalStateException::class.java) { service.require("missing") } + assertSame(registration, service.products.get("PRODUCT")) + assertSame(registration, service.products.require("product")) + assertThrows(IllegalStateException::class.java) { service.products.require("missing") } assertThrows(UnsupportedOperationException::class.java) { @Suppress("UNCHECKED_CAST") - (service.all() as MutableList).clear() + (service.products.all() as MutableList).clear() } } } diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateModelTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateModelTest.kt index fba37c2b4..67f8f7b9b 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateModelTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/UpdateModelTest.kt @@ -5,8 +5,11 @@ import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.dependencies.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ArtifactDescriptor import org.pnfolder.pnlibrary.api.updates.release.ProductDependency import org.pnfolder.pnlibrary.api.updates.release.ProductRelease @@ -77,7 +80,7 @@ class UpdateModelTest { fun `automatic external dependency requires secure complete artifact`() { assertThrows(IllegalArgumentException::class.java) { ExternalPluginDependency.builder("Vault", "1.7.3") - .artifact("http://example.test/vault.jar", 10, "00".repeat(32)) + .artifact("http://example.test/vault.jar", "00".repeat(32)) .build() } val manual = ExternalPluginDependency.builder("Vault", "1.7.3") diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/UpdatePlanSnapshotTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/UpdatePlanSnapshotTest.kt index f91b34217..a321f09f0 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/UpdatePlanSnapshotTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/UpdatePlanSnapshotTest.kt @@ -3,12 +3,16 @@ package org.pnfolder.pnlibrary.api.updates import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.dependencies.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ArtifactDescriptor import org.pnfolder.pnlibrary.api.updates.release.ProductChange import org.pnfolder.pnlibrary.api.updates.release.ProductDependency import org.pnfolder.pnlibrary.api.updates.release.ProductRelease import org.pnfolder.pnlibrary.api.updates.release.UpdatePlan +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion import java.util.UUID diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/backup/BackupExportTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/backup/BackupExportTest.kt new file mode 100644 index 000000000..a9efbfef5 --- /dev/null +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/updates/backup/BackupExportTest.kt @@ -0,0 +1,22 @@ +package org.pnfolder.pnlibrary.api.updates.backup + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest + +class BackupExportTest { + @Test + fun `an export needs a plain file name`() { + listOf("", "a/b.sql", "..", "a\b.sql").forEach { name -> + assertThrows(IllegalArgumentException::class.java) { BackupExport(BackupKind.DATABASE, "db", name) {} } + } + } + + @Test + fun `file names of exports must differ`() { + val builder = PluginUpdateRequest.builder().backupExport(BackupKind.DATABASE, "Кланы", "clans.sql") {} + assertThrows(IllegalArgumentException::class.java) { builder.backupExport(BackupKind.DATABASE, "Ещё", "clans.sql") {} } + assertEquals(1, builder.exports.size) + } +} diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/version/ApiVersionRangeTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/version/ApiVersionRangeTest.kt index 2f155f644..dad35e076 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/version/ApiVersionRangeTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/version/ApiVersionRangeTest.kt @@ -26,6 +26,6 @@ class ApiVersionRangeTest { @Test fun `publishes the current independent API generation`() { - assertEquals(1, PnLibraryApi.VERSION) + assertEquals(2, PnLibraryApi.VERSION) } } diff --git a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/version/SemanticVersionTest.kt b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/version/SemanticVersionTest.kt index 5019b25e9..365eb5b94 100644 --- a/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/version/SemanticVersionTest.kt +++ b/modules/api/src/test/kotlin/org/pnfolder/pnlibrary/api/version/SemanticVersionTest.kt @@ -64,4 +64,12 @@ class SemanticVersionTest { fun `rejects inverted range`() { assertThrows(IllegalArgumentException::class.java) { VersionRange.closed("3.0.0", "2.0.0") } } + + @Test + fun `a range prints in interval notation and equal versions hash alike`() { + assertEquals("[2.0.0, 3.0.0]", VersionRange.closed("2.0.0", "3.0.0").toString()) + assertEquals("(1.0.0, *]", VersionRange.greaterThan("1.0.0").toString()) + assertEquals("[*, 2.0.0)", VersionRange.until("2.0.0").toString()) + assertEquals(SemanticVersion.parse("1.2.3+a").hashCode(), SemanticVersion.parse("1.2.3+b").hashCode()) + } } diff --git a/modules/bootstrap/build.gradle.kts b/modules/bootstrap/build.gradle.kts index ab1b7600f..e42b4a516 100644 --- a/modules/bootstrap/build.gradle.kts +++ b/modules/bootstrap/build.gradle.kts @@ -66,7 +66,8 @@ tasks.withType().configureEach { useJUnitPlatform() } mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-bootstrap", project.version.toString()) pom { name.set("pnLibrary Bootstrap") diff --git a/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/BootstrapPlatform.java b/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/BootstrapPlatform.java index 5f294be52..f34876fcd 100644 --- a/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/BootstrapPlatform.java +++ b/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/BootstrapPlatform.java @@ -54,5 +54,6 @@ public enum BootstrapPlatform { * @return {@code plugin.yml}, {@code bungee.yml} or {@code velocity-plugin.json} */ public String descriptor() { return descriptor; } + /** Whether {@code fileName} is a universal pnLibrary jar. */ static boolean isUniversal(String fileName) { return fileName != null && UNIVERSAL.matcher(fileName).matches(); } } diff --git a/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/GitHubReleaseClient.java b/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/GitHubReleaseClient.java index 5d82cd0d3..318e54583 100644 --- a/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/GitHubReleaseClient.java +++ b/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/GitHubReleaseClient.java @@ -13,6 +13,7 @@ import java.nio.charset.StandardCharsets; import java.util.Locale; +/** Minimal GitHub releases API client that works without any library on the classpath. */ final class GitHubReleaseClient { private static final int JSON_LIMIT = 2 * 1024 * 1024; private final BootstrapOptions options; diff --git a/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/LibraryInstaller.java b/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/LibraryInstaller.java index 8548e2f37..6752a0043 100644 --- a/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/LibraryInstaller.java +++ b/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/LibraryInstaller.java @@ -97,7 +97,7 @@ public Placement download(Path pluginsDirectory) throws Exception { Path directory = pluginsDirectory.toAbsolutePath().normalize(); Files.createDirectories(directory); Path target = directory.resolve(release.fileName()).normalize(); - if (!directory.equals(target.getParent()) || !release.fileName().matches("[A-Za-z0-9._-]+\\.jar")) { + if (!directory.equals(target.getParent()) || !RepositoryCatalog.isLibraryFileName(release.fileName())) { throw new IllegalStateException("unsafe release filename: " + release.fileName()); } diff --git a/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/RepositoryCatalog.java b/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/RepositoryCatalog.java index a429dbcd9..4499a1cf6 100644 --- a/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/RepositoryCatalog.java +++ b/modules/bootstrap/src/main/java/org/pnfolder/pnlibrary/bootstrap/RepositoryCatalog.java @@ -21,6 +21,12 @@ final class RepositoryCatalog { static final String PATH = ".pnlibrary/releases.json"; private static final Pattern SAFE_FILE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]*\\.jar"); + /** Every library jar is named {@code pnLibrary-...}, so a typo in the catalog cannot overwrite another plugin's jar. */ + static boolean isLibraryFileName(String file) { + return file != null && SAFE_FILE.matcher(file).matches() + && file.regionMatches(true, 0, BootstrapDefaults.PRODUCT_NAME + "-", 0, BootstrapDefaults.PRODUCT_NAME.length() + 1); + } + private static final Pattern SHA256 = Pattern.compile("(?i)^[0-9a-f]{64}$"); private RepositoryCatalog() {} @@ -158,7 +164,7 @@ private static boolean fitsJava(JsonObject entry, int javaFeature) { * One {@code artifacts} entry, verified complete, or {@code null} when it is missing a required field. * * @param requireUniversalName {@code true} for a {@code UNIVERSAL} entry, whose file must match the universal - * jar name pattern; a platform-specific entry only needs a safe jar filename, checked against the downloaded + * jar name pattern; a platform-specific entry needs a safe {@code pnLibrary-} jar filename, checked against the downloaded * jar's own descriptor when it is installed */ private static LibraryRelease decodeArtifact( @@ -166,7 +172,7 @@ private static LibraryRelease decodeArtifact( String file = text(entry, "file"); String url = text(entry, "url"); String sha256 = text(entry, "sha256"); - if (file == null || !SAFE_FILE.matcher(file).matches()) return null; + if (!isLibraryFileName(file)) return null; if (requireUniversalName && !BootstrapPlatform.isUniversal(file)) return null; if (sha256 == null || !SHA256.matcher(sha256).matches()) return null; URI uri; diff --git a/modules/bootstrap/src/test/java/org/pnfolder/pnlibrary/bootstrap/RepositoryCatalogTest.java b/modules/bootstrap/src/test/java/org/pnfolder/pnlibrary/bootstrap/RepositoryCatalogTest.java index c57b0d473..60c22088d 100644 --- a/modules/bootstrap/src/test/java/org/pnfolder/pnlibrary/bootstrap/RepositoryCatalogTest.java +++ b/modules/bootstrap/src/test/java/org/pnfolder/pnlibrary/bootstrap/RepositoryCatalogTest.java @@ -123,6 +123,7 @@ void whenNoPlatformIsGivenTheVersionIsStillPicked() { void anIncompleteOrUnsafeArtifactIsIgnoredButTheVersionStays() { String[] entries = { artifact("UNIVERSAL", "other.jar", SUM), + artifact("BUKKIT", "Vault.jar", SUM), "{\"platform\":\"UNIVERSAL\",\"file\":\"pnLibrary-1.0.0-universal.jar\",\"url\":\"http://example.org/a.jar\",\"sha256\":\"" + SUM + "\"}", "{\"platform\":\"UNIVERSAL\",\"file\":\"pnLibrary-1.0.0-universal.jar\",\"url\":\"https://example.org/a.jar\",\"sha256\":\"short\"}", artifact("UNIVERSAL", "pnLibrary-1.0.0-universal.jar", SUM, 99_999_999L, null), diff --git a/modules/common/api/common.api b/modules/common/api/common.api index 93c355c9c..d2ad52321 100644 --- a/modules/common/api/common.api +++ b/modules/common/api/common.api @@ -1,3 +1,49 @@ +public final class org/pnfolder/pnlibrary/api/plugin/ModuleId { + public static final field Companion Lorg/pnfolder/pnlibrary/api/plugin/ModuleId$Companion; + public synthetic fun (Ljava/lang/String;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun equals (Ljava/lang/Object;)Z + public final fun getValue ()Ljava/lang/String; + public fun hashCode ()I + public static final fun of (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/plugin/ModuleId$Companion { + public final fun of (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; +} + +public final class org/pnfolder/pnlibrary/api/plugin/PluginAccess { + public static final field Companion Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess$Companion; + public synthetic fun (ZZLjava/util/Set;Ljava/util/Set;Ljava/util/Set;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun allows (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Z + public static final fun builder ()Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess$Builder; + public final fun getAllowAll ()Z + public final fun getAllowedPatterns ()Ljava/util/Set; + public final fun getAllowedPlugins ()Ljava/util/Set; + public final fun getDeniedPlugins ()Ljava/util/Set; + public final fun getOwnerAllowed ()Z + public static final fun only ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess; + public static final fun ownerOnly ()Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess; + public static final fun shared ()Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess; +} + +public final class org/pnfolder/pnlibrary/api/plugin/PluginAccess$Builder { + public final fun allow ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess$Builder; + public final fun allowAll ()Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess$Builder; + public final fun allowMatching ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess$Builder; + public final fun build ()Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess; + public final fun deny ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess$Builder; + public final fun denyAll ()Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess$Builder; + public final fun owner ()Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess$Builder; +} + +public final class org/pnfolder/pnlibrary/api/plugin/PluginAccess$Companion { + public final fun builder ()Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess$Builder; + public final fun only ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess; + public final fun ownerOnly ()Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess; + public final fun shared ()Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess; +} + public final class org/pnfolder/pnlibrary/api/plugin/PluginId { public static final field Companion Lorg/pnfolder/pnlibrary/api/plugin/PluginId$Companion; public synthetic fun (Ljava/lang/String;Lkotlin/jvm/internal/DefaultConstructorMarker;)V @@ -12,6 +58,14 @@ public final class org/pnfolder/pnlibrary/api/plugin/PluginId$Companion { public final fun of (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/plugin/PluginId; } +public final class org/pnfolder/pnlibrary/common/concurrent/FailureThrottle { + public static final field MAX_KEYS I + public fun ()V + public fun (JLkotlin/jvm/functions/Function0;)V + public synthetic fun (JLkotlin/jvm/functions/Function0;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun shouldReport (Ljava/lang/String;)Z +} + public final class org/pnfolder/pnlibrary/common/concurrent/ManagedWorker : java/lang/AutoCloseable { public fun (Ljava/lang/String;IILjava/time/Duration;)V public synthetic fun (Ljava/lang/String;IILjava/time/Duration;ILkotlin/jvm/internal/DefaultConstructorMarker;)V diff --git a/modules/common/build.gradle.kts b/modules/common/build.gradle.kts index 90f35b72d..7ef125c86 100644 --- a/modules/common/build.gradle.kts +++ b/modules/common/build.gradle.kts @@ -21,7 +21,8 @@ tasks.matching { it.name == "generateMetadataFileForMavenPublication" }.configur mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-common", project.version.toString()) pom { name.set("pnLibrary Common") diff --git a/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/ModuleId.kt b/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/ModuleId.kt new file mode 100644 index 000000000..eb1f1bd97 --- /dev/null +++ b/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/ModuleId.kt @@ -0,0 +1,28 @@ +package org.pnfolder.pnlibrary.api.plugin + +import java.util.Locale + +/** Validated, case-insensitive local identity of a logical module. */ +class ModuleId private constructor( + /** Normalized lowercase module identifier. */ + val value: String, +) { + /** Returns whether [other] contains the same normalized identifier. */ + override fun equals(other: Any?): Boolean = other is ModuleId && value == other.value + /** Returns the normalized identifier hash. */ + override fun hashCode(): Int = value.hashCode() + /** Returns [value] without additional formatting. */ + override fun toString(): String = value + + companion object { + private val FORMAT = Regex("[a-z0-9][a-z0-9_.-]{0,63}") + + /** Normalizes and validates [value]. */ + @JvmStatic + fun of(value: String): ModuleId { + val normalized = value.trim().lowercase(Locale.ROOT) + require(FORMAT.matches(normalized)) { "Module ID must match ${FORMAT.pattern}" } + return ModuleId(normalized) + } + } +} diff --git a/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginAccess.kt b/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginAccess.kt new file mode 100644 index 000000000..347c9b0d5 --- /dev/null +++ b/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/api/plugin/PluginAccess.kt @@ -0,0 +1,103 @@ +package org.pnfolder.pnlibrary.api.plugin + +import org.pnfolder.pnlibrary.common.text.Wildcards +import java.util.Collections + +/** + * Immutable answer to "which plugins may use something that another plugin owns": a placeholder, a currency, + * the right to add types to a configuration. + * + * The rules are checked in this order: a denied plugin never passes; the owner passes if [ownerAllowed]; + * then [allowAll], an exact entry of [allowedPlugins], and the case-insensitive [allowedPatterns] + * where `*` matches any characters. + * + * ```kotlin + * val access = PluginAccess.builder().owner().allow("scoreboard").allowMatching("admin-*").deny("admin-untrusted").build() + * PluginAccess.ownerOnly() // only the owner + * PluginAccess.shared() // the owner and every plugin + * PluginAccess.only("clans") // the owner and the listed plugins + * ``` + * + * @property ownerAllowed whether the plugin that owns the thing may use it + * @property allowAll whether every plugin may use it unless denied + * @property allowedPlugins exact plugin IDs that may use it + * @property allowedPatterns case-insensitive plugin-ID patterns where `*` is a wildcard + * @property deniedPlugins plugin IDs refused before any allow rule is read + */ +class PluginAccess private constructor( + val ownerAllowed: Boolean, + val allowAll: Boolean, + val allowedPlugins: Set, + val allowedPatterns: Set, + val deniedPlugins: Set, +) { + /** Returns whether [consumer] may use something owned by [owner]. */ + fun allows(owner: PluginId, consumer: PluginId): Boolean { + if (consumer in deniedPlugins) return false + if (ownerAllowed && owner == consumer) return true + if (allowAll || consumer in allowedPlugins) return true + return allowedPatterns.any { Wildcards.matches(it, consumer.value) } + } + + /** Ready-made policies and the builder entry point. */ + companion object { + /** Only the owning plugin. */ + @JvmStatic + fun ownerOnly(): PluginAccess = Builder().owner().build() + + /** The owner and every plugin. */ + @JvmStatic + fun shared(): PluginAccess = Builder().owner().allowAll().build() + + /** The owner and the listed plugins. */ + @JvmStatic + fun only(vararg pluginIds: String): PluginAccess = Builder().owner().allow(*pluginIds).build() + + /** Creates an empty builder: nobody passes until a rule is added. */ + @JvmStatic + fun builder(): Builder = Builder() + } + + /** Fluent builder for [PluginAccess]. */ + class Builder internal constructor() { + private var owner = false + private var all = false + private val allowed = linkedSetOf() + private val patterns = linkedSetOf() + private val denied = linkedSetOf() + + /** Lets the owning plugin pass. */ + fun owner(): Builder = apply { owner = true } + + /** Lets every plugin pass unless denied. */ + fun allowAll(): Builder = apply { all = true } + + /** Forgets every allow rule except the owner's own. Denials stay. */ + fun denyAll(): Builder = apply { + all = false + allowed.clear() + patterns.clear() + } + + /** Lets the plugins with these IDs pass. */ + fun allow(vararg pluginIds: String): Builder = apply { pluginIds.map(PluginId::of).forEach(allowed::add) } + + /** Adds case-insensitive plugin-ID patterns; `*` is the wildcard. */ + fun allowMatching(vararg values: String): Builder = apply { + require(values.none(String::isBlank)) { "Plugin access patterns must not be blank" } + values.map(String::trim).forEach(patterns::add) + } + + /** Refuses the plugins with these IDs, overriding every allow rule. */ + fun deny(vararg pluginIds: String): Builder = apply { pluginIds.map(PluginId::of).forEach(denied::add) } + + /** Creates the immutable policy. */ + fun build(): PluginAccess = PluginAccess( + owner, + all, + Collections.unmodifiableSet(LinkedHashSet(allowed)), + Collections.unmodifiableSet(LinkedHashSet(patterns)), + Collections.unmodifiableSet(LinkedHashSet(denied)), + ) + } +} diff --git a/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/concurrent/FailureThrottle.kt b/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/concurrent/FailureThrottle.kt new file mode 100644 index 000000000..bd244456e --- /dev/null +++ b/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/concurrent/FailureThrottle.kt @@ -0,0 +1,30 @@ +package org.pnfolder.pnlibrary.common.concurrent + +import java.util.concurrent.ConcurrentHashMap + +/** + * Lets a failure through the first time and then at most once per [intervalMillis] for the same key, so a loop that + * keeps failing fills the log once instead of on every pass. + */ +class FailureThrottle( + private val intervalMillis: Long = 60_000, + private val clock: () -> Long = System::currentTimeMillis, +) { + private val lastReported = ConcurrentHashMap() + + /** True when the failure with this [key] should be written now; later calls inside the interval return false. */ + fun shouldReport(key: String): Boolean { + val now = clock() + if (lastReported.size >= MAX_KEYS) lastReported.entries.removeIf { now - it.value >= intervalMillis } + var allowed = false + lastReported.compute(key) { _, last -> + allowed = last == null || now - last >= intervalMillis + if (allowed) now else last + } + return allowed + } + + private companion object { + const val MAX_KEYS = 256 + } +} diff --git a/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/minecraft/MinecraftVersionRange.kt b/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/minecraft/MinecraftVersionRange.kt index b42bf27af..c0e047561 100644 --- a/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/minecraft/MinecraftVersionRange.kt +++ b/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/minecraft/MinecraftVersionRange.kt @@ -89,11 +89,15 @@ data class MinecraftVersionRange( } /** Formats a value such as `[1.8.8, 1.12.2]`, `>=1.20.5`, or `<1.13`. */ - override fun toString(): String = when { - minimum == null && maximum == null -> "all known versions" - minimum == null -> "${if (includeMaximum) "<=" else "<"}${maximum!!.text}" - maximum == null -> "${if (includeMinimum) ">=" else ">"}${minimum.text}" - else -> "${if (includeMinimum) "[" else "("}${minimum.text}, ${maximum.text}${if (includeMaximum) "]" else ")"}" + override fun toString(): String { + val low = minimum + val high = maximum + return when { + low != null && high != null -> "${if (includeMinimum) "[" else "("}${low.text}, ${high.text}${if (includeMaximum) "]" else ")"}" + low != null -> "${if (includeMinimum) ">=" else ">"}${low.text}" + high != null -> "${if (includeMaximum) "<=" else "<"}${high.text}" + else -> "all known versions" + } } /** Java-friendly factories for common version-range shapes. */ diff --git a/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/text/Wildcards.kt b/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/text/Wildcards.kt index 85a47487b..268adfeab 100644 --- a/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/text/Wildcards.kt +++ b/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/text/Wildcards.kt @@ -1,5 +1,7 @@ package org.pnfolder.pnlibrary.common.text +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicInteger import java.util.regex.Pattern /** @@ -7,10 +9,28 @@ import java.util.regex.Pattern * including an empty one, and every other character is matched literally. */ object Wildcards { + private const val MAXIMUM_CACHED = 1024 + + private val compiled = ConcurrentHashMap() + private val compilations = AtomicInteger() + + /** How many patterns were compiled since start; used by tests to prove the cache works. */ + internal fun compilationCount(): Int = compilations.get() + /** Returns whether the whole of [value] matches [pattern], ignoring case. */ @JvmStatic - fun matches(pattern: String, value: String): Boolean { + fun matches(pattern: String, value: String): Boolean = patternFor(pattern).matcher(value).matches() + + // Patterns come from configuration, so the set is small; the cap only guards against a caller feeding unbounded text. + private fun patternFor(pattern: String): Pattern { + compiled[pattern]?.let { return it } + if (compiled.size >= MAXIMUM_CACHED) compiled.clear() + return compiled.computeIfAbsent(pattern) { compile(it) } + } + + private fun compile(pattern: String): Pattern { + compilations.incrementAndGet() val expression = pattern.split('*').joinToString(".*", transform = Pattern::quote) - return Pattern.compile("^$expression$", Pattern.CASE_INSENSITIVE).matcher(value).matches() + return Pattern.compile("^$expression$", Pattern.CASE_INSENSITIVE) } } diff --git a/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/time/DisplayZone.kt b/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/time/DisplayZone.kt index c064fa5a1..42f6bcba1 100644 --- a/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/time/DisplayZone.kt +++ b/modules/common/src/main/kotlin/org/pnfolder/pnlibrary/common/time/DisplayZone.kt @@ -4,7 +4,7 @@ import java.time.ZoneId /** * Time zone in which every time shown to a person is written. Stored times are always UTC instants; - * only the display changes. The runtime sets it from `time-zone` in config.yml at startup. + * only the display changes. The runtime sets it from the `time-zone` setting at startup and when it changes. */ object DisplayZone { /** The zone used for display; defaults to the system zone until the runtime sets it. */ diff --git a/modules/common/src/test/kotlin/org/pnfolder/pnlibrary/common/concurrent/FailureThrottleTest.kt b/modules/common/src/test/kotlin/org/pnfolder/pnlibrary/common/concurrent/FailureThrottleTest.kt new file mode 100644 index 000000000..98cac9efb --- /dev/null +++ b/modules/common/src/test/kotlin/org/pnfolder/pnlibrary/common/concurrent/FailureThrottleTest.kt @@ -0,0 +1,20 @@ +package org.pnfolder.pnlibrary.common.concurrent + +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class FailureThrottleTest { + @Test + fun `lets the first failure through and holds repeats until the interval passes`() { + var now = 1_000L + val throttle = FailureThrottle(60_000) { now } + + assertTrue(throttle.shouldReport("a")) + assertFalse(throttle.shouldReport("a")) + assertTrue(throttle.shouldReport("b")) + + now += 60_000 + assertTrue(throttle.shouldReport("a")) + } +} diff --git a/modules/common/src/test/kotlin/org/pnfolder/pnlibrary/common/text/WildcardsTest.kt b/modules/common/src/test/kotlin/org/pnfolder/pnlibrary/common/text/WildcardsTest.kt index 5ba235cc4..1a9b84f7f 100644 --- a/modules/common/src/test/kotlin/org/pnfolder/pnlibrary/common/text/WildcardsTest.kt +++ b/modules/common/src/test/kotlin/org/pnfolder/pnlibrary/common/text/WildcardsTest.kt @@ -23,3 +23,29 @@ class WildcardsTest { assertFalse(Wildcards.matches("exact", "exactly")) } } + +class WildcardsCacheTest { + private val patterns = listOf("*", "", "shop-*", "*-addon", "a*b*c", "clan.v2", "Exact", "x*", "a\\Qb*", "[a-z]*", "(?i)q", "pn*lib*", "**", "é*") + private val values = listOf("", "shop-main", "SHOP-", "eco-addon", "aXbYc", "clan.v2", "clanXv2", "EXACT", + "xyz", "a\\Qbzz", "abc", "q", "pnlibrary", "PN-lib", "Éa", "[a-z]x") + + private fun reference(pattern: String, value: String): Boolean { + val expression = pattern.split('*').joinToString(".*", transform = java.util.regex.Pattern::quote) + return java.util.regex.Pattern.compile("^$expression$", java.util.regex.Pattern.CASE_INSENSITIVE).matcher(value).matches() + } + + @Test + fun `cached matching equals compiling on every call`() { + for (pattern in patterns) for (value in values) { + org.junit.jupiter.api.Assertions.assertEquals(reference(pattern, value), Wildcards.matches(pattern, value), "$pattern / $value") + } + } + + @Test + fun `a pattern is compiled once however many times it is used`() { + val unique = List(7) { "cache-test-$it-*" } + val before = Wildcards.compilationCount() + repeat(100_000) { Wildcards.matches(unique[it % unique.size], "cache-test-${it % 7}-value") } + org.junit.jupiter.api.Assertions.assertEquals(unique.size, Wildcards.compilationCount() - before) + } +} diff --git a/modules/console/build.gradle.kts b/modules/console/build.gradle.kts index 12f261ed8..f372bee35 100644 --- a/modules/console/build.gradle.kts +++ b/modules/console/build.gradle.kts @@ -18,7 +18,8 @@ dependencies { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-console", project.version.toString()) pom { name.set("pnLibrary Console Style") diff --git a/modules/core/build.gradle.kts b/modules/core/build.gradle.kts index 6b2a20748..a62de490b 100644 --- a/modules/core/build.gradle.kts +++ b/modules/core/build.gradle.kts @@ -9,16 +9,12 @@ base { archivesName = "${rootProject.property("pnlibrary.name")}-core" } dependencies { implementation(project(":modules:api")) - implementation(project(":modules:runtime-spi")) - api(project(":modules:link")) - api(project(":modules:journal")) - api(project(":modules:upload")) - api(project(":modules:events")) - api(project(":modules:placeholders")) + implementation(project(":modules:spi")) + implementation(project(":modules:common")) api(project(":modules:updates")) implementation(project(":modules:features:currency-runtime")) implementation(project(":modules:features:config-runtime")) - implementation(project(":modules:features:minecraft-localization-api")) + implementation(project(":modules:features:localization-api")) implementation(libs.kotlin.stdlib) implementation(libs.gson) implementation(libs.snakeyaml) @@ -37,7 +33,8 @@ dependencies { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates( groupId = "io.github.pnfolder", diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/configs/ConfigsCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/configs/ConfigsCommand.kt new file mode 100644 index 000000000..08027d9da --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/configs/ConfigsCommand.kt @@ -0,0 +1,248 @@ +package org.pnfolder.pnlibrary.core.commands.configs + +import net.kyori.adventure.text.Component +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandNodeBuilder +import org.pnfolder.pnlibrary.api.commands.definition.command +import org.pnfolder.pnlibrary.api.config.ConfigApply +import org.pnfolder.pnlibrary.api.config.ConfigEditException +import org.pnfolder.pnlibrary.api.config.ConfigId +import org.pnfolder.pnlibrary.api.config.ConfigInfo +import org.pnfolder.pnlibrary.api.config.ConfigPolymorphic +import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.core.commands.engine.pageCount +import java.lang.reflect.ParameterizedType +import java.lang.reflect.Type + +/** + * `/pn configs`: every configuration file of every plugin under its identifier `plugin/module:path`. + * + * | Command | What it does | + * |---|---| + * | `/pn configs [page]` | lists the files with their class and state | + * | `/pn configs info ` | one file: where it lies, whether it is loaded, what was skipped, problems | + * | `/pn configs reload ` | reads the file again; the old value stays when the new one is broken | + * | `/pn configs validate ` | checks the loaded value without writing anything | + * | `/pn configs types ` | the words a polymorphic type understands and which plugin added each | + * | `/pn configs settings ` | the settings of a file that may be changed in game (`@ConfigEditable`), with values | + * | `/pn configs edit ` | changes one such setting and saves the file; needs `pnlibrary.configs.edit` | + * + * It never shows values from a file, so secrets cannot leak through it. Requires `pnlibrary.configs`; the console always may. + */ +class ConfigsCommand(private val library: PnLibrary) { + fun definition(): CommandDefinition = command("configs") { + permission(PERMISSION) + noPermissionMessage("Конфигурации плагинов доступны администраторам. Нужно право $PERMISSION.") + consoleBypassesPermission() + executes { list(it, 1) } + argument("page", ArgumentType.integer()) { executes { list(it, it.get("page")) } } + literal("info") { withId { context, id -> info(context, id) } } + literal("reload") { withId { context, id -> reload(context, id) } } + literal("validate") { withId { context, id -> validate(context, id) } } + literal("settings") { withId { context, id -> settings(context, id) } } + literal("edit") { + permission(EDIT_PERMISSION) + noPermissionMessage("Менять настройки может тот, у кого есть право $EDIT_PERMISSION.") + argument("id", ArgumentType.string()) { + suggests { library.configurations.all().filter { !it.readOnly }.map { it.id.toString() } } + argument("path", ArgumentType.string()) { + argument("value", ArgumentType.greedyString()) { + executes { context -> + val id = parseId(context) ?: return@executes + edit(context, id, context.get("path"), context.get("value")) + } + } + } + } + } + literal("types") { + argument("type", ArgumentType.string()) { + suggests { polymorphicBases().map { it.simpleName } } + executes { types(it, it.get("type")) } + } + } + } + + private fun org.pnfolder.pnlibrary.api.commands.definition.CommandNodeBuilder.withId(action: (CommandContext, ConfigId) -> Unit) { + argument("id", ArgumentType.string()) { + suggests { library.configurations.all().map { it.id.toString() } } + executes { context -> parseId(context)?.let { action(context, it) } } + } + } + + /** The file named by the `id` argument, or `null` after telling the sender what is wrong with it. */ + private fun parseId(context: CommandContext): ConfigId? { + val typed = context.get("id") + val id = runCatching { ConfigId.parse(typed) }.getOrElse { + say(context, "Неверный адрес «$typed»: ${it.message}", ChatPalette.DANGER) + return null + } + if (library.configurations.get(id) == null) { + say(context, "Такого файла нет: $id. Список: $ROOT", ChatPalette.DANGER) + return null + } + return id + } + + private fun say(context: CommandContext, text: String, color: net.kyori.adventure.text.format.TextColor = ChatPalette.TEXT) = + context.sender.send(Component.text(text, color)) + + private fun list(context: CommandContext, requested: Int) { + val all = library.configurations.all() + val pages = pageCount(all.size, PAGE_SIZE) + val page = requested.coerceIn(1, pages) + say(context, "Конфигурации: ${all.size}, страница $page/$pages", ChatPalette.ACCENT) + all.drop((page - 1) * PAGE_SIZE).take(PAGE_SIZE).forEach { info -> + val state = when { + !info.exists -> "нет файла" + info.skippedUnknownTypes.isNotEmpty() -> "пропущено элементов: ${info.skippedUnknownTypes.size}" + info.isLoaded -> "загружен" + else -> "не загружен" + } + val flags = if (info.readOnly) ", только чтение" else "" + say(context, "${info.id} ${info.modelType.simpleName} ($state$flags)", if (info.isLoaded) ChatPalette.TEXT else ChatPalette.FAINT) + } + say(context, "Подробнее: $ROOT info <адрес>", ChatPalette.FAINT) + } + + private fun info(context: CommandContext, id: ConfigId) { + val info = requireNotNull(library.configurations.get(id)?.info) + say(context, id.toString(), ChatPalette.ACCENT) + say(context, " плагин: ${info.plugin}, модуль: ${info.module}, корень: ${info.root.name.lowercase()}") + say(context, " файл: ${info.file}${if (info.exists) "" else " (не существует)"}") + say(context, " класс: ${info.modelType.name}") + say(context, " загружен: ${if (info.isLoaded) "да, ${info.loadedAt}" else "нет"}${if (info.readOnly) "; только чтение" else ""}") + if (info.skippedUnknownTypes.isNotEmpty()) { + say(context, " пропущено из-за неизвестного type (остаётся в файле):", ChatPalette.WARN) + info.skippedUnknownTypes.forEach { say(context, " $it", ChatPalette.WARN) } + } + problems(context, info) + } + + private fun problems(context: CommandContext, info: ConfigInfo) { + if (info.problems.isEmpty()) return + say(context, " проблемы:", ChatPalette.DANGER) + info.problems.forEach { say(context, " ${it.path}: ${it.message}", ChatPalette.DANGER) } + } + + private fun settings(context: CommandContext, id: ConfigId) { + val config = requireNotNull(library.configurations.get(id)) + val list = config.settings + if (list.isEmpty()) { + say(context, "$id: нет настроек, которые можно менять в игре.", ChatPalette.FAINT) + return + } + say(context, "$id: настроек ${list.size}", ChatPalette.ACCENT) + list.forEach { setting -> + val limits = listOfNotNull(setting.min?.let { "от ${trim(it)}" }, setting.max?.let { "до ${trim(it)}" }).joinToString(" ") + val choices = if (setting.choices.isEmpty()) "" else " (${setting.choices.joinToString("|")})" + val applies = when (setting.apply) { + ConfigApply.LIVE -> "" + ConfigApply.RELOAD -> " [нужно перечитать]" + ConfigApply.RESTART -> " [нужен перезапуск]" + } + say(context, " ${setting.path} = ${setting.value ?: "?"}$choices${if (limits.isEmpty()) "" else " ($limits)"}$applies") + if (setting.description.isNotBlank()) say(context, " ${setting.title}: ${setting.description}", ChatPalette.FAINT) + } + config.info?.pendingApply?.let { say(context, "Есть изменения, которые ещё не работают: ${applyWord(it)}.", ChatPalette.WARN) } + } + + private fun trim(number: Double): String = if (number == Math.floor(number)) number.toLong().toString() else number.toString() + + private fun applyWord(apply: ConfigApply) = when (apply) { + ConfigApply.LIVE -> "работают сразу" + ConfigApply.RELOAD -> "нужно перечитать файл: $ROOT reload <адрес>" + ConfigApply.RESTART -> "нужен перезапуск сервера" + } + + private fun edit(context: CommandContext, id: ConfigId, path: String, value: String) { + val config = requireNotNull(library.configurations.get(id)) + try { + val result = config.edit(path, value) + say(context, "$id: $path ${result.previous ?: "?"} → ${result.setting.value}. Файл сохранён.", ChatPalette.OK) + if (result.setting.apply != ConfigApply.LIVE) say(context, "Начнёт работать: ${applyWord(result.setting.apply)}.", ChatPalette.WARN) + } catch (error: ConfigEditException) { + say(context, "Не изменено: ${error.message}", ChatPalette.DANGER) + } catch (error: IllegalStateException) { + say(context, "Не изменено: ${error.message}", ChatPalette.DANGER) + } + } + + private fun reload(context: CommandContext, id: ConfigId) { + val config = requireNotNull(library.configurations.get(id)) + try { + config.reload() + say(context, "$id прочитан заново.", ChatPalette.OK) + config.info?.takeIf { it.skippedUnknownTypes.isNotEmpty() }?.let { + say(context, "Пропущено элементов с неизвестным type: ${it.skippedUnknownTypes.size}. Подробнее: $ROOT info $id", ChatPalette.WARN) + } + } catch (error: Exception) { + say(context, "$id не прочитан, прежнее значение сохранено: ${error.message}", ChatPalette.DANGER) + } + } + + private fun validate(context: CommandContext, id: ConfigId) { + val config = requireNotNull(library.configurations.get(id)) + if (!config.isLoaded) { + say(context, "$id не загружен, проверять нечего.", ChatPalette.WARN) + return + } + val problems = config.validate() + if (problems.isEmpty()) say(context, "$id: проблем нет.", ChatPalette.OK) + else { + say(context, "$id: проблем ${problems.size}", ChatPalette.DANGER) + problems.forEach { say(context, " ${it.path}: ${it.message}", ChatPalette.DANGER) } + } + } + + private fun types(context: CommandContext, typed: String) { + val base = polymorphicBases().firstOrNull { it.simpleName.equals(typed, ignoreCase = true) || it.name == typed } + if (base == null) { + say(context, "Такого типа нет среди зарегистрированных конфигураций: $typed", ChatPalette.DANGER) + return + } + val words = library.configurations.types(base) + say(context, "${base.simpleName}: слов ${words.size}", ChatPalette.ACCENT) + words.forEach { word -> + val who = word.owner?.let { "добавил $it в ${word.target}" } ?: "объявлен в самом типе" + val aliases = if (word.aliases.isEmpty()) "" else " (также ${word.aliases.joinToString()})" + say(context, " ${word.name}$aliases → ${word.implementation.simpleName}; $who; приоритет ${word.priority}") + } + } + + /** The polymorphic types that the registered files use, found by looking through the fields of their classes. */ + private fun polymorphicBases(): List> { + val seen = linkedSetOf>() + val found = linkedSetOf>() + fun visit(type: Type) { + val raw = when (type) { + is Class<*> -> type + is ParameterizedType -> { + type.actualTypeArguments.forEach(::visit) + type.rawType as? Class<*> + } + // Kotlin writes List as List. + is java.lang.reflect.WildcardType -> { + type.upperBounds.forEach(::visit) + null + } + else -> null + } ?: return + if (raw.isPrimitive || raw.name.startsWith("java.") || !seen.add(raw)) return + if (raw.isAnnotationPresent(ConfigPolymorphic::class.java)) found += raw + raw.declaredFields.forEach { visit(it.genericType) } + } + library.configurations.all().forEach { visit(it.modelType) } + return found.toList() + } + + companion object { + const val PERMISSION = "pnlibrary.configs" + const val EDIT_PERMISSION = "pnlibrary.configs.edit" + private const val ROOT = "/pn configs" + private const val PAGE_SIZE = 10 + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/deps/DepsCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/deps/DepsCommand.kt new file mode 100644 index 000000000..45c8ff1ef --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/deps/DepsCommand.kt @@ -0,0 +1,98 @@ +package org.pnfolder.pnlibrary.core.commands.deps + +import net.kyori.adventure.text.format.TextColor +import org.pnfolder.pnlibrary.api.chat.ChatKit +import org.pnfolder.pnlibrary.api.chat.ChatReader +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command +import org.pnfolder.pnlibrary.api.downloads.DownloadState +import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.core.lifecycle.dependencyDownloads + +/** + * `/pn deps`: plugins that other plugins need and the server does not have. + * + * | Command | What it does | + * |---|---| + * | `/pn deps` | what is missing, with the links, and the code of each group | + * | `/pn deps install ` | downloads that group now, even when automatic download is off | + * | `/pn deps auto on\|off` | whether missing plugins are downloaded without a command | + * + * The automatic switch is kept in the data folder and is the same one the game menu changes. Requires + * `pnlibrary.deps`; the console always may use it. + */ +class DepsCommand(private val library: PnLibrary) { + fun definition(): CommandDefinition = command("deps") { + permission(PERMISSION) + noPermissionMessage("Зависимости плагинов доступны администраторам. Нужно право $PERMISSION.") + consoleBypassesPermission() + executes { status(it) } + literal("install") { + argument("code", ArgumentType.string()) { + suggests { library.dependencyDownloads()?.missingGroups()?.map { it.code }.orEmpty() } + executes { install(it, it.get("code")) } + } + } + literal("auto") { + literal("on") { executes { switch(it, true) } } + literal("off") { executes { switch(it, false) } } + } + } + + private fun kit(context: CommandContext) = ChatKit(ChatReader.of(context.sender)) + + private fun say(context: CommandContext, text: String, color: TextColor = ChatPalette.TEXT) = + context.sender.send(kit(context).text(text, color)) + + private fun status(context: CommandContext) { + val downloads = library.dependencyDownloads() ?: return say(context, "Загрузки зависимостей здесь недоступны.", ChatPalette.DANGER) + say(context, "Автозагрузка недостающих плагинов: ${if (downloads.automatic()) "включена" else "выключена"}.", ChatPalette.ACCENT) + val groups = downloads.missingGroups() + if (groups.isEmpty()) return say(context, "Всё нужное установлено.", ChatPalette.LABEL) + groups.forEach { group -> + say(context, "${group.owner} просит:", ChatPalette.ACCENT) + group.items.forEach { item -> + val name = if (item.title.equals(item.plugin, ignoreCase = true)) item.plugin else "${item.title} (${item.plugin})" + say(context, " $name ${item.minimum}+ · ${if (item.required) "обязательный" else "необязательный"}") + item.description?.let { say(context, " $it", ChatPalette.LABEL) } + if (item.noFileForServer) say(context, " для этого сервера готового файла нет, скачайте вручную", ChatPalette.LABEL) + item.variant?.let { say(context, " выбран файл: $it", ChatPalette.LABEL) } + (listOfNotNull(item.page) + item.sources).forEach { say(context, " $it", ChatPalette.LABEL) } + } + val line = if (group.installable) " Установить: /pn deps install ${group.code}" else " Скачайте по ссылкам и положите в plugins." + say(context, line, ChatPalette.SOFT) + } + } + + private fun install(context: CommandContext, code: String) { + val downloads = library.dependencyDownloads() ?: return say(context, "Загрузки зависимостей здесь недоступны.", ChatPalette.DANGER) + val stage = try { + downloads.installGroup(code) + } catch (error: IllegalArgumentException) { + return say(context, error.message ?: "Установить нельзя.", ChatPalette.DANGER) + } ?: return say(context, "Такого кода нет или всё уже скачано. Список: /pn deps", ChatPalette.DANGER) + say(context, "Скачиваю…", ChatPalette.LABEL) + stage.whenComplete { shots, error -> + val failed = shots?.firstOrNull { it.state == DownloadState.FAILED } + when { + error != null -> say(context, "Не вышло: ${error.message}", ChatPalette.DANGER) + failed != null -> say(context, "Не вышло: ${failed.message ?: "причина неизвестна"}", ChatPalette.DANGER) + else -> say(context, "Готово. Перезапустите сервер, чтобы плагины загрузились.", ChatPalette.ACCENT) + } + } + } + + private fun switch(context: CommandContext, value: Boolean) { + val downloads = library.dependencyDownloads() ?: return say(context, "Загрузки зависимостей здесь недоступны.", ChatPalette.DANGER) + downloads.setAutomatic(value) + val text = if (value) "Недостающие плагины теперь скачиваются сами." else "Автозагрузка выключена: ссылки и код будут в сообщении." + say(context, text, ChatPalette.ACCENT) + } + + companion object { + const val PERMISSION = "pnlibrary.deps" + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/ChatPager.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/ChatPager.kt similarity index 75% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/ChatPager.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/ChatPager.kt index a7df45fda..81e81654d 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/ChatPager.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/ChatPager.kt @@ -1,8 +1,10 @@ -package org.pnfolder.pnlibrary.core.commands +package org.pnfolder.pnlibrary.core.commands.engine import net.kyori.adventure.text.Component import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette + +internal fun pageCount(total: Int, pageSize: Int): Int = ((total + pageSize - 1) / pageSize).coerceAtLeast(1) internal fun chatPager(kit: ChatKit, base: String, page: Int, pages: Int): Component { fun link(target: Int, label: String) = kit.option(label, "$base $target", "Страница $target из $pages", ChatPalette.SOFT) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/CommandFeedback.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandFeedback.kt similarity index 76% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/CommandFeedback.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandFeedback.kt index 323c7d004..f081ec283 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/CommandFeedback.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandFeedback.kt @@ -1,25 +1,25 @@ -package org.pnfolder.pnlibrary.core.commands +package org.pnfolder.pnlibrary.core.commands.engine import net.kyori.adventure.key.Key import net.kyori.adventure.sound.Sound import net.kyori.adventure.text.event.ClickEvent import org.pnfolder.pnlibrary.api.chat.ChatKit import org.pnfolder.pnlibrary.api.chat.ChatNotice -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.commands.BadUsage +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandError -import org.pnfolder.pnlibrary.api.commands.CommandErrorHandler -import org.pnfolder.pnlibrary.api.commands.CommandFailed import org.pnfolder.pnlibrary.api.commands.CommandSender -import org.pnfolder.pnlibrary.api.commands.ConsoleOnly -import org.pnfolder.pnlibrary.api.commands.InvalidArgument -import org.pnfolder.pnlibrary.api.commands.NoPermission -import org.pnfolder.pnlibrary.api.commands.OnCooldown -import org.pnfolder.pnlibrary.api.commands.PlayerNotFound -import org.pnfolder.pnlibrary.api.commands.PlayerOnly +import org.pnfolder.pnlibrary.api.commands.error.BadUsage +import org.pnfolder.pnlibrary.api.commands.error.CommandError +import org.pnfolder.pnlibrary.api.commands.error.CommandErrorHandler +import org.pnfolder.pnlibrary.api.commands.error.CommandFailed +import org.pnfolder.pnlibrary.api.commands.error.ConsoleOnly +import org.pnfolder.pnlibrary.api.commands.error.InvalidArgument +import org.pnfolder.pnlibrary.api.commands.error.NoPermission +import org.pnfolder.pnlibrary.api.commands.error.OnCooldown +import org.pnfolder.pnlibrary.api.commands.error.PlayerNotFound +import org.pnfolder.pnlibrary.api.commands.error.PlayerOnly import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import java.util.concurrent.ConcurrentHashMap @@ -28,16 +28,11 @@ internal const val DEFAULT_USAGE = "Использование: {usage}" internal typealias ErrorHandlers = Map, CommandErrorHandler<*>> -/** - * Handlers that a plugin, or one module of it, sets for all of its commands. A module's scope has its plugin's scope - * as [parent], so the chain runs subcommand, command, module, plugin, then the library's standard. The handlers are - * read on every error, so a plugin may set them at any time. - */ +// A module's scope chains to its plugin's scope, so the error waterfall runs: node → module → plugin → library. internal class CommandFeedbackScope(val parent: CommandFeedbackScope? = null) { val handlers = ConcurrentHashMap, CommandErrorHandler<*>>() } -/** The handler for [error] among [handlers]: the one of its own class, else of the nearest base class, else `null`. */ internal fun handlerFor(handlers: ErrorHandlers, error: CommandError): CommandErrorHandler? { var type: Class<*>? = error.javaClass while (type != null && CommandError::class.java.isAssignableFrom(type)) { @@ -49,14 +44,7 @@ internal fun handlerFor(handlers: ErrorHandlers, error: CommandError): CommandEr return null } -/** - * The library's own standard answers, the last link of the chain, taken from `config.yml`: one place that gives - * every plugin the same wording and sound until a plugin chooses otherwise. An error with its own default message - * says that; any other is answered with the text of its nearest built-in base class, and the last resort is the - * text for [CommandFailed]. - * - * @property deniedSound sound played with the denial text, or `null` for none - */ +// Last link of the error chain; falls back through base classes and uses CommandFailed text as a last resort. internal class StandardCommandFeedback( deniedMessage: String = DEFAULT_NO_PERMISSION, val deniedSound: Sound? = null, @@ -102,6 +90,8 @@ internal fun standardCommandFeedback(config: PnLibraryConfig): StandardCommandFe playerNotFoundMessage = config.playerNotFoundMessage, playerOnlyMessage = config.playerOnlyMessage, consoleOnlyMessage = config.consoleOnlyMessage, + cooldownMessage = config.cooldownMessage, + failedMessage = config.commandFailedMessage, ) internal fun CommandSender.chatNotice(tone: ChatTone, text: String, detail: String? = null) { diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/CommandRegistry.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandRegistry.kt similarity index 84% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/CommandRegistry.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandRegistry.kt index 58abc3a14..2e1809bbc 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/CommandRegistry.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandRegistry.kt @@ -1,17 +1,20 @@ -package org.pnfolder.pnlibrary.core.commands +package org.pnfolder.pnlibrary.core.commands.engine -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.CommandError -import org.pnfolder.pnlibrary.api.commands.CommandFailure -import org.pnfolder.pnlibrary.api.commands.CommandNode -import org.pnfolder.pnlibrary.api.commands.CommandNodeKind import org.pnfolder.pnlibrary.api.commands.CommandRegistration -import org.pnfolder.pnlibrary.api.commands.NoPermission -import org.pnfolder.pnlibrary.api.commands.completedExecution -import org.pnfolder.pnlibrary.api.commands.completedSuggestions +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandNode +import org.pnfolder.pnlibrary.api.commands.definition.CommandNodeKind +import org.pnfolder.pnlibrary.api.commands.definition.SenderRule +import org.pnfolder.pnlibrary.api.commands.definition.completedExecution +import org.pnfolder.pnlibrary.api.commands.definition.completedSuggestions +import org.pnfolder.pnlibrary.api.commands.error.CommandError +import org.pnfolder.pnlibrary.api.commands.error.CommandFailed +import org.pnfolder.pnlibrary.api.commands.error.CommandFailure +import org.pnfolder.pnlibrary.api.commands.error.NoPermission import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.common.lang.Failures import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.spi.commands.PlatformCommandAdapter import org.pnfolder.pnlibrary.spi.commands.PlatformCommandDispatcher @@ -27,11 +30,6 @@ import java.util.concurrent.atomic.AtomicLong internal const val DEFAULT_NO_PERMISSION = "Недостаточно прав для этой команды." -/** - * Registers, routes and runs portable commands, and answers a problem from the most specific level that has an - * answer: the subcommand, the command, the plugin module, the plugin as a whole, and last [standard], the library's - * own wording from `config.yml`. - */ internal class CommandRegistry( private val commandAdapter: PlatformCommandAdapter, private val logging: PlatformLogging, @@ -98,6 +96,7 @@ internal class CommandRegistry( val route = try { router.route(command, context) } catch (error: Throwable) { + Failures.rethrowIfFatal(error) executionFailed(registration.owner, registration.command.name, context, error) return completedExecution() } @@ -111,6 +110,7 @@ internal class CommandRegistry( val stage = try { executable.node.execution.execute(executable.context) } catch (error: Throwable) { + Failures.rethrowIfFatal(error) failed(registration, executable, error) return completedExecution() } @@ -120,10 +120,7 @@ internal class CommandRegistry( } } - /** - * A command that stopped with a [CommandFailure] reports an error of its own: it is answered through the same - * levels as any other. Anything else is an unexpected error, which is logged and shown as a failure. - */ + // CommandFailure = intentional error, answered through the normal chain. Anything else is logged and shown as a failure. private fun failed(registration: Registration, executable: CommandRoute.Executable, error: Throwable) { val failure = generateSequence(error) { it.cause }.filterIsInstance().firstOrNull() if (failure == null) { @@ -133,12 +130,8 @@ internal class CommandRegistry( answer(registration, executable.context, failure.error, executable.path.asReversed()) } - /** - * Answers [error] from the most specific level that can: the nodes from the deepest involved up to the command, - * then the plugin module, then the plugin, then the library standard. On each level the handler of the error's - * own class comes first, then the one of its nearest base class; at a node, a plain no-permission text counts as - * a handler. - */ + // Error waterfall: deepest node → parent nodes → module → plugin → library standard. + // At each level the handler for the exact error class wins, then the nearest base class. private fun answer(registration: Registration, context: CommandContext, error: CommandError, nodes: List) { fun handledBy(handlers: ErrorHandlers): Boolean { val handler = handlerFor(handlers, error) ?: return false @@ -160,15 +153,20 @@ internal class CommandRegistry( private fun helpFor(node: CommandNode?, context: CommandContext): List { if (node == null) return emptyList() val ways = node.children - .filter { it.description.isNotEmpty() && it.permission.let { needed -> needed == null || context.sender.hasPermission(needed) } } + .filter { child -> + child.description.isNotEmpty() && + child.permission.let { needed -> needed == null || context.sender.hasPermission(needed) } && + when (child.senderRule) { + SenderRule.PLAYER -> !context.sender.isConsole + SenderRule.CONSOLE -> context.sender.isConsole + SenderRule.ANY -> true + } + } .map { (if (it.kind == CommandNodeKind.ARGUMENT) "<${it.name}>" else it.name) + " — " + it.description.first() } return node.description + ways } - /** - * Runs a plugin's reaction. When it throws, the failure is logged and `false` returned so the next level answers; - * the sender never sees a broken handler's error. - */ + // A broken handler logs and returns false so the next level answers — the sender never sees handler exceptions. private inline fun react(registration: Registration, reaction: () -> Unit): Boolean = try { reaction() @@ -187,6 +185,7 @@ internal class CommandRegistry( val stage = try { router.suggest(command, context) } catch (error: Throwable) { + Failures.rethrowIfFatal(error) suggestionFailed(registration.owner, error) return completedSuggestions(emptyList()) } @@ -218,7 +217,7 @@ internal class CommandRegistry( failuresByCommand[commandName] = (failuresByCommand[commandName] ?: 0L) + 1L } logging.log(owner, LogLevel.ERROR, "Command execution failed", error) - context.sender.chatNotice(ChatTone.FAILURE, "Команда не выполнилась.") + standard.answer(context, CommandFailed()) } private fun suggestionFailed(owner: Any, error: Throwable) { @@ -250,7 +249,7 @@ internal class CommandRegistry( } } - /** Only the wrapper a dependent stage adds is removed; the cause of the command's own exception stays with it. */ + // Strips the CompletionException wrapper added by the stage; keeps the original cause. private fun unwrap(error: Throwable): Throwable = if (error is CompletionException) error.cause ?: error else error private inner class Registration( diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/CommandService.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandService.kt similarity index 79% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/CommandService.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandService.kt index 5534b6e31..3f1d24008 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/CommandService.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandService.kt @@ -1,9 +1,9 @@ -package org.pnfolder.pnlibrary.core.commands +package org.pnfolder.pnlibrary.core.commands.engine -import org.pnfolder.pnlibrary.api.commands.CommandBuilder -import org.pnfolder.pnlibrary.api.commands.CommandDefinition import org.pnfolder.pnlibrary.api.commands.CommandRegistration -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.CommandBuilder +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command /** * Registers portable commands and binds their lifecycle to an owner. diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/CommandTreeRouter.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandTreeRouter.kt similarity index 79% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/CommandTreeRouter.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandTreeRouter.kt index f4875e737..48379717a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/CommandTreeRouter.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandTreeRouter.kt @@ -1,30 +1,28 @@ -package org.pnfolder.pnlibrary.core.commands +package org.pnfolder.pnlibrary.core.commands.engine -import org.pnfolder.pnlibrary.api.commands.ArgumentSpec -import org.pnfolder.pnlibrary.api.commands.ArgumentType import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.CommandError -import org.pnfolder.pnlibrary.api.commands.CommandNode -import org.pnfolder.pnlibrary.api.commands.CommandNodeKind -import org.pnfolder.pnlibrary.api.commands.ConsoleOnly -import org.pnfolder.pnlibrary.api.commands.IncompleteCommand -import org.pnfolder.pnlibrary.api.commands.NoPermission -import org.pnfolder.pnlibrary.api.commands.PlayerOnly -import org.pnfolder.pnlibrary.api.commands.SenderRule -import org.pnfolder.pnlibrary.api.commands.UnknownArgument -import org.pnfolder.pnlibrary.api.commands.completedSuggestions +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentSpec +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandNode +import org.pnfolder.pnlibrary.api.commands.definition.CommandNodeKind +import org.pnfolder.pnlibrary.api.commands.definition.SenderRule +import org.pnfolder.pnlibrary.api.commands.definition.completedSuggestions +import org.pnfolder.pnlibrary.api.commands.error.CommandError +import org.pnfolder.pnlibrary.api.commands.error.ConsoleOnly +import org.pnfolder.pnlibrary.api.commands.error.IncompleteCommand +import org.pnfolder.pnlibrary.api.commands.error.NoPermission +import org.pnfolder.pnlibrary.api.commands.error.PlayerOnly +import org.pnfolder.pnlibrary.api.commands.error.UnknownArgument import java.util.LinkedHashMap import java.util.Locale import java.util.concurrent.CompletionStage internal sealed class CommandRoute { data class Executable(val node: CommandNode, val context: CommandContext, val path: List) : CommandRoute() - data class Problem(val error: CommandError, val nodes: List) : CommandRoute() } -/** Parses and completes immutable command trees without knowing the native server platform. */ internal class CommandTreeRouter { fun route(command: CommandDefinition, context: CommandContext): CommandRoute { var node = command.root @@ -67,7 +65,6 @@ internal class CommandTreeRouter { else problem(IncompleteCommand(usage(path, node, routed)), nodes) } - /** Why the sender may not enter [node], or `null` when it may. */ private fun blocked(node: CommandNode, context: CommandContext): CommandError? { if (!allowed(node, context)) return NoPermission(node.permission.orEmpty()) return when (node.senderRule) { @@ -83,7 +80,7 @@ internal class CommandTreeRouter { var node = command.root val values = LinkedHashMap() var routed = context.copy(parsedValues = values.toMap()) - if (!allowed(node, routed)) return completedSuggestions(emptyList()) + if (!canSuggest(node, routed)) return completedSuggestions(emptyList()) val consumed = if (context.arguments.isEmpty()) emptyList() else context.arguments.dropLast(1) val partial = if (context.arguments.isEmpty()) context.currentInput else context.arguments.last() @@ -93,7 +90,7 @@ internal class CommandTreeRouter { val child = childFor(node, token) ?: return if (node.acceptsExtraArguments) node.suggestions.suggest(routed.copy(currentInput = partial)) else completedSuggestions(emptyList()) - if (!allowed(child, routed)) return completedSuggestions(emptyList()) + if (!canSuggest(child, routed)) return completedSuggestions(emptyList()) if (child.kind == CommandNodeKind.ARGUMENT) { val parsed = parse(child, token) ?: return completedSuggestions(emptyList()) values[child.name] = parsed @@ -112,12 +109,12 @@ internal class CommandTreeRouter { private fun lastSuggestions(node: CommandNode, suggestionContext: CommandContext, partial: String): CompletionStage> { val literals = node.children.asSequence() .filter { it.kind == CommandNodeKind.LITERAL } - .filter { allowed(it, suggestionContext) } + .filter { canSuggest(it, suggestionContext) } .map { it.name } .filter { it.startsWith(partial, ignoreCase = true) } .toList() val argument = node.children.firstOrNull { it.kind == CommandNodeKind.ARGUMENT } - ?.takeIf { allowed(it, suggestionContext) } + ?.takeIf { canSuggest(it, suggestionContext) } val stage = when { argument != null -> argument.suggestions.suggest(suggestionContext).thenApply { it + builtInSuggestions(argument) } node.children.isEmpty() || node.acceptsExtraArguments -> node.suggestions.suggest(suggestionContext) @@ -146,12 +143,23 @@ internal class CommandTreeRouter { return permissionAllowed && node.availability.isAvailable(context) } + // allowed() checks only permission; senderRule is checked separately in route() via blocked(). + // Suggestions must respect senderRule too — otherwise console sees player-only tab completions. + private fun canSuggest(node: CommandNode, context: CommandContext): Boolean { + if (!allowed(node, context)) return false + return when (node.senderRule) { + SenderRule.PLAYER -> !context.sender.isConsole + SenderRule.CONSOLE -> context.sender.isConsole + SenderRule.ANY -> true + } + } + @Suppress("UNCHECKED_CAST") private fun parse(node: CommandNode, token: String): Any? = (node.argumentType as? ArgumentType)?.parse(token) private fun usage(path: List, node: CommandNode, context: CommandContext): String { - val accessible = node.children.filter { allowed(it, context) } + val accessible = node.children.filter { canSuggest(it, context) } val suffix = when { accessible.isEmpty() -> "" accessible.size == 1 -> " " + display(accessible.single()) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/TabSuggestions.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/TabSuggestions.kt similarity index 94% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/TabSuggestions.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/TabSuggestions.kt index f11af18b4..4125d114c 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/TabSuggestions.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/engine/TabSuggestions.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.commands +package org.pnfolder.pnlibrary.core.commands.engine import java.util.concurrent.CompletionStage import java.util.concurrent.TimeUnit diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusChat.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusChat.kt index d347e831d..8d7f4b90f 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusChat.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusChat.kt @@ -3,27 +3,23 @@ package org.pnfolder.pnlibrary.core.commands.events import net.kyori.adventure.text.Component import net.kyori.adventure.text.event.ClickEvent import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.events.EventInspector -import org.pnfolder.pnlibrary.api.events.ListenerInfo -import java.time.LocalDate +import org.pnfolder.pnlibrary.api.events.inspect.EventInspector +import org.pnfolder.pnlibrary.api.events.inspect.ListenerInfo +import org.pnfolder.pnlibrary.core.text.BAR_WIDTH +import org.pnfolder.pnlibrary.core.text.nanosText +import org.pnfolder.pnlibrary.core.text.shortName -internal fun kit(context: CommandContext) = ChatKit(ChatReader.of(context.sender)) +internal fun busKit(context: CommandContext) = ChatKit(ChatReader.of(context.sender)) -internal fun bar(kit: ChatKit, value: Long, busiest: Long): String { +internal fun busBar(kit: ChatKit, value: Long, busiest: Long): String { val width = ((value * BAR_WIDTH + busiest - 1) / busiest.coerceAtLeast(1)).toInt().coerceIn(1, BAR_WIDTH) return (if (kit.reader.ascii) "#" else "█").repeat(width) } -internal fun dayTitle(date: LocalDate, today: LocalDate): String = when (date) { - today -> "Сегодня" - today.minusDays(1) -> "Вчера" - else -> DAY.format(date) -} - -internal fun hints(kit: ChatKit): List = +internal fun busHints(kit: ChatKit): List = if (kit.reader.interactive) emptyList() else kit.commandHints( "$ROOT [all|listened|called|denied] [страница]" to "список событий", @@ -42,30 +38,22 @@ internal fun hints(kit: ChatKit): List = "$ROOT history of <событие>" to "вызовы одного события по дням", ) -internal fun footer(kit: ChatKit, vararg buttons: Component?): List = listOfNotNull(kit.actions(*buttons)) +internal fun busFooter(kit: ChatKit, vararg buttons: Component?): List = listOfNotNull(kit.actions(*buttons)) internal fun backToEvents(kit: ChatKit): Component = kit.button("назад", ROOT, "К списку событий", ChatPalette.ACCENT) -internal fun pageCount(total: Int): Int = ((total + PAGE_SIZE - 1) / PAGE_SIZE).coerceAtLeast(1) - -internal fun shortName(name: String): String = name.substringAfterLast('.') - -internal fun micros(nanos: Long): String = - if (nanos >= NANOS_PER_MILLI) "%.1f мс".format(nanos / NANOS_PER_MILLI.toDouble()) - else "%.1f мкс".format(nanos / NANOS_PER_MICRO.toDouble()) - -internal fun ownerOf(info: ListenerInfo): String = info.module?.let { "${info.plugin}/$it" } ?: info.plugin.toString() +internal fun ListenerInfo.ownerLabel(): String = module?.let { "$plugin/$it" } ?: plugin.toString() internal fun listenerRow(kit: ChatKit, info: ListenerInfo): Component = listenerRow( kit, info, - Component.empty().append(kit.text(ownerOf(info), ChatPalette.ACCENT)).append(kit.dot()) + Component.empty().append(kit.text(info.ownerLabel(), ChatPalette.ACCENT)).append(kit.dot()) .append(kit.text(shortName(info.eventType), ChatPalette.TEXT)), ) /** A listener on the page of its own event, where the event name would only repeat the title. */ internal fun eventListenerRow(kit: ChatKit, info: ListenerInfo): Component = - listenerRow(kit, info, kit.text(ownerOf(info), ChatPalette.ACCENT)) + listenerRow(kit, info, kit.text(info.ownerLabel(), ChatPalette.ACCENT)) private fun listenerRow(kit: ChatKit, info: ListenerInfo, title: Component): Component { var line = kit.text(" ").append(title).append(kit.text(" приоритет ${info.priority}", ChatPalette.SOFT)) @@ -74,13 +62,13 @@ private fun listenerRow(kit: ChatKit, info: ListenerInfo, title: Component): Com if (!kit.reader.interactive) return line.append(kit.text(" ${info.source}", ChatPalette.FAINT)) return line.hoverEvent( kit.tooltip( - kit.text(ownerOf(info), ChatPalette.ACCENT), + kit.text(info.ownerLabel(), ChatPalette.ACCENT), kit.blank(), kit.hoverField("Событие", kit.text(info.eventType, ChatPalette.TEXT)), kit.hoverField("Источник", kit.text(info.source, ChatPalette.TEXT)), kit.hoverField("Приоритет", kit.text(info.priority.toString(), ChatPalette.TEXT)), kit.hoverField("Запусков", kit.text(info.invocations.toString(), ChatPalette.TEXT)), - kit.hoverField("Среднее время", kit.text(micros(info.averageNanos), ChatPalette.TEXT)), + kit.hoverField("Среднее время", kit.text(nanosText(info.averageNanos), ChatPalette.TEXT)), kit.hoverField("Ошибок", kit.text(info.failures.toString(), if (info.failures > 0) ChatPalette.DANGER else ChatPalette.TEXT)), ), ).clickEvent(ClickEvent.runCommand("$ROOT view ${info.eventType}")) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusCommandSettings.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusCommandSettings.kt deleted file mode 100644 index 69713605b..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusCommandSettings.kt +++ /dev/null @@ -1,25 +0,0 @@ -package org.pnfolder.pnlibrary.core.commands.events - -import org.pnfolder.pnlibrary.api.events.EventInfo - -internal const val ROOT = "/pn bus" -internal const val PAGE_SIZE = 8 -internal const val TOP_SIZE = 10 -internal val RANGES = linkedMapOf("1h" to 1, "24h" to 24, "7d" to 168, "30d" to 720) -internal const val MAX_TRACES = 6 -internal const val DAYS_PER_PAGE = 7 -internal const val EVENTS_PER_PAGE = 6 -internal const val HOVER_EVENTS = 5 -internal const val MAX_SUGGESTED_DAYS = 31 -internal const val BAR_WIDTH = 12 -internal val DAY = java.time.format.DateTimeFormatter.ofPattern("d MMMM", java.util.Locale("ru")) -internal const val NANOS_PER_MICRO = 1_000L -internal const val NANOS_PER_MILLI = 1_000_000L - -internal val FILTERS: List Boolean>> = listOf( - "all" to { _: EventInfo -> true }, - "listened" to { e: EventInfo -> e.listeners > 0 }, - "called" to { e: EventInfo -> e.calls > 0 }, - "denied" to { e: EventInfo -> e.denied > 0 }, -) -internal val LABELS = mapOf("all" to "все", "listened" to "со слушателями", "called" to "вызывались", "denied" to "с отказами") diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusConstants.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusConstants.kt new file mode 100644 index 000000000..46d633320 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusConstants.kt @@ -0,0 +1,8 @@ +package org.pnfolder.pnlibrary.core.commands.events + +internal const val ROOT = "/pn bus" +internal const val PAGE_SIZE = 8 +internal const val TOP_SIZE = 10 +internal val RANGES = linkedMapOf("1h" to 1, "24h" to 24, "7d" to 168, "30d" to 720) +internal const val DAYS_PER_PAGE = 7 +internal const val EVENTS_PER_PAGE = 6 diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusEventPages.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusEventPages.kt index 9532bf76c..b2f581632 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusEventPages.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusEventPages.kt @@ -3,25 +3,27 @@ package org.pnfolder.pnlibrary.core.commands.events import net.kyori.adventure.text.Component import net.kyori.adventure.text.event.ClickEvent import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.api.commands.CommandContext import org.pnfolder.pnlibrary.api.events.Event -import org.pnfolder.pnlibrary.api.events.EventInfo -import org.pnfolder.pnlibrary.api.events.EventInspector +import org.pnfolder.pnlibrary.api.events.inspect.EventInfo +import org.pnfolder.pnlibrary.api.events.inspect.EventInspector import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.common.text.RussianText -import org.pnfolder.pnlibrary.core.commands.chatPager +import org.pnfolder.pnlibrary.core.commands.engine.chatPager +import org.pnfolder.pnlibrary.core.commands.engine.pageCount +import org.pnfolder.pnlibrary.core.text.shortName +/** Chat pages describing bus events. */ internal class BusEventPages(private val library: PnLibrary) { private val bus: EventInspector get() = library.events.inspector fun list(context: CommandContext, word: String, requestedPage: Int) { - val kit = kit(context) + val kit = busKit(context) val all = bus.events() - val filter = FILTERS.first { it.first == word } - val shown = all.filter(filter.second) + val shown = all.filter(BusFilter.named(word)::keeps) val traced = bus.tracedEvents() - val pages = pageCount(shown.size) + val pages = pageCount(shown.size, PAGE_SIZE) val page = requestedPage.coerceIn(1, pages) val total = bus.listeners().size val queued = bus.asyncQueued().let { if (it > 0) ", в очереди $it" else "" } @@ -39,26 +41,27 @@ internal class BusEventPages(private val library: PnLibrary) { lines += chatPager(kit, "$ROOT $word", page, pages) } lines += kit.blank() - lines += footer(kit, kit.option("все слушатели", "$ROOT listeners", "Каждый слушатель каждого плагина", ChatPalette.ACCENT), + lines += busFooter(kit, kit.option("все слушатели", "$ROOT listeners", "Каждый слушатель каждого плагина", ChatPalette.ACCENT), kit.option("записи", "$ROOT traces", "Записанные вызовы", ChatPalette.ACCENT), kit.option("история", "$ROOT history", "Сколько раз вызывали по дням", ChatPalette.ACCENT)) - lines += hints(kit) + lines += busHints(kit) lines.forEach(context.sender::send) } private fun tabs(kit: ChatKit, all: List, current: String): Component { var line = kit.text(" Показать: ", ChatPalette.LABEL) - FILTERS.forEachIndexed { index, (word, predicate) -> + BusFilter.entries.forEachIndexed { index, filter -> + val word = filter.word if (index > 0) line = line.append(kit.text(" ")) - val count = all.count(predicate) + val count = all.count(filter::keeps) val open = word == current val body = if (open) ChatPalette.ACCENT else if (count == 0) ChatPalette.FAINT else ChatPalette.SOFT - val label = "${LABELS.getValue(word)} $count" + val label = "${filter.label} $count" val button = kit.text("[", ChatPalette.FAINT).append(kit.text(label, body)).append(kit.text("]", ChatPalette.FAINT)) line = line.append( if (open || !kit.reader.interactive) button else button.clickEvent(ClickEvent.runCommand("$ROOT $word")).hoverEvent( - kit.tooltip(kit.text("Нажмите, чтобы показать: ${LABELS.getValue(word)}", ChatPalette.ACCENT), kit.blank(), + kit.tooltip(kit.text("Нажмите, чтобы показать: ${filter.label}", ChatPalette.ACCENT), kit.blank(), kit.text("$ROOT $word", ChatPalette.LABEL)), ), ) @@ -103,7 +106,7 @@ internal class BusEventPages(private val library: PnLibrary) { fun view(context: CommandContext, typed: String) { val name = bus.resolve(typed) - val kit = kit(context) + val kit = busKit(context) val type = bus.eventType(name) val info = bus.events().firstOrNull { it.eventType == name } if (info == null) { @@ -128,7 +131,7 @@ internal class BusEventPages(private val library: PnLibrary) { if (listeners.isEmpty()) lines += kit.note(" Никто не слушает это событие.") listeners.forEach { lines += eventListenerRow(kit, it) } lines += kit.blank() - lines += footer(kit, backToEvents(kit), + lines += busFooter(kit, backToEvents(kit), kit.button("записи", "$ROOT traces $name", "Записанные вызовы этого события", ChatPalette.ACCENT), kit.button("история", "$ROOT history of $name", "Вызовы этого события по дням", ChatPalette.ACCENT)) if (!kit.reader.interactive) lines += kit.note("Запись: $ROOT trace $name | $ROOT trace off $name") @@ -152,7 +155,7 @@ internal class BusEventPages(private val library: PnLibrary) { val name = bus.resolve(typed) val type = bus.eventType(name) if (type == null) { - context.sender.send(kit(context).text("Такого события нет: $name. Список: $ROOT", ChatPalette.DANGER)) + context.sender.send(busKit(context).text("Такого события нет: $name. Список: $ROOT", ChatPalette.DANGER)) return } change(type) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusFilter.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusFilter.kt new file mode 100644 index 000000000..ccb01d144 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusFilter.kt @@ -0,0 +1,18 @@ +package org.pnfolder.pnlibrary.core.commands.events + +import org.pnfolder.pnlibrary.api.events.inspect.EventInfo + +/** A way to narrow the event list: the word typed after `/pn bus`, its label on the tab, and which events it keeps. */ +internal enum class BusFilter(val word: String, val label: String, private val test: (EventInfo) -> Boolean) { + ALL("all", "все", { true }), + LISTENED("listened", "со слушателями", { it.listeners > 0 }), + CALLED("called", "вызывались", { it.calls > 0 }), + DENIED("denied", "с отказами", { it.denied > 0 }), + ; + + fun keeps(event: EventInfo): Boolean = test(event) + + companion object { + fun named(word: String): BusFilter = entries.first { it.word == word } + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusHistoryPages.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusHistoryPages.kt index 9d7067dd3..c936696f3 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusHistoryPages.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusHistoryPages.kt @@ -3,15 +3,20 @@ package org.pnfolder.pnlibrary.core.commands.events import net.kyori.adventure.text.Component import net.kyori.adventure.text.event.ClickEvent import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.events.EventDay -import org.pnfolder.pnlibrary.api.events.EventInspector +import org.pnfolder.pnlibrary.api.events.inspect.EventInspector +import org.pnfolder.pnlibrary.api.events.inspect.history.EventDay import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.common.text.RussianText import org.pnfolder.pnlibrary.common.time.DisplayZone -import org.pnfolder.pnlibrary.core.commands.chatPager +import org.pnfolder.pnlibrary.core.commands.engine.chatPager +import org.pnfolder.pnlibrary.core.commands.engine.pageCount +import org.pnfolder.pnlibrary.core.text.DAY +import org.pnfolder.pnlibrary.core.text.dayTitle +import org.pnfolder.pnlibrary.core.text.shortName +/** Chat pages with recent bus history. */ internal class BusHistoryPages(private val library: PnLibrary) { private val bus: EventInspector get() = library.events.inspector @@ -20,10 +25,10 @@ internal class BusHistoryPages(private val library: PnLibrary) { * events were called and how many calls were denied. A click opens that day; for one event it opens the event. */ fun history(context: CommandContext, typed: String?, requestedPage: Int) { - val kit = kit(context) + val kit = busKit(context) val name = typed?.let(bus::resolve) val days = bus.history(name).groupBy { it.date }.entries.toList() - val pages = ((days.size + DAYS_PER_PAGE - 1) / DAYS_PER_PAGE).coerceAtLeast(1) + val pages = pageCount(days.size, DAYS_PER_PAGE) val page = requestedPage.coerceIn(1, pages) val shown = days.drop((page - 1) * DAYS_PER_PAGE).take(DAYS_PER_PAGE) val keep = bus.historyDays @@ -44,7 +49,7 @@ internal class BusHistoryPages(private val library: PnLibrary) { } if (name == null && shown.isNotEmpty()) lines += kit.note("Нажмите на день, чтобы увидеть его события.", ChatPalette.FAINT) lines += kit.blank() - lines += footer(kit, backToEvents(kit)) + lines += busFooter(kit, backToEvents(kit)) lines.forEach(context.sender::send) } @@ -58,7 +63,7 @@ internal class BusHistoryPages(private val library: PnLibrary) { ): Component { val total = entries.sumOf { it.calls } val denied = entries.sumOf { it.denied } - val bar = bar(kit, total, busiest) + val bar = busBar(kit, total, busiest) var line = kit.text(" ").append(kit.text(bar, ChatPalette.INFO)).append(kit.text(" ${dayTitle(date, today)}", ChatPalette.ACCENT)) .append(kit.text(" $total ${RussianText.plural(total, "вызов", "вызова", "вызовов")}", ChatPalette.TEXT)) if (name == null) { @@ -78,14 +83,14 @@ internal class BusHistoryPages(private val library: PnLibrary) { } fun historyDay(context: CommandContext, typed: String, requestedPage: Int) { - val kit = kit(context) + val kit = busKit(context) val date = runCatching { java.time.LocalDate.parse(typed) }.getOrNull() if (date == null) { context.sender.send(kit.text("Дата должна быть вида 2026-10-27. Список дней: $ROOT history", ChatPalette.DANGER)) return } val entries = bus.history().filter { it.date == date }.sortedByDescending { it.calls } - val pages = ((entries.size + EVENTS_PER_PAGE - 1) / EVENTS_PER_PAGE).coerceAtLeast(1) + val pages = pageCount(entries.size, EVENTS_PER_PAGE) val page = requestedPage.coerceIn(1, pages) val today = java.time.LocalDate.now(DisplayZone.zone) val total = entries.sumOf { it.calls } @@ -104,12 +109,12 @@ internal class BusHistoryPages(private val library: PnLibrary) { lines += chatPager(kit, "$ROOT history day $date", page, pages) } lines += kit.blank() - lines += footer(kit, kit.button("назад", "$ROOT history", "К списку дней", ChatPalette.ACCENT)) + lines += busFooter(kit, kit.button("назад", "$ROOT history", "К списку дней", ChatPalette.ACCENT)) lines.forEach(context.sender::send) } private fun historyRow(kit: ChatKit, day: EventDay, busiest: Long): Component { - var line = kit.text(" ").append(kit.text(bar(kit, day.calls, busiest), ChatPalette.INFO)) + var line = kit.text(" ").append(kit.text(busBar(kit, day.calls, busiest), ChatPalette.INFO)) .append(kit.text(" ${day.calls}", ChatPalette.TEXT)).append(kit.text(" ${shortName(day.eventType)}", ChatPalette.ACCENT)) if (day.denied > 0) line = line.append(kit.text(" отказов ${day.denied}", ChatPalette.DANGER)) if (!kit.reader.interactive) return line @@ -126,3 +131,5 @@ internal class BusHistoryPages(private val library: PnLibrary) { ).clickEvent(ClickEvent.runCommand("$ROOT view ${day.eventType}")) } } + +private const val HOVER_EVENTS = 5 diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusListenerPages.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusListenerPages.kt index 91493c242..9ea256056 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusListenerPages.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusListenerPages.kt @@ -1,25 +1,29 @@ package org.pnfolder.pnlibrary.core.commands.events import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.events.EventInfo -import org.pnfolder.pnlibrary.api.events.EventInspector -import org.pnfolder.pnlibrary.api.events.ListenerInfo +import org.pnfolder.pnlibrary.api.events.inspect.EventInfo +import org.pnfolder.pnlibrary.api.events.inspect.EventInspector +import org.pnfolder.pnlibrary.api.events.inspect.ListenerInfo import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.common.time.DisplayZone -import org.pnfolder.pnlibrary.core.commands.chatPager +import org.pnfolder.pnlibrary.core.commands.engine.chatPager +import org.pnfolder.pnlibrary.core.commands.engine.pageCount +import org.pnfolder.pnlibrary.core.text.nanosText +import org.pnfolder.pnlibrary.core.text.shortName import java.nio.file.Path import java.time.LocalDateTime import java.time.temporal.ChronoUnit +/** Chat pages describing bus listeners. */ internal class BusListenerPages(private val library: PnLibrary) { private val bus: EventInspector get() = library.events.inspector fun listeners(context: CommandContext, requestedPage: Int) { - val kit = kit(context) + val kit = busKit(context) val all = bus.listeners() - val pages = pageCount(all.size) + val pages = pageCount(all.size, PAGE_SIZE) val page = requestedPage.coerceIn(1, pages) val lines = mutableListOf( kit.blank(), @@ -33,7 +37,7 @@ internal class BusListenerPages(private val library: PnLibrary) { lines += chatPager(kit, "$ROOT listeners", page, pages) } lines += kit.blank() - lines += footer(kit, backToEvents(kit)) + lines += busFooter(kit, backToEvents(kit)) lines.forEach(context.sender::send) } @@ -52,22 +56,22 @@ internal class BusListenerPages(private val library: PnLibrary) { fun topDenied(context: CommandContext) = top(context, "Чаще всего отклонялись", "Отказов не было.") { it.denied } private fun top(context: CommandContext, title: String, empty: String, count: (EventInfo) -> Long) { - val kit = kit(context) + val kit = busKit(context) val ranked = bus.events().filter { count(it) > 0 }.sortedByDescending(count).take(TOP_SIZE) val busiest = ranked.firstOrNull()?.let(count) ?: 0 val lines = mutableListOf(kit.blank(), kit.header(title, kit.text("${ranked.size}", ChatPalette.LABEL)), kit.blank()) if (ranked.isEmpty()) lines += kit.note(empty) ranked.forEach { - lines += kit.text(" ").append(kit.text(bar(kit, count(it), busiest), ChatPalette.SOFT)) + lines += kit.text(" ").append(kit.text(busBar(kit, count(it), busiest), ChatPalette.SOFT)) .append(kit.text(" ${count(it)} ", ChatPalette.LABEL)).append(kit.text(shortName(it.eventType), ChatPalette.TEXT)) } lines += kit.blank() - lines += footer(kit, backToEvents(kit)) + lines += busFooter(kit, backToEvents(kit)) lines.forEach(context.sender::send) } fun range(context: CommandContext, word: String) { - val kit = kit(context) + val kit = busKit(context) val hours = RANGES.getValue(word) val totals = callsSince(LocalDateTime.now(DisplayZone.zone).truncatedTo(ChronoUnit.HOURS).minusHours(hours - 1L)) val ranked = totals.entries.sortedByDescending { it.value.calls }.take(TOP_SIZE) @@ -80,17 +84,18 @@ internal class BusListenerPages(private val library: PnLibrary) { if (bus.historyDays <= 0) lines += kit.note("История выключена.") else if (ranked.isEmpty()) lines += kit.note("За этот период событий не было.") ranked.forEach { (name, sums) -> - var line = kit.text(" ").append(kit.text(bar(kit, sums.calls, busiest), ChatPalette.SOFT)) + var line = kit.text(" ").append(kit.text(busBar(kit, sums.calls, busiest), ChatPalette.SOFT)) .append(kit.text(" ${sums.calls} ", ChatPalette.LABEL)).append(kit.text(shortName(name), ChatPalette.TEXT)) .append(kit.text(" ${"%.1f".format(sums.calls.toDouble() / hours)}/ч", ChatPalette.FAINT)) if (sums.denied > 0) line = line.append(kit.text(" отказов ${sums.denied}", ChatPalette.DANGER)) lines += line } lines += kit.blank() - lines += footer(kit, backToEvents(kit)) + lines += busFooter(kit, backToEvents(kit)) lines.forEach(context.sender::send) } + /** Running call counters of a listener group. */ private class Totals(var calls: Long = 0, var denied: Long = 0) private fun callsSince(since: LocalDateTime): Map { @@ -120,16 +125,16 @@ internal class BusListenerPages(private val library: PnLibrary) { } private fun listenerPage(context: CommandContext, requestedPage: Int, all: List, title: String, empty: String, base: String) { - val kit = kit(context) - val pages = pageCount(all.size) + val kit = busKit(context) + val pages = pageCount(all.size, PAGE_SIZE) val page = requestedPage.coerceIn(1, pages) val lines = mutableListOf(kit.blank(), kit.header(title, kit.text("${all.size}", ChatPalette.LABEL)), kit.blank()) if (all.isEmpty()) lines += kit.note(empty) all.drop((page - 1) * PAGE_SIZE).take(PAGE_SIZE).forEach { info -> - var line = kit.text(" ").append(kit.text(ownerOf(info), ChatPalette.ACCENT)).append(kit.dot()) + var line = kit.text(" ").append(kit.text(info.ownerLabel(), ChatPalette.ACCENT)).append(kit.dot()) .append(kit.text(shortName(info.eventType), ChatPalette.TEXT)) - .append(kit.text(" средн. ${micros(info.averageNanos)}", ChatPalette.LABEL)) - .append(kit.text(" макс. ${micros(info.maxNanos)}", ChatPalette.SOFT)) + .append(kit.text(" средн. ${nanosText(info.averageNanos)}", ChatPalette.LABEL)) + .append(kit.text(" макс. ${nanosText(info.maxNanos)}", ChatPalette.SOFT)) .append(kit.text(" запусков ${info.invocations}", ChatPalette.FAINT)) if (info.failures > 0) line = line.append(kit.text(" ошибок ${info.failures}", ChatPalette.DANGER)) lines += line @@ -139,7 +144,7 @@ internal class BusListenerPages(private val library: PnLibrary) { lines += chatPager(kit, base, page, pages) } lines += kit.blank() - lines += footer(kit, backToEvents(kit)) + lines += busFooter(kit, backToEvents(kit)) lines.forEach(context.sender::send) } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusTracePages.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusTracePages.kt index 9019073a7..0de44df17 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusTracePages.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/BusTracePages.kt @@ -2,19 +2,22 @@ package org.pnfolder.pnlibrary.core.commands.events import net.kyori.adventure.text.Component import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.events.DispatchMode -import org.pnfolder.pnlibrary.api.events.EventInspector -import org.pnfolder.pnlibrary.api.events.EventTrace +import org.pnfolder.pnlibrary.api.events.bus.DispatchMode +import org.pnfolder.pnlibrary.api.events.inspect.EventInspector +import org.pnfolder.pnlibrary.api.events.inspect.trace.EventTrace import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.core.text.NANOS_PER_MICRO +import org.pnfolder.pnlibrary.core.text.shortName +/** Chat pages with event trace output. */ internal class BusTracePages(private val library: PnLibrary) { private val bus: EventInspector get() = library.events.inspector fun traces(context: CommandContext, typed: String?) { val name = typed?.let(bus::resolve) - val kit = kit(context) + val kit = busKit(context) val all = bus.traces().filter { name == null || it.eventName == name } val lines = mutableListOf( kit.blank(), @@ -23,7 +26,7 @@ internal class BusTracePages(private val library: PnLibrary) { ) if (all.isEmpty()) lines += kit.note("Пусто. Включите запись на странице события: $ROOT view <событие>") all.takeLast(MAX_TRACES).reversed().forEach { lines += traceBlock(kit, it) } - lines += footer(kit, backToEvents(kit), + lines += busFooter(kit, backToEvents(kit), if (all.isEmpty()) null else kit.button("очистить", "$ROOT clear", "Забыть записанные вызовы", ChatPalette.DANGER)) lines.forEach(context.sender::send) } @@ -54,3 +57,5 @@ internal class BusTracePages(private val library: PnLibrary) { return lines } } + +private const val MAX_TRACES = 6 diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/EventBusCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/EventBusCommand.kt index 87bc1cc39..238d3f15f 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/EventBusCommand.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/events/EventBusCommand.kt @@ -1,11 +1,12 @@ package org.pnfolder.pnlibrary.core.commands.events -import org.pnfolder.pnlibrary.api.commands.ArgumentType -import org.pnfolder.pnlibrary.api.commands.CommandBuilder -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command -import org.pnfolder.pnlibrary.api.events.EventInspector +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandBuilder +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command +import org.pnfolder.pnlibrary.api.events.inspect.EventInspector import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.core.text.shortName /** * `/pn bus`: a window into the event bus, shared by every platform and drawn like the other `/pn` pages. @@ -51,7 +52,7 @@ class EventBusCommand(private val library: PnLibrary) { private fun CommandBuilder.eventViews() { executes { events.list(it, "all", 1) } - FILTERS.forEach { (word, _) -> + BusFilter.entries.map(BusFilter::word).forEach { word -> literal(word) { executes { events.list(it, word, 1) } argument("page", ArgumentType.integer()) { executes { events.list(it, word, it.get("page")) } } @@ -159,3 +160,5 @@ class EventBusCommand(private val library: PnLibrary) { const val PERMISSION = "pnlibrary.events.bus" } } + +private const val MAX_SUGGESTED_DAYS = 31 diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/groups/GroupsCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/groups/GroupsCommand.kt index 3bd420ee1..2786843fb 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/groups/GroupsCommand.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/groups/GroupsCommand.kt @@ -1,17 +1,17 @@ package org.pnfolder.pnlibrary.core.commands.groups import org.pnfolder.pnlibrary.api.chat.ChatNotice -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.commands.ArgumentType -import org.pnfolder.pnlibrary.api.commands.CommandBuilder +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.CommandNodeBuilder -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandBuilder +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandNodeBuilder +import org.pnfolder.pnlibrary.api.commands.definition.command import org.pnfolder.pnlibrary.core.link.Link -import org.pnfolder.pnlibrary.core.link.NetworkServer -import org.pnfolder.pnlibrary.core.link.RemoteAction import org.pnfolder.pnlibrary.core.link.ServerGroups +import org.pnfolder.pnlibrary.core.link.remote.RemoteAction +import org.pnfolder.pnlibrary.core.link.report.NetworkServer /** * `/pn groups` on a proxy: groups of servers and the plugins each of them should have, compared with what the diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/groups/GroupsPages.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/groups/GroupsPages.kt index d8cd773be..98f6136b9 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/groups/GroupsPages.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/groups/GroupsPages.kt @@ -3,13 +3,13 @@ package org.pnfolder.pnlibrary.core.commands.groups import net.kyori.adventure.text.event.ClickEvent import org.pnfolder.pnlibrary.api.chat.ChatKit import org.pnfolder.pnlibrary.api.chat.ChatNotice -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandContext import org.pnfolder.pnlibrary.common.text.RussianText -import org.pnfolder.pnlibrary.core.link.NetworkServer import org.pnfolder.pnlibrary.core.link.ServerGroups +import org.pnfolder.pnlibrary.core.link.report.NetworkServer internal const val GROUPS_ROOT = "/pn groups" @@ -126,9 +126,10 @@ internal class GroupsPages(private val groups: ServerGroups, private val servers lines += kit.section("Серверы") if (group.servers.isEmpty()) lines += kit.note("Серверов нет: $ROOT join ${group.name} <сервер>", ChatPalette.FAINT) groups.compare(group, servers()).forEach { state -> + val known = state.known val verdict = when { - state.known == null -> kit.text("не присылал отчёт", ChatPalette.DANGER) - !state.known!!.online -> kit.text("нет связи", ChatPalette.DANGER) + known == null -> kit.text("не присылал отчёт", ChatPalette.DANGER) + !known.online -> kit.text("нет связи", ChatPalette.DANGER) state.ok -> kit.text("всё в порядке", ChatPalette.ACCENT) else -> kit.text("", ChatPalette.TEXT) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/modules/DiskUsage.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/modules/DiskUsage.kt new file mode 100644 index 000000000..a600b45d9 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/modules/DiskUsage.kt @@ -0,0 +1,106 @@ +package org.pnfolder.pnlibrary.core.commands.modules + +import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import java.io.File +import java.nio.file.Files +import java.nio.file.Path + +/** + * What one plugin takes on the disk of this server, split by kind; plain values, so it also crosses to another server. + * + * @property name plugin name as its folder or jar is called + * @property jar the plugin's own jar + * @property configs settings files (`yml`, `json`, `toml`, `properties`, ...) in its folder + * @property libraries jars it downloaded into a `lib`, `libs` or `libraries` folder + * @property logs log files in its folder + * @property data everything else in its folder: databases, caches, saved players + */ +data class DiskRow(val name: String, val jar: Long, val configs: Long, val libraries: Long, val logs: Long, val data: Long) { + val total: Long get() = jar + configs + libraries + logs + data +} + +/** + * The disk of the `plugins` folder. + * + * @property registeredLibraries size of the jars of libraries that plugins and modules registered through pnLibrary + * @property free free space on the disk, or -1 when unknown + * @property capacity size of the disk, or -1 when unknown + */ +data class DiskReport(val rows: List, val registeredLibraries: Long, val free: Long, val capacity: Long) { + val total: Long get() = rows.sumOf { it.total } + + companion object { + val EMPTY = DiskReport(emptyList(), 0, -1, -1) + } +} + +/** Counts the bytes of the `plugins` folder, plugin by plugin; never fails, an unreadable file counts as zero. */ +object DiskUsage { + private val CONFIGS = setOf("yml", "yaml", "json", "toml", "properties", "conf", "cfg", "hocon", "ini", "xml") + private val LIBRARY_FOLDERS = setOf("lib", "libs", "libraries") + + /** The `plugins` folder of this server; the runtime sets it at start, `null` until then. */ + @Volatile + var pluginsFolder: Path? = null + + /** Scans [plugins]; [registered] are the jars of registered libraries, counted once each. */ + fun scan(plugins: Path?, registered: Collection): DiskReport { + val known = registered.map(::File).filter { it.isFile }.distinctBy { it.absolutePath }.sumOf { it.length() } + if (plugins == null || !Files.isDirectory(plugins)) return DiskReport(emptyList(), known, -1, -1) + val rows = linkedMapOf() + val children = runCatching { + Files.list(plugins).use { stream -> stream.collect(java.util.stream.Collectors.toList()) } + }.getOrDefault(emptyList()) + val folders = children.filter { Files.isDirectory(it) } + folders.forEach { rows[it.fileName.toString().lowercase()] = folderRow(it) } + children.filter { it.fileName.toString().endsWith(".jar", true) }.forEach { jar -> + val base = jar.fileName.toString().dropLast(4).replace(Regex("[-_ ]v?\\d.*$"), "") + val key = rows.keys.firstOrNull { it == base.lowercase() } ?: base.lowercase() + val size = runCatching { Files.size(jar) }.getOrDefault(0L) + val row = rows[key] ?: DiskRow(base, 0, 0, 0, 0, 0) + rows[key] = row.copy(jar = row.jar + size) + } + val store = runCatching { Files.getFileStore(plugins) }.getOrNull() + return DiskReport( + rows.values.sortedByDescending { it.total }, known, + store?.let { runCatching { it.usableSpace }.getOrDefault(-1L) } ?: -1, + store?.let { runCatching { it.totalSpace }.getOrDefault(-1L) } ?: -1, + ) + } + + private fun folderRow(folder: Path): DiskRow { + var configs = 0L + var libraries = 0L + var logs = 0L + var data = 0L + runCatching { + Files.walk(folder).use { stream -> + stream.filter { Files.isRegularFile(it) }.forEach { file -> + val size = runCatching { Files.size(file) }.getOrDefault(0L) + val relative = folder.relativize(file) + val first = relative.getName(0).toString().lowercase() + val extension = file.fileName.toString().substringAfterLast('.', "").lowercase() + when { + first in LIBRARY_FOLDERS && relative.nameCount > 1 -> libraries += size + extension in CONFIGS -> configs += size + extension == "log" || first == "logs" || (extension == "gz" && first.startsWith("log")) -> logs += size + else -> data += size + } + } + } + } + return DiskRow(folder.fileName.toString(), 0, configs, libraries, logs, data) + } + + /** `1.5 МБ`, `320 КБ`, `12 Б`; the same text in the command and the menu. */ + fun format(bytes: Long): String = when { + bytes < 0 -> "неизвестно" + bytes < 1024 -> "$bytes Б" + bytes < 1024 * 1024 -> "${bytes / 1024} КБ" + bytes < 1024L * 1024 * 1024 -> "%.1f МБ".format(java.util.Locale.ROOT, bytes / 1048576.0) + else -> "%.2f ГБ".format(java.util.Locale.ROOT, bytes / 1073741824.0) + } + + /** Registered libraries of this server and the size of the jar of each, for [LibraryRow]. */ + fun registeredFiles(library: PnLibrary): List = LibraryRow.all(library).mapNotNull { it.file }.distinct() +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/modules/LibraryRow.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/modules/LibraryRow.kt new file mode 100644 index 000000000..9c2b644ac --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/modules/LibraryRow.kt @@ -0,0 +1,94 @@ +package org.pnfolder.pnlibrary.core.commands.modules + +import org.pnfolder.pnlibrary.api.runtime.PnLibrary + +/** + * One library registered by a plugin or a module, as the menu and `/pn modules libs` show it; plain values, so it also + * crosses to another server. + * + * @property owner `plugin` when the whole plugin registered it, `plugin:module` for one module + * @property conflict another owner uses a different version of the same library + * @property file where the jar lies on this server, or `null` while it is not known + * @property place the same place counted from the server folder (`plugins/pnLibrary/libraries/...`), for people to read + * @property size bytes of that jar, or -1 when unknown + * @property trust [GIVEN] when the author gave a sum the jar is checked against, [NONE] when the jar is not checked + * @property scope `PLUGIN`, `ISOLATED` or `LIBRARY`, see [org.pnfolder.pnlibrary.api.libraries.LibraryScope] + */ +data class LibraryRow( + val owner: String, + val title: String, + val coordinates: String, + val version: String, + val description: String?, + val repositories: List, + val isolated: Boolean, + val required: Boolean, + val verified: Boolean, + val conflict: Boolean, + val file: String? = null, + val size: Long = -1, + val trust: String = NONE, + val scope: String = "PLUGIN", + val place: String? = null, +) { + /** The plugin that owns the library, also when a module registered it. */ + val plugin: String get() = owner.substringBefore(':') + + /** The module that registered the library, or `null` when the whole plugin did. */ + val module: String? get() = owner.substringAfter(':', "").ifEmpty { null } + + /** `плагину shop` or `модулю rewards плагина shop`: whose the library is, in words. */ + val ownerText: String get() = module?.let { "модулю $it плагина $plugin" } ?: "плагину $plugin" + + /** The folder of the jar counted from the server folder, without the file name. */ + val folder: String? get() = place?.substringBeforeLast('/', "")?.ifEmpty { null } + + /** The file name of the jar. */ + val fileName: String? get() = place?.substringAfterLast('/') + + /** Whether this row belongs to [name]: the plugin itself, or any of its modules, or exactly that module. */ + fun belongsTo(name: String): Boolean = owner.equals(name, true) || owner.startsWith("$name:", true) + + companion object { + const val GIVEN = "GIVEN" + const val NONE = "NONE" + + private fun locateLoaded(coordinates: String): String? = + org.pnfolder.pnlibrary.spi.libraries.ExternalLibraries.fileOf(LibraryRow::class.java.classLoader, coordinates) + + /** [file] counted from the server folder with `/`, or as it is when it lies elsewhere. */ + fun placeOf(file: String, root: java.nio.file.Path? = DiskUsage.pluginsFolder?.parent): String { + val path = java.nio.file.Paths.get(file).toAbsolutePath().normalize() + val inside = root?.toAbsolutePath()?.normalize()?.takeIf { path.startsWith(it) } + return (inside?.relativize(path) ?: path).toString().replace('\\', '/') + } + + /** Every library of every plugin and module of this server. */ + fun all(library: PnLibrary, locate: (String) -> String? = ::locateLoaded): List { + val usage = library.plugins.libraryUsage() + val versions = usage.groupBy { it.library.group to it.library.artifact }.mapValues { entry -> entry.value.map { it.library.version }.toSet() } + return usage.map { use -> + val item = use.library + val file = locate(item.coordinates) + val trust = if (item.sources.isNotEmpty() && item.sources.all { it.sha256 != null }) GIVEN else NONE + LibraryRow( + owner = use.owner, + title = item.title, + coordinates = item.coordinates, + version = item.version, + description = item.description, + repositories = item.allSources.map { it.url }, + isolated = item.isolated, + required = item.required, + verified = trust != NONE, + conflict = (versions[item.group to item.artifact]?.size ?: 1) > 1, + file = file, + trust = trust, + scope = item.scope.name, + place = file?.let { placeOf(it) }, + size = file?.let { java.io.File(it) }?.takeIf { it.isFile }?.length() ?: -1, + ) + }.sortedWith(compareBy({ it.owner }, { it.title })) + } + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/modules/ModuleLabels.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/modules/ModuleLabels.kt new file mode 100644 index 000000000..76593615b --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/modules/ModuleLabels.kt @@ -0,0 +1,28 @@ +package org.pnfolder.pnlibrary.core.commands.modules + +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.plugin.ModuleContext +import org.pnfolder.pnlibrary.api.plugin.control.ModuleState +import org.pnfolder.pnlibrary.api.runtime.PnLibrary + +/** Words and colours for module states, shared by `/pn modules` and the menu. */ +object ModuleLabels { + fun label(state: ModuleState): String = when (state) { + ModuleState.ENABLED -> "работает" + ModuleState.DISABLED -> "выключен" + ModuleState.FAILED -> "ошибка" + } + + fun color(state: ModuleState) = when (state) { + ModuleState.ENABLED -> ChatPalette.OK + ModuleState.DISABLED -> ChatPalette.FAINT + ModuleState.FAILED -> ChatPalette.DANGER + } + + /** What a module is called to a person: its own name from the metadata, then its id. */ + fun title(module: ModuleContext): String = module.metadata.name.ifBlank { module.id.value } + + /** Every module of every plugin with the text that names it in commands: `плагин:модуль`. */ + fun named(library: PnLibrary): List> = + library.plugins.all().flatMap { plugin -> plugin.all().map { "${plugin.id.value}:${it.id.value}" to it } }.sortedBy { it.first } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/modules/ModulesCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/modules/ModulesCommand.kt new file mode 100644 index 000000000..44813f9c9 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/modules/ModulesCommand.kt @@ -0,0 +1,267 @@ +package org.pnfolder.pnlibrary.core.commands.modules + +import net.kyori.adventure.text.event.ClickEvent +import net.kyori.adventure.text.format.TextColor +import org.pnfolder.pnlibrary.api.chat.ChatKit +import org.pnfolder.pnlibrary.api.chat.ChatReader +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandNodeBuilder +import org.pnfolder.pnlibrary.api.commands.definition.command +import org.pnfolder.pnlibrary.api.libraries.ModuleLibrary +import org.pnfolder.pnlibrary.api.plugin.ModuleContext +import org.pnfolder.pnlibrary.api.plugin.control.ModuleControl +import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import java.util.concurrent.CompletionStage + +/** + * `/pn modules`: the modules of every plugin and their switches. + * + * | Command | What it does | + * |---|---| + * | `/pn modules` | every module with its state | + * | `/pn modules plugins` | every plugin with its modules and the number of libraries | + * | `/pn modules libs [<плагин>\|<плагин:модуль>]` | libraries with name, description, who registered them and version conflicts | + * | `/pn modules disk` | what every plugin takes on the disk: jar, settings, libraries, logs, data | + * | `/pn modules view <модуль>` | one module: state, last error, whether it starts with the server | + * | `/pn modules enable\|disable\|restart\|reload <модуль>` | switches the module now | + * | `/pn modules auto <модуль> on\|off` | whether the module starts with the server; saved | + * + * `<модуль>` is `плагин:модуль`, or just the module id when it is unique. Requires `pnlibrary.modules`; the console + * always may use it. A module its plugin registered without hooks is listed but cannot be switched. + */ +class ModulesCommand(private val library: PnLibrary) { + fun definition(): CommandDefinition = command("modules") { + permission(PERMISSION) + noPermissionMessage("Модули плагинов доступны администраторам. Нужно право $PERMISSION.") + consoleBypassesPermission() + executes { list(it) } + literal("libs") { + executes { libs(it, null) } + argument("owner", ArgumentType.string()) { + suggests { LibraryRow.all(library).map { it.owner }.distinct() } + executes { libs(it, it.get("owner")) } + } + } + literal("plugins") { executes { plugins(it) } } + literal("disk") { executes { disk(it) } } + literal("view") { moduleArgument { context, typed -> view(context, typed) } } + for (action in Action.values()) { + literal(action.word) { moduleArgument { context, typed -> change(context, typed, action) } } + } + literal("auto") { + argument("module", ArgumentType.string()) { + suggests { names() } + for ((word, value) in listOf("on" to true, "off" to false)) { + literal(word) { + executes { context -> + withModule(context, context.get("module")) { kit, name, module -> auto(context, kit, name, module, value) } + } + } + } + } + } + } + + private fun CommandNodeBuilder.moduleArgument(run: (CommandContext, String) -> Unit) { + argument("module", ArgumentType.string()) { + suggests { names() } + executes { run(it, it.get("module")) } + } + } + + private fun names(): List = ModuleLabels.named(library).map { it.first } + + private fun kit(context: CommandContext) = ChatKit(ChatReader.of(context.sender)) + + private fun withModule(context: CommandContext, typed: String, action: (ChatKit, String, ModuleContext) -> Unit) { + val kit = kit(context) + val all = ModuleLabels.named(library) + val found = all.firstOrNull { it.first.equals(typed, true) } + ?: all.singleOrNull { it.second.id.value.equals(typed, true) } + if (found == null) { + context.sender.send(kit.text("Такого модуля нет или имя неоднозначно: $typed. Список: $ROOT", ChatPalette.DANGER)) + return + } + action(kit, found.first, found.second) + } + + private fun list(context: CommandContext) { + val kit = kit(context) + val all = ModuleLabels.named(library) + val lines = mutableListOf(kit.blank(), kit.header("Модули плагинов", kit.text("${all.size}", ChatPalette.LABEL))) + if (all.isEmpty()) lines += kit.note("Модулей пока нет.", ChatPalette.FAINT) + all.forEach { (name, module) -> + val control = module.control + val state = control.state + var row = kit.text(" ").append(kit.text(kit.glyph('●'), ModuleLabels.color(state))) + .append(kit.text(" ${name}", ChatPalette.ACCENT)) + .append(kit.text(" ${ModuleLabels.label(state)}", ModuleLabels.color(state))) + if (!control.isControllable) { + row = row.append(kit.dot()).append(kit.text("без переключателя", ChatPalette.FAINT)) + } else if (!control.autoStart) { + row = row.append(kit.dot()).append(kit.text("не включается сам", ChatPalette.WARN)) + } + lines += if (kit.reader.interactive) row.clickEvent(ClickEvent.runCommand("$ROOT view ${name}")) else row + } + if (!kit.reader.interactive) { + lines += kit.blank() + lines += kit.commandHints( + "$ROOT view <модуль>" to "карточка модуля", + "$ROOT enable|disable|restart|reload <модуль>" to "переключить сейчас", + "$ROOT auto <модуль> on|off" to "включать ли вместе с сервером", + ) + } + lines.forEach(context.sender::send) + } + + private fun libraryLine(kit: ChatKit, library: ModuleLibrary, fromPlugin: Boolean): net.kyori.adventure.text.Component { + val suffix = if (fromPlugin) " (от плагина)" else "" + val line = kit.text(" ${library.title} ${library.version}$suffix", if (fromPlugin) ChatPalette.FAINT else ChatPalette.SOFT) + return library.description?.let { line.append(kit.text(": $it", ChatPalette.LABEL)) } ?: line + } + + private fun libs(context: CommandContext, owner: String?) { + val kit = kit(context) + val rows = LibraryRow.all(library).filter { owner == null || it.belongsTo(owner) } + val lines = mutableListOf(kit.blank(), kit.header("Библиотеки", kit.text("${rows.size}", ChatPalette.LABEL))) + if (rows.isEmpty()) lines += kit.note(if (owner == null) "Плагины не подключили библиотек." else "У $owner нет библиотек.", ChatPalette.FAINT) + rows.groupBy { it.owner }.forEach { (who, own) -> + lines += kit.text(" $who", ChatPalette.ACCENT) + own.forEach { row -> + var line = kit.text(" ${row.title}", ChatPalette.TEXT).append(kit.text(" ${row.version}", ChatPalette.SOFT)) + .append(kit.dot()) + .append(kit.text(when (row.scope) { "ISOLATED" -> "отдельно"; "LIBRARY" -> "в pnLibrary"; else -> "в плагине" }, ChatPalette.FAINT)) + if (row.size >= 0) line = line.append(kit.dot()).append(kit.text(DiskUsage.format(row.size), ChatPalette.SOFT)) + line = line.append(kit.dot()).append( + when (row.trust) { + LibraryRow.GIVEN -> kit.text("сумма задана", ChatPalette.OK) + else -> kit.text("jar не проверяется", ChatPalette.WARN) + }, + ) + if (!row.required) line = line.append(kit.dot()).append(kit.text("необязательная", ChatPalette.FAINT)) + if (row.conflict) line = line.append(kit.dot()).append(kit.text("другая версия у другого плагина", ChatPalette.DANGER)) + lines += line + row.description?.let { lines += kit.text(" $it", ChatPalette.LABEL) } + row.place?.let { lines += kit.text(" лежит: $it", ChatPalette.FAINT) } + } + } + lines.forEach(context.sender::send) + } + + private fun disk(context: CommandContext) { + val kit = kit(context) + val report = DiskUsage.scan(DiskUsage.pluginsFolder, DiskUsage.registeredFiles(library)) + val lines = mutableListOf(kit.blank(), kit.header("Диск плагинов", kit.text(DiskUsage.format(report.total), ChatPalette.LABEL))) + report.rows.forEach { row -> + val share = if (report.total > 0) row.total * 100 / report.total else 0 + lines += kit.text(" ${row.name}", ChatPalette.ACCENT).append(kit.dot()) + .append(kit.text("${DiskUsage.format(row.total)} ($share%)", if (share >= 50) ChatPalette.WARN else ChatPalette.SOFT)) + lines += kit.text( + " плагин ${DiskUsage.format(row.jar)} · настройки ${DiskUsage.format(row.configs)} · библиотеки ${DiskUsage.format(row.libraries)}" + + " · журналы ${DiskUsage.format(row.logs)} · данные ${DiskUsage.format(row.data)}", + ChatPalette.FAINT, + ) + } + lines += kit.blank() + lines += kit.hoverField("Библиотеки pnLibrary", kit.text(DiskUsage.format(report.registeredLibraries), ChatPalette.TEXT)) + lines += kit.hoverField("Свободно на диске", kit.text("${DiskUsage.format(report.free)} из ${DiskUsage.format(report.capacity)}", ChatPalette.TEXT)) + lines.forEach(context.sender::send) + } + + private fun plugins(context: CommandContext) { + val kit = kit(context) + val all = library.plugins.all() + val lines = mutableListOf(kit.blank(), kit.header("Плагины библиотеки", kit.text("${all.size}", ChatPalette.LABEL))) + all.sortedBy { it.id.value }.forEach { plugin -> + val modules = plugin.all() + lines += kit.text(" ${plugin.id.value}", ChatPalette.ACCENT) + .append(kit.dot()).append(kit.text("модулей ${modules.size}", ChatPalette.SOFT)) + .append(kit.dot()).append(kit.text("библиотек ${plugin.allLibraries.size}", ChatPalette.SOFT)) + modules.forEach { module -> + val state = module.control.state + lines += kit.text(" ${module.id.value}", ChatPalette.TEXT).append(kit.text(" ${ModuleLabels.label(state)}", ModuleLabels.color(state))) + } + } + lines.forEach(context.sender::send) + } + + private fun view(context: CommandContext, typed: String) = withModule(context, typed) { kit, name, module -> + val control = module.control + val lines = mutableListOf( + kit.blank(), + kit.header(ModuleLabels.title(module), kit.bracketed(ModuleLabels.label(control.state), ModuleLabels.color(control.state))), + kit.hoverField("Имя", kit.text(name, ChatPalette.TEXT)), + kit.hoverField("Описание", kit.text(module.metadata.description ?: "плагин не описал", ChatPalette.TEXT)), + kit.hoverField("Переключается", kit.text(if (control.isControllable) "да" else "нет, плагин не дал методы включения", ChatPalette.TEXT)), + kit.hoverField("Включается с сервером", kit.text(if (control.autoStart) "да" else "нет", ChatPalette.TEXT)), + ) + val own = module.libraries.loaded + val shared = library.plugins.all().firstOrNull { plugin -> plugin.all().any { it === module } }?.libraries?.loaded.orEmpty() + if (own.isNotEmpty() || shared.isNotEmpty()) { + lines += kit.hoverField("Библиотеки", kit.text("${own.size + shared.size}", ChatPalette.TEXT)) + own.forEach { lines += libraryLine(kit, it, false) } + shared.forEach { lines += libraryLine(kit, it, true) } + } + control.lastError?.let { lines += kit.hoverField("Ошибка", kit.text(it.message ?: it.javaClass.simpleName, ChatPalette.DANGER)) } + if (control.isControllable && kit.reader.interactive) { + var buttons = kit.text(" ") + Action.values().forEach { a -> + buttons = buttons.append(kit.option(a.label, "$ROOT ${a.word} ${name}", a.hint, a.color)).append(kit.text(" ")) + } + val toggle = if (control.autoStart) "off" to "Не включать с сервером" else "on" to "Включать с сервером" + buttons = buttons.append(kit.option(toggle.second, "$ROOT auto ${name} ${toggle.first}", "Сохраняется между перезапусками", ChatPalette.SOFT)) + lines += kit.blank() + lines += buttons + } + lines.forEach(context.sender::send) + } + + private fun change(context: CommandContext, typed: String, action: Action) = withModule(context, typed) { kit, name, module -> + val control = module.control + if (!control.isControllable) { + context.sender.send(kit.text("У модуля ${name} нет методов включения и выключения.", ChatPalette.DANGER)) + return@withModule + } + action.run(control).whenComplete { _, _ -> + val failed = control.lastError + context.sender.send( + if (failed != null) { + kit.text("Модуль ${name}: ошибка, ${failed.message ?: failed.javaClass.simpleName}", ChatPalette.DANGER) + } else { + kit.text("Модуль ${name}: ${ModuleLabels.label(control.state)}", ChatPalette.OK) + }, + ) + } + } + + private fun auto(context: CommandContext, kit: ChatKit, name: String, module: ModuleContext, enabled: Boolean) { + if (!module.control.isControllable) { + context.sender.send(kit.text("У модуля ${name} нет методов включения и выключения.", ChatPalette.DANGER)) + return + } + module.control.setAutoStart(enabled) + val text = if (enabled) "будет включаться вместе с сервером" else "не будет включаться вместе с сервером" + context.sender.send(kit.text("Модуль ${name} $text.", ChatPalette.OK)) + } + + private enum class Action( + val word: String, + val label: String, + val hint: String, + val color: TextColor, + val run: (ModuleControl) -> CompletionStage<*>, + ) { + ENABLE("enable", "Включить", "Запустить модуль", ChatPalette.OK, { it.enable() }), + DISABLE("disable", "Выключить", "Остановить до следующего запуска сервера", ChatPalette.DANGER, { it.disable() }), + RESTART("restart", "Перезапустить", "Выключить и включить заново", ChatPalette.WARN, { it.restart() }), + RELOAD("reload", "Перечитать", "Перечитать настройки модуля", ChatPalette.INFO, { it.reload() }), + } + + companion object { + const val PERMISSION = "pnlibrary.modules" + const val ROOT = "/pn modules" + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ProxyCommandContext.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ProxyCommandContext.kt new file mode 100644 index 000000000..9fbc4c3c6 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ProxyCommandContext.kt @@ -0,0 +1,34 @@ +package org.pnfolder.pnlibrary.core.commands.proxy + +import net.kyori.adventure.sound.Sound +import net.kyori.adventure.text.Component +import org.pnfolder.pnlibrary.api.audiences.AudienceSender +import org.pnfolder.pnlibrary.api.audiences.Delivery +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.CommandSender + +/** Builds the context of a command typed on a proxy; replies to the proxy control command name it with [ProxyCommandNames]. */ +fun proxyCommandContext(audience: AudienceSender, alias: String, arguments: Array): CommandContext = + CommandContext( + sender = ProxyCommandSender(audience, ProxyCommandNames.owns(alias)), + arguments = arguments.toList(), + invokedAlias = alias, + currentInput = arguments.lastOrNull().orEmpty(), + ) + +/** Delegates portable command replies to the native audience bridge, rewriting `/pn` for the proxy control command. */ +private class ProxyCommandSender( + private val audience: AudienceSender, + private val proxyControl: Boolean, +) : CommandSender, AudienceSender by audience { + override fun send(message: Component) = audience.sendMessage(shown(message)) + + // Explicit overrides preserve native delivery instead of CommandSender's fallback defaults. + override fun sendMessage(text: Component) = audience.sendMessage(shown(text)) + + override fun actionBar(text: Component) = audience.actionBar(text) + + override fun playSound(sound: Sound): Delivery = audience.playSound(sound) + + private fun shown(message: Component) = if (proxyControl) ProxyCommandNames.rewrite(message) else message +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ProxyControlCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ProxyControlCommand.kt index 4f74fe60f..1a8fb9a1b 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ProxyControlCommand.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ProxyControlCommand.kt @@ -4,23 +4,27 @@ import net.kyori.adventure.text.Component import org.pnfolder.pnlibrary.api.chat.ChatKit import org.pnfolder.pnlibrary.api.chat.ChatNotice import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition import org.pnfolder.pnlibrary.api.commands.CommandRegistration import org.pnfolder.pnlibrary.api.commands.CommandSender -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.core.commands.configs.ConfigsCommand +import org.pnfolder.pnlibrary.core.commands.deps.DepsCommand import org.pnfolder.pnlibrary.core.commands.events.EventBusCommand import org.pnfolder.pnlibrary.core.commands.groups.GroupsCommand +import org.pnfolder.pnlibrary.core.commands.modules.ModulesCommand import org.pnfolder.pnlibrary.core.commands.tasks.TaskCommand +import org.pnfolder.pnlibrary.core.lifecycle.MountableCommands import org.pnfolder.pnlibrary.core.lifecycle.dispatchRuntimeCommand import org.pnfolder.pnlibrary.core.lifecycle.mountableCommand import org.pnfolder.pnlibrary.core.lifecycle.registerRuntimeCommand import org.pnfolder.pnlibrary.core.link.Link -import org.pnfolder.pnlibrary.core.link.LinkReports -import org.pnfolder.pnlibrary.core.link.NetworkServer import org.pnfolder.pnlibrary.core.link.ServerGroups +import org.pnfolder.pnlibrary.core.link.report.LinkReports +import org.pnfolder.pnlibrary.core.link.report.NetworkServer import org.pnfolder.pnlibrary.core.updates.catalog.ProxyUpdateCommand import java.util.Collections import java.util.UUID @@ -82,12 +86,12 @@ class ProxyControlCommand(private val library: PnLibrary, private val link: Link aliases(*ProxyCommandNames.ALIASES.toTypedArray()) executes { updates.overview(it, OTHERS) } updates.install(this) - library.mountableCommand("events")?.let { mount("events", it) } - library.mountableCommand("debug")?.let { mount("debug", it) } - library.mountableCommand("stats")?.let { mount("stats", it) } - library.mountableCommand("placeholders")?.let { mount("placeholders", it) } + for (name in MountableCommands.ALL) library.mountableCommand(name)?.let { mount(name, it) } mount("bus", EventBusCommand(library).definition()) mount("tasks", TaskCommand(library).definition()) + mount("modules", ModulesCommand(library).definition()) + mount("configs", ConfigsCommand(library).definition()) + mount("deps", DepsCommand(library).definition()) mount("servers", ServersCommand(link, ServersCommand.fromReports(link)).definition()) mount("groups", GroupsCommand(link, withProxy()).definition()) } @@ -108,6 +112,7 @@ class ProxyControlCommand(private val library: PnLibrary, private val link: Link "/pn tasks" to "pnlibrary.tasks", "/pn stats" to "pnlibrary.stats", "/pn placeholders" to "pnlibrary.placeholders", + "/pn settings" to "pnlibrary.settings", "/pn servers" to ServersCommand.PERMISSION, "/pn groups" to GroupsCommand.PERMISSION, "/pn debug" to "pnlibrary.debug", diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ServersCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ServersCommand.kt index abcbe74e1..48e2a8ff9 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ServersCommand.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ServersCommand.kt @@ -3,20 +3,20 @@ package org.pnfolder.pnlibrary.core.commands.proxy import net.kyori.adventure.text.Component import net.kyori.adventure.text.event.ClickEvent import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.commands.ArgumentType +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.CommandNodeBuilder -import org.pnfolder.pnlibrary.api.commands.command -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandNodeBuilder +import org.pnfolder.pnlibrary.api.commands.definition.command +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.common.text.RussianText import org.pnfolder.pnlibrary.core.commands.tasks.TaskLabels import org.pnfolder.pnlibrary.core.link.Link -import org.pnfolder.pnlibrary.core.link.LinkNames -import org.pnfolder.pnlibrary.core.link.NetworkServer -import org.pnfolder.pnlibrary.core.link.RemoteAction +import org.pnfolder.pnlibrary.core.link.remote.LinkNames +import org.pnfolder.pnlibrary.core.link.remote.RemoteAction +import org.pnfolder.pnlibrary.core.link.report.NetworkServer import org.pnfolder.pnlibrary.core.updates.catalog.CatalogLabels import java.time.Duration import java.time.Instant diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/settings/SettingsCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/settings/SettingsCommand.kt new file mode 100644 index 000000000..42c84ba61 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/settings/SettingsCommand.kt @@ -0,0 +1,162 @@ +package org.pnfolder.pnlibrary.core.commands.settings + +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.format.TextColor +import org.pnfolder.pnlibrary.api.chat.ChatKit +import org.pnfolder.pnlibrary.api.chat.ChatReader +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command +import org.pnfolder.pnlibrary.core.commands.engine.chatPager +import org.pnfolder.pnlibrary.core.commands.engine.pageCount +import org.pnfolder.pnlibrary.core.settings.SettingApply +import org.pnfolder.pnlibrary.core.settings.SettingChange +import org.pnfolder.pnlibrary.core.settings.SettingException +import org.pnfolder.pnlibrary.core.settings.SettingKind +import org.pnfolder.pnlibrary.core.settings.SettingPickerHook +import org.pnfolder.pnlibrary.core.settings.SettingTexts +import org.pnfolder.pnlibrary.core.settings.SettingValue +import org.pnfolder.pnlibrary.core.settings.SettingsRegistry +import org.pnfolder.pnlibrary.core.settings.SettingsStore + +/** + * `/pn settings`: every setting of the library, changed in game; there is no settings file to edit. + * + * | Command | What it does | + * |---|---| + * | `/pn settings [list] [page]` | all settings with their values | + * | `/pn settings get ` | one setting: value, default, limits, when a change starts to work | + * | `/pn settings set ` | changes a setting and saves it in `data/settings.json` | + * | `/pn settings reset ` | returns a setting to its default | + * | `/pn settings pick [filter]` | a player opens the menu list of a choice setting, narrowed to the names that contain the filter | + * + * Requires `pnlibrary.settings`; the console always may. The list of settings is [SettingsRegistry]. + */ +internal class SettingsCommand(private val settings: SettingsStore, private val picker: SettingPickerHook = SettingPickerHook()) { + fun definition(): CommandDefinition = command("settings") { + permission(PERMISSION) + noPermissionMessage("Настройки библиотеки доступны администраторам. Нужно право $PERMISSION.") + consoleBypassesPermission() + executes { list(it, 1) } + argument("page", ArgumentType.integer()) { executes { list(it, it.get("page")) } } + literal("list") { + executes { list(it, 1) } + argument("page", ArgumentType.integer()) { executes { list(it, it.get("page")) } } + } + literal("get") { + argument("key", ArgumentType.string()) { + suggests { keys() } + executes { context -> show(context, context.get("key")) } + } + } + literal("set") { + argument("key", ArgumentType.string()) { + suggests { keys() } + argument("value", ArgumentType.greedyString()) { + suggests { context -> values(context.parsedValues["key"] as? String ?: context.arguments.getOrNull(1)) } + executes { context -> change(context, context.get("key")) { settings.set(it, context.get("value")) } } + } + } + } + literal("pick") { + argument("key", ArgumentType.string()) { + suggests { choiceKeys() } + executes { context -> pick(context, context.get("key"), "") } + argument("filter", ArgumentType.greedyString()) { + executes { context -> pick(context, context.get("key"), context.get("filter")) } + } + } + } + literal("reset") { + argument("key", ArgumentType.string()) { + suggests { settings.values().filter { it.changed }.map { it.spec.key } } + executes { context -> change(context, context.get("key"), settings::reset) } + } + } + } + + private fun keys(): List = SettingsRegistry.all.map { it.key } + + private fun choiceKeys(): List = SettingsRegistry.all.filter { it.choices != null }.map { it.key } + + /** Opens the menu list of the choice setting [key] for the player, narrowed to [filter]. */ + private fun pick(context: CommandContext, key: String, filter: String) { + val spec = SettingsRegistry[key]?.takeIf { it.choices != null } + ?: return say(context, "Нет настройки с выбором из списка: $key. Есть: ${choiceKeys().joinToString()}.", ChatPalette.DANGER) + if (context.sender.isConsole) return say(context, "Список открывается в меню игрока. В консоли: $ROOT set ${spec.key} <значение>.", ChatPalette.WARN) + val opened = picker.opener?.invoke(context, spec.key, filter.trim()) ?: false + if (!opened) { + say(context, "Меню здесь недоступно. Откройте /pn gui на игровом сервере или используйте $ROOT set ${spec.key} <значение>.", ChatPalette.WARN) + } + } + + /** What is worth proposing for the value of [key]: the words of a switch, the examples, the default. */ + private fun values(key: String?): List { + val spec = key?.let { SettingsRegistry[it] } ?: return emptyList() + val proposals = when (spec.kind) { + SettingKind.SWITCH -> listOf(SettingTexts.switchWord(true), SettingTexts.switchWord(false)) + SettingKind.NUMBER -> listOfNotNull(spec.min?.toString(), spec.max?.toString()) + SettingKind.TEXT, SettingKind.TIME -> spec.examples + SettingKind.CHOICE -> spec.examples + spec.choices?.all.orEmpty() + } + return (listOf(spec.display(spec.default)) + proposals).distinct() + } + + private fun say(context: CommandContext, text: String, color: TextColor = ChatPalette.TEXT) = + context.sender.send(Component.text(text, color)) + + private fun list(context: CommandContext, requested: Int) { + val all = settings.values() + val pages = pageCount(all.size, PAGE_SIZE) + val page = requested.coerceIn(1, pages) + say(context, "Настройки библиотеки: ${all.size}, страница $page/$pages", ChatPalette.ACCENT) + all.drop((page - 1) * PAGE_SIZE).take(PAGE_SIZE).forEach { entry -> + val mark = if (entry.changed) " (по умолчанию ${entry.spec.display(entry.spec.default)})" else "" + say(context, "${entry.spec.key} = ${entry.spec.display(entry.current)}$mark", if (entry.changed) ChatPalette.OK else ChatPalette.TEXT) + } + if (pages > 1) context.sender.send(chatPager(ChatKit(ChatReader.of(context.sender)), "$ROOT list", page, pages)) + say(context, "Подробнее: $ROOT get <ключ>. Изменить: $ROOT set <ключ> <значение>.", ChatPalette.FAINT) + } + + private fun show(context: CommandContext, key: String) { + val entry = try { + settings.value(key) + } catch (error: SettingException) { + return say(context, error.message.orEmpty(), ChatPalette.DANGER) + } + describe(entry).forEach { (text, color) -> say(context, text, color) } + } + + private fun describe(entry: SettingValue): List> { + val spec = entry.spec + return buildList { + add(spec.key to ChatPalette.ACCENT) + add(" значение: ${spec.display(entry.current)}${if (entry.changed) "" else " (по умолчанию)"}" to ChatPalette.TEXT) + if (entry.changed) add(" по умолчанию: ${spec.display(spec.default)}" to ChatPalette.TEXT) + add(" тип: ${spec.kind.label}" to ChatPalette.TEXT) + spec.range().takeIf { it.isNotEmpty() }?.let { add(" допустимо: $it" to ChatPalette.TEXT) } + if (spec.examples.isNotEmpty()) add(" примеры: ${spec.examples.joinToString()}" to ChatPalette.TEXT) + add(" заработает: ${spec.applies.label}" to if (spec.applies == SettingApply.LIVE) ChatPalette.TEXT else ChatPalette.WARN) + add(" ${spec.description}" to ChatPalette.FAINT) + } + } + + private fun change(context: CommandContext, key: String, action: (String) -> SettingChange) { + try { + val result = action(key) + val spec = result.spec + say(context, "${spec.key}: ${spec.display(result.before)} → ${spec.display(result.after)}. Сохранено.", ChatPalette.OK) + if (spec.applies == SettingApply.RESTART) say(context, "Начнёт работать ${spec.applies.label} сервера.", ChatPalette.WARN) + } catch (error: SettingException) { + say(context, "Не изменено: ${error.message}", ChatPalette.DANGER) + } + } + + companion object { + const val PERMISSION = "pnlibrary.settings" + private const val ROOT = "/pn settings" + private const val PAGE_SIZE = 6 + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskCommand.kt index d7e6f39a6..fe1b2ea45 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskCommand.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskCommand.kt @@ -3,17 +3,18 @@ package org.pnfolder.pnlibrary.core.commands.tasks import net.kyori.adventure.text.Component import net.kyori.adventure.text.event.ClickEvent import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.commands.ArgumentType +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus import org.pnfolder.pnlibrary.common.text.RussianText -import org.pnfolder.pnlibrary.core.commands.chatPager +import org.pnfolder.pnlibrary.core.commands.engine.chatPager +import org.pnfolder.pnlibrary.core.commands.engine.pageCount import org.pnfolder.pnlibrary.core.lifecycle.cancelTask import org.pnfolder.pnlibrary.core.lifecycle.runTaskNow import org.pnfolder.pnlibrary.core.lifecycle.taskSnapshots @@ -72,7 +73,7 @@ class TaskCommand(private val library: PnLibrary) { } literal("cancel") { argument("id", ArgumentType.string()) { - suggests { library.taskSnapshots().filter { TaskLabels.isActive(it.status) }.map { it.id.value.take(TaskLabels.SHORT_ID) } } + suggests { library.taskSnapshots().filter { it.isActive }.map { it.id.value.take(TaskLabels.SHORT_ID) } } executes { cancel(it, it.get("id")) } } } @@ -92,10 +93,11 @@ class TaskCommand(private val library: PnLibrary) { private fun list(context: CommandContext, period: TaskPeriod, state: TaskState, requestedPage: Int) { val kit = kit(context) - val all = library.taskSnapshots().sortedByDescending { TaskLabels.activity(it) } + val everything = library.taskSnapshots().sortedByDescending { TaskLabels.activity(it) } + val all = TaskLabels.roots(everything) val inPeriod = all.filter(period::keep) val shown = inPeriod.filter(state::keep) - val pages = ((shown.size + PAGE_SIZE - 1) / PAGE_SIZE).coerceAtLeast(1) + val pages = pageCount(shown.size, PAGE_SIZE) val page = requestedPage.coerceIn(1, pages) val count = "${all.size} ${RussianText.plural(all.size.toLong(), "задача", "задачи", "задач")}" val lines = mutableListOf(kit.blank(), kit.header("Задачи плагинов", kit.text(count, ChatPalette.LABEL))) @@ -103,7 +105,12 @@ class TaskCommand(private val library: PnLibrary) { lines += tabs(kit, "Какие", TaskState.values().toList(), state, { it.label }, { s -> inPeriod.count(s::keep) }) { "$ROOT ${period.word} ${it.word}" } lines += kit.blank() if (shown.isEmpty()) lines += kit.note("Здесь пока пусто.", ChatPalette.FAINT) - shown.drop((page - 1) * PAGE_SIZE).take(PAGE_SIZE).forEach { lines += row(kit, it) } + shown.drop((page - 1) * PAGE_SIZE).take(PAGE_SIZE).forEach { task -> + lines += row(kit, task, everything) + TaskLabels.childrenOf(task, everything).take(CHILD_PREVIEW).forEach { lines += child(kit, it) } + val more = TaskLabels.children(task, everything) - CHILD_PREVIEW + if (more > 0) lines += kit.text(" … и ещё $more подзадач, откройте задачу", ChatPalette.FAINT) + } if (pages > 1) { lines += kit.blank() lines += chatPager(kit, "$ROOT ${period.word} ${state.word}", page, pages) @@ -143,7 +150,7 @@ class TaskCommand(private val library: PnLibrary) { return line } - private fun row(kit: ChatKit, task: TaskSnapshot): Component { + private fun row(kit: ChatKit, task: TaskSnapshot, all: Collection): Component { val title = kit.text(" ").append(kit.text(kit.glyph('●'), TaskLabels.color(task.status))) .append(kit.text(" ${TaskLabels.title(task)}", ChatPalette.ACCENT)) .append(kit.text(" ${TaskLabels.label(task.status)}", TaskLabels.color(task.status))) @@ -152,6 +159,8 @@ class TaskCommand(private val library: PnLibrary) { .append(kit.dot()).append(kit.text(runs, ChatPalette.SOFT)) .append(kit.dot()).append(kit.text(TaskLabels.ago(TaskLabels.activity(task)), ChatPalette.FAINT)) if (task.lastFailure != null) facts = facts.append(kit.dot()).append(kit.text("ошибка", ChatPalette.DANGER)) + TaskLabels.parent(task, all)?.let { facts = facts.append(kit.dot()).append(kit.text("↳ $it", ChatPalette.SOFT)) } + TaskLabels.lag(task)?.let { facts = facts.append(kit.dot()).append(kit.text("лаг", ChatPalette.DANGER)) } val lines = mutableListOf(title, facts) task.description?.let { lines += kit.text(" ${it.take(DESCRIPTION_PREVIEW)}", ChatPalette.LABEL) } val block = lines.drop(1).fold(lines.first()) { all, line -> all.append(Component.newline()).append(line) } @@ -167,6 +176,15 @@ class TaskCommand(private val library: PnLibrary) { return block.hoverEvent(kit.tooltip(*hover.toTypedArray())).clickEvent(ClickEvent.runCommand("$ROOT view ${task.id.value}")) } + private fun child(kit: ChatKit, task: TaskSnapshot): Component { + val line = kit.text(" ↳ ", ChatPalette.FAINT).append(kit.text(kit.glyph('●'), TaskLabels.color(task.status))) + .append(kit.text(" ${TaskLabels.title(task)}", ChatPalette.TEXT)) + .append(kit.text(" ${TaskLabels.label(task.status)}", TaskLabels.color(task.status))) + val withLag = TaskLabels.lag(task)?.let { line.append(kit.dot()).append(kit.text("лаг", ChatPalette.DANGER)) } ?: line + if (!kit.reader.interactive) return withLag + return withLag.clickEvent(ClickEvent.runCommand("$ROOT view ${task.id.value}")) + } + private fun view(context: CommandContext, typed: String) = withTask(context, typed) { kit, task -> val lines = mutableListOf( kit.blank(), @@ -177,9 +195,10 @@ class TaskCommand(private val library: PnLibrary) { if (task.description == null && task.usage == null) { lines += kit.note("Плагин не описал эту задачу. Описание задаётся в TaskSpec: description и usage.", ChatPalette.FAINT) } - lines += TaskDetail.who(kit, task) + lines += TaskDetail.who(kit, task, library.taskSnapshots()) lines += TaskDetail.whenLines(kit, task) lines += TaskDetail.rights(kit, task) + lines += TaskDetail.subtasks(kit, task, library.taskSnapshots()) task.lastFailure?.let { lines += kit.blank() lines += kit.section("Ошибка") @@ -198,7 +217,7 @@ class TaskCommand(private val library: PnLibrary) { } private fun stop(kit: ChatKit, task: TaskSnapshot): Component? { - if (TaskLabels.isActive(task.status) && task.cancellable) { + if (task.isActive && task.cancellable) { return kit.button("остановить", "$ROOT cancel ${task.id.value}", "Остановить задачу", ChatPalette.DANGER) } return closed(kit, "остановка закрыта", TaskLabels.stopAnswer(task)) @@ -237,5 +256,6 @@ class TaskCommand(private val library: PnLibrary) { private const val ROOT = "/pn tasks" private const val PAGE_SIZE = 6 private const val DESCRIPTION_PREVIEW = 70 + private const val CHILD_PREVIEW = 3 } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskDetail.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskDetail.kt index 1debfc351..f45a0dafe 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskDetail.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskDetail.kt @@ -1,25 +1,30 @@ package org.pnfolder.pnlibrary.core.commands.tasks import net.kyori.adventure.text.Component +import net.kyori.adventure.text.event.ClickEvent import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot import org.pnfolder.pnlibrary.common.time.DisplayZone import java.time.Instant +/** Chat page with the details of one task. */ internal object TaskDetail { - fun who(kit: ChatKit, task: TaskSnapshot): List { + fun who(kit: ChatKit, task: TaskSnapshot, all: Collection = emptyList()): List { val lines = mutableListOf() lines += kit.blank() lines += kit.section("Кто и как") lines += kit.field("Плагин", kit.text(task.ownerName, ChatPalette.TEXT)) + TaskLabels.parent(task, all)?.let { lines += kit.field("Подзадача от", kit.text(it, ChatPalette.TEXT)) } + TaskLabels.children(task, all).takeIf { it > 0 }?.let { lines += kit.field("Подзадач", kit.text("$it", ChatPalette.TEXT)) } task.source?.let { lines += kit.field("Класс", kit.text(it, ChatPalette.TEXT)) } task.key?.let { lines += kit.field("Ключ", kit.text(it, ChatPalette.TEXT)) } if (task.tags.isNotEmpty()) lines += kit.field("Теги", kit.text(task.tags.joinToString(", "), ChatPalette.SOFT)) lines += kit.field("Выполняется", kit.text(TaskLabels.where(task), ChatPalette.TEXT)) task.interval?.let { lines += kit.field("Повторяется", kit.text("каждые ${TaskLabels.span(it)}", ChatPalette.TEXT)) } lines += kit.field("Запусков", kit.text("${task.runCount}, пропущено ${task.skippedCount}", ChatPalette.TEXT)) - task.lastDuration?.let { lines += kit.field("Последний заняла", kit.text(TaskLabels.span(it), ChatPalette.TEXT)) } + task.lastDuration?.let { lines += kit.field("Прошлый запуск шёл", kit.text(TaskLabels.span(it), ChatPalette.TEXT)) } + TaskLabels.lag(task)?.let { lines += kit.field("Опоздание", kit.text(it, ChatPalette.DANGER)) } return lines } @@ -35,6 +40,22 @@ internal object TaskDetail { return lines } + fun subtasks(kit: ChatKit, task: TaskSnapshot, all: Collection): List { + val parent = task.parentId?.let { id -> all.firstOrNull { it.id == id } } + val children = TaskLabels.childrenOf(task, all) + if (parent == null && children.isEmpty()) return emptyList() + val lines = mutableListOf(kit.blank(), kit.section("Связанные задачи")) + parent?.let { + val open = ClickEvent.runCommand("/pn tasks view ${it.id.value}") + lines += kit.field("Родитель", kit.text(TaskLabels.title(it), ChatPalette.ACCENT).clickEvent(open)) + } + children.forEach { + val open = ClickEvent.runCommand("/pn tasks view ${it.id.value}") + lines += kit.field("Подзадача", kit.text("${TaskLabels.title(it)}, ${TaskLabels.label(it.status)}", ChatPalette.TEXT).clickEvent(open)) + } + return lines + } + fun rights(kit: ChatKit, task: TaskSnapshot): List { val lines = mutableListOf() lines += kit.blank() diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskLabels.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskLabels.kt index 6653b2a42..c8399b609 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskLabels.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskLabels.kt @@ -1,9 +1,9 @@ package org.pnfolder.pnlibrary.core.commands.tasks import net.kyori.adventure.text.format.TextColor -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskStatus +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus import org.pnfolder.pnlibrary.common.time.DisplayZone import java.time.Duration import java.time.Instant @@ -11,6 +11,7 @@ import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.Locale +/** Chat wording, colours and time formats for task statuses and moments. */ object TaskLabels { fun label(status: TaskStatus): String = when (status) { TaskStatus.SCHEDULED -> "ожидает запуска" @@ -28,9 +29,7 @@ object TaskLabels { TaskStatus.FAILED -> ChatPalette.DANGER } - /** Whether the task can still run, so it can be cancelled. */ - fun isActive(status: TaskStatus): Boolean = status == TaskStatus.SCHEDULED || status == TaskStatus.RUNNING - + /** The latest moment something happened to the task: it started, completed, or was created. */ fun activity(task: TaskSnapshot): Instant = listOfNotNull(task.lastStartedAt, task.lastCompletedAt, task.createdAt).max() fun isToday(task: TaskSnapshot): Boolean = @@ -38,8 +37,37 @@ object TaskLabels { fun title(task: TaskSnapshot): String = task.name ?: task.key ?: task.id.value.take(SHORT_ID) + /** Name of the task that started [task], or `null` for a task scheduled directly. */ + fun parent(task: TaskSnapshot, all: Collection): String? = + task.parentId?.let { id -> all.firstOrNull { it.id == id }?.let(::title) ?: "уже завершена" } + + /** Tasks with no parent in [all], the top level of the list. */ + fun roots(all: List): List { + val ids = all.mapTo(HashSet()) { it.id } + return all.filter { it.parentId == null || it.parentId !in ids } + } + + /** Tasks started by [task]. */ + fun childrenOf(task: TaskSnapshot, all: Collection): List = all.filter { it.parentId == task.id } + + /** `3, активных 1` for the subtasks of [task]. */ + fun childrenLine(task: TaskSnapshot, all: Collection): String { + val children = childrenOf(task, all) + return "${children.size}, активных ${children.count { it.isActive }}" + } + + /** How many tasks were started by [task]. */ + fun children(task: TaskSnapshot, all: Collection): Int = all.count { it.parentId == task.id } + + /** Text about a noticeable delay such as a server freeze, or `null` when the task ran on time. */ + fun lag(task: TaskSnapshot): String? { + val worst = task.worstLag?.takeIf { it >= NOTABLE_LAG } ?: return null + val last = task.lastLag ?: Duration.ZERO + return "последнее ${span(last)}, наибольшее ${span(worst)}" + } + fun stopAnswer(task: TaskSnapshot): String = when { - !isActive(task.status) -> "нет, задача уже ${label(task.status)}" + !task.isActive -> "нет, задача уже ${label(task.status)}" !task.cancellable -> "нет, плагин запретил" else -> "да" } @@ -91,4 +119,5 @@ object TaskLabels { private const val HOURS_PER_DAY = 24L const val SHORT_ID = 8 + private val NOTABLE_LAG: Duration = Duration.ofSeconds(1) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskPeriod.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskPeriod.kt index 6cc81231b..4933eb3de 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskPeriod.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskPeriod.kt @@ -1,9 +1,10 @@ package org.pnfolder.pnlibrary.core.commands.tasks -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot import java.time.Duration import java.time.Instant +/** Age bucket of a finished task in the task list; [word] is the command argument. */ enum class TaskPeriod(val word: String, val label: String) { TODAY("today", "сегодня"), @@ -15,9 +16,9 @@ enum class TaskPeriod(val word: String, val label: String) { ; fun keep(task: TaskSnapshot): Boolean = when (this) { - TODAY -> TaskLabels.isToday(task) || TaskLabels.isActive(task.status) - WEEK -> TaskLabels.activity(task).isAfter(Instant.now().minus(Duration.ofDays(WEEK_DAYS))) || TaskLabels.isActive(task.status) - OLDER -> !TaskLabels.isToday(task) && !TaskLabels.isActive(task.status) + TODAY -> TaskLabels.isToday(task) || task.isActive + WEEK -> TaskLabels.activity(task).isAfter(Instant.now().minus(Duration.ofDays(WEEK_DAYS))) || task.isActive + OLDER -> !TaskLabels.isToday(task) && !task.isActive ANY -> true } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskState.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskState.kt index aad7e44e4..8ab3dda8c 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskState.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskState.kt @@ -1,8 +1,9 @@ package org.pnfolder.pnlibrary.core.commands.tasks -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus +/** Task filter of the task list; [word] is the command argument. */ enum class TaskState(val word: String, val label: String) { ALL("all", "все"), @@ -15,7 +16,7 @@ enum class TaskState(val word: String, val label: String) { fun keep(task: TaskSnapshot): Boolean = when (this) { ALL -> true - ACTIVE -> TaskLabels.isActive(task.status) + ACTIVE -> task.isActive FAILED -> task.status == TaskStatus.FAILED || task.lastFailure != null DONE -> task.status == TaskStatus.COMPLETED || task.status == TaskStatus.CANCELLED } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticContributors.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticContributors.kt index 7533cd1e1..0bfcdfa69 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticContributors.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticContributors.kt @@ -4,6 +4,7 @@ import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticConfiguration import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticRegistration import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsContributor import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticValueSanitizer import java.nio.file.Path import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean @@ -11,6 +12,7 @@ import java.util.concurrent.atomic.AtomicBoolean /** Contributor registrations and configuration declarations for one plugin. */ internal class DiagnosticContributors( private val sanitizer: DiagnosticValueSanitizer, + private val onFailure: (what: String, error: Throwable) -> Unit = { _, _ -> }, ) { private val contributors = ConcurrentHashMap() @@ -71,8 +73,9 @@ internal class DiagnosticContributors( } } } - } catch (_: Exception) { + } catch (error: Exception) { // One malformed contributor must not prevent collection from the others. + onFailure("A diagnostics contributor of $plugin failed to list its configuration files", error) } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticIncidentLog.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticIncidentLog.kt index 4056cbb17..24d628f31 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticIncidentLog.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticIncidentLog.kt @@ -1,6 +1,7 @@ package org.pnfolder.pnlibrary.core.diagnostics -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticLevel +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticLevel +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticValueSanitizer import java.time.Instant import java.util.ArrayDeque diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticStatusStore.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticStatusStore.kt index 4918eb8be..22d2dd574 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticStatusStore.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticStatusStore.kt @@ -1,5 +1,6 @@ package org.pnfolder.pnlibrary.core.diagnostics +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticValueSanitizer import java.time.Instant import java.util.concurrent.ConcurrentHashMap diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticThrowables.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticThrowables.kt deleted file mode 100644 index f2be4e890..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticThrowables.kt +++ /dev/null @@ -1,75 +0,0 @@ -package org.pnfolder.pnlibrary.core.diagnostics - -import java.nio.charset.StandardCharsets -import java.security.MessageDigest -import java.util.concurrent.CompletionException -import java.util.concurrent.ExecutionException - -/** Shared rules for grouping repeated failures: the significant cause, its origin frame, and a stable fingerprint. */ -internal object DiagnosticThrowables { - private const val FINGERPRINT_BYTES = 8 - private val UUID_PATTERN = Regex("(?i)\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b") - private val LONG_NUMBER_PATTERN = Regex("\\b\\d{4,}\\b") - private val WHITESPACE_PATTERN = Regex("\\s+") - private val IGNORED_FRAME_PREFIXES = listOf( - "java.", "javax.", "kotlin.", "kotlinx.", "sun.", "jdk.", - "org.bukkit.", "net.minecraft.", "io.papermc.", "com.destroystokyo.paper.", - "org.pnfolder.pnlibrary.", - ) - - /** Strips asynchronous wrappers so the failure that actually happened is reported. */ - fun unwrap(error: Throwable?): Throwable? { - var current = error ?: return null - while (current is CompletionException || current is ExecutionException) { - current = current.cause ?: break - } - return current - } - - /** Returns the first frame outside the JDK, the server and pnLibrary, or the top frame when there is none. */ - fun originFrame(error: Throwable?): StackTraceElement? { - val trace = unwrap(error)?.stackTrace ?: return null - return trace.firstOrNull(::isApplicationFrame) ?: trace.firstOrNull() - } - - /** Describes [originFrame] of [error] as report data, or returns `null` for an empty stack trace. */ - fun origin(error: Throwable): Map? { - val frame = originFrame(error) ?: return null - return linkedMapOf( - "class" to frame.className, - "method" to frame.methodName, - "file" to frame.fileName, - "line" to frame.lineNumber.takeIf { it >= 0 }, - ) - } - - /** - * Fingerprints a failure from its [context], message and significant cause. - * - * Identifiers and long numbers are masked, so repeats of one problem share an id. - */ - fun fingerprint(context: List, message: String, error: Throwable?): String { - val significant = unwrap(error) - val frame = originFrame(error) - val source = (context + listOf( - normalize(message), - significant?.javaClass?.name.orEmpty(), - normalize(significant?.message.orEmpty()), - frame?.className.orEmpty(), - frame?.methodName.orEmpty(), - )).joinToString("\u0000") - return MessageDigest.getInstance("SHA-256") - .digest(source.toByteArray(StandardCharsets.UTF_8)) - .take(FINGERPRINT_BYTES) - .joinToString("") { "%02x".format(it) } - } - - private fun isApplicationFrame(frame: StackTraceElement): Boolean = - IGNORED_FRAME_PREFIXES.none(frame.className::startsWith) - - private fun normalize(value: String): String = value - .replace(UUID_PATTERN, "") - .replace(LONG_NUMBER_PATTERN, "") - .replace(WHITESPACE_PATTERN, " ") - .trim() -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticsRegistry.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticsRegistry.kt index 423c9fd23..fc88746a1 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticsRegistry.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticsRegistry.kt @@ -1,9 +1,10 @@ package org.pnfolder.pnlibrary.core.diagnostics -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticLevel import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticRegistration import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsContributor import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsService +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticLevel +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticValueSanitizer import java.nio.file.Path import java.util.concurrent.ConcurrentHashMap @@ -32,6 +33,13 @@ internal class DiagnosticsRegistry(eventLimit: Int = DEFAULT_EVENT_LIMIT) : Diag @Volatile private var activityListener: DiagnosticEventListener? = null + /** + * Told what failed when a listener or a plugin's contributor throws. None of them may reject a diagnostic event, + * so the failure ends here instead of with the caller. + */ + @Volatile + var onInternalFailure: (what: String, error: Throwable) -> Unit = { _, _ -> } + /** * Installs a best-effort callback invoked after an event changes. * @@ -105,8 +113,9 @@ internal class DiagnosticsRegistry(eventLimit: Int = DEFAULT_EVENT_LIMIT) : Diag ) { try { activityListener?.onEvent(plugin, level, component, code, message, error, fields) - } catch (_: Exception) { + } catch (error: Exception) { // Compatibility listeners are observers and must never reject diagnostics. + onInternalFailure("The diagnostic activity listener failed", error) } } @@ -210,18 +219,25 @@ internal class DiagnosticsRegistry(eventLimit: Int = DEFAULT_EVENT_LIMIT) : Diag ) private fun stateOf(plugin: String) = - plugins.computeIfAbsent(sanitizer.key(plugin)) { PluginState(limit, sanitizer) } + plugins.computeIfAbsent(sanitizer.key(plugin)) { + PluginState(limit, sanitizer) { what, error -> onInternalFailure(what, error) } + } private fun notifyEventsChanged() { try { eventChangeListener?.invoke() - } catch (_: Exception) { + } catch (error: Exception) { // Persistence callbacks are best-effort and must not reject the event. + onInternalFailure("The diagnostic history callback failed", error) } } - private class PluginState(eventLimit: Int, sanitizer: DiagnosticValueSanitizer) { - val contributors = DiagnosticContributors(sanitizer) + private class PluginState( + eventLimit: Int, + sanitizer: DiagnosticValueSanitizer, + onFailure: (what: String, error: Throwable) -> Unit, + ) { + val contributors = DiagnosticContributors(sanitizer, onFailure) val statuses = DiagnosticStatusStore(sanitizer) val incidents = DiagnosticIncidentLog(eventLimit, sanitizer) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/command/DiagnosticCommand.kt similarity index 90% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommand.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/command/DiagnosticCommand.kt index 54671d189..180dd4a01 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommand.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/command/DiagnosticCommand.kt @@ -1,15 +1,15 @@ -package org.pnfolder.pnlibrary.core.diagnostics +package org.pnfolder.pnlibrary.core.diagnostics.command import net.kyori.adventure.text.Component import org.pnfolder.pnlibrary.api.chat.ChatKit import org.pnfolder.pnlibrary.api.chat.ChatNotice -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticReport +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticReport import org.pnfolder.pnlibrary.api.runtime.PnLibrary import java.util.Locale diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommandExecutor.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/command/DiagnosticCommandExecutor.kt similarity index 94% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommandExecutor.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/command/DiagnosticCommandExecutor.kt index 8b4be0530..b484c7748 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommandExecutor.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/command/DiagnosticCommandExecutor.kt @@ -1,10 +1,10 @@ -package org.pnfolder.pnlibrary.core.diagnostics +package org.pnfolder.pnlibrary.core.diagnostics.command import org.pnfolder.pnlibrary.api.diagnostics.DebugRequest -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticReport +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticReport import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskSpec +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec import org.pnfolder.pnlibrary.core.lifecycle.runtimeTaskScope import java.time.Clock import java.util.concurrent.ConcurrentHashMap diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigFileDiagnostics.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/ConfigFileDiagnostics.kt similarity index 74% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigFileDiagnostics.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/ConfigFileDiagnostics.kt index 4ff1b74f1..07baa72bf 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigFileDiagnostics.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/ConfigFileDiagnostics.kt @@ -1,14 +1,15 @@ -package org.pnfolder.pnlibrary.core.diagnostics +package org.pnfolder.pnlibrary.core.diagnostics.config import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticConfiguration import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsContributor import org.pnfolder.pnlibrary.config.ManagedConfigFile +import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticsRegistry /** * Puts every file a plugin registers through the configuration service into that plugin's report, with the fields * marked `@ConfigSecret` hidden. The returned handle removes the file from the report again. */ -internal fun configFileDiagnostics(diagnostics: DiagnosticsRegistry): (ManagedConfigFile) -> AutoCloseable? = { file -> +internal fun DiagnosticsRegistry.reportConfigFile(file: ManagedConfigFile): AutoCloseable? { val configuration = DiagnosticConfiguration.builder(file.path).also { builder -> file.secretPaths.forEach(builder::exclude) }.build() @@ -17,5 +18,5 @@ internal fun configFileDiagnostics(diagnostics: DiagnosticsRegistry): (ManagedCo override fun collect(): Map = emptyMap() override fun configurations(): Collection = listOf(configuration) } - diagnostics.register(file.pluginId.value, file.directory, contributor) + return register(file.pluginId.value, file.directory, contributor) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigReader.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/ConfigReader.kt similarity index 83% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigReader.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/ConfigReader.kt index 1bf1b80fe..b9267d733 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigReader.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/ConfigReader.kt @@ -1,15 +1,16 @@ -package org.pnfolder.pnlibrary.core.diagnostics +package org.pnfolder.pnlibrary.core.diagnostics.config import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticConfiguration import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticRedactor import java.nio.charset.StandardCharsets import java.nio.file.Path /** * Reads plugin configuration files for support reports, with the values each report must hide. * - * File confinement is done by [SecureConfigurationFileReader], syntax by [ConfigurationDocumentCodec], and + * File confinement is done by [SecureConfigReader], syntax by [ConfigurationDocumentCodec], and * the hiding rules by [ConfigRedaction], built from the global settings and the file's own declaration. * * @param dataFolder default trusted root for relative configuration paths @@ -20,7 +21,7 @@ internal class ConfigReader( private val globalConfig: PnLibraryConfig = PnLibraryConfig(), ) { private val redactor = DiagnosticRedactor() - private val secureFileReader = SecureConfigurationFileReader(MAX_FILE_SIZE_BYTES) + private val secureFileReader = SecureConfigReader(MAX_FILE_SIZE_BYTES) private val documentCodec = ConfigurationDocumentCodec(redactor) /** Text configuration prepared for a plaintext local report. */ @@ -48,9 +49,11 @@ internal class ConfigReader( val path = configSpec.path val read = secureFileReader.read(rootDirectory, path) val content = read.content ?: return ExactFile(path, error = read.error) - if (!documentCodec.isStructured(path)) return ExactFile(path, content) - val redaction = redaction(configSpec, rootDirectory) + if (!documentCodec.isStructured(path)) { + // Values of a format that is not parsed cannot be hidden one by one, so the file is only sent when nothing has to be. + return if (redaction.hasRequests) ExactFile(path, error = UNPARSABLE_WITH_RULES) else ExactFile(path, content) + } val data = runCatchingNonFatal { documentCodec.parse(path, content) }.getOrNull() if (data == null) { // A file that cannot be parsed cannot have single values hidden, so it is only sent when nothing has to be. @@ -103,22 +106,12 @@ internal class ConfigReader( } private fun redaction(configSpec: DiagnosticConfiguration, rootDirectory: Path): ConfigRedaction = ConfigRedaction( - excludedPaths = (administratorPaths("${rootDirectory.fileName}/${configSpec.path}") + configSpec.excludedPaths).toSet(), + excludedPaths = configSpec.excludedPaths.toSet(), keyPatterns = ConfigRedaction.compile(globalConfig.secretKeyPatterns + configSpec.secretKeyPatterns), valuePatterns = ConfigRedaction.compile(globalConfig.redactValuePatterns + configSpec.valuePatterns), redactor = redactor, ) - /** An entry is either a path for every file, or `plugin/file.yml:path` for that one file only. */ - private fun administratorPaths(fileKey: String): List = globalConfig.excludedPaths.mapNotNull { entry -> - val colon = entry.indexOf(':') - when { - colon < 0 -> entry - entry.substring(0, colon).trim().equals(fileKey, ignoreCase = true) -> entry.substring(colon + 1).trim() - else -> null - } - } - companion object { const val MAX_FILE_SIZE_BYTES = 1_048_576L private const val UNPARSABLE_WITH_RULES = "[file cannot be parsed and has values that must stay hidden]" diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigRedaction.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/ConfigRedaction.kt similarity index 84% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigRedaction.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/ConfigRedaction.kt index 20db87885..b3eb1234d 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigRedaction.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/ConfigRedaction.kt @@ -1,12 +1,13 @@ -package org.pnfolder.pnlibrary.core.diagnostics +package org.pnfolder.pnlibrary.core.diagnostics.config import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticRedactor import java.util.regex.Pattern /** * The values of one configuration file that a report must hide. * - * [requested] is what an administrator (`excluded-paths`, key and value patterns) or the plugin (`@ConfigSecret`, + * [requested] is what an administrator (key and value patterns) or the plugin (`@ConfigSecret`, * its own patterns) asked for; those promises hold in every report. [redact] adds the built-in secret key names, * the built-in text redactor and size limits for a plaintext report. */ @@ -16,6 +17,8 @@ internal class ConfigRedaction( private val valuePatterns: List, private val redactor: DiagnosticRedactor, ) { + private val wildcardPaths: List> = excludedPaths.filter { "*" in it.split('.') }.map { it.split('.') } + /** Whether anything was asked to be hidden in this file. */ val hasRequests: Boolean get() = excludedPaths.isNotEmpty() || keyPatterns.isNotEmpty() || valuePatterns.isNotEmpty() @@ -30,7 +33,7 @@ internal class ConfigRedaction( for ((key, value) in data) { val path = if (parent.isEmpty()) key else "$parent.$key" result[key] = when { - path in excludedPaths -> EXCLUDED + isExcluded(path) -> EXCLUDED matchesKeyPattern(key, path) -> SECRET_KEY else -> hideRequestedValue(value, path) } @@ -54,7 +57,7 @@ internal class ConfigRedaction( for ((key, value) in data.entries.take(MAX_ENTRIES_PER_MAP)) { val path = if (parent.isEmpty()) key else "$parent.$key" result[key] = when { - path in excludedPaths -> EXCLUDED + isExcluded(path) -> EXCLUDED isBuiltInSecret(key, path) || matchesKeyPattern(key, path) -> SECRET_KEY else -> redactValue(value, path, depth) } @@ -72,6 +75,13 @@ internal class ConfigRedaction( else -> replaceValuePatterns(redactor.redact(value.toString())) } + /** A `*` segment in an excluded path stands for any key, so a secret inside the values of a map is found. */ + private fun isExcluded(path: String): Boolean = + path in excludedPaths || wildcardPaths.any { pattern -> matches(pattern, path.split('.')) } + + private fun matches(pattern: List, segments: List): Boolean = + pattern.size == segments.size && pattern.indices.all { pattern[it] == "*" || pattern[it] == segments[it] } + private fun replaceValuePatterns(input: String): String = valuePatterns.fold(input) { text, pattern -> // A pattern that fails on this input hides the whole value: a report must never leak what it could not check. runCatchingNonFatal { pattern.matcher(text).replaceAll(SECRET_VALUE) }.getOrDefault(SECRET_VALUE) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigurationDocumentCodec.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/ConfigurationDocumentCodec.kt similarity index 96% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigurationDocumentCodec.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/ConfigurationDocumentCodec.kt index dd3458f5a..b2b8b40a7 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigurationDocumentCodec.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/ConfigurationDocumentCodec.kt @@ -1,7 +1,8 @@ -package org.pnfolder.pnlibrary.core.diagnostics +package org.pnfolder.pnlibrary.core.diagnostics.config import com.google.gson.Gson import com.google.gson.JsonParser +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticRedactor import org.yaml.snakeyaml.LoaderOptions import org.yaml.snakeyaml.Yaml import org.yaml.snakeyaml.constructor.SafeConstructor @@ -12,7 +13,7 @@ import java.util.Properties * * The codec deliberately produces a neutral tree of maps, lists, scalar values, * and `null`. It performs no path validation or secret filtering; those concerns - * belong to [SecureConfigurationFileReader] and [ConfigReader], respectively. + * belong to [SecureConfigReader] and [ConfigReader], respectively. * Unknown extensions are represented by a bounded `raw` value. */ internal class ConfigurationDocumentCodec( diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/SecureConfigurationFileReader.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/SecureConfigReader.kt similarity index 97% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/SecureConfigurationFileReader.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/SecureConfigReader.kt index 753a99a7a..177e5e748 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/SecureConfigurationFileReader.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/config/SecureConfigReader.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.diagnostics +package org.pnfolder.pnlibrary.core.diagnostics.config import java.nio.file.Files import java.nio.file.Path @@ -13,7 +13,7 @@ import java.nio.file.Path * * @param maximumBytes largest accepted file size in bytes */ -internal class SecureConfigurationFileReader( +internal class SecureConfigReader( private val maximumBytes: Long = DEFAULT_MAXIMUM_BYTES, ) { /** Result of one confined file read. Exactly one of [content] and [error] is set. */ diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticRedactor.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/redaction/DiagnosticRedactor.kt similarity index 93% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticRedactor.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/redaction/DiagnosticRedactor.kt index 7a77139af..fcdf26f19 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticRedactor.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/redaction/DiagnosticRedactor.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.diagnostics +package org.pnfolder.pnlibrary.core.diagnostics.redaction import java.util.regex.Pattern @@ -53,9 +53,7 @@ internal class DiagnosticRedactor { private val EMAIL: Pattern = Pattern.compile( "(?]+)" ) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/redaction/DiagnosticThrowables.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/redaction/DiagnosticThrowables.kt new file mode 100644 index 000000000..751c6fd8d --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/redaction/DiagnosticThrowables.kt @@ -0,0 +1,79 @@ +package org.pnfolder.pnlibrary.core.diagnostics.redaction + +import java.nio.charset.StandardCharsets +import java.security.MessageDigest +import java.util.concurrent.CompletionException +import java.util.concurrent.ExecutionException + +// Shared rules for grouping repeated failures: the significant cause, its origin frame, and a stable fingerprint. + +private const val FINGERPRINT_BYTES = 8 +private const val HEX_DIGITS = "0123456789abcdef" +internal val UUID_REGEX = Regex("(?i)\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b") +private val LONG_NUMBER_PATTERN = Regex("\\b\\d{4,}\\b") +private val WHITESPACE_PATTERN = Regex("\\s+") +private val IGNORED_FRAME_PREFIXES = listOf( + "java.", "javax.", "kotlin.", "kotlinx.", "sun.", "jdk.", + "org.bukkit.", "net.minecraft.", "io.papermc.", "com.destroystokyo.paper.", + "org.pnfolder.pnlibrary.", +) + +/** Strips asynchronous wrappers so the failure that actually happened is reported. */ +internal fun Throwable?.significantCause(): Throwable? { + var current = this ?: return null + while (current is CompletionException || current is ExecutionException) { + current = current.cause ?: break + } + return current +} + +/** Returns the first frame outside the JDK, the server and pnLibrary, or the top frame when there is none. */ +internal fun Throwable?.originFrame(): StackTraceElement? { + val trace = significantCause()?.stackTrace ?: return null + return trace.firstOrNull(::isApplicationFrame) ?: trace.firstOrNull() +} + +/** Describes [originFrame] of this error as report data, or returns `null` for an empty stack trace. */ +internal fun Throwable.originData(): Map? { + val frame = originFrame() ?: return null + return linkedMapOf( + "class" to frame.className, + "method" to frame.methodName, + "file" to frame.fileName, + "line" to frame.lineNumber.takeIf { it >= 0 }, + ) +} + +/** + * Fingerprints this failure (or none) from its [context], message and significant cause. + * + * Identifiers and long numbers are masked, so repeats of one problem share an id. + */ +internal fun Throwable?.fingerprint(context: List, message: String): String { + val significant = significantCause() + val frame = originFrame() + val source = (context + listOf( + normalize(message), + significant?.javaClass?.name.orEmpty(), + normalize(significant?.message.orEmpty()), + frame?.className.orEmpty(), + frame?.methodName.orEmpty(), + )).joinToString("\u0000") + val digest = MessageDigest.getInstance("SHA-256").digest(source.toByteArray(StandardCharsets.UTF_8)) + val hex = CharArray(FINGERPRINT_BYTES * 2) + for (index in 0 until FINGERPRINT_BYTES) { + val value = digest[index].toInt() and 0xFF + hex[index * 2] = HEX_DIGITS[value ushr 4] + hex[index * 2 + 1] = HEX_DIGITS[value and 0x0F] + } + return String(hex) +} + +private fun isApplicationFrame(frame: StackTraceElement): Boolean = + IGNORED_FRAME_PREFIXES.none(frame.className::startsWith) + +private fun normalize(value: String): String = value + .replace(UUID_REGEX, "") + .replace(LONG_NUMBER_PATTERN, "") + .replace(WHITESPACE_PATTERN, " ") + .trim() diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticValueSanitizer.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/redaction/DiagnosticValueSanitizer.kt similarity index 93% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticValueSanitizer.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/redaction/DiagnosticValueSanitizer.kt index b217da679..5fd89437a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticValueSanitizer.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/diagnostics/redaction/DiagnosticValueSanitizer.kt @@ -1,6 +1,6 @@ -package org.pnfolder.pnlibrary.core.diagnostics +package org.pnfolder.pnlibrary.core.diagnostics.redaction -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticLevel +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticLevel import java.io.PrintWriter import java.io.StringWriter import java.util.IdentityHashMap @@ -46,10 +46,10 @@ internal class DiagnosticValueSanitizer( code: String, message: String, error: Throwable?, - ): String = DiagnosticThrowables.fingerprint(listOf(key(plugin), level.name, component, code), message, error) + ): String = error.fingerprint(listOf(key(plugin), level.name, component, code), message) /** Returns the first useful application frame for an exception, if available. */ - fun exceptionOrigin(error: Throwable): Map? = DiagnosticThrowables.origin(error) + fun exceptionOrigin(error: Throwable): Map? = error.originData() private fun map( values: Map<*, *>?, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadBatch.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadBatch.kt index 404f34d48..029ae9470 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadBatch.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadBatch.kt @@ -6,7 +6,8 @@ import org.pnfolder.pnlibrary.api.downloads.DownloadState import org.pnfolder.pnlibrary.api.downloads.FileDownload import org.pnfolder.pnlibrary.api.downloads.FileDownloads import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup +import org.pnfolder.pnlibrary.core.downloads.settings.DownloadConfiguration +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup import java.util.Collections import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage @@ -17,7 +18,7 @@ import java.util.concurrent.atomic.AtomicReference /** Tracks the files of one download request and runs at most one download of them at a time. */ internal class DownloadBatch( private val request: FileDownloads, - private val configuration: DownloadConfiguration, + private val configuration: () -> DownloadConfiguration, private val executor: Executor, private val managerIsClosed: () -> Boolean, private val install: (List, beforePublish: () -> Unit) -> Unit, @@ -25,6 +26,7 @@ internal class DownloadBatch( private val dependenciesStaged: (List) -> Unit, private val failed: (List, Throwable) -> Unit, private val remove: (DownloadBatch) -> Unit, + private val automaticAllowed: () -> Boolean = { configuration().automatic }, ) : DownloadRegistration { private val stateLock = Any() private val closed = AtomicBoolean(false) @@ -56,10 +58,10 @@ internal class DownloadBatch( } val selectedFiles = selectFiles(declarations, automaticPolicy) - if (!configuration.enabled) return blocked(promise, "система загрузок отключена") + if (!configuration().enabled) return blocked(promise, "система загрузок отключена") if (selectedFiles.isEmpty()) { if (automaticPolicy && declarations.isNotEmpty()) { - return blocked(promise, "автозагрузка запрещена в downloads.yml") + return blocked(promise, "автозагрузка выключена (включить: /pn deps auto on)") } promise.complete(snapshots()) return promise @@ -89,7 +91,7 @@ internal class DownloadBatch( } private fun selectFiles(declarations: List, automaticPolicy: Boolean): List = - if (automaticPolicy && !configuration.automatic) { + if (automaticPolicy && !automaticAllowed()) { declarations.filter(FileDownload::forceAutomaticDownload) } else { declarations diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadConfiguration.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadConfiguration.kt deleted file mode 100644 index 3ff06d26c..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadConfiguration.kt +++ /dev/null @@ -1,34 +0,0 @@ -package org.pnfolder.pnlibrary.core.downloads - -import org.pnfolder.pnlibrary.api.downloads.DownloadDestination -import org.pnfolder.pnlibrary.config.LibraryConfigFiles -import java.nio.file.Path -import java.util.function.Supplier - -/** Administrator policy from `downloads.yml`: whether downloads run, start automatically, and which destinations are allowed. */ -internal data class DownloadConfiguration( - val enabled: Boolean = true, - val automatic: Boolean = false, - val destinations: Set = setOf( - DownloadDestination.DATA_FOLDER, DownloadDestination.CACHE, - ), -) { - companion object { - /** - * Reads the policy from [path], creating the file with defaults when it is missing. - * - * An unreadable file never blocks startup: conservative defaults are used and [warning] explains why. - */ - fun load(path: Path, warning: (String) -> Unit = {}): DownloadConfiguration = try { - LibraryConfigFiles.load( - file = path, - type = DownloadSettings::class.java, - defaults = Supplier { DownloadSettings() }, - warning = warning, - ).toConfiguration() - } catch (error: Exception) { - warning("downloads.yml не прочитан, используются значения по умолчанию: ${error.message}") - DownloadConfiguration() - } - } -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadSettings.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadSettings.kt deleted file mode 100644 index d125197f4..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadSettings.kt +++ /dev/null @@ -1,48 +0,0 @@ -package org.pnfolder.pnlibrary.core.downloads - -import org.pnfolder.pnlibrary.api.config.ConfigComment -import org.pnfolder.pnlibrary.api.config.ConfigDefaultOnInvalid -import org.pnfolder.pnlibrary.api.downloads.DownloadDestination - -/** Content of `plugins/pnLibrary/downloads.yml`: rules for files that plugins download through pnLibrary. */ -@ConfigComment( - "pnLibrary: загрузка файлов (downloads.yml)", - "", - "Правила для файлов, которые плагины скачивают через API pnLibrary.", - "Адреса скачивания не ограничиваются; ограничиваются только действия и места сохранения.", -) -/** - * Configuration section that restricts which download actions plugins may perform through pnLibrary. - */ -internal class DownloadSettings { - @field:ConfigDefaultOnInvalid - @field:ConfigComment("Включить систему загрузок. false: все запросы плагинов на загрузку отклоняются.") - var enabled: Boolean = true - - @field:ConfigDefaultOnInvalid - @field:ConfigComment("Разрешить загрузки, которые плагин запускает сам, без команды администратора.") - var automatic: Boolean = false - - @field:ConfigComment("Куда разрешено сохранять скачанные файлы.") - var destinations: Destinations = Destinations() - - /** Switches for the places a downloaded file may be saved to. */ - class Destinations { - @field:ConfigDefaultOnInvalid - @field:ConfigComment("Папка данных плагина, который запросил файл.") - var dataFolder: Boolean = true - - @field:ConfigDefaultOnInvalid - @field:ConfigComment("Общий кэш pnLibrary.") - var cache: Boolean = true - } - - fun toConfiguration(): DownloadConfiguration = DownloadConfiguration( - enabled = enabled, - automatic = automatic, - destinations = buildSet { - if (destinations.dataFolder) add(DownloadDestination.DATA_FOLDER) - if (destinations.cache) add(DownloadDestination.CACHE) - }, - ) -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/CompositeDownloadRegistration.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/CompositeDownloadRegistration.kt similarity index 91% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/CompositeDownloadRegistration.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/CompositeDownloadRegistration.kt index 988d7535b..4bdc76e8a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/CompositeDownloadRegistration.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/CompositeDownloadRegistration.kt @@ -1,8 +1,8 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.dependencies import org.pnfolder.pnlibrary.api.downloads.DownloadRegistration import org.pnfolder.pnlibrary.api.downloads.DownloadSnapshot -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup import java.util.concurrent.CompletionStage /** Presents two download registrations, such as declared files and dependencies, as one. */ diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DependencyDownloadReporter.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DependencyDownloadReporter.kt similarity index 50% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DependencyDownloadReporter.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DependencyDownloadReporter.kt index 12ea44199..3c46175fc 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DependencyDownloadReporter.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DependencyDownloadReporter.kt @@ -1,12 +1,13 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.dependencies -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.downloads.FileDownload import org.pnfolder.pnlibrary.api.logging.LogLevel import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity import org.pnfolder.pnlibrary.console.ConsoleCard import org.pnfolder.pnlibrary.console.ConsoleTree -import org.pnfolder.pnlibrary.core.ui.ConsoleStyle +import org.pnfolder.pnlibrary.core.downloads.DownloadFailureInterpreter +import org.pnfolder.pnlibrary.core.text.ConsoleStyle import org.pnfolder.pnlibrary.spi.platform.PlatformLogging import org.pnfolder.pnlibrary.spi.platform.PlatformOwnerMetadata import java.io.IOException @@ -16,6 +17,8 @@ import java.nio.file.Paths internal class DependencyDownloadReporter( private val logging: PlatformLogging, private val ownership: PlatformOwnerMetadata, + /** The control command as typed on this platform: `pn`, or `pnproxy` on a proxy where `pn` belongs to the game servers. */ + private val root: String = "pn", ) { fun failure(owner: Any, error: Throwable, level: LogLevel) { val details = DownloadFailureInterpreter.explain(error) @@ -37,6 +40,46 @@ internal class DependencyDownloadReporter( } } + /** Tells the administrator what is missing, where to get it, and how to have it installed. */ + fun missing(owner: Any, group: MissingGroup, installingNow: Boolean) { + val command = "$root deps install ${group.code}" + val needed = group.items.filter { it.required } + val optional = group.items.filterNot { it.required } + val trees = listOf("Обязательные" to needed, "Необязательные" to optional).filter { it.second.isNotEmpty() }.map { (name, items) -> + ConsoleTree.builder(name).also { tree -> items.forEach { item -> describe(tree, item) } }.build() + } + val next = ConsoleTree.builder("Что сделать").also { tree -> + when { + installingNow -> tree.child("Скачиваю сам, это займёт несколько секунд; потом перезапустите сервер") + group.installable -> tree.child("Вставьте в консоль: $command").child("Или включите автозагрузку: $root deps auto on") + else -> tree.child("Скачайте по ссылкам выше и положите в папку plugins") + } + }.build() + ConsoleCard.builder(ConsoleStyle.theme(ChatTone.WARNING), "НЕ ХВАТАЕТ ПЛАГИНОВ") + .mascot("o.o", group.owner, "нужны другие плагины") + .blank().also { card -> trees.forEach { card.tree(it).blank() } }.tree(next).blank() + .status(if (needed.isEmpty()) "Без них ${group.owner} работает, но без части возможностей" else "Без них ${group.owner} работает не полностью") + .build() + .send { logging.console(owner, it) } + if (!installingNow && group.installable) { + logging.log(owner, LogLevel.WARNING, "${group.owner}: не хватает ${group.items.joinToString { it.plugin }}. Установить: $command") + } + } + + /** One missing plugin: its name and version, why it is needed, how the file is checked, and where to get it. */ + private fun describe(tree: ConsoleTree.Builder, item: MissingDependency) { + val name = if (item.title.equals(item.plugin, ignoreCase = true)) item.plugin else "${item.title} (${item.plugin})" + tree.child("$name ${item.minimum}+") + item.description?.let { tree.child(" $it") } + if (item.noFileForServer) tree.child(" для этого сервера готового файла нет, скачайте вручную") + item.variant?.let { tree.child(" выбран файл: $it") } + val links = listOfNotNull(item.page) + item.sources + links.forEach { tree.child(" $it") } + if (item.sources.isNotEmpty()) { + tree.child(if (item.checked) " файл проверяется по SHA-256 автора" else " сумма автора не задана, файл берётся с первой доступной ссылки") + } + } + fun staged(owner: Any, declarations: List) { val files = declarations.map { Paths.get(it.relativePath).fileName.toString() } ConsoleCard.builder(ConsoleStyle.theme(ChatTone.SUCCESS), "ЗАВИСИМОСТИ ПОДГОТОВЛЕНЫ") diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DependencyDownloadRequestFactory.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DependencyDownloadRequestFactory.kt similarity index 61% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DependencyDownloadRequestFactory.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DependencyDownloadRequestFactory.kt index 844c1a1d0..dac277c46 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DependencyDownloadRequestFactory.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DependencyDownloadRequestFactory.kt @@ -1,9 +1,11 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.dependencies -import org.pnfolder.pnlibrary.api.dependencies.ExternalPluginDependency import org.pnfolder.pnlibrary.api.dependencies.PluginDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalArtifact +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency import org.pnfolder.pnlibrary.api.downloads.DownloadDestination import org.pnfolder.pnlibrary.api.downloads.FileDownloads +import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.version.SemanticVersion import java.nio.file.Path @@ -13,35 +15,45 @@ internal data class DependencyDownloadRequest( val requirements: Map, ) -internal class DependencyDownloadRequestFactory(private val pluginDirectory: Path) { +/** [platform] and [minecraft] pick, among a dependency's files, the one made for this server. */ +internal class DependencyDownloadRequestFactory( + private val serverUpdateFolder: Path, + private val platform: PlatformType, + private val minecraft: () -> String?, +) { + /** The file of [dependency] meant for this server, or null when it has none (only a page, or no variant fits). */ + fun fileFor(dependency: ExternalPluginDependency): ExternalArtifact? = dependency.artifactFor(platform, minecraft()) + + /** The external dependencies that are not installed at a fitting version. */ + fun missing(dependencies: List, installedPlugins: Map): List = + dependencies.mapNotNull { it.external }.filterNot { isAlreadyCompatible(it, installedPlugins) } + fun create( dependencies: List, installedPlugins: Map, ): DependencyDownloadRequest? { val downloadable = dependencies.mapNotNull { dependency -> val external = dependency.external ?: return@mapNotNull null - val artifact = external.artifact ?: return@mapNotNull null - if (!dependency.automaticDownload || isAlreadyCompatible(external, installedPlugins)) return@mapNotNull null + val artifact = fileFor(external) ?: return@mapNotNull null + if (isAlreadyCompatible(external, installedPlugins)) return@mapNotNull null Triple(dependency, external, artifact) } if (downloadable.isEmpty()) return null val request = FileDownloads.builder() - .dataDirectory(pluginDirectory.resolve("update")) + .dataDirectory(serverUpdateFolder) .also { builder -> downloadable.forEach { (dependency, external, artifact) -> val key = dependencyKey(external.plugin) builder.file(key) { file -> file.url(artifact.uri.toString()) .required(dependency.required) - .automaticDownload(true) + .automaticDownload(dependency.automaticDownload) .forceAutomaticDownload(dependency.forceAutomaticDownload) .destination(DownloadDestination.DATA_FOLDER, safeFileName(external.plugin)) - val expectedSize = artifact.size - val expectedHash = artifact.sha256 - if (expectedSize != null && expectedHash != null) { - file.integrity(expectedSize, expectedHash) - } + artifact.mirrors.forEach { file.mirror(it.toString()) } + artifact.sha256?.let { file.sha256(it) } + artifact.maxBytes?.let { file.maxBytes(it) } } } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadedDependencyStore.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DownloadedDependencyStore.kt similarity index 96% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadedDependencyStore.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DownloadedDependencyStore.kt index 545d1d785..d18173863 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadedDependencyStore.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DownloadedDependencyStore.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.dependencies import java.nio.file.Files import java.nio.file.Path diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/MissingDependencies.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/MissingDependencies.kt new file mode 100644 index 000000000..aa25c5d74 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/MissingDependencies.kt @@ -0,0 +1,69 @@ +package org.pnfolder.pnlibrary.core.downloads.dependencies + +import org.pnfolder.pnlibrary.api.downloads.DownloadRegistration +import org.pnfolder.pnlibrary.api.downloads.DownloadState +import java.net.URI +import java.security.SecureRandom + +/** One plugin that is not installed (or too old): what it is, why it is needed, and the addresses it can be had from. */ +internal data class MissingDependency( + val plugin: String, + val minimum: String, + val page: URI?, + val sources: List, + val title: String = plugin, + val description: String? = null, + val required: Boolean = true, + /** `true` when the author gave a SHA-256 the file is checked against; else the file is taken as downloaded. */ + val checked: Boolean = false, + /** Name of the chosen file when the plugin has several for different servers. */ + val variant: String? = null, + /** `true` when the plugin has files, but none is made for this platform or Minecraft version. */ + val noFileForServer: Boolean = false, +) + +/** The missing dependencies of one plugin; [code] confirms their installation from the console. */ +internal class MissingGroup( + val owner: String, + val code: String, + val items: List, + private val registration: DownloadRegistration?, +) { + val installable: Boolean get() = registration != null + val addresses: List get() = items.flatMap { it.sources } + + /** Not yet staged: still worth telling the administrator about. */ + val pending: Boolean + get() = registration?.snapshots()?.let { shots -> shots.isEmpty() || shots.any { it.state != DownloadState.STAGED } } ?: true + + fun install() = requireNotNull(registration) { "У этих зависимостей нет прямой ссылки" }.downloadNow() +} + +/** Missing dependencies waiting for the administrator, found by the code printed with them. */ +internal class MissingDependencies { + private val groups = ArrayList() + private val random = SecureRandom() + + @Synchronized + fun add(owner: String, items: List, registration: DownloadRegistration?): MissingGroup { + val group = MissingGroup(owner, newCode(), items, registration) + groups += group + return group + } + + @Synchronized + fun pending(): List = groups.filter { it.pending } + + @Synchronized + fun find(code: String): MissingGroup? = groups.firstOrNull { it.pending && it.code.equals(code.trim(), ignoreCase = true) } + + private fun newCode(): String = (0 until CODE_PARTS).joinToString("-") { + (0 until PART_LENGTH).map { ALPHABET[random.nextInt(ALPHABET.length)] }.joinToString("") + } + + private companion object { + const val ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789" + const val CODE_PARTS = 4 + const val PART_LENGTH = 4 + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/AtomicDownloadPublisher.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/AtomicDownloadPublisher.kt similarity index 96% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/AtomicDownloadPublisher.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/AtomicDownloadPublisher.kt index 3dd4a6618..c655c8bae 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/AtomicDownloadPublisher.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/AtomicDownloadPublisher.kt @@ -1,8 +1,8 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.fetch import org.pnfolder.pnlibrary.common.io.AtomicFiles import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup import java.nio.file.Files import java.nio.file.LinkOption import java.nio.file.Path diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DirectDownloads.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/DirectDownloads.kt similarity index 57% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DirectDownloads.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/DirectDownloads.kt index 9635c505b..ab5b5ae4d 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DirectDownloads.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/DirectDownloads.kt @@ -1,20 +1,34 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.fetch import org.pnfolder.pnlibrary.api.dependencies.PluginDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency import org.pnfolder.pnlibrary.api.downloads.DownloadRegistration +import org.pnfolder.pnlibrary.api.downloads.DownloadSnapshot import org.pnfolder.pnlibrary.api.downloads.FileDownload import org.pnfolder.pnlibrary.api.downloads.FileDownloads import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.updates.engine.TrustedHttpClient +import org.pnfolder.pnlibrary.core.downloads.DownloadBatch +import org.pnfolder.pnlibrary.core.downloads.dependencies.DependencyDownloadReporter +import org.pnfolder.pnlibrary.core.downloads.dependencies.DependencyDownloadRequestFactory +import org.pnfolder.pnlibrary.core.downloads.dependencies.DownloadedDependencyStore +import org.pnfolder.pnlibrary.core.downloads.dependencies.MissingDependencies +import org.pnfolder.pnlibrary.core.downloads.dependencies.MissingDependency +import org.pnfolder.pnlibrary.core.downloads.dependencies.MissingGroup +import org.pnfolder.pnlibrary.core.downloads.settings.DownloadConfiguration import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import org.pnfolder.pnlibrary.spi.platform.PlatformLogging import org.pnfolder.pnlibrary.spi.platform.PlatformOwnerMetadata import org.pnfolder.pnlibrary.spi.platform.PlatformPluginInventory import org.pnfolder.pnlibrary.spi.platform.PlatformReadiness +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths import java.nio.file.Files import java.nio.file.Path import java.time.Duration +import java.util.concurrent.CompletionStage import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.ExecutorService import java.util.concurrent.Executors @@ -27,8 +41,9 @@ internal class DirectDownloads( private val inventory: PlatformPluginInventory, private val readiness: PlatformReadiness, private val logging: PlatformLogging, - private val libraryData: Path, - private val configuration: DownloadConfiguration, + paths: LibraryPaths, + private val configuration: () -> DownloadConfiguration, + private val saveAutomatic: (Boolean) -> Unit = {}, private val http: TrustedHttpClient = TrustedHttpClient( Duration.ofSeconds(8), Duration.ofSeconds(30), ), @@ -39,14 +54,17 @@ internal class DirectDownloads( } private val registrations = CopyOnWriteArrayList() private val pluginJarVerifier = PluginJarVerifier(identity) - private val filePublisher = AtomicDownloadPublisher(libraryData) + private val filePublisher = AtomicDownloadPublisher(paths.data) + private val missing = MissingDependencies() private val artifactPreparer = DownloadArtifactPreparer( - identity.type, libraryData, configuration, http, MAX_BYTES, + identity.type, paths.data, configuration, http, MAX_BYTES, + ) + private val dependencyStore = DownloadedDependencyStore(paths.data) + private val dependencyReporter = DependencyDownloadReporter( + logging, ownership, if (identity.type == PlatformType.VELOCITY || identity.type == PlatformType.BUNGEECORD) "pnproxy" else "pn", ) - private val dependencyStore = DownloadedDependencyStore(libraryData) - private val dependencyReporter = DependencyDownloadReporter(logging, ownership) private val dependencyRequestFactory = DependencyDownloadRequestFactory( - requireNotNull(libraryData.parent) { "Library data directory must have a parent plugins directory" }, + paths.serverUpdateFolder, identity.type, { identity.minecraftVersion }, ) fun register(owner: Any, request: FileDownloads): DownloadRegistration = register(owner, request, null) @@ -68,12 +86,15 @@ internal class DirectDownloads( blocked = { reason -> logging.log(owner, LogLevel.WARNING, reason) }, dependenciesStaged = { declarations -> runCatchingNonFatal { dependencyReporter.staged(owner, declarations) } + .onFailure { logging.log(owner, LogLevel.ERROR, "Could not report the staged dependencies", it) } }, failed = { declarations, error -> val level = if (declarations.any(FileDownload::required)) LogLevel.ERROR else LogLevel.WARNING runCatchingNonFatal { dependencyReporter.failure(owner, error, level) } + .onFailure { logging.log(owner, LogLevel.ERROR, "Could not report the failed dependency download", it) } }, remove = registrations::remove, + automaticAllowed = ::automatic, ).also { registration -> registrations += registration registration.startAutomatic() @@ -86,10 +107,50 @@ internal class DirectDownloads( fun registerDependencies(owner: Any, dependencies: List): DownloadRegistration? { val installed = installedPlugins(owner) readiness.whenServerReady(Runnable { confirmDownloadedDependencies(owner, installedPlugins(owner)) }) - val download = dependencyRequestFactory.create(dependencies, installed) ?: return null - return register(owner, download.request) { declaration, path -> - download.requirements[declaration.key]?.let { pluginJarVerifier.verify(path, it) } + val lacking = dependencyRequestFactory.missing(dependencies, installed) + val download = dependencyRequestFactory.create(dependencies, installed) + val registration = download?.let { request -> + register(owner, request.request) { declaration, path -> + request.requirements[declaration.key]?.let { pluginJarVerifier.verify(path, it) } + } } + if (lacking.isNotEmpty()) announceMissing(owner, lacking, registration) + return registration + } + + private fun announceMissing(owner: Any, lacking: List, registration: DownloadRegistration?) { + val items = lacking.map { + val file = dependencyRequestFactory.fileFor(it) + MissingDependency( + it.plugin, it.minimumVersion.toString(), it.downloadPage, file?.let { a -> listOf(a.uri) + a.mirrors }.orEmpty(), + title = it.title, description = it.description, required = it.required, checked = file?.sha256 != null, + variant = file?.label.takeIf { _ -> it.artifacts.size > 1 }, + noFileForServer = file == null && it.artifacts.isNotEmpty(), + ) + } + val group = missing.add(ownerName(owner), items, registration) + runCatchingNonFatal { dependencyReporter.missing(owner, group, automatic() && registration != null) } + .onFailure { logging.log(owner, LogLevel.ERROR, "Could not report the missing dependencies", it) } + } + + private fun ownerName(owner: Any): String = ownership.ownerDetails(owner)?.get("name") ?: PnLibraryIdentity.NAME + + /** Whether downloads that a plugin starts itself are allowed now. */ + fun automatic(): Boolean = configuration().automatic + + /** Saves the choice as the setting `downloads.automatic`. */ + fun setAutomatic(value: Boolean) = saveAutomatic(value) + + /** Dependencies still missing, with the code that installs each group. */ + internal fun missingGroups(): List = missing.pending() + + /** + * Installs the group with this [code] now, whatever the automatic switch says: typing the code is the approval, + *. + */ + internal fun installGroup(code: String): CompletionStage>? { + val group = missing.find(code) ?: return null + return group.install() } internal fun install(request: FileDownloads, declaration: FileDownload) { diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadArtifactPreparer.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/DownloadArtifactPreparer.kt similarity index 80% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadArtifactPreparer.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/DownloadArtifactPreparer.kt index 9973057f8..74a3fab97 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadArtifactPreparer.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/DownloadArtifactPreparer.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.fetch import org.pnfolder.pnlibrary.api.downloads.DownloadDestination import org.pnfolder.pnlibrary.api.downloads.FileDownload @@ -6,8 +6,9 @@ import org.pnfolder.pnlibrary.api.downloads.FileDownloads import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.common.io.Digests import org.pnfolder.pnlibrary.common.jvm.JavaRuntime -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup -import org.pnfolder.pnlibrary.core.updates.engine.TrustedHttpClient +import org.pnfolder.pnlibrary.core.downloads.settings.DownloadConfiguration +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient import java.nio.file.Files import java.nio.file.Path import java.util.UUID @@ -16,10 +17,12 @@ import java.util.UUID internal class DownloadArtifactPreparer( private val platform: PlatformType, private val libraryData: Path, - private val configuration: DownloadConfiguration, - private val http: TrustedHttpClient, + private val configuration: () -> DownloadConfiguration, + http: TrustedHttpClient, private val maximumBytes: Long = 512L * 1024L * 1024L, ) { + private val fetcher = SourceFetcher(http) + fun prepare( request: FileDownloads, declaration: FileDownload, @@ -30,8 +33,9 @@ internal class DownloadArtifactPreparer( } val target = target(request, declaration) - val limit = declaration.source.size?.coerceAtMost(maximumBytes)?.toInt() ?: maximumBytes.toInt() - val bytes = http.get(declaration.source.uri, limit) + val allowed = declaration.source.maxBytes ?: maximumBytes + val limit = declaration.source.size?.coerceAtMost(allowed)?.toInt() ?: allowed.toInt() + val bytes = fetcher.fetch(declaration.source, limit) verifyIntegrity(declaration, bytes) val staging = libraryData.resolve("downloads/staging").resolve("${UUID.randomUUID()}-${target.fileName}") @@ -56,7 +60,7 @@ internal class DownloadArtifactPreparer( } private fun target(request: FileDownloads, declaration: FileDownload): Path { - require(declaration.destination in configuration.destinations) { + require(declaration.destination in configuration().destinations) { "назначение ${declaration.destination} запрещено конфигурацией" } val root = when (declaration.destination) { diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/PluginJarVerifier.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/PluginJarVerifier.kt similarity index 92% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/PluginJarVerifier.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/PluginJarVerifier.kt index 2a656c2b8..21cb1158a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/PluginJarVerifier.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/PluginJarVerifier.kt @@ -1,6 +1,6 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.fetch -import org.pnfolder.pnlibrary.api.dependencies.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import org.yaml.snakeyaml.LoaderOptions @@ -9,7 +9,6 @@ import org.yaml.snakeyaml.constructor.SafeConstructor import java.nio.file.Path import java.util.jar.JarFile -/** Verifies that a downloaded plugin JAR declares the expected identity and version. */ internal class PluginJarVerifier( private val platform: PlatformIdentity, ) { diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/SourceFetcher.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/SourceFetcher.kt new file mode 100644 index 000000000..c34bb8295 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/SourceFetcher.kt @@ -0,0 +1,34 @@ +package org.pnfolder.pnlibrary.core.downloads.fetch + +import org.pnfolder.pnlibrary.api.downloads.DirectDownloadSource +import org.pnfolder.pnlibrary.common.io.Digests +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient + +/** + * Gets the bytes of one declared file from its address, then from its mirrors in order. + * + * With a SHA-256 declared, the first address whose file matches wins. Without one, the first address that answers wins: + * the file is taken as it came, and nothing is compared with other addresses or remembered. + */ +internal class SourceFetcher(private val http: TrustedHttpClient) { + fun fetch(source: DirectDownloadSource, limit: Int): ByteArray { + val addresses = listOf(source.uri) + source.mirrors + val expected = source.sha256 + val failures = mutableListOf() + var answered = false + for (address in addresses) { + val bytes = try { + http.get(address, limit) + } catch (error: Exception) { + if (addresses.size == 1) throw error + failures += "$address: ${error.message}" + continue + } + if (expected == null || Digests.sha256(bytes).equals(expected, ignoreCase = true)) return bytes + answered = true + failures += "$address: SHA-256 файла не совпадает" + } + val message = "ни один источник не дал нужный файл (${failures.joinToString("; ")})" + throw if (answered) IllegalArgumentException(message) else IllegalStateException(message) + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/settings/DownloadConfiguration.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/settings/DownloadConfiguration.kt new file mode 100644 index 000000000..72ab7db70 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/downloads/settings/DownloadConfiguration.kt @@ -0,0 +1,23 @@ +package org.pnfolder.pnlibrary.core.downloads.settings + +import org.pnfolder.pnlibrary.api.downloads.DownloadDestination +import org.pnfolder.pnlibrary.core.settings.LibrarySettings + +/** Administrator policy for downloads: whether they run, start automatically, and which destinations are allowed. */ +internal data class DownloadConfiguration( + val enabled: Boolean = true, + val automatic: Boolean = true, + val destinations: Set = setOf( + DownloadDestination.DATA_FOLDER, DownloadDestination.CACHE, + ), +) + +/** The download policy in these settings (the `downloads.*` keys). */ +internal fun LibrarySettings.downloads(): DownloadConfiguration = DownloadConfiguration( + enabled = downloadsEnabled, + automatic = downloadsAutomatic, + destinations = buildSet { + if (downloadsToDataFolder) add(DownloadDestination.DATA_FOLDER) + if (downloadsToCache) add(DownloadDestination.CACHE) + }, +) diff --git a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventDispatcher.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventDispatcher.kt similarity index 83% rename from modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventDispatcher.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventDispatcher.kt index c3d882475..d9e4aabd7 100644 --- a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventDispatcher.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventDispatcher.kt @@ -1,24 +1,29 @@ package org.pnfolder.pnlibrary.core.events -import org.pnfolder.pnlibrary.api.events.DispatchMode import org.pnfolder.pnlibrary.api.events.Event -import org.pnfolder.pnlibrary.api.events.EventDay -import org.pnfolder.pnlibrary.api.events.EventHour -import org.pnfolder.pnlibrary.api.events.EventInfo -import org.pnfolder.pnlibrary.api.events.EventInspector -import org.pnfolder.pnlibrary.api.events.EventListenerRegistration -import org.pnfolder.pnlibrary.api.events.EventScope -import org.pnfolder.pnlibrary.api.events.EventService -import org.pnfolder.pnlibrary.api.events.EventSubscription -import org.pnfolder.pnlibrary.api.events.EventTrace import org.pnfolder.pnlibrary.api.events.InternalEventApi -import org.pnfolder.pnlibrary.api.events.Listener -import org.pnfolder.pnlibrary.api.events.ListenerInfo +import org.pnfolder.pnlibrary.api.events.bus.DispatchMode +import org.pnfolder.pnlibrary.api.events.bus.EventScope +import org.pnfolder.pnlibrary.api.events.bus.EventService +import org.pnfolder.pnlibrary.api.events.inspect.EventInfo +import org.pnfolder.pnlibrary.api.events.inspect.EventInspector +import org.pnfolder.pnlibrary.api.events.inspect.ListenerInfo +import org.pnfolder.pnlibrary.api.events.inspect.history.EventDay +import org.pnfolder.pnlibrary.api.events.inspect.history.EventHour +import org.pnfolder.pnlibrary.api.events.inspect.trace.EventTrace +import org.pnfolder.pnlibrary.api.events.listener.EventListenerRegistration +import org.pnfolder.pnlibrary.api.events.listener.EventSubscription +import org.pnfolder.pnlibrary.api.events.listener.Listener import org.pnfolder.pnlibrary.api.plugin.ModuleId import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.common.concurrent.ManagedWorker import org.pnfolder.pnlibrary.common.lang.Failures import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.core.events.inspect.EventCounters +import org.pnfolder.pnlibrary.core.events.inspect.EventHandlerInspector +import org.pnfolder.pnlibrary.core.events.inspect.history.EventHistory +import org.pnfolder.pnlibrary.core.events.inspect.trace.EventTracer +import org.pnfolder.pnlibrary.core.events.registration.ListenerRegistration import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage import java.util.concurrent.CopyOnWriteArrayList @@ -29,7 +34,6 @@ import java.util.concurrent.atomic.LongAdder import java.util.function.Consumer import java.util.function.Supplier -/** Thread-safe, mode-aware implementation of the platform-independent event bus. */ class EventDispatcher( private val history: EventHistory? = null, private val errorLogger: (PluginId, String, Throwable) -> Unit, @@ -127,11 +131,10 @@ class EventDispatcher( if (tracedAs != null && steps != null) tracer.record(tracedAs, event, steps, mode) } - /** A failing listener is logged and skipped; [steps] is null unless the event is traced. */ private fun deliver(subscription: Subscription, event: Event, steps: MutableList?) { val before = if (steps != null) tracer.resultText(event) else null if (subscription.ignoreDenied && !event.isAllowed) { - steps?.add(EventTrace.Step(subscription.scope.plugin, subscription.scope.module, subscription.priority, true, false, 0, before, before)) + steps?.add(stepOf(subscription, skipped = true, failed = false, nanos = 0, before = before, after = before)) return } val started = System.nanoTime() @@ -144,24 +147,28 @@ class EventDispatcher( subscription.failures.increment() // A broken listener is logged and skipped; a dying JVM (out of memory, stack overflow) is not ours to hide. Failures.rethrowIfFatal(error) - // A logger that throws must not cost the remaining listeners their turn. - runCatchingNonFatal { - errorLogger( - subscription.scope.plugin, - "[pnLibrary/events] Listener failed for ${event.javaClass.name}", - error, - ) - } + logFailure(subscription, event, error) } finally { val elapsed = System.nanoTime() - started subscription.totalNanos.add(elapsed) subscription.maxNanos.accumulateAndGet(elapsed, ::maxOf) - steps?.add( - EventTrace.Step( - subscription.scope.plugin, subscription.scope.module, subscription.priority, false, failed, - elapsed, before, tracer.resultText(event), - ), - ) + steps?.add(stepOf(subscription, skipped = false, failed = failed, nanos = elapsed, before = before, after = tracer.resultText(event))) + } + } + + private fun stepOf( + subscription: Subscription, + skipped: Boolean, + failed: Boolean, + nanos: Long, + before: String?, + after: String?, + ) = EventTrace.Step(subscription.scope.plugin, subscription.scope.module, subscription.priority, skipped, failed, nanos, before, after) + + // A broken logger must not cost the remaining listeners their turn. + private fun logFailure(subscription: Subscription, event: Event, error: Throwable) { + runCatchingNonFatal { + errorLogger(subscription.scope.plugin, "[pnLibrary/events] Listener failed for ${event.javaClass.name}", error) } } @@ -223,6 +230,7 @@ class EventDispatcher( synchronized(scopes) { if (scopes[pluginId] === this) scopes.remove(pluginId) } } + // Does not remove the scope from scopes map — the caller (close/unregisterAll) does that. fun closeInternal() { if (!scopeClosed.compareAndSet(false, true)) return ownedSubscriptions.forEach { it.close() } diff --git a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/HandlerCache.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/HandlerCache.kt similarity index 72% rename from modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/HandlerCache.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/HandlerCache.kt index 57624e63b..f1c957619 100644 --- a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/HandlerCache.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/HandlerCache.kt @@ -3,12 +3,8 @@ package org.pnfolder.pnlibrary.core.events import java.util.WeakHashMap import java.util.concurrent.atomic.AtomicLong -/** - * Sorted listeners per event class. Adding or closing a subscription for type T drops only the cached - * lists of classes that T matches, so churn on one event never slows the others. A list built while a - * change was happening is returned for that call but not cached. Weak keys let an unloaded plugin's - * event classes be collected when nothing listens to them. - */ +// Invalidating T drops only entries for classes T matches, so churn on one event never slows others. +// Lists built during a change are returned but not cached. Weak keys allow plugin class GC. class HandlerCache( private val all: () -> Sequence, private val matches: (S, Class<*>) -> Boolean, @@ -17,12 +13,11 @@ class HandlerCache( private val generation = AtomicLong() private val cache = WeakHashMap, List>() - /** The most recently used lookup, readable without a lock: hot events repeat the same class. */ + // Hot events repeat the same class — the last-used entry is a lock-free fast path. private class Last(val type: Class<*>, val handlers: List) @Volatile private var last: Last? = null - /** Forgets cached lists affected by a subscription to [changed]; `null` forgets everything. */ fun invalidate(changed: Class<*>?) { synchronized(cache) { generation.incrementAndGet() diff --git a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventCounters.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/inspect/EventCounters.kt similarity index 87% rename from modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventCounters.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/inspect/EventCounters.kt index 95754e361..2f60f7632 100644 --- a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventCounters.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/inspect/EventCounters.kt @@ -1,7 +1,8 @@ -package org.pnfolder.pnlibrary.core.events +package org.pnfolder.pnlibrary.core.events.inspect import org.pnfolder.pnlibrary.api.events.Event -import org.pnfolder.pnlibrary.api.events.EventInfo +import org.pnfolder.pnlibrary.api.events.inspect.EventInfo +import org.pnfolder.pnlibrary.core.events.inspect.history.EventHistory import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.LongAdder @@ -17,6 +18,7 @@ class EventCounters(private val history: EventHistory?) { private val counters = ConcurrentHashMap() + /** Counts one call of [event] and passes it to the history. */ fun count(event: Event) { val name = event.javaClass.name val counter = counters[name] ?: counters.computeIfAbsent(name) { Counter(event.javaClass) } diff --git a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventHandlerInspector.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/inspect/EventHandlerInspector.kt similarity index 95% rename from modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventHandlerInspector.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/inspect/EventHandlerInspector.kt index fa409afd7..3da6f76a9 100644 --- a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventHandlerInspector.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/inspect/EventHandlerInspector.kt @@ -1,8 +1,8 @@ -package org.pnfolder.pnlibrary.core.events +package org.pnfolder.pnlibrary.core.events.inspect import org.pnfolder.pnlibrary.api.events.Event -import org.pnfolder.pnlibrary.api.events.EventHandler -import org.pnfolder.pnlibrary.api.events.Listener +import org.pnfolder.pnlibrary.api.events.listener.EventHandler +import org.pnfolder.pnlibrary.api.events.listener.Listener import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.lang.reflect.Modifier diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/inspect/history/EventHistory.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/inspect/history/EventHistory.kt new file mode 100644 index 000000000..93bbdc0ea --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/inspect/history/EventHistory.kt @@ -0,0 +1,225 @@ +package org.pnfolder.pnlibrary.core.events.inspect.history + +import org.pnfolder.pnlibrary.api.events.inspect.history.EventDay +import org.pnfolder.pnlibrary.api.events.inspect.history.EventHour +import org.pnfolder.pnlibrary.common.concurrent.FailureThrottle +import org.pnfolder.pnlibrary.common.concurrent.ManagedWorker +import org.pnfolder.pnlibrary.common.io.AtomicFiles +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import java.nio.file.Files +import java.nio.file.Path +import java.time.Instant +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.temporal.ChronoUnit +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ConcurrentSkipListMap +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.atomic.LongAdder + +/** + * Per-day call counters of every event type, kept for [retentionDays] and stored in a small text file so the + * history survives restarts. + * + * Counting takes no lock: the current hour and day are looked up once a minute, and each call is a map read and + * two adder increments. Writing happens on a background worker at most once per [flushEveryMillis] + * and once more on [close], so a crash loses at most a minute of counts. A retention of `0` keeps nothing. + * The file starts with a `# pnLibrary event history v1` line and then holds one `dateeventcallsdenied` + * line per day and event; lines that do not fit that shape are ignored. Hourly counters of the last 30 days at most + * are stored the same way, with `yyyy-MM-ddTHH:00` in the first column. + */ +class EventHistory( + private val file: Path?, + private val retentionDays: Int, + private val zone: () -> ZoneId = { ZoneId.systemDefault() }, + private val clock: () -> Long = System::currentTimeMillis, + private val flushEveryMillis: Long = 60_000, + private val onFailure: (Throwable) -> Unit = {}, + /** The wall-clock time that decides which hour and day a call belongs to. */ + private val now: () -> Long = System::currentTimeMillis, +) : AutoCloseable { + private class Counts { + val calls = LongAdder() + val denied = LongAdder() + + fun add(amount: Long, deniedAmount: Long) { + calls.add(amount) + denied.add(deniedAmount) + } + } + + /** The hour and day that calls belong to from [validFrom] until [validUntil]; replaced when the minute changes. */ + private class Bucket( + val validFrom: Long, + val validUntil: Long, + val hourCounts: ConcurrentHashMap, + val dayCounts: ConcurrentHashMap, + ) + + private val days = ConcurrentSkipListMap>() + private val hours = ConcurrentSkipListMap>() + private val dirty = AtomicBoolean(false) + private val lastFlush = AtomicLong(clock()) + private val failureThrottle = FailureThrottle() + private val worker = if (file != null && retentionDays > 0) ManagedWorker("pnLibrary-event-history") else null + + @Volatile + private var bucket: Bucket? = null + + /** How many days are kept; `0` means the history is off. */ + val retention: Int get() = retentionDays + + init { + if (file != null && retentionDays > 0) runCatchingNonFatal { load(file) }.onFailure(::report) + } + + /** Counts one call of [eventType] for today and this hour, and writes the file later if enough time passed. */ + fun record(eventType: String, denied: Boolean) { + if (retentionDays <= 0) return + val current = currentBucket() + val deniedAmount = if (denied) 1L else 0L + countsOf(current.dayCounts, eventType).add(1, deniedAmount) + countsOf(current.hourCounts, eventType).add(1, deniedAmount) + if (!dirty.get()) dirty.set(true) + val tick = clock() + val previous = lastFlush.get() + if (tick - previous >= flushEveryMillis && lastFlush.compareAndSet(previous, tick)) { + worker?.let { runCatchingNonFatal { it.submit { flush() } } } + } + } + + private fun countsOf(map: ConcurrentHashMap, eventType: String): Counts = + map[eventType] ?: map.computeIfAbsent(eventType) { Counts() } + + private fun currentBucket(): Bucket { + val millis = now() + bucket?.let { if (millis >= it.validFrom && millis < it.validUntil) return it } + return startBucket(millis) + } + + // Offsets of time zones are whole minutes, so a bucket that ends on a minute boundary never straddles an hour. + private fun startBucket(millis: Long): Bucket { + val local = localTime(millis) + val minuteStart = millis - Math.floorMod(millis, MINUTE_MILLIS) + val created = Bucket( + minuteStart, + minuteStart + MINUTE_MILLIS, + hours.computeIfAbsent(local.truncatedTo(ChronoUnit.HOURS)) { ConcurrentHashMap() }, + days.computeIfAbsent(local.toLocalDate()) { ConcurrentHashMap() }, + ) + bucket = created + prune(local) + return created + } + + private fun localTime(millis: Long): LocalDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), zone()) + + /** The recorded days, newest first and then by event name; only [eventType] when given. */ + fun entries(eventType: String? = null): List = + days.descendingMap().flatMap { (date, events) -> + events.entries.sortedBy { it.key }.filter { eventType == null || it.key == eventType } + .map { EventDay(date, it.key, it.value.calls.sum(), it.value.denied.sum()) } + } + + /** The recorded hours, newest first and then by event name; only [eventType] when given. */ + fun hourly(eventType: String? = null): List = + hours.descendingMap().flatMap { (hour, events) -> + events.entries.sortedBy { it.key }.filter { eventType == null || it.key == eventType } + .map { EventHour(hour, it.key, it.value.calls.sum(), it.value.denied.sum()) } + } + + /** Writes days and hours to `event-history.csv` or `event-history.json` beside the history file; `null` if not possible. */ + fun export(json: Boolean): Path? { + val source = file ?: return null + if (retentionDays <= 0) return null + val days = entries() + val hours = hourly() + val text = if (json) { + fun quote(value: String) = "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + buildString { + append("{\"days\":[") + append(days.joinToString(",") { """{"date":"${it.date}","event":${quote(it.eventType)},"calls":${it.calls},"denied":${it.denied}}""" }) + append("],\"hours\":[") + append(hours.joinToString(",") { """{"hour":"${it.hour}","event":${quote(it.eventType)},"calls":${it.calls},"denied":${it.denied}}""" }) + append("]}").append(NL) + } + } else { + fun cell(value: String) = if (value.any { it == ',' || it == '"' }) "\"" + value.replace("\"", "\"\"") + "\"" else value + buildString { + append("period,time,event,calls,denied").append(NL) + days.forEach { append("day,${it.date},${cell(it.eventType)},${it.calls},${it.denied}").append(NL) } + hours.forEach { append("hour,${it.hour},${cell(it.eventType)},${it.calls},${it.denied}").append(NL) } + } + } + val target = source.resolveSibling(if (json) "event-history.json" else "event-history.csv") + return runCatchingNonFatal { AtomicFiles.write(target, text.toByteArray(Charsets.UTF_8)); target }.getOrNull() + } + + private fun prune(local: LocalDateTime) { + val keepHours = minOf(retentionDays, MAX_HOURLY_DAYS) * 24L + hours.headMap(local.truncatedTo(ChronoUnit.HOURS).minusHours(keepHours - 1)).clear() + days.headMap(local.toLocalDate().minusDays(retentionDays.toLong() - 1)).clear() + } + + private fun load(source: Path) { + if (!Files.isRegularFile(source)) return + Files.readAllLines(source).forEach { line -> + val parts = line.split('\t') + if (parts.size != 4) return@forEach + val calls = parts[2].toLongOrNull() ?: return@forEach + val denied = parts[3].toLongOrNull() ?: return@forEach + val events = if ('T' in parts[0]) { + val hour = runCatchingNonFatal { LocalDateTime.parse(parts[0]) }.getOrNull() ?: return@forEach + hours.computeIfAbsent(hour) { ConcurrentHashMap() } + } else { + val date = runCatchingNonFatal { LocalDate.parse(parts[0]) }.getOrNull() ?: return@forEach + days.computeIfAbsent(date) { ConcurrentHashMap() } + } + countsOf(events, parts[1]).add(calls, denied) + } + prune(localTime(now())) + } + + /** Writes the file now when something changed; the write goes to a temporary file first. */ + fun flush() { + val target = file ?: return + if (retentionDays <= 0 || !dirty.getAndSet(false)) return + prune(localTime(now())) + val text = buildString { + append(HEADER).append(NL) + days.forEach { (date, events) -> appendLines(date, events) } + hours.forEach { (hour, events) -> appendLines(hour, events) } + } + runCatchingNonFatal { + Files.createDirectories(target.parent) + AtomicFiles.write(target, text.toByteArray(Charsets.UTF_8)) + }.onFailure { + dirty.set(true) + report(it) + } + } + + private fun StringBuilder.appendLines(period: Any, events: Map) { + events.forEach { (name, counts) -> append("$period\t$name\t${counts.calls.sum()}\t${counts.denied.sum()}\n") } + } + + /** A history that cannot be read or written is lost count by count, so the first failure of each kind is passed on. */ + private fun report(error: Throwable) { + if (failureThrottle.shouldReport(error.javaClass.name)) onFailure(error) + } + + override fun close() { + worker?.close() + flush() + } + + private companion object { + /** The first line of the history file, which names its format version. */ + const val HEADER = "# pnLibrary event history v1" + const val MAX_HOURLY_DAYS = 30 + const val NL = '\n' + const val MINUTE_MILLIS = 60_000L + } +} diff --git a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventTracer.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/inspect/trace/EventTracer.kt similarity index 76% rename from modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventTracer.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/inspect/trace/EventTracer.kt index f8a0fad90..4517a3177 100644 --- a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventTracer.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/inspect/trace/EventTracer.kt @@ -1,9 +1,9 @@ -package org.pnfolder.pnlibrary.core.events +package org.pnfolder.pnlibrary.core.events.inspect.trace -import org.pnfolder.pnlibrary.api.events.DispatchMode import org.pnfolder.pnlibrary.api.events.Event -import org.pnfolder.pnlibrary.api.events.EventTrace import org.pnfolder.pnlibrary.api.events.ResultedEvent +import org.pnfolder.pnlibrary.api.events.bus.DispatchMode +import org.pnfolder.pnlibrary.api.events.inspect.trace.EventTrace import java.time.Instant import java.util.ArrayDeque @@ -15,20 +15,24 @@ class EventTracer { /** Calls per traced type, so a type with a small capacity never pushes out the calls of another. */ private val recorded = HashMap, ArrayDeque>() + /** Starts recording calls of [eventType] and its subtypes, keeping the latest [capacity] of them. */ fun enable(eventType: Class, capacity: Int) { require(capacity in 1..1_000) { "Trace capacity must be between 1 and 1000" } synchronized(recorded) { traced = traced + (eventType to capacity) } } + /** Stops recording [eventType]; calls already recorded stay until [clear]. */ fun disable(eventType: Class) { synchronized(recorded) { traced = traced - eventType } } + /** The names of the traced event types, sorted. */ fun tracedNames(): List = traced.keys.map { it.name }.sorted() /** Every recorded call, oldest first. */ fun traces(): List = synchronized(recorded) { recorded.values.flatten() }.sortedBy { it.at } + /** Forgets every recorded call; tracing stays on. */ fun clear() { synchronized(recorded) { recorded.clear() } } @@ -40,8 +44,10 @@ class EventTracer { return current.keys.firstOrNull { it.isAssignableFrom(type) } } + /** The result of a resulted [event] as text, or null for a plain event. */ fun resultText(event: Event): String? = (event as? ResultedEvent<*>)?.result?.toString() + /** Stores one call of [event] under [tracedAs], dropping the oldest calls above the capacity. */ fun record(tracedAs: Class, event: Event, steps: List, mode: DispatchMode) { val trace = EventTrace(event.eventName, event.isAllowed, resultText(event), steps, mode, Thread.currentThread().name, Instant.now()) synchronized(recorded) { diff --git a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/PlayerLifecyclePublisher.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/player/PlayerLifecyclePublisher.kt similarity index 93% rename from modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/PlayerLifecyclePublisher.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/player/PlayerLifecyclePublisher.kt index a733b832b..c6bf606d3 100644 --- a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/PlayerLifecyclePublisher.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/player/PlayerLifecyclePublisher.kt @@ -1,5 +1,6 @@ -package org.pnfolder.pnlibrary.core.events +package org.pnfolder.pnlibrary.core.events.player +import org.pnfolder.pnlibrary.api.events.Event import org.pnfolder.pnlibrary.api.events.player.PlayerJoinedEvent import org.pnfolder.pnlibrary.api.events.player.PlayerLeftEvent import org.pnfolder.pnlibrary.api.runtime.PnLibrary diff --git a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/ListenerRegistration.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/registration/ListenerRegistration.kt similarity index 72% rename from modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/ListenerRegistration.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/registration/ListenerRegistration.kt index 7314cec08..e5df1fc94 100644 --- a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/ListenerRegistration.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/events/registration/ListenerRegistration.kt @@ -1,8 +1,8 @@ -package org.pnfolder.pnlibrary.core.events +package org.pnfolder.pnlibrary.core.events.registration -import org.pnfolder.pnlibrary.api.events.EventListenerRegistration -import org.pnfolder.pnlibrary.api.events.EventSubscription -import org.pnfolder.pnlibrary.api.events.Listener +import org.pnfolder.pnlibrary.api.events.listener.EventListenerRegistration +import org.pnfolder.pnlibrary.api.events.listener.EventSubscription +import org.pnfolder.pnlibrary.api.events.listener.Listener import java.util.concurrent.atomic.AtomicBoolean /** All the subscriptions made for the handlers of one listener object; closing it closes every one. */ diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/cleanup/ResourceCleanup.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/exceptions/ResourceCleanup.kt similarity index 54% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/cleanup/ResourceCleanup.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/exceptions/ResourceCleanup.kt index f03a8f2bf..1daa4ef94 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/cleanup/ResourceCleanup.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/exceptions/ResourceCleanup.kt @@ -1,13 +1,7 @@ -package org.pnfolder.pnlibrary.core.cleanup +package org.pnfolder.pnlibrary.core.exceptions -/** Executes lifecycle cleanup steps without abandoning later resources after a failure. */ -internal object ResourceCleanup { - /** - * Runs every [steps] action and attaches failures to [primary]. - * - * This is intended for rollback paths where the exception that caused the - * rollback must remain the exception observed by the caller. - */ +object ResourceCleanup { + // Rollback helper: later failures suppress into the primary so the caller sees the original cause. fun suppressInto(primary: Throwable, vararg steps: () -> Unit) { steps.forEach { step -> try { @@ -18,10 +12,6 @@ internal object ResourceCleanup { } } - /** - * Runs every [steps] action and throws the first failure after completion. - * Later failures are attached to the first one as suppressed exceptions. - */ fun closeAll(vararg steps: () -> Unit) { var failure: Throwable? = null steps.forEach { step -> diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/exceptions/Throwables.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/exceptions/Throwables.kt new file mode 100644 index 000000000..3b4269577 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/exceptions/Throwables.kt @@ -0,0 +1,7 @@ +package org.pnfolder.pnlibrary.core.exceptions + +/** The innermost cause of this failure, or the failure itself when it has none. */ +internal fun Throwable.rootCause(): Throwable = generateSequence(this) { it.cause }.last() + +/** The message of [rootCause], or its class name when it has no message. */ +internal fun Throwable.rootMessage(): String = rootCause().let { it.message ?: it.javaClass.simpleName } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/expansions/ExpansionRegistry.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/expansions/ExpansionRegistry.kt index 7af735ca7..70872b411 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/expansions/ExpansionRegistry.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/expansions/ExpansionRegistry.kt @@ -2,7 +2,7 @@ package org.pnfolder.pnlibrary.core.expansions import org.pnfolder.pnlibrary.api.expansions.Expansion import org.pnfolder.pnlibrary.api.expansions.ExpansionManager -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup /** Thread-safe expansion registry; [onFailure] receives every exception an expansion throws while starting or stopping. */ internal class ExpansionRegistry( diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalGroups.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalGroups.kt similarity index 100% rename from modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalGroups.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalGroups.kt diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalRecord.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalRecord.kt similarity index 80% rename from modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalRecord.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalRecord.kt index aebea6db3..c3ecd297c 100644 --- a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalRecord.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalRecord.kt @@ -36,11 +36,17 @@ data class JournalRecord( ) { /** Short id shared by repeats of the same event: same level, source, first message line and exception. */ val fingerprint: String - get() { - val key = listOf(level.name, source, message.lineSequence().first().take(200), details["exception"].orEmpty()) - .joinToString("\u0000") - return "%08x".format(key.hashCode()) - } + get() = cachedFingerprint ?: computeFingerprint().also { cachedFingerprint = it } + + // Benign race: a String is immutable, so two threads that compute it at once store equal values. + private var cachedFingerprint: String? = null + + private fun computeFingerprint(): String { + val key = listOf(level.name, source, message.lineSequence().first().take(200), details["exception"].orEmpty()) + .joinToString("\u0000") + val hex = Integer.toHexString(key.hashCode()) + return if (hex.length >= 8) hex else "0".repeat(8 - hex.length) + hex + } companion object { /** Type of the hourly statistics records; they are not events, so reads without a type skip them. */ diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalBlockCodec.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalBlockCodec.kt similarity index 81% rename from modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalBlockCodec.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalBlockCodec.kt index 77a44a966..7c5d14c65 100644 --- a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalBlockCodec.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalBlockCodec.kt @@ -1,6 +1,8 @@ -package org.pnfolder.pnlibrary.core.journal +package org.pnfolder.pnlibrary.core.journal.store import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.core.journal.JournalLevel +import org.pnfolder.pnlibrary.core.journal.JournalRecord import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.DataInputStream @@ -11,18 +13,12 @@ import java.util.zip.CRC32 import java.util.zip.GZIPInputStream import java.util.zip.GZIPOutputStream -/** - * Binary block format of a journal file. - * - * A file is a sequence of blocks with no file header, so any prefix of a file stays readable: - * ``` - * block := u32 payloadLength | u32 crc32(payload) | payload - * payload := gzip( u32 recordCount, record* ) - * record := i64 timeMillis | utf level | utf source | utf type | utf message | u16 detailCount | (utf key | utf value)* - * ``` - * Each block is independently compressed and checksummed. A damaged block is skipped by its length, - * and a truncated tail (power loss during a write) is ignored, so earlier blocks always survive. - */ +// A file is a sequence of blocks with no file header, so any prefix stays readable: +// block := u32 payloadLength | u32 crc32(payload) | payload +// payload := gzip( u32 recordCount, record* ) +// record := i64 timeMillis | utf level | utf source | utf type | utf message | u16 detailCount | (utf key | utf value)* +// A damaged block is skipped by its length; a truncated tail (power loss mid-write) is ignored, +// so earlier blocks always survive. object JournalBlockCodec { private const val HEADER_BYTES = 8 private const val MAX_PAYLOAD_BYTES = 16 * 1024 * 1024 @@ -47,17 +43,14 @@ object JournalBlockCodec { return block.toByteArray() } - /** - * Decodes every intact block in [bytes]. Blocks with a bad checksum or unreadable payload are skipped; - * decoding stops at the first incomplete block, which is what an interrupted write leaves behind. - */ + // Stops at the first incomplete block, which is what an interrupted write leaves behind. fun decodeAll(bytes: ByteArray): List { val result = mutableListOf() visit(ByteArrayInputStream(bytes), bytes.size.toLong()) { result += it } return result } - /** Streams intact blocks under a byte budget, retaining one compressed block at a time. */ + // Retains one compressed block at a time; bad-checksum blocks are skipped. fun visit(stream: InputStream, maximumBytes: Long, record: (JournalRecord) -> Unit) { val input = DataInputStream(stream) var remaining = maximumBytes diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalFiles.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalFiles.kt new file mode 100644 index 000000000..e267d073c --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalFiles.kt @@ -0,0 +1,42 @@ +package org.pnfolder.pnlibrary.core.journal.store + +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.core.journal.JournalLevel +import java.nio.file.Files +import java.nio.file.Path +import java.time.LocalDate +import java.util.concurrent.atomic.AtomicInteger + +// Segment files are named `-[-segment].pnj`. +internal class JournalFiles(private val directory: Path) { + // Each listing costs a system call per file, so callers keep it rare. + val listings = AtomicInteger() + + fun all(): List { + if (!Files.isDirectory(directory)) return emptyList() + listings.incrementAndGet() + return Files.list(directory).use { stream -> + stream.filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(".pnj") } + .sorted() + .collect(java.util.stream.Collectors.toList()) + } + } + + fun of(level: JournalLevel, files: List): List { + val prefix = "${level.fileGroup}-" + return files.filter { it.fileName.toString().startsWith(prefix) } + } + + fun levelOf(file: Path): JournalLevel? = + JournalLevel.values().firstOrNull { file.fileName.toString().startsWith("${it.fileGroup}-") } + + fun pathOf(level: JournalLevel, date: LocalDate, segment: Int): Path = + directory.resolve("${level.fileGroup}-$date${if (segment == 0) "" else "-$segment"}.pnj") + + fun dateOf(file: Path): LocalDate? = + runCatchingNonFatal { LocalDate.parse(file.fileName.toString().substringAfter('-').take(10)) } + .getOrNull() + + fun segmentOf(file: Path): Int = file.fileName.toString().substringAfter('-').drop(10) + .removePrefix("-").removeSuffix(".pnj").toIntOrNull() ?: 0 +} diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalQueries.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalQueries.kt similarity index 69% rename from modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalQueries.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalQueries.kt index a084e43a3..ce17f78df 100644 --- a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalQueries.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalQueries.kt @@ -1,10 +1,13 @@ -package org.pnfolder.pnlibrary.core.journal +package org.pnfolder.pnlibrary.core.journal.store import net.kyori.adventure.text.Component import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.core.journal.JournalDetail import org.pnfolder.pnlibrary.core.journal.JournalGroup +import org.pnfolder.pnlibrary.core.journal.JournalLevel +import org.pnfolder.pnlibrary.core.journal.JournalRecord +import org.pnfolder.pnlibrary.core.journal.view.joinDigest import java.time.Duration /** What the menu and the join notice read from the journal: equal events merged, one event with its details. */ @@ -13,10 +16,27 @@ class JournalQueries( private val config: PnLibraryConfig, private val startedAtMillis: Long, private val eventsCommand: String, + private val clock: () -> Long = System::currentTimeMillis, ) { - /** The lines shown to an administrator who joins, empty when the journal cannot be read. */ - fun joinNotice(): List { - val now = System.currentTimeMillis() + private val noticeLock = Any() + private var noticeBuiltAt: Long? = null + private var notice: List = emptyList() + + /** + * The lines shown to an administrator who joins, empty when the journal cannot be read. Several joins within + * [NOTICE_TTL_MILLIS] share one journal read, so a wave of administrators does not rescan the files. + */ + fun joinNotice(): List = synchronized(noticeLock) { + val now = clock() + val builtAt = noticeBuiltAt + if (builtAt == null || now - builtAt >= NOTICE_TTL_MILLIS || now < builtAt) { + notice = buildJoinNotice(now) + noticeBuiltAt = now + } + notice + } + + private fun buildJoinNotice(now: Long): List { val since = now - Duration.ofHours(config.journalJoinNoticeHours.toLong()).toMillis() return runCatchingNonFatal { joinDigest(journal.read(sinceMillis = since, limit = SCAN), now, config.journalJoinNoticeHours, startedAtMillis, eventsCommand) @@ -31,7 +51,7 @@ class JournalQueries( journal.read(levels = levels, sinceMillis = since, limit = SCAN) .groupBy { it.fingerprint } .map { (id, group) -> - val newest = group.maxByOrNull { it.timeMillis }!! + val newest = group.maxBy { it.timeMillis } JournalGroup(id, newest.level.fileGroup, newest.source, newest.message.lineSequence().first(), group.size, newest.timeMillis) } .sortedByDescending { it.lastMillis } @@ -57,5 +77,6 @@ class JournalQueries( private companion object { const val SCAN = 5_000 const val TIMES = 50 + const val NOTICE_TTL_MILLIS = 45_000L } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalReader.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalReader.kt new file mode 100644 index 000000000..ea7ced164 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalReader.kt @@ -0,0 +1,82 @@ +package org.pnfolder.pnlibrary.core.journal.store + +import org.pnfolder.pnlibrary.core.journal.JournalLevel +import org.pnfolder.pnlibrary.core.journal.JournalRecord +import java.nio.file.Files +import java.nio.file.NoSuchFileException +import java.nio.file.Path +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneOffset +import java.util.PriorityQueue + +/** Newest-first reads over the journal's segment files, bounded by a byte budget. */ +internal class JournalReader(private val files: JournalFiles, private val maximumReadBytes: Long) { + /** Newest-first read; [Snapshot.truncated] tells whether the byte budget stopped it before all matches. */ + fun readSnapshot( + levels: Set, + source: String?, + sinceMillis: Long?, + limit: Int, + type: String? = null, + ): Snapshot { + require(limit in 1..100_000) { "Journal limit must be between 1 and 100000" } + val wanted = if (levels.isEmpty()) JournalLevel.values().toSet() else levels + val segments = segmentsNewestFirst(wanted, sinceMillis) + val newest = PriorityQueue(compareBy { it.timeMillis }) + var remaining = maximumReadBytes + var scannedDate: LocalDate? = null + var truncated = false + for (file in segments) { + val date = files.dateOf(file) + if (newest.size >= limit && date != scannedDate) break + scannedDate = date + try { + val size = Files.size(file) + // Files are read whole and newest first: reading stops at a file that does not fit, so the + // returned records are always the newest complete set rather than an arbitrary prefix. + if (size > remaining) { truncated = true; break } + Files.newInputStream(file).buffered().use { input -> + JournalBlockCodec.visit(input, size) { record -> + offer(newest, record, limit, source, sinceMillis, type) + } + } + remaining -= size + } catch (_: NoSuchFileException) { + // Retention can remove a segment after the reader takes its snapshot. + } + } + return Snapshot(newest.sortedByDescending { it.timeMillis }, truncated) + } + + /** The segment files of [levels] that can hold records from [sinceMillis] on, newest day and segment first. */ + private fun segmentsNewestFirst(levels: Set, sinceMillis: Long?): List { + val sinceDate = sinceMillis?.let(::utcDate) + val all = files.all() + return levels.flatMap { files.of(it, all) }.filter { sinceDate == null || files.dateOf(it)?.isBefore(sinceDate) != true } + .sortedWith(compareByDescending { files.dateOf(it) }.thenByDescending(files::segmentOf)) + } + + /** Keeps [record] in [newest] when it matches the filters and is among the [limit] newest seen so far. */ + private fun offer( + newest: PriorityQueue, + record: JournalRecord, + limit: Int, + source: String?, + sinceMillis: Long?, + type: String?, + ) { + val typeFits = if (type == null) record.type != JournalRecord.STATS_TYPE else record.type == type + if (!typeFits || (source != null && record.source != source) || (sinceMillis != null && record.timeMillis < sinceMillis)) return + if (newest.size < limit) { + newest.add(record) + } else if (record.timeMillis > newest.peek().timeMillis) { + newest.poll() + newest.add(record) + } + } + + class Snapshot(val records: List, val truncated: Boolean) + + private fun utcDate(millis: Long): LocalDate = Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).toLocalDate() +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalStore.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalStore.kt new file mode 100644 index 000000000..f4c3f6dfe --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/store/JournalStore.kt @@ -0,0 +1,196 @@ +package org.pnfolder.pnlibrary.core.journal.store + +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.core.journal.JournalLevel +import org.pnfolder.pnlibrary.core.journal.JournalRecord +import java.nio.channels.FileChannel +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardOpenOption +import java.time.Clock +import java.time.Duration +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneOffset +import java.util.concurrent.atomic.AtomicLong + +// Segments: `-[-n].pnj`; active segment tracked in memory so the folder is listed only on first use per day. +// ERROR blocks are forced to disk before append() returns — a crash right after cannot lose an error record. +// Retention is per level so errors are kept longer than routine info lines. +class JournalStore( + private val directory: Path, + private val retention: Map, + private val clock: Clock = Clock.systemUTC(), + private val maximumSegmentBytes: Long = 8L * 1024 * 1024, + private val maximumDiskBytes: Long = 256L * 1024 * 1024, + private val maximumReadBytes: Long = 64L * 1024 * 1024, +) { + init { + require(JournalLevel.values().all { it in retention }) { "Every journal level needs a retention period" } + require(maximumSegmentBytes > 0 && maximumDiskBytes >= maximumSegmentBytes && maximumReadBytes > 0) + } + + private class Segment(val path: Path, var bytes: Long) + + private val files = JournalFiles(directory) + private val reader = JournalReader(files, maximumReadBytes) + private val active = HashMap, Segment>() + private val loadedDays = HashSet() + private var lastPrunedOn: LocalDate? = null + private var lastEnforcedAtMillis = clock.millis() + private var newSegmentStarted = false + + // Tests use it to prove that appends do not scan the folder. + val directoryListings: Int get() = files.listings.get() + + // One per chunk, not per record. + val blocksWritten = AtomicLong() + + fun append(record: JournalRecord) = appendAll(listOf(record)) { _, error -> throw error } + + // One block per level/day/BATCH_RECORDS so a burst costs one compress + one file open, not one per record. + @Synchronized + fun appendAll(records: List, rejected: (JournalRecord, Throwable) -> Unit) { + if (records.isEmpty()) return + Files.createDirectories(directory) + pruneOncePerDay() + records.groupByTo(LinkedHashMap()) { it.level to utcDate(it.timeMillis) }.forEach { (key, group) -> + group.chunked(BATCH_RECORDS).forEach { writeChunk(key.first, key.second, it, rejected) } + } + if (newSegmentStarted || clock.millis() - lastEnforcedAtMillis >= ENFORCE_INTERVAL_MILLIS) { + enforceDiskBudget(files.all()) + } + } + + private fun pruneOncePerDay() { + val today = today() + if (lastPrunedOn == today) return + lastPrunedOn = today + forgetSegments() + runCatchingNonFatal { prune() } + } + + private fun writeChunk( + level: JournalLevel, + date: LocalDate, + chunk: List, + rejected: (JournalRecord, Throwable) -> Unit, + ) { + val block = try { + JournalBlockCodec.encode(chunk).also { require(it.size <= maximumDiskBytes) { "Journal block exceeds disk budget" } } + } catch (error: IllegalArgumentException) { + if (chunk.size == 1) rejected(chunk[0], error) else chunk.forEach { writeChunk(level, date, listOf(it), rejected) } + return + } + val segment = segmentFor(level, date, block.size) + FileChannel.open(segment.path, StandardOpenOption.CREATE, StandardOpenOption.WRITE, + StandardOpenOption.APPEND).use { channel -> + val bytes = java.nio.ByteBuffer.wrap(block) + while (bytes.hasRemaining()) channel.write(bytes) + if (level == JournalLevel.ERROR) channel.force(true) + } + segment.bytes += block.size + blocksWritten.incrementAndGet() + } + + // A new segment triggers an async disk-budget check to avoid accumulating too many files. + private fun segmentFor(level: JournalLevel, date: LocalDate, size: Int): Segment { + if (loadedDays.add(date)) loadDay(date) + val key = level to date + val current = active[key] + if (current != null && current.bytes + size <= maximumSegmentBytes) return current + newSegmentStarted = true + val number = current?.let { files.segmentOf(it.path) + 1 } ?: 0 + return Segment(files.pathOf(level, date, number), 0).also { active[key] = it } + } + + private fun loadDay(date: LocalDate) { + val all = files.all() + for (level in JournalLevel.values()) { + val newest = files.of(level, all).filter { files.dateOf(it) == date }.maxByOrNull(files::segmentOf) ?: continue + active[level to date] = Segment(newest, Files.size(newest)) + } + } + + fun read( + levels: Set = emptySet(), + source: String? = null, + sinceMillis: Long? = null, + limit: Int = 100, + type: String? = null, + ): List = reader.readSnapshot(levels, source, sinceMillis, limit, type).records + + fun summary(): Map { + val since = clock.millis() - Duration.ofHours(24).toMillis() + return JournalLevel.values().associate { level -> + val snapshot = reader.readSnapshot(levels = setOf(level), source = null, sinceMillis = since, limit = SUMMARY_LIMIT) + val recent = snapshot.records + level.fileGroup to linkedMapOf( + "recordsLast24h" to recent.size, + "countCapped" to (recent.size >= SUMMARY_LIMIT || snapshot.truncated), + "readBudgetExhausted" to snapshot.truncated, + "maximumReadBytes" to maximumReadBytes, + "maximumDiskBytes" to maximumDiskBytes, + "newestAtMillis" to recent.firstOrNull()?.timeMillis, + "retentionDays" to retentionDays(level), + ) + } + } + + @Synchronized + fun prune(): Int { + if (!Files.isDirectory(directory)) return 0 + val today = today() + val survivors = ArrayList() + var removed = 0 + for (file in files.all()) { + val level = files.levelOf(file) + val date = files.dateOf(file) + if (level == null || date == null || !date.isBefore(today.minusDays(retentionDays(level)))) { + survivors.add(file) + } else { + Files.deleteIfExists(file) + removed++ + } + } + if (removed > 0) forgetSegments() + return removed + enforceDiskBudget(survivors) + } + + // Routine levels evicted before ERROR — the disk budget must never force-remove error records early. + private fun enforceDiskBudget(all: List): Int { + lastEnforcedAtMillis = clock.millis() + newSegmentStarted = false + val ordered = all.sortedWith(compareBy { it.fileName.toString().startsWith("${JournalLevel.ERROR.fileGroup}-") } + .thenBy { files.dateOf(it) }.thenBy(files::segmentOf)) + var total = ordered.sumOf { Files.size(it) } + var removed = 0 + for (file in ordered) { + if (total <= maximumDiskBytes) break + val bytes = Files.size(file) + if (Files.deleteIfExists(file)) { total -= bytes; removed++ } + } + if (removed > 0) forgetSegments() + return removed + } + + private fun forgetSegments() { + active.clear() + loadedDays.clear() + } + + private companion object { + // More than SUMMARY_LIMIT records in 24 h is reported as "at least". + const val SUMMARY_LIMIT = 10_000 + // Far below the decoder's limit of 10 000. + const val BATCH_RECORDS = 256 + // Disk budget is checked at least this often even when no new segment starts. + const val ENFORCE_INTERVAL_MILLIS = 60_000L + } + + private fun retentionDays(level: JournalLevel) = retention.getValue(level).toDays().coerceAtLeast(1) + + private fun today(): LocalDate = LocalDate.now(clock.withZone(ZoneOffset.UTC)) + + private fun utcDate(millis: Long): LocalDate = Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).toLocalDate() +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalCard.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalCard.kt new file mode 100644 index 000000000..c69a87122 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalCard.kt @@ -0,0 +1,183 @@ +package org.pnfolder.pnlibrary.core.journal.view + +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.event.ClickEvent +import org.pnfolder.pnlibrary.api.chat.ChatKit +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.commands.CommandSender +import org.pnfolder.pnlibrary.common.time.DisplayZone +import org.pnfolder.pnlibrary.core.journal.JournalRecord +import org.pnfolder.pnlibrary.core.journal.store.JournalStore +import org.pnfolder.pnlibrary.core.text.wrapText + +/** The detail card of one event, or the timeline of its occurrences when [repeats] is set. */ +internal fun journalCard( + sender: CommandSender, + kit: ChatKit, + journal: JournalStore, + id: String?, + repeats: Boolean, + fullTrace: Boolean = false, + root: String, +) { + val group = journal.read(limit = SCAN_LIMIT).filter { it.fingerprint == id }.sortedByDescending { it.timeMillis } + if (id == null || group.isEmpty()) { + sender.send(kit.text("Такой записи нет: возможно, её уже удалили по сроку хранения.", ChatPalette.DANGER)) + return + } + val record = group.first() + val lines = cardHead(kit, id, record).toMutableList() + lines += whenSection(kit, group) + lines += kit.blank() + val (body, traceHidden) = + if (repeats) repeatsSection(kit, group) to false else detailsSection(kit, record, sender.isConsole || fullTrace) + lines += body + val buttons = cardButtons(kit, root, id, repeats, fullTrace, traceHidden, group) + lines += kit.actions(*buttons.toTypedArray()) ?: kit.blank() + lines.forEach(sender::send) +} + +/** The title of the card: the event id and level, its source and type. */ +private fun cardHead(kit: ChatKit, id: String, record: JournalRecord): List { + val (tag, color) = levelStyle(record.level) + return listOf( + kit.blank(), + kit.blank(), + kit.header("Событие $id", kit.bracketed(tag, color)), + kit.text(" ${record.source}", ChatPalette.ACCENT).append(kit.dot()).append(kit.text(record.type, ChatPalette.LABEL)), + kit.blank(), + ) +} + +/** The first and the last time of the event and how often it repeated. */ +private fun whenSection(kit: ChatKit, group: List): List { + val last = group.first().timeMillis + val first = group.last().timeMillis + val lines = mutableListOf( + kit.section("Когда"), + kit.field("Последний раз", moment(kit, last).append(kit.text(" ${ago(last)}", agoColor(last)))), + kit.field("Часовой пояс", kit.text(zoneLabel(), ChatPalette.SOFT)), + ) + if (group.size > 1) { + val gap = (last - first) / (group.size - 1) + lines += kit.field("Первый раз", moment(kit, first).append(kit.text(" ${ago(first)}", agoColor(first)))) + lines += kit.field( + "Повторов", + kit.text(group.size.toString(), ChatPalette.ORANGE).append(kit.text(" примерно раз в ${span(gap)}", ChatPalette.SOFT)), + ) + } + return lines +} + +/** The occurrences of the event, newest first, grouped by day. */ +private fun repeatsSection(kit: ChatKit, group: List): List { + val lines = mutableListOf() + val zone = DisplayZone.zone + val today = java.time.LocalDate.now(zone) + val days = group.take(REPEAT_ROWS).groupBy { java.time.Instant.ofEpochMilli(it.timeMillis).atZone(zone).toLocalDate() } + days.forEach { (day, items) -> lines += dayRows(kit, day, items, today, zone) } + if (group.size > REPEAT_ROWS) { + lines += kit.note("Показаны последние $REPEAT_ROWS из ${group.size}.") + lines += kit.blank() + } + return lines +} + +/** The heading of one day and a row for each occurrence of it. */ +private fun dayRows( + kit: ChatKit, + day: java.time.LocalDate, + items: List, + today: java.time.LocalDate, + zone: java.time.ZoneId, +): List { + val lines = mutableListOf() + val title = when (day) { + today -> "Сегодня" + today.minusDays(1) -> "Вчера" + else -> longDate(day) + } + val dayTip = kit.tooltip( + kit.text(DAY_WITH_YEAR.format(day), ChatPalette.TEXT), + kit.text(WEEKDAY.format(day), ChatPalette.LABEL), + kit.blank(), + kit.hoverField("Событий в этот день", kit.text(items.size.toString(), ChatPalette.ORANGE)), + ) + var heading = kit.section(title) + if (day == today || day == today.minusDays(1)) heading = heading.append(kit.text(" · ${longDate(day)}", ChatPalette.SOFT)) + lines += heading.append(kit.text(" ×${items.size}", ChatPalette.ORANGE)).hoverEvent(dayTip) + items.forEach { item -> + lines += kit.text(" " + CLOCK.withZone(zone).format(java.time.Instant.ofEpochMilli(item.timeMillis)), ChatPalette.TEXT) + .append(kit.text(" ${ago(item.timeMillis)}", agoColor(item.timeMillis))) + .hoverEvent(momentTip(kit, item.timeMillis)) + } + lines += kit.blank() + return lines +} + +/** The message, its details and the stack trace; the flag says whether some trace lines were folded away. */ +private fun detailsSection(kit: ChatKit, record: JournalRecord, wholeTrace: Boolean): Pair, Boolean> { + val lines = mutableListOf(kit.section("Что случилось")) + wrapText(record.message, CARD_WIDTH).forEach { lines += kit.text(" $it", ChatPalette.TEXT) } + record.details.filterKeys { it != JournalRecord.STACKTRACE }.forEach { (key, value) -> + lines += kit.text(" $key: ", ChatPalette.LABEL).append(kit.text(value, ChatPalette.SOFT)) + } + var hidden = false + val trace = record.details[JournalRecord.STACKTRACE]?.lines().orEmpty() + if (trace.isNotEmpty()) { + lines += kit.blank() + lines += kit.section("Стек вызовов") + val (view, folded) = traceView(kit, trace, wholeTrace) + lines += view + hidden = folded + } + lines += kit.blank() + return lines to hidden +} + +/** The buttons under the card; a null entry is a button that does not apply. */ +private fun cardButtons( + kit: ChatKit, + root: String, + id: String, + repeats: Boolean, + fullTrace: Boolean, + traceHidden: Boolean, + group: List, +): List { + val buttons = mutableListOf( + kit.button("назад", root, "К списку событий", ChatPalette.ACCENT), + if (repeats) kit.button("карточка", "$root view $id", "Вернуться к карточке", ChatPalette.ACCENT) + else if (group.size > 1) kit.button("повторы", "$root times $id", "Когда это повторялось", ChatPalette.ACCENT) + else null, + if (traceHidden) kit.button("показать всё", "$root full $id", "Стек вызовов целиком, ничего не свёрнуто", ChatPalette.ACCENT) + else if (fullTrace) kit.button("свернуть", "$root view $id", "Снова свернуть служебные вызовы", ChatPalette.ACCENT) + else null, + ) + if (kit.reader.interactive) buttons += copyButton(kit, group) + return buttons +} + +/** Copies the report for the plugin author; only in a chat that can click. */ +private fun copyButton(kit: ChatKit, group: List): Component = + kit.bracketed("скопировать", ChatPalette.OK) + .clickEvent(ClickEvent.copyToClipboard(clipboardText(group.first(), group.size))) + .hoverEvent( + kit.tooltip( + kit.text("Скопировать отчёт для автора плагина", ChatPalette.OK), + kit.blank(), + kit.text("Время, число повторов, сообщение и весь стек вызовов", ChatPalette.LABEL), + ), + ) + +/** Plain text for the plugin author: what happened, how often, and the whole stack trace. */ +internal fun clipboardText(record: JournalRecord, count: Int): String = buildString { + appendLine("[${record.level}] ${record.source} · ${record.type}") + appendLine("Время: ${stamp(record.timeMillis)} ${zoneLabel()}, повторов: $count") + appendLine(record.message) + record.details.filterKeys { it != JournalRecord.STACKTRACE }.forEach { (key, value) -> appendLine("$key: $value") } + record.details[JournalRecord.STACKTRACE]?.let { + appendLine() + append(it) + } +}.trim() diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalCommand.kt similarity index 55% rename from modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalCommand.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalCommand.kt index 87896d661..b26063fbf 100644 --- a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalCommand.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalCommand.kt @@ -1,10 +1,12 @@ -package org.pnfolder.pnlibrary.core.journal +package org.pnfolder.pnlibrary.core.journal.view import org.pnfolder.pnlibrary.api.chat.ChatKit import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.commands.ArgumentType -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command +import org.pnfolder.pnlibrary.core.journal.store.JournalStore /** * `/pn events [info|warning|error|all] [page]`: the journal with repeats of one event folded into a single row. @@ -20,35 +22,34 @@ fun journalCommand(journal: JournalStore, root: String = "/pn events"): CommandD noPermissionMessage("Журнал событий доступен администраторам. Нужно право pnlibrary.events.view.") consoleBypassesPermission() // The router accepts only declared words, so every level, page and card id is declared here. - executes { context -> list(context.sender, ChatKit(ChatReader.of(context.sender)), journal, context.arguments, root) } + executes { showList(it, journal, root) } listOf("all", "info", "warning", "error").forEach { level -> literal(level) { - executes { context -> list(context.sender, ChatKit(ChatReader.of(context.sender)), journal, context.arguments, root) } + executes { showList(it, journal, root) } argument("page", ArgumentType.integer()) { - executes { context -> list(context.sender, ChatKit(ChatReader.of(context.sender)), journal, context.arguments, root) } + executes { showList(it, journal, root) } } } } literal("view") { argument("id", ArgumentType.string()) { - executes { context -> - card(context.sender, ChatKit(ChatReader.of(context.sender)), journal, context.arguments.getOrNull(1), repeats = false, root = root) - } + executes { showCard(it, journal, root, repeats = false, fullTrace = false) } } } literal("full") { argument("id", ArgumentType.string()) { - executes { context -> - card(context.sender, ChatKit(ChatReader.of(context.sender)), journal, context.arguments.getOrNull(1), repeats = false, fullTrace = true, - root = root) - } + executes { showCard(it, journal, root, repeats = false, fullTrace = true) } } } literal("times") { argument("id", ArgumentType.string()) { - executes { context -> - card(context.sender, ChatKit(ChatReader.of(context.sender)), journal, context.arguments.getOrNull(1), repeats = true, root = root) - } + executes { showCard(it, journal, root, repeats = true, fullTrace = false) } } } } + +private fun showList(context: CommandContext, journal: JournalStore, root: String) = + journalList(context.sender, ChatKit(ChatReader.of(context.sender)), journal, context.arguments, root) + +private fun showCard(context: CommandContext, journal: JournalStore, root: String, repeats: Boolean, fullTrace: Boolean) = + journalCard(context.sender, ChatKit(ChatReader.of(context.sender)), journal, context.arguments.getOrNull(1), repeats, fullTrace, root) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalConstants.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalConstants.kt new file mode 100644 index 000000000..07ef2c01b --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalConstants.kt @@ -0,0 +1,14 @@ +package org.pnfolder.pnlibrary.core.journal.view + +internal const val PAGE_SIZE = 5 + +// Keeps lines from flooding a player's chat; the console and the card show the full message. +internal const val CHAT_CHARS = 46 + +// Records read to fold repeats and to count how often an event happened. +internal const val SCAN_LIMIT = 5_000 + +internal const val HOVER_WIDTH = 44 +internal const val HOVER_MESSAGE_LINES = 4 +internal const val CARD_WIDTH = 56 +internal const val REPEAT_ROWS = 15 diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalDigest.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalDigest.kt similarity index 73% rename from modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalDigest.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalDigest.kt index 0221eff5f..15e17f35f 100644 --- a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalDigest.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalDigest.kt @@ -1,13 +1,16 @@ -package org.pnfolder.pnlibrary.core.journal +package org.pnfolder.pnlibrary.core.journal.view import net.kyori.adventure.text.Component import net.kyori.adventure.text.event.ClickEvent +import net.kyori.adventure.text.event.HoverEvent import net.kyori.adventure.text.format.TextColor import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.common.text.RussianText import org.pnfolder.pnlibrary.common.time.DisplayZone +import org.pnfolder.pnlibrary.core.journal.JournalLevel +import org.pnfolder.pnlibrary.core.journal.JournalRecord import java.time.Duration import java.time.Instant import java.time.format.DateTimeFormatter @@ -69,58 +72,72 @@ fun joinDigest( .sortedByDescending { it.first().timeMillis } if (groups.isEmpty()) return emptyList() - val errors = groups.filter { it.first().level == JournalLevel.ERROR } - val warnings = groups.filter { it.first().level == JournalLevel.WARNING } - val errorCount = errors.sumOf { it.size } - val warningCount = warnings.sumOf { it.size } - - fun reasonOf(group: List): Reason { - val first = group.last().timeMillis - return when { - first >= startedAtMillis - 1_000 && first <= startedAtMillis + STARTUP.toMillis() -> Reason.STARTUP - group.first().timeMillis >= now - JUST_NOW.toMillis() -> Reason.JUST_NOW - group.size >= RECURRING_FROM -> Reason.RECURRING - else -> Reason.PLAIN - } - } + val hasErrors = groups.any { it.first().level == JournalLevel.ERROR } + val ranked = rankByUrgency(groups, now, startedAtMillis) + val top = ranked.first() + val topReason = reasonOf(top, now, startedAtMillis) + val lines = mutableListOf( + kit.blank(), + kit.header("Журнал", kit.text("за последние $windowHours ${RussianText.plural(windowHours.toLong(), "час", "часа", "часов")}", ChatPalette.LABEL)), + summaryLine(kit, relevant.count { it.level == JournalLevel.ERROR }, relevant.count { it.level == JournalLevel.WARNING }), + strip(kit, relevant, now, windowHours, startedAtMillis), + ) + ranked.take(MAX_NOTABLE).forEach { lines += notableLine(kit, it, reasonOf(it, now, startedAtMillis), root) } + lines += adviceLine(kit, top, topReason, hasErrors) + lines += kit.blank() + lines += digestActions(kit, root, hasErrors, topReason != Reason.PLAIN, top) + return lines +} - // Most urgent first; errors before warnings inside one reason. If nothing stands out, the newest error (or warning). - val ranked = groups.sortedWith(compareBy> { reasonOf(it).ordinal } - .thenBy { if (it.first().level == JournalLevel.ERROR) 0 else 1 }) - val notable = ranked.take(MAX_NOTABLE) - val topReason = reasonOf(ranked.first()) +/** The buttons under the digest; the card button appears only when something is worth a closer look. */ +private fun digestActions(kit: ChatKit, root: String, hasErrors: Boolean, urgentReason: Boolean, top: List): Component { + val urgent = hasErrors || urgentReason + return kit.actions( + kit.button("открыть журнал", if (hasErrors) "$root error" else "$root warning", "Список событий", ChatPalette.ACCENT), + if (urgent) kit.button("подробнее", "$root view ${top.first().fingerprint}", "Карточка главного события", ChatPalette.ACCENT) else null, + ) ?: kit.blank() +} + +/** Most urgent first; errors before warnings inside one reason. If nothing stands out, the newest error (or warning) leads. */ +private fun rankByUrgency(groups: List>, now: Long, startedAtMillis: Long): List> = + groups.sortedWith( + compareBy> { reasonOf(it, now, startedAtMillis).ordinal } + .thenBy { if (it.first().level == JournalLevel.ERROR) 0 else 1 }, + ) + +/** One piece of advice for the top event, or the calm note when nothing is urgent; nothing when only errors stand out plainly. */ +private fun adviceLine(kit: ChatKit, top: List, topReason: Reason, hasErrors: Boolean): List { + if (topReason == Reason.PLAIN) { + return if (hasErrors) emptyList() else listOf(kit.note("Ничего срочного. Загляните в журнал, когда будет время.", ChatPalette.FAINT)) + } // An event that keeps repeating is a repeating problem even when its last repeat was a moment ago. - val adviceReason = if (topReason == Reason.JUST_NOW && ranked.first().size >= RECURRING_FROM) Reason.RECURRING else topReason + val reason = if (topReason == Reason.JUST_NOW && top.size >= RECURRING_FROM) Reason.RECURRING else topReason + return listOf(kit.note(reason.advice, ChatPalette.FAINT)) +} +/** Why [group], newest first, deserves a look: it began at startup, just happened, or keeps coming back. */ +private fun reasonOf(group: List, now: Long, startedAtMillis: Long): Reason { + val first = group.last().timeMillis + return when { + first >= startedAtMillis - 1_000 && first <= startedAtMillis + STARTUP.toMillis() -> Reason.STARTUP + group.first().timeMillis >= now - JUST_NOW.toMillis() -> Reason.JUST_NOW + group.size >= RECURRING_FROM -> Reason.RECURRING + else -> Reason.PLAIN + } +} + +/** ` ● 3 ошибки ▲ 2 предупреждения`: only the kinds that occurred. */ +private fun summaryLine(kit: ChatKit, errorCount: Int, warningCount: Int): Component { val summary = mutableListOf() - if (errors.isNotEmpty()) { + if (errorCount > 0) { summary += kit.text(kit.glyph('●') + " $errorCount ", ChatPalette.DANGER) .append(kit.text(RussianText.plural(errorCount.toLong(), "ошибка", "ошибки", "ошибок"), ChatPalette.SOFT)) } - if (warnings.isNotEmpty()) { + if (warningCount > 0) { summary += kit.text(kit.glyph('▲') + " $warningCount ", ChatPalette.WARN) .append(kit.text(RussianText.plural(warningCount.toLong(), "предупреждение", "предупреждения", "предупреждений"), ChatPalette.SOFT)) } - - val lines = mutableListOf( - kit.blank(), - kit.header("Журнал", kit.text("за последние $windowHours ${RussianText.plural(windowHours.toLong(), "час", "часа", "часов")}", ChatPalette.LABEL)), - summary.drop(1).fold(kit.text(" ").append(summary.first())) { line, part -> line.append(kit.text(" ")).append(part) }, - strip(kit, relevant, now, windowHours, startedAtMillis), - ) - notable.forEach { lines += notableLine(kit, it, reasonOf(it), now, root) } - if (topReason == Reason.PLAIN) { - if (errors.isEmpty()) lines += kit.note("Ничего срочного. Загляните в журнал, когда будет время.", ChatPalette.FAINT) - } else { - lines += kit.note(adviceReason.advice, ChatPalette.FAINT) - } - lines += kit.blank() - val urgent = errors.isNotEmpty() || topReason != Reason.PLAIN - lines += kit.actions( - kit.button("открыть журнал", if (errors.isNotEmpty()) "$root error" else "$root warning", "Список событий", ChatPalette.ACCENT), - if (urgent) kit.button("подробнее", "$root view ${ranked.first().first().fingerprint}", "Карточка главного события", ChatPalette.ACCENT) else null, - ) ?: kit.blank() - return lines + return summary.drop(1).fold(kit.text(" ").append(summary.first())) { line, part -> line.append(kit.text(" ")).append(part) } } private fun levelColor(level: JournalLevel): TextColor = when (level) { @@ -209,7 +226,7 @@ private fun stripTipLines( } /** ` ● pnShop ×3 старт Database is locked`, clickable to open the card; the reason word is dropped when plain. */ -private fun notableLine(kit: ChatKit, group: List, reason: Reason, now: Long, root: String): Component { +private fun notableLine(kit: ChatKit, group: List, reason: Reason, root: String): Component { val record = group.first() val color = levelColor(record.level) val icon = if (record.level == JournalLevel.ERROR) '●' else '▲' @@ -228,7 +245,12 @@ private fun notableLine(kit: ChatKit, group: List, reason: Reason line = line.append(kit.text(" ${reason.word}", reasonColor)) } line = line.append(kit.text(" $message", ChatPalette.SOFT)) - val tip = mutableListOf( + return line.clickEvent(ClickEvent.runCommand("$root view ${record.fingerprint}")).hoverEvent(notableTip(kit, group)) +} + +private fun notableTip(kit: ChatKit, group: List): HoverEvent { + val record = group.first() + return kit.tooltip( kit.text(record.source, ChatPalette.ACCENT), kit.text(record.message.lineSequence().first().take(120), ChatPalette.TEXT), kit.blank(), @@ -240,5 +262,4 @@ private fun notableLine(kit: ChatKit, group: List, reason: Reason kit.blank(), kit.text("Нажмите, чтобы открыть карточку", ChatPalette.FAINT), ) - return line.clickEvent(ClickEvent.runCommand("$root view ${record.fingerprint}")).hoverEvent(kit.tooltip(*tip.toTypedArray())) } diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalList.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalList.kt similarity index 82% rename from modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalList.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalList.kt index 14e8847d0..6e60ac0ea 100644 --- a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalList.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalList.kt @@ -1,11 +1,14 @@ -package org.pnfolder.pnlibrary.core.journal +package org.pnfolder.pnlibrary.core.journal.view import net.kyori.adventure.text.Component import net.kyori.adventure.text.event.ClickEvent import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.api.commands.CommandSender import org.pnfolder.pnlibrary.common.text.RussianText +import org.pnfolder.pnlibrary.core.journal.JournalLevel +import org.pnfolder.pnlibrary.core.journal.JournalRecord +import org.pnfolder.pnlibrary.core.journal.store.JournalStore import java.util.Locale /** Filter words in the order of the tabs: the command word, the tab label and the levels it shows. */ @@ -16,7 +19,8 @@ private val FILTERS = listOf( Triple("info", "инфо", setOf(JournalLevel.INFO)), ) -fun list(sender: CommandSender, kit: ChatKit, journal: JournalStore, arguments: List, root: String) { +/** Prints one page of the journal for the filter and page named in [arguments], or tells which level words exist. */ +internal fun journalList(sender: CommandSender, kit: ChatKit, journal: JournalStore, arguments: List, root: String) { val word = arguments.getOrNull(0)?.lowercase(Locale.ROOT) ?: "all" val filter = FILTERS.firstOrNull { it.first == word || (word == "warn" && it.first == "warning") } if (filter == null) { @@ -31,16 +35,10 @@ fun list(sender: CommandSender, kit: ChatKit, journal: JournalStore, arguments: val page = (arguments.getOrNull(1)?.toIntOrNull() ?: 1).coerceIn(1, pages) val rows = groups.drop((page - 1) * PAGE_SIZE).take(PAGE_SIZE) - val lines = mutableListOf( - kit.blank(), - kit.blank(), - kit.header("События", kit.text("${groups.size} ${RussianText.plural(groups.size.toLong(), "запись", "записи", "записей")}", ChatPalette.LABEL)), - tabs(kit, everything, filter.first, root), - kit.blank(), - ) + val lines = listHead(kit, groups.size, tabs(kit, everything, filter.first, root)).toMutableList() if (rows.isEmpty()) lines += kit.note("Здесь пока пусто.") rows.forEach { group -> - lines += row(kit, group, sender.isConsole, root) + lines += journalRow(kit, group, sender.isConsole, root) lines += kit.blank() } if (pages > 1) { @@ -53,6 +51,14 @@ fun list(sender: CommandSender, kit: ChatKit, journal: JournalStore, arguments: lines.forEach(sender::send) } +private fun listHead(kit: ChatKit, count: Int, tabs: Component): List = listOf( + kit.blank(), + kit.blank(), + kit.header("События", kit.text("$count ${RussianText.plural(count.toLong(), "запись", "записи", "записей")}", ChatPalette.LABEL)), + tabs, + kit.blank(), +) + /** * `Показать:` and one button per filter, such as `[ошибки 3]`. Every button has the same gray brackets; the open * filter is violet and the others are gray, so the difference is one color and never depends on the level. diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalRows.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalRows.kt similarity index 76% rename from modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalRows.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalRows.kt index 2b6630a66..38e5153be 100644 --- a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalRows.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalRows.kt @@ -1,27 +1,15 @@ -package org.pnfolder.pnlibrary.core.journal +package org.pnfolder.pnlibrary.core.journal.view import net.kyori.adventure.text.Component import net.kyori.adventure.text.event.ClickEvent import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.core.journal.JournalLevel +import org.pnfolder.pnlibrary.core.journal.JournalRecord +import org.pnfolder.pnlibrary.core.text.wrapText -/** Splits [text] into lines of at most [width] characters at spaces. */ -fun wrap(text: String, width: Int): List { - val lines = mutableListOf() - var current = StringBuilder() - text.split(' ').forEach { word -> - if (current.isNotEmpty() && current.length + 1 + word.length > width) { - lines += current.toString() - current = StringBuilder() - } - if (current.isNotEmpty()) current.append(' ') - current.append(word) - } - if (current.isNotEmpty()) lines += current.toString() - return lines -} - -fun levelStyle(level: JournalLevel) = when (level) { +/** The label and the color that mark records of [level]. */ +internal fun levelStyle(level: JournalLevel) = when (level) { JournalLevel.ERROR -> "ОШИБКА" to ChatPalette.DANGER JournalLevel.WARNING -> "ВНИМАНИЕ" to ChatPalette.WARN JournalLevel.INFO -> "инфо" to ChatPalette.SOFT @@ -42,7 +30,7 @@ private fun levelIcon(kit: ChatKit, level: JournalLevel): Component = when (leve * One event as a two-line block with a colored bar on its left edge: the source, the repeat count and how long * ago on the first line, the message on the second. [group] holds the repeats, newest first. */ -fun row(kit: ChatKit, group: List, full: Boolean, root: String): Component { +internal fun journalRow(kit: ChatKit, group: List, full: Boolean, root: String): Component { val record = group.first() val (tag, color) = levelStyle(record.level) val text = if (!full && record.message.length > CHAT_CHARS) record.message.take(CHAT_CHARS) + "…" else record.message @@ -53,7 +41,7 @@ fun row(kit: ChatKit, group: List, full: Boolean, root: String): icon.append(kit.text(" $tag", color)).append(kit.dot()).append(kit.text(record.source, ChatPalette.ACCENT)), kit.blank(), ) - wrap(record.message.lineSequence().first(), HOVER_WIDTH).take(HOVER_MESSAGE_LINES).forEach { hover += kit.text(it, ChatPalette.TEXT) } + wrapText(record.message.lineSequence().first(), HOVER_WIDTH).take(HOVER_MESSAGE_LINES).forEach { hover += kit.text(it, ChatPalette.TEXT) } hover += kit.blank() hover += kit.hoverField("Последний раз", kit.text(fullStamp(record.timeMillis), ChatPalette.TEXT)) if (group.size > 1) { diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalTime.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalTime.kt similarity index 55% rename from modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalTime.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalTime.kt index 7d673a2d9..f97ad07d8 100644 --- a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalTime.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalTime.kt @@ -1,9 +1,9 @@ -package org.pnfolder.pnlibrary.core.journal +package org.pnfolder.pnlibrary.core.journal.view import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.TextColor import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.common.text.RussianText import org.pnfolder.pnlibrary.common.time.DisplayZone import java.time.format.DateTimeFormatter @@ -11,39 +11,37 @@ import java.util.Locale // Dates and times of the journal, always in the configured display zone (DisplayZone). -val TIME: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM HH:mm:ss") -val CLOCK: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss") -val DAY: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM") -val DAY_WITH_YEAR: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy") +private val TIME: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM HH:mm:ss") +internal val CLOCK: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss") +internal val DAY_WITH_YEAR: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy") +private val TIME_WITH_YEAR: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss") -val TIME_WITH_YEAR: DateTimeFormatter = - DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss") - -/** Day and time, with the year only when it is not the current one, so old events are never ambiguous. */ -fun stamp(millis: Long): String { +// The year is shown only when it is not the current one, so old events are never ambiguous. +internal fun stamp(millis: Long): String { val instant = java.time.Instant.ofEpochMilli(millis) val zone = DisplayZone.zone val sameYear = instant.atZone(zone).year == java.time.LocalDate.now(zone).year return (if (sameYear) TIME else TIME_WITH_YEAR).withZone(zone).format(instant) } -val RU = Locale("ru") -val LONG_DAY: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMMM", RU) -val LONG_DAY_YEAR: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMMM yyyy 'года'", RU) -val WEEKDAY: DateTimeFormatter = DateTimeFormatter.ofPattern("EEEE", RU) -val UTC_STAMP: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(java.time.ZoneOffset.UTC) -/** "16 октября 2023 года", or "16 октября" within the current year. */ -fun longDate(date: java.time.LocalDate): String = +private val RU = Locale("ru") +private val LONG_DAY: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMMM", RU) +private val LONG_DAY_YEAR: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMMM yyyy 'года'", RU) +internal val WEEKDAY: DateTimeFormatter = DateTimeFormatter.ofPattern("EEEE", RU) +private val UTC_STAMP: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(java.time.ZoneOffset.UTC) + +// "16 октября 2023 года", or "16 октября" within the current year. +internal fun longDate(date: java.time.LocalDate): String = if (date.year == java.time.LocalDate.now(DisplayZone.zone).year) LONG_DAY.format(date) else LONG_DAY_YEAR.format(date) -fun localDate(millis: Long): java.time.LocalDate = java.time.Instant.ofEpochMilli(millis).atZone(DisplayZone.zone).toLocalDate() +private fun localDate(millis: Long): java.time.LocalDate = java.time.Instant.ofEpochMilli(millis).atZone(DisplayZone.zone).toLocalDate() -/** "16 октября 2023 года, 16:45:07": the date in words, then the clock in the display zone. */ -fun fullStamp(millis: Long): String = +// "16 октября 2023 года, 16:45:07": the date in words, then the clock in the display zone. +internal fun fullStamp(millis: Long): String = "${longDate(localDate(millis))}, ${CLOCK.withZone(DisplayZone.zone).format(java.time.Instant.ofEpochMilli(millis))}" -/** The same moment as numbers and in UTC, for the hover card, so the exact value is always one hover away. */ -fun momentTip(kit: ChatKit, millis: Long) = kit.tooltip( +// Numbers and UTC in the hover, so the exact value is always one hover away. +internal fun momentTip(kit: ChatKit, millis: Long) = kit.tooltip( kit.text(TIME_WITH_YEAR.withZone(DisplayZone.zone).format(java.time.Instant.ofEpochMilli(millis)), ChatPalette.TEXT), kit.text(WEEKDAY.format(localDate(millis)), ChatPalette.LABEL), kit.blank(), @@ -52,18 +50,15 @@ fun momentTip(kit: ChatKit, millis: Long) = kit.tooltip( kit.hoverField("Прошло", kit.text(ago(millis).removeSuffix(" назад"), agoColor(millis))), ) -/** A date and time in words that shows the exact numbers when hovered. */ -fun moment(kit: ChatKit, millis: Long): Component = +internal fun moment(kit: ChatKit, millis: Long): Component = kit.text(fullStamp(millis), ChatPalette.TEXT).hoverEvent(momentTip(kit, millis)) -/** "How long ago": gray, and dimmer once it is more than a month old. */ -fun agoColor(millis: Long, now: Long = System.currentTimeMillis()): TextColor = +// Dimmer once the event is more than a month old. +internal fun agoColor(millis: Long, now: Long = System.currentTimeMillis()): TextColor = if (now - millis < 30L * 86_400_000) ChatPalette.SOFT else ChatPalette.FAINT -/** - * How long ago [millis] was, with the two largest units: "только что", "5 мин назад", "3 ч 12 мин назад", - * "5 дней назад", "3 месяца 2 дня назад" or "3 года 1 день назад". - */ -fun ago(millis: Long, now: Long = System.currentTimeMillis(), zone: java.time.ZoneId = DisplayZone.zone): String { + +// Two largest units: "только что", "5 мин назад", "3 ч 12 мин назад", "5 дней назад", "3 месяца 2 дня назад". +internal fun ago(millis: Long, now: Long = System.currentTimeMillis(), zone: java.time.ZoneId = DisplayZone.zone): String { val seconds = ((now - millis) / 1000).coerceAtLeast(0) if (seconds < 60) return "только что" if (seconds < 86_400) { @@ -82,8 +77,7 @@ fun ago(millis: Long, now: Long = System.currentTimeMillis(), zone: java.time.Zo return (parts.joinToString(" ").ifEmpty { "1 день" }) + " назад" } -/** A span such as "1 ч 20 мин" for the average gap between repeats. */ -fun span(millis: Long): String { +internal fun span(millis: Long): String { val minutes = millis / 60_000 return when { minutes < 1 -> "меньше минуты" @@ -92,8 +86,9 @@ fun span(millis: Long): String { else -> "${minutes / 1440} д ${minutes % 1440 / 60} ч" } } -/** The display zone as `Europe/Moscow (UTC+03:00)`, so nobody has to guess which clock a time uses. */ -fun zoneLabel(): String { + +// Includes the offset so nobody has to guess which clock a time uses. +internal fun zoneLabel(): String { val zone = DisplayZone.zone val offset = zone.rules.getOffset(java.time.Instant.now()).id.let { if (it == "Z") "+00:00" else it } return "${zone.id} (UTC$offset)" diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalTrace.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalTrace.kt similarity index 66% rename from modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalTrace.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalTrace.kt index 4f1b54520..64b728e25 100644 --- a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalTrace.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/view/JournalTrace.kt @@ -1,50 +1,35 @@ -package org.pnfolder.pnlibrary.core.journal +package org.pnfolder.pnlibrary.core.journal.view import net.kyori.adventure.text.Component import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.common.text.RussianText // Stack traces in chat: colored like source code, with frames of the JDK and the server folded. /** Stack trace lines in a player's chat card; the console prints all of them. */ -const val CARD_TRACE_LINES = 14 +internal const val CARD_TRACE_LINES = 14 /** Stack trace frame: optional module prefix, class, method and the `File.java:44` location. */ -val FRAME = Regex("""^at\s+(?:\S*/)?([\w$.]+)\.([\w$<>]+)\((.*)\)$""") +private val FRAME = Regex("""^at\s+(?:\S*/)?([\w$.]+)\.([\w$<>]+)\((.*)\)$""") /** Exception line: optional `Caused by: `, the class and its message. */ -val HEAD = Regex("""^(Caused by: |Suppressed: )?([\w$.]+)(?::\s?(.*))?$""") +private val HEAD = Regex("""^(Caused by: |Suppressed: )?([\w$.]+)(?::\s?(.*))?$""") /** Packages of the JDK, the server and common libraries: their frames are dimmed, the plugin's own stay bright. */ -val FRAMEWORK = listOf( +private val FRAMEWORK = listOf( "java.", "javax.", "jdk.", "sun.", "org.bukkit.", "io.papermc.", "net.minecraft.", "com.mojang.", "org.spigotmc.", "net.md_5.", "com.destroystokyo.", "io.netty.", "org.apache.", "kotlin.", "kotlinx.", "com.velocitypowered.", "net.kyori.", "org.jetbrains.", ) /** One trace line as colored text, and whether it is a frame of the JDK, the server or a library. */ -fun traceLine(kit: ChatKit, line: String): Pair { +internal fun traceLine(kit: ChatKit, line: String): Pair { val text = line.replace("\t", " ").trim() FRAME.matchEntire(text)?.let { match -> val (className, method, location) = match.destructured val framework = FRAMEWORK.any { className.startsWith(it) } - val tip = kit.tooltip( - kit.text("$className.$method", if (framework) ChatPalette.FAINT else ChatPalette.TEXT), - kit.text(location, if (framework) ChatPalette.FAINT else ChatPalette.SOFT), - ) - val component = if (framework) { - kit.text(" · ", ChatPalette.FAINT) - .append(kit.text("${className.substringAfterLast('.')}.$method", ChatPalette.FAINT)) - .append(kit.text(" $location", ChatPalette.FAINT)) - } else { - kit.text(" ▸ ", ChatPalette.ORANGE) - .append(kit.text(className.substringAfterLast('.'), ChatPalette.TEXT)) - .append(kit.text(".", ChatPalette.FAINT)) - .append(kit.text(method, ChatPalette.ACCENT)) - .append(kit.text(" $location", ChatPalette.SOFT)) - } - return component.hoverEvent(tip) to framework + return frameLine(kit, className, method, location, framework) to framework } HEAD.matchEntire(text)?.let { match -> val prefix = match.groupValues[1] @@ -60,12 +45,32 @@ fun traceLine(kit: ChatKit, line: String): Pair { return kit.text(" $text", ChatPalette.FAINT) to false } +/** A stack frame: the plugin's own frames are bright and the frames of the JDK and the server are dimmed. */ +private fun frameLine(kit: ChatKit, className: String, method: String, location: String, framework: Boolean): Component { + val tip = kit.tooltip( + kit.text("$className.$method", if (framework) ChatPalette.FAINT else ChatPalette.TEXT), + kit.text(location, if (framework) ChatPalette.FAINT else ChatPalette.SOFT), + ) + val component = if (framework) { + kit.text(" · ", ChatPalette.FAINT) + .append(kit.text("${className.substringAfterLast('.')}.$method", ChatPalette.FAINT)) + .append(kit.text(" $location", ChatPalette.FAINT)) + } else { + kit.text(" ▸ ", ChatPalette.ORANGE) + .append(kit.text(className.substringAfterLast('.'), ChatPalette.TEXT)) + .append(kit.text(".", ChatPalette.FAINT)) + .append(kit.text(method, ChatPalette.ACCENT)) + .append(kit.text(" $location", ChatPalette.SOFT)) + } + return component.hoverEvent(tip) +} + /** * The whole stack trace colored like source code: exception classes in red with their package dimmed, the plugin's * own frames in amber and green, frames of the JDK and the server dimmed. In chat the dimmed frames of one run are * folded into a single line and the list is cut; the console shows every line. */ -fun traceView(kit: ChatKit, trace: List, full: Boolean): Pair, Boolean> { +internal fun traceView(kit: ChatKit, trace: List, full: Boolean): Pair, Boolean> { val rendered = trace.map { traceLine(kit, it) } if (full) return rendered.map { it.first } to false val out = mutableListOf() diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/lifecycle/RuntimeResources.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/lifecycle/RuntimeResources.kt index 9215941d2..650943585 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/lifecycle/RuntimeResources.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/lifecycle/RuntimeResources.kt @@ -1,110 +1,80 @@ package org.pnfolder.pnlibrary.core.lifecycle import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.commands.CommandBuilder import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition import org.pnfolder.pnlibrary.api.commands.CommandRegistration -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.CommandBuilder +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.api.tasks.TaskScope -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.core.downloads.fetch.DirectDownloads import org.pnfolder.pnlibrary.core.journal.JournalDetail import org.pnfolder.pnlibrary.core.journal.JournalGroup -import org.pnfolder.pnlibrary.core.placeholders.PlaceholderInfo +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderInfo +import org.pnfolder.pnlibrary.core.settings.SettingPickerHook +import org.pnfolder.pnlibrary.core.settings.SettingsStore import org.pnfolder.pnlibrary.core.stats.StatsSnapshot import org.pnfolder.pnlibrary.core.tasks.TaskControl import java.util.concurrent.CompletionStage -/** Private runtime capabilities, deliberately absent from the consumer API facade. */ +object MountableCommands { + const val EVENTS = "events" + const val DEBUG = "debug" + const val STATS = "stats" + const val PLACEHOLDERS = "placeholders" + const val SETTINGS = "settings" + + val ALL = listOf(EVENTS, DEBUG, STATS, PLACEHOLDERS, SETTINGS) +} + internal interface RuntimeResources { val runtimeTasks: TaskScope fun registerRuntimeCommand(command: CommandDefinition): CommandRegistration - - /** A shared command the platform puts under its own control command (`events`, `debug`), or `null`. */ fun mountableCommand(name: String): CommandDefinition? - - /** Runs a registered command for a viewer who is not on this server, or `null` when this platform cannot. */ fun dispatchCommand(command: CommandDefinition, context: CommandContext): CompletionStage? - - /** The notice for an administrator who has just joined: recent problems from the journal, or nothing. */ fun journalJoinNotice(): List - - /** Journal records of the last [sinceHours] hours, equal events merged, newest first; [level] is `info`, `warning`, `error` or `null`. */ fun journalGroups(level: String?, sinceHours: Int, limit: Int): List - - /** Every live and retained task of every plugin. */ fun taskSnapshots(): List - - /** The numbers of the server right now: tasks, events, and the errors and warnings of the day. */ fun statsSnapshot(): StatsSnapshot - - /** Every registered placeholder with its type, format and PlaceholderAPI names. */ - fun placeholderInfos(): List = emptyList() - - /** Stops the task with this id for an administrator; the task may forbid it. */ + fun placeholderInfos(): List fun cancelTask(id: String): TaskControl - - /** Starts the waiting task with this id at once for an administrator; the task may forbid it. */ fun runTaskNow(id: String): TaskControl - - /** The whole event behind a [JournalGroup.id], or `null` when it is no longer in the journal. */ + fun dependencyDownloads(): DirectDownloads? + fun librarySettings(): SettingsStore? + val settingPicker: SettingPickerHook fun journalDetail(id: String): JournalDetail? } -/** Every live and retained task of every plugin; empty when the runtime has no task service. */ -fun PnLibrary.taskSnapshots(): List = (this as? RuntimeResources)?.taskSnapshots().orEmpty() - -/** Stops the task with this id for an administrator; the task may forbid it. */ -fun PnLibrary.cancelTask(id: String): TaskControl = (this as? RuntimeResources)?.cancelTask(id) ?: TaskControl.UNAVAILABLE - -/** Starts the waiting task with this id at once for an administrator; the task may forbid it. */ -fun PnLibrary.runTaskNow(id: String): TaskControl = (this as? RuntimeResources)?.runTaskNow(id) ?: TaskControl.UNAVAILABLE - -/** The whole journal event with the id [id]; `null` when there is none or the runtime has no journal. */ -fun PnLibrary.journalDetail(id: String): JournalDetail? = (this as? RuntimeResources)?.journalDetail(id) - -/** Journal events of the last [sinceHours] hours for a menu; empty when the runtime has no journal. */ +internal fun PnLibrary.dependencyDownloads(): DirectDownloads? = resources()?.dependencyDownloads() +fun PnLibrary.settingPicker(): SettingPickerHook? = resources()?.settingPicker +internal fun PnLibrary.librarySettings(): SettingsStore? = resources()?.librarySettings() +fun PnLibrary.taskSnapshots(): List = resources()?.taskSnapshots().orEmpty() +fun PnLibrary.cancelTask(id: String): TaskControl = resources()?.cancelTask(id) ?: TaskControl.UNAVAILABLE +fun PnLibrary.runTaskNow(id: String): TaskControl = resources()?.runTaskNow(id) ?: TaskControl.UNAVAILABLE +fun PnLibrary.journalDetail(id: String): JournalDetail? = resources()?.journalDetail(id) fun PnLibrary.journalGroups(level: String? = null, sinceHours: Int = 24, limit: Int = 200): List = - (this as? RuntimeResources)?.journalGroups(level, sinceHours, limit).orEmpty() + resources()?.journalGroups(level, sinceHours, limit).orEmpty() -/** - * Native pnLibrary integration only. Consumer plugins obtain tasks through ModuleContext.tasks. - * This bridge belongs to core, not to the published public API. - */ +// Consumer plugins get tasks through ModuleContext.tasks — this bridge is for core only. fun PnLibrary.runtimeTaskScope(): TaskScope = runtimeResources().runtimeTasks -/** Lines to show an administrator on joining, empty when the journal has nothing to report or the notice is off. */ fun PnLibrary.journalJoinNotice(): List = runtimeResources().journalJoinNotice() - -/** The numbers of the server right now. */ fun PnLibrary.statsSnapshot(): StatsSnapshot = runtimeResources().statsSnapshot() - -/** Every registered placeholder; empty when the runtime has no placeholders. */ -fun PnLibrary.placeholderInfos(): List = (this as? RuntimeResources)?.placeholderInfos().orEmpty() - -/** Registers a pnLibrary-owned command from core or a bundled native integration. */ +fun PnLibrary.placeholderInfos(): List = resources()?.placeholderInfos().orEmpty() fun PnLibrary.registerRuntimeCommand(command: CommandDefinition): CommandRegistration = runtimeResources().registerRuntimeCommand(command) - -/** - * A shared command that this platform does not register on its own: the platform mounts it under its control - * command instead (`events` and `debug` under Bukkit `/pn`). `null` where the command is registered separately. - */ -fun PnLibrary.mountableCommand(name: String): CommandDefinition? = (this as? RuntimeResources)?.mountableCommand(name) - -/** Runs a registered command for a viewer on another server; `null` when the platform cannot dispatch it. */ +fun PnLibrary.mountableCommand(name: String): CommandDefinition? = resources()?.mountableCommand(name) fun PnLibrary.dispatchRuntimeCommand(command: CommandDefinition, context: CommandContext): CompletionStage? = - (this as? RuntimeResources)?.dispatchCommand(command, context) - -/** Builds a pnLibrary-owned command; consumer plugins use ModuleContext.registerCommand. */ + resources()?.dispatchCommand(command, context) fun PnLibrary.registerRuntimeCommand( name: String, configure: CommandBuilder.() -> Unit, ): CommandRegistration = registerRuntimeCommand(command(name, configure)) -/** Only the core runtime implements [RuntimeResources]; any other [PnLibrary] is a wiring error. */ +private fun PnLibrary.resources(): RuntimeResources? = this as? RuntimeResources private fun PnLibrary.runtimeResources(): RuntimeResources = - this as? RuntimeResources ?: throw IllegalStateException( + resources() ?: throw IllegalStateException( "Runtime resources are available only on the pnLibrary core runtime, not on ${javaClass.name}", ) diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/Link.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/Link.kt similarity index 72% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/Link.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/Link.kt index 81bb9a8fd..7066f1fd2 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/Link.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/Link.kt @@ -1,5 +1,11 @@ package org.pnfolder.pnlibrary.core.link +import org.pnfolder.pnlibrary.core.link.remote.DataClient +import org.pnfolder.pnlibrary.core.link.remote.DataHandler +import org.pnfolder.pnlibrary.core.link.remote.LinkTransport +import org.pnfolder.pnlibrary.core.link.remote.RemoteControl +import org.pnfolder.pnlibrary.core.link.remote.RemoteReplies +import org.pnfolder.pnlibrary.core.link.report.NetworkReport import java.nio.file.Path import java.time.Instant @@ -20,13 +26,18 @@ class Link( private val transport: LinkTransport? = null, private val uplink: ((ByteArray) -> Boolean)? = null, ) { + /** Whether the link has a key; without one nothing is sent or received. */ val enabled: Boolean get() = key != null + /** Whether this link is the proxy's end, which can send to servers by name. */ val onProxy: Boolean get() = transport != null /** On the proxy: the game servers heard from since it started. */ val registry = LinkRegistry() + /** The remote requests this end made and has no answer to yet. */ val replies = RemoteReplies() + /** The data questions this end asked and has no answer to yet. */ val data = DataClient(key) { bytes -> uplink?.invoke(bytes) ?: false } + /** Sends update controls to other servers. */ val control = RemoteControl(this) /** On a game server: the latest network map from the proxy, or null until one arrives. */ @@ -39,10 +50,12 @@ class Link( var calls: DataHandler? = null private set + /** Keeps the latest network map from the proxy, as received at [now]. */ fun remember(report: NetworkReport, now: Instant = Instant.now()) { network = ReceivedNetwork(report, now) } + /** Sets what answers the data questions other servers ask of this one. */ fun answerCallsWith(handler: DataHandler) { calls = handler } @@ -56,6 +69,7 @@ class Link( fun send(target: String, message: ByteArray): Boolean = transport?.send(target, message) ?: uplink?.invoke(message) ?: false + /** A network map and when this server received it. */ data class ReceivedNetwork(val report: NetworkReport, val receivedAt: Instant) companion object { diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkReceiver.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkReceiver.kt similarity index 73% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkReceiver.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkReceiver.kt index ba69d12c6..385d4d66c 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkReceiver.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkReceiver.kt @@ -1,5 +1,14 @@ package org.pnfolder.pnlibrary.core.link +import org.pnfolder.pnlibrary.core.link.remote.DataCall +import org.pnfolder.pnlibrary.core.link.remote.DataHandler +import org.pnfolder.pnlibrary.core.link.remote.LinkNames +import org.pnfolder.pnlibrary.core.link.remote.RemoteExecutor +import org.pnfolder.pnlibrary.core.link.remote.RemoteRequest +import org.pnfolder.pnlibrary.core.link.remote.RemoteResult +import org.pnfolder.pnlibrary.core.link.wire.DataChunks +import org.pnfolder.pnlibrary.core.link.wire.LinkCodec +import org.pnfolder.pnlibrary.core.link.wire.LinkFrame import java.time.Instant /** @@ -19,33 +28,21 @@ class LinkReceiver( private val executor: RemoteExecutor? = null, private val data: DataHandler? = null, ) { + /** Whether the link has a key; without one nothing is accepted. */ val enabled: Boolean get() = link.enabled /** Handles [message] from [server]; returns true when it was a valid message. */ fun receive(server: String, fromServer: Boolean, message: ByteArray): Boolean { val key = link.key if (!fromServer || key == null) return false - LinkCodec.decode(message, key)?.let { - link.registry.accept(server, it) - return true + when (val frame = LinkCodec.decodeFrame(message, key) ?: return false) { + is LinkFrame.Report -> link.registry.accept(server, frame.report) + is LinkFrame.Request -> route(server, frame.request.copy(origin = server), key) + is LinkFrame.Result -> deliver(frame.result, key) + is LinkFrame.Call -> routeCall(server, frame.call.copy(origin = server), key) + is LinkFrame.Chunk -> if (frame.chunk.to == LinkNames.PROXY_ORIGIN) link.data.accept(frame.chunk) else link.send(frame.chunk.to, message) } - LinkCodec.decodeRequest(message, key)?.let { - route(server, it.copy(origin = server), key) - return true - } - LinkCodec.decodeResult(message, key)?.let { - deliver(it, key) - return true - } - LinkCodec.decodeCall(message, key)?.let { - routeCall(server, it.copy(origin = server), key) - return true - } - LinkCodec.decodeChunk(message, key)?.let { - if (it.to == LinkNames.PROXY_ORIGIN) link.data.accept(it) else link.send(it.to, message) - return true - } - return false + return true } private fun route(server: String, request: RemoteRequest, key: ByteArray) { diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkRegistry.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkRegistry.kt similarity index 58% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkRegistry.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkRegistry.kt index ea50821dc..7d5e313a7 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkRegistry.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkRegistry.kt @@ -1,22 +1,27 @@ package org.pnfolder.pnlibrary.core.link +import org.pnfolder.pnlibrary.core.link.report.LinkReport import java.time.Instant import java.util.concurrent.ConcurrentHashMap -/** The game servers a proxy has heard from, by the name the proxy knows them under. */ +/** The newest report of every server that answered over the link; a newer report from the same name replaces the old one. */ class LinkRegistry { + /** One server's report and when it arrived. */ data class Entry(val name: String, val report: LinkReport, val receivedAt: Instant) private val entries = ConcurrentHashMap() + /** Stores [report] as the latest of [name]. */ fun accept(name: String, report: LinkReport, now: Instant = Instant.now()) { entries[name] = Entry(name, report, now) } + /** Every known server, sorted by name without regard to case. */ fun all(): List = entries.values.sortedBy { it.name.lowercase() } - /** The server called [name], ignoring case, or null. */ + /** The server called [name], ignoring case, or `null`. */ fun get(name: String): Entry? = entries.values.firstOrNull { it.name.equals(name, ignoreCase = true) } + /** Forgets every server. */ fun clear() = entries.clear() } diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkTimeouts.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkTimeouts.kt similarity index 92% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkTimeouts.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkTimeouts.kt index 0fc31ce10..73da2b1cc 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkTimeouts.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkTimeouts.kt @@ -17,6 +17,7 @@ internal class LinkTimeouts(threadName: String) { removeOnCancelPolicy = true } + /** Runs [action] once after [seconds]; cancel the returned future to drop it. */ fun after(seconds: Long, action: () -> Unit): ScheduledFuture<*> = timer.schedule(Runnable { action() }, seconds, TimeUnit.SECONDS) private companion object { diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/ServerGroups.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/ServerGroups.kt similarity index 97% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/ServerGroups.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/ServerGroups.kt index 01d80238a..de6b736fa 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/ServerGroups.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/ServerGroups.kt @@ -1,7 +1,8 @@ package org.pnfolder.pnlibrary.core.link -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.common.io.TsvRecords +import org.pnfolder.pnlibrary.core.link.report.NetworkServer import java.nio.file.Path /** @@ -91,6 +92,7 @@ class ServerGroups(private val file: () -> Path?) { val ok: Boolean get() = known != null && known.online && missing.isEmpty() && outdated.isEmpty() } + /** Every group in the file, sorted by name ignoring case. */ fun all(): List { val servers = linkedMapOf>() val plugins = linkedMapOf>() @@ -117,6 +119,7 @@ class ServerGroups(private val file: () -> Path?) { /** The group called [name], ignoring case, or null. */ fun get(name: String): Group? = all().firstOrNull { it.name.equals(name, ignoreCase = true) } + /** The groups that [server] belongs to, ignoring case. */ fun of(server: String): List = all().filter { group -> group.servers.any { it.equals(server, true) } } /** Makes an empty group; returns false when the name is taken, reserved or unfit. */ diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/DataClient.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/DataClient.kt similarity index 84% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/DataClient.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/DataClient.kt index d4364b5d2..f5ddfd31c 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/DataClient.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/DataClient.kt @@ -1,17 +1,14 @@ -package org.pnfolder.pnlibrary.core.link +package org.pnfolder.pnlibrary.core.link.remote +import org.pnfolder.pnlibrary.core.link.LinkTimeouts +import org.pnfolder.pnlibrary.core.link.wire.DataChunks +import org.pnfolder.pnlibrary.core.link.wire.LinkCodec import java.time.Instant import java.util.UUID import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ScheduledFuture -/** - * The questions this server asked and has no answer to yet. - * - * @param key the shared key, or null when the link is off - * @param uplink sends a question to the proxy; false when nobody can carry it - */ class DataClient( private val key: ByteArray?, private val timeoutSeconds: Long = TIMEOUT_SECONDS, @@ -26,10 +23,6 @@ class DataClient( private val waiting = ConcurrentHashMap() private val timeouts = LinkTimeouts("pnlibrary-link-data") - /** - * Asks [target] for [method]. The future holds the answer, or fails with a [DataException] when the server is not - * reachable, does not answer in time or refuses. - */ fun call(target: String, viewer: String, method: String, args: String): CompletableFuture { val future = CompletableFuture() if (key == null) { @@ -55,7 +48,6 @@ class DataClient( return future } - /** Takes one piece of an answer; completes the question when the last one arrives. */ fun accept(chunk: DataChunk) { val pending = waiting[chunk.id] ?: return pending.pieces[chunk.index] = chunk.bytes diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/DataLink.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/DataLink.kt similarity index 92% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/DataLink.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/DataLink.kt index f1104bba7..3bdf55090 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/DataLink.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/DataLink.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.link +package org.pnfolder.pnlibrary.core.link.remote import java.time.Instant import java.util.UUID @@ -46,4 +46,5 @@ fun interface DataHandler { fun handle(call: DataCall, reply: (Boolean, String) -> Unit) } +/** Why a data request failed; its message is shown to the player or logged. */ class DataException(message: String) : RuntimeException(message) diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/Remote.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/Remote.kt similarity index 91% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/Remote.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/Remote.kt index b109fe889..d88934c55 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/Remote.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/Remote.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.link +package org.pnfolder.pnlibrary.core.link.remote import java.time.Instant import java.util.UUID @@ -7,6 +7,7 @@ import java.util.UUID enum class RemoteAction( /** The word used in the `/pn servers ` command. */ val word: String, + /** Whether the request must name a plugin. */ val needsProduct: Boolean, /** The permission the person asking must have on the server they ask from. */ val permission: String, @@ -51,7 +52,9 @@ data class RemoteRequest( */ data class RemoteResult(val id: UUID, val origin: String, val ok: Boolean, val text: String, val sentAt: Instant) +/** Fixed names used on the link. */ object LinkNames { + /** The name under which the proxy is addressed. */ const val PROXY = "proxy" /** The origin of a request made on the proxy itself. */ diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/RemoteControl.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/RemoteControl.kt similarity index 89% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/RemoteControl.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/RemoteControl.kt index 6ec0d73f1..fd0056334 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/RemoteControl.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/RemoteControl.kt @@ -1,5 +1,8 @@ -package org.pnfolder.pnlibrary.core.link +package org.pnfolder.pnlibrary.core.link.remote +import org.pnfolder.pnlibrary.core.link.Link +import org.pnfolder.pnlibrary.core.link.LinkTimeouts +import org.pnfolder.pnlibrary.core.link.wire.LinkCodec import java.time.Instant import java.util.UUID import java.util.concurrent.ConcurrentHashMap @@ -7,6 +10,7 @@ import java.util.concurrent.ScheduledFuture /** Sends bytes to the game server called [server]; returns false when it cannot be reached. */ fun interface LinkTransport { + /** Sends [message] to [server]; false when it cannot be reached. */ fun send(server: String, message: ByteArray): Boolean } @@ -28,6 +32,7 @@ class RemoteReplies { } } + /** Stops waiting for request [id], for a request that could not be sent. */ fun cancel(id: UUID) { waiting.remove(id)?.timeout?.cancel(false) } diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/RemoteExecutor.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/RemoteExecutor.kt similarity index 52% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/RemoteExecutor.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/RemoteExecutor.kt index 3300b6599..6609266a4 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/RemoteExecutor.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/remote/RemoteExecutor.kt @@ -1,8 +1,9 @@ -package org.pnfolder.pnlibrary.core.link +package org.pnfolder.pnlibrary.core.link.remote import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdateState +import org.pnfolder.pnlibrary.core.exceptions.rootMessage import java.time.Duration import java.time.Instant import java.util.UUID @@ -26,46 +27,53 @@ class RemoteExecutor(private val library: PnLibrary, private val clock: () -> In val product = request.product.orEmpty() try { when (request.action) { - RemoteAction.CHECK -> library.updates.checkNow(actor).whenComplete { plan, error -> - reply( - if (error != null) { - result(request, false, "Проверка не удалась: ${message(error)}") - } else { - val count = plan.plan?.changes?.size ?: 0 - result(request, true, if (count == 0) "Всё актуально." else "Найдено обновлений: $count.") - }, - ) - } + RemoteAction.CHECK -> check(request, actor, reply) RemoteAction.UPDATE -> update(request, product, actor, reply) - RemoteAction.AUTO_ON, RemoteAction.AUTO_OFF -> { - val enabled = request.action == RemoteAction.AUTO_ON - library.updates.setAutomaticDownload(product, enabled, actor).whenComplete { _, error -> - reply( - if (error != null) { - result(request, false, "Не удалось изменить: ${message(error)}") - } else { - result(request, true, "Автозагрузка $product: ${if (enabled) "включена" else "выключена"}.") - }, - ) - } - } + RemoteAction.AUTO_ON, RemoteAction.AUTO_OFF -> automatic(request, product, actor, reply) } } catch (error: Exception) { - reply(result(request, false, message(error))) + library.logging.logger(library.owner, "link").error("Remote action ${request.action} from ${request.origin} failed", error) + reply(result(request, false, error.rootMessage())) + } + } + + private fun check(request: RemoteRequest, actor: UpdateActor, reply: (RemoteResult) -> Unit) { + library.updates.plans.check(actor).whenComplete { plan, error -> + reply( + if (error != null) { + result(request, false, "Проверка не удалась: ${error.rootMessage()}") + } else { + val count = plan.plan?.changes?.size ?: 0 + result(request, true, if (count == 0) "Всё актуально." else "Найдено обновлений: $count.") + }, + ) + } + } + + private fun automatic(request: RemoteRequest, product: String, actor: UpdateActor, reply: (RemoteResult) -> Unit) { + val enabled = request.action == RemoteAction.AUTO_ON + library.updates.settings.automaticDownload(product, enabled, actor).whenComplete { _, error -> + reply( + if (error != null) { + result(request, false, "Не удалось изменить: ${error.rootMessage()}") + } else { + result(request, true, "Автозагрузка $product: ${if (enabled) "включена" else "выключена"}.") + }, + ) } } private fun update(request: RemoteRequest, product: String, actor: UpdateActor, reply: (RemoteResult) -> Unit) { - if (library.updates.get(product) == null) return reply(result(request, false, "Плагин $product не подключён к обновлениям pnLibrary.")) - library.updates.checkNow(actor).whenComplete { plan, error -> + if (library.updates.products.get(product) == null) return reply(result(request, false, "Плагин $product не подключён к обновлениям pnLibrary.")) + library.updates.plans.check(actor).whenComplete { plan, error -> val change = plan?.plan?.changes?.firstOrNull { it.product.value.equals(product, ignoreCase = true) } when { - error != null -> reply(result(request, false, "Проверка не удалась: ${message(error)}")) + error != null -> reply(result(request, false, "Проверка не удалась: ${error.rootMessage()}")) plan.state != UpdateState.UPDATE_AVAILABLE || change == null -> reply(result(request, true, "Для $product нет обновления.")) - else -> library.updates.stage(plan.id, actor).whenComplete { _, stageError -> + else -> library.updates.plans.stage(plan.id, actor).whenComplete { _, stageError -> reply( if (stageError != null) { - result(request, false, "Не удалось подготовить: ${message(stageError)}") + result(request, false, "Не удалось подготовить: ${stageError.rootMessage()}") } else { result(request, true, "Подготовлено: $product v${change.from} » v${change.to}. Нужен перезапуск.") }, @@ -77,11 +85,6 @@ class RemoteExecutor(private val library: PnLibrary, private val clock: () -> In private fun result(request: RemoteRequest, ok: Boolean, text: String) = RemoteResult(request.id, request.origin, ok, text, clock()) - private fun message(error: Throwable): String { - val cause = generateSequence(error) { it.cause }.last() - return cause.message ?: cause.javaClass.simpleName - } - private companion object { val REMEMBER: Duration = Duration.ofMinutes(10) } diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkReport.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/report/LinkReport.kt similarity index 94% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkReport.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/report/LinkReport.kt index 33db3c7d7..7be41f04c 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkReport.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/report/LinkReport.kt @@ -1,5 +1,6 @@ -package org.pnfolder.pnlibrary.core.link +package org.pnfolder.pnlibrary.core.link.report +import org.pnfolder.pnlibrary.core.link.ServerGroups import java.time.Instant /** diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkReports.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/report/LinkReports.kt similarity index 88% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkReports.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/report/LinkReports.kt index edee12217..e2a188a2e 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkReports.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/report/LinkReports.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.link +package org.pnfolder.pnlibrary.core.link.report import org.pnfolder.pnlibrary.api.runtime.PnLibrary import java.time.Instant @@ -11,7 +11,7 @@ object LinkReports { platform = platform, libraryVersion = library.version.toString(), players = players, - plugins = library.updates.all().map { + plugins = library.updates.products.all().map { val snapshot = it.snapshot val current = snapshot.currentVersion.toString() LinkPlugin(snapshot.product, current, snapshot.latestVersion?.toString()?.takeIf { latest -> latest != current }, snapshot.state.name) diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/NetworkPublisher.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/report/NetworkPublisher.kt similarity index 88% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/NetworkPublisher.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/report/NetworkPublisher.kt index bfa96acaf..f485dcf20 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/NetworkPublisher.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/report/NetworkPublisher.kt @@ -1,6 +1,8 @@ -package org.pnfolder.pnlibrary.core.link +package org.pnfolder.pnlibrary.core.link.report import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.core.link.Link +import org.pnfolder.pnlibrary.core.link.wire.LinkCodec import java.time.Duration import java.time.Instant diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/DataChunks.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/DataChunks.kt similarity index 95% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/DataChunks.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/DataChunks.kt index e7f2f1d7f..e3ffd7001 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/DataChunks.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/DataChunks.kt @@ -1,5 +1,6 @@ -package org.pnfolder.pnlibrary.core.link +package org.pnfolder.pnlibrary.core.link.wire +import org.pnfolder.pnlibrary.core.link.remote.DataChunk import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.time.Instant diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/FrameSigner.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/FrameSigner.kt new file mode 100644 index 000000000..7a5bbecc7 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/FrameSigner.kt @@ -0,0 +1,26 @@ +package org.pnfolder.pnlibrary.core.link.wire + +import java.security.MessageDigest +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec + +internal fun interface FrameSigner { + fun sign(bytes: ByteArray, key: ByteArray): ByteArray +} + +// One Mac per thread per key — Mac init is the expensive part; doFinal() resets to the initialized state for reuse. +internal class CachedHmac(private val create: () -> Mac = { Mac.getInstance(ALGORITHM) }) : FrameSigner { + private val perThread = ThreadLocal() + + override fun sign(bytes: ByteArray, key: ByteArray): ByteArray { + val cached = perThread.get()?.takeIf { MessageDigest.isEqual(it.key, key) } + ?: Keyed(key.copyOf(), create().apply { init(SecretKeySpec(key, ALGORITHM)) }).also(perThread::set) + return cached.mac.doFinal(bytes) + } + + private class Keyed(val key: ByteArray, val mac: Mac) + + private companion object { + const val ALGORITHM = "HmacSHA256" + } +} diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkCodec.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkCodec.kt similarity index 56% rename from modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkCodec.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkCodec.kt index b4126f486..e345e7474 100644 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkCodec.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkCodec.kt @@ -1,5 +1,14 @@ -package org.pnfolder.pnlibrary.core.link +package org.pnfolder.pnlibrary.core.link.wire +import org.pnfolder.pnlibrary.core.link.ServerGroups +import org.pnfolder.pnlibrary.core.link.remote.DataCall +import org.pnfolder.pnlibrary.core.link.remote.DataChunk +import org.pnfolder.pnlibrary.core.link.remote.RemoteAction +import org.pnfolder.pnlibrary.core.link.remote.RemoteRequest +import org.pnfolder.pnlibrary.core.link.remote.RemoteResult +import org.pnfolder.pnlibrary.core.link.report.LinkReport +import org.pnfolder.pnlibrary.core.link.report.NetworkReport +import org.pnfolder.pnlibrary.core.link.report.NetworkServer import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.DataInputStream @@ -8,27 +17,14 @@ import java.security.MessageDigest import java.time.Duration import java.time.Instant import java.util.UUID -import javax.crypto.Mac -import javax.crypto.spec.SecretKeySpec -/** - * Writes and reads the signed messages of the link between a game server and the proxy. - * - * A message is the report followed by an HMAC-SHA256 of everything before it, made with the key both sides share. - * A message with a wrong signature, an unknown version or a time too far from now is dropped, so a player who - * sends bytes on the channel by hand cannot pose as a server. - */ +// Message format: body + HMAC-SHA256(body, sharedKey). Wrong signature, bad version, or stale time → dropped. +// A player sending raw bytes on the channel cannot pose as a server. object LinkCodec { const val CHANNEL = "pnlibrary:link" - - /** Longer lists are cut so the message stays under the plugin message limit. */ const val MAX_PLUGINS = 150 - const val MAX_NETWORK_PLUGINS = 40 - - /** A plugin message may not be larger than this. */ const val MAX_FRAME_BYTES = 32_000 - const val MAX_SERVERS = 30 private const val MAX_GROUPS = 30 @@ -41,29 +37,23 @@ object LinkCodec { private const val CALL_VERSION = 5 private const val CHUNK_VERSION = 6 private const val MAX_RESULT_TEXT = 1_000 - private const val MAC_ALGORITHM = "HmacSHA256" private const val MAC_BYTES = 32 private const val MAX_TEXT = 200 private val TOLERANCE: Duration = Duration.ofMinutes(2) + private val hmac: FrameSigner = CachedHmac() fun encode(report: LinkReport, key: ByteArray): ByteArray = signed(key) { out -> out.writeByte(VERSION) - writeReport(out, report, MAX_PLUGINS) + ReportWire.write(out, report, MAX_PLUGINS) } - /** Reads [message], or returns null when the signature, the version or the time is wrong. */ fun decode(message: ByteArray, key: ByteArray, now: Instant = Instant.now()): LinkReport? = - verified(message, key) { input -> + verified(message, key, hmac) { input -> if (input.readUnsignedByte() != VERSION) return@verified null - readReport(input).takeIf { fresh(it.sentAt, now) } + ReportWire.read(input).takeIf { fresh(it.sentAt, now) } } - /** - * Encodes the network map and signs it with [key]. - * - * Servers refuse plugin messages over 32767 bytes and kick the player who carried one, so when the map is larger - * than [MAX_FRAME_BYTES] the plugin lists, then the groups and the servers are cut until it fits. - */ + // Servers kick the player who delivers an oversized plugin message, so we halve limits until it fits. fun encodeNetwork(network: NetworkReport, key: ByteArray): ByteArray { var plugins = MAX_NETWORK_PLUGINS var items = MAX_GROUP_ITEMS @@ -86,13 +76,13 @@ object LinkCodec { private fun networkBytes(network: NetworkReport, key: ByteArray, pluginLimit: Int, itemLimit: Int, serverLimit: Int, groupLimit: Int): ByteArray = signed(key) { out -> out.writeByte(NETWORK_VERSION) - writeReport(out, network.proxy, pluginLimit) + ReportWire.write(out, network.proxy, pluginLimit) val servers = network.servers.take(serverLimit) out.writeInt(servers.size) servers.forEach { out.writeUTF(it.name.take(MAX_TEXT)) out.writeBoolean(it.online) - writeReport(out, it.report, pluginLimit) + ReportWire.write(out, it.report, pluginLimit) } val groups = network.groups.take(groupLimit) out.writeInt(groups.size) @@ -119,14 +109,13 @@ object LinkCodec { private fun readNames(input: DataInputStream): Set = List(input.readInt().coerceIn(0, MAX_GROUP_ITEMS)) { input.readUTF() }.toSet() - /** Reads a network map, or returns null when the signature, the version or the time is wrong. */ fun decodeNetwork(message: ByteArray, key: ByteArray, now: Instant = Instant.now()): NetworkReport? = - verified(message, key) { input -> + verified(message, key, hmac) { input -> if (input.readUnsignedByte() != NETWORK_VERSION) return@verified null - val proxy = readReport(input) + val proxy = ReportWire.read(input) if (!fresh(proxy.sentAt, now)) return@verified null val count = input.readInt().coerceIn(0, MAX_SERVERS) - val servers = List(count) { NetworkServer(input.readUTF(), input.readBoolean(), readReport(input)) } + val servers = List(count) { NetworkServer(input.readUTF(), input.readBoolean(), ReportWire.read(input)) } val groups = List(input.readInt().coerceIn(0, MAX_GROUPS)) { ServerGroups.Group(input.readUTF(), readNames(input), readNames(input), unpair(readNames(input)), unpair(readNames(input))) } @@ -145,20 +134,20 @@ object LinkCodec { out.writeUTF(request.product.orEmpty().take(MAX_TEXT)) } - /** Reads a remote request, or returns null when the signature, the version, the time or the action is wrong. */ fun decodeRequest(message: ByteArray, key: ByteArray, now: Instant = Instant.now()): RemoteRequest? = - verified(message, key) { input -> - if (input.readUnsignedByte() != REQUEST_VERSION) return@verified null - val id = UUID(input.readLong(), input.readLong()) - val sentAt = Instant.ofEpochMilli(input.readLong()) - if (!fresh(sentAt, now)) return@verified null - val target = input.readUTF() - val origin = input.readUTF() - val actor = input.readUTF() - val actionName = input.readUTF() - val action = RemoteAction.values().firstOrNull { it.name == actionName } ?: return@verified null - RemoteRequest(id, target, origin, actor, action, input.readUTF().ifEmpty { null }, sentAt) - } + verified(message, key, hmac) { input -> if (input.readUnsignedByte() == REQUEST_VERSION) readRequest(input, now) else null } + + private fun readRequest(input: DataInputStream, now: Instant): RemoteRequest? { + val id = UUID(input.readLong(), input.readLong()) + val sentAt = Instant.ofEpochMilli(input.readLong()) + if (!fresh(sentAt, now)) return null + val target = input.readUTF() + val origin = input.readUTF() + val actor = input.readUTF() + val actionName = input.readUTF() + val action = RemoteAction.values().firstOrNull { it.name == actionName } ?: return null + return RemoteRequest(id, target, origin, actor, action, input.readUTF().ifEmpty { null }, sentAt) + } fun encodeResult(result: RemoteResult, key: ByteArray): ByteArray = signed(key) { out -> out.writeByte(RESULT_VERSION) @@ -170,15 +159,15 @@ object LinkCodec { out.writeUTF(result.text.take(MAX_RESULT_TEXT)) } - /** Reads the answer to a remote request, or returns null when the signature, the version or the time is wrong. */ fun decodeResult(message: ByteArray, key: ByteArray, now: Instant = Instant.now()): RemoteResult? = - verified(message, key) { input -> - if (input.readUnsignedByte() != RESULT_VERSION) return@verified null - val id = UUID(input.readLong(), input.readLong()) - val sentAt = Instant.ofEpochMilli(input.readLong()) - if (!fresh(sentAt, now)) return@verified null - RemoteResult(id, input.readUTF(), input.readBoolean(), input.readUTF(), sentAt) - } + verified(message, key, hmac) { input -> if (input.readUnsignedByte() == RESULT_VERSION) readResult(input, now) else null } + + private fun readResult(input: DataInputStream, now: Instant): RemoteResult? { + val id = UUID(input.readLong(), input.readLong()) + val sentAt = Instant.ofEpochMilli(input.readLong()) + if (!fresh(sentAt, now)) return null + return RemoteResult(id, input.readUTF(), input.readBoolean(), input.readUTF(), sentAt) + } fun encodeCall(call: DataCall, key: ByteArray): ByteArray = signed(key) { out -> out.writeByte(CALL_VERSION) @@ -194,20 +183,20 @@ object LinkCodec { out.write(args) } - /** Reads a question, or returns null when the signature, the version or the time is wrong. */ fun decodeCall(message: ByteArray, key: ByteArray, now: Instant = Instant.now()): DataCall? = - verified(message, key) { input -> - if (input.readUnsignedByte() != CALL_VERSION) return@verified null - val id = UUID(input.readLong(), input.readLong()) - val sentAt = Instant.ofEpochMilli(input.readLong()) - if (!fresh(sentAt, now)) return@verified null - val target = input.readUTF() - val origin = input.readUTF() - val viewer = input.readUTF() - val method = input.readUTF() - val args = String(ByteArray(input.readInt().coerceIn(0, MAX_FRAME_BYTES)).also { input.readFully(it) }, Charsets.UTF_8) - DataCall(id, target, origin, viewer, method, args, sentAt) - } + verified(message, key, hmac) { input -> if (input.readUnsignedByte() == CALL_VERSION) readCall(input, now) else null } + + private fun readCall(input: DataInputStream, now: Instant): DataCall? { + val id = UUID(input.readLong(), input.readLong()) + val sentAt = Instant.ofEpochMilli(input.readLong()) + if (!fresh(sentAt, now)) return null + val target = input.readUTF() + val origin = input.readUTF() + val viewer = input.readUTF() + val method = input.readUTF() + val args = String(ByteArray(input.readInt().coerceIn(0, MAX_FRAME_BYTES)).also { input.readFully(it) }, Charsets.UTF_8) + return DataCall(id, target, origin, viewer, method, args, sentAt) + } fun encodeChunk(chunk: DataChunk, key: ByteArray): ByteArray = signed(key) { out -> out.writeByte(CHUNK_VERSION) @@ -222,64 +211,50 @@ object LinkCodec { out.write(chunk.bytes) } - /** Reads one piece of an answer, or returns null when the signature, the version, the time or the numbers are wrong. */ fun decodeChunk(message: ByteArray, key: ByteArray, now: Instant = Instant.now()): DataChunk? = - verified(message, key) { input -> - if (input.readUnsignedByte() != CHUNK_VERSION) return@verified null - val id = UUID(input.readLong(), input.readLong()) - val sentAt = Instant.ofEpochMilli(input.readLong()) - if (!fresh(sentAt, now)) return@verified null - val to = input.readUTF() - val ok = input.readBoolean() - val index = input.readInt() - val count = input.readInt() - if (count !in 1..DataChunks.MAX_PIECES || index !in 0 until count) return@verified null - val bytes = ByteArray(input.readInt().coerceIn(0, DataChunks.PIECE)).also { input.readFully(it) } - DataChunk(id, to, ok, index, count, bytes, sentAt) - } + verified(message, key, hmac) { input -> if (input.readUnsignedByte() == CHUNK_VERSION) readChunk(input, now) else null } - private fun fresh(sentAt: Instant, now: Instant): Boolean = Math.abs(Duration.between(sentAt, now).toMillis()) <= TOLERANCE.toMillis() + private fun readChunk(input: DataInputStream, now: Instant): DataChunk? { + val id = UUID(input.readLong(), input.readLong()) + val sentAt = Instant.ofEpochMilli(input.readLong()) + if (!fresh(sentAt, now)) return null + val to = input.readUTF() + val ok = input.readBoolean() + val index = input.readInt() + val count = input.readInt() + if (count !in 1..DataChunks.MAX_PIECES || index !in 0 until count) return null + val bytes = ByteArray(input.readInt().coerceIn(0, DataChunks.PIECE)).also { input.readFully(it) } + return DataChunk(id, to, ok, index, count, bytes, sentAt) + } + + fun decodeFrame(message: ByteArray, key: ByteArray, now: Instant = Instant.now()): LinkFrame? = decodeFrame(message, key, now, hmac) - private fun writeReport(out: DataOutputStream, report: LinkReport, limit: Int) { - out.writeLong(report.sentAt.toEpochMilli()) - out.writeUTF(report.platform.take(MAX_TEXT)) - out.writeUTF(report.libraryVersion.take(MAX_TEXT)) - out.writeInt(report.players) - val plugins = report.plugins.take(limit) - out.writeInt(plugins.size) - plugins.forEach { - out.writeUTF(it.product.take(MAX_TEXT)) - out.writeUTF(it.version.take(MAX_TEXT)) - out.writeUTF(it.latest.orEmpty().take(MAX_TEXT)) - out.writeUTF(it.state.take(MAX_TEXT)) + internal fun decodeFrame(message: ByteArray, key: ByteArray, now: Instant, signer: FrameSigner): LinkFrame? = + verified(message, key, signer) { input -> + when (input.readUnsignedByte()) { + VERSION -> ReportWire.read(input).takeIf { fresh(it.sentAt, now) }?.let(LinkFrame::Report) + REQUEST_VERSION -> readRequest(input, now)?.let(LinkFrame::Request) + RESULT_VERSION -> readResult(input, now)?.let(LinkFrame::Result) + CALL_VERSION -> readCall(input, now)?.let(LinkFrame::Call) + CHUNK_VERSION -> readChunk(input, now)?.let(LinkFrame::Chunk) + else -> null + } } - } - private fun readReport(input: DataInputStream): LinkReport { - val sentAt = Instant.ofEpochMilli(input.readLong()) - val platform = input.readUTF() - val library = input.readUTF() - val players = input.readInt() - val count = input.readInt().coerceIn(0, MAX_PLUGINS) - val plugins = List(count) { LinkPlugin(input.readUTF(), input.readUTF(), input.readUTF().ifEmpty { null }, input.readUTF()) } - return LinkReport(platform, library, players, plugins, sentAt) - } + private fun fresh(sentAt: Instant, now: Instant): Boolean = Math.abs(Duration.between(sentAt, now).toMillis()) <= TOLERANCE.toMillis() private fun signed(key: ByteArray, write: (DataOutputStream) -> Unit): ByteArray { val body = ByteArrayOutputStream() DataOutputStream(body).use(write) val bytes = body.toByteArray() - return bytes + sign(bytes, key) + return bytes + hmac.sign(bytes, key) } - private fun verified(message: ByteArray, key: ByteArray, read: (DataInputStream) -> T?): T? { + private fun verified(message: ByteArray, key: ByteArray, signer: FrameSigner, read: (DataInputStream) -> T?): T? { if (message.size <= MAC_BYTES) return null val body = message.copyOfRange(0, message.size - MAC_BYTES) val mac = message.copyOfRange(message.size - MAC_BYTES, message.size) - if (!MessageDigest.isEqual(mac, sign(body, key))) return null + if (!MessageDigest.isEqual(mac, signer.sign(body, key))) return null return runCatching { DataInputStream(ByteArrayInputStream(body)).use(read) }.getOrNull() } - - private fun sign(bytes: ByteArray, key: ByteArray): ByteArray = - Mac.getInstance(MAC_ALGORITHM).apply { init(SecretKeySpec(key, MAC_ALGORITHM)) }.doFinal(bytes) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkFrame.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkFrame.kt new file mode 100644 index 000000000..651ff093f --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkFrame.kt @@ -0,0 +1,25 @@ +package org.pnfolder.pnlibrary.core.link.wire + +import org.pnfolder.pnlibrary.core.link.remote.DataCall +import org.pnfolder.pnlibrary.core.link.remote.DataChunk +import org.pnfolder.pnlibrary.core.link.remote.RemoteRequest +import org.pnfolder.pnlibrary.core.link.remote.RemoteResult +import org.pnfolder.pnlibrary.core.link.report.LinkReport + +/** What a game server may send to the proxy once its signature has checked out. */ +sealed interface LinkFrame { + /** A server report. */ + class Report(val report: LinkReport) : LinkFrame + + /** A remote update request for another server or the proxy. */ + class Request(val request: RemoteRequest) : LinkFrame + + /** The answer to a remote update request. */ + class Result(val result: RemoteResult) : LinkFrame + + /** A data question for another server or the proxy. */ + class Call(val call: DataCall) : LinkFrame + + /** One piece of the answer to a data question. */ + class Chunk(val chunk: DataChunk) : LinkFrame +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkSecret.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkSecret.kt new file mode 100644 index 000000000..fa81a34d1 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkSecret.kt @@ -0,0 +1,47 @@ +package org.pnfolder.pnlibrary.core.link.wire + +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardOpenOption +import java.nio.file.attribute.PosixFilePermissions +import java.security.SecureRandom +import java.util.Base64 + +// The proxy creates the file; game servers only read it, so the link stays off until the admin copies it over. +object LinkSecret { + const val FILE = "link.key" + private const val KEY_BYTES = 32 + + fun read(folder: Path): ByteArray? = runCatching { + val text = String(Files.readAllBytes(folder.resolve(FILE)), Charsets.UTF_8).removePrefix(BOM).trim() + Base64.getDecoder().decode(text).takeIf { it.size >= KEY_BYTES } + }.getOrNull() + + // A file that exists but is unreadable is left alone — overwriting it would silently break all servers that have the old key. + fun readOrCreate(folder: Path, warn: (String) -> Unit = {}): ByteArray? { + val path = folder.resolve(FILE) + if (Files.exists(path)) { + return read(folder) ?: null.also { warn("$FILE exists but holds no valid key; the link stays off until it is fixed or deleted") } + } + val key = ByteArray(KEY_BYTES).also(SecureRandom()::nextBytes) + return runCatching { + Files.createDirectories(folder) + create(path, (Base64.getEncoder().encodeToString(key) + '\n').toByteArray(Charsets.UTF_8)) + key + }.getOrNull() + } + + // Owner-only from the first byte, so the key is never readable by others between creation and chmod. + private fun create(path: Path, content: ByteArray) { + val posix = path.fileSystem.supportedFileAttributeViews().contains("posix") + if (posix) { + val owner = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")) + Files.createFile(path, owner) + Files.write(path, content, StandardOpenOption.WRITE) + } else { + Files.write(path, content, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE) + } + } + + private const val BOM = "\uFEFF" +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/ReportWire.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/ReportWire.kt new file mode 100644 index 000000000..7d3ae36d0 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/link/wire/ReportWire.kt @@ -0,0 +1,37 @@ +package org.pnfolder.pnlibrary.core.link.wire + +import org.pnfolder.pnlibrary.core.link.report.LinkPlugin +import org.pnfolder.pnlibrary.core.link.report.LinkReport +import java.io.DataInputStream +import java.io.DataOutputStream +import java.time.Instant + +/** The byte layout of a [LinkReport], shared by server reports and network maps. */ +internal object ReportWire { + private const val MAX_TEXT = 200 + + fun write(out: DataOutputStream, report: LinkReport, limit: Int) { + out.writeLong(report.sentAt.toEpochMilli()) + out.writeUTF(report.platform.take(MAX_TEXT)) + out.writeUTF(report.libraryVersion.take(MAX_TEXT)) + out.writeInt(report.players) + val plugins = report.plugins.take(limit) + out.writeInt(plugins.size) + plugins.forEach { + out.writeUTF(it.product.take(MAX_TEXT)) + out.writeUTF(it.version.take(MAX_TEXT)) + out.writeUTF(it.latest.orEmpty().take(MAX_TEXT)) + out.writeUTF(it.state.take(MAX_TEXT)) + } + } + + fun read(input: DataInputStream): LinkReport { + val sentAt = Instant.ofEpochMilli(input.readLong()) + val platform = input.readUTF() + val library = input.readUTF() + val players = input.readInt() + val count = input.readInt().coerceIn(0, LinkCodec.MAX_PLUGINS) + val plugins = List(count) { LinkPlugin(input.readUTF(), input.readUTF(), input.readUTF().ifEmpty { null }, input.readUTF()) } + return LinkReport(platform, library, players, plugins, sentAt) + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticCapture.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticCapture.kt index 7212bb4d7..384076c56 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticCapture.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticCapture.kt @@ -1,19 +1,22 @@ package org.pnfolder.pnlibrary.core.logging import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.common.concurrent.FailureThrottle import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.spi.platform.PlatformLogging import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership +/** Wraps platform logging: records warnings and errors into the incident buffer and the journal while passing output through. */ internal class DiagnosticCapture( private val ownership: PlatformOwnership, private val native: PlatformLogging, private val incidents: DiagnosticLogBuffer? = null, - private val journal: ((Any, LogLevel, String, Throwable?) -> Unit)? = null, + private val journal: ((Any, LogLevel, String, Throwable?, Map) -> Unit)? = null, private val onError: (Any, String, Throwable) -> Unit = { _, _, _ -> }, ) : PlatformLogging { private val emitting = ThreadLocal() private val echoes = java.util.concurrent.ConcurrentHashMap() + private val stageFailures = FailureThrottle() private companion object { const val ECHO_WINDOW_NANOS = 2_000_000_000L @@ -21,14 +24,15 @@ internal class DiagnosticCapture( } override fun log(owner: Any, level: LogLevel, message: String, error: Throwable?) = - write(owner, level, message, error, true) + write(owner, level, message, error) - /** - * Writes one line. With [record] `false` it is console only and never reaches the black box; a [LogLevel.DEBUG] - * line is the opposite and never reaches the console. - */ - fun write(owner: Any, level: LogLevel, message: String, error: Throwable? = null, record: Boolean = true) { - val result = if (record) capture(owner, level, message, error, true) else null + /** Writes to the journal and incident buffer at [level] without emitting to the console. */ + fun captureOnly(owner: Any, level: LogLevel, message: String, error: Throwable? = null) { + capture(owner, level, message, error, true, emptyMap()) + } + + fun write(owner: Any, level: LogLevel, message: String, error: Throwable? = null, record: Boolean = true, context: Map = emptyMap()) { + val result = if (record) capture(owner, level, message, error, true, context) else null if (level == LogLevel.DEBUG) return val output = when { result == null || result.emitOriginal -> message @@ -36,7 +40,7 @@ internal class DiagnosticCapture( else -> return } rememberEcho(level, output) - emit { native.log(owner, level, ConsoleStyle.decorate(level, output), if (output == message) error else null) } + emit { native.log(owner, level, LogLevelMarks.decorate(level, output), if (output == message) error else null) } } override fun console(owner: Any, message: String) = emit { native.console(owner, message) } @@ -50,7 +54,7 @@ internal class DiagnosticCapture( private fun observeLine(owner: Any, level: LogLevel, message: String, error: Throwable?, includeJournal: Boolean) { if (emitting.get() == true || echoedRecently(level, message)) return - capture(owner, level, message, error, includeJournal) + capture(owner, level, message, error, includeJournal, emptyMap()) } /** A native logger may echo our line on another thread, where the thread-local guard cannot see it. */ @@ -65,10 +69,32 @@ internal class DiagnosticCapture( if (echoes.size <= ECHO_LIMIT) echoes["$level|$message"] = now } - private fun capture(owner: Any, level: LogLevel, message: String, error: Throwable?, includeJournal: Boolean): DiagnosticLogBuffer.CaptureResult? { - if (includeJournal) runCatchingNonFatal { journal?.invoke(owner, level, message, error) } - if (error != null && level >= LogLevel.ERROR) runCatchingNonFatal { onError(owner, message, error) } - return runCatchingNonFatal { incidents?.record(ownership, owner, level, message, error) }.getOrNull() + private fun capture( + owner: Any, + level: LogLevel, + message: String, + error: Throwable?, + includeJournal: Boolean, + context: Map, + ): DiagnosticLogBuffer.CaptureResult? { + if (includeJournal) guarded(owner, "journal") { journal?.invoke(owner, level, message, error, context) } + // An error logged as text only still has to reach the error tracker, which takes throwables. + if (level >= LogLevel.ERROR) guarded(owner, "error report") { onError(owner, message, error ?: LoggedError(message)) } + return guarded(owner, "incident buffer") { incidents?.record(ownership, owner, level, message, error) } + } + + /** + * A broken stage must not stop the line or the other stages, but it must not stay unseen either. The report goes to + * the console only: recording it would run the broken stage again. + */ + private inline fun guarded(owner: Any, stage: String, action: () -> T): T? = + runCatchingNonFatal(action).onFailure { reportStageFailure(owner, stage, it) }.getOrNull() + + private fun reportStageFailure(owner: Any, stage: String, error: Throwable) { + if (!stageFailures.shouldReport(stage)) return + val message = "pnLibrary could not pass a log line to the $stage: ${error.javaClass.simpleName}: ${error.message}" + rememberEcho(LogLevel.ERROR, message) + emit { native.log(owner, LogLevel.ERROR, LogLevelMarks.decorate(LogLevel.ERROR, message), error) } } private inline fun emit(action: () -> Unit) { @@ -78,4 +104,7 @@ internal class DiagnosticCapture( if (previous == null) emitting.remove() else emitting.set(previous) } } + + /** Stands in for the missing exception of an error logged as plain text. */ + private class LoggedError(message: String) : RuntimeException(message) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticLogBuffer.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticLogBuffer.kt index 1aee0e85b..e1ae9ab3b 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticLogBuffer.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticLogBuffer.kt @@ -2,8 +2,11 @@ package org.pnfolder.pnlibrary.core.logging import org.pnfolder.pnlibrary.api.logging.LogLevel import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticRedactor -import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticThrowables +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticRedactor +import org.pnfolder.pnlibrary.core.diagnostics.redaction.fingerprint +import org.pnfolder.pnlibrary.core.diagnostics.redaction.originData +import org.pnfolder.pnlibrary.core.diagnostics.redaction.originFrame +import org.pnfolder.pnlibrary.core.diagnostics.redaction.significantCause import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership import java.io.PrintWriter import java.io.StringWriter @@ -11,7 +14,28 @@ import java.time.Instant import java.util.ArrayDeque import java.util.LinkedHashMap -internal class DiagnosticLogBuffer(private val capacity: Int = 2_000) { +/** + * Bounded in-memory buffer of logged incidents that collapses repeated occurrences of the same problem. + * + * [redact] and [fingerprintOf] are the expensive steps (a dozen regexes, SHA-256), so they run only the first time + * a raw combination of plugin, level, text and error shape is seen; a repeat is found by that raw key alone. + */ +internal class DiagnosticLogBuffer( + private val capacity: Int = 2_000, + private val redact: (String) -> String = DiagnosticRedactor()::redact, + private val fingerprintOf: (List, String, Throwable?) -> String = { context, message, error -> error.fingerprint(context, message) }, +) { + /** What a record looks like before redaction; equal keys always redact and fingerprint to the same incident. */ + private data class RawKey( + val plugin: String, + val level: LogLevel, + val message: String, + val errorClass: String?, + val errorMessage: String?, + val frameClass: String?, + val frameMethod: String?, + ) + internal data class CaptureResult(val emitOriginal: Boolean, val summary: String? = null) private data class Occurrence(val timeUtc: String, val thread: String) @@ -35,6 +59,9 @@ internal class DiagnosticLogBuffer(private val capacity: Int = 2_000) { private val incidents = LinkedHashMap() private val redactor = DiagnosticRedactor() + private val incidentOfRaw = object : LinkedHashMap(16, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry): Boolean = size > RAW_KEYS_LIMIT + } private var timelineEntryCount = 0 @Volatile private var changeListener: ((List>) -> Unit)? = null @@ -59,15 +86,26 @@ internal class DiagnosticLogBuffer(private val capacity: Int = 2_000) { val nowMs = System.currentTimeMillis() val now = Instant.ofEpochMilli(nowMs).toString() - val plugin = redactor.redact(platform.ownerDetails(owner)["name"] ?: owner.javaClass.simpleName).take(96) - val safeMessage = redactor.redact(message).take(MAX_MESSAGE_CHARS) - val fingerprint = fingerprint(plugin, level, safeMessage, error) + val rawPlugin = platform.ownerDetails(owner)["name"] ?: owner.javaClass.simpleName + val rawKey = rawKeyOf(rawPlugin, level, message, error) + val known = incidentOfRaw[rawKey]?.let(incidents::get) + if (known != null) return repeatIncident(known, known.plugin, nowMs, now) + + val plugin = redact(rawPlugin).take(96) + val safeMessage = redact(message).take(MAX_MESSAGE_CHARS) + val fingerprint = fingerprintOf(listOf(plugin, level.name), safeMessage, error) + incidentOfRaw[rawKey] = fingerprint val existing = incidents[fingerprint] - if (existing == null) return startIncident(fingerprint, level, plugin, safeMessage, error, nowMs, now) return repeatIncident(existing, plugin, nowMs, now) } + private fun rawKeyOf(plugin: String, level: LogLevel, message: String, error: Throwable?): RawKey { + val significant = error.significantCause() + val frame = error.originFrame() + return RawKey(plugin, level, message, significant?.javaClass?.name, significant?.message, frame?.className, frame?.methodName) + } + private fun startIncident( fingerprint: String, level: LogLevel, @@ -84,7 +122,7 @@ internal class DiagnosticLogBuffer(private val capacity: Int = 2_000) { plugin = plugin, message = message, exceptionType = error?.javaClass?.name, - origin = error?.let(DiagnosticThrowables::origin), + origin = error?.originData(), fullError = completeError, consoleBlock = consoleBlock(now, level, message, completeError), firstSeenUtc = now, @@ -169,9 +207,6 @@ internal class DiagnosticLogBuffer(private val capacity: Int = 2_000) { changeListener?.let { listener -> runCatchingNonFatal { listener(snapshot()) } } } - private fun fingerprint(plugin: String, level: LogLevel, message: String, error: Throwable?): String = - DiagnosticThrowables.fingerprint(listOf(plugin, level.name), message, error) - private fun fullStackTrace(error: Throwable): String { val writer = StringWriter() error.printStackTrace(PrintWriter(writer)) @@ -198,6 +233,7 @@ internal class DiagnosticLogBuffer(private val capacity: Int = 2_000) { companion object { private const val MAX_MESSAGE_CHARS = 4_096 + private const val RAW_KEYS_LIMIT = 8_192 private const val MAX_ERROR_CHARS = 1_048_576 private const val MAX_TIMELINE_OCCURRENCES = 100_000 private const val SUMMARY_INTERVAL_MS = 5 * 60 * 1_000L diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/ConsoleStyle.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/LogLevelMarks.kt similarity index 96% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/ConsoleStyle.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/LogLevelMarks.kt index 6d9b70005..9dce46ccf 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/ConsoleStyle.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/LogLevelMarks.kt @@ -6,7 +6,7 @@ import org.pnfolder.pnlibrary.api.logging.LogLevel * Marks lines the native logger cannot tell apart: it has no success level, so a success would look like plain info. * Warnings and errors already carry the platform's own level and colour. */ -object ConsoleStyle { +object LogLevelMarks { const val SUCCESS_MARK = "[OK] " const val CRITICAL_MARK = "[CRITICAL] " diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/ModuleLogging.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/ModuleLogging.kt index 13912a9f2..da0eed0b8 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/ModuleLogging.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/logging/ModuleLogging.kt @@ -6,7 +6,7 @@ import org.pnfolder.pnlibrary.api.logging.LoggingService import org.pnfolder.pnlibrary.api.logging.MessageBox import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.core.ui.ConsoleStyle +import org.pnfolder.pnlibrary.core.text.ConsoleStyle import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import org.pnfolder.pnlibrary.spi.platform.PlatformLogging import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership @@ -19,15 +19,18 @@ internal class ModuleLogging( private val diagnostics: PlatformSnapshotProvider, private val identity: PlatformIdentity, private val diagnosticLogs: DiagnosticLogBuffer? = null, - private val journal: ((Any, LogLevel, String, Throwable?) -> Unit)? = null, + private val journal: ((Any, LogLevel, String, Throwable?, Map) -> Unit)? = null, private val capture: DiagnosticCapture = DiagnosticCapture(ownership, logging, diagnosticLogs, journal), ) : LoggingService { private data class Row(val status: String, val label: String, val detail: String, val error: Throwable?) private enum class MessageKind { GENERIC, ENABLED, DISABLED } override fun logger(owner: Any, name: String): PnLogger = object : PnLogger { - override fun log(level: LogLevel, message: String, error: Throwable?, record: Boolean) = - capture.write(owner, level, "[$name] $message", error, record) + override fun log(level: LogLevel, message: String, error: Throwable?, context: Map) = + capture.write(owner, level, "[$name] $message", error, true, context) + + override fun record(level: LogLevel, message: String, error: Throwable?) = + capture.captureOnly(owner, level, "[$name] $message", error) } override fun box(owner: Any, title: String): MessageBox = diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/HistoryScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/HistoryScreens.kt deleted file mode 100644 index b079ad0b4..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/HistoryScreens.kt +++ /dev/null @@ -1,123 +0,0 @@ -package org.pnfolder.pnlibrary.core.menu - -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.updates.UpdateState -import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup -import org.pnfolder.pnlibrary.api.updates.backup.UpdateHistoryEntry -import org.pnfolder.pnlibrary.core.updates.catalog.CatalogLabels - -internal class HistoryScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { - fun history(player: MenuViewer, product: String?, page: Int) { - val normalized = product?.lowercase() - data.historyCount(normalized).thenCompose { total -> - data.historyPage(page + 1, normalized).thenApply { total to it } - }.whenComplete { result, error -> - sync { - if (!player.online) return@sync - val (total, entries) = result ?: (0 to emptyList()) - val back: (MenuViewer) -> Unit = if (product == null) { who -> routes.home(who) } else { who -> routes.card(who, product) } - val rows = if (error != null) { - emptyList() - } else { - entries.map { entry -> - val item = historyItem(entry, NOTE_PREVIEW_LINES, Style.left("подробности")) - Row(item, go { historyEntry(it, entry) { who -> history(who, product, page) } }) - } - } - val title = if (product == null) "История" else "История $product" - list(player, title, rows, page, HISTORY_PAGE, { who, to -> history(who, product, to) }, back, "Записей пока нет", total) - } - } - } - - fun backups(player: MenuViewer, page: Int) { - data.backups().whenComplete { all, error -> - sync { - if (!player.online) return@sync - val rows = if (error != null) { - emptyList() - } else { - all.sortedByDescending { it.createdAt }.map { backup -> - Row(backupItem(backup, Style.left("выбрать откат")), go { backupChoice(it, backup) }) - } - } - list(player, "Резервные копии", rows, page, PAGE_SIZE, { who, to -> backups(who, to) }, { routes.home(it) }, "Резервных копий нет") - } - } - } - - private fun backupChoice(player: MenuViewer, backup: UpdateBackup) { - val builder = frame(Menus.chest(title("Откат")).rows(SMALL_ROWS), SMALL_ROWS) - builder.slot(4, backupItem(backup)) - val plain = Style.lore( - listOf("Вернутся сохранённые JAR.", "Конфигурации не изменятся.", "Применится после перезапуска."), - emptyList(), Style.left("откатить"), - ) - builder.button(11, icon(Icons.ROLLBACK, "TNT", "Откатить плагины", plain, danger = true), go { who -> - allowed(who, ROLLBACK) { rollback(who, backup, restoreConfigurations = false) } - }) - if (backup.configurationFiles > 0) { - val full = Style.lore( - listOf("Вернутся JAR и файлы настроек: ${backup.configurationFiles}.", "Применится после перезапуска."), - emptyList(), Style.left("откатить"), - ) - builder.button(13, icon(Icons.ROLLBACK, "TNT", "Откатить плагины и настройки", full, danger = true), go { who -> - allowed(who, ROLLBACK) { rollback(who, backup, restoreConfigurations = true) } - }) - } - builder.button(SMALL_BACK, backItem("Отмена"), go { backups(it, 0) }) - show(player, builder.build()) - } - - private fun historyEntry(player: MenuViewer, entry: UpdateHistoryEntry, back: (MenuViewer) -> Unit) { - val builder = frame(Menus.chest(title("Запись истории")).rows(DETAIL_ROWS), DETAIL_ROWS) - builder.slot(4, historyItem(entry, NOTE_LINES)) - entry.changes.take(CHANGE_BUTTONS).forEachIndexed { index, change -> - val product = change.product.value - val known = data.snapshot(product) != null - val lore = Style.lore( - listOf("Версия изменилась."), - listOf("Было" to "${change.from}", "Стало" to "${change.to}"), - *if (known) arrayOf(Style.left("открыть карточку")) else emptyArray(), - ) - val stack = icon(Icons.PLUGIN, "PAPER", product, lore, muted = !known) - if (known) builder.button(CHANGE_FIRST + index, stack, go { routes.card(it, product) }) else builder.slot(CHANGE_FIRST + index, stack) - } - builder.button(DETAIL_BACK, backItem(), go { back(it) }) - show(player, builder.build()) - } - - private fun rollback(player: MenuViewer, backup: UpdateBackup, restoreConfigurations: Boolean) { - player.close() - data.rollback(backup.id, restoreConfigurations, player.actor).whenComplete { _, error -> - sync { - if (!player.online) return@sync - if (error != null) tell(player, ChatTone.FAILURE, "Не удалось подготовить откат.", reason(error)) - else tell(player, ChatTone.SUCCESS, "Резервный набор подготовлен.", "Полностью перезапустите сервер, чтобы применить его.") - } - } - } - - private fun historyItem(entry: UpdateHistoryEntry, noteLines: Int, vararg clicks: String): ItemSpec { - val failed = entry.state == UpdateState.FAILED - val parameters = buildList { - add("Когда" to time(entry.occurredAt)) - add("Кто" to entry.actor.name) - entry.changes.forEach { add(it.product.value to "${it.from} » ${it.to}") } - } - val note = entry.message?.let { wrap(it, limit = noteLines) }.orEmpty() - .map { if (failed) Style.danger(it) else Style.description(it) } - val title = "${CatalogLabels.operationLabel(entry.operation)}: ${CatalogLabels.stateLabel(entry.state)}" - return icon(null, if (failed) "BARRIER" else "PAPER", title, Style.lore(emptyList(), parameters, *clicks, extra = note), danger = failed) - } - - private fun backupItem(backup: UpdateBackup, vararg clicks: String): ItemSpec { - val parameters = buildList { - backup.createdAt?.let { add("Создана" to time(it)) } - backup.components.forEach { add(it.product.value to "${it.backupVersion ?: "?"} (было ${it.updatedVersion ?: "?"})") } - if (backup.configurationFiles > 0) add("Файлов настроек" to "${backup.configurationFiles}") - } - val lore = Style.lore(emptyList(), parameters, *clicks) - return icon(Icons.BACKUPS, "CHEST", "Резервный набор", lore) - } -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/LibraryMenu.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/LibraryMenu.kt index 9f17820d3..479bc822a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/LibraryMenu.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/LibraryMenu.kt @@ -1,5 +1,7 @@ package org.pnfolder.pnlibrary.core.menu +import org.pnfolder.pnlibrary.core.menu.data.MenuData + /** * The inventory menu of `/pn gui`: everything the update commands do, on several connected screens. * @@ -21,4 +23,7 @@ class LibraryMenu( fun home(player: MenuViewer) = router.home(player) fun open(player: MenuViewer) = router.open(player) + + /** Opens the list of values of the choice setting [key], only those that contain [filter]; for `/pn settings pick`. */ + fun pickSetting(player: MenuViewer, key: String, filter: String) = router.pick(player, key, filter) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/LocalMenuData.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/LocalMenuData.kt deleted file mode 100644 index f7387cddd..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/LocalMenuData.kt +++ /dev/null @@ -1,156 +0,0 @@ -package org.pnfolder.pnlibrary.core.menu - -import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.events.EventDay -import org.pnfolder.pnlibrary.api.events.EventDescription -import org.pnfolder.pnlibrary.api.events.EventInfo -import org.pnfolder.pnlibrary.api.events.EventTrace -import org.pnfolder.pnlibrary.api.events.ListenerInfo -import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup -import org.pnfolder.pnlibrary.api.updates.backup.UpdateHistoryEntry -import org.pnfolder.pnlibrary.core.journal.JournalDetail -import org.pnfolder.pnlibrary.core.journal.JournalGroup -import org.pnfolder.pnlibrary.core.lifecycle.cancelTask -import org.pnfolder.pnlibrary.core.lifecycle.journalDetail -import org.pnfolder.pnlibrary.core.lifecycle.journalGroups -import org.pnfolder.pnlibrary.core.lifecycle.placeholderInfos -import org.pnfolder.pnlibrary.core.lifecycle.runTaskNow -import org.pnfolder.pnlibrary.core.lifecycle.statsSnapshot -import org.pnfolder.pnlibrary.core.lifecycle.taskSnapshots -import org.pnfolder.pnlibrary.core.link.ServerGroups -import org.pnfolder.pnlibrary.core.placeholders.PlaceholderInfo -import org.pnfolder.pnlibrary.core.stats.StatsSnapshot -import org.pnfolder.pnlibrary.core.tasks.TaskControl -import org.pnfolder.pnlibrary.core.updates.catalog.UpdateStatusMessages -import java.time.Duration -import java.time.Instant -import java.util.UUID -import java.util.concurrent.CompletionStage - -/** - * The facts of the library on this server. It is the source of this server's own menu, and the one that answers when - * another server asks over the link. - * - * @param library this server's library - * @param directory the plugins of this platform - * @param run runs a chat command for a viewer and returns what it printed - * @param groups the groups of servers, on a proxy; null on a game server - */ -class LocalMenuData( - private val library: PnLibrary, - private val directory: PluginDirectory, - private val run: (ViewerInfo, String) -> List = { _, _ -> emptyList() }, - private val groups: ServerGroups? = null, -) : MenuData { - private val bus get() = library.events.inspector - - override fun version(): String = library.version - - override fun snapshots(): List = library.updates.all().map { it.snapshot }.sortedBy { it.product.lowercase() } - - override fun snapshot(product: String): UpdateSnapshot? = library.updates.get(product)?.snapshot - - override fun plugins(): List = library.plugins.all().map { registration -> - val owner = directory.owner(registration.owner) - PluginRow(owner?.name ?: registration.owner.javaClass.simpleName, owner?.version, registration.all().size) - } - - override fun plan(): PlanInfo? = library.updates.currentPlan().orElse(null)?.let { plan -> - PlanInfo(plan.state, plan.plan?.changes?.isNotEmpty() == true, plan.blockers.map { UpdateStatusMessages.blocker(it) }) - } - - override fun heldUntil(product: String): Instant? = library.updates.heldUntil(product) - - override fun historyCount(product: String?): CompletionStage = library.updates.historyCount(product) - - override fun historyPage(page: Int, product: String?): CompletionStage> = library.updates.historyPage(page, product) - - override fun backups(): CompletionStage> = library.updates.backups() - - override fun checkAll(actor: UpdateActor): CompletionStage = library.updates.checkNow(actor).thenApply { true } - - override fun checkOne(product: String, actor: UpdateActor) { - library.updates.get(product)?.checkNow() - } - - override fun setAutomatic(product: String, enabled: Boolean, actor: UpdateActor): CompletionStage = - library.updates.setAutomaticDownload(product, enabled, actor).thenApply { true } - - override fun setChannel(product: String, channel: UpdateChannel?, actor: UpdateActor): CompletionStage = - library.updates.setChannel(product, channel, actor).thenApply { true } - - override fun setHeld(product: String, duration: Duration?, actor: UpdateActor): CompletionStage = - library.updates.setHeld(product, duration, actor).thenApply { true } - - override fun rollback(id: UUID, restoreConfigurations: Boolean, actor: UpdateActor): CompletionStage = - library.updates.rollback(id, restoreConfigurations, actor).thenApply { true } - - override fun journalGroups(level: String?, hours: Int, limit: Int): List = library.journalGroups(level, hours, limit) - - override fun journalDetail(id: String): JournalDetail? = library.journalDetail(id) - - override fun tasks(): List = library.taskSnapshots() - - override fun runTask(id: String): TaskControl = library.runTaskNow(id) - - override fun cancelTask(id: String): TaskControl = library.cancelTask(id) - - override fun stats(): StatsSnapshot = library.statsSnapshot() - - override fun placeholders(): List = library.placeholderInfos() - - override fun events(): List = bus.events() - - override fun listeners(): List = bus.listeners() - - override fun eventHistory(eventType: String?): List = bus.history(eventType) - - override fun eventHistoryDays(): Int = bus.historyDays - - override fun tracedEvents(): List = bus.tracedEvents() - - override fun traces(): List = bus.traces() - - override fun clearTraces() = bus.clearTraces() - - override fun setTracing(eventType: String, enabled: Boolean) { - val type = bus.eventType(eventType) ?: return - if (enabled) bus.enableTracing(type) else bus.disableTracing(type) - } - - override fun exportEventHistory(json: Boolean): String? = bus.exportHistory(json)?.toString() - - override fun eventAbout(eventType: String): EventAbout? { - val type = bus.eventType(eventType) ?: return null - val about = type.getAnnotation(EventDescription::class.java) - return EventAbout(about?.purpose.orEmpty(), about?.usage.orEmpty(), directory.ownerOf(type)) - } - - override fun ownerNamed(name: String): OwnerInfo? = directory.ownerNamed(name) - - override fun groups(): List = groups?.all().orEmpty() - - override fun editGroup(edit: GroupEdit): Boolean { - val store = groups ?: return false - val server = edit.server.orEmpty() - val plugin = edit.plugin.orEmpty() - return when (edit.op) { - GroupOp.CREATE -> store.create(edit.group) - GroupOp.DELETE -> store.delete(edit.group) - GroupOp.ADD_SERVER -> store.edit(edit.group) { it.addServer(server) } - GroupOp.REMOVE_SERVER -> store.edit(edit.group) { it.removeServer(server) } - GroupOp.ADD_PLUGIN -> store.edit(edit.group) { it.addPlugin(plugin) } - GroupOp.REMOVE_PLUGIN -> store.edit(edit.group) { it.removePlugin(plugin) } - GroupOp.NEED -> store.edit(edit.group) { it.with(server, plugin, true) } - GroupOp.SKIP -> store.edit(edit.group) { it.with(server, plugin, false) } - GroupOp.RESET -> store.edit(edit.group) { it.reset(server) } - } - } - - override fun command(viewer: ViewerInfo, line: String): List = run(viewer, line) -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuData.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuData.kt deleted file mode 100644 index 446ef8c45..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuData.kt +++ /dev/null @@ -1,151 +0,0 @@ -package org.pnfolder.pnlibrary.core.menu - -import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.events.EventDay -import org.pnfolder.pnlibrary.api.events.EventInfo -import org.pnfolder.pnlibrary.api.events.EventTrace -import org.pnfolder.pnlibrary.api.events.ListenerInfo -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState -import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup -import org.pnfolder.pnlibrary.api.updates.backup.UpdateHistoryEntry -import org.pnfolder.pnlibrary.core.journal.JournalDetail -import org.pnfolder.pnlibrary.core.journal.JournalGroup -import org.pnfolder.pnlibrary.core.link.ServerGroups -import org.pnfolder.pnlibrary.core.placeholders.PlaceholderInfo -import org.pnfolder.pnlibrary.core.stats.StatsSnapshot -import org.pnfolder.pnlibrary.core.tasks.TaskControl -import java.time.Duration -import java.time.Instant -import java.util.UUID -import java.util.concurrent.CompletionStage - -data class PlanInfo(val state: UpdateState, val hasChanges: Boolean, val blockers: List) - -data class PluginRow(val name: String, val version: String?, val modules: Int) - -data class EventAbout(val purpose: String, val usage: String, val owner: OwnerInfo?) - -data class ViewerInfo(val name: String, val permissions: Set) - -enum class GroupOp { - CREATE, - - DELETE, - - ADD_SERVER, - - REMOVE_SERVER, - - ADD_PLUGIN, - - REMOVE_PLUGIN, - - NEED, - - /** One server of the group does not need a plugin, whatever the rest do. */ - SKIP, - - RESET, -} - -data class GroupEdit(val op: GroupOp, val group: String, val server: String? = null, val plugin: String? = null) - -/** - * Everything the menu reads from a server and everything it asks a server to do. - * - * The menu is always built by the server the player stands on. It asks a [MenuData] for the facts: this server's own - * library for its own menu, or another server's library, reached over the link, for the menu of that server. A proxy - * therefore draws nothing; it answers these calls. - * - * Methods that return a [CompletionStage] finish later; the others answer at once on this server and may take a moment - * on another one, so the menu calls them away from the server thread. - */ -interface MenuData { - fun version(): String - - fun snapshots(): List - - /** The update state of one plugin, or null when it did not register. */ - fun snapshot(product: String): UpdateSnapshot? - - fun plugins(): List - - /** The current update plan, or null when there is none. */ - fun plan(): PlanInfo? - - /** Until when updates of [product] are paused, or null. */ - fun heldUntil(product: String): Instant? - - fun historyCount(product: String?): CompletionStage - - fun historyPage(page: Int, product: String?): CompletionStage> - - fun backups(): CompletionStage> - - fun checkAll(actor: UpdateActor): CompletionStage - - /** Asks the catalog of one plugin for a new version; it does not wait for the answer. */ - fun checkOne(product: String, actor: UpdateActor) - - fun setAutomatic(product: String, enabled: Boolean, actor: UpdateActor): CompletionStage - - /** Sets the update channel of [product]; null returns it to the default. */ - fun setChannel(product: String, channel: UpdateChannel?, actor: UpdateActor): CompletionStage - - /** Pauses updates of [product] for [duration]; null lifts the pause. */ - fun setHeld(product: String, duration: Duration?, actor: UpdateActor): CompletionStage - - fun rollback(id: UUID, restoreConfigurations: Boolean, actor: UpdateActor): CompletionStage - - /** The journal groups of the last [hours] hours; [level] is `info`, `warning`, `error` or null. */ - fun journalGroups(level: String?, hours: Int, limit: Int): List - - /** The whole journal event behind a group, or null when it is no longer there. */ - fun journalDetail(id: String): JournalDetail? - - fun tasks(): List - - fun stats(): StatsSnapshot - - fun placeholders(): List - - fun runTask(id: String): TaskControl - - fun cancelTask(id: String): TaskControl - - fun events(): List - - fun listeners(): List - - fun eventHistory(eventType: String?): List - - /** How many days of calls are kept. */ - fun eventHistoryDays(): Int - - fun tracedEvents(): List - - fun traces(): List - - fun clearTraces() - - fun setTracing(eventType: String, enabled: Boolean) - - /** Writes the call history to a file and returns where, or null. */ - fun exportEventHistory(json: Boolean): String? - - /** The purpose and the owner of an event, or null when it is unknown. */ - fun eventAbout(eventType: String): EventAbout? - - fun ownerNamed(name: String): OwnerInfo? - - fun groups(): List - - /** Applies one change to the groups; returns false when there is no such group or the name is unfit. */ - fun editGroup(edit: GroupEdit): Boolean - - fun command(viewer: ViewerInfo, line: String): List -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuLayout.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuLayout.kt deleted file mode 100644 index 68dbf07b0..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuLayout.kt +++ /dev/null @@ -1,103 +0,0 @@ -package org.pnfolder.pnlibrary.core.menu - -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogRoutes -import java.time.Duration -import java.time.format.DateTimeFormatter -import java.util.Locale - -internal val ROUTES = UpdateCatalogRoutes("/pn updates", update = { product -> "/pn update $product" }, check = "/pn check") -internal const val DOWNLOAD = "pnlibrary.updates.download" -internal const val SETTINGS = "pnlibrary.updates.settings" -internal const val ROLLBACK = "pnlibrary.updates.rollback" -internal const val HOME_ROWS = 5 -internal const val NETWORK_SLOT = 34 -internal const val NETWORK_CHECK = 49 -internal const val PROXY_LABEL = "Прокси" -internal const val NETWORK_UPDATE = 51 -internal const val GROUP_ADD = 46 -internal const val GROUP_PLUGINS = 47 -internal const val GROUP_DELETE = 52 -internal const val GROUPS_PERMISSION = "pnlibrary.groups" -internal const val HOME_CLOSE = 40 -internal const val SUPPORT_SLOT = 38 -internal const val RESTART_SLOT = 41 -internal const val ROLLBACK_SLOT = 42 -internal const val CARD_ROWS = 4 -internal const val CARD_BACK = 31 -internal const val SMALL_ROWS = 3 -internal const val SUPPORT_TOOL_SLOT = 16 -internal const val SMALL_BACK = 22 -internal const val LIST_ROWS = 6 -internal const val PAGE_SIZE = 45 -internal const val HISTORY_PAGE = 10 -internal const val FOOTER_START = 45 -internal const val FOOTER_END = 54 -internal const val BACK = 45 -internal const val PREVIOUS = 48 -internal const val NEXT = 50 -internal const val REFRESH = 49 -internal const val FILTER = 47 -internal const val DATE_FILTER = 46 -internal const val JOURNAL_HOURS = 24 -internal const val JOURNAL_LIMIT = 200 -internal const val MESSAGE_PREVIEW = 70 -internal val LEVEL_CYCLE = listOf(null, "error", "warning", "info") -internal val LEVELS = mapOf("error" to "ошибки", "warning" to "предупреждения", "info" to "сведения") -internal const val CLOSE = 53 -internal const val BUS = "pnlibrary.events.bus" -internal const val CYCLE_HOLDS = 3 -internal const val HOURS_PER_DAY = 24 -internal const val MINUTES_PER_HOUR = 60 -internal const val TASKS = "pnlibrary.tasks" -internal const val STATS = "pnlibrary.stats" -internal const val PLACEHOLDERS = "pnlibrary.placeholders" -internal const val DETAIL_ROWS = 5 -internal const val DETAIL_BACK = 40 -internal const val CHANGE_FIRST = 19 -internal const val CHANGE_BUTTONS = 7 -internal const val WRAP_WIDTH = 44 -internal const val WRAP_LINES = 8 -internal const val TRACE_LINES = 12 -internal const val NOTE_LINES = 8 -internal const val NOTE_PREVIEW_LINES = 2 -internal const val TIMES_SHOWN = 10 -internal const val DETAILS_SHOWN = 8 -internal const val TRACE_STEPS = 6 -internal const val BAR_WIDTH = 12 -internal const val NANOS_PER_MICRO = 1_000L -internal const val NANOS_PER_MILLI = 1_000_000L -internal val DAY: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMMM", Locale("ru")) -internal val DAY_YEAR: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMMM yyyy", Locale("ru")) -internal const val SECONDS_PER_MINUTE = 60L -internal const val TITLE_LIMIT = 30 -internal const val TIMES_PREVIEW = 5 -internal const val BLOCKER_LINES = 3 -internal const val CHECK_REOPEN_MILLIS = 3_000L -internal const val LEGACY_BLACK: Short = 15 -internal const val LEGACY_PURPLE: Short = 10 - -/** Whether the menu may change the update channel; only `dev` works for now, so the choice is switched off. */ -internal const val CHANNEL_SWITCH = false - -internal val CHANNEL_ITEMS = mapOf( - UpdateChannel.STABLE to "EMERALD", - UpdateChannel.RC to "GOLD_INGOT", - UpdateChannel.BETA to "IRON_INGOT", - UpdateChannel.ALPHA to "REDSTONE", - UpdateChannel.DEV to "COAL", -) -internal val CHANNEL_HINTS = mapOf( - UpdateChannel.STABLE to "Только проверенные релизы.", - UpdateChannel.RC to "Кандидаты в релиз и стабильные.", - UpdateChannel.BETA to "Бета-версии, кандидаты и стабильные.", - UpdateChannel.ALPHA to "Ранние версии: возможны ошибки.", - UpdateChannel.DEV to "Все версии, включая ежедневные сборки.", -) -internal val HOLDS = listOf( - "1 час" to Duration.ofHours(1), - "6 часов" to Duration.ofHours(6), - "1 день" to Duration.ofDays(1), - "3 дня" to Duration.ofDays(3), - "7 дней" to Duration.ofDays(7), -) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuModel.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuModel.kt index 3ba9e55d8..d2c7ad0b5 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuModel.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuModel.kt @@ -1,7 +1,7 @@ package org.pnfolder.pnlibrary.core.menu import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.updates.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor import org.pnfolder.pnlibrary.core.link.Link import java.util.UUID @@ -21,18 +21,24 @@ data class ItemSpec( val legacyData: Short = 0, ) +/** Mouse button and modifier of a menu click. */ enum class ClickType { LEFT, RIGHT, SHIFT_LEFT, SHIFT_RIGHT, MIDDLE, OTHER } +/** A click a viewer made on a menu slot. */ class MenuClick(val player: MenuViewer, val slot: Int, val click: ClickType) +/** Reacts to a click on a menu button. */ fun interface MenuClickHandler { fun handle(click: MenuClick) } +/** A slot of a menu: the item shown and the handler for clicks, either may be null. */ class MenuItem(val item: ItemSpec?, val handler: MenuClickHandler?) +/** A finished chest menu that a viewer can open. */ class Menu(val title: String, val rows: Int, val items: Map) +/** Collects slots of a chest menu; create it with [Menus.chest]. */ class MenuBuilder internal constructor(private val title: String) { private var rows = DEFAULT_ROWS private val items = linkedMapOf() @@ -64,6 +70,7 @@ class MenuBuilder internal constructor(private val title: String) { } } +/** Entry point for building menus. */ object Menus { fun chest(title: String): MenuBuilder = MenuBuilder(title) } @@ -94,8 +101,10 @@ interface MenuViewer { fun runCommand(command: String) } +/** Name, version and authors of the plugin that owns something. */ data class OwnerInfo(val name: String, val version: String?, val authors: List) +/** Finds the plugin behind an object, a class or a name. */ interface PluginDirectory { /** The plugin that [owner] is, or null when it is not one. */ fun owner(owner: Any?): OwnerInfo? @@ -106,6 +115,7 @@ interface PluginDirectory { fun ownerOf(type: Class<*>?): OwnerInfo? } +/** What a menu needs from the platform: threads, scheduling and plugin lookup. */ interface MenuHost : PluginDirectory { fun sync(action: () -> Unit) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuRouter.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuRouter.kt index 03af21cd9..8293f3b8f 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuRouter.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuRouter.kt @@ -1,12 +1,31 @@ package org.pnfolder.pnlibrary.core.menu -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot import org.pnfolder.pnlibrary.core.commands.tasks.TaskPeriod import org.pnfolder.pnlibrary.core.commands.tasks.TaskState -import org.pnfolder.pnlibrary.core.link.NetworkReport -import org.pnfolder.pnlibrary.core.link.NetworkServer +import org.pnfolder.pnlibrary.core.link.report.NetworkReport +import org.pnfolder.pnlibrary.core.link.report.NetworkServer +import org.pnfolder.pnlibrary.core.menu.data.EventAbout +import org.pnfolder.pnlibrary.core.menu.screens.BusHistoryScreens +import org.pnfolder.pnlibrary.core.menu.screens.BusScreens +import org.pnfolder.pnlibrary.core.menu.screens.ConfigScreens +import org.pnfolder.pnlibrary.core.menu.screens.Filter +import org.pnfolder.pnlibrary.core.menu.screens.GroupScreens +import org.pnfolder.pnlibrary.core.menu.screens.HistoryScreens +import org.pnfolder.pnlibrary.core.menu.screens.HomeScreens +import org.pnfolder.pnlibrary.core.menu.screens.JournalScreens +import org.pnfolder.pnlibrary.core.menu.screens.LibrarySettingsScreens +import org.pnfolder.pnlibrary.core.menu.screens.ModuleScreens +import org.pnfolder.pnlibrary.core.menu.screens.NetworkScreens +import org.pnfolder.pnlibrary.core.menu.screens.PlaceholderScreens +import org.pnfolder.pnlibrary.core.menu.screens.SettingsScreens +import org.pnfolder.pnlibrary.core.menu.screens.StatsScreens +import org.pnfolder.pnlibrary.core.menu.screens.TaskScreens +import org.pnfolder.pnlibrary.core.menu.screens.UpdateScreens +import org.pnfolder.pnlibrary.core.menu.style.Row import java.time.Duration +/** Opens menu screens by route and keeps the navigation back stack of a session. */ internal class MenuRouter(private val session: MenuSession) : MenuRoutes { private val homeScreens = HomeScreens(session, this) private val updateScreens = UpdateScreens(session, this) @@ -14,12 +33,15 @@ internal class MenuRouter(private val session: MenuSession) : MenuRoutes { private val settingsScreens = SettingsScreens(session, this) private val journalScreens = JournalScreens(session, this) private val taskScreens = TaskScreens(session, this) + private val moduleScreens = ModuleScreens(session, this) private val networkScreens = NetworkScreens(session, this) private val groupScreens = GroupScreens(session, this) private val statsScreens = StatsScreens(session, this) private val placeholderScreens = PlaceholderScreens(session, this) private val busScreens = BusScreens(session, this) private val busHistoryScreens = BusHistoryScreens(session, this) + private val configScreens = ConfigScreens(session, this) + private val librarySettingsScreens = LibrarySettingsScreens(session, this) override fun aboutOf(name: String): EventAbout? = taskScreens.aboutOf(name) override fun backups(player: MenuViewer, page: Int) = historyScreens.backups(player, page) @@ -29,6 +51,7 @@ internal class MenuRouter(private val session: MenuSession) : MenuRoutes { override fun busTraces(player: MenuViewer, event: String?, page: Int) = busHistoryScreens.busTraces(player, event, page) override fun card(player: MenuViewer, product: String) = updateScreens.card(player, product) override fun checkAll(player: MenuViewer) = updateScreens.checkAll(player) + override fun configs(player: MenuViewer, page: Int) = configScreens.configs(player, page) override fun everyone(player: MenuViewer, done: String, change: (UpdateSnapshot) -> java.util.concurrent.CompletionStage<*>) = updateScreens.everyone(player, done, change) override fun groups(player: MenuViewer, page: Int): Unit = groupScreens.groups(player, page) @@ -37,9 +60,15 @@ internal class MenuRouter(private val session: MenuSession) : MenuRoutes { updateScreens.hold(snapshot, duration, player) override fun home(player: MenuViewer) = homeScreens.home(player) override fun journal(player: MenuViewer, level: String?, page: Int) = journalScreens.journal(player, level, page) + override fun librarySettings(player: MenuViewer, page: Int) = librarySettingsScreens.librarySettings(player, page) + override fun pickSetting(player: MenuViewer, key: String, filter: String) = librarySettingsScreens.pick(player, key, filter) override fun journalRows(level: String?, back: (MenuViewer) -> Unit): List = journalScreens.journalRows(level, back) override fun labelled(label: String, text: String): List> = taskScreens.labelled(label, text) override fun members(map: NetworkReport): List = networkScreens.members(map) + override fun modules(player: MenuViewer, plugin: String?, page: Int, back: (MenuViewer) -> Unit) = moduleScreens.modules(player, plugin, page, back) + override fun libraries(player: MenuViewer, owner: String?, page: Int, back: (MenuViewer) -> Unit) = moduleScreens.libraries(player, owner, page, back) + + override fun disk(player: MenuViewer, page: Int, back: (MenuViewer) -> Unit) = moduleScreens.disk(player, page, back) override fun network(player: MenuViewer, page: Int) = networkScreens.network(player, page) override fun ownerLine(name: String): String = taskScreens.ownerLine(name) override fun ownerParameters(owner: OwnerInfo?): List> = taskScreens.ownerParameters(owner) @@ -48,6 +77,7 @@ internal class MenuRouter(private val session: MenuSession) : MenuRoutes { override fun setAutomatic(snapshot: UpdateSnapshot, enable: Boolean, player: MenuViewer): java.util.concurrent.CompletionStage<*> = updateScreens.setAutomatic(snapshot, enable, player) override fun settings(player: MenuViewer) = settingsScreens.settings(player) + override fun missingPlugins(player: MenuViewer, page: Int) = settingsScreens.missingPlugins(player, page) override fun stats(player: MenuViewer) = statsScreens.stats(player) override fun support(player: MenuViewer) = settingsScreens.support(player) override fun tasks(player: MenuViewer, period: TaskPeriod, state: TaskState, page: Int) = taskScreens.tasks(player, period, state, page) @@ -55,4 +85,6 @@ internal class MenuRouter(private val session: MenuSession) : MenuRoutes { override fun versioned(owner: OwnerInfo): String = taskScreens.versioned(owner) fun open(player: MenuViewer) = session.away(player) { home(player) } + + fun pick(player: MenuViewer, key: String, filter: String) = session.away(player) { pickSetting(player, key, filter) } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuRoutes.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuRoutes.kt index c29dc8cc0..885cae376 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuRoutes.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuRoutes.kt @@ -1,10 +1,13 @@ package org.pnfolder.pnlibrary.core.menu -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot import org.pnfolder.pnlibrary.core.commands.tasks.TaskPeriod import org.pnfolder.pnlibrary.core.commands.tasks.TaskState -import org.pnfolder.pnlibrary.core.link.NetworkReport -import org.pnfolder.pnlibrary.core.link.NetworkServer +import org.pnfolder.pnlibrary.core.link.report.NetworkReport +import org.pnfolder.pnlibrary.core.link.report.NetworkServer +import org.pnfolder.pnlibrary.core.menu.data.EventAbout +import org.pnfolder.pnlibrary.core.menu.screens.Filter +import org.pnfolder.pnlibrary.core.menu.style.Row import java.time.Duration /** The screens that more than one part of the menu opens, so each part needs no knowledge of the others. */ @@ -17,15 +20,23 @@ internal interface MenuRoutes { fun busTraces(player: MenuViewer, event: String?, page: Int) fun card(player: MenuViewer, product: String) fun checkAll(player: MenuViewer) + fun configs(player: MenuViewer, page: Int) fun everyone(player: MenuViewer, done: String, change: (UpdateSnapshot) -> java.util.concurrent.CompletionStage<*>) fun groups(player: MenuViewer, page: Int): Unit fun history(player: MenuViewer, product: String?, page: Int) fun hold(snapshot: UpdateSnapshot, duration: Duration?, player: MenuViewer): java.util.concurrent.CompletionStage<*> fun home(player: MenuViewer) fun journal(player: MenuViewer, level: String?, page: Int) + fun librarySettings(player: MenuViewer, page: Int) + fun pickSetting(player: MenuViewer, key: String, filter: String) fun journalRows(level: String?, back: (MenuViewer) -> Unit): List fun labelled(label: String, text: String): List> fun members(map: NetworkReport): List + fun modules(player: MenuViewer, plugin: String?, page: Int, back: (MenuViewer) -> Unit) + fun libraries(player: MenuViewer, owner: String?, page: Int, back: (MenuViewer) -> Unit) + + /** What every plugin takes on the disk. */ + fun disk(player: MenuViewer, page: Int, back: (MenuViewer) -> Unit) fun network(player: MenuViewer, page: Int) fun ownerLine(name: String): String fun ownerParameters(owner: OwnerInfo?): List> @@ -33,6 +44,8 @@ internal interface MenuRoutes { fun plugins(player: MenuViewer, filter: Filter, page: Int) fun setAutomatic(snapshot: UpdateSnapshot, enable: Boolean, player: MenuViewer): java.util.concurrent.CompletionStage<*> fun settings(player: MenuViewer) + + fun missingPlugins(player: MenuViewer, page: Int) fun stats(player: MenuViewer) fun support(player: MenuViewer) fun tasks(player: MenuViewer, period: TaskPeriod, state: TaskState, page: Int) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuScreens.kt index 491e05ca0..5418c8f4d 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuScreens.kt @@ -1,7 +1,12 @@ package org.pnfolder.pnlibrary.core.menu import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.chat.ChatTone +import net.kyori.adventure.text.event.ClickEvent +import org.pnfolder.pnlibrary.api.chat.ChatKit +import org.pnfolder.pnlibrary.api.chat.ChatReader +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.core.menu.style.Row /** The helpers every screen group uses; they live in the [MenuSession] and are only forwarded here. */ internal abstract class MenuScreens(private val session: MenuSession, protected val routes: MenuRoutes) { @@ -30,6 +35,17 @@ internal abstract class MenuScreens(private val session: MenuSession, protected protected fun tell(player: MenuViewer, tone: ChatTone, text: String, detail: String? = null) = session.tell(player, tone, text, detail) + /** Closes the menu and offers [command] to the viewer to put into the chat line; [text] tells what to type. */ + protected fun suggestCommand(player: MenuViewer, text: String, command: String) { + player.close() + val kit = ChatKit(ChatReader.PLAYER) + val line = kit.mark(ChatTone.INFO).append(kit.text(text, ChatPalette.TEXT)).append(kit.text(" ")) + .append(kit.bracketed("Ввести команду", ChatPalette.ACCENT)) + .clickEvent(ClickEvent.suggestCommand(command)) + .hoverEvent(kit.tooltip(kit.text("Нажмите, чтобы вставить в чат", ChatPalette.TEXT), kit.text(command.trim(), ChatPalette.LABEL))) + player.send(listOf(line)) + } + protected fun list( player: MenuViewer, title: String, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuSession.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuSession.kt index ce9503cda..12697c90f 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuSession.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuSession.kt @@ -3,10 +3,33 @@ package org.pnfolder.pnlibrary.core.menu import org.pnfolder.pnlibrary.api.chat.ChatKit import org.pnfolder.pnlibrary.api.chat.ChatNotice import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.core.exceptions.rootMessage +import org.pnfolder.pnlibrary.core.menu.data.MenuData +import org.pnfolder.pnlibrary.core.menu.data.ViewerInfo +import org.pnfolder.pnlibrary.core.menu.style.BACK +import org.pnfolder.pnlibrary.core.menu.style.FOOTER_END +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.MenuPermissions +import org.pnfolder.pnlibrary.core.menu.style.NEXT +import org.pnfolder.pnlibrary.core.menu.style.PREVIOUS +import org.pnfolder.pnlibrary.core.menu.style.ROUTES +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.backItem +import org.pnfolder.pnlibrary.core.menu.style.closeItem +import org.pnfolder.pnlibrary.core.menu.style.footerCorners +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.menuTitle +import org.pnfolder.pnlibrary.core.menu.style.pane import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogView +private const val LIST_ROWS = 6 +private const val REFRESH = 49 +private const val CLOSE = 53 + +/** State of one open menu: viewer, data source and the current screen. */ internal class MenuSession( val data: MenuData, val host: MenuHost, @@ -15,7 +38,7 @@ internal class MenuSession( val remote get() = remoteName != null fun allowed(player: MenuViewer, permission: String, action: () -> Unit) { - if (player.hasPermission(permission) || player.hasPermission("pnlibrary.admin")) action() + if (player.hasPermission(permission) || player.hasPermission(MenuPermissions.ADMIN)) action() else tell(player, ChatTone.FAILURE, "Не хватает права.", permission) } @@ -45,29 +68,43 @@ internal class MenuSession( val pages = ((total - 1) / perPage + 1).coerceAtLeast(1) val current = page.coerceIn(0, pages - 1) val shown = if (total == rows.size) rows.drop(current * perPage).take(perPage) else rows.take(perPage) - val builder = Menus.chest(title("$title ${current + 1}/$pages")).rows(LIST_ROWS) + val builder = Menus.chest(menuTitle("$title ${current + 1}/$pages")).rows(LIST_ROWS) shown.forEachIndexed { slot, row -> if (row.click != null) builder.button(slot, row.stack, row.click) else builder.slot(slot, row.stack) } if (total == 0) builder.slot(22, icon(Icons.PROBLEMS, "BARRIER", emptyText, emptyList(), muted = true)) footerCorners(builder) builder.fill(pane(), 0, FOOTER_END) builder.button(BACK, backItem(), go { back(it) }) + pager(builder, current, pages, perPage, total, shown.size, reopen) + extra(builder) + builder.button(CLOSE, closeItem(), go { it.close() }) + show(player, builder.build()) + } + + private fun pager(builder: MenuBuilder, current: Int, pages: Int, perPage: Int, total: Int, shown: Int, reopen: (MenuViewer, Int) -> Unit) { + val first = if (total == 0) 0 else current * perPage + 1 + val range = "$first–${current * perPage + shown} из $total" if (current > 0) { - val previous = icon(Icons.BACK, "ARROW", "Назад по списку", Style.lore(emptyList(), emptyList(), Style.left("страница $current")), good = true) + val lore = Style.lore(emptyList(), listOf("Сейчас" to "${current + 1} из $pages"), Style.left("на предыдущую")) + val previous = icon(null, "SPECTRAL_ARROW", "◀ Страница $current", lore, good = true) builder.button(PREVIOUS, previous, go { reopen(it, current - 1) }) + } else if (pages > 1) { + builder.slot(PREVIOUS, icon(null, "GRAY_DYE", "Это первая страница", emptyList(), muted = true)) } if (current < pages - 1) { - val following = icon(Icons.NEXT, "ARROW", "Дальше по списку", - Style.lore(emptyList(), emptyList(), Style.left("страница ${current + 2}")), good = true) + val lore = Style.lore(emptyList(), listOf("Сейчас" to "${current + 1} из $pages"), Style.left("на следующую")) + val following = icon(null, "SPECTRAL_ARROW", "Страница ${current + 2} ▶", lore, good = true) builder.button(NEXT, following, go { reopen(it, current + 1) }) + } else if (pages > 1) { + builder.slot(NEXT, icon(null, "GRAY_DYE", "Это последняя страница", emptyList(), muted = true)) } builder.button( REFRESH, - icon(Icons.CHECK, "COMPASS", "Обновить список", Style.lore(listOf("Перечитать данные заново."), emptyList(), Style.left("обновить"))), + icon( + Icons.CHECK, "COMPASS", "Страница ${current + 1} из $pages", + Style.lore(listOf("Показано $range."), emptyList(), Style.left("обновить список")), + ), go { reopen(it, current) }, ) - extra(builder) - builder.button(CLOSE, closeItem(), go { it.close() }) - show(player, builder.build()) } fun go(action: (MenuViewer) -> Unit) = MenuClickHandler { click -> away(click.player) { action(click.player) } } @@ -81,7 +118,7 @@ internal class MenuSession( try { action() } catch (error: Exception) { - if (player != null) tell(player, ChatTone.FAILURE, "Сервер $remoteName не ответил.", reason(error)) + if (player != null) tell(player, ChatTone.FAILURE, "Сервер $remoteName не ответил.", error.rootMessage()) } } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuText.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuText.kt deleted file mode 100644 index bbf432a3d..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuText.kt +++ /dev/null @@ -1,82 +0,0 @@ -package org.pnfolder.pnlibrary.core.menu - -import org.pnfolder.pnlibrary.common.time.DisplayZone -import java.time.Duration -import java.time.Instant -import java.time.LocalDate -import java.time.format.DateTimeFormatter -import java.util.Locale - -internal fun left(span: Duration): String { - val days = span.toDays() - val hours = span.toHours() % HOURS_PER_DAY - val minutes = span.toMinutes() % MINUTES_PER_HOUR - return when { - days > 0 -> "$days д $hours ч" - hours > 0 -> "$hours ч $minutes мин" - else -> "${minutes.coerceAtLeast(1)} мин" - } -} - -internal fun duration(nanos: Long): String = - if (nanos >= NANOS_PER_MILLI) "%.1f мс".format(nanos / NANOS_PER_MILLI.toDouble()) else "%.1f мкс".format(nanos / NANOS_PER_MICRO.toDouble()) - -internal fun shortName(name: String): String = name.substringAfterLast('.') - -internal fun time(moment: Instant): String = format(moment, "HH:mm") - -internal fun stamp(moment: Instant): String = format(moment, "HH:mm:ss") - -private fun format(moment: Instant, clock: String): String { - val zone = DisplayZone.zone - val year = if (moment.atZone(zone).year == LocalDate.now(zone).year) "" else " yyyy" - return DateTimeFormatter.ofPattern("d MMMM$year, $clock", Locale("ru")).withZone(zone).format(moment) -} - -/** How long ago [moment] was, or how long until it: `только что`, `5 мин назад`, `через 2 ч 10 мин`. */ -internal fun ago(moment: Instant): String { - val span = Duration.between(moment, Instant.now()) - return when { - span.abs().seconds < SECONDS_PER_MINUTE -> "только что" - span.isNegative -> "через ${left(span.negated())}" - else -> "${left(span)} назад" - } -} - -internal fun dayTitle(date: LocalDate, today: LocalDate): String = when (date) { - today -> "Сегодня" - today.minusDays(1) -> "Вчера" - else -> (if (date.year == today.year) DAY else DAY_YEAR).format(date) -} - -internal fun bar(value: Long, busiest: Long): String { - val width = ((value * BAR_WIDTH + busiest - 1) / busiest.coerceAtLeast(1)).toInt().coerceIn(1, BAR_WIDTH) - return "█".repeat(width) -} - -internal fun wrap(text: String, width: Int = WRAP_WIDTH, limit: Int = WRAP_LINES): List { - val lines = ArrayList() - for (raw in text.lines()) { - var line = StringBuilder() - for (word in raw.trim().split(' ')) { - if (line.isNotEmpty() && line.length + 1 + word.length > width) { - lines += line.toString() - line = StringBuilder() - } - var rest = word - while (rest.length > width) { - lines += rest.take(width) - rest = rest.drop(width) - } - if (line.isNotEmpty()) line.append(' ') - line.append(rest) - } - lines += line.toString() - } - return if (lines.size > limit) lines.take(limit) + "…" else lines -} - -internal fun reason(error: Throwable): String { - val cause = generateSequence(error) { it.cause }.last() - return cause.message ?: cause.javaClass.simpleName -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/PluginPolicyScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/PluginPolicyScreens.kt deleted file mode 100644 index 9b8596ed3..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/PluginPolicyScreens.kt +++ /dev/null @@ -1,99 +0,0 @@ -package org.pnfolder.pnlibrary.core.menu - -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import java.time.Duration -import java.time.Instant - -internal class PluginPolicyScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { - /** The channel choice. It stays in the code and is switched on by [CHANNEL_SWITCH] once more than `dev` works. */ - fun channels(player: MenuViewer, product: String) { - val current = data.snapshot(product)?.channel - val builder = frame(Menus.chest(title("Канал $product")).rows(SMALL_ROWS), SMALL_ROWS) - UpdateChannel.values().forEachIndexed { index, channel -> - val chosen = channel == current - val lore = Style.lore( - listOf(CHANNEL_HINTS.getValue(channel)), - if (chosen) listOf("Состояние" to "выбран сейчас") else emptyList(), - *if (chosen) emptyArray() else arrayOf(Style.left("выбрать")), - ) - builder.button( - 10 + index, - icon(null, CHANNEL_ITEMS.getValue(channel), channel.name.lowercase(), lore, good = chosen), - go { who -> allowed(who, SETTINGS) { chooseChannel(who, product, channel) } }, - ) - } - builder.button( - 16, - icon( - Icons.RESET, "BARRIER", "Сбросить", - Style.lore(listOf("Вернуть канал, который указал плагин."), emptyList(), Style.left("сбросить")), muted = true, - ), - go { who -> allowed(who, SETTINGS) { chooseChannel(who, product, null) } }, - ) - builder.button(SMALL_BACK, backItem(), go { routes.card(it, product) }) - show(player, builder.build()) - } - - private fun holdSummary(remaining: Duration?) = icon( - Icons.CLOCK, "CLOCK", "Пауза сейчас", - Style.lore( - listOf("Пока пауза идёт, обновления не предлагаются и не скачиваются."), - listOf("Состояние" to (remaining?.let { "‖ осталось ${left(it)}" } ?: "нет паузы")), - ), - alternative = "WATCH", warn = remaining != null, - ) - - private fun holdChoice(label: String, selectedRemaining: Duration?): ItemSpec { - val note = selectedRemaining?.let { listOf("Выбрано" to "● осталось ${left(it)}") } ?: emptyList() - val action = if (selectedRemaining != null) "начать срок заново" else "приостановить" - return icon( - Icons.CLOCK, "CLOCK", label, - Style.lore(listOf("Приостановить обновления на этот срок."), note, Style.left(action)), - alternative = "WATCH", good = selectedRemaining != null, - ) - } - - fun holds(player: MenuViewer, product: String) { - val until = data.heldUntil(product)?.takeIf { it.isAfter(Instant.now()) } - val remaining = until?.let { Duration.between(Instant.now(), it) } - val chosen = remaining?.let { holdIndex(it) } ?: -1 - val builder = frame(Menus.chest(title("Пауза $product")).rows(SMALL_ROWS), SMALL_ROWS) - builder.slot(4, holdSummary(remaining)) - HOLDS.forEachIndexed { index, (label, duration) -> - val item = holdChoice(label, if (index == chosen) remaining else null) - builder.button(10 + index, item, go { who -> allowed(who, SETTINGS) { chooseHold(who, product, duration) } }) - } - if (remaining != null) { - builder.button( - 16, - icon(Icons.RESET, "REDSTONE", "Снять паузу", Style.lore(listOf("Вернуть обновления сейчас."), emptyList(), Style.left("снять")), good = true), - go { who -> allowed(who, SETTINGS) { chooseHold(who, product, null) } }, - ) - } - builder.button(SMALL_BACK, backItem(), go { routes.card(it, product) }) - show(player, builder.build()) - } - - private fun holdIndex(remaining: Duration): Int = HOLDS.indexOfFirst { it.second >= remaining }.takeIf { it >= 0 } ?: (HOLDS.size - 1) - - private fun chooseChannel(player: MenuViewer, product: String, channel: UpdateChannel?) { - data.setChannel(product, channel, player.actor).whenComplete { _, error -> - sync { - if (error != null) tell(player, ChatTone.FAILURE, "Не удалось изменить канал.", reason(error)) - else tell(player, ChatTone.SUCCESS, "Канал $product: ${channel?.name?.lowercase() ?: "как указал плагин"}.") - routes.card(player, product) - } - } - } - - private fun chooseHold(player: MenuViewer, product: String, duration: Duration?) { - data.setHeld(product, duration, player.actor).whenComplete { _, error -> - sync { - if (error != null) tell(player, ChatTone.FAILURE, "Не удалось изменить паузу.", reason(error)) - else tell(player, ChatTone.SUCCESS, if (duration == null) "Пауза $product снята." else "Обновления $product приостановлены.") - routes.card(player, product) - } - } - } -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/ProxyMenu.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/ProxyMenu.kt index 51c8a92df..85e38cf05 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/ProxyMenu.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/ProxyMenu.kt @@ -4,17 +4,12 @@ import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.core.commands.proxy.ProxyCommandNames import org.pnfolder.pnlibrary.core.commands.proxy.ProxyControlCommand import org.pnfolder.pnlibrary.core.link.Link +import org.pnfolder.pnlibrary.core.menu.data.LocalMenuData +import org.pnfolder.pnlibrary.core.menu.data.MenuDataServer +import org.pnfolder.pnlibrary.core.menu.data.ViewerInfo import java.util.UUID import java.util.concurrent.Executors -object MenuPermissions { - val ALL = listOf( - "pnlibrary.admin", "pnlibrary.servers", "pnlibrary.updates.view", "pnlibrary.updates.download", "pnlibrary.updates.rollback", - "pnlibrary.updates.settings", "pnlibrary.updates.restart", "pnlibrary.events.view", "pnlibrary.events.bus", "pnlibrary.tasks", - "pnlibrary.stats", "pnlibrary.placeholders", "pnlibrary.debug", "pnlibrary.currency.list", - ) -} - /** * The questions about a proxy's library that game servers ask. * @@ -29,8 +24,15 @@ object ProxyMenu { * @param link the proxy's link, which keeps the server groups * @param control the proxy's `/pn`, which runs the chat commands behind the buttons * @param describe the plugin behind a registration owner, or null + * @param holds whether the player of that name, connected to this proxy, has the permission */ - fun server(library: PnLibrary, link: Link, control: ProxyControlCommand, describe: (Any?) -> OwnerInfo?): MenuDataServer { + fun server( + library: PnLibrary, + link: Link, + control: ProxyControlCommand, + describe: (Any?) -> OwnerInfo?, + holds: (viewer: String, permission: String) -> Boolean, + ): MenuDataServer { val directory = object : PluginDirectory { override fun owner(owner: Any?): OwnerInfo? = describe(owner) @@ -44,6 +46,6 @@ object ProxyMenu { control.run(viewerId, viewer.name, viewer.permissions::contains, line).map(ProxyCommandNames::rewrite) } val executor = Executors.newCachedThreadPool { task -> Thread(task, "pnlibrary-menu-data").apply { isDaemon = true } } - return MenuDataServer(LocalMenuData(library, directory, run, link.groups()), executor) + return MenuDataServer(LocalMenuData(library, directory, run, link.groups()), executor, holds) } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/LocalMenuData.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/LocalMenuData.kt new file mode 100644 index 000000000..ad8b00cca --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/LocalMenuData.kt @@ -0,0 +1,260 @@ +package org.pnfolder.pnlibrary.core.menu.data + +import net.kyori.adventure.text.Component +import org.pnfolder.pnlibrary.api.config.ConfigEditResult +import org.pnfolder.pnlibrary.api.config.ConfigId +import org.pnfolder.pnlibrary.api.config.ConfigSetting +import org.pnfolder.pnlibrary.api.events.EventDescription +import org.pnfolder.pnlibrary.api.events.inspect.EventInfo +import org.pnfolder.pnlibrary.api.events.inspect.ListenerInfo +import org.pnfolder.pnlibrary.api.events.inspect.history.EventDay +import org.pnfolder.pnlibrary.api.events.inspect.trace.EventTrace +import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.core.commands.modules.DiskReport +import org.pnfolder.pnlibrary.core.commands.modules.DiskUsage +import org.pnfolder.pnlibrary.core.commands.modules.LibraryRow +import org.pnfolder.pnlibrary.core.journal.JournalDetail +import org.pnfolder.pnlibrary.core.journal.JournalGroup +import org.pnfolder.pnlibrary.core.lifecycle.cancelTask +import org.pnfolder.pnlibrary.core.lifecycle.dependencyDownloads +import org.pnfolder.pnlibrary.core.lifecycle.journalDetail +import org.pnfolder.pnlibrary.core.lifecycle.journalGroups +import org.pnfolder.pnlibrary.core.lifecycle.librarySettings +import org.pnfolder.pnlibrary.core.lifecycle.placeholderInfos +import org.pnfolder.pnlibrary.core.lifecycle.runTaskNow +import org.pnfolder.pnlibrary.core.lifecycle.statsSnapshot +import org.pnfolder.pnlibrary.core.lifecycle.taskSnapshots +import org.pnfolder.pnlibrary.core.link.ServerGroups +import org.pnfolder.pnlibrary.core.menu.OwnerInfo +import org.pnfolder.pnlibrary.core.menu.PluginDirectory +import org.pnfolder.pnlibrary.core.menu.screens.ConfigRow +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderInfo +import org.pnfolder.pnlibrary.core.settings.SettingApply +import org.pnfolder.pnlibrary.core.settings.SettingException +import org.pnfolder.pnlibrary.core.stats.StatsSnapshot +import org.pnfolder.pnlibrary.core.tasks.TaskControl +import org.pnfolder.pnlibrary.core.updates.catalog.UpdateStatusMessages +import java.time.Duration +import java.time.Instant +import java.util.UUID +import java.util.concurrent.CompletionStage + +/** + * The facts of the library on this server. It is the source of this server's own menu, and the one that answers when + * another server asks over the link. + * + * @param library this server's library + * @param directory the plugins of this platform + * @param run runs a chat command for a viewer and returns what it printed + * @param groups the groups of servers, on a proxy; null on a game server + */ +class LocalMenuData( + private val library: PnLibrary, + private val directory: PluginDirectory, + private val run: (ViewerInfo, String) -> List = { _, _ -> emptyList() }, + private val groups: ServerGroups? = null, +) : MenuData { + private val bus get() = library.events.inspector + + override fun downloadsAutomatic(): Boolean? = library.dependencyDownloads()?.automatic() + + override fun setDownloadsAutomatic(value: Boolean) { + library.dependencyDownloads()?.setAutomatic(value) + } + + override fun missingDependencies(): List = library.dependencyDownloads()?.missingGroups().orEmpty().map { group -> + MissingPlugins( + group.code, group.owner, group.installable, + group.items.map { "${it.title} ${it.minimum}+ · ${if (it.required) "обязательный" else "необязательный"}" }, + group.items.flatMap { listOfNotNull(it.page) + it.sources }.map { it.toString() }.distinct(), + ) + } + + override fun installDependencies(code: String): java.util.concurrent.CompletionStage { + val downloads = library.dependencyDownloads() + ?: return java.util.concurrent.CompletableFuture.completedFuture("Загрузки зависимостей здесь недоступны.") + val stage = try { + downloads.installGroup(code) + } catch (error: IllegalArgumentException) { + return java.util.concurrent.CompletableFuture.completedFuture(error.message ?: "Установить нельзя.") + } ?: return java.util.concurrent.CompletableFuture.completedFuture("Такого кода нет или всё уже скачано.") + return stage.handle { shots, error -> + val failed = shots?.firstOrNull { it.state == org.pnfolder.pnlibrary.api.downloads.DownloadState.FAILED } + when { + error != null -> "Не вышло: ${error.message}" + failed != null -> "Не вышло: ${failed.message ?: "причина неизвестна"}" + else -> "Готово. Перезапустите сервер, чтобы плагины загрузились." + } + } + } + + override fun version(): String = library.version + + override fun snapshots(): List = library.updates.products.all().map { it.snapshot }.sortedBy { it.product.lowercase() } + + override fun snapshot(product: String): UpdateSnapshot? = library.updates.products.get(product)?.snapshot + + override fun plugins(): List = library.plugins.all().map { registration -> + val owner = directory.owner(registration.owner) + PluginRow(owner?.name ?: registration.owner.javaClass.simpleName, owner?.version, registration.all().size) + } + + override fun plan(): PlanInfo? = library.updates.plans.current().orElse(null)?.let { plan -> + PlanInfo(plan.state, plan.plan?.changes?.isNotEmpty() == true, plan.blockers.map { UpdateStatusMessages.blocker(it) }) + } + + override fun heldUntil(product: String): Instant? = library.updates.settings.heldUntil(product) + + override fun historyCount(product: String?): CompletionStage = library.updates.history.count(product) + + override fun historyPage(page: Int, product: String?): CompletionStage> = library.updates.history.page(page, product) + + override fun backups(): CompletionStage> = library.updates.backups.list() + + override fun checkAll(actor: UpdateActor): CompletionStage = library.updates.plans.check(actor).thenApply { true } + + override fun checkOne(product: String, actor: UpdateActor) { + library.updates.products.get(product)?.checkNow() + } + + override fun setAutomatic(product: String, enabled: Boolean, actor: UpdateActor): CompletionStage = + library.updates.settings.automaticDownload(product, enabled, actor).thenApply { true } + + override fun setChannel(product: String, channel: UpdateChannel?, actor: UpdateActor): CompletionStage = + library.updates.settings.channel(product, channel, actor).thenApply { true } + + override fun setJavaBuild(product: String, java: Int?, actor: UpdateActor): CompletionStage = + library.updates.settings.javaBuild(product, java, actor).thenApply { true } + + override fun setHeld(product: String, duration: Duration?, actor: UpdateActor): CompletionStage = + (if (duration == null) library.updates.settings.release(product, actor) else library.updates.settings.hold(product, duration, actor)).thenApply { true } + + override fun extractBackup(id: UUID, product: String, actor: UpdateActor): CompletionStage = + library.updates.backups.extract(id, product, actor) + + override fun restoreDatabase(id: UUID, product: String, name: String, actor: UpdateActor): CompletionStage = + library.updates.backups.restoreDatabase(id, product, name, actor).thenApply { true } + + override fun rollback(id: UUID, restoreConfigurations: Boolean, actor: UpdateActor): CompletionStage = + library.updates.backups.rollback(id, actor, restoreConfigurations).thenApply { true } + + override fun journalGroups(level: String?, hours: Int, limit: Int): List = library.journalGroups(level, hours, limit) + + override fun journalDetail(id: String): JournalDetail? = library.journalDetail(id) + + override fun tasks(): List = library.taskSnapshots() + + override fun modules(): List = ModuleInfo.all(library) + + override fun libraries(): List = LibraryRow.all(library) + + @Volatile + private var diskAt = 0L + + @Volatile + private var diskCache = DiskReport.EMPTY + + /** The scan is remembered for half a minute: a big folder is not walked again for every click. */ + override fun disk(): DiskReport { + val now = System.currentTimeMillis() + if (now - diskAt > 30_000) { + diskCache = DiskUsage.scan(DiskUsage.pluginsFolder, DiskUsage.registeredFiles(library)) + diskAt = now + } + return diskCache + } + + override fun moduleAction(key: String, action: String): ModuleInfo = ModuleInfo.apply(library, key, action) + + override fun runTask(id: String): TaskControl = library.runTaskNow(id) + + override fun cancelTask(id: String): TaskControl = library.cancelTask(id) + + override fun stats(): StatsSnapshot = library.statsSnapshot() + + override fun placeholders(): List = library.placeholderInfos() + + override fun configs(): List = library.configurations.all().map { info -> + val config = library.configurations.get(info.id) + ConfigRow(info.id.toString(), info.modelType.name, info.isLoaded, info.readOnly, config?.settings?.size ?: 0, info.pendingApply) + } + + override fun configSettings(id: String): List = library.configurations.get(ConfigId.parse(id))?.settings.orEmpty() + + override fun editConfig(id: String, path: String, text: String): ConfigEditResult = + requireNotNull(library.configurations.get(ConfigId.parse(id))) { "Файла $id нет" }.edit(path, text) + + override fun settings(): List = library.librarySettings()?.values().orEmpty().map { entry -> + val spec = entry.spec + SettingRow( + spec.key, spec.title, spec.kind.name, spec.description, entry.current, spec.default, entry.changed, spec.range(), spec.examples, + spec.applies == SettingApply.LIVE, spec.choices?.id.orEmpty(), + ) + } + + override fun changeSetting(key: String, value: String?, actor: UpdateActor): SettingOutcome { + val store = library.librarySettings() ?: return SettingOutcome(false, "Настройки здесь недоступны.") + return try { + val change = if (value == null) store.reset(key) else store.set(key, value) + SettingOutcome(true, change.spec.display(change.after), change.spec.applies == SettingApply.LIVE) + } catch (error: SettingException) { + SettingOutcome(false, error.message.orEmpty()) + } + } + + override fun events(): List = bus.events() + + override fun listeners(): List = bus.listeners() + + override fun eventHistory(eventType: String?): List = bus.history(eventType) + + override fun eventHistoryDays(): Int = bus.historyDays + + override fun tracedEvents(): List = bus.tracedEvents() + + override fun traces(): List = bus.traces() + + override fun clearTraces() = bus.clearTraces() + + override fun setTracing(eventType: String, enabled: Boolean) { + val type = bus.eventType(eventType) ?: return + if (enabled) bus.enableTracing(type) else bus.disableTracing(type) + } + + override fun exportEventHistory(json: Boolean): String? = bus.exportHistory(json)?.toString() + + override fun eventAbout(eventType: String): EventAbout? { + val type = bus.eventType(eventType) ?: return null + val about = type.getAnnotation(EventDescription::class.java) + return EventAbout(about?.purpose.orEmpty(), about?.usage.orEmpty(), directory.ownerOf(type)) + } + + override fun ownerNamed(name: String): OwnerInfo? = directory.ownerNamed(name) + + override fun groups(): List = groups?.all().orEmpty() + + override fun editGroup(edit: GroupEdit): Boolean { + val store = groups ?: return false + val server = edit.server.orEmpty() + val plugin = edit.plugin.orEmpty() + return when (edit.op) { + GroupOp.CREATE -> store.create(edit.group) + GroupOp.DELETE -> store.delete(edit.group) + GroupOp.ADD_SERVER -> store.edit(edit.group) { it.addServer(server) } + GroupOp.REMOVE_SERVER -> store.edit(edit.group) { it.removeServer(server) } + GroupOp.ADD_PLUGIN -> store.edit(edit.group) { it.addPlugin(plugin) } + GroupOp.REMOVE_PLUGIN -> store.edit(edit.group) { it.removePlugin(plugin) } + GroupOp.NEED -> store.edit(edit.group) { it.with(server, plugin, true) } + GroupOp.SKIP -> store.edit(edit.group) { it.with(server, plugin, false) } + GroupOp.RESET -> store.edit(edit.group) { it.reset(server) } + } + } + + override fun command(viewer: ViewerInfo, line: String): List = run(viewer, line) +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuCalls.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuCalls.kt new file mode 100644 index 000000000..9523ad5cd --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuCalls.kt @@ -0,0 +1,59 @@ +package org.pnfolder.pnlibrary.core.menu.data + +/** Names of the calls the menu sends to another server over the link. */ +object MenuCalls { + const val VERSION = "version" + const val SNAPSHOTS = "snapshots" + const val SNAPSHOT = "snapshot" + const val PLUGINS = "plugins" + const val PLAN = "plan" + const val HELD_UNTIL = "heldUntil" + const val HISTORY_COUNT = "historyCount" + const val HISTORY_PAGE = "historyPage" + const val BACKUPS = "backups" + const val CHECK_ALL = "checkAll" + const val CHECK_ONE = "checkOne" + const val SET_AUTOMATIC = "setAutomatic" + const val SET_CHANNEL = "setChannel" + const val SET_JAVA_BUILD = "setJavaBuild" + const val SET_HELD = "setHeld" + const val ROLLBACK = "rollback" + const val RESTORE_DATABASE = "restore-database" + const val EXTRACT_BACKUP = "extract-backup" + const val JOURNAL_GROUPS = "journalGroups" + const val JOURNAL_DETAIL = "journalDetail" + const val TASKS = "tasks" + const val STATS = "stats" + const val PLACEHOLDERS = "placeholders" + const val RUN_TASK = "runTask" + const val CANCEL_TASK = "cancelTask" + const val MODULES = "modules" + const val LIBRARIES = "libraries" + const val DISK = "disk" + const val MODULE_ACTION = "moduleAction" + const val EVENTS = "events" + const val LISTENERS = "listeners" + const val EVENT_HISTORY = "eventHistory" + const val EVENT_HISTORY_DAYS = "eventHistoryDays" + const val TRACED_EVENTS = "tracedEvents" + const val TRACES = "traces" + const val CLEAR_TRACES = "clearTraces" + const val SET_TRACING = "setTracing" + const val EXPORT_EVENT_HISTORY = "exportEventHistory" + const val EVENT_ABOUT = "eventAbout" + const val OWNER_NAMED = "ownerNamed" + const val COMMAND = "command" + const val GROUPS = "groups" + const val EDIT_GROUP = "editGroup" + const val SETTINGS = "settings" + const val CHANGE_SETTING = "changeSetting" + + /** The calls that change nothing, whose answers may be remembered for a moment. */ + val READS = setOf( + GROUPS, + VERSION, SNAPSHOTS, SNAPSHOT, PLUGINS, PLAN, HELD_UNTIL, HISTORY_COUNT, HISTORY_PAGE, BACKUPS, JOURNAL_GROUPS, JOURNAL_DETAIL, + TASKS, MODULES, LIBRARIES, DISK, STATS, + PLACEHOLDERS, SETTINGS, + EVENTS, LISTENERS, EVENT_HISTORY, EVENT_HISTORY_DAYS, TRACED_EVENTS, TRACES, EVENT_ABOUT, OWNER_NAMED, + ) +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuData.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuData.kt new file mode 100644 index 000000000..93b406f1f --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuData.kt @@ -0,0 +1,256 @@ +package org.pnfolder.pnlibrary.core.menu.data + +import net.kyori.adventure.text.Component +import org.pnfolder.pnlibrary.api.config.ConfigEditResult +import org.pnfolder.pnlibrary.api.config.ConfigSetting +import org.pnfolder.pnlibrary.api.events.inspect.EventInfo +import org.pnfolder.pnlibrary.api.events.inspect.ListenerInfo +import org.pnfolder.pnlibrary.api.events.inspect.history.EventDay +import org.pnfolder.pnlibrary.api.events.inspect.trace.EventTrace +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState +import org.pnfolder.pnlibrary.core.commands.modules.DiskReport +import org.pnfolder.pnlibrary.core.commands.modules.LibraryRow +import org.pnfolder.pnlibrary.core.journal.JournalDetail +import org.pnfolder.pnlibrary.core.journal.JournalGroup +import org.pnfolder.pnlibrary.core.link.ServerGroups +import org.pnfolder.pnlibrary.core.menu.OwnerInfo +import org.pnfolder.pnlibrary.core.menu.screens.ConfigRow +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderInfo +import org.pnfolder.pnlibrary.core.stats.StatsSnapshot +import org.pnfolder.pnlibrary.core.tasks.TaskControl +import java.time.Duration +import java.time.Instant +import java.util.UUID +import java.util.concurrent.CompletionStage + +/** State of the pending update plan and what blocks it. */ +data class PlanInfo(val state: UpdateState, val hasChanges: Boolean, val blockers: List) + +/** One plugin line of the plugin list. */ +data class PluginRow(val name: String, val version: String?, val modules: Int) + +/** What an event is for, how to use it, and which plugin owns it. */ +data class EventAbout(val purpose: String, val usage: String, val owner: OwnerInfo?) + +/** Name and permissions of the player who looks at the menu. */ +data class ViewerInfo(val name: String, val permissions: Set) + +/** + * One setting of the library as the menu shows it. + * + * @property kind `SWITCH`, `NUMBER`, `TEXT`, `TIME` or `CHOICE` + * @property range the allowed values in words, or empty + * @property live whether a change starts to work at once; otherwise it waits for a restart + * @property choiceSource the name of the list a `CHOICE` setting is chosen from; the menu builds the list itself, it is not sent + */ +data class SettingRow( + val key: String, + val title: String, + val kind: String, + val description: String, + val current: String, + val default: String, + val changed: Boolean, + val range: String, + val examples: List, + val live: Boolean, + val choiceSource: String = "", +) + +/** What came of changing a setting from the menu: [message] is the reason when [ok] is false, otherwise the new value. */ +data class SettingOutcome(val ok: Boolean, val message: String, val live: Boolean = true) + +/** Kind of change the menu asks a proxy to make to server groups. */ +enum class GroupOp { + CREATE, + + DELETE, + + ADD_SERVER, + + REMOVE_SERVER, + + ADD_PLUGIN, + + REMOVE_PLUGIN, + + NEED, + + /** One server of the group does not need a plugin, whatever the rest do. */ + SKIP, + + RESET, +} + +/** One group change; [server] and [plugin] are set only for operations that need them. */ +data class GroupEdit(val op: GroupOp, val group: String, val server: String? = null, val plugin: String? = null) + +/** + * Everything the menu reads from a server and everything it asks a server to do. + * + * The menu is always built by the server the player stands on. It asks a [MenuData] for the facts: this server's own + * library for its own menu, or another server's library, reached over the link, for the menu of that server. A proxy + * therefore draws nothing; it answers these calls. + * + * Methods that return a [CompletionStage] finish later; the others answer at once on this server and may take a moment + * on another one, so the menu calls them away from the server thread. + */ +interface MenuData { + fun version(): String + + fun snapshots(): List + + /** The update state of one plugin, or null when it did not register. */ + fun snapshot(product: String): UpdateSnapshot? + + fun plugins(): List + + /** The current update plan, or null when there is none. */ + fun plan(): PlanInfo? + + /** Until when updates of [product] are paused, or null. */ + fun heldUntil(product: String): Instant? + + fun historyCount(product: String?): CompletionStage + + fun historyPage(page: Int, product: String?): CompletionStage> + + fun backups(): CompletionStage> + + fun checkAll(actor: UpdateActor): CompletionStage + + /** Asks the catalog of one plugin for a new version; it does not wait for the answer. */ + fun checkOne(product: String, actor: UpdateActor) + + fun setAutomatic(product: String, enabled: Boolean, actor: UpdateActor): CompletionStage + + /** Sets the update channel of [product]; null returns it to the default. */ + fun setChannel(product: String, channel: UpdateChannel?, actor: UpdateActor): CompletionStage + + /** Chooses the Java build of [product]; null returns it to the recommended one. */ + fun setJavaBuild(product: String, java: Int?, actor: UpdateActor): CompletionStage + + /** Pauses updates of [product] for [duration]; null lifts the pause. */ + fun setHeld(product: String, duration: Duration?, actor: UpdateActor): CompletionStage + + fun rollback(id: UUID, restoreConfigurations: Boolean, actor: UpdateActor): CompletionStage + + /** Puts the saved database [name] of [product] back from the set [id]; rows written since are lost. */ + fun restoreDatabase(id: UUID, product: String, name: String, actor: UpdateActor): CompletionStage + + /** Copies the saved files of [product] from the set [id] into a folder and returns its path. */ + fun extractBackup(id: UUID, product: String, actor: UpdateActor): CompletionStage + + /** The journal groups of the last [hours] hours; [level] is `info`, `warning`, `error` or null. */ + fun journalGroups(level: String?, hours: Int, limit: Int): List + + /** The whole journal event behind a group, or null when it is no longer there. */ + fun journalDetail(id: String): JournalDetail? + + fun tasks(): List + + fun stats(): StatsSnapshot + + fun placeholders(): List + + /** The configuration files of this server; another server's files are managed there, so the default is none. */ + fun configs(): List = emptyList() + + /** The settings of one file that may be changed in game, with their values. */ + fun configSettings(id: String): List = emptyList() + + /** Changes one setting of a file of this server and saves it. */ + fun editConfig(id: String, path: String, text: String): ConfigEditResult = + throw UnsupportedOperationException("Настройки меняются на самом сервере") + + /** Every setting of the library of this server with its value; empty when it has none. */ + fun settings(): List = emptyList() + + /** Sets the setting [key] to [value], or returns it to the default when [value] is null. */ + fun changeSetting(key: String, value: String?, actor: UpdateActor): SettingOutcome = + SettingOutcome(false, "Настройки меняются на самом сервере") + + /** Whether missing plugins are downloaded without a command; `null` when this server has no such download. */ + fun downloadsAutomatic(): Boolean? = null + + fun setDownloadsAutomatic(value: Boolean) {} + + /** Plugins other plugins need and the server lacks, grouped by who asks; none when nothing is missing or this server cannot say. */ + fun missingDependencies(): List = emptyList() + + /** Downloads the group with this [code] now and says in a sentence how it went. */ + fun installDependencies(code: String): java.util.concurrent.CompletionStage = + java.util.concurrent.CompletableFuture.completedFuture("Здесь нечего скачивать.") + + /** The modules of the plugins on this server; none when this server cannot switch them. */ + fun modules(): List = emptyList() + + /** Runs one of [ModuleInfo.ACTIONS] on the module [key] and returns how the module looks afterwards. */ + /** The libraries plugins and modules of this server registered; none when this server cannot say. */ + fun libraries(): List = emptyList() + + /** What each plugin takes on the disk of this server. */ + fun disk(): DiskReport = DiskReport.EMPTY + + fun moduleAction(key: String, action: String): ModuleInfo = + throw UnsupportedOperationException("Модули переключаются на самом сервере") + + fun runTask(id: String): TaskControl + + fun cancelTask(id: String): TaskControl + + fun events(): List + + fun listeners(): List + + fun eventHistory(eventType: String?): List + + /** How many days of calls are kept. */ + fun eventHistoryDays(): Int + + fun tracedEvents(): List + + fun traces(): List + + fun clearTraces() + + fun setTracing(eventType: String, enabled: Boolean) + + /** Writes the call history to a file and returns where, or null. */ + fun exportEventHistory(json: Boolean): String? + + /** The purpose and the owner of an event, or null when it is unknown. */ + fun eventAbout(eventType: String): EventAbout? + + fun ownerNamed(name: String): OwnerInfo? + + fun groups(): List + + /** Applies one change to the groups; returns false when there is no such group or the name is unfit. */ + fun editGroup(edit: GroupEdit): Boolean + + fun command(viewer: ViewerInfo, line: String): List +} + +/** + * One group of missing plugins, as the menu shows it. + * + * @property code what `/pn deps install ` takes + * @property owner the plugin that asks for them + * @property installable whether the library can download them (otherwise they are put in by hand) + * @property lines one line per plugin: name, version, required or not + * @property links the addresses to get them from + */ +data class MissingPlugins( + val code: String, + val owner: String, + val installable: Boolean, + val lines: List, + val links: List, +) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuDataServer.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuDataServer.kt similarity index 63% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuDataServer.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuDataServer.kt index 76f09bf9f..55526d86b 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuDataServer.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuDataServer.kt @@ -1,11 +1,18 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.data import com.google.gson.JsonObject import com.google.gson.JsonParser -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.core.link.DataCall -import org.pnfolder.pnlibrary.core.link.DataHandler +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.core.exceptions.rootMessage +import org.pnfolder.pnlibrary.core.link.remote.DataCall +import org.pnfolder.pnlibrary.core.link.remote.DataHandler +import org.pnfolder.pnlibrary.core.menu.style.BUS +import org.pnfolder.pnlibrary.core.menu.style.GROUPS_PERMISSION +import org.pnfolder.pnlibrary.core.menu.style.MenuPermissions +import org.pnfolder.pnlibrary.core.menu.style.ROLLBACK +import org.pnfolder.pnlibrary.core.menu.style.SETTINGS +import org.pnfolder.pnlibrary.core.menu.style.TASKS import java.time.Duration import java.util.UUID import java.util.concurrent.CompletionStage @@ -18,12 +25,18 @@ import java.util.concurrent.ExecutorService * It only reads the facts and carries out the actions of [MenuData]; it never draws anything. The server of the viewer * builds the menu from the answers. * + * Actions that change something, and commands, are allowed only when this server itself knows the viewer and says they + * hold the permission: what the asking server writes in the request is never taken as a right. + * * @param data the facts of this server * @param executor where the questions are answered, away from the thread that received them + * @param holds whether the player of that name, as this server sees them, has the permission; false for a player this + * server does not know */ class MenuDataServer( private val data: MenuData, private val executor: Executor, + private val holds: (viewer: String, permission: String) -> Boolean, ) : DataHandler, AutoCloseable { override fun close() { (executor as? ExecutorService)?.shutdown() @@ -43,14 +56,23 @@ class MenuDataServer( val args = runCatching { JsonParser.parseString(call.args).asJsonObject }.getOrDefault(JsonObject()) val actor = UpdateActor(UpdateActor.Kind.INTEGRATION, "remote:${call.origin}", "${call.viewer.ifEmpty { "игрок" }} (${call.origin})") val ask = Question(call, args, actor, reply) - if (updates(ask) || journalAndTasks(ask) || events(ask) || network(ask)) return + val needed = REQUIRED[call.method] + if (needed != null && !allowed(call.viewer, needed)) { + reply(false, "Не хватает права: $needed") + return + } + if (updates(ask) || journalAndTasks(ask) || events(ask) || network(ask) || librarySettings(ask)) return reply(false, "Неизвестный запрос: ${call.method}") } + private fun allowed(viewer: String, permission: String): Boolean = + holds(viewer, permission) || holds(viewer, MenuPermissions.ADMIN) + + /** Pending confirmation of a data call awaiting the player's answer. */ private class Question(val call: DataCall, val args: JsonObject, val actor: UpdateActor, val reply: (Boolean, String) -> Unit) { fun text(name: String): String? = args.get(name)?.takeIf { !it.isJsonNull }?.asString - fun give(value: Any?) = reply(true, MenuCalls.gson.toJson(value)) + fun give(value: Any?) = reply(true, MenuWire.gson.toJson(value)) fun done(stage: CompletionStage) { stage.whenComplete { value, error -> finish(reply, value, error) } @@ -80,11 +102,20 @@ class MenuDataServer( val channel = text("channel")?.let { name -> UpdateChannel.values().firstOrNull { it.name == name } } done(data.setChannel(text("product").orEmpty(), channel, actor)) } + MenuCalls.SET_JAVA_BUILD -> { + val java = args.get("java")?.takeIf { !it.isJsonNull }?.asInt + done(data.setJavaBuild(text("product").orEmpty(), java, actor)) + } MenuCalls.SET_HELD -> { val duration = args.get("millis")?.takeIf { !it.isJsonNull }?.asLong?.let(Duration::ofMillis) done(data.setHeld(text("product").orEmpty(), duration, actor)) } MenuCalls.ROLLBACK -> done(data.rollback(UUID.fromString(text("id")), args.get("restore")?.asBoolean == true, actor)) + MenuCalls.RESTORE_DATABASE -> done( + data.restoreDatabase(UUID.fromString(text("id")), requireNotNull(text("product")), requireNotNull(text("name")), actor), + ) + MenuCalls.EXTRACT_BACKUP -> data.extractBackup(UUID.fromString(text("id")), requireNotNull(text("product")), actor) + .whenComplete { value, error -> finish(reply, value, error) } else -> return@with false } true @@ -96,6 +127,10 @@ class MenuDataServer( MenuCalls.JOURNAL_GROUPS -> give(data.journalGroups(text("level"), args.get("hours")?.asInt ?: 24, args.get("limit")?.asInt ?: 200)) MenuCalls.JOURNAL_DETAIL -> give(data.journalDetail(text("id").orEmpty())) MenuCalls.TASKS -> give(data.tasks()) + MenuCalls.MODULES -> give(data.modules()) + MenuCalls.LIBRARIES -> give(data.libraries()) + MenuCalls.DISK -> give(data.disk()) + MenuCalls.MODULE_ACTION -> give(data.moduleAction(text("key").orEmpty(), text("action").orEmpty())) MenuCalls.STATS -> give(data.stats()) MenuCalls.PLACEHOLDERS -> give(data.placeholders()) MenuCalls.RUN_TASK -> give(data.runTask(text("id").orEmpty())) @@ -129,6 +164,16 @@ class MenuDataServer( true } + /** The settings of the library. Returns false when the question is not one of these. */ + private fun librarySettings(ask: Question): Boolean = with(ask) { + when (call.method) { + MenuCalls.SETTINGS -> give(data.settings()) + MenuCalls.CHANGE_SETTING -> give(data.changeSetting(text("key").orEmpty(), text("value"), actor)) + else -> return@with false + } + true + } + /** Owners, server groups and chat commands. Returns false when the question is not one of these. */ private fun network(ask: Question): Boolean = with(ask) { when (call.method) { @@ -139,9 +184,9 @@ class MenuDataServer( give(data.editGroup(GroupEdit(op, text("group").orEmpty(), text("server"), text("plugin")))) } MenuCalls.COMMAND -> { - val permissions = args.getAsJsonArray("permissions")?.map { it.asString }?.toSet().orEmpty() + val permissions = MenuPermissions.ALL.filter { holds(call.viewer, it) }.toSet() val viewer = ViewerInfo(call.viewer.ifEmpty { "игрок" }, permissions) - give(MenuCalls.encodeLines(data.command(viewer, text("line").orEmpty()))) + give(MenuWire.encodeLines(data.command(viewer, text("line").orEmpty()))) } else -> return@with false @@ -151,6 +196,24 @@ class MenuDataServer( } private fun finish(reply: (Boolean, String) -> Unit, value: Any?, error: Throwable?) { - if (error != null) reply(false, generateSequence(error) { it.cause }.last().let { it.message ?: it.javaClass.simpleName }) - else reply(true, MenuCalls.gson.toJson(value)) + if (error != null) reply(false, error.rootMessage()) + else reply(true, MenuWire.gson.toJson(value)) } + +private val REQUIRED: Map = mapOf( + MenuCalls.CHECK_ALL to MenuPermissions.UPDATES_DOWNLOAD, + MenuCalls.CHECK_ONE to MenuPermissions.UPDATES_DOWNLOAD, + MenuCalls.SET_AUTOMATIC to SETTINGS, + MenuCalls.SET_CHANNEL to SETTINGS, + MenuCalls.SET_HELD to SETTINGS, + MenuCalls.ROLLBACK to ROLLBACK, + MenuCalls.RESTORE_DATABASE to ROLLBACK, + MenuCalls.EXTRACT_BACKUP to ROLLBACK, + MenuCalls.RUN_TASK to TASKS, + MenuCalls.CANCEL_TASK to TASKS, + MenuCalls.MODULE_ACTION to MenuPermissions.MODULES, + MenuCalls.SET_TRACING to BUS, + MenuCalls.CLEAR_TRACES to BUS, + MenuCalls.EDIT_GROUP to GROUPS_PERMISSION, + MenuCalls.CHANGE_SETTING to MenuPermissions.LIBRARY_SETTINGS, +) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuWire.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuWire.kt new file mode 100644 index 000000000..be86f5b81 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuWire.kt @@ -0,0 +1,35 @@ +package org.pnfolder.pnlibrary.core.menu.data + +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import com.google.gson.JsonDeserializer +import com.google.gson.JsonPrimitive +import com.google.gson.JsonSerializer +import com.google.gson.reflect.TypeToken +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer +import java.lang.reflect.Type +import java.time.Duration +import java.time.Instant +import java.time.LocalDate + +/** How the menu's questions and answers are written as JSON on the link. */ +object MenuWire { + val gson: Gson = GsonBuilder() + .registerTypeAdapter(Instant::class.java, JsonSerializer { value, _, _ -> JsonPrimitive(value.toString()) }) + .registerTypeAdapter(Instant::class.java, JsonDeserializer { json, _, _ -> Instant.parse(json.asString) }) + .registerTypeAdapter(Duration::class.java, JsonSerializer { value, _, _ -> JsonPrimitive(value.toMillis()) }) + .registerTypeAdapter(Duration::class.java, JsonDeserializer { json, _, _ -> Duration.ofMillis(json.asLong) }) + .registerTypeAdapter(LocalDate::class.java, JsonSerializer { value, _, _ -> JsonPrimitive(value.toString()) }) + .registerTypeAdapter(LocalDate::class.java, JsonDeserializer { json, _, _ -> LocalDate.parse(json.asString) }) + .create() + + private val chat = GsonComponentSerializer.gson() + + fun encodeLines(lines: List): List = lines.map(chat::serialize) + + /** The chat messages in [texts]; one that cannot be read is skipped. */ + fun decodeLines(texts: List): List = texts.mapNotNull { runCatching { chat.deserialize(it) }.getOrNull() } + + inline fun typeOf(): Type = object : TypeToken() {}.type +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/ModuleInfo.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/ModuleInfo.kt new file mode 100644 index 000000000..f9cd64d09 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/ModuleInfo.kt @@ -0,0 +1,65 @@ +package org.pnfolder.pnlibrary.core.menu.data + +import org.pnfolder.pnlibrary.api.plugin.ModuleContext +import org.pnfolder.pnlibrary.api.plugin.control.ModuleState +import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.core.commands.modules.ModuleLabels + +/** One module of a plugin as the menu sees it; plain values, so it also crosses to another server. */ +data class ModuleInfo( + val key: String, + val plugin: String, + val title: String, + val state: ModuleState, + val autoStart: Boolean, + val controllable: Boolean, + val error: String?, + /** The libraries the module registered itself, as `group:artifact:version`. */ + val libraries: List = emptyList(), + /** The libraries its plugin registered for all of its modules. */ + val pluginLibraries: List = emptyList(), + /** What the module is for, as its plugin wrote it; `null` when it did not. */ + val description: String? = null, +) { + companion object { + /** What can be done to a module; the words are the ones `/pn modules` uses. */ + val ACTIONS = listOf("enable", "disable", "restart", "reload", "auto-on", "auto-off") + + fun of(key: String, module: ModuleContext, pluginLibraries: List = emptyList()): ModuleInfo = ModuleInfo( + key = key, + plugin = module.metadata.name, + title = ModuleLabels.title(module), + state = module.control.state, + autoStart = module.control.autoStart, + controllable = module.control.isControllable, + error = module.control.lastError?.let { it.message ?: it.javaClass.simpleName }, + libraries = module.libraries.loaded.map { it.coordinates }, + pluginLibraries = pluginLibraries, + description = module.metadata.description, + ) + + fun all(library: PnLibrary): List = + library.plugins.all().flatMap { plugin -> + val shared = plugin.libraries.loaded.map { it.coordinates } + plugin.all().map { of("${plugin.id.value}:${it.id.value}", it, shared) } + }.sortedBy { it.key } + + /** Runs [action] on the module [key] and returns how it looks afterwards. */ + fun apply(library: PnLibrary, key: String, action: String): ModuleInfo { + val module = ModuleLabels.named(library).firstOrNull { it.first == key }?.second + ?: throw IllegalArgumentException("Модуль $key не найден") + require(action in ACTIONS) { "Неизвестное действие: $action" } + val control = module.control + when (action) { + "enable" -> control.enable() + "disable" -> control.disable() + "restart" -> control.restart() + "reload" -> control.reload() + "auto-on" -> control.setAutoStart(true) + else -> control.setAutoStart(false) + } + val plugin = library.plugins.all().first { registration -> registration.all().any { it === module } } + return of(key, module, plugin.libraries.loaded.map { it.coordinates }) + } + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/RemoteMenuData.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/RemoteMenuData.kt similarity index 63% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/RemoteMenuData.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/RemoteMenuData.kt index 9fb034d50..555fb3458 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/RemoteMenuData.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/data/RemoteMenuData.kt @@ -1,37 +1,35 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.data -import com.google.gson.Gson -import com.google.gson.GsonBuilder -import com.google.gson.JsonArray -import com.google.gson.JsonDeserializer import com.google.gson.JsonObject -import com.google.gson.JsonPrimitive -import com.google.gson.JsonSerializer -import com.google.gson.reflect.TypeToken import net.kyori.adventure.text.Component -import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer -import org.pnfolder.pnlibrary.api.events.EventDay -import org.pnfolder.pnlibrary.api.events.EventInfo -import org.pnfolder.pnlibrary.api.events.EventTrace -import org.pnfolder.pnlibrary.api.events.ListenerInfo -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot +import org.pnfolder.pnlibrary.api.events.inspect.EventInfo +import org.pnfolder.pnlibrary.api.events.inspect.ListenerInfo +import org.pnfolder.pnlibrary.api.events.inspect.history.EventDay +import org.pnfolder.pnlibrary.api.events.inspect.trace.EventTrace +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup -import org.pnfolder.pnlibrary.api.updates.backup.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.core.commands.modules.DiskReport +import org.pnfolder.pnlibrary.core.commands.modules.LibraryRow import org.pnfolder.pnlibrary.core.journal.JournalDetail import org.pnfolder.pnlibrary.core.journal.JournalGroup -import org.pnfolder.pnlibrary.core.link.DataClient -import org.pnfolder.pnlibrary.core.link.DataException import org.pnfolder.pnlibrary.core.link.ServerGroups -import org.pnfolder.pnlibrary.core.placeholders.PlaceholderInfo +import org.pnfolder.pnlibrary.core.link.remote.DataClient +import org.pnfolder.pnlibrary.core.link.remote.DataException +import org.pnfolder.pnlibrary.core.menu.OwnerInfo +import org.pnfolder.pnlibrary.core.menu.style.HISTORY_PAGE +import org.pnfolder.pnlibrary.core.menu.style.PLACEHOLDERS +import org.pnfolder.pnlibrary.core.menu.style.ROLLBACK +import org.pnfolder.pnlibrary.core.menu.style.STATS +import org.pnfolder.pnlibrary.core.menu.style.TASKS +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderInfo import org.pnfolder.pnlibrary.core.stats.StatsSnapshot import org.pnfolder.pnlibrary.core.tasks.TaskControl -import java.lang.reflect.Type import java.time.Duration import java.time.Instant -import java.time.LocalDate import java.util.UUID import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage @@ -39,71 +37,6 @@ import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit -object MenuCalls { - const val VERSION = "version" - const val SNAPSHOTS = "snapshots" - const val SNAPSHOT = "snapshot" - const val PLUGINS = "plugins" - const val PLAN = "plan" - const val HELD_UNTIL = "heldUntil" - const val HISTORY_COUNT = "historyCount" - const val HISTORY_PAGE = "historyPage" - const val BACKUPS = "backups" - const val CHECK_ALL = "checkAll" - const val CHECK_ONE = "checkOne" - const val SET_AUTOMATIC = "setAutomatic" - const val SET_CHANNEL = "setChannel" - const val SET_HELD = "setHeld" - const val ROLLBACK = "rollback" - const val JOURNAL_GROUPS = "journalGroups" - const val JOURNAL_DETAIL = "journalDetail" - const val TASKS = "tasks" - const val STATS = "stats" - const val PLACEHOLDERS = "placeholders" - const val RUN_TASK = "runTask" - const val CANCEL_TASK = "cancelTask" - const val EVENTS = "events" - const val LISTENERS = "listeners" - const val EVENT_HISTORY = "eventHistory" - const val EVENT_HISTORY_DAYS = "eventHistoryDays" - const val TRACED_EVENTS = "tracedEvents" - const val TRACES = "traces" - const val CLEAR_TRACES = "clearTraces" - const val SET_TRACING = "setTracing" - const val EXPORT_EVENT_HISTORY = "exportEventHistory" - const val EVENT_ABOUT = "eventAbout" - const val OWNER_NAMED = "ownerNamed" - const val COMMAND = "command" - const val GROUPS = "groups" - const val EDIT_GROUP = "editGroup" - - /** The calls that change nothing, whose answers may be remembered for a moment. */ - val READS = setOf( - GROUPS, - VERSION, SNAPSHOTS, SNAPSHOT, PLUGINS, PLAN, HELD_UNTIL, HISTORY_COUNT, HISTORY_PAGE, BACKUPS, JOURNAL_GROUPS, JOURNAL_DETAIL, TASKS, STATS, - PLACEHOLDERS, - EVENTS, LISTENERS, EVENT_HISTORY, EVENT_HISTORY_DAYS, TRACED_EVENTS, TRACES, EVENT_ABOUT, OWNER_NAMED, - ) - - val gson: Gson = GsonBuilder() - .registerTypeAdapter(Instant::class.java, JsonSerializer { value, _, _ -> JsonPrimitive(value.toString()) }) - .registerTypeAdapter(Instant::class.java, JsonDeserializer { json, _, _ -> Instant.parse(json.asString) }) - .registerTypeAdapter(Duration::class.java, JsonSerializer { value, _, _ -> JsonPrimitive(value.toMillis()) }) - .registerTypeAdapter(Duration::class.java, JsonDeserializer { json, _, _ -> Duration.ofMillis(json.asLong) }) - .registerTypeAdapter(LocalDate::class.java, JsonSerializer { value, _, _ -> JsonPrimitive(value.toString()) }) - .registerTypeAdapter(LocalDate::class.java, JsonDeserializer { json, _, _ -> LocalDate.parse(json.asString) }) - .create() - - private val chat = GsonComponentSerializer.gson() - - fun encodeLines(lines: List): List = lines.map(chat::serialize) - - /** The chat messages in [texts]; one that cannot be read is skipped. */ - fun decodeLines(texts: List): List = texts.mapNotNull { runCatching { chat.deserialize(it) }.getOrNull() } - - inline fun typeOf(): Type = object : TypeToken() {}.type -} - /** * The library of another server, reached over the link. * @@ -118,6 +51,7 @@ class RemoteMenuData( private val target: String, private val client: DataClient, ) : MenuData { + /** Cached remote response with the time it was received. */ private class Remembered(val at: Long, val json: String) private val remembered = ConcurrentHashMap() @@ -153,9 +87,18 @@ class RemoteMenuData( override fun setChannel(product: String, channel: UpdateChannel?, actor: UpdateActor): CompletionStage = later { ask(MenuCalls.SET_CHANNEL, args("product" to product, "channel" to channel?.name), actor.name) } + override fun setJavaBuild(product: String, java: Int?, actor: UpdateActor): CompletionStage = + later { ask(MenuCalls.SET_JAVA_BUILD, args("product" to product, "java" to java), actor.name) } + override fun setHeld(product: String, duration: Duration?, actor: UpdateActor): CompletionStage = later { ask(MenuCalls.SET_HELD, args("product" to product, "millis" to duration?.toMillis()), actor.name) } + override fun extractBackup(id: UUID, product: String, actor: UpdateActor): CompletionStage = + later { ask(MenuCalls.EXTRACT_BACKUP, args("id" to id.toString(), "product" to product), actor.name) } + + override fun restoreDatabase(id: UUID, product: String, name: String, actor: UpdateActor): CompletionStage = + later { ask(MenuCalls.RESTORE_DATABASE, args("id" to id.toString(), "product" to product, "name" to name), actor.name) } + override fun rollback(id: UUID, restoreConfigurations: Boolean, actor: UpdateActor): CompletionStage = later { ask(MenuCalls.ROLLBACK, args("id" to id.toString(), "restore" to restoreConfigurations), actor.name) } @@ -166,6 +109,15 @@ class RemoteMenuData( override fun tasks(): List = ask(MenuCalls.TASKS) + override fun modules(): List = ask(MenuCalls.MODULES) + + override fun libraries(): List = ask(MenuCalls.LIBRARIES) + + override fun disk(): DiskReport = ask(MenuCalls.DISK) + + override fun moduleAction(key: String, action: String): ModuleInfo = + ask(MenuCalls.MODULE_ACTION, args("key" to key, "action" to action)) + override fun stats(): StatsSnapshot = ask(MenuCalls.STATS) override fun placeholders(): List = ask(MenuCalls.PLACEHOLDERS) @@ -200,15 +152,19 @@ class RemoteMenuData( override fun ownerNamed(name: String): OwnerInfo? = ask(MenuCalls.OWNER_NAMED, args("name" to name)) + override fun settings(): List = ask(MenuCalls.SETTINGS) + + override fun changeSetting(key: String, value: String?, actor: UpdateActor): SettingOutcome = + ask(MenuCalls.CHANGE_SETTING, args("key" to key, "value" to value), actor.name) + override fun groups(): List = ask(MenuCalls.GROUPS) override fun editGroup(edit: GroupEdit): Boolean = ask(MenuCalls.EDIT_GROUP, args("op" to edit.op.name, "group" to edit.group, "server" to edit.server, "plugin" to edit.plugin)) override fun command(viewer: ViewerInfo, line: String): List { - val permissions = JsonArray().also { array -> viewer.permissions.forEach { array.add(it) } } - val lines = ask>(MenuCalls.COMMAND, args("line" to line).also { it.add("permissions", permissions) }, viewer.name) - return MenuCalls.decodeLines(lines) + val lines = ask>(MenuCalls.COMMAND, args("line" to line), viewer.name) + return MenuWire.decodeLines(lines) } private fun args(vararg pairs: Pair): JsonObject = JsonObject().also { json -> @@ -238,7 +194,7 @@ class RemoteMenuData( val json = remembered[key]?.takeIf { reads && now - it.at < REMEMBER_NANOS }?.json ?: wait(method, args, viewer).also { if (reads) remembered[key] = Remembered(now, it) else remembered.clear() } - return MenuCalls.gson.fromJson(json, MenuCalls.typeOf()) + return MenuWire.gson.fromJson(json, MenuWire.typeOf()) } private fun wait(method: String, args: JsonObject, viewer: String): String = try { diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/BusHistoryScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/BusHistoryScreens.kt similarity index 81% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/BusHistoryScreens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/BusHistoryScreens.kt index e0694325a..f5f542dfb 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/BusHistoryScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/BusHistoryScreens.kt @@ -1,10 +1,31 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.screens -import org.pnfolder.pnlibrary.api.events.DispatchMode -import org.pnfolder.pnlibrary.api.events.EventTrace +import org.pnfolder.pnlibrary.api.events.bus.DispatchMode +import org.pnfolder.pnlibrary.api.events.inspect.trace.EventTrace import org.pnfolder.pnlibrary.common.time.DisplayZone +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.style.FILTER +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.TITLE_LIMIT +import org.pnfolder.pnlibrary.core.menu.style.ago +import org.pnfolder.pnlibrary.core.menu.style.clockStamp +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.progressBar +import org.pnfolder.pnlibrary.core.text.dayTitle +import org.pnfolder.pnlibrary.core.text.nanosText +import org.pnfolder.pnlibrary.core.text.shortName import java.time.LocalDate +private const val TRACE_STEPS = 6 + +/** Menu screens listing recent event bus history. */ internal class BusHistoryScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { fun busDays(player: MenuViewer, event: String?, page: Int) { val back: (MenuViewer) -> Unit = if (event == null) { who -> routes.busHome(who) } else { who -> routes.busEvent(who, event) { routes.busHome(it) } } @@ -18,7 +39,7 @@ internal class BusHistoryScreens(session: MenuSession, routes: MenuRoutes) : Men add("Вызовов" to "$total") if (event == null) add("Событий" to "${entries.size}") if (denied > 0) add("Отказов" to "$denied") - add("Нагрузка" to bar(total, busiest)) + add("Нагрузка" to progressBar(total, busiest)) } val hint = if (event == null) Style.left("события этого дня") else Style.left("открыть событие") val click = if (event == null) go { who -> busDay(who, date, 0, page) } else go { who -> routes.busEvent(who, event) { busDays(it, event, page) } } @@ -36,7 +57,7 @@ internal class BusHistoryScreens(session: MenuSession, routes: MenuRoutes) : Men val parameters = buildList { add("Вызовов" to "${day.calls}") if (day.denied > 0) add("Отказов" to "${day.denied}") - add("Нагрузка" to bar(day.calls, busiest)) + add("Нагрузка" to progressBar(day.calls, busiest)) } Row( icon(null, "PAPER", shortName(day.eventType), Style.lore(emptyList(), parameters, Style.left("открыть событие")), warn = day.denied > 0), @@ -77,7 +98,7 @@ internal class BusHistoryScreens(session: MenuSession, routes: MenuRoutes) : Men "" to "$owner · $action" } val parameters = buildList { - trace.at?.let { add("Когда" to stamp(it)); add("" to ago(it)) } + trace.at?.let { add("Когда" to clockStamp(it)); add("" to ago(it)) } add("Результат" to (trace.result ?: "-")) add("Режим" to if (trace.mode == DispatchMode.ASYNC) "async, мир не трогать" else "sync") add("Поток" to trace.thread) @@ -104,11 +125,11 @@ internal class BusHistoryScreens(session: MenuSession, routes: MenuRoutes) : Men add("Приоритет" to "${step.priority}") add("Что сделал" to action) if (step.changedResult) add("Результат" to "${step.resultBefore} → ${step.resultAfter}") - if (!step.skipped) add("Время" to duration(step.nanos)) + if (!step.skipped) add("Время" to nanosText(step.nanos)) } Row(icon(null, "PAPER", owner, Style.lore(emptyList(), parameters), danger = step.failed, warn = step.changedResult, muted = step.skipped)) } - val title = "${shortName(trace.eventName)}${trace.at?.let { ", ${stamp(it)}" }.orEmpty()}" + val title = "${shortName(trace.eventName)}${trace.at?.let { ", ${clockStamp(it)}" }.orEmpty()}" list(player, title.take(TITLE_LIMIT), rows, page, PAGE_SIZE, { who, to -> busTrace(who, trace, to, back) }, back, "Никто не отвечал") } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/BusScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/BusScreens.kt similarity index 83% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/BusScreens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/BusScreens.kt index 47dde403c..89a515e0c 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/BusScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/BusScreens.kt @@ -1,12 +1,43 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.screens -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.events.EventInfo -import org.pnfolder.pnlibrary.api.events.ListenerInfo +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.api.events.inspect.EventInfo +import org.pnfolder.pnlibrary.api.events.inspect.ListenerInfo import org.pnfolder.pnlibrary.common.time.DisplayZone +import org.pnfolder.pnlibrary.core.menu.ClickType +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuBuilder +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.Menus +import org.pnfolder.pnlibrary.core.menu.style.DETAIL_BACK +import org.pnfolder.pnlibrary.core.menu.style.DETAIL_ROWS +import org.pnfolder.pnlibrary.core.menu.style.FILTER +import org.pnfolder.pnlibrary.core.menu.style.HOME_CLOSE +import org.pnfolder.pnlibrary.core.menu.style.HOME_ROWS +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.MESSAGE_PREVIEW +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.ago +import org.pnfolder.pnlibrary.core.menu.style.backItem +import org.pnfolder.pnlibrary.core.menu.style.clockStamp +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.menuFrame +import org.pnfolder.pnlibrary.core.menu.style.menuTitle +import org.pnfolder.pnlibrary.core.menu.style.section +import org.pnfolder.pnlibrary.core.text.dayTitle +import org.pnfolder.pnlibrary.core.text.nanosText +import org.pnfolder.pnlibrary.core.text.shortName +import org.pnfolder.pnlibrary.core.text.wrapText import java.time.LocalDate +/** Menu screens for event bus overview, events and listeners. */ internal class BusScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { + /** Filter applied to the event list. */ private enum class BusFilter(val label: String, val keep: (EventInfo) -> Boolean) { ALL("все", { true }), LISTENED("со слушателями", { it.listeners > 0 }), @@ -22,7 +53,7 @@ internal class BusScreens(session: MenuSession, routes: MenuRoutes) : MenuScreen val calls = data.eventHistory(null).filter { it.date == today }.sumOf { it.calls } val failures = listeners.sumOf { it.failures } val traced = data.tracedEvents().size - val builder = frame(Menus.chest(title("События плагинов")).rows(HOME_ROWS), HOME_ROWS) + val builder = menuFrame(Menus.chest(menuTitle("События плагинов")).rows(HOME_ROWS), HOME_ROWS) busSummary(builder, events.size, listeners.size, calls, failures) busButtons(builder, events.size, listeners.size, failures, traced) builder.button(HOME_CLOSE, backItem(), go { routes.home(it) }) @@ -35,7 +66,7 @@ internal class BusScreens(session: MenuSession, routes: MenuRoutes) : MenuScreen icon( Icons.OVERVIEW, "NETHER_STAR", "События плагинов", Style.lore( - wrap("Так плагины сообщают друг другу, что произошло. Одни вызывают событие, другие слушают его и отвечают."), + wrapText("Так плагины сообщают друг другу, что произошло. Одни вызывают событие, другие слушают его и отвечают."), listOf( "Событий" to "$events", "Слушателей" to "$listeners", @@ -130,12 +161,12 @@ internal class BusScreens(session: MenuSession, routes: MenuRoutes) : MenuScreen val recording = info.eventType in data.tracedEvents() val about = routes.aboutOf(info.eventType) val owner = about?.owner - val purpose = about?.purpose?.takeIf { it.isNotBlank() }?.let { wrap(it, limit = 3) }.orEmpty() + val purpose = about?.purpose?.takeIf { it.isNotBlank() }?.let { wrapText(it, limit = 3) }.orEmpty() val parameters = buildList { add("Плагин" to (owner?.let { routes.versioned(it) } ?: "сервер или библиотека")) add("Слушателей" to "${info.listeners}") add("Вызовов" to "${info.calls}") - info.lastCalledAt?.let { add("Последний" to "${stamp(it)}, ${ago(it)}") } + info.lastCalledAt?.let { add("Последний" to "${clockStamp(it)}, ${ago(it)}") } if (info.denied > 0) add("Отказов" to "${info.denied}") add("Запись" to if (recording) "● идёт" else "не ведётся") } @@ -150,7 +181,7 @@ internal class BusScreens(session: MenuSession, routes: MenuRoutes) : MenuScreen tell(player, ChatTone.INFO, "Такого события больше нет.") return back(player) } - val builder = frame(Menus.chest(title(shortName(name))).rows(DETAIL_ROWS), DETAIL_ROWS) + val builder = menuFrame(Menus.chest(menuTitle(shortName(name))).rows(DETAIL_ROWS), DETAIL_ROWS) builder.slot(4, eventCard(name, info)) eventButtons(builder, name, info, back) builder.button(DETAIL_BACK, backItem(), go { back(it) }) @@ -164,12 +195,12 @@ internal class BusScreens(session: MenuSession, routes: MenuRoutes) : MenuScreen add("Слушателей" to "${info.listeners}") add("Вызовов" to "${info.calls}") add("Отказов" to "${info.denied}") - add("Последний вызов" to (info.lastCalledAt?.let { "${stamp(it)}, ${ago(it)}" } ?: "с запуска не было")) + add("Последний вызов" to (info.lastCalledAt?.let { "${clockStamp(it)}, ${ago(it)}" } ?: "с запуска не было")) addAll(eventDays(name)) addAll(routes.labelled("Класс", name)) about?.usage?.takeIf { it.isNotBlank() }?.let { addAll(routes.labelled("Как использовать", it)) } } - val purpose = about?.purpose?.takeIf { it.isNotBlank() }?.let { wrap(it) } ?: listOf("Автор плагина не описал это событие.") + val purpose = about?.purpose?.takeIf { it.isNotBlank() }?.let { wrapText(it) } ?: listOf("Автор плагина не описал это событие.") return icon(null, "NETHER_STAR", shortName(name), Style.lore(purpose, parameters)) } @@ -208,6 +239,7 @@ internal class BusScreens(session: MenuSession, routes: MenuRoutes) : MenuScreen data.setTracing(name, name !in data.tracedEvents()) } + /** Search and paging state of the listener list. */ private class ListenerQuery( val title: String, val back: (MenuViewer) -> Unit, @@ -230,8 +262,8 @@ internal class BusScreens(session: MenuSession, routes: MenuRoutes) : MenuScreen add("Событие" to shortName(info.eventType)) add("Приоритет" to "${info.priority}") add("Запусков" to "${info.invocations}") - add("Среднее" to duration(info.averageNanos)) - add("Максимум" to duration(info.maxNanos)) + add("Среднее" to nanosText(info.averageNanos)) + add("Максимум" to nanosText(info.maxNanos)) if (info.failures > 0) add("Ошибок" to "✖ ${info.failures}") if (info.ignoreDenied) add("Особенность" to "работает даже после отказа") add("Откуда" to info.source.take(MESSAGE_PREVIEW)) @@ -247,7 +279,7 @@ internal class BusScreens(session: MenuSession, routes: MenuRoutes) : MenuScreen add("Слушателей" to "${group.size}") add("Событий" to "${group.map { it.eventType }.distinct().size}") add("Запусков" to "${group.sumOf { it.invocations }}") - add("Время всего" to duration(group.sumOf { it.totalNanos })) + add("Время всего" to nanosText(group.sumOf { it.totalNanos })) if (failures > 0) add("Ошибок" to "✖ $failures") } val query = ListenerQuery( diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/ConfigPickers.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/ConfigPickers.kt new file mode 100644 index 000000000..192f731fd --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/ConfigPickers.kt @@ -0,0 +1,111 @@ +package org.pnfolder.pnlibrary.core.menu.screens + +import org.pnfolder.pnlibrary.api.config.ConfigSetting +import org.pnfolder.pnlibrary.api.config.ConfigSettingKind +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.Menus +import org.pnfolder.pnlibrary.core.menu.style.ConfigLook +import org.pnfolder.pnlibrary.core.menu.style.ConfigNumbers +import org.pnfolder.pnlibrary.core.menu.style.DATE_FILTER +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.SMALL_BACK +import org.pnfolder.pnlibrary.core.menu.style.SMALL_ROWS +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.TITLE_LIMIT +import org.pnfolder.pnlibrary.core.menu.style.backItem +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.menuFrame +import org.pnfolder.pnlibrary.core.menu.style.menuTitle +import org.pnfolder.pnlibrary.core.text.WRAP_WIDTH +import org.pnfolder.pnlibrary.core.text.wrapText + +/** Writes [text] into a setting, then runs [after] with the viewer; the screens that edit a value share it. */ +internal typealias SettingWriter = (MenuViewer, ConfigSetting, String, (MenuViewer) -> Unit) -> Unit + +/** + * The two screens that edit a setting more comfortably than a click on its item: a number editor with steps of + * different size, and a paged list of choices for a setting that has many. + */ +internal class ConfigPickers(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { + private fun setting(id: String, path: String): ConfigSetting? = data.configSettings(id).firstOrNull { it.path == path } + + /** The number editor: the value in the middle, steps down on the left, steps up on the right. */ + fun number(player: MenuViewer, id: String, path: String, back: (MenuViewer) -> Unit, write: SettingWriter, ask: (MenuViewer, ConfigSetting) -> Unit) { + val setting = setting(id, path)?.takeIf { it.value?.toDoubleOrNull() != null } ?: return back(player) + val current = requireNotNull(setting.value).toDouble() + val builder = menuFrame(Menus.chest(menuTitle(setting.title.take(TITLE_LIMIT))).rows(SMALL_ROWS + 1), SMALL_ROWS + 1) + val again = { who: MenuViewer -> number(who, id, path, back, write, ask) } + builder.slot(VALUE, ConfigLook.setting(setting, true)) + ConfigNumbers.ladder(setting).forEachIndexed { index, (label, amount) -> + builder.button(VALUE - 1 - index, stepItem("−", label, true), go { who -> write(who, setting, text(setting, current - amount), again) }) + builder.button(VALUE + 1 + index, stepItem("+", label, false), go { who -> write(who, setting, text(setting, current + amount), again) }) + } + builder.button( + TYPE, + icon(Icons.CHANGELOG, "NAME_TAG", "Ввести значение", Style.lore(typingHelp(setting), emptyList(), Style.left("написать в чате"))), + go { who -> ask(who, setting) }, + ) + setting.min?.let { limit -> builder.button(LOW, edge("Минимум", limit, setting), go { who -> write(who, setting, text(setting, limit), again) }) } + setting.max?.let { limit -> builder.button(HIGH, edge("Максимум", limit, setting), go { who -> write(who, setting, text(setting, limit), again) }) } + builder.button(SMALL_BACK, backItem(), go { back(it) }) + show(player, builder.build()) + } + + private fun typingHelp(setting: ConfigSetting): List { + val base = if (setting.kind == ConfigSettingKind.INTEGER) "Целое число." else "Число, дробная часть через точку." + val time = if (setting.duration != null) " Время можно писать так: 90m, 1h30m, 45с, 2д." else "" + return wrapText(base + time, WRAP_WIDTH, 3) + } + + private fun stepItem(sign: String, label: String, down: Boolean): ItemSpec = + icon( + null, if (down) "RED_DYE" else "LIME_DYE", "$sign $label", + Style.lore(emptyList(), emptyList(), Style.left(if (down) "уменьшить" else "увеличить")), danger = down, good = !down, + ) + + private fun edge(name: String, limit: Double, setting: ConfigSetting): ItemSpec = + icon( + Icons.CLOCK, "CLOCK", name, + Style.lore(emptyList(), listOf("Значение" to ConfigNumbers.shown(setting.copy(value = ConfigLook.number(limit)))), Style.left("поставить")), + ) + + /** Rounds to what the field holds: whole numbers without a fraction, decimals to thousandths. */ + private fun text(setting: ConfigSetting, value: Double): String { + val bounded = value.coerceIn(setting.min ?: -Double.MAX_VALUE, setting.max ?: Double.MAX_VALUE) + return if (setting.kind == ConfigSettingKind.INTEGER) Math.round(bounded).toString() else ConfigLook.number(Math.round(bounded * MILLI) / MILLI) + } + + /** All choices of a setting in pages; a click picks one and returns to [done]. */ + fun choice(player: MenuViewer, id: String, path: String, page: Int, done: (MenuViewer) -> Unit, write: SettingWriter) { + val setting = setting(id, path) ?: return done(player) + val rows = setting.choices.map { value -> + val chosen = value == setting.value + val lore = Style.lore(emptyList(), emptyList(), *(if (chosen) emptyArray() else arrayOf(Style.left("выбрать")))) + Row( + icon(null, if (chosen) "LIME_DYE" else "PAPER", value, lore, good = chosen), + if (chosen) null else go { who -> write(who, setting, value, done) }, + ) + } + list( + player, setting.title.take(TITLE_LIMIT), rows, page, PAGE_SIZE, { who, to -> choice(who, id, path, to, done, write) }, done, "Вариантов нет", + extra = { + val facts = ConfigLook.place("Настройка" to setting.title, "Сейчас" to setting.value.orEmpty(), "Вариантов" to "${setting.choices.size}") + it.slot(DATE_FILTER, facts) + }, + ) + } + + private companion object { + const val VALUE = 13 + const val TYPE = 4 + const val LOW = 20 + const val HIGH = 24 + const val MILLI = 1000.0 + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/ConfigScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/ConfigScreens.kt new file mode 100644 index 000000000..c59eb68a5 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/ConfigScreens.kt @@ -0,0 +1,242 @@ +package org.pnfolder.pnlibrary.core.menu.screens + +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.api.config.ConfigApply +import org.pnfolder.pnlibrary.api.config.ConfigEditException +import org.pnfolder.pnlibrary.api.config.ConfigId +import org.pnfolder.pnlibrary.api.config.ConfigSetting +import org.pnfolder.pnlibrary.api.config.ConfigSettingKind +import org.pnfolder.pnlibrary.core.menu.ClickType +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.style.ConfigLook +import org.pnfolder.pnlibrary.core.menu.style.ConfigNumbers +import org.pnfolder.pnlibrary.core.menu.style.DATE_FILTER +import org.pnfolder.pnlibrary.core.menu.style.FILTER +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.TITLE_LIMIT +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.text.WRAP_WIDTH +import org.pnfolder.pnlibrary.core.text.wrapText + +private const val CONFIGS_EDIT = "pnlibrary.configs.edit" + +/** One configuration file in the menu list. */ +data class ConfigRow( + val id: String, + val model: String, + val loaded: Boolean, + val readOnly: Boolean, + /** How many settings of the file may be changed in game. */ + val editable: Int, + /** What the changes made since the last read still wait for, or null. */ + val pending: ConfigApply?, +) + +/** + * Menu screens for configuration files: plugins, their modules, their files, and the settings of one file that a + * plugin marked as editable. A switch flips on a click, a choice goes round, a number goes up and down, and a text is + * typed in chat. How each button looks is [ConfigLook]. + */ +internal class ConfigScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { + /** What the first level lists: the plugins, or every file of every plugin with its plugin and module named. */ + internal enum class Top(val label: String) { PLUGINS("Выбрать плагин"), ALL("Все конфигурации") } + + /** How the files of one plugin are laid out: grouped by module, or all of them in one list. */ + internal enum class View(val label: String) { MODULES("По модулям"), FILES("Все файлы плагина") } + + private val pickers = ConfigPickers(session, routes) + + private data class Located(val file: ConfigRow, val plugin: String, val module: String, val path: String) + + private fun located(): List = data.configs().map { + val id = ConfigId.parse(it.id) + Located(it, id.plugin.value, id.module.value, id.path) + } + + private fun waiting(files: List): ConfigApply? = files.mapNotNull { it.file.pending }.maxOrNull() + + /** The first level of the section. */ + fun configs(player: MenuViewer, page: Int) = configsBy(player, Top.PLUGINS, page) + + fun configsBy(player: MenuViewer, top: Top, page: Int) { + val all = located() + val rows = if (top == Top.PLUGINS) all.groupBy { it.plugin }.toSortedMap().map { (plugin, files) -> pluginRow(plugin, files, top) } + else all.sortedWith(compareBy({ it.plugin }, { it.module }, { it.path })).map { fileRow(it, true, true) { who -> configsBy(who, top, page) } } + val other = Top.entries.first { it != top } + list( + player, "Конфигурации", rows, page, PAGE_SIZE, { who, to -> configsBy(who, top, to) }, { routes.home(it) }, "Конфигураций нет", + extra = { + val switch = switcher("Показать", "Выбрать плагин или сразу увидеть все файлы.", Top.entries.map { t -> t.label }, top.ordinal) + it.button(FILTER, switch, go { who -> configsBy(who, other, 0) }) + it.slot(DATE_FILTER, ConfigLook.place("Плагинов" to "${all.map { f -> f.plugin }.distinct().size}", "Файлов" to "${all.size}")) + }, + ) + } + + private fun switcher(label: String, description: String, options: List, selected: Int) = icon( + Icons.SETTINGS, "HOPPER", "$label: ${options[selected]}", + Style.lore(wrapText(description, WRAP_WIDTH, 2), emptyList(), Style.left("переключить"), extra = Style.choices(options, selected)), + ) + + private fun pluginRow(plugin: String, files: List, top: Top): Row = Row( + ConfigLook.plugin(plugin, files.map { it.module }.distinct().size, files.size, files.sumOf { it.file.editable }, waiting(files)), + go { who -> pluginFiles(who, plugin, null, 0, top) }, + ) + + /** + * The second level: one plugin. The switch button picks between its modules and every file of the plugin + * with its module named; a plugin with one module opens on its files. + */ + fun pluginFiles(player: MenuViewer, plugin: String, view: View?, page: Int, top: Top) { + val files = located().filter { it.plugin == plugin } + val modules = files.map { it.module }.distinct().sorted() + val shown = view ?: if (modules.size > 1) View.MODULES else View.FILES + val rows = if (shown == View.MODULES) modules.map { moduleRow(plugin, it, files.filter { f -> f.module == it }, top) } + else { + files.sortedWith(compareBy({ it.module }, { it.path })) + .map { fileRow(it, false, modules.size > 1) { who -> pluginFiles(who, plugin, shown, page, top) } } + } + val switch = View.entries.first { it != shown } + list( + player, plugin, rows, page, PAGE_SIZE, { who, to -> pluginFiles(who, plugin, shown, to, top) }, { configsBy(it, top, 0) }, + "У плагина нет конфигураций", + extra = { + it.button( + FILTER, + switcher("Показать", "Модули плагина или все его файлы подряд.", View.entries.map { v -> v.label }, shown.ordinal), + go { who -> pluginFiles(who, plugin, switch, 0, top) }, + ) + it.slot(DATE_FILTER, ConfigLook.place("Плагин" to plugin, "Модулей" to "${modules.size}", "Файлов" to "${files.size}")) + }, + ) + } + + /** The third level: the files of one module. */ + fun moduleFiles(player: MenuViewer, plugin: String, module: String, page: Int, top: Top) { + val files = located().filter { it.plugin == plugin && it.module == module } + val rows = files.sortedBy { it.path }.map { fileRow(it, false, false) { who -> moduleFiles(who, plugin, module, page, top) } } + list( + player, "$plugin · $module".take(TITLE_LIMIT), rows, page, PAGE_SIZE, { who, to -> moduleFiles(who, plugin, module, to, top) }, + { pluginFiles(it, plugin, View.MODULES, 0, top) }, "В модуле нет конфигураций", + extra = { it.slot(DATE_FILTER, ConfigLook.place("Плагин" to plugin, "Модуль" to module, "Файлов" to "${files.size}")) }, + ) + } + + private fun moduleRow(plugin: String, module: String, files: List, top: Top): Row = Row( + ConfigLook.module(plugin, module, files.size, files.sumOf { it.file.editable }, waiting(files)), + go { who -> moduleFiles(who, plugin, module, 0, top) }, + ) + + private fun fileRow(entry: Located, withPlugin: Boolean, withModule: Boolean, back: (MenuViewer) -> Unit): Row { + val file = entry.file + val item = ConfigLook.file(file, entry.plugin, entry.module, entry.path, withPlugin, withModule) + return Row(item, if (file.editable > 0) go { who -> card(who, file.id, 0, back) } else null) + } + + /** The settings of one file; [back] returns to the screen it was opened from. */ + fun card(player: MenuViewer, id: String, page: Int, back: (MenuViewer) -> Unit) { + val file = data.configs().firstOrNull { it.id == id } + val address = ConfigId.parse(id) + val rows = data.configSettings(id).map { setting -> row(id, setting, file?.readOnly == true, page, back) } + list( + player, "${address.module.value} · ${address.path.substringAfterLast('/')}".take(TITLE_LIMIT), rows, page, PAGE_SIZE, + { who, to -> card(who, id, to, back) }, back, "В этом файле нет настроек для игры", + extra = { + it.slot( + DATE_FILTER, + ConfigLook.place( + "Плагин" to address.plugin.value, + "Модуль" to address.module.value, + "Файл" to address.path, + "Класс" to file?.model.orEmpty(), + ), + ) + }, + ) + } + + private fun row(id: String, setting: ConfigSetting, readOnly: Boolean, page: Int, back: (MenuViewer) -> Unit): Row { + val click = if (readOnly) null else goClick { who, how -> change(who, id, setting, how, page, back) } + return Row(ConfigLook.setting(setting, readOnly), click) + } + + private fun change(player: MenuViewer, id: String, setting: ConfigSetting, how: ClickType, page: Int, back: (MenuViewer) -> Unit) { + val here = { who: MenuViewer -> card(who, id, page, back) } + val numeric = setting.kind == ConfigSettingKind.INTEGER || setting.kind == ConfigSettingKind.DECIMAL + when { + setting.kind == ConfigSettingKind.TEXT -> allowed(player, CONFIGS_EDIT) { ask(player, id, setting) } + numeric && how == ClickType.MIDDLE -> allowed( + player, + CONFIGS_EDIT, + ) { pickers.number(player, id, setting.path, here, writer(id), { who, item -> ask(who, id, item) }) } + setting.kind == ConfigSettingKind.CHOICE && how.isShift() && setting.choices.size > 2 -> + allowed(player, CONFIGS_EDIT) { pickers.choice(player, id, setting.path, 0, here, writer(id)) } + else -> next(setting, how)?.let { value -> allowed(player, CONFIGS_EDIT) { write(player, id, setting, value, here) } } + } + } + + private fun ClickType.isShift() = this == ClickType.SHIFT_LEFT || this == ClickType.SHIFT_RIGHT + + private fun writer(id: String): SettingWriter = { who, setting, value, after -> write(who, id, setting, value, after) } + + private fun ask(player: MenuViewer, id: String, setting: ConfigSetting) { + val hint = listOf( + setting.format.takeIf(String::isNotBlank)?.let { "Формат: $it." }, + setting.examples.takeIf { it.isNotEmpty() }?.let { "Например: ${it.joinToString()}." }, + ) + .filterNotNull().joinToString(" ") + suggestCommand(player, "Введите новое значение для «${setting.title}». $hint".trim(), "/pn configs edit $id ${setting.path} ${setting.value.orEmpty()}") + } + + private fun write(player: MenuViewer, id: String, setting: ConfigSetting, next: String, after: (MenuViewer) -> Unit) { + host.async { + val outcome = try { + data.editConfig(id, setting.path, next) + null + } catch (error: ConfigEditException) { + error.message + } catch (error: Exception) { + error.message ?: "Не удалось записать файл" + } + host.sync { + if (outcome != null) tell(player, ChatTone.FAILURE, "Не изменено.", outcome) + else if (setting.apply != ConfigApply.LIVE) { + tell(player, ChatTone.WARNING, "Сохранено: ${setting.title} = $next.", "Заработает: ${ConfigLook.applyWord(setting.apply)}.") + } + after(player) + } + } + } + + /** The value a click moves to, or `null` when the click does nothing. */ + private fun next(setting: ConfigSetting, how: ClickType): String? { + val current = setting.value ?: return null + val backwards = how == ClickType.RIGHT || how == ClickType.SHIFT_RIGHT + val big = how == ClickType.SHIFT_LEFT || how == ClickType.SHIFT_RIGHT + return when (setting.kind) { + ConfigSettingKind.BOOLEAN -> (current != "true").toString() + ConfigSettingKind.CHOICE -> { + val at = setting.choices.indexOf(current) + val step = if (backwards) -1 else 1 + setting.choices[Math.floorMod(at + step, setting.choices.size)] + } + ConfigSettingKind.INTEGER -> { + val step = ConfigNumbers.ladder(setting)[if (big) 1 else 0].second * (if (backwards) -1 else 1) + clamp((current.toLongOrNull() ?: return null) + step, setting).let { Math.round(it).toString() } + } + ConfigSettingKind.DECIMAL -> { + val step = ConfigNumbers.ladder(setting)[if (big) 1 else 0].second * (if (backwards) -1 else 1) + ConfigLook.number(clamp(Math.round(((current.toDoubleOrNull() ?: return null) + step) * 1000.0) / 1000.0, setting)) + } + ConfigSettingKind.TEXT -> null + } + } + + private fun clamp(value: Double, setting: ConfigSetting): Double = value.coerceIn(setting.min ?: -Double.MAX_VALUE, setting.max ?: Double.MAX_VALUE) +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/GroupScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/GroupScreens.kt similarity index 91% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/GroupScreens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/GroupScreens.kt index b02d3b3c0..b5c0b8f04 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/GroupScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/GroupScreens.kt @@ -1,14 +1,37 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.screens import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.core.link.LinkNames -import org.pnfolder.pnlibrary.core.link.NetworkReport -import org.pnfolder.pnlibrary.core.link.RemoteAction +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.core.exceptions.rootMessage import org.pnfolder.pnlibrary.core.link.ServerGroups +import org.pnfolder.pnlibrary.core.link.remote.LinkNames +import org.pnfolder.pnlibrary.core.link.remote.RemoteAction +import org.pnfolder.pnlibrary.core.link.report.NetworkReport +import org.pnfolder.pnlibrary.core.menu.ClickType +import org.pnfolder.pnlibrary.core.menu.MenuBuilder +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.data.GroupEdit +import org.pnfolder.pnlibrary.core.menu.data.GroupOp +import org.pnfolder.pnlibrary.core.menu.data.RemoteMenuData +import org.pnfolder.pnlibrary.core.menu.style.GROUPS_PERMISSION +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.NETWORK_CHECK +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.icon +private const val NETWORK_UPDATE = 51 +private const val GROUP_ADD = 46 +private const val GROUP_PLUGINS = 47 +private const val GROUP_DELETE = 52 + +/** Menu screens for server groups and their members. */ internal class GroupScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { private val comparer = ServerGroups { null } @@ -54,7 +77,7 @@ internal class GroupScreens(session: MenuSession, routes: MenuRoutes) : MenuScre val loaded = proxyData.groups() host.sync { then(loaded, map) } } catch (error: Exception) { - host.sync { tell(player, ChatTone.FAILURE, "Прокси не ответил.", reason(error)) } + host.sync { tell(player, ChatTone.FAILURE, "Прокси не ответил.", error.rootMessage()) } } } } @@ -66,7 +89,7 @@ internal class GroupScreens(session: MenuSession, routes: MenuRoutes) : MenuScre val done = proxyData.editGroup(edit) host.sync { if (done) then() else tell(player, ChatTone.FAILURE, "Не получилось изменить группу ${edit.group}.") } } catch (error: Exception) { - host.sync { tell(player, ChatTone.FAILURE, "Прокси не ответил.", reason(error)) } + host.sync { tell(player, ChatTone.FAILURE, "Прокси не ответил.", error.rootMessage()) } } } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/HistoryScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/HistoryScreens.kt new file mode 100644 index 000000000..a3dac06be --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/HistoryScreens.kt @@ -0,0 +1,244 @@ +package org.pnfolder.pnlibrary.core.menu.screens + +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.api.updates.backup.BackupKind +import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup +import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackupItem +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.state.UpdateState +import org.pnfolder.pnlibrary.core.exceptions.rootMessage +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.Menus +import org.pnfolder.pnlibrary.core.menu.style.DETAIL_BACK +import org.pnfolder.pnlibrary.core.menu.style.DETAIL_ROWS +import org.pnfolder.pnlibrary.core.menu.style.HISTORY_PAGE +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.ROLLBACK +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.SMALL_BACK +import org.pnfolder.pnlibrary.core.menu.style.SMALL_ROWS +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.backItem +import org.pnfolder.pnlibrary.core.menu.style.clockTime +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.menuFrame +import org.pnfolder.pnlibrary.core.menu.style.menuTitle +import org.pnfolder.pnlibrary.core.text.wrapText +import org.pnfolder.pnlibrary.core.updates.catalog.CatalogLabels +import org.pnfolder.pnlibrary.updates.history.BackupItemText + +private const val DATABASE_BUTTONS = 3 +private const val DATABASE_FIRST = 15 +private const val FILES_BUTTON = 20 +private const val CHANGE_FIRST = 19 +private const val CHANGE_BUTTONS = 7 +private const val NOTE_LINES = 8 +private const val NOTE_PREVIEW_LINES = 2 + +/** Menu screens showing the history of updates and changes. */ +internal class HistoryScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { + fun history(player: MenuViewer, product: String?, page: Int) { + val normalized = product?.lowercase() + data.historyCount(normalized).thenCompose { total -> + data.historyPage(page + 1, normalized).thenApply { total to it } + }.whenComplete { result, error -> + sync { + if (!player.online) return@sync + val (total, entries) = result ?: (0 to emptyList()) + val back: (MenuViewer) -> Unit = if (product == null) { who -> routes.home(who) } else { who -> routes.card(who, product) } + val rows = if (error != null) { + emptyList() + } else { + entries.map { entry -> + val item = historyItem(entry, NOTE_PREVIEW_LINES, Style.left("подробности")) + Row(item, go { historyEntry(it, entry) { who -> history(who, product, page) } }) + } + } + val title = if (product == null) "История" else "История $product" + list(player, title, rows, page, HISTORY_PAGE, { who, to -> history(who, product, to) }, back, "Записей пока нет", total) + } + } + } + + /** First the plugins that have saved copies; a click lists that plugin's copies by date. */ + fun backups(player: MenuViewer, page: Int) { + data.backups().whenComplete { all, error -> + sync { + if (!player.online) return@sync + val rows = if (error != null) emptyList() else productsOf(all).map { (product, sets) -> + val latest = sets.mapNotNull { it.createdAt }.maxOrNull() + val lore = Style.lore( + emptyList(), + listOf("Копий" to sets.size.toString()) + listOfNotNull(latest?.let { "Последняя" to clockTime(it) }), + Style.left("выбрать дату"), + ) + Row(icon(Icons.PLUGIN, "PAPER", product, lore), go { pluginBackups(it, product, 0) }) + } + list(player, "Резервные копии", rows, page, PAGE_SIZE, { who, to -> backups(who, to) }, { routes.home(it) }, "Резервных копий нет") + } + } + } + + private fun productsOf(all: List): List>> = + all.flatMap { backup -> (backup.components.map { it.product.value } + backup.items.map { it.product.value }).distinct().map { it to backup } } + .groupBy({ it.first }, { it.second }).toSortedMap(String.CASE_INSENSITIVE_ORDER).toList() + + private fun pluginBackups(player: MenuViewer, product: String, page: Int) { + data.backups().whenComplete { all, error -> + sync { + if (!player.online) return@sync + val rows = if (error != null) { + emptyList() + } else { + all.filter { backup -> productsOf(listOf(backup)).any { it.first == product } }.sortedByDescending { it.createdAt }.map { backup -> + Row(backupItem(backup, Style.left("выбрать откат")), go { backupChoice(it, backup, product) }) + } + } + list(player, "Копии $product", rows, page, PAGE_SIZE, { who, to -> pluginBackups(who, product, to) }, { backups(it, 0) }, "Копий нет") + } + } + } + + private fun backupChoice(player: MenuViewer, backup: UpdateBackup, product: String) { + val builder = menuFrame(Menus.chest(menuTitle("Откат")).rows(SMALL_ROWS), SMALL_ROWS) + builder.slot(4, backupItem(backup)) + val plain = Style.lore( + listOf("Вернутся сохранённые JAR.", "Конфигурации не изменятся.", "Применится после перезапуска.") + + if (databasesOf(backup, product).isEmpty()) emptyList() else listOf("Базы данных не изменятся: их возвращают кнопками справа."), + emptyList(), Style.left("откатить"), + ) + builder.button(11, icon(Icons.ROLLBACK, "TNT", "Откатить плагины", plain, danger = true), go { who -> + allowed(who, ROLLBACK) { rollback(who, backup, restoreConfigurations = false) } + }) + if (backup.configurationFiles > 0) { + val full = Style.lore( + listOf("Вернутся JAR и файлы настроек: ${backup.configurationFiles}.", "Применится после перезапуска."), + emptyList(), Style.left("откатить"), + ) + builder.button(13, icon(Icons.ROLLBACK, "TNT", "Откатить плагины и настройки", full, danger = true), go { who -> + allowed(who, ROLLBACK) { rollback(who, backup, restoreConfigurations = true) } + }) + } + databasesOf(backup, product).take(DATABASE_BUTTONS).forEachIndexed { index, item -> + val lore = Style.lore( + listOf("Заменит данные базы сохранёнными.", "Спросит подтверждение."), + listOf("Размер копии" to BackupItemText.size(item.bytes)), Style.left("вернуть базу"), + ) + builder.button(DATABASE_FIRST + index, icon(Icons.BACKUPS, "CHEST", "Вернуть базу «${item.name}»", lore, danger = true), go { who -> + allowed(who, ROLLBACK) { databaseConfirm(who, backup, item, product) } + }) + } + if (backup.items.any { it.kind != BackupKind.CONFIGURATION && it.product.value.equals(product, ignoreCase = true) }) { + val lore = Style.lore( + listOf("Положит сохранённые базы и выгрузки в папку на сервере.", "Подойдёт, если базу нельзя вернуть кнопкой."), + emptyList(), Style.left("выдать файлы"), + ) + builder.button(FILES_BUTTON, icon(Icons.BACKUPS, "CHEST", "Выдать файлы", lore), go { who -> + allowed(who, ROLLBACK) { extractFiles(who, backup, product) } + }) + } + builder.button(SMALL_BACK, backItem("Отмена"), go { pluginBackups(it, product, 0) }) + show(player, builder.build()) + } + + private fun databasesOf(backup: UpdateBackup, product: String) = + backup.items.filter { it.kind == BackupKind.DATABASE && it.product.value.equals(product, ignoreCase = true) } + + /** The last question before a database is replaced: what is lost, what is kept, and a way out. */ + private fun databaseConfirm(player: MenuViewer, backup: UpdateBackup, item: UpdateBackupItem, product: String) { + val builder = menuFrame(Menus.chest(menuTitle("Вернуть базу")).rows(SMALL_ROWS), SMALL_ROWS) + val warning = Style.lore( + listOf( + "Таблицы базы «${item.name}» будут заменены теми, что были до обновления.", + "Всё, что записано в базу с тех пор, пропадёт: игроки, балансы, прогресс.", + "Текущее состояние сохранится отдельной копией на сервере, вернуть его можно командой.", + ), + listOf("Плагин" to item.product.value, "Копия" to BackupItemText.size(item.bytes)), Style.left("подтвердить"), + ) + builder.slot(4, icon(Icons.BACKUPS, "CHEST", "Вы можете потерять данные", warning, danger = true)) + builder.button(11, icon(Icons.ROLLBACK, "TNT", "Да, заменить базу", warning, danger = true), go { who -> + allowed(who, ROLLBACK) { restoreDatabase(who, backup, item) } + }) + builder.button(SMALL_BACK, backItem("Отмена"), go { backupChoice(it, backup, product) }) + show(player, builder.build()) + } + + private fun extractFiles(player: MenuViewer, backup: UpdateBackup, product: String) { + player.close() + data.extractBackup(backup.id, product, player.actor).whenComplete { folder, error -> + sync { + if (!player.online) return@sync + if (error != null) tell(player, ChatTone.FAILURE, "Не удалось выдать файлы.", error.rootMessage()) + else tell(player, ChatTone.SUCCESS, "Файлы плагина $product выданы.", "Папка на сервере: $folder") + } + } + } + + private fun restoreDatabase(player: MenuViewer, backup: UpdateBackup, item: UpdateBackupItem) { + player.close() + data.restoreDatabase(backup.id, item.product.value, item.name, player.actor).whenComplete { _, error -> + sync { + if (!player.online) return@sync + if (error != null) tell(player, ChatTone.FAILURE, "Не удалось вернуть базу.", error.rootMessage()) + else tell(player, ChatTone.SUCCESS, "База «${item.name}» возвращена.", "Перезапустите плагин ${item.product.value}, чтобы он перечитал данные.") + } + } + } + + private fun historyEntry(player: MenuViewer, entry: UpdateHistoryEntry, back: (MenuViewer) -> Unit) { + val builder = menuFrame(Menus.chest(menuTitle("Запись истории")).rows(DETAIL_ROWS), DETAIL_ROWS) + builder.slot(4, historyItem(entry, NOTE_LINES)) + entry.changes.take(CHANGE_BUTTONS).forEachIndexed { index, change -> + val product = change.product.value + val known = data.snapshot(product) != null + val lore = Style.lore( + listOf("Версия изменилась."), + listOf("Было" to "${change.from}", "Стало" to "${change.to}"), + *if (known) arrayOf(Style.left("открыть карточку")) else emptyArray(), + ) + val stack = icon(Icons.PLUGIN, "PAPER", product, lore, muted = !known) + if (known) builder.button(CHANGE_FIRST + index, stack, go { routes.card(it, product) }) else builder.slot(CHANGE_FIRST + index, stack) + } + builder.button(DETAIL_BACK, backItem(), go { back(it) }) + show(player, builder.build()) + } + + private fun rollback(player: MenuViewer, backup: UpdateBackup, restoreConfigurations: Boolean) { + player.close() + data.rollback(backup.id, restoreConfigurations, player.actor).whenComplete { _, error -> + sync { + if (!player.online) return@sync + if (error != null) tell(player, ChatTone.FAILURE, "Не удалось подготовить откат.", error.rootMessage()) + else tell(player, ChatTone.SUCCESS, "Резервный набор подготовлен.", "Полностью перезапустите сервер, чтобы применить его.") + } + } + } + + private fun historyItem(entry: UpdateHistoryEntry, noteLines: Int, vararg clicks: String): ItemSpec { + val failed = entry.state == UpdateState.FAILED + val parameters = buildList { + add("Когда" to clockTime(entry.occurredAt)) + add("Кто" to entry.actor.name) + entry.changes.forEach { add(it.product.value to "${it.from} » ${it.to}") } + } + val note = entry.message?.let { wrapText(it, limit = noteLines) }.orEmpty() + .map { if (failed) Style.danger(it) else Style.description(it) } + val title = "${CatalogLabels.operationLabel(entry.operation)}: ${CatalogLabels.stateLabel(entry.state)}" + return icon(null, if (failed) "BARRIER" else "PAPER", title, Style.lore(emptyList(), parameters, *clicks, extra = note), danger = failed) + } + + private fun backupItem(backup: UpdateBackup, vararg clicks: String): ItemSpec { + val parameters = buildList { + backup.createdAt?.let { add("Создана" to clockTime(it)) } + backup.components.forEach { add(it.product.value to "${it.backupVersion ?: "?"} (было ${it.updatedVersion ?: "?"})") } + backup.items.forEach { add("Сохранено" to BackupItemText.describe(it)) } + } + val lore = Style.lore(emptyList(), parameters, *clicks) + return icon(Icons.BACKUPS, "CHEST", "Резервный набор", lore) + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/HomeScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/HomeScreens.kt similarity index 70% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/HomeScreens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/HomeScreens.kt index 318d1113a..adb189d19 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/HomeScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/HomeScreens.kt @@ -1,18 +1,49 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.screens import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.core.commands.tasks.TaskPeriod import org.pnfolder.pnlibrary.core.commands.tasks.TaskState +import org.pnfolder.pnlibrary.core.menu.MenuBuilder +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.Menus +import org.pnfolder.pnlibrary.core.menu.data.PlanInfo +import org.pnfolder.pnlibrary.core.menu.style.BUS +import org.pnfolder.pnlibrary.core.menu.style.CONFIGS +import org.pnfolder.pnlibrary.core.menu.style.HOME_CLOSE +import org.pnfolder.pnlibrary.core.menu.style.HOME_ROWS +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.JOURNAL_HOURS +import org.pnfolder.pnlibrary.core.menu.style.JOURNAL_LIMIT +import org.pnfolder.pnlibrary.core.menu.style.MenuPermissions +import org.pnfolder.pnlibrary.core.menu.style.PLACEHOLDERS +import org.pnfolder.pnlibrary.core.menu.style.STATS +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.TASKS +import org.pnfolder.pnlibrary.core.menu.style.ago +import org.pnfolder.pnlibrary.core.menu.style.closeItem +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.menuFrame +import org.pnfolder.pnlibrary.core.menu.style.menuTitle +import org.pnfolder.pnlibrary.core.menu.style.section import org.pnfolder.pnlibrary.core.updates.catalog.CatalogLabels +private const val NETWORK_SLOT = 37 +private const val SUPPORT_SLOT = 38 +private const val RESTART_SLOT = 41 +private const val ROLLBACK_SLOT = 42 + +/** Menu home page with the main sections. */ internal class HomeScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { fun home(player: MenuViewer) { val snapshots = snapshots() val pending = snapshots.count { it.state in CatalogLabels.PENDING } val errors = data.journalGroups("error", JOURNAL_HOURS, JOURNAL_LIMIT).size val problems = snapshots.count { it.state in CatalogLabels.PROBLEMS } + errors - val builder = frame(Menus.chest(title("Главная")).rows(HOME_ROWS), HOME_ROWS) + val builder = menuFrame(Menus.chest(menuTitle("Главная")).rows(HOME_ROWS), HOME_ROWS) summary(builder, pending, problems) sections(builder, pending, problems, errors) network(builder) @@ -73,6 +104,24 @@ internal class HomeScreens(session: MenuSession, routes: MenuRoutes) : MenuScree section(Icons.CLOCK, "CLOCK", "Задачи плагинов", "Что плагины делают по расписанию и для чего.", "Всего" to "${data.tasks().size}"), go { allowed(it, TASKS) { routes.tasks(it, TaskPeriod.TODAY, TaskState.ALL, 0) } }, ) + builder.button( + 28, + section(Icons.TOOLS, "CHEST", "Модули плагинов", "Включить, выключить или перезапустить модули.", "Всего" to "${data.modules().size}"), + go { who -> allowed(who, MenuPermissions.MODULES) { routes.modules(who, null, 0) { routes.home(it) } } }, + ) + builder.button( + 34, + section( + Icons.CHANGELOG, "BOOKSHELF", "Библиотеки плагинов", "Какие библиотеки подключили плагины и модули.", + "Всего" to "${data.libraries().size}", + ), + go { who -> routes.libraries(who, null, 0) { routes.home(it) } }, + ) + builder.button( + 19, + section(Icons.OVERVIEW, "HOPPER", "Диск плагинов", "Сколько места занимают плагины, настройки и библиотеки."), + go { who -> allowed(who, MenuPermissions.MODULES) { routes.disk(who, 0) { routes.home(it) } } }, + ) builder.button( 31, section(Icons.UPDATES, "REDSTONE_TORCH", "События плагинов", "Как плагины общаются друг с другом: слушатели, вызовы, ошибки."), @@ -83,6 +132,14 @@ internal class HomeScreens(session: MenuSession, routes: MenuRoutes) : MenuScree section(Icons.OVERVIEW, "COMPARATOR", "Статистика", "Задачи, события, ошибки и предупреждения за сутки."), go { allowed(it, STATS) { routes.stats(it) } }, ) + builder.button( + 21, + section( + Icons.SETTINGS, "WRITABLE_BOOK", "Конфигурации", "Файлы настроек плагинов: включить, выключить, изменить.", + "Файлов" to "${data.configs().size}", + ), + go { allowed(it, CONFIGS) { routes.configs(it, 0) } }, + ) builder.button( 23, section(Icons.TOOLS, "NAME_TAG", "Плейсхолдеры", "Что плагины публикуют для текста и PlaceholderAPI."), diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/JournalScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/JournalScreens.kt similarity index 73% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/JournalScreens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/JournalScreens.kt index 3a4b54ffb..bac461054 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/JournalScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/JournalScreens.kt @@ -1,11 +1,44 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.screens -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.common.time.DisplayZone import org.pnfolder.pnlibrary.core.journal.JournalDetail import org.pnfolder.pnlibrary.core.journal.JournalGroup +import org.pnfolder.pnlibrary.core.menu.ClickType +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuBuilder +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.Menus +import org.pnfolder.pnlibrary.core.menu.style.DETAIL_BACK +import org.pnfolder.pnlibrary.core.menu.style.DETAIL_ROWS +import org.pnfolder.pnlibrary.core.menu.style.FILTER +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.JOURNAL_HOURS +import org.pnfolder.pnlibrary.core.menu.style.JOURNAL_LIMIT +import org.pnfolder.pnlibrary.core.menu.style.MESSAGE_PREVIEW +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.ago +import org.pnfolder.pnlibrary.core.menu.style.backItem +import org.pnfolder.pnlibrary.core.menu.style.clockStamp +import org.pnfolder.pnlibrary.core.menu.style.clockTime +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.menuFrame +import org.pnfolder.pnlibrary.core.menu.style.menuTitle +import org.pnfolder.pnlibrary.core.text.wrapText import java.time.Instant +private val LEVEL_CYCLE = listOf(null, "error", "warning", "info") +private val LEVELS = mapOf("error" to "ошибки", "warning" to "предупреждения", "info" to "сведения") +private const val TRACE_LINES = 12 +private const val DETAILS_SHOWN = 8 +private const val TIMES_PREVIEW = 5 + +/** Menu screens for the journal of recorded problems. */ internal class JournalScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { fun journal(player: MenuViewer, level: String?, page: Int) { val title = "Журнал сервера" + (level?.let { " " + LEVELS.getValue(it) } ?: "") @@ -47,7 +80,7 @@ internal class JournalScreens(session: MenuSession, routes: MenuRoutes) : MenuSc val material = journalMaterial(group.level) val parameters = listOf( "Источник" to group.source, - "Когда" to time(Instant.ofEpochMilli(group.lastMillis)), + "Когда" to clockTime(Instant.ofEpochMilli(group.lastMillis)), "Повторов" to "${group.count}", ) val lore = Style.lore( @@ -63,7 +96,7 @@ internal class JournalScreens(session: MenuSession, routes: MenuRoutes) : MenuSc tell(player, ChatTone.INFO, "Это событие уже вышло из журнала.") return back(player) } - val builder = frame(Menus.chest(title("Событие")).rows(DETAIL_ROWS), DETAIL_ROWS) + val builder = menuFrame(Menus.chest(menuTitle("Событие")).rows(DETAIL_ROWS), DETAIL_ROWS) builder.slot(4, journalSummary(detail)) detail.stackTrace?.let { trace -> builder.button(20, traceItem(trace), go { who -> who.close(); runCommand(who, "pn events full $id") }) @@ -84,12 +117,12 @@ internal class JournalScreens(session: MenuSession, routes: MenuRoutes) : MenuSc private fun journalSummary(detail: JournalDetail): ItemSpec { val last = Instant.ofEpochMilli(detail.times.first()) val summary = Style.lore( - wrap(detail.message), + wrapText(detail.message), listOf( "Важность" to LEVELS.getValue(detail.level), "Источник" to detail.source, "Повторов" to "${detail.times.size}", - "Последний раз" to stamp(last), + "Последний раз" to clockStamp(last), "" to ago(last), ), ) @@ -98,7 +131,7 @@ internal class JournalScreens(session: MenuSession, routes: MenuRoutes) : MenuSc } private fun traceItem(trace: String): ItemSpec { - val lore = Style.lore(emptyList(), emptyList(), Style.left("весь текст в чат"), extra = wrap(trace, limit = TRACE_LINES).map { Style.danger(it) }) + val lore = Style.lore(emptyList(), emptyList(), Style.left("весь текст в чат"), extra = wrapText(trace, limit = TRACE_LINES).map { Style.danger(it) }) return icon(Icons.PROBLEMS, "BOOK", "Текст ошибки", lore, danger = true) } @@ -106,7 +139,7 @@ internal class JournalScreens(session: MenuSession, routes: MenuRoutes) : MenuSc val moments = detail.times.map { Instant.ofEpochMilli(it) } val more = moments.size - TIMES_PREVIEW val timesLore = Style.lore( - moments.take(TIMES_PREVIEW).map { stamp(it) }, + moments.take(TIMES_PREVIEW).map { clockStamp(it) }, listOf("Пояс" to DisplayZone.zone.id), *if (more > 0) arrayOf(Style.left("все ${moments.size} раз")) else emptyArray(), extra = if (more > 0) listOf(Style.description("и ещё $more")) else emptyList(), @@ -130,7 +163,7 @@ internal class JournalScreens(session: MenuSession, routes: MenuRoutes) : MenuSc val rows = detail.times.mapIndexed { index, millis -> val moment = Instant.ofEpochMilli(millis) val lore = Style.lore(emptyList(), listOf("Было" to ago(moment), "Номер" to "${detail.times.size - index} из ${detail.times.size}")) - Row(icon(Icons.CLOCK, "CLOCK", stamp(moment), lore, alternative = "WATCH")) + Row(icon(Icons.CLOCK, "CLOCK", clockStamp(moment), lore, alternative = "WATCH")) } list(player, "Когда случалось", rows, page, PAGE_SIZE, { who, to -> journalTimes(who, id, to, back) }, { journalEvent(it, id, back) }, "Времени нет") } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/LibrarySettingsScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/LibrarySettingsScreens.kt new file mode 100644 index 000000000..e271f33c5 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/LibrarySettingsScreens.kt @@ -0,0 +1,197 @@ +package org.pnfolder.pnlibrary.core.menu.screens + +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.core.menu.ClickType +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.data.SettingOutcome +import org.pnfolder.pnlibrary.core.menu.data.SettingRow +import org.pnfolder.pnlibrary.core.menu.style.ConfigLook +import org.pnfolder.pnlibrary.core.menu.style.DATE_FILTER +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.MenuPermissions +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.settings.ChoiceSource +import org.pnfolder.pnlibrary.core.settings.SettingTexts +import org.pnfolder.pnlibrary.core.text.WRAP_WIDTH +import org.pnfolder.pnlibrary.core.text.wrapText + +private const val BIG_STEP = 10 + +/** + * The page with every setting of the library and its value. A switch flips on a click, a number goes up and down + * (Shift for ten at a time), a text or a time is typed in the chat, a choice among many values rolls to the next one (Shift opens a picker), the wheel + * returns a setting to its default. + * The same settings are changed by `/pn settings`; the list comes from the server whose menu this is. + */ +internal class LibrarySettingsScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { + private val picker = SettingChoicePicker(session, routes) + + fun librarySettings(player: MenuViewer, page: Int) { + val all = data.settings() + val rows = all.map { Row(item(it), goClick { who, how -> click(who, it, how, page) }) } + list( + player, "Параметры библиотеки", rows, page, PAGE_SIZE, { who, to -> librarySettings(who, to) }, { routes.settings(it) }, + "Настроек нет", + extra = { + it.slot( + DATE_FILTER, + ConfigLook.place("Настроек" to "${all.size}", "Изменено" to "${all.count { row -> row.changed }}"), + ) + }, + ) + } + + private fun item(row: SettingRow): ItemSpec { + val switch = row.kind == KIND_SWITCH + val source = ChoiceSource.named(row.choiceSource) + val options = source?.rolling(row.current).orEmpty() + val parameters = buildList { + if (!switch) add("Значение" to row.current) + if (source != null) add("Вариант" to variant(source, row.current)) + if (source != null) addAll(source.lore(row.current)) + if (row.changed && !switch) add("По умолчанию" to row.default) + if (row.range.isNotEmpty()) add("Допустимо" to row.range) + if (row.examples.isNotEmpty() && source == null) add("Примеры" to row.examples.joinToString(", ")) + if (!row.live) add("Заработает" to "после перезапуска") + } + val on = row.current == "true" + val choices = when { + switch -> Style.choices( + listOf(SettingTexts.switchWord(true), SettingTexts.switchWord(false)), + if (on) 0 else 1, + if (row.default == "true") 0 else 1, + ) + source != null -> ConfigLook.window(options, options.indexOf(row.current)) + else -> emptyList() + } + val (texture, material) = when (row.kind) { + KIND_SWITCH -> Icons.TOGGLE to if (on) "LIME_DYE" else "GRAY_DYE" + KIND_NUMBER -> Icons.CLOCK to "REPEATER" + KIND_TIME -> Icons.CLOCK to "CLOCK" + KIND_CHOICE -> Icons.SETTINGS to "COMPASS" + else -> Icons.CHANGELOG to "NAME_TAG" + } + return icon( + texture, material, row.title, + Style.lore(wrapText(row.description, WRAP_WIDTH, 5), parameters, *hints(row), extra = choices), + good = switch && on, muted = switch && !on, warn = row.changed && !switch, + ) + } + + /** `3 из 21`; a value outside the rolled set is not counted in it: `— из 21`. */ + private fun variant(source: ChoiceSource, current: String): String { + val at = source.cycle.indexOf(current) + return "${if (at >= 0) at + 1 else "—"} из ${source.cycle.size}" + } + + private fun hints(row: SettingRow): Array = buildList { + when (row.kind) { + KIND_SWITCH -> add(Style.left("включить или выключить")) + KIND_NUMBER -> { + add(Style.left("больше")) + add(Style.right("меньше")) + add(Style.shiftLeft("на десять")) + } + KIND_CHOICE -> if (ChoiceSource.named(row.choiceSource) != null) { + add(Style.left("следующий")) + add(Style.right("предыдущий")) + add(Style.shiftLeft("весь список")) + } else { + add(Style.left("ввести в чате")) + } + else -> add(Style.left("ввести в чате")) + } + if (row.changed) add(Style.middle("вернуть значение по умолчанию")) + }.toTypedArray() + + private fun click(player: MenuViewer, row: SettingRow, how: ClickType, page: Int) { + if (how == ClickType.MIDDLE) { + if (row.changed) change(player, row, null, page) + return + } + when (row.kind) { + KIND_SWITCH -> change(player, row, (row.current != "true").toString(), page) + KIND_NUMBER -> number(player, row, how, page) + KIND_CHOICE -> choose(player, row, how, page) + else -> type(player, row) + } + } + + private fun type(player: MenuViewer, row: SettingRow) = allowed(player, MenuPermissions.LIBRARY_SETTINGS) { + suggestCommand(player, "Введите новое значение для «${row.title}». ${hint(row)}".trim(), "/pn settings set ${row.key} ${row.current}") + } + + /** + * A click rolls to the next value, a right click to the previous one, Shift + click opens the whole list; a setting + * without a list asks for the value in the chat. + */ + private fun choose(player: MenuViewer, row: SettingRow, how: ClickType, page: Int) { + val source = ChoiceSource.named(row.choiceSource) ?: return type(player, row) + when (how) { + ClickType.SHIFT_LEFT, ClickType.SHIFT_RIGHT -> pick(player, row, source, "", page) + else -> change(player, row, source.step(row.current, how == ClickType.RIGHT), page) + } + } + + /** + * Opens the list of values of the choice setting [key] narrowed to [filter], or tells that there is no such setting. + * `/pn settings pick` opens it this way. + */ + fun pick(player: MenuViewer, key: String, filter: String) { + val row = data.settings().firstOrNull { it.key == key } + val source = row?.let { ChoiceSource.named(it.choiceSource) } + if (row == null || source == null) return tell(player, ChatTone.FAILURE, "Нет настройки с выбором из списка: $key.") + pick(player, row, source, filter, 0) + } + + private fun pick(player: MenuViewer, row: SettingRow, source: ChoiceSource, filter: String, page: Int) = allowed(player, MenuPermissions.LIBRARY_SETTINGS) { + val target = SettingChoicePicker.Target(row, source, { who, value -> change(who, row, value, page) }, { type(it, row) }, { librarySettings(it, page) }) + picker.open(player, target, filter) + } + + private fun hint(row: SettingRow): String = listOfNotNull( + row.range.takeIf { it.isNotEmpty() }?.let { "Допустимо: $it." }, + row.examples.takeIf { it.isNotEmpty() }?.let { "Например: ${it.joinToString()}." }, + ).joinToString(" ") + + private fun number(player: MenuViewer, row: SettingRow, how: ClickType, page: Int) { + val current = row.current.toLongOrNull() ?: return + val step = if (how == ClickType.SHIFT_LEFT || how == ClickType.SHIFT_RIGHT) BIG_STEP else 1 + val direction = if (how == ClickType.RIGHT || how == ClickType.SHIFT_RIGHT) -1 else 1 + change(player, row, (current + direction * step).toString(), page) + } + + private fun change(player: MenuViewer, row: SettingRow, value: String?, page: Int) { + allowed(player, MenuPermissions.LIBRARY_SETTINGS) { + host.async { + val outcome = try { + data.changeSetting(row.key, value, player.actor) + } catch (error: Exception) { + SettingOutcome(false, error.message ?: "Не удалось сохранить настройку") + } + host.sync { + when { + !outcome.ok -> tell(player, ChatTone.FAILURE, "Не изменено.", outcome.message) + !outcome.live -> + tell(player, ChatTone.WARNING, "Сохранено: ${row.title} = ${outcome.message}.", "Заработает после перезапуска сервера.") + } + librarySettings(player, page) + } + } + } + } + + private companion object { + const val KIND_SWITCH = "SWITCH" + const val KIND_NUMBER = "NUMBER" + const val KIND_TIME = "TIME" + const val KIND_CHOICE = "CHOICE" + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/ModuleScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/ModuleScreens.kt new file mode 100644 index 000000000..7d1bd1570 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/ModuleScreens.kt @@ -0,0 +1,258 @@ +package org.pnfolder.pnlibrary.core.menu.screens + +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.api.plugin.control.ModuleState +import org.pnfolder.pnlibrary.core.commands.modules.DiskReport +import org.pnfolder.pnlibrary.core.commands.modules.DiskRow +import org.pnfolder.pnlibrary.core.commands.modules.DiskUsage +import org.pnfolder.pnlibrary.core.commands.modules.LibraryRow +import org.pnfolder.pnlibrary.core.commands.modules.ModuleLabels +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.Menus +import org.pnfolder.pnlibrary.core.menu.data.ModuleInfo +import org.pnfolder.pnlibrary.core.menu.style.DETAIL_BACK +import org.pnfolder.pnlibrary.core.menu.style.DETAIL_ROWS +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.MenuPermissions +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.backItem +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.menuFrame +import org.pnfolder.pnlibrary.core.menu.style.menuTitle +import org.pnfolder.pnlibrary.core.menu.style.section +import org.pnfolder.pnlibrary.core.text.wrapText + +/** Menu screens for the modules of plugins: a list and a card with the same switches as `/pn modules`. */ +internal class ModuleScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { + /** The modules of every plugin, or only those of [plugin] when it is given. */ + fun modules(player: MenuViewer, plugin: String?, page: Int, back: (MenuViewer) -> Unit = { routes.home(it) }) { + val all = data.modules().filter { plugin == null || it.key.startsWith("${plugin.lowercase()}:", ignoreCase = true) } + val rows = all.map { info -> Row(item(info), go { who -> module(who, info.key) { modules(it, plugin, page, back) } }) } + list( + player, if (plugin == null) "Модули плагинов" else "Модули: $plugin", rows, page, PAGE_SIZE, + { who, to -> modules(who, plugin, to, back) }, back, "Модулей нет", + ) + } + + /** + * Without [owner] a list of plugins to choose from, each with its libraries counted; with a plugin its libraries, with + * `plugin:module` the libraries of that module. + */ + fun libraries(player: MenuViewer, owner: String?, page: Int, back: (MenuViewer) -> Unit) { + if (owner == null) return pluginsWithLibraries(player, page, back) + val rows = data.libraries().filter { it.belongsTo(owner) }.map { row -> Row(libraryItem(row, withOwner = owner.contains(':').not()), go { }) } + list( + player, "Библиотеки: $owner", rows, page, PAGE_SIZE, + { who, to -> libraries(who, owner, to, back) }, back, "Библиотек нет", + ) + } + + /** Every library of every plugin in one list, for when the plugin does not matter. */ + private fun allLibraries(player: MenuViewer, page: Int, back: (MenuViewer) -> Unit) { + val rows = data.libraries().map { row -> Row(libraryItem(row, withOwner = true), go { }) } + list( + player, "Все библиотеки", rows, page, PAGE_SIZE, + { who, to -> allLibraries(who, to, back) }, back, "Библиотек нет", + ) + } + + private fun pluginsWithLibraries(player: MenuViewer, page: Int, back: (MenuViewer) -> Unit) { + val all = data.libraries() + val reopen = { who: MenuViewer -> libraries(who, null, page, back) } + val summary = Row( + icon( + null, "BOOKSHELF", "Все библиотеки", + Style.lore( + listOf("Одним списком, у каждой написано, чья она."), + listOf("Библиотек" to "${all.size}", "Плагинов" to "${all.map { it.plugin }.distinct().size}"), + Style.left("открыть"), + ), + ), + go { who -> allLibraries(who, 0, reopen) }, + ) + val plugins = all.groupBy { it.plugin }.toSortedMap(String.CASE_INSENSITIVE_ORDER).map { (plugin, own) -> + val modules = own.mapNotNull { it.module }.distinct() + val size = own.mapNotNull { it.file }.distinct().sumOf { java.io.File(it).length() } + val parameters = buildList { + add("Библиотек" to "${own.size}") + if (modules.isNotEmpty()) add("Модулей" to "${modules.size}: ${modules.joinToString().take(40)}") + if (size > 0) add("Размер" to DiskUsage.format(size)) + if (own.any { it.conflict }) add("Внимание" to "другая версия у другого плагина") + } + Row( + icon( + null, if (own.any { it.conflict }) "BARRIER" else "CHEST", plugin, + Style.lore(listOf("Что подключили сам плагин и его модули."), parameters, Style.left("открыть")), + danger = own.any { it.conflict }, + ), + go { who -> libraries(who, plugin, 0, reopen) }, + ) + } + list( + player, "Библиотеки", listOf(summary) + plugins, page, PAGE_SIZE, + { who, to -> libraries(who, null, to, back) }, back, "Библиотек нет", + ) + } + + /** Every plugin by the space it takes, biggest first, with the split into jar, settings, libraries, logs and data. */ + fun disk(player: MenuViewer, page: Int, back: (MenuViewer) -> Unit) { + away(player) { + val result = runCatching { data.disk() } + sync { + val report = result.getOrNull() + if (report == null) { + tell(player, ChatTone.FAILURE, "Не получилось посчитать диск", result.exceptionOrNull()?.message) + return@sync back(player) + } + val rows = listOf(Row(diskSummary(report), go { })) + report.rows.map { Row(diskItem(it, report.total), go { }) } + list( + player, "Диск плагинов", rows, page, PAGE_SIZE, + { who, to -> disk(who, to, back) }, back, "Плагинов нет", + ) + } + } + } + + private fun diskSummary(report: DiskReport): ItemSpec = icon( + null, "HOPPER", "Всего", + Style.lore( + listOf("Плагины, их папки, настройки и библиотеки."), + listOf( + "Занято" to DiskUsage.format(report.total), + "Библиотек pnLibrary" to DiskUsage.format(report.registeredLibraries), + "Свободно на диске" to DiskUsage.format(report.free), + "Размер диска" to DiskUsage.format(report.capacity), + ), + ), + ) + + private fun diskItem(row: DiskRow, total: Long): ItemSpec { + val share = if (total > 0) row.total * 100 / total else 0 + return icon( + null, "CHEST", row.name, + Style.lore( + listOf("Доля: $share% от всех плагинов"), + listOf( + "Всего" to DiskUsage.format(row.total), + "Сам плагин" to DiskUsage.format(row.jar), + "Настройки" to DiskUsage.format(row.configs), + "Библиотеки" to DiskUsage.format(row.libraries), + "Журналы" to DiskUsage.format(row.logs), + "Данные" to DiskUsage.format(row.data), + ), + ), + danger = share >= 50, + ) + } + + private fun libraryItem(row: LibraryRow, withOwner: Boolean): ItemSpec { + val parameters = buildList { + add("Версия" to row.version) + add("Принадлежит" to row.ownerText) + add("Загрузка" to when (row.scope) { "ISOLATED" -> "отдельно"; "LIBRARY" -> "в pnLibrary"; else -> "в плагине" }) + if (row.size >= 0) add("Размер" to DiskUsage.format(row.size)) + row.fileName?.let { add("Файл" to it.takeLastText(40)) } + row.folder?.let { add("Папка" to it.takeLastText(40)) } + add("Сумма" to when (row.trust) { LibraryRow.GIVEN -> "задана автором"; else -> "jar не проверяется" }) + if (!row.required) add("Обязательная" to "нет") + if (row.conflict) add("Внимание" to "другая версия у другого плагина") + row.repositories.firstOrNull()?.let { add("Откуда" to it.removePrefix("https://").takeLastText(40, fromStart = true)) } + } + val description = row.description?.let { wrapText(it, limit = 3) } ?: listOf("Автор не описал эту библиотеку.") + return icon( + null, if (row.conflict) "BARRIER" else "BOOK", if (withOwner) "${row.title} · ${row.plugin}" else row.title, + Style.lore(description, parameters), + danger = row.conflict, good = !row.conflict && row.trust != LibraryRow.NONE, + ) + } + + private fun item(info: ModuleInfo): ItemSpec { + val material = when (info.state) { + ModuleState.ENABLED -> "LIME_DYE" + ModuleState.DISABLED -> "GRAY_DYE" + ModuleState.FAILED -> "BARRIER" + } + val parameters = buildList { + info.description?.let { add("О модуле" to it.take(60)) } + add("Состояние" to ModuleLabels.label(info.state)) + if (info.controllable) add("С сервером" to if (info.autoStart) "включается" else "не включается") + else add("Переключатель" to "плагин не дал") + val libraries = info.libraries.size + info.pluginLibraries.size + if (libraries > 0) add("Библиотек" to "$libraries") + info.error?.let { add("Ошибка" to "✖ ${it.take(60)}") } + } + return icon( + null, material, info.title, Style.lore(listOf(info.key), parameters, Style.left("открыть")), + good = info.state == ModuleState.ENABLED, danger = info.state == ModuleState.FAILED, muted = info.state == ModuleState.DISABLED, + ) + } + + private fun module(player: MenuViewer, key: String, back: (MenuViewer) -> Unit) { + val info = data.modules().firstOrNull { it.key == key } + if (info == null) { + tell(player, ChatTone.INFO, "Этот модуль уже исчез из списка.") + return back(player) + } + val builder = menuFrame(Menus.chest(menuTitle(info.title)).rows(DETAIL_ROWS), DETAIL_ROWS) + builder.slot(4, item(info)) + val total = info.libraries.size + info.pluginLibraries.size + builder.button( + 22, + section(Icons.CHANGELOG, "BOOKSHELF", "Библиотеки", "Что модуль и его плагин подключили для работы.", "Всего" to "$total"), + go { who -> libraries(who, key, 0) { module(it, key, back) } }, + ) + if (info.controllable) { + val reopen = { who: MenuViewer -> module(who, key, back) } + val on = info.state == ModuleState.ENABLED + builder.button(10, control(Icons.CHECK, "EMERALD", "Включить", "Запустить модуль.", !on), act(key, "enable", "включён", reopen)) + val off = control(Icons.PROBLEMS, "REDSTONE", "Выключить", "Остановить до следующего запуска сервера.", on) + builder.button(11, off, act(key, "disable", "выключен", reopen)) + val restart = control(Icons.UPDATES, "REPEATER", "Перезапустить", "Выключить и включить заново.", true) + builder.button(12, restart, act(key, "restart", "перезапущен", reopen)) + val reload = control(Icons.SETTINGS, "WRITABLE_BOOK", "Перечитать", "Перечитать настройки; если сам не умеет, перезапустится.", on) + builder.button(13, reload, act(key, "reload", "перечитан", reopen)) + val toggle = if (info.autoStart) "auto-off" to "Не включать с сервером" else "auto-on" to "Включать с сервером" + builder.button( + 15, control(Icons.HISTORY, "CLOCK", toggle.second, "Сохраняется между перезапусками сервера.", true), + act(key, toggle.first, "настроен", reopen), + ) + } + builder.button(DETAIL_BACK, backItem(), go { back(it) }) + show(player, builder.build()) + } + + private fun control(texture: String?, material: String, label: String, description: String, available: Boolean): ItemSpec = + icon( + texture, if (available) material else "COAL", label, + if (available) Style.lore(listOf(description), emptyList(), Style.left("выполнить")) else Style.lore(listOf(description), emptyList()), + muted = !available, + ) + + private fun act(key: String, action: String, done: String, reopen: (MenuViewer) -> Unit) = go { who -> + allowed(who, MenuPermissions.MODULES) { + away(who) { + val result = runCatching { data.moduleAction(key, action) } + sync { + result.onSuccess { info -> + if (info.error != null) tell(who, ChatTone.FAILURE, "Модуль ${info.title}: ошибка", info.error) + else tell(who, ChatTone.SUCCESS, "Модуль ${info.title} $done") + }.onFailure { tell(who, ChatTone.FAILURE, "Не получилось", it.message) } + reopen(who) + } + } + } + } +} + +/** Cuts a long text to [limit] characters with `…`: the end is kept (the folder), or the start when [fromStart]. */ +private fun String.takeLastText(limit: Int, fromStart: Boolean = false): String = when { + length <= limit -> this + fromStart -> take(limit - 1) + "…" + else -> "…" + takeLast(limit - 1) +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/NetworkScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/NetworkScreens.kt similarity index 74% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/NetworkScreens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/NetworkScreens.kt index 8a7c2f2d9..b915afc43 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/NetworkScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/NetworkScreens.kt @@ -1,13 +1,28 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.screens -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.updates.UpdateState -import org.pnfolder.pnlibrary.core.link.LinkNames -import org.pnfolder.pnlibrary.core.link.NetworkReport -import org.pnfolder.pnlibrary.core.link.NetworkServer +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.core.link.ServerGroups +import org.pnfolder.pnlibrary.core.link.remote.LinkNames +import org.pnfolder.pnlibrary.core.link.report.NetworkReport +import org.pnfolder.pnlibrary.core.link.report.NetworkServer +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.NETWORK_CHECK +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.section import org.pnfolder.pnlibrary.core.updates.catalog.CatalogLabels +private const val PROXY_LABEL = "Прокси" + +/** Menu screens describing the proxy network and its servers. */ internal class NetworkScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { fun network(player: MenuViewer, page: Int) { val received = host.link.network diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/PlaceholderScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/PlaceholderScreens.kt similarity index 67% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/PlaceholderScreens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/PlaceholderScreens.kt index d8d6f187b..757cf286e 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/PlaceholderScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/PlaceholderScreens.kt @@ -1,5 +1,15 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.screens +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.icon + +/** Menu screens for registered placeholders. */ internal class PlaceholderScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { /** Every placeholder with its type, format and PlaceholderAPI names; checking a value stays in `/pn placeholders test`. */ fun placeholders(player: MenuViewer, page: Int) { diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/PluginPolicyScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/PluginPolicyScreens.kt new file mode 100644 index 000000000..1ac629624 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/PluginPolicyScreens.kt @@ -0,0 +1,174 @@ +package org.pnfolder.pnlibrary.core.menu.screens + +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.core.exceptions.rootMessage +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.Menus +import org.pnfolder.pnlibrary.core.menu.style.HOLDS +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.SETTINGS +import org.pnfolder.pnlibrary.core.menu.style.SMALL_BACK +import org.pnfolder.pnlibrary.core.menu.style.SMALL_ROWS +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.backItem +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.menuFrame +import org.pnfolder.pnlibrary.core.menu.style.menuTitle +import org.pnfolder.pnlibrary.core.menu.style.timeLeft +import java.time.Duration +import java.time.Instant + +private val CHANNEL_ITEMS = mapOf( + UpdateChannel.STABLE to "EMERALD", + UpdateChannel.RC to "GOLD_INGOT", + UpdateChannel.BETA to "IRON_INGOT", + UpdateChannel.ALPHA to "REDSTONE", + UpdateChannel.DEV to "COAL", +) +private val CHANNEL_HINTS = mapOf( + UpdateChannel.STABLE to "Только проверенные релизы.", + UpdateChannel.RC to "Кандидаты в релиз и стабильные.", + UpdateChannel.BETA to "Бета-версии, кандидаты и стабильные.", + UpdateChannel.ALPHA to "Ранние версии: возможны ошибки.", + UpdateChannel.DEV to "Все версии, включая ежедневные сборки.", +) + +/** Menu screens for per-plugin update policies. */ +internal class PluginPolicyScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { + /** The channel choice. It stays in the code and is switched on by [CHANNEL_SWITCH] once more than `dev` works. */ + fun channels(player: MenuViewer, product: String) { + val current = data.snapshot(product)?.channel + val builder = menuFrame(Menus.chest(menuTitle("Канал $product")).rows(SMALL_ROWS), SMALL_ROWS) + UpdateChannel.values().forEachIndexed { index, channel -> + val chosen = channel == current + val lore = Style.lore( + listOf(CHANNEL_HINTS.getValue(channel)), + if (chosen) listOf("Состояние" to "выбран сейчас") else emptyList(), + *if (chosen) emptyArray() else arrayOf(Style.left("выбрать")), + ) + builder.button( + 10 + index, + icon(null, CHANNEL_ITEMS.getValue(channel), channel.name.lowercase(), lore, good = chosen), + go { who -> allowed(who, SETTINGS) { chooseChannel(who, product, channel) } }, + ) + } + builder.button( + 16, + icon( + Icons.RESET, "BARRIER", "Сбросить", + Style.lore(listOf("Вернуть канал, который указал плагин."), emptyList(), Style.left("сбросить")), muted = true, + ), + go { who -> allowed(who, SETTINGS) { chooseChannel(who, product, null) } }, + ) + builder.button(SMALL_BACK, backItem(), go { routes.card(it, product) }) + show(player, builder.build()) + } + + /** The Java build choice for a release that has several builds, for example one for Java 8 and one for Java 17. */ + fun javaBuilds(player: MenuViewer, product: String) { + val snapshot = data.snapshot(product) ?: return routes.home(player) + val builder = menuFrame(Menus.chest(menuTitle("Сборка Java $product")).rows(SMALL_ROWS), SMALL_ROWS) + snapshot.javaBuilds.take(7).forEachIndexed { index, java -> + val chosen = java == snapshot.javaBuild + val recommended = java == snapshot.recommendedJava + val notes = buildList { + if (chosen) add("Состояние" to "выбрана сейчас") + if (recommended) add("Рекомендуется" to if (snapshot.javaBuild == null) "используется" else "подходит этому серверу") + add("На сервере" to "Java ${snapshot.currentJava}") + } + val lore = Style.lore(listOf("Скачать сборку для Java $java."), notes, *if (chosen) emptyArray() else arrayOf(Style.left("выбрать"))) + builder.button( + 10 + index, + icon(Icons.SETTINGS, "COMPARATOR", "Java $java", lore, good = chosen || (recommended && snapshot.javaBuild == null)), + go { who -> allowed(who, SETTINGS) { chooseJava(who, product, java) } }, + ) + } + builder.button( + 16, + icon( + Icons.RESET, "BARRIER", "Подбирать самому", + Style.lore(listOf("Сборка, как у установленной версии, иначе самая новая из подходящих."), emptyList(), Style.left("сбросить")), muted = true, + ), + go { who -> allowed(who, SETTINGS) { chooseJava(who, product, null) } }, + ) + builder.button(SMALL_BACK, backItem(), go { routes.card(it, product) }) + show(player, builder.build()) + } + + private fun chooseJava(player: MenuViewer, product: String, java: Int?) { + data.setJavaBuild(product, java, player.actor).whenComplete { _, error -> + sync { + if (error != null) tell(player, ChatTone.FAILURE, "Не удалось выбрать сборку Java.", error.rootMessage()) + else tell(player, ChatTone.SUCCESS, if (java == null) "Сборка Java $product подбирается сама." else "Сборка Java $product: $java.") + routes.card(player, product) + } + } + } + + private fun holdSummary(remaining: Duration?) = icon( + Icons.CLOCK, "CLOCK", "Пауза сейчас", + Style.lore( + listOf("Пока пауза идёт, обновления не предлагаются и не скачиваются."), + listOf("Состояние" to (remaining?.let { "‖ осталось ${timeLeft(it)}" } ?: "нет паузы")), + ), + alternative = "WATCH", warn = remaining != null, + ) + + private fun holdChoice(label: String, selectedRemaining: Duration?): ItemSpec { + val note = selectedRemaining?.let { listOf("Выбрано" to "● осталось ${timeLeft(it)}") } ?: emptyList() + val action = if (selectedRemaining != null) "начать срок заново" else "приостановить" + return icon( + Icons.CLOCK, "CLOCK", label, + Style.lore(listOf("Приостановить обновления на этот срок."), note, Style.left(action)), + alternative = "WATCH", good = selectedRemaining != null, + ) + } + + fun holds(player: MenuViewer, product: String) { + val until = data.heldUntil(product)?.takeIf { it.isAfter(Instant.now()) } + val remaining = until?.let { Duration.between(Instant.now(), it) } + val chosen = remaining?.let { holdIndex(it) } ?: -1 + val builder = menuFrame(Menus.chest(menuTitle("Пауза $product")).rows(SMALL_ROWS), SMALL_ROWS) + builder.slot(4, holdSummary(remaining)) + HOLDS.forEachIndexed { index, (label, duration) -> + val item = holdChoice(label, if (index == chosen) remaining else null) + builder.button(10 + index, item, go { who -> allowed(who, SETTINGS) { chooseHold(who, product, duration) } }) + } + if (remaining != null) { + builder.button( + 16, + icon(Icons.RESET, "REDSTONE", "Снять паузу", Style.lore(listOf("Вернуть обновления сейчас."), emptyList(), Style.left("снять")), good = true), + go { who -> allowed(who, SETTINGS) { chooseHold(who, product, null) } }, + ) + } + builder.button(SMALL_BACK, backItem(), go { routes.card(it, product) }) + show(player, builder.build()) + } + + private fun holdIndex(remaining: Duration): Int = HOLDS.indexOfFirst { it.second >= remaining }.takeIf { it >= 0 } ?: (HOLDS.size - 1) + + private fun chooseChannel(player: MenuViewer, product: String, channel: UpdateChannel?) { + data.setChannel(product, channel, player.actor).whenComplete { _, error -> + sync { + if (error != null) tell(player, ChatTone.FAILURE, "Не удалось изменить канал.", error.rootMessage()) + else tell(player, ChatTone.SUCCESS, "Канал $product: ${channel?.name?.lowercase() ?: "как указал плагин"}.") + routes.card(player, product) + } + } + } + + private fun chooseHold(player: MenuViewer, product: String, duration: Duration?) { + data.setHeld(product, duration, player.actor).whenComplete { _, error -> + sync { + if (error != null) tell(player, ChatTone.FAILURE, "Не удалось изменить паузу.", error.rootMessage()) + else tell(player, ChatTone.SUCCESS, if (duration == null) "Пауза $product снята." else "Обновления $product приостановлены.") + routes.card(player, product) + } + } + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/SettingChoicePicker.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/SettingChoicePicker.kt new file mode 100644 index 000000000..3ff4fece8 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/SettingChoicePicker.kt @@ -0,0 +1,120 @@ +package org.pnfolder.pnlibrary.core.menu.screens + +import org.pnfolder.pnlibrary.core.menu.ClickType +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.data.SettingRow +import org.pnfolder.pnlibrary.core.menu.style.DATE_FILTER +import org.pnfolder.pnlibrary.core.menu.style.FILTER +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.TITLE_LIMIT +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.settings.ChoiceSource +import java.time.Instant + +/** + * The screen that chooses one value of a setting that has many (a time zone): one paged list of all values, like the + * other choice lists, but each value tells about itself, and the list can be sorted, narrowed to the popular values or + * searched by a part of the name. + * + * It knows nothing about the settings screen: the screen hands over what to do on a pick, on typing and on going back. + */ +internal class SettingChoicePicker(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { + /** What the picker works on; [pick] writes the chosen value, [type] asks for it in the chat, [back] leaves the picker. */ + class Target( + val row: SettingRow, + val source: ChoiceSource, + val pick: (MenuViewer, String) -> Unit, + val type: (MenuViewer) -> Unit, + val back: (MenuViewer) -> Unit, + ) + + /** How the list is shown: the number of the sort order, whether only the popular values, and the text searched for. */ + private data class View(val order: Int = 0, val popular: Boolean = false, val filter: String = "") + + /** Opens the list of values, already narrowed to those that contain [filter] when it is not empty. */ + fun open(player: MenuViewer, target: Target, filter: String = "") = values(player, target, View(filter = filter.trim()), 0) + + private fun values(player: MenuViewer, target: Target, view: View, page: Int) { + val row = target.row + val source = target.source + val now = Instant.now() + val shown = source.view(view.order, view.popular, view.filter, now) + val rows = shown.map { value -> + val chosen = value == row.current + val lore = Style.lore(emptyList(), source.lore(value, now), *(if (chosen) emptyArray() else arrayOf(Style.left("выбрать")))) + Row(icon(null, if (chosen) "LIME_DYE" else "PAPER", value, lore, good = chosen), if (chosen) null else go { who -> target.pick(who, value) }) + } + val empty = if (view.filter.isEmpty()) "Вариантов нет" else "Ничего не найдено" + list( + player, title(row, view), rows, page, PAGE_SIZE, { who, to -> values(who, target, view, to) }, target.back, empty, + extra = { builder -> + builder.button(DATE_FILTER, typeItem(row, shown.size), go { target.type(it) }) + if (!view.popular) { + val next = view.copy(order = (view.order + 1) % source.orders.size) + builder.button(FILTER, orderItem(source, view), goClick { who, _ -> values(who, target, next, 0) }) + } + if (view.filter.isNotEmpty()) { + builder.button(TOGGLE, resetItem(view), go { who -> values(who, target, view.copy(filter = ""), 0) }) + } else if (source.popular.isNotEmpty()) { + builder.button(TOGGLE, popularItem(view), go { who -> values(who, target, view.copy(popular = !view.popular), 0) }) + } + builder.button(SEARCH, searchItem(view), goClick { who, how -> search(who, target, view, how) }) + }, + ) + } + + private fun title(row: SettingRow, view: View): String = when { + view.filter.isNotEmpty() -> "${row.title}: «${view.filter}»" + view.popular -> "${row.title}: популярные" + else -> row.title + }.take(TITLE_LIMIT) + + /** A click asks for the text in the chat; the wheel clears the search. */ + private fun search(player: MenuViewer, target: Target, view: View, how: ClickType) { + if (how == ClickType.MIDDLE) { + if (view.filter.isNotEmpty()) values(player, target, view.copy(filter = ""), 0) + return + } + suggestCommand(player, "Напишите часть названия для «${target.row.title}», например new york.", "/pn settings pick ${target.row.key} ") + } + + private fun orderItem(source: ChoiceSource, view: View): ItemSpec = + icon( + null, "HOPPER", "Сортировка", + Style.lore(emptyList(), emptyList(), Style.left("следующий порядок"), extra = Style.choices(source.orders.map { it.label }, view.order, 0)), + ) + + private fun popularItem(view: View): ItemSpec = + icon( + null, "NETHER_STAR", "Популярные", + Style.lore(emptyList(), emptyList(), Style.left("переключить"), extra = Style.choices(listOf("Все", "Популярные"), if (view.popular) 1 else 0, 0)), + good = view.popular, + ) + + private fun searchItem(view: View): ItemSpec { + val hints = listOfNotNull(Style.left("искать по названию"), Style.middle("сбросить поиск").takeIf { view.filter.isNotEmpty() }) + val found = listOfNotNull(view.filter.takeIf { it.isNotEmpty() }?.let { "Ищем" to it }) + return icon(null, "COMPASS", "Поиск", Style.lore(emptyList(), found, *hints.toTypedArray())) + } + + private fun resetItem(view: View): ItemSpec = + icon(null, "BARRIER", "Сбросить поиск", Style.lore(emptyList(), listOf("Ищем" to view.filter), Style.left("показать всё")), danger = true) + + private fun typeItem(row: SettingRow, shown: Int): ItemSpec = + icon( + Icons.CHANGELOG, "NAME_TAG", "Ввести в чате", + Style.lore(emptyList(), listOf("Сейчас" to row.current, "Показано" to "$shown"), Style.left("написать значение")), + ) + + private companion object { + const val TOGGLE = 51 + const val SEARCH = 52 + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/SettingsScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/SettingsScreens.kt similarity index 50% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/SettingsScreens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/SettingsScreens.kt index 5e99b518b..acda2184f 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/SettingsScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/SettingsScreens.kt @@ -1,12 +1,40 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.screens +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.core.menu.MenuBuilder +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.Menus +import org.pnfolder.pnlibrary.core.menu.style.HOLDS +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.MenuPermissions +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.ROUTES +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.SETTINGS +import org.pnfolder.pnlibrary.core.menu.style.SMALL_BACK +import org.pnfolder.pnlibrary.core.menu.style.SMALL_ROWS +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.backItem +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.menuFrame +import org.pnfolder.pnlibrary.core.menu.style.menuTitle +import org.pnfolder.pnlibrary.core.menu.style.timeLeft +import org.pnfolder.pnlibrary.core.text.WRAP_WIDTH +import org.pnfolder.pnlibrary.core.text.wrapText import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogView -import org.pnfolder.pnlibrary.core.updates.policy.UpdateDefaults +import org.pnfolder.pnlibrary.updates.policy.UpdateDefaults import java.time.Duration import java.time.Instant +private const val SUPPORT_TOOL_SLOT = 16 +private const val CYCLE_HOLDS = 3 + +/** Menu screens for library settings. */ internal class SettingsScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { private fun pauseFootnote(registered: Int, unregistered: Int): List = buildList { add("") @@ -16,14 +44,30 @@ internal class SettingsScreens(session: MenuSession, routes: MenuRoutes) : MenuS fun settings(player: MenuViewer) { val all = snapshots() - val builder = frame(Menus.chest(title("Настройки")).rows(SMALL_ROWS + 1), SMALL_ROWS + 1) + val builder = menuFrame(Menus.chest(menuTitle("Настройки")).rows(SMALL_ROWS + 1), SMALL_ROWS + 1) howItWorks(builder) autoForAll(builder, all) + downloadsForMissing(builder) pauseForAll(builder, all) + libraryParameters(builder) builder.button(SMALL_BACK + 9, backItem(), go { routes.home(it) }) show(player, builder.build()) } + private fun libraryParameters(builder: MenuBuilder) { + builder.button( + SMALL_BACK, + icon( + Icons.SETTINGS, "WRITABLE_BOOK", "Параметры библиотеки", + Style.lore( + wrapText("Приватность отчётов, часовой пояс, загрузки файлов, время проверки обновлений. То же делает /pn settings.", WRAP_WIDTH, 4), + emptyList(), Style.left("открыть"), + ), + ), + go { who -> allowed(who, MenuPermissions.LIBRARY_SETTINGS) { routes.librarySettings(who, 0) } }, + ) + } + private fun howItWorks(builder: MenuBuilder) { builder.slot( 4, @@ -32,7 +76,7 @@ internal class SettingsScreens(session: MenuSession, routes: MenuRoutes) : MenuS Style.lore( listOf("Проверка и сообщения включены всегда, отключить библиотеку нельзя."), listOf( - "Проверка" to "каждые ${UpdateDefaults.CHECK_INTERVAL.toHours()} ч", + "Проверка" to "каждые ${checkInterval()}", "Консоль" to "сообщения всегда", "Канал" to "только dev", ), @@ -41,6 +85,10 @@ internal class SettingsScreens(session: MenuSession, routes: MenuRoutes) : MenuS ) } + /** How often the catalogs are asked, as this server has it set. */ + private fun checkInterval(): String = + data.settings().firstOrNull { it.key == "updates.check-interval" }?.current ?: "${UpdateDefaults.CHECK_INTERVAL.toHours()}ч" + private fun autoForAll(builder: MenuBuilder, all: List) { val automatic = all.count { it.automaticDownload } val everyoneAuto = all.isNotEmpty() && automatic == all.size @@ -65,6 +113,79 @@ internal class SettingsScreens(session: MenuSession, routes: MenuRoutes) : MenuS ) } + /** The plugins other plugins need and the server lacks: who asks, what, from where; a click downloads a group. */ + fun missingPlugins(player: MenuViewer, page: Int) { + val rows = data.missingDependencies().map { group -> + Row( + icon( + null, if (group.installable) "HOPPER" else "BARRIER", "Нужно для ${group.owner}", + Style.lore( + group.lines + group.links.take(4).map { " $it" } + + (if (group.installable) emptyList() else listOf("Скачайте по ссылкам и положите в plugins.")), + listOf("Код" to group.code), + if (group.installable) Style.left("скачать") else "", + ), + danger = !group.installable, + ), + go { who -> + if (!group.installable) return@go + allowed(who, SETTINGS) { + tell(who, ChatTone.INFO, "Скачиваю…") + data.installDependencies(group.code).whenComplete { text, error -> + sync { + tell(who, if (error == null && text.startsWith("Готово")) ChatTone.SUCCESS else ChatTone.FAILURE, text ?: "Не вышло.") + missingPlugins(who, page) + } + } + } + }, + ) + } + list( + player, "Недостающие плагины", rows, page, PAGE_SIZE, + { who, to -> missingPlugins(who, to) }, { routes.settings(it) }, "Всё нужное установлено", + ) + } + + private fun downloadsForMissing(builder: MenuBuilder) { + val automatic = data.downloadsAutomatic() ?: return + val missing = data.missingDependencies() + if (missing.isNotEmpty()) builder.button( + 14, + icon( + Icons.SETTINGS, "CHEST", "Что не хватает", + Style.lore( + wrapText("Плагины, которые просят другие плагины, а на сервере их нет. Там же можно скачать.", WRAP_WIDTH, 3), + listOf("Групп" to "${missing.size}"), Style.left("открыть"), + ), + danger = true, + ), + go { who -> allowed(who, SETTINGS) { missingPlugins(who, 0) } }, + ) + builder.button( + 13, + icon( + Icons.TOGGLE, "HOPPER", "Недостающие плагины", + Style.lore( + wrapText( + "Если плагину нужен другой плагин, скачать его самому. Иначе в консоль придут ссылки и код: /pn deps install <код>.", + WRAP_WIDTH, + 4, + ), + emptyList(), Style.left(if (automatic) "выключить" else "включить"), + extra = Style.choices(listOf("скачивать самому", "только сообщать"), if (automatic) 0 else 1), + ), + alternative = "REDSTONE_TORCH_ON", good = automatic, muted = !automatic, + ), + go { who -> + allowed(who, SETTINGS) { + data.setDownloadsAutomatic(!automatic) + settings(who) + } + }, + ) + } + private fun pauseForAll(builder: MenuBuilder, all: List) { val untils = all.mapNotNull { data.heldUntil(it.product) }.filter { it.isAfter(Instant.now()) } val longest = untils.maxOrNull()?.let { Duration.between(Instant.now(), it) } @@ -73,7 +194,7 @@ internal class SettingsScreens(session: MenuSession, routes: MenuRoutes) : MenuS 1 + (HOLDS.take(CYCLE_HOLDS).indexOfFirst { it.second >= span }.takeIf { it >= 0 } ?: (CYCLE_HOLDS - 1)) } ?: 0 val pauseNote = buildList { - if (untils.isNotEmpty()) add("Осталось" to left(longest!!)) + longest?.let { add("Осталось" to timeLeft(it)) } if (untils.isNotEmpty()) add("На паузе" to "${untils.size} из ${all.size}") } builder.button( @@ -101,7 +222,7 @@ internal class SettingsScreens(session: MenuSession, routes: MenuRoutes) : MenuS } fun tools(player: MenuViewer) { - val builder = frame(Menus.chest(title("Инструменты")).rows(SMALL_ROWS + 1), SMALL_ROWS + 1) + val builder = menuFrame(Menus.chest(menuTitle("Инструменты")).rows(SMALL_ROWS + 1), SMALL_ROWS + 1) val entries = listOf( Triple(Icons.CHECK, "COMPASS", "Статус сервера") to ("Версии сервера и всех плагинов." to "pn status"), Triple(Icons.CHANGELOG, "WRITTEN_BOOK", "Отчёт для поддержки") to ("Зашифрованный отчёт, который можно отправить нам." to "pn debug"), diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/StatsScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/StatsScreens.kt similarity index 70% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/StatsScreens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/StatsScreens.kt index caa47fb68..6a9d6c18a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/StatsScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/StatsScreens.kt @@ -1,10 +1,25 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.screens +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.Menus +import org.pnfolder.pnlibrary.core.menu.style.DETAIL_BACK +import org.pnfolder.pnlibrary.core.menu.style.DETAIL_ROWS +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.backItem +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.menuFrame +import org.pnfolder.pnlibrary.core.menu.style.menuTitle import org.pnfolder.pnlibrary.core.stats.StatsSnapshot +/** Menu screens with usage statistics. */ internal class StatsScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { fun stats(player: MenuViewer) { val now = data.stats() - val builder = frame(Menus.chest(title("Статистика")).rows(DETAIL_ROWS), DETAIL_ROWS) + val builder = menuFrame(Menus.chest(menuTitle("Статистика")).rows(DETAIL_ROWS), DETAIL_ROWS) builder.slot(4, overview(now)) builder.slot(20, tasks(now)) builder.slot(22, events(now)) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/TaskScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/TaskScreens.kt similarity index 61% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/TaskScreens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/TaskScreens.kt index 8473fc8dc..0fe20babe 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/TaskScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/TaskScreens.kt @@ -1,22 +1,50 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.screens -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskStatus +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus import org.pnfolder.pnlibrary.common.time.DisplayZone import org.pnfolder.pnlibrary.core.commands.tasks.TaskLabels import org.pnfolder.pnlibrary.core.commands.tasks.TaskPeriod import org.pnfolder.pnlibrary.core.commands.tasks.TaskState +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuBuilder +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.Menus +import org.pnfolder.pnlibrary.core.menu.OwnerInfo +import org.pnfolder.pnlibrary.core.menu.data.EventAbout +import org.pnfolder.pnlibrary.core.menu.style.DATE_FILTER +import org.pnfolder.pnlibrary.core.menu.style.DETAIL_BACK +import org.pnfolder.pnlibrary.core.menu.style.DETAIL_ROWS +import org.pnfolder.pnlibrary.core.menu.style.FILTER +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.MESSAGE_PREVIEW +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.TASKS +import org.pnfolder.pnlibrary.core.menu.style.ago +import org.pnfolder.pnlibrary.core.menu.style.backItem +import org.pnfolder.pnlibrary.core.menu.style.clockStamp +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.menuFrame +import org.pnfolder.pnlibrary.core.menu.style.menuTitle import org.pnfolder.pnlibrary.core.tasks.TaskControl +import org.pnfolder.pnlibrary.core.text.wrapText +/** Menu screens for scheduled tasks. */ internal class TaskScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { fun tasks(player: MenuViewer, period: TaskPeriod, state: TaskState, page: Int) { val nextPeriod = TaskPeriod.values()[(period.ordinal + 1) % TaskPeriod.values().size] val nextState = TaskState.values()[(state.ordinal + 1) % TaskState.values().size] - val all = data.tasks() + val everything = data.tasks() + val all = TaskLabels.roots(everything) val inPeriod = all.filter(period::keep) val rows = inPeriod.filter(state::keep).sortedByDescending { TaskLabels.activity(it) }.map { task -> - Row(taskItem(task), go { who -> taskDetail(who, task.id.value) { tasks(it, period, state, page) } }) + Row(taskItem(task, everything), go { who -> taskDetail(who, task.id.value) { tasks(it, period, state, page) } }) } val byDate = icon( Icons.CLOCK, "CLOCK", "Когда", @@ -43,7 +71,7 @@ internal class TaskScreens(session: MenuSession, routes: MenuRoutes) : MenuScree ) } - private fun taskItem(task: TaskSnapshot): ItemSpec { + private fun taskItem(task: TaskSnapshot, all: Collection): ItemSpec { val material = when (task.status) { TaskStatus.SCHEDULED -> "CLOCK" TaskStatus.RUNNING -> "EMERALD" @@ -51,11 +79,14 @@ internal class TaskScreens(session: MenuSession, routes: MenuRoutes) : MenuScree TaskStatus.CANCELLED -> "COAL" TaskStatus.FAILED -> "BARRIER" } - val description = task.description?.let { wrap(it, limit = 3) } ?: listOf("Плагин не описал эту задачу.") + val description = task.description?.let { wrapText(it, limit = 3) } ?: listOf("Плагин не описал эту задачу.") val parameters = buildList { add("Плагин" to ownerLine(task.ownerName)) add("Состояние" to TaskLabels.label(task.status)) add("Запусков" to "${task.runCount}") + TaskLabels.children(task, all).takeIf { it > 0 }?.let { add("Подзадач" to TaskLabels.childrenLine(task, all)) } + TaskLabels.parent(task, all)?.let { add("Подзадача от" to it) } + TaskLabels.lag(task)?.let { add("Опоздание" to it) } task.lastFailure?.let { add("Ошибка" to "✖ ${it.take(MESSAGE_PREVIEW)}") } } val lore = Style.lore(description, parameters, Style.left("подробности")) @@ -71,22 +102,62 @@ internal class TaskScreens(session: MenuSession, routes: MenuRoutes) : MenuScree tell(player, ChatTone.INFO, "Эта задача уже исчезла из списка.") return back(player) } - val builder = frame(Menus.chest(title("Задача")).rows(DETAIL_ROWS), DETAIL_ROWS) + val builder = menuFrame(Menus.chest(menuTitle("Задача")).rows(DETAIL_ROWS), DETAIL_ROWS) taskSummary(builder, task) taskFacts(builder, task) + relations(builder, task, back) runControl(builder, task, back) stopControl(builder, task, back) builder.button(DETAIL_BACK, backItem(), go { back(it) }) show(player, builder.build()) } + /** Slot 33: the parent of a subtask, or the list of subtasks of a task that started some. */ + private fun relations(builder: MenuBuilder, task: TaskSnapshot, back: (MenuViewer) -> Unit) { + val all = data.tasks() + val parent = task.parentId?.let { id -> all.firstOrNull { it.id == id } } + if (parent != null) { + val item = icon( + Icons.ROLLBACK, "ARROW", "Подзадача от: ${TaskLabels.title(parent)}", + Style.lore( + listOf("Эту задачу запустила другая задача."), + listOf("Состояние" to TaskLabels.label(parent.status)), + Style.left("открыть родителя"), + ), + ) + builder.button(33, item, go { who -> taskDetail(who, parent.id.value, back) }) + } + val children = TaskLabels.childrenOf(task, all) + if (children.isNotEmpty()) { + val item = icon( + Icons.CHANGELOG, "CHEST", "Подзадачи: ${children.size}", + Style.lore(listOf("Задачи, которые запустила эта задача."), listOf("Активных" to "${children.count { it.isActive }}"), Style.left("показать")), + ) + builder.button(34, item, go { who -> subtasks(who, task.id.value, back) }) + } + } + + private fun subtasks(player: MenuViewer, parentId: String, back: (MenuViewer) -> Unit) { + val all = data.tasks() + val parent = all.firstOrNull { it.id.value == parentId } ?: return back(player) + val rows = TaskLabels.childrenOf(parent, all).sortedByDescending { TaskLabels.activity(it) }.map { task -> + Row(taskItem(task, all), go { who -> taskDetail(who, task.id.value) { subtasks(it, parentId, back) } }) + } + list( + player, "Подзадачи: ${TaskLabels.title(parent)}", rows, 0, PAGE_SIZE, { who, _ -> subtasks(who, parentId, back) }, + { taskDetail(it, parentId, back) }, "Подзадач нет", + ) + } + private fun taskSummary(builder: MenuBuilder, task: TaskSnapshot) { val summary = buildList { add("Плагин" to ownerLine(task.ownerName)) add("Состояние" to TaskLabels.label(task.status)) task.interval?.let { add("Повторяется" to "каждые ${TaskLabels.span(it)}") } + TaskLabels.parent(task, data.tasks())?.let { add("Подзадача от" to it) } + TaskLabels.children(task, data.tasks()).takeIf { it > 0 }?.let { add("Подзадач" to "$it") } } - val about = task.description?.let { wrap(it) } ?: listOf("Плагин не описал эту задачу.") + val about = task.description?.let { wrapText(it) } ?: listOf("Плагин не описал эту задачу.") builder.slot( 4, icon( @@ -97,24 +168,41 @@ internal class TaskScreens(session: MenuSession, routes: MenuRoutes) : MenuScree } private fun taskFacts(builder: MenuBuilder, task: TaskSnapshot) { - val usage = task.usage?.let { wrap(it) } ?: listOf("Не указано. Плагин может добавить usage в TaskSpec.") + val usage = task.usage?.let { wrapText(it) } ?: listOf("Не указано. Плагин может добавить usage в TaskSpec.") builder.slot(20, icon(Icons.CHANGELOG, "WRITTEN_BOOK", "Как используется", Style.lore(usage, emptyList()), muted = task.usage == null)) val runs = buildList { add("Запусков" to "${task.runCount}") add("Пропущено" to "${task.skippedCount}") - task.lastDuration?.let { add("Последний заняла" to TaskLabels.span(it)) } + task.lastDuration?.let { add("Прошлый запуск шёл" to TaskLabels.span(it)) } + TaskLabels.lag(task)?.let { add("Опоздание" to it) } add("Где" to TaskLabels.where(task)) } builder.slot(21, icon(Icons.SETTINGS, "COMPARATOR", "Как выполняется", Style.lore(emptyList(), runs))) + lagSlot(builder, task) taskTimes(builder, task) } + private fun lagSlot(builder: MenuBuilder, task: TaskSnapshot) { + val lag = TaskLabels.lag(task) + val lore = buildList { + task.lastLag?.let { add("Последнее" to TaskLabels.span(it)) } + task.worstLag?.let { add("Наибольшее" to TaskLabels.span(it)) } + add("Пропущено" to "${task.skippedCount}") + if (task.failedCount > 0) add("Ошибок" to "${task.failedCount}") + } + val note = if (lag == null) "Запуски идут вовремя." else "Сервер или поток не успевали: запуск начинался позже срока." + builder.slot( + 25, + icon(Icons.PROBLEMS, "CLOCK", "Опоздания", Style.lore(listOf(note), lore), alternative = "WATCH", danger = lag != null, muted = lag == null), + ) + } + private fun taskTimes(builder: MenuBuilder, task: TaskSnapshot) { val times = buildList { - add("Создана" to stamp(task.createdAt)) - task.nextRunAt?.let { add("Следующий запуск" to stamp(it)); add("" to ago(it)) } - task.lastStartedAt?.let { add("Последний запуск" to stamp(it)); add("" to ago(it)) } - task.lastCompletedAt?.let { add("Закончилась" to stamp(it)) } + add("Создана" to clockStamp(task.createdAt)) + task.nextRunAt?.let { add("Следующий запуск" to clockStamp(it)); add("" to ago(it)) } + task.lastStartedAt?.let { add("Последний запуск" to clockStamp(it)); add("" to ago(it)) } + task.lastCompletedAt?.let { add("Закончилась" to clockStamp(it)) } add("Пояс" to DisplayZone.zone.id) } builder.slot(22, icon(Icons.CLOCK, "CLOCK", "Время", Style.lore(emptyList(), times), alternative = "WATCH")) @@ -128,7 +216,7 @@ internal class TaskScreens(session: MenuSession, routes: MenuRoutes) : MenuScree } builder.slot(23, icon(Icons.PLUGIN, "PAPER", "Откуда и права", Style.lore(emptyList(), origin))) task.lastFailure?.let { failure -> - val lore = Style.lore(emptyList(), emptyList(), extra = wrap(failure).map { Style.danger(it) }) + val lore = Style.lore(emptyList(), emptyList(), extra = wrapText(failure).map { Style.danger(it) }) builder.slot(24, icon(Icons.PROBLEMS, "BARRIER", "Последняя ошибка", lore, danger = true)) } } @@ -157,7 +245,7 @@ internal class TaskScreens(session: MenuSession, routes: MenuRoutes) : MenuScree } private fun stopControl(builder: MenuBuilder, task: TaskSnapshot, back: (MenuViewer) -> Unit) { - if (!TaskLabels.isActive(task.status)) { + if (!task.isActive) { builder.slot(31, closedControl("Остановка закрыта", TaskLabels.stopAnswer(task).replaceFirstChar { it.uppercase() } + ".")) return } @@ -202,5 +290,5 @@ internal class TaskScreens(session: MenuSession, routes: MenuRoutes) : MenuScree /** [text] as `[ label ]` followed by indented lines, for a value that does not fit one line. */ fun labelled(label: String, text: String): List> = - wrap(text).mapIndexed { index, line -> (if (index == 0) label else "") to line } + wrapText(text).mapIndexed { index, line -> (if (index == 0) label else "") to line } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/UpdateScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/UpdateScreens.kt similarity index 78% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/UpdateScreens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/UpdateScreens.kt index 95fcced9c..7d9e12d37 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/UpdateScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/screens/UpdateScreens.kt @@ -1,15 +1,46 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.screens -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState +import org.pnfolder.pnlibrary.core.exceptions.rootMessage +import org.pnfolder.pnlibrary.core.menu.ClickType +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuBuilder +import org.pnfolder.pnlibrary.core.menu.MenuRoutes +import org.pnfolder.pnlibrary.core.menu.MenuScreens +import org.pnfolder.pnlibrary.core.menu.MenuSession +import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.Menus +import org.pnfolder.pnlibrary.core.menu.style.Icons +import org.pnfolder.pnlibrary.core.menu.style.MenuPermissions +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.ROUTES +import org.pnfolder.pnlibrary.core.menu.style.Row +import org.pnfolder.pnlibrary.core.menu.style.SETTINGS +import org.pnfolder.pnlibrary.core.menu.style.Style +import org.pnfolder.pnlibrary.core.menu.style.backItem +import org.pnfolder.pnlibrary.core.menu.style.clockTime +import org.pnfolder.pnlibrary.core.menu.style.icon +import org.pnfolder.pnlibrary.core.menu.style.menuFrame +import org.pnfolder.pnlibrary.core.menu.style.menuTitle +import org.pnfolder.pnlibrary.core.menu.style.section import org.pnfolder.pnlibrary.core.updates.catalog.CatalogLabels import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogView import java.time.Duration +private const val DOWNLOAD = MenuPermissions.UPDATES_DOWNLOAD +private const val CARD_ROWS = 4 +private const val CARD_BACK = 31 +private const val BLOCKER_LINES = 3 +private const val CHECK_REOPEN_MILLIS = 3_000L +private const val CHANNEL_SWITCH = false + +/** Plugin list filter in the updates screen. */ internal enum class Filter(val title: String) { ALL("Плагины"), UPDATES("Обновления"), PROBLEMS("Проблемы") } +/** Menu screens for plugin updates and problems. */ internal class UpdateScreens(session: MenuSession, routes: MenuRoutes) : MenuScreens(session, routes) { private val policy = PluginPolicyScreens(session, routes) @@ -43,7 +74,7 @@ internal class UpdateScreens(session: MenuSession, routes: MenuRoutes) : MenuScr fun card(player: MenuViewer, product: String) { val snapshot = data.snapshot(product) ?: return routes.home(player) - val builder = frame(Menus.chest(title(snapshot.product)).rows(CARD_ROWS), CARD_ROWS) + val builder = menuFrame(Menus.chest(menuTitle(snapshot.product)).rows(CARD_ROWS), CARD_ROWS) builder.slot(4, plate(snapshot)) cardActions(builder, snapshot) channelSlot(builder, snapshot) @@ -62,6 +93,33 @@ internal class UpdateScreens(session: MenuSession, routes: MenuRoutes) : MenuScr go { who -> who.close(); tell(who, ChatTone.INFO, "Список изменений ${snapshot.product}", link) }, ) } + if (snapshot.javaBuilds.size > 1) { + val now = snapshot.javaBuild ?: snapshot.recommendedJava + builder.button( + 23, + section( + Icons.SETTINGS, "COMPARATOR", "Сборка Java", "У релиза несколько сборок: выберите под вашу Java.", + "Сейчас" to (now?.let { "Java $it" + if (snapshot.javaBuild == null) " (подбор)" else "" } ?: "подбор"), + ), + go { policy.javaBuilds(it, snapshot.product) }, + ) + } + val modules = data.modules().count { it.key.startsWith("${snapshot.product.lowercase()}:", ignoreCase = true) } + if (modules > 0) { + builder.button( + 24, + section(Icons.TOOLS, "CHEST", "Модули", "Включить, выключить или перезапустить модули плагина.", "Модулей" to "$modules"), + go { who -> allowed(who, MenuPermissions.MODULES) { routes.modules(who, snapshot.product, 0) { card(it, snapshot.product) } } }, + ) + } + val libraries = data.libraries().count { it.belongsTo(snapshot.product) } + if (libraries > 0) { + builder.button( + 25, + section(Icons.CHANGELOG, "BOOKSHELF", "Библиотеки", "Что плагин и его модули подключили для работы.", "Всего" to "$libraries"), + go { who -> routes.libraries(who, snapshot.product, 0) { card(it, snapshot.product) } }, + ) + } builder.button(CARD_BACK, backItem(), go { plugins(it, Filter.ALL, 0) }) show(player, builder.build()) } @@ -116,7 +174,7 @@ internal class UpdateScreens(session: MenuSession, routes: MenuRoutes) : MenuScr val link = release.changelogUrl val parameters = buildList { add("Канал" to release.channel.name.lowercase()) - release.publishedAt?.let { add("Выпущен" to time(it)) } + release.publishedAt?.let { add("Выпущен" to clockTime(it)) } if (current) add("Состояние" to "установлена сейчас") } val lore = Style.lore(emptyList(), parameters, *if (link != null) arrayOf(Style.left("получить список изменений")) else emptyArray()) @@ -132,7 +190,7 @@ internal class UpdateScreens(session: MenuSession, routes: MenuRoutes) : MenuScr data.checkAll(player.actor).whenComplete { _, error -> sync { if (!player.online) return@sync - if (error != null) return@sync tell(player, ChatTone.FAILURE, "Не удалось проверить обновления.", reason(error)) + if (error != null) return@sync tell(player, ChatTone.FAILURE, "Не удалось проверить обновления.", error.rootMessage()) val snapshots = snapshots() val news = UpdateCatalogView.announcement(snapshots, ROUTES, PnLibraryIdentity.SUPPORT_URL) if (news.isEmpty()) tell(player, ChatTone.SUCCESS, "Проверка завершена: все плагины используют актуальные версии.") @@ -152,7 +210,7 @@ internal class UpdateScreens(session: MenuSession, routes: MenuRoutes) : MenuScr val enable = !snapshot.automaticDownload data.setAutomatic(snapshot.product, enable, player.actor).whenComplete { _, error -> sync { - if (error != null) tell(player, ChatTone.FAILURE, "Не удалось изменить автозагрузку.", reason(error)) + if (error != null) tell(player, ChatTone.FAILURE, "Не удалось изменить автозагрузку.", error.rootMessage()) else tell(player, ChatTone.SUCCESS, "Автозагрузка ${snapshot.product}: ${if (enable) "включена" else "выключена"}.") card(player, snapshot.product) } @@ -163,7 +221,7 @@ internal class UpdateScreens(session: MenuSession, routes: MenuRoutes) : MenuScr val stages = snapshots().map { change(it).toCompletableFuture() } java.util.concurrent.CompletableFuture.allOf(*stages.toTypedArray()).whenComplete { _, error -> sync { - if (error != null) tell(player, ChatTone.FAILURE, "Не всё удалось изменить.", reason(error)) + if (error != null) tell(player, ChatTone.FAILURE, "Не всё удалось изменить.", error.rootMessage()) else tell(player, ChatTone.SUCCESS, done) routes.settings(player) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/ConfigLook.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/ConfigLook.kt new file mode 100644 index 000000000..37ff719c1 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/ConfigLook.kt @@ -0,0 +1,219 @@ +package org.pnfolder.pnlibrary.core.menu.style + +import org.pnfolder.pnlibrary.api.config.ConfigApply +import org.pnfolder.pnlibrary.api.config.ConfigSetting +import org.pnfolder.pnlibrary.api.config.ConfigSettingKind +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.screens.ConfigRow +import org.pnfolder.pnlibrary.core.text.WRAP_WIDTH +import org.pnfolder.pnlibrary.core.text.wrapText + +/** + * How the configuration screens look: the icon, the name and the lines of every kind of button. + * + * Names stay short (a file shows its own name, not its full address); everything else goes into the description and + * into labelled facts. A long value is broken into short lines under its label, so it never runs off the item. + */ +internal object ConfigLook { + private const val LINE_WIDTH = 38 + private const val LABEL_FRAME = 4 + private const val CONTINUATION_FRAME = 5 + private const val MIN_WIDTH = 12 + private const val FACT_LINES = 5 + private const val BAR_WIDTH = 12 + private const val PERCENT = 100 + private const val BREAKS = " /\\.-_:," + private val RED = MenuColors.color("&#FF7A7A") + private const val CHOICES_SHOWN = 8 + private val GREEN = MenuColors.color("EE7A0") + private val GRAY = MenuColors.color("B7A99") + private val AMBER = MenuColors.color("&#FFB347") + + fun applyWord(apply: ConfigApply) = when (apply) { + ConfigApply.LIVE -> "сразу" + ConfigApply.RELOAD -> "после перечитывания файла" + ConfigApply.RESTART -> "после перезапуска" + } + + fun number(value: Double): String = if (value == Math.floor(value) && Math.abs(value) < 1e15) value.toLong().toString() else value.toString() + + /** + * One fact; a long value continues on the lines below the label. The value is broken at spaces and after `/ \ . - _ :`, + * so a path or a class name is cut between its parts and never inside a word. + */ + fun fact(label: String, value: String): List> { + val lines = softWrap(value, LINE_WIDTH - label.length - LABEL_FRAME, LINE_WIDTH - CONTINUATION_FRAME) + val kept = if (lines.size > FACT_LINES) lines.take(FACT_LINES - 1) + "${lines[FACT_LINES - 1]}…" else lines + return kept.mapIndexed { index, line -> (if (index == 0) label else "") to line } + } + + /** Breaks [text] into lines that fit [firstWidth] and then [width]; a piece longer than a line is cut only as the last resort. */ + fun softWrap(text: String, firstWidth: Int, width: Int): List { + val lines = ArrayList() + var line = StringBuilder() + var limit = firstWidth.coerceAtLeast(MIN_WIDTH) + fun flush() { + lines += line.toString().trimEnd() + line = StringBuilder() + limit = width + } + for (piece in pieces(text)) { + val size = piece.trimEnd().length + if (line.isNotEmpty() && line.length + size > limit) flush() + var rest = piece + while (rest.trimEnd().length > limit) { + if (line.isNotEmpty()) flush() + lines += rest.take(limit) + rest = rest.drop(limit) + limit = width + } + line.append(rest) + } + if (line.isNotEmpty() || lines.isEmpty()) lines += line.toString().trimEnd() + return lines + } + + private fun pieces(text: String): List { + val result = ArrayList() + val current = StringBuilder() + for (char in text) { + current.append(char) + if (char in BREAKS) { + result += current.toString() + current.clear() + } + } + if (current.isNotEmpty()) result += current.toString() + return result + } + + private fun facts(vararg pairs: Pair): List> = pairs.flatMap { (label, value) -> fact(label, value) } + + private fun about(text: String): List = wrapText(text, WRAP_WIDTH, 3) + + private fun editableWord(count: Int) = if (count > 0) "$count" else "нет" + + private fun pending(apply: ConfigApply?): List> = apply?.let { listOf("Ждёт" to AMBER + applyWord(it)) }.orEmpty() + + fun plugin(name: String, modules: Int, files: Int, editable: Int, waiting: ConfigApply?): ItemSpec = icon( + Icons.PLUGIN, "BOOKSHELF", name, + Style.lore( + about("Конфигурации плагина. Откройте, чтобы выбрать модуль или файл."), + facts("Модулей" to "$modules", "Файлов" to "$files", "Можно менять" to editableWord(editable)) + pending(waiting), + Style.left("открыть"), + ), + warn = waiting != null, + ) + + fun module(plugin: String, module: String, files: Int, editable: Int, waiting: ConfigApply?): ItemSpec = icon( + Icons.RELEASES, "CHEST", module, + Style.lore( + about("Модуль плагина $plugin. Внутри его файлы настроек."), + facts("Файлов" to "$files", "Можно менять" to editableWord(editable)) + pending(waiting), + Style.left("файлы модуля"), + ), + warn = waiting != null, + ) + + /** A file: its own name as the title; the plugin and module only when the list mixes several. */ + fun file(row: ConfigRow, plugin: String, module: String, path: String, withPlugin: Boolean, withModule: Boolean): ItemSpec { + val name = path.substringAfterLast('/') + val folder = path.substringBeforeLast('/', "") + val shown = buildList { + if (withPlugin) addAll(fact("Плагин", plugin)) + if (withModule) addAll(fact("Модуль", module)) + if (folder.isNotEmpty()) addAll(fact("Папка", folder)) + addAll(fact("Класс", row.model)) + add("Состояние" to if (row.loaded) "$GREEN● загружен" else "$GRAY○ не загружен") + add("Можно менять" to editableWord(row.editable)) + if (row.readOnly) add("Режим" to "только чтение") + addAll(pending(row.pending)) + } + val text = if (row.editable > 0) "Настройки, которые можно менять в игре." else "В этом файле нет настроек для игры. Его правят вручную." + val hint = if (row.editable > 0) arrayOf(Style.left("настройки")) else emptyArray() + return icon( + if (row.readOnly) Icons.LOCKED else Icons.CHANGELOG, + if (row.readOnly) "BARRIER" else "WRITABLE_BOOK", + name, + Style.lore(about(text), shown, *hint), + good = row.editable > 0 && row.loaded, + warn = row.pending != null, + muted = row.editable == 0, + ) + } + + /** One setting: the value, what it may be, when a change starts to work, and what a click does. */ + fun setting(setting: ConfigSetting, readOnly: Boolean): ItemSpec { + val numeric = setting.kind == ConfigSettingKind.INTEGER || setting.kind == ConfigSettingKind.DECIMAL + val shown = buildList { + when { + setting.kind == ConfigSettingKind.BOOLEAN -> add("Состояние" to if (setting.value == "true") "$GREEN✔ включено" else "$RED✘ выключено") + numeric -> addAll(fact("Значение", ConfigNumbers.shown(setting))) + else -> addAll(fact("Значение", setting.value ?: "?")) + } + if (setting.choices.size > 1) add("Вариант" to "${setting.choices.indexOf(setting.value) + 1} из ${setting.choices.size}") + if (setting.min != null || setting.max != null) add("Границы" to "${setting.min?.let(::number) ?: "…"} … ${setting.max?.let(::number) ?: "…"}") + scale(setting)?.let { add("Шкала" to it) } + if (numeric) addAll(ConfigNumbers.ladder(setting).take(2).let { (one, ten) -> listOf("Шаг" to one.first, "С Shift" to ten.first) }) + if (setting.format.isNotBlank()) addAll(fact("Формат", setting.format)) + if (setting.examples.isNotEmpty()) addAll(fact("Примеры", setting.examples.joinToString(", "))) + if (setting.apply != ConfigApply.LIVE) add("Заработает" to AMBER + applyWord(setting.apply)) + } + val description = setting.description.takeIf(String::isNotBlank)?.let { wrapText(it, WRAP_WIDTH, 4) }.orEmpty() + val (texture, material) = when (setting.kind) { + ConfigSettingKind.BOOLEAN -> Icons.TOGGLE to if (setting.value == "true") "LIME_DYE" else "GRAY_DYE" + ConfigSettingKind.CHOICE -> Icons.SETTINGS to "COMPARATOR" + ConfigSettingKind.INTEGER, ConfigSettingKind.DECIMAL -> Icons.CLOCK to if (setting.duration != null) "CLOCK" else "REPEATER" + ConfigSettingKind.TEXT -> Icons.CHANGELOG to "NAME_TAG" + } + return icon( + texture, material, setting.title, + Style.lore(description, shown, *hints(setting, readOnly), extra = choices(setting)), + good = setting.kind == ConfigSettingKind.BOOLEAN && setting.value == "true", + muted = setting.kind == ConfigSettingKind.BOOLEAN && setting.value != "true", + ) + } + + /** Where a number sits between its bounds, as a bar; only when both bounds are known. */ + private fun scale(setting: ConfigSetting): String? { + val low = setting.min ?: return null + val high = setting.max?.takeIf { it > low } ?: return null + val value = setting.value?.toDoubleOrNull() ?: return null + val share = ((value - low) / (high - low)).coerceIn(0.0, 1.0) + val filled = Math.round(share * BAR_WIDTH).toInt() + return GREEN + "█".repeat(filled) + GRAY + "░".repeat(BAR_WIDTH - filled) + " ${Math.round(share * PERCENT)}%" + } + + private fun hints(setting: ConfigSetting, readOnly: Boolean): Array = if (readOnly) emptyArray() else when (setting.kind) { + ConfigSettingKind.BOOLEAN -> arrayOf(Style.left("включить или выключить")) + ConfigSettingKind.CHOICE -> + if (setting.choices.size > CHOICES_SHOWN) arrayOf(Style.left("следующий"), Style.right("предыдущий"), Style.shiftLeft("весь список")) + else arrayOf(Style.left("следующий вариант"), Style.right("предыдущий")) + ConfigSettingKind.INTEGER, ConfigSettingKind.DECIMAL -> + arrayOf(Style.left("больше"), Style.right("меньше"), Style.shiftLeft("в десять раз сильнее"), Style.middle("ввести число")) + ConfigSettingKind.TEXT -> arrayOf(Style.left("ввести текст в чате")) + } + + /** The choices one under another with the current one marked; a long list shows the window around it. */ + private fun choices(setting: ConfigSetting): List = window(setting.choices, setting.choices.indexOf(setting.value).coerceAtLeast(0)) + + /** + * The rolling switcher: [options] one under another with the one at [at] marked, at most [CHOICES_SHOWN] lines around + * it, and `▲ выше ещё N` / `▼ ниже ещё N` for what is cut off. Config settings and library settings share it. + */ + fun window(options: List, at: Int): List { + if (options.isEmpty()) return emptyList() + val from = (at - CHOICES_SHOWN / 2).coerceIn(0, (options.size - CHOICES_SHOWN).coerceAtLeast(0)) + val shown = options.drop(from).take(CHOICES_SHOWN) + val below = options.size - from - shown.size + return buildList { + if (from > 0) add("$GRAY ▲ выше ещё $from") + addAll(Style.choices(shown, at - from)) + if (below > 0) add("$GRAY ▼ ниже ещё $below") + } + } + + /** The "where you are" item of a screen: the path down to the plugin, module or file. */ + fun place(vararg pairs: Pair): ItemSpec = + icon(Icons.PLUGINS, "COMPASS", "Где вы", Style.lore(emptyList(), facts(*pairs))) +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/ConfigNumbers.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/ConfigNumbers.kt new file mode 100644 index 000000000..b6786abf3 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/ConfigNumbers.kt @@ -0,0 +1,74 @@ +package org.pnfolder.pnlibrary.core.menu.style + +import org.pnfolder.pnlibrary.api.config.ConfigSetting +import java.util.concurrent.TimeUnit + +/** How numbers of the settings menu are written, stepped and cut into the buttons of the number editor. */ +internal object ConfigNumbers { + private const val LADDER = 4 + private const val TEN = 10.0 + private val SECOND = TimeUnit.SECONDS.toMillis(1) + private val MINUTE = TimeUnit.MINUTES.toMillis(1) + private val HOUR = TimeUnit.HOURS.toMillis(1) + private val DAY = TimeUnit.DAYS.toMillis(1) + private val PARTS = listOf(DAY to "д", HOUR to "ч", MINUTE to "мин", SECOND to "с", 1L to "мс") + + /** Sizes of one step for a time kept in each unit, smallest first. */ + private val TIME_STEPS = mapOf( + TimeUnit.MILLISECONDS to listOf(1L, 100L, SECOND, 10 * SECOND), + TimeUnit.SECONDS to listOf(SECOND, MINUTE, 10 * MINUTE, HOUR), + TimeUnit.MINUTES to listOf(MINUTE, 10 * MINUTE, HOUR, DAY), + TimeUnit.HOURS to listOf(HOUR, 6 * HOUR, DAY, 7 * DAY), + TimeUnit.DAYS to listOf(DAY, 7 * DAY, 30 * DAY, 365 * DAY), + ) + + /** The value with its unit, and for a time also written out: `5400 сек (1 ч 30 мин)`. */ + fun shown(setting: ConfigSetting): String { + val value = setting.value ?: return "?" + val unit = setting.duration ?: return if (setting.unit.isBlank()) value else "$value ${setting.unit}" + val millis = value.toDoubleOrNull()?.let { (it * unit.toMillis(1)).toLong() } ?: return value + return "$value ${unitWord(unit)} (${human(millis)})" + } + + /** A length of time in words: `1 ч 30 мин`. */ + fun human(millis: Long): String { + if (millis <= 0) return "0 с" + var rest = millis + val words = PARTS.mapNotNull { (size, word) -> + val count = rest / size + rest %= size + if (count > 0) "$count $word" else null + } + return words.take(LADDER).joinToString(" ") + } + + /** The four step sizes of a number, smallest first: the label and the amount in the unit the field keeps. */ + fun ladder(setting: ConfigSetting): List> { + val unit = setting.duration + if (unit != null) { + val one = unit.toMillis(1).coerceAtLeast(1) + val sizes = TIME_STEPS[unit] ?: listOf(one, one * 10, one * 100, one * 1000) + val ladder = sizes.map { human(it) to it.toDouble() / one }.filter { fits(it.second, setting) }.take(LADDER) + return if (ladder.size >= 2) ladder else listOf("1" to 1.0, "10" to TEN) + } + val label = setting.unit.takeIf(String::isNotBlank)?.let { " $it" }.orEmpty() + val amounts = generateSequence(setting.step) { it * TEN }.take(LADDER).filter { fits(it, setting) }.toList() + .let { if (it.size >= 2) it else listOf(setting.step, setting.step * TEN) } + return amounts.map { ConfigLook.number(it) + label to it } + } + + private fun fits(amount: Double, setting: ConfigSetting): Boolean { + val low = setting.min + val high = setting.max + return low == null || high == null || amount <= high - low || amount == setting.step + } + + fun unitWord(unit: TimeUnit): String = when (unit) { + TimeUnit.MILLISECONDS -> "мс" + TimeUnit.SECONDS -> "сек" + TimeUnit.MINUTES -> "мин" + TimeUnit.HOURS -> "ч" + TimeUnit.DAYS -> "дн" + else -> unit.name.lowercase() + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuColors.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuColors.kt similarity index 96% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuColors.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuColors.kt index 0191fb1df..bf9358150 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuColors.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuColors.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.style /** * Colours of the menu text, written as the `§x§R§R§G§G§B§B` form that every platform understands. diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuConstants.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuConstants.kt new file mode 100644 index 000000000..ccd49c5e8 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuConstants.kt @@ -0,0 +1,41 @@ +package org.pnfolder.pnlibrary.core.menu.style + +import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogRoutes +import java.time.Duration + +internal val ROUTES = UpdateCatalogRoutes("/pn updates", update = { product -> "/pn update $product" }, check = "/pn check") +internal const val SETTINGS = MenuPermissions.UPDATES_SETTINGS +internal const val ROLLBACK = MenuPermissions.UPDATES_ROLLBACK +internal const val HOME_ROWS = 5 +internal const val NETWORK_CHECK = 49 +internal const val GROUPS_PERMISSION = "pnlibrary.groups" +internal const val HOME_CLOSE = 40 +internal const val SMALL_ROWS = 3 +internal const val SMALL_BACK = 22 +internal const val PAGE_SIZE = 45 +internal const val HISTORY_PAGE = 10 +internal const val FOOTER_END = 54 +internal const val BACK = 45 +internal const val PREVIOUS = 48 +internal const val NEXT = 50 +internal const val FILTER = 47 +internal const val DATE_FILTER = 46 +internal const val JOURNAL_HOURS = 24 +internal const val JOURNAL_LIMIT = 200 +internal const val MESSAGE_PREVIEW = 70 +internal const val BUS = MenuPermissions.EVENTS_BUS +internal const val TASKS = MenuPermissions.TASKS +internal const val STATS = MenuPermissions.STATS +internal const val PLACEHOLDERS = MenuPermissions.PLACEHOLDERS +internal const val CONFIGS = "pnlibrary.configs" +internal const val DETAIL_ROWS = 5 +internal const val DETAIL_BACK = 40 +internal const val TITLE_LIMIT = 30 +/** Whether the menu may change the update channel; only `dev` works for now, so the choice is switched off. */ +internal val HOLDS = listOf( + "1 час" to Duration.ofHours(1), + "6 часов" to Duration.ofHours(6), + "1 день" to Duration.ofDays(1), + "3 дня" to Duration.ofDays(3), + "7 дней" to Duration.ofDays(7), +) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuPermissions.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuPermissions.kt new file mode 100644 index 000000000..9d928d0a7 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuPermissions.kt @@ -0,0 +1,26 @@ +package org.pnfolder.pnlibrary.core.menu.style + +/** Every permission that opens a page of the menu, each named once. */ +internal object MenuPermissions { + const val ADMIN = "pnlibrary.admin" + const val SERVERS = "pnlibrary.servers" + const val UPDATES_VIEW = "pnlibrary.updates.view" + const val UPDATES_DOWNLOAD = "pnlibrary.updates.download" + const val UPDATES_ROLLBACK = "pnlibrary.updates.rollback" + const val UPDATES_SETTINGS = "pnlibrary.updates.settings" + const val UPDATES_RESTART = "pnlibrary.updates.restart" + const val EVENTS_VIEW = "pnlibrary.events.view" + const val EVENTS_BUS = "pnlibrary.events.bus" + const val TASKS = "pnlibrary.tasks" + const val MODULES = "pnlibrary.modules" + const val STATS = "pnlibrary.stats" + const val PLACEHOLDERS = "pnlibrary.placeholders" + const val DEBUG = "pnlibrary.debug" + const val CURRENCY_LIST = "pnlibrary.currency.list" + const val LIBRARY_SETTINGS = "pnlibrary.settings" + + val ALL = listOf( + ADMIN, SERVERS, UPDATES_VIEW, UPDATES_DOWNLOAD, UPDATES_ROLLBACK, UPDATES_SETTINGS, UPDATES_RESTART, + EVENTS_VIEW, EVENTS_BUS, TASKS, MODULES, STATS, PLACEHOLDERS, DEBUG, CURRENCY_LIST, LIBRARY_SETTINGS, + ) +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuStyle.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuStyle.kt similarity index 80% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuStyle.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuStyle.kt index 0d4f370c1..f6252e247 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/MenuStyle.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuStyle.kt @@ -1,5 +1,17 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.style +import org.pnfolder.pnlibrary.core.menu.ItemSpec +import org.pnfolder.pnlibrary.core.menu.MenuBuilder +import org.pnfolder.pnlibrary.core.menu.MenuClickHandler + +private const val FOOTER_START = 45 +private const val LEGACY_BLACK: Short = 15 +private const val LEGACY_PURPLE: Short = 10 + +/** The remark after the option that is the default one. */ +internal const val DEFAULT_NOTE = "(по умолчанию)" + +/** Gradient color pair used for titles and highlights. */ internal enum class Tone(val from: String, val to: String) { NORMAL("D19BFF", "F5C6FF"), GOOD("6EE7A0", "B8F5D2"), @@ -8,6 +20,7 @@ internal enum class Tone(val from: String, val to: String) { MUTED("9AA4AD", "C9D0D6"), } +/** One menu row: an item and an optional click handler. */ internal class Row(val stack: ItemSpec, val click: MenuClickHandler? = null) internal fun section(texture: String?, material: String, label: String, description: String, vararg parameters: Pair): ItemSpec = @@ -19,9 +32,9 @@ internal fun backItem(label: String = "Назад"): ItemSpec = internal fun closeItem(): ItemSpec = icon(Icons.BACK, "BARRIER", "Закрыть", Style.lore(emptyList(), emptyList(), Style.left("закрыть меню")), danger = true) -internal fun title(text: String): String = MenuColors.legacy('0') + "pnLibrary " + MenuColors.legacy('5') + "» " + MenuColors.legacy('0') + text +internal fun menuTitle(text: String): String = MenuColors.legacy('0') + "pnLibrary " + MenuColors.legacy('5') + "» " + MenuColors.legacy('0') + text -internal fun frame(builder: MenuBuilder, rows: Int): MenuBuilder { +internal fun menuFrame(builder: MenuBuilder, rows: Int): MenuBuilder { val last = (rows - 1) * 9 listOf(0, 1, 9, 7, 8, 17, last, last + 1, last - 9, last + 7, last + 8, last - 1).forEach { builder.slot(it, accent()) } return builder.fill(pane()) @@ -62,6 +75,7 @@ internal fun icon( return ItemSpec(texture, material, alternative, Style.name(label, tone), lore) } +/** Shared item builders and text styles for menu screens. */ internal object Style { private val DIM = MenuColors.color("ﰢE") private val PLAIN = MenuColors.color("&#F7F2F7") @@ -80,14 +94,21 @@ internal object Style { fun shiftLeft(action: String): String = click("Shift + клик", "5BC8F5", "B5ECFF", action) + fun middle(action: String): String = click("Колёсико", "FDE047", "FFB347", action) + fun description(text: String): String = DESCRIPTION + text - fun choices(options: List, selected: Int): List = options.mapIndexed { index, label -> - if (index == selected) { + /** A small grey italic remark, for example `(по умолчанию)` after an option; the one place that turns italics on. */ + fun note(text: String): String = MenuColors.color(" AA4AD") + MenuColors.legacy('o') + text + + /** The option list of a switch or a choice; the option at [defaultIndex] gets the grey italic mark [DEFAULT_NOTE]. */ + fun choices(options: List, selected: Int, defaultIndex: Int? = null): List = options.mapIndexed { index, label -> + val line = if (index == selected) { MenuColors.color(" EE7A0➤ ") + MenuColors.gradient(label, "D19BFF", "FF9BD2") } else { MenuColors.color(" ﰢE· B7A99") + label } + if (index == defaultIndex) "$line ${note(DEFAULT_NOTE)}" else line } fun danger(text: String): String = MenuColors.color(" &#FF7A7A") + text @@ -121,6 +142,7 @@ internal object Style { } } +/** Item materials used as icons in menu screens. */ internal object Icons { const val OVERVIEW = "35747010d84aa56483b75f6243d94f34c534603584b2cc68a45bf365840105fd" const val PLUGINS = "c16808126eec0cd41d6040e211985719272c388d32ecae795d47f7a9cee71113" diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuText.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuText.kt new file mode 100644 index 000000000..601fa3659 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuText.kt @@ -0,0 +1,49 @@ +package org.pnfolder.pnlibrary.core.menu.style + +import org.pnfolder.pnlibrary.common.time.DisplayZone +import org.pnfolder.pnlibrary.core.text.BAR_WIDTH +import java.time.Duration +import java.time.Instant +import java.time.LocalDate +import java.time.format.DateTimeFormatter +import java.util.Locale + +private const val HOURS_PER_DAY = 24 +private const val MINUTES_PER_HOUR = 60 +private const val SECONDS_PER_MINUTE = 60L + +internal fun timeLeft(span: Duration): String { + val days = span.toDays() + val hours = span.toHours() % HOURS_PER_DAY + val minutes = span.toMinutes() % MINUTES_PER_HOUR + return when { + days > 0 -> "$days д $hours ч" + hours > 0 -> "$hours ч $minutes мин" + else -> "${minutes.coerceAtLeast(1)} мин" + } +} + +internal fun clockTime(moment: Instant): String = format(moment, "HH:mm") + +internal fun clockStamp(moment: Instant): String = format(moment, "HH:mm:ss") + +private fun format(moment: Instant, clock: String): String { + val zone = DisplayZone.zone + val year = if (moment.atZone(zone).year == LocalDate.now(zone).year) "" else " yyyy" + return DateTimeFormatter.ofPattern("d MMMM$year, $clock", Locale("ru")).withZone(zone).format(moment) +} + +/** How long ago [moment] was, or how long until it: `только что`, `5 мин назад`, `через 2 ч 10 мин`. */ +internal fun ago(moment: Instant): String { + val span = Duration.between(moment, Instant.now()) + return when { + span.abs().seconds < SECONDS_PER_MINUTE -> "только что" + span.isNegative -> "через ${timeLeft(span.negated())}" + else -> "${timeLeft(span)} назад" + } +} + +internal fun progressBar(value: Long, busiest: Long): String { + val width = ((value * BAR_WIDTH + busiest - 1) / busiest.coerceAtLeast(1)).toInt().coerceIn(1, BAR_WIDTH) + return "█".repeat(width) +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/ChartIds.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/ChartIds.kt new file mode 100644 index 000000000..a8cc6f9ca --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/ChartIds.kt @@ -0,0 +1,8 @@ +package org.pnfolder.pnlibrary.core.metrics + +private val CHART_ID = Regex("[A-Za-z0-9_-]{1,64}") + +/** Trims this chart id and rejects values that a metrics provider could not represent; every supported provider accepts the rest. */ +internal fun String.validChartId(): String = trim().also { + require(CHART_ID.matches(it)) { "Invalid metrics chart id: $this" } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/ErrorPipeline.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/ErrorPipeline.kt index 6547fd372..cfbf1b386 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/ErrorPipeline.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/ErrorPipeline.kt @@ -1,7 +1,8 @@ package org.pnfolder.pnlibrary.core.metrics -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter -import org.pnfolder.pnlibrary.api.metrics.TelemetryError +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.error.TelemetryError +import org.pnfolder.pnlibrary.common.concurrent.FailureThrottle import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean @@ -14,7 +15,9 @@ import java.util.concurrent.atomic.AtomicLong internal class ErrorPipeline( private val delegate: ErrorReporter? = null, private val maxStackFrames: Int = 80, + private val onForwardingFailure: (Throwable) -> Unit = {}, ) : ErrorReporter { + private val failureThrottle = FailureThrottle() private val closed = AtomicBoolean(false) private val seen = ConcurrentHashMap.newKeySet() private val captured = AtomicLong() @@ -31,7 +34,10 @@ internal class ErrorPipeline( if (seen.add(fingerprint)) { forwarded.incrementAndGet() runCatchingNonFatal { delegate?.capture(safe) } - .onFailure { forwardingFailures.incrementAndGet() } + .onFailure { failure -> + forwardingFailures.incrementAndGet() + if (failureThrottle.shouldReport(failure.javaClass.name)) onForwardingFailure(failure) + } } else { deduplicated.incrementAndGet() } @@ -61,8 +67,15 @@ internal class ErrorPipeline( ) private fun redact(value: String?): String? = value - ?.replace(Regex("(?i)(Bearer\\s+)[A-Za-z0-9._~+/=-]+"), "$1[redacted]") - ?.replace(Regex("(?i)([?&](?:api_?key|token|secret)=)[^&\\s]+"), "$1[redacted]") - ?.replace(Regex("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"), "[uuid]") - ?.replace(Regex("(?i)(/home/|/Users/|C:\\\\Users\\\\)[^/\\\\\\s]+"), "$1[user]") + ?.replace(BEARER, "$1[redacted]") + ?.replace(QUERY_SECRET, "$1[redacted]") + ?.replace(UUID, "[uuid]") + ?.replace(HOME_FOLDER, "$1[user]") + + private companion object { + val BEARER = Regex("(?i)(Bearer\\s+)[A-Za-z0-9._~+/=-]+") + val QUERY_SECRET = Regex("(?i)([?&](?:api_?key|token|secret)=)[^&\\s]+") + val UUID = Regex("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") + val HOME_FOLDER = Regex("(?i)(/home/|/Users/|C:\\\\Users\\\\)[^/\\\\\\s]+") + } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/MetricsChartId.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/MetricsChartId.kt deleted file mode 100644 index b0cf03f9d..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/MetricsChartId.kt +++ /dev/null @@ -1,12 +0,0 @@ -package org.pnfolder.pnlibrary.core.metrics - -/** Chart identifier rules accepted by every supported metrics provider. */ -internal object MetricsChartId { - private val PATTERN = Regex("[A-Za-z0-9_-]{1,64}") - - /** Trims [id] and rejects values that a provider could not represent. */ - @JvmStatic - fun normalize(id: String): String = id.trim().also { - require(PATTERN.matches(it)) { "Invalid metrics chart id: $id" } - } -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/bstats/BStatsClient.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/bstats/BStatsClient.kt index ce8624310..51cdfd1f6 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/bstats/BStatsClient.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/bstats/BStatsClient.kt @@ -3,27 +3,9 @@ package org.pnfolder.pnlibrary.core.metrics.bstats import org.bstats.MetricsBase import org.bstats.charts.CustomChart import org.bstats.json.JsonObjectBuilder -import java.util.function.BiConsumer import java.util.function.Consumer -import java.util.function.Supplier -/** - * The one bStats sender for every platform. - * - * Collecting charts, timing and submitting stay in [MetricsBase], which must not be changed. A platform only says what - * differs between servers: its name, where the settings are, what it reports about itself, and how to reach the main - * thread and the log. - * - * @param platform the platform name bStats knows: `bukkit`, `bungeecord` or `velocity` - * @param serviceId the bStats identifier of the plugin - * @param settings what the shared bStats file says - * @param pluginVersion version of the plugin that reports - * @param appendPlatformData adds what the platform reports about itself: players, online mode, version - * @param mainThread runs a task on the server thread, or `null` when data may be collected on any thread - * @param ownerEnabled whether the plugin is still running; sending stops once it is not - * @param warn writes a warning with the cause to the plugin log - * @param info writes a line to the plugin log - */ +/** The one bStats sender for every platform. Collecting charts, timing and submitting stay in [MetricsBase]. */ class BStatsClient( platform: String, serviceId: Int, @@ -40,7 +22,7 @@ class BStatsClient( settings.serverUuid, serviceId, settings.enabled, - Consumer { builder -> + { builder -> appendPlatformData(builder) builder.appendField("javaVersion", System.getProperty("java.version")) builder.appendField("osName", System.getProperty("os.name")) @@ -48,23 +30,18 @@ class BStatsClient( builder.appendField("osVersion", System.getProperty("os.version")) builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()) }, - Consumer { builder -> builder.appendField("pluginVersion", pluginVersion) }, + { builder -> builder.appendField("pluginVersion", pluginVersion) }, mainThread?.let { run -> Consumer { task -> run(task) } }, - Supplier { ownerEnabled() }, - BiConsumer { message, error -> warn(message, error) }, - Consumer { message -> info(message) }, + { ownerEnabled() }, + { message, error -> warn(message, error) }, + { message -> info(message) }, settings.logFailedRequests, settings.logSentData, settings.logResponseStatusText, false, ) - /** Adds a chart that is read each time data is sent. */ - fun addCustomChart(chart: CustomChart) { - base.addCustomChart(chart) - } + fun addCustomChart(chart: CustomChart) = base.addCustomChart(chart) - fun shutdown() { - base.shutdown() - } + fun shutdown() = base.shutdown() } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/bstats/BStatsMetricsSession.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/bstats/BStatsMetricsSession.kt index 456f92039..9b78afc75 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/bstats/BStatsMetricsSession.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/bstats/BStatsMetricsSession.kt @@ -8,8 +8,8 @@ import org.bstats.charts.MultiLineChart import org.bstats.charts.SimpleBarChart import org.bstats.charts.SimplePie import org.bstats.charts.SingleLineChart -import org.pnfolder.pnlibrary.api.metrics.MetricsCredentials -import org.pnfolder.pnlibrary.core.metrics.AbstractMetricsSession +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsCredentials +import org.pnfolder.pnlibrary.core.metrics.session.AbstractMetricsSession /** Translates shared lazy chart definitions into native bStats charts. */ class BStatsMetricsSession( diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/CompositePluginMetrics.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/factory/CompositePluginMetrics.kt similarity index 93% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/CompositePluginMetrics.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/factory/CompositePluginMetrics.kt index 72c5ed349..e85307628 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/CompositePluginMetrics.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/factory/CompositePluginMetrics.kt @@ -1,8 +1,8 @@ -package org.pnfolder.pnlibrary.core.metrics +package org.pnfolder.pnlibrary.core.metrics.factory -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider import org.pnfolder.pnlibrary.api.metrics.PluginMetrics -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup import java.util.Collections import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Supplier diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/NativePluginMetricsFactory.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/factory/NativePluginMetricsFactory.kt similarity index 96% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/NativePluginMetricsFactory.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/factory/NativePluginMetricsFactory.kt index 756681079..26d890afb 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/NativePluginMetricsFactory.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/factory/NativePluginMetricsFactory.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.metrics +package org.pnfolder.pnlibrary.core.metrics.factory import org.pnfolder.pnlibrary.api.metrics.PluginMetrics diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/ProviderMetricsFactory.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/factory/ProviderMetricsFactory.kt similarity index 90% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/ProviderMetricsFactory.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/factory/ProviderMetricsFactory.kt index da8e2929c..fb0776a66 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/ProviderMetricsFactory.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/factory/ProviderMetricsFactory.kt @@ -1,8 +1,8 @@ -package org.pnfolder.pnlibrary.core.metrics +package org.pnfolder.pnlibrary.core.metrics.factory -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.spi.metrics.PlatformMetricsFactory diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/faststats/AbstractFastStatsMetricsSession.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/faststats/AbstractFastStatsMetricsSession.kt index 59841bdd9..ba33120ea 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/faststats/AbstractFastStatsMetricsSession.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/faststats/AbstractFastStatsMetricsSession.kt @@ -2,8 +2,8 @@ package org.pnfolder.pnlibrary.core.metrics.faststats import dev.faststats.ErrorTracker import dev.faststats.Metrics -import org.pnfolder.pnlibrary.api.metrics.MetricsCredentials -import org.pnfolder.pnlibrary.core.metrics.AbstractMetricsSession +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsCredentials +import org.pnfolder.pnlibrary.core.metrics.session.AbstractMetricsSession import java.util.concurrent.atomic.AtomicBoolean /** diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/faststats/FastStatsSupport.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/faststats/FastStatsSupport.kt index d52c34fc2..0bd0eba1c 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/faststats/FastStatsSupport.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/faststats/FastStatsSupport.kt @@ -4,27 +4,24 @@ import com.google.gson.JsonArray import com.google.gson.JsonObject import dev.faststats.Metrics import dev.faststats.TrackedError -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter -import org.pnfolder.pnlibrary.api.metrics.TelemetryError -import org.pnfolder.pnlibrary.core.metrics.MetricsChartId +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.error.TelemetryError +import org.pnfolder.pnlibrary.core.metrics.validChartId import org.pnfolder.pnlibrary.internal.faststats.FastStatsBridge import java.util.concurrent.Callable import java.util.function.Supplier /** Shared, platform-neutral FastStats helpers used by every platform adapter. */ internal object FastStatsSupport { - @JvmStatic - fun validId(id: String): String = MetricsChartId.normalize(id) - fun simplePie(factory: Metrics.Factory, id: String, value: Supplier) = - factory.addMetric(FastStatsBridge.string(validId(id), Callable { value.get() ?: "unknown" })) + factory.addMetric(FastStatsBridge.string(id.validChartId(), Callable { value.get() ?: "unknown" })) /** Publishes name-to-count pairs; FastStats represents pies, lines and simple bars identically. */ fun numberMap(factory: Metrics.Factory, id: String, values: Supplier>) = - factory.addMetric(FastStatsBridge.numberMap(validId(id), Callable { values.get() })) + factory.addMetric(FastStatsBridge.numberMap(id.validChartId(), Callable { values.get() })) fun drilldownPie(factory: Metrics.Factory, id: String, values: Supplier>>) = - factory.addMetric(FastStatsBridge.`object`(validId(id), Callable { + factory.addMetric(FastStatsBridge.`object`(id.validChartId(), Callable { JsonObject().also { root -> values.get().forEach { (group, entries) -> root.add(group, JsonObject().also { child -> entries.forEach { (key, value) -> child.addProperty(key, value) } }) @@ -33,10 +30,10 @@ internal object FastStatsSupport { })) fun singleLineChart(factory: Metrics.Factory, id: String, value: Supplier) = - factory.addMetric(FastStatsBridge.number(validId(id), Callable { value.get() })) + factory.addMetric(FastStatsBridge.number(id.validChartId(), Callable { value.get() })) fun advancedBarChart(factory: Metrics.Factory, id: String, values: Supplier>) = - factory.addMetric(FastStatsBridge.`object`(validId(id), Callable { + factory.addMetric(FastStatsBridge.`object`(id.validChartId(), Callable { JsonObject().also { root -> values.get().forEach { (key, numbers) -> root.add(key, JsonArray().also { array -> numbers.forEach(array::add) }) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/AbstractMetricsSession.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/session/AbstractMetricsSession.kt similarity index 96% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/AbstractMetricsSession.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/session/AbstractMetricsSession.kt index 38e2293eb..3aaed4052 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/AbstractMetricsSession.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/session/AbstractMetricsSession.kt @@ -1,8 +1,8 @@ -package org.pnfolder.pnlibrary.core.metrics +package org.pnfolder.pnlibrary.core.metrics.session -import org.pnfolder.pnlibrary.api.metrics.MetricsCredentials -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsCredentials +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Supplier diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/MetricsSessions.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/session/MetricsSessions.kt similarity index 93% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/MetricsSessions.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/session/MetricsSessions.kt index f9ff08859..75eacfa16 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/MetricsSessions.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/metrics/session/MetricsSessions.kt @@ -1,11 +1,12 @@ -package org.pnfolder.pnlibrary.core.metrics +package org.pnfolder.pnlibrary.core.metrics.session -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.metrics.MetricsService import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.core.metrics.ErrorPipeline import org.pnfolder.pnlibrary.spi.metrics.PlatformMetricsFactory import java.util.Collections import java.util.IdentityHashMap diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/DiagnosticObservationBridge.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/DiagnosticObservationBridge.kt deleted file mode 100644 index a4184075a..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/DiagnosticObservationBridge.kt +++ /dev/null @@ -1,49 +0,0 @@ -package org.pnfolder.pnlibrary.core.observability - -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticLevel -import org.pnfolder.pnlibrary.api.observability.ObservationLevel -import org.pnfolder.pnlibrary.api.observability.ObservationRequest - -/** Translates one legacy diagnostic incident into one modern observation. */ -internal class DiagnosticObservationBridge( - private val runtime: ObservabilityRuntime, -) { - fun record( - plugin: String, - level: DiagnosticLevel, - component: String, - code: String, - message: String, - error: Throwable?, - fields: Map, - ) { - runtime.record( - ObservationRequest( - plugin = plugin, - source = component, - message = message, - level = level.toObservationLevel(), - data = observationData(code, error, fields), - error = error, - ), - ) - } - - private fun observationData( - code: String, - error: Throwable?, - fields: Map, - ): Map = fields.toStringValues() + mapOf( - "code" to code, - "hasException" to (error != null).toString(), - ) -} - -internal fun DiagnosticLevel.toObservationLevel(): ObservationLevel = when (this) { - DiagnosticLevel.INFO -> ObservationLevel.INFO - DiagnosticLevel.WARNING -> ObservationLevel.WARNING - DiagnosticLevel.ERROR -> ObservationLevel.ERROR -} - -internal fun Map.toStringValues(): Map = - mapValues { (_, value) -> value?.toString() ?: "null" } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/LegacyActivityMapper.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/LegacyActivityMapper.kt deleted file mode 100644 index 46d107a62..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/LegacyActivityMapper.kt +++ /dev/null @@ -1,48 +0,0 @@ -package org.pnfolder.pnlibrary.core.observability - -import org.pnfolder.pnlibrary.api.activity.ActivityCategory -import org.pnfolder.pnlibrary.api.activity.ActivityEvent -import org.pnfolder.pnlibrary.api.activity.ActivityQuery -import org.pnfolder.pnlibrary.api.activity.ActivitySeverity -import org.pnfolder.pnlibrary.api.observability.Observation -import org.pnfolder.pnlibrary.api.observability.ObservationLevel -import org.pnfolder.pnlibrary.api.observability.ObservationQuery -import org.pnfolder.pnlibrary.api.observability.ObservationRequest -import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal - -/** Conversion rules kept in one place for the deprecated activity API. */ -internal object LegacyActivityMapper { - private const val CATEGORY_FIELD = "category" - - fun request(event: ActivityEvent): ObservationRequest = ObservationRequest( - plugin = event.pluginId, - source = event.source, - message = event.type, - level = ObservationLevel.valueOf(event.severity.name), - data = event.metadata + mapOf(CATEGORY_FIELD to event.category.name), - ) - - fun query(query: ActivityQuery): ObservationQuery = ObservationQuery( - limit = query.limit, - plugin = query.pluginId, - minimumLevel = query.minimumSeverity?.let { ObservationLevel.valueOf(it.name) }, - since = query.since, - until = query.until, - ) - - fun event(observation: Observation): ActivityEvent = ActivityEvent( - eventId = observation.id, - timestamp = observation.timestamp, - type = observation.message, - category = category(observation.data[CATEGORY_FIELD]), - severity = ActivitySeverity.valueOf(observation.level.name), - source = observation.source, - pluginId = observation.plugin, - metadata = observation.data - CATEGORY_FIELD, - ) - - private fun category(value: String?): ActivityCategory { - if (value == null) return ActivityCategory.SYSTEM - return runCatchingNonFatal { ActivityCategory.valueOf(value) }.getOrDefault(ActivityCategory.SYSTEM) - } -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityHub.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityHub.kt index 0d4184263..9d55824c8 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityHub.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityHub.kt @@ -1,36 +1,25 @@ package org.pnfolder.pnlibrary.core.observability -import org.pnfolder.pnlibrary.api.activity.ActivityAttachment -import org.pnfolder.pnlibrary.api.activity.ActivityEvent -import org.pnfolder.pnlibrary.api.activity.ActivityQuery -import org.pnfolder.pnlibrary.api.activity.ActivityService -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticLevel import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticRegistration import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsContributor import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsService -import org.pnfolder.pnlibrary.api.observability.ComponentStatus -import org.pnfolder.pnlibrary.api.observability.ObservabilityReport -import org.pnfolder.pnlibrary.api.observability.ObservabilityReportRequest +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticLevel import org.pnfolder.pnlibrary.api.observability.ObservabilityService -import org.pnfolder.pnlibrary.api.observability.Observation -import org.pnfolder.pnlibrary.api.observability.ObservationQuery -import org.pnfolder.pnlibrary.api.observability.ObservationRequest +import org.pnfolder.pnlibrary.api.observability.observation.Observation +import org.pnfolder.pnlibrary.api.observability.observation.ObservationQuery +import org.pnfolder.pnlibrary.api.observability.observation.ObservationRequest +import org.pnfolder.pnlibrary.api.observability.report.ComponentStatus +import org.pnfolder.pnlibrary.api.observability.report.ObservabilityReport +import org.pnfolder.pnlibrary.api.observability.report.ObservabilityReportRequest import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticsRegistry import java.nio.file.Path -/** - * One entry point for diagnostics, observations, activity history, attachments, - * component status, and support reports. - * - * [PnLibrary.diagnostics][org.pnfolder.pnlibrary.api.runtime.PnLibrary.diagnostics], - * [PnLibrary.activity][org.pnfolder.pnlibrary.api.runtime.PnLibrary.activity] and - * [PnLibrary.observability][org.pnfolder.pnlibrary.api.runtime.PnLibrary.observability] are this one object seen - * through three interfaces. Storage and retention stay inside [ObservabilityRuntime]. - */ +// PnLibrary.diagnostics and PnLibrary.observability are this one object seen through two interfaces. +// Storage and retention stay inside ObservabilityRuntime. internal class ObservabilityHub( private val diagnostics: DiagnosticsRegistry, private val runtime: ObservabilityRuntime, -) : DiagnosticsService, ActivityService, ObservabilityService { +) : DiagnosticsService, ObservabilityService { override val apiVersion: Int get() = diagnostics.apiVersion @@ -93,53 +82,7 @@ internal class ObservabilityHub( override fun createReport(request: ObservabilityReportRequest): ObservabilityReport = runtime.createReport(request) - override fun record(event: ActivityEvent): ActivityEvent { - val observation = runtime.record(LegacyActivityMapper.request(event)) - return event.copy(eventId = observation.id, timestamp = observation.timestamp) - } - - override fun recent(query: ActivityQuery): List = - runtime.recent(LegacyActivityMapper.query(query)).map(LegacyActivityMapper::event) - - override fun attach( - eventId: String, - name: String, - contentType: String, - bytes: ByteArray, - ): ActivityAttachment = runtime.attachBytes( - observationId = eventId, - name = name, - contentType = contentType, - bytes = bytes, - ).toLegacyAttachment(eventId) - - override fun attachFile( - eventId: String, - path: Path, - contentType: String, - ): ActivityAttachment = runtime.attachFile(eventId, path).toLegacyAttachment(eventId) - - override fun exportJournal(): ByteArray = runtime.reportSnapshot().journal - - override fun exportAttachments(): Map = runtime.reportSnapshot().attachments - - override fun exportAttachmentManifest(): ByteArray = runtime.reportSnapshot().attachmentManifest - - override fun clear() { - runtime.clear() - } - override fun close() { runtime.close() } - - private fun StoredAttachment.toLegacyAttachment(eventId: String): ActivityAttachment = - ActivityAttachment( - id = id, - eventId = eventId, - name = originalName, - contentType = contentType, - size = size, - sha256 = sha256, - ) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityRuntime.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityRuntime.kt index 95259b5cf..3a65b4d19 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityRuntime.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityRuntime.kt @@ -1,25 +1,31 @@ package org.pnfolder.pnlibrary.core.observability -import org.pnfolder.pnlibrary.api.observability.ComponentStatus -import org.pnfolder.pnlibrary.api.observability.ObservabilityReport -import org.pnfolder.pnlibrary.api.observability.ObservabilityReportRequest import org.pnfolder.pnlibrary.api.observability.ObservabilityService -import org.pnfolder.pnlibrary.api.observability.Observation -import org.pnfolder.pnlibrary.api.observability.ObservationLevel -import org.pnfolder.pnlibrary.api.observability.ObservationQuery -import org.pnfolder.pnlibrary.api.observability.ObservationRequest +import org.pnfolder.pnlibrary.api.observability.observation.Observation +import org.pnfolder.pnlibrary.api.observability.observation.ObservationKeys +import org.pnfolder.pnlibrary.api.observability.observation.ObservationLevel +import org.pnfolder.pnlibrary.api.observability.observation.ObservationQuery +import org.pnfolder.pnlibrary.api.observability.observation.ObservationRequest +import org.pnfolder.pnlibrary.api.observability.report.ComponentStatus +import org.pnfolder.pnlibrary.api.observability.report.ObservabilityReport +import org.pnfolder.pnlibrary.api.observability.report.ObservabilityReportRequest +import org.pnfolder.pnlibrary.core.observability.store.AttachmentStore +import org.pnfolder.pnlibrary.core.observability.store.ComponentStatusRegistry +import org.pnfolder.pnlibrary.core.observability.store.ObservationJournal +import org.pnfolder.pnlibrary.core.observability.store.StoredAttachment +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths import java.nio.file.Path import java.time.Instant /** Records observations with their attachments and component statuses, and applies retention to them. */ internal class ObservabilityRuntime( - dataFolder: Path, + paths: LibraryPaths, private val clock: () -> Long = System::currentTimeMillis, reportFactory: ((ObservabilityReportRequest) -> ObservabilityReport)? = null, ) : ObservabilityService { private val recordLock = Any() - private val journal = ObservationJournal(dataFolder, clock) - private val attachmentStore = AttachmentStore(dataFolder) + private val journal = ObservationJournal(paths.observations, clock) + private val attachmentStore = AttachmentStore(paths.attachments) private val statusRegistry = ComponentStatusRegistry() @Volatile private var reportFactory = reportFactory @@ -35,7 +41,14 @@ internal class ObservabilityRuntime( } override fun record(request: ObservationRequest): Observation = synchronized(recordLock) { - val observation = Observation.from(request, clock()) + val timestamp = clock() + val keepFor = request.data[ObservationKeys.KEEP_FOR_MS]?.toLongOrNull() + val stored = Observation.from(request.copy(data = request.data - ObservationKeys.KEEP_FOR_MS), timestamp) + val observation = if (keepFor == null) { + stored + } else { + stored.copy(data = stored.data + (ObservationKeys.KEEP_UNTIL_MS to (timestamp + keepFor).toString())) + } request.files.forEach { file -> attachmentStore.save(observation.id, file) } journal.append(observation) observation diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationConversions.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationConversions.kt new file mode 100644 index 000000000..b26a9d276 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationConversions.kt @@ -0,0 +1,13 @@ +package org.pnfolder.pnlibrary.core.observability + +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticLevel +import org.pnfolder.pnlibrary.api.observability.observation.ObservationLevel + +internal fun DiagnosticLevel.toObservationLevel(): ObservationLevel = when (this) { + DiagnosticLevel.INFO -> ObservationLevel.INFO + DiagnosticLevel.WARNING -> ObservationLevel.WARNING + DiagnosticLevel.ERROR -> ObservationLevel.ERROR +} + +internal fun Map.toStringValues(): Map = + mapValues { (_, value) -> value?.toString() ?: "null" } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationJournal.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationJournal.kt deleted file mode 100644 index 31157b29f..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationJournal.kt +++ /dev/null @@ -1,78 +0,0 @@ -package org.pnfolder.pnlibrary.core.observability - -import com.google.gson.GsonBuilder -import org.pnfolder.pnlibrary.api.observability.Observation -import org.pnfolder.pnlibrary.common.io.TextFiles -import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import java.nio.charset.StandardCharsets -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.StandardOpenOption -import java.util.ArrayDeque - -/** Append-only JSON Lines journal of observations that keeps only what retention allows. */ -internal class ObservationJournal( - dataFolder: Path, - private val clock: () -> Long = System::currentTimeMillis, -) : AutoCloseable { - private val gson = GsonBuilder().disableHtmlEscaping().create() - private val lock = Any() - private val observations = ArrayDeque() - private val file = dataFolder.resolve("observability").resolve("observations.jsonl") - - init { - Files.createDirectories(file.parent) - load() - } - - fun append(observation: Observation) = synchronized(lock) { - observations.addLast(observation) - val retained = ObservationRetention.active(observations, clock()) - if (retained.size != observations.size) { - observations.clear() - observations.addAll(retained) - rewrite() - } else { - TextFiles.write( - file, - gson.toJson(observation) + "\n", - StandardCharsets.UTF_8, - StandardOpenOption.CREATE, - StandardOpenOption.APPEND, - ) - } - } - - fun recent(): List = synchronized(lock) { observations.toList() } - - fun clear() = synchronized(lock) { - observations.clear() - Files.deleteIfExists(file) - } - - fun applyRetention(now: Long): Set = synchronized(lock) { - val active = ObservationRetention.active(observations, now) - observations.clear() - observations.addAll(active) - rewrite() - active.mapTo(linkedSetOf()) { observation -> observation.id } - } - - private fun rewrite() { - if (observations.isEmpty()) { - Files.deleteIfExists(file) - return - } - val content = observations.joinToString(separator = "\n", postfix = "\n") { gson.toJson(it) } - TextFiles.write(file, content, StandardCharsets.UTF_8) - } - - private fun load() = synchronized(lock) { - if (!Files.isRegularFile(file)) return - Files.readAllLines(file, StandardCharsets.UTF_8) - .mapNotNull { line -> runCatchingNonFatal { gson.fromJson(line, Observation::class.java) }.getOrNull() } - .forEach(observations::addLast) - } - - override fun close() = Unit -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationRetention.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationRetention.kt deleted file mode 100644 index 4eb316b63..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationRetention.kt +++ /dev/null @@ -1,26 +0,0 @@ -package org.pnfolder.pnlibrary.core.observability - -import org.pnfolder.pnlibrary.api.observability.Observation -import org.pnfolder.pnlibrary.api.observability.ObservationLevel -import java.time.Duration - -/** How long observations of each level are kept; critical ones stay until the hard size bound. */ -internal object ObservationRetention { - fun active(observations: Collection, now: Long): List = - observations.filter { observation -> - observation.level == ObservationLevel.CRITICAL || - now - observation.timestamp <= lifetime(observation.level) - }.takeLast(MAX_OBSERVATIONS) - - /** Hard bound prevents even critical observations from growing the journal forever. */ - internal const val MAX_OBSERVATIONS = 10_000 - - private fun lifetime(level: ObservationLevel): Long = when (level) { - ObservationLevel.TRACE -> Duration.ofHours(6).toMillis() - ObservationLevel.INFO -> Duration.ofDays(7).toMillis() - ObservationLevel.NOTICE, - ObservationLevel.WARNING -> Duration.ofDays(30).toMillis() - ObservationLevel.ERROR -> Duration.ofDays(90).toMillis() - ObservationLevel.CRITICAL -> Long.MAX_VALUE - } -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/SupportRuntime.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/SupportRuntime.kt index f9508349e..79ede89a9 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/SupportRuntime.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/SupportRuntime.kt @@ -1,13 +1,15 @@ package org.pnfolder.pnlibrary.core.observability -import org.pnfolder.pnlibrary.api.activity.ActivityCategory -import org.pnfolder.pnlibrary.api.activity.ActivitySeverity import org.pnfolder.pnlibrary.api.diagnostics.DebugRequest -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticReport +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticLevel +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticReport import org.pnfolder.pnlibrary.api.logging.LogLevel -import org.pnfolder.pnlibrary.api.observability.ObservabilityReport -import org.pnfolder.pnlibrary.api.observability.ObservabilityReportRequest +import org.pnfolder.pnlibrary.api.observability.observation.ObservationLevel +import org.pnfolder.pnlibrary.api.observability.observation.ObservationRequest +import org.pnfolder.pnlibrary.api.observability.report.ObservabilityReport +import org.pnfolder.pnlibrary.api.observability.report.ObservabilityReportRequest import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig +import org.pnfolder.pnlibrary.common.concurrent.FailureThrottle import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticsRegistry import org.pnfolder.pnlibrary.core.logging.DiagnosticCapture @@ -15,15 +17,15 @@ import org.pnfolder.pnlibrary.core.logging.DiagnosticLogBuffer import org.pnfolder.pnlibrary.core.observability.history.IncidentHistoryStore import org.pnfolder.pnlibrary.core.observability.report.SupportDeliveryFactory import org.pnfolder.pnlibrary.core.observability.report.SupportReportGenerator -import org.pnfolder.pnlibrary.core.observability.reportSnapshot +import org.pnfolder.pnlibrary.core.observability.report.reportSnapshot import org.pnfolder.pnlibrary.core.upload.UploadLedger import org.pnfolder.pnlibrary.spi.platform.PlatformDiagnostics import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import org.pnfolder.pnlibrary.spi.platform.PlatformLogObservation import org.pnfolder.pnlibrary.spi.platform.PlatformLogging import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths import java.nio.file.Files -import java.nio.file.Path import java.time.Instant import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.Executors @@ -42,22 +44,22 @@ internal class SupportRuntime( private val platformLogging: PlatformLogging, private val diagnostics: DiagnosticsRegistry, private val config: PnLibraryConfig, - dataFolder: Path, + paths: LibraryPaths, private val runtimeDiagnostics: () -> Map = { emptyMap() }, - private val journal: ((Any, LogLevel, String, Throwable?) -> Unit)? = null, + private val journal: ((Any, LogLevel, String, Throwable?, Map) -> Unit)? = null, private val onRuntimeError: (Any, Throwable) -> Unit = { _, _ -> }, ) : AutoCloseable { - private val observations = ObservabilityRuntime(dataFolder) - private val diagnosticBridge = DiagnosticObservationBridge(observations) + private val observations = ObservabilityRuntime(paths) val service = ObservabilityHub(diagnostics, observations) val logs = DiagnosticLogBuffer(config.logRecords.coerceIn(10, 2_000)) val capture = DiagnosticCapture(ownership, platformLogging, logs, journal) { logOwner, message, error -> service.record( - type = "RUNTIME_ERROR", - category = ActivityCategory.ERROR, - severity = ActivitySeverity.ERROR, - source = logOwner.javaClass.name, - metadata = mapOf("message" to message.take(512), "exception" to error.javaClass.name), + ObservationRequest( + source = logOwner.javaClass.name, + message = "RUNTIME_ERROR", + level = ObservationLevel.ERROR, + data = mapOf("message" to message.take(512), "exception" to error.javaClass.name), + ), ) onRuntimeError(logOwner, error) } @@ -65,17 +67,18 @@ internal class SupportRuntime( fun logSummary(): Map = logs.summary() private val delivery = SupportDeliveryFactory(config) - private val uploadLedger = UploadLedger(dataFolder.resolve("upload-ledger.json")) + private val uploadLedger = UploadLedger(paths.uploadLedger) private val encryption = delivery.encryptionCodec() private val history = IncidentHistoryStore( - directory = dataFolder.resolve("diagnostics/history"), + directory = paths.diagnosticsHistory, codec = encryption, retentionDays = config.historyRetentionDays, maxBytes = config.historyMaxBytes.toLong(), ) private val uploader = delivery.uploader() private val reports = SupportReportGenerator( - dataFolder = dataFolder, + dataFolder = paths.pluginFolder, + reportsFolder = paths.reports, config = config, diagnosticsRegistry = diagnostics, platformIdentity = identity, @@ -89,6 +92,7 @@ internal class SupportRuntime( runtimeDiagnostics = runtimeDiagnostics, ) private val persistRequested = AtomicBoolean(false) + private val internalFailures = FailureThrottle() private val reportInProgress = AtomicBoolean(false) private val reportsCreated = AtomicLong() private val reportsFailed = AtomicLong() @@ -103,10 +107,11 @@ internal class SupportRuntime( } fun initialize(isRuntimeClosed: () -> Boolean) { + diagnostics.onInternalFailure = ::reportInternalFailure observations.configureReportFactory(::createObservabilityReport) logs.onChange { persistHistory() } diagnostics.onEventsChanged(::persistHistory) - diagnostics.onActivityEvent(diagnosticBridge::record) + diagnostics.onActivityEvent(::recordDiagnostic) platformLogObservation.observeNativeLogs { nativeOwner, level, message, error -> if (config.journalForeignPlugins || nativeOwner === owner) capture.observe(nativeOwner, level, message, error) else capture.observeWithoutJournal(nativeOwner, level, message, error) @@ -197,7 +202,7 @@ internal class SupportRuntime( diagnostics.onEventsChanged(null) diagnostics.onActivityEvent(null) worker.shutdownNow() - if (persistRequested.getAndSet(false)) runCatchingNonFatal { writeHistory() } + if (persistRequested.getAndSet(false)) saveHistory() diagnostics.clear() service.close() } @@ -210,7 +215,7 @@ internal class SupportRuntime( if (!persistRequested.compareAndSet(false, true)) return try { worker.schedule( - { if (persistRequested.getAndSet(false)) runCatchingNonFatal { writeHistory() } }, + { if (persistRequested.getAndSet(false)) saveHistory() }, HISTORY_FLUSH_DELAY_MS, TimeUnit.MILLISECONDS, ) @@ -219,12 +224,44 @@ internal class SupportRuntime( } } + /** Turns one diagnostic incident into one observation. */ + private fun recordDiagnostic( + plugin: String, + level: DiagnosticLevel, + component: String, + code: String, + message: String, + error: Throwable?, + fields: Map, + ) { + observations.record( + ObservationRequest( + plugin = plugin, + source = component, + message = message, + level = level.toObservationLevel(), + data = fields.toStringValues() + mapOf("code" to code, "hasException" to (error != null).toString()), + error = error, + ), + ) + } + /** Logs a failed background job; a periodic task must not throw, or the executor cancels it. */ + /** Console only: recording it would raise another diagnostic event and run the failing callback again. */ + private fun reportInternalFailure(what: String, error: Throwable) { + if (!internalFailures.shouldReport("$what|${error.javaClass.name}")) return + capture.write(this, LogLevel.WARNING, what, error, record = false) + } + private fun warnBackgroundFailure(job: String): (Throwable) -> Unit = { error -> capture.log(this, LogLevel.WARNING, "$job failed", error) } - // History writes stay silent: logging their failure would record a new incident and request another write. + /** A failed write is shown on the console only: recording it would add an incident and request another write. */ + private fun saveHistory() { + runCatchingNonFatal { writeHistory() }.onFailure { reportInternalFailure("Diagnostic history could not be saved", it) } + } + private fun writeHistory() { history.save(logs.snapshot(), diagnostics.eventSnapshot()) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/history/IncidentHistoryStore.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/history/IncidentHistoryStore.kt index 161511790..71ff8ee09 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/history/IncidentHistoryStore.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/history/IncidentHistoryStore.kt @@ -2,7 +2,7 @@ package org.pnfolder.pnlibrary.core.observability.history import com.google.gson.Gson import org.pnfolder.pnlibrary.common.io.AtomicFiles -import org.pnfolder.pnlibrary.core.security.EncryptedEnvelopeCodec +import org.pnfolder.pnlibrary.core.observability.report.EncryptedEnvelopeCodec import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/security/EncryptedEnvelopeCodec.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/EncryptedEnvelopeCodec.kt similarity index 99% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/security/EncryptedEnvelopeCodec.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/EncryptedEnvelopeCodec.kt index c44de1ebb..23404b222 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/security/EncryptedEnvelopeCodec.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/EncryptedEnvelopeCodec.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.security +package org.pnfolder.pnlibrary.core.observability.report import com.google.gson.Gson import java.io.ByteArrayOutputStream diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityReportSnapshot.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/ObservabilityReportSnapshot.kt similarity index 63% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityReportSnapshot.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/ObservabilityReportSnapshot.kt index 0350d1f53..423cfa0fa 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityReportSnapshot.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/ObservabilityReportSnapshot.kt @@ -1,8 +1,13 @@ -package org.pnfolder.pnlibrary.core.observability +package org.pnfolder.pnlibrary.core.observability.report import com.google.gson.GsonBuilder -import org.pnfolder.pnlibrary.api.observability.ObservationQuery +import org.pnfolder.pnlibrary.api.observability.observation.Observation +import org.pnfolder.pnlibrary.api.observability.observation.ObservationKeys +import org.pnfolder.pnlibrary.api.observability.observation.ObservationQuery +import org.pnfolder.pnlibrary.core.observability.ObservabilityRuntime +import org.pnfolder.pnlibrary.core.observability.store.StoredAttachment import java.nio.charset.StandardCharsets +import java.time.Instant /** Observation journal, attachments, statuses and analytics captured for one support report. */ internal data class ObservabilityReportSnapshot( @@ -17,7 +22,7 @@ internal fun ObservabilityRuntime.reportSnapshot(): ObservabilityReportSnapshot val gson = GsonBuilder().disableHtmlEscaping().create() val observations = recent(ObservationQuery(limit = Int.MAX_VALUE)) val journal = observations - .joinToString(separator = "\n", postfix = "\n") { gson.toJson(it) } + .joinToString(separator = "\n", postfix = "\n") { gson.toJson(it.reportLine()) } .toByteArray(StandardCharsets.UTF_8) val storedAttachments = allAttachments() @@ -52,3 +57,18 @@ private fun StoredAttachment.manifestEntry(): Map = linkedMapOf( "size" to size, "sha256" to sha256, ) + +/** The stored observation with readable UTC times, so support sees when it happened and when it expires. */ +internal fun Observation.reportLine(): Map = linkedMapOf( + "id" to id, + "timestamp" to timestamp, + "timeUtc" to Instant.ofEpochMilli(timestamp).toString(), + "expiresUtc" to data[ObservationKeys.KEEP_UNTIL_MS]?.toLongOrNull()?.let(Instant::ofEpochMilli)?.toString(), + "plugin" to plugin, + "source" to source, + "level" to level, + "message" to message, + "data" to data - ObservationKeys.KEEP_UNTIL_MS, + "errorType" to errorType, + "errorMessage" to errorMessage, +) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportArchiveBuilder.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportArchiveBuilder.kt index f091ce24c..753f46bb6 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportArchiveBuilder.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportArchiveBuilder.kt @@ -8,15 +8,7 @@ import java.nio.charset.StandardCharsets import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream -/** - * Builds the deterministic ZIP layout encrypted inside a `.pnsupport` container. - * - * Entry paths are relative and traversal-safe. Content is copied at insertion, - * the uncompressed byte budget is enforced before ZIP compression, and [build] - * does not mutate builder state, so repeated builds produce equivalent archives. - * - * @param maximumUncompressedBytes total payload budget before ZIP compression - */ +// Content is copied at insertion and build() does not mutate state, so repeated builds are equivalent. internal class SupportArchiveBuilder( private val maximumUncompressedBytes: Long = Long.MAX_VALUE, ) { @@ -32,12 +24,6 @@ internal class SupportArchiveBuilder( fun text(path: String, value: String) = bytes(path, value.toByteArray(StandardCharsets.UTF_8)) - /** - * Adds or replaces one archive entry using a defensive copy of [value]. - * - * @throws IllegalArgumentException for an empty/traversing path or if the new - * aggregate payload exceeds the configured uncompressed byte budget - */ fun bytes(path: String, value: ByteArray) { val safe = path.replace('\\', '/').trimStart('/').also { require(it.isNotBlank() && ".." !in it.split('/')) { "Invalid diagnostic archive path: $path" } @@ -51,7 +37,6 @@ internal class SupportArchiveBuilder( payloadBytes = nextSize } - /** Creates a ZIP containing all entries and an SHA-256 checksum manifest. */ fun build(): ByteArray { val checksums = entries.mapValues { (_, bytes) -> Digests.sha256(bytes) } val archiveEntries = entries + mapOf( diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportDeliveryFactory.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportDeliveryFactory.kt index 8e722daf6..a509f7cf0 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportDeliveryFactory.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportDeliveryFactory.kt @@ -1,7 +1,7 @@ package org.pnfolder.pnlibrary.core.observability.report import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig -import org.pnfolder.pnlibrary.core.security.EncryptedEnvelopeCodec +import org.pnfolder.pnlibrary.core.observability.report.EncryptedEnvelopeCodec import org.pnfolder.pnlibrary.core.upload.CatboxUploader import org.pnfolder.pnlibrary.core.upload.EncryptedReportUploader import org.pnfolder.pnlibrary.core.upload.FileIoUploader diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportAssembler.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportAssembler.kt index 474f137b2..7aea0d99f 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportAssembler.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportAssembler.kt @@ -3,9 +3,9 @@ package org.pnfolder.pnlibrary.core.observability.report import org.pnfolder.pnlibrary.api.diagnostics.DebugRequest import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.core.diagnostics.ConfigReader import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticsRegistry -import org.pnfolder.pnlibrary.core.observability.ObservabilityReportSnapshot +import org.pnfolder.pnlibrary.core.diagnostics.config.ConfigReader +import org.pnfolder.pnlibrary.core.observability.report.ObservabilityReportSnapshot import org.pnfolder.pnlibrary.spi.platform.PlatformDiagnosticReport import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import java.nio.file.Path @@ -130,12 +130,13 @@ internal class SupportReportAssembler( target: String, encrypted: Boolean, ) { + val used = mutableSetOf() diagnostics.configurations(target).forEach { registered -> val root = registered.dataDirectory ?: dataFolder val directory = "plugins/${safePath(registered.plugin)}/configuration/" if (encrypted) { val file = configurations.readProtectedFile(registered.configuration, root) - val path = safeConfigurationPath(file.path) + val path = unique(directory, safeConfigurationPath(file.path), used) if (file.error == null) { archive.bytes(directory + path, requireNotNull(file.content)) } else { @@ -143,7 +144,7 @@ internal class SupportReportAssembler( } } else { val file = configurations.readRedactedFile(registered.configuration, root) - val path = safeConfigurationPath(file.path) + val path = unique(directory, safeConfigurationPath(file.path), used) if (file.error == null) { archive.text(directory + path, file.content) } else { @@ -153,6 +154,15 @@ internal class SupportReportAssembler( } } + /** Two names that differ only in replaced characters get `-2`, `-3`, ... before the extension so neither overwrites the other. */ + private fun unique(directory: String, path: String, used: MutableSet): String { + val dot = path.lastIndexOf('.').takeIf { it > path.lastIndexOf('/') + 1 } ?: path.length + var candidate = path + var number = 2 + while (!used.add((directory + candidate).lowercase())) candidate = path.substring(0, dot) + "-" + number++ + path.substring(dot) + return candidate + } + private fun safePath(value: String): String = value .lowercase() .replace(Regex("[^a-z0-9._-]+"), "-") diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportGenerator.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportGenerator.kt index 3a06a378c..f10d03dfd 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportGenerator.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportGenerator.kt @@ -1,11 +1,11 @@ package org.pnfolder.pnlibrary.core.observability.report import org.pnfolder.pnlibrary.api.diagnostics.DebugRequest -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticReport +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticReport import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticsRegistry -import org.pnfolder.pnlibrary.core.observability.ObservabilityReportSnapshot -import org.pnfolder.pnlibrary.core.security.EncryptedEnvelopeCodec +import org.pnfolder.pnlibrary.core.observability.report.EncryptedEnvelopeCodec +import org.pnfolder.pnlibrary.core.observability.report.ObservabilityReportSnapshot import org.pnfolder.pnlibrary.core.upload.UploadLedger import org.pnfolder.pnlibrary.core.upload.UploadProvider import org.pnfolder.pnlibrary.core.upload.UploadReceipt @@ -26,7 +26,8 @@ import java.nio.file.Path * failures are instead returned in [DiagnosticReport.uploadError], preserving the * successfully written local report for manual support workflows. * - * @param dataFolder runtime data root and parent of the `reports` directory + * @param dataFolder plugin data folder, the default root for configuration files + * @param reportsFolder where the generated reports are stored * @param config immutable diagnostic and upload policy * @param diagnosticsRegistry source of plugin snapshots and configuration declarations * @param encryptionCodec envelope codec required in encrypted mode @@ -37,6 +38,7 @@ import java.nio.file.Path */ internal class SupportReportGenerator( private val dataFolder: Path, + reportsFolder: Path, private val config: PnLibraryConfig, diagnosticsRegistry: DiagnosticsRegistry, platformIdentity: PlatformIdentity, @@ -63,7 +65,7 @@ internal class SupportReportGenerator( observabilitySnapshot = observabilitySnapshot, runtimeDiagnostics = runtimeDiagnostics, ) - private val reportStore = SupportReportStore(dataFolder.resolve("reports")) + private val reportStore = SupportReportStore(reportsFolder) /** * Generates one report according to [request], stores it locally, and optionally diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/AttachmentStore.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/store/AttachmentStore.kt similarity index 96% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/AttachmentStore.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/store/AttachmentStore.kt index 4353fc86e..ee6eafe03 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/AttachmentStore.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/store/AttachmentStore.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.observability +package org.pnfolder.pnlibrary.core.observability.store import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken @@ -21,9 +21,8 @@ internal data class StoredAttachment( ) /** Stores observation attachments on disk with a manifest, refusing executable and unsafe files. */ -internal class AttachmentStore(dataFolder: Path) { +internal class AttachmentStore(private val directory: Path) { private val gson = GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create() - private val directory = dataFolder.resolve("observability").resolve("attachments") private val manifest = directory.resolve("manifest.json") private val attachments = linkedMapOf() diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ComponentStatusRegistry.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/store/ComponentStatusRegistry.kt similarity index 81% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ComponentStatusRegistry.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/store/ComponentStatusRegistry.kt index df9c83a97..8c47f7c8a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/ComponentStatusRegistry.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/store/ComponentStatusRegistry.kt @@ -1,6 +1,6 @@ -package org.pnfolder.pnlibrary.core.observability +package org.pnfolder.pnlibrary.core.observability.store -import org.pnfolder.pnlibrary.api.observability.ComponentStatus +import org.pnfolder.pnlibrary.api.observability.report.ComponentStatus /** Latest reported status of every plugin component. */ internal class ComponentStatusRegistry { diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/store/ObservationJournal.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/store/ObservationJournal.kt new file mode 100644 index 000000000..f563055bc --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/store/ObservationJournal.kt @@ -0,0 +1,107 @@ +package org.pnfolder.pnlibrary.core.observability.store + +import com.google.gson.GsonBuilder +import org.pnfolder.pnlibrary.api.observability.observation.Observation +import org.pnfolder.pnlibrary.common.io.TextFiles +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import java.io.Writer +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardOpenOption +import java.util.ArrayDeque + +/** + * Append-only JSON Lines journal of observations that keeps only what retention allows. + * + * Expired observations are cut from the file once a minute or when the list outgrows its bound by a margin, + * not on every append; [recent] never shows an expired one meanwhile. + * + * @param retain keeps the observations that are still active at a time; replaceable so tests can count its use + */ +internal class ObservationJournal( + private val file: Path, + private val clock: () -> Long = System::currentTimeMillis, + private val retain: (Collection, Long) -> List = Collection::retained, +) : AutoCloseable { + private val gson = GsonBuilder().disableHtmlEscaping().create() + private val lock = Any() + private val observations = ArrayDeque() + private var writer: Writer? = null + private var lastRetentionAt: Long? = null + + init { + Files.createDirectories(file.parent) + load() + } + + fun append(observation: Observation) = synchronized(lock) { + observations.addLast(observation) + val out = writer ?: Files.newBufferedWriter(file, StandardCharsets.UTF_8, + StandardOpenOption.CREATE, StandardOpenOption.APPEND).also { writer = it } + out.write(gson.toJson(observation)) + out.write("\n") + out.flush() + val now = clock() + val last = lastRetentionAt + if (observations.size > MAX_OBSERVATIONS + OVERFLOW_MARGIN || + last == null || now - last >= RETENTION_INTERVAL_MILLIS || now < last + ) { + lastRetentionAt = now + val active = retain(observations, now) + if (active.size != observations.size) replaceAndRewrite(active) + } + } + + fun recent(): List = synchronized(lock) { retain(observations, clock()) } + + fun clear() = synchronized(lock) { + closeWriter() + observations.clear() + Files.deleteIfExists(file) + } + + fun applyRetention(now: Long): Set = synchronized(lock) { + val active = retain(observations, now) + replaceAndRewrite(active) + active.mapTo(linkedSetOf()) { observation -> observation.id } + } + + private fun replaceAndRewrite(active: List) { + observations.clear() + observations.addAll(active) + rewrite() + } + + private fun rewrite() { + closeWriter() + if (observations.isEmpty()) { + Files.deleteIfExists(file) + return + } + val content = observations.joinToString(separator = "\n", postfix = "\n") { gson.toJson(it) } + TextFiles.write(file, content, StandardCharsets.UTF_8) + } + + private fun load() = synchronized(lock) { + if (!Files.isRegularFile(file)) return + Files.readAllLines(file, StandardCharsets.UTF_8) + .mapNotNull { line -> runCatchingNonFatal { gson.fromJson(line, Observation::class.java) }.getOrNull() } + .forEach(observations::addLast) + } + + private fun closeWriter() { + val open = writer ?: return + writer = null + open.close() + } + + override fun close() = synchronized(lock) { closeWriter() } + + private companion object { + const val RETENTION_INTERVAL_MILLIS = 60_000L + + /** How far past the bound the list may grow before it is cut at once, so a full journal is not rewritten per append. */ + const val OVERFLOW_MARGIN = 500 + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/store/ObservationRetention.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/store/ObservationRetention.kt new file mode 100644 index 000000000..366fe2078 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/observability/store/ObservationRetention.kt @@ -0,0 +1,29 @@ +package org.pnfolder.pnlibrary.core.observability.store + +import org.pnfolder.pnlibrary.api.observability.observation.Observation +import org.pnfolder.pnlibrary.api.observability.observation.ObservationKeys +import org.pnfolder.pnlibrary.api.observability.observation.ObservationLevel +import java.time.Duration + +/** Hard bound prevents even critical observations from growing the journal forever. */ +internal const val MAX_OBSERVATIONS = 10_000 + +/** The observations still worth keeping at [now]: how long each level lives, critical ones until the hard size bound. */ +internal fun Collection.retained(now: Long): List = + filter { observation -> observation.isActive(now) }.takeLast(MAX_OBSERVATIONS) + +/** The author's period, when set, replaces the level's default in both directions. */ +private fun Observation.isActive(now: Long): Boolean { + val keepUntil = data[ObservationKeys.KEEP_UNTIL_MS]?.toLongOrNull() + if (keepUntil != null) return now <= keepUntil + return level == ObservationLevel.CRITICAL || now - timestamp <= level.lifetime() +} + +private fun ObservationLevel.lifetime(): Long = when (this) { + ObservationLevel.TRACE -> Duration.ofHours(6).toMillis() + ObservationLevel.INFO -> Duration.ofDays(7).toMillis() + ObservationLevel.NOTICE, + ObservationLevel.WARNING -> Duration.ofDays(30).toMillis() + ObservationLevel.ERROR -> Duration.ofDays(90).toMillis() + ObservationLevel.CRITICAL -> Long.MAX_VALUE +} diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderDefinitionBuilder.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderDefinitionBuilder.kt similarity index 76% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderDefinitionBuilder.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderDefinitionBuilder.kt index e1c495022..d67fc9f2f 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderDefinitionBuilder.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderDefinitionBuilder.kt @@ -1,18 +1,20 @@ package org.pnfolder.pnlibrary.core.placeholders -import org.pnfolder.pnlibrary.api.placeholders.AsyncPlaceholderResolver -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAccess -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapter import org.pnfolder.pnlibrary.api.placeholders.PlaceholderBuilder -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderCachePolicy import org.pnfolder.pnlibrary.api.placeholders.PlaceholderFormatter -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderKey -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderPublication import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRegistration -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRequest -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderResolver import org.pnfolder.pnlibrary.api.placeholders.PlaceholderUpdater +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapter +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderCachePolicy +import org.pnfolder.pnlibrary.api.placeholders.model.AsyncPlaceholderResolver +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderPublication +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderResolver +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderEntry +import org.pnfolder.pnlibrary.core.placeholders.formatters.PlaceholderFormatterRegistry import java.util.Locale import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage @@ -33,8 +35,8 @@ class PlaceholderDefinitionBuilder( private var defaultFormat: String? = null private var resolver: ((PlaceholderRequest) -> CompletionStage)? = null private var updater: PlaceholderUpdater? = null - private var access = PlaceholderAccess.ownerOnly() - private var updateAccess = PlaceholderAccess.ownerOnly() + private var access = PluginAccess.ownerOnly() + private var updateAccess = PluginAccess.ownerOnly() private var cachePolicy = PlaceholderCachePolicy.none() private var fallback: T? = null private val publications = mutableListOf() @@ -49,11 +51,11 @@ class PlaceholderDefinitionBuilder( } override fun update(updater: PlaceholderUpdater) = apply { this.updater = updater } - override fun updateAccess(access: PlaceholderAccess) = apply { this.updateAccess = access } - override fun access(access: PlaceholderAccess) = apply { this.access = access } + override fun updateAccess(access: PluginAccess) = apply { this.updateAccess = access } + override fun access(access: PluginAccess) = apply { this.access = access } - override fun access(configure: Consumer) = apply { - access = PlaceholderAccess.builder().also(configure::accept).build() + override fun access(configure: Consumer) = apply { + access = PluginAccess.builder().also(configure::accept).build() } override fun cache(policy: PlaceholderCachePolicy) = apply { cachePolicy = policy } @@ -72,6 +74,7 @@ class PlaceholderDefinitionBuilder( } } + /** Registers the placeholder with the hub; fails when it has no resolver or its address is taken. */ fun install(): PlaceholderRegistration { val entry = PlaceholderEntry( owner = owner, diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderHub.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderHub.kt similarity index 83% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderHub.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderHub.kt index 8e919ba79..387522937 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderHub.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderHub.kt @@ -1,18 +1,28 @@ package org.pnfolder.pnlibrary.core.placeholders -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapter -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterRegistry -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterState import org.pnfolder.pnlibrary.api.placeholders.PlaceholderBuilder import org.pnfolder.pnlibrary.api.placeholders.PlaceholderFormatter -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderKey import org.pnfolder.pnlibrary.api.placeholders.PlaceholderProvider import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRegistration -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRequest import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapter +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapterState +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderAdapterRegistry +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.core.placeholders.builtin.BuiltInPlaceholders +import org.pnfolder.pnlibrary.core.placeholders.builtin.GlobalPlaceholderValueStore +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderAddress +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderAddressIndex +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderEntries +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderEntry +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderEntryLookup +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderInfo +import org.pnfolder.pnlibrary.core.placeholders.formatters.PlaceholderFormatterRegistry +import org.pnfolder.pnlibrary.core.placeholders.formatters.PlaceholderTemplateRenderer import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import java.util.Collections import java.util.Locale @@ -33,10 +43,12 @@ import java.util.function.Consumer class PlaceholderHub( private val platform: PlatformIdentity, private val valueStore: GlobalPlaceholderValueStore = GlobalPlaceholderValueStore(), + /** Receives the text and the exception of every unexpected failure while resolving; each distinct text once. */ + private val failures: (String, Throwable) -> Unit = { _, _ -> }, /** Receives the text of every problem worth the administrator's attention; each distinct one once. */ private val issues: (String) -> Unit = {}, ) : PlaceholderAdapterRegistry { - private val entries = ConcurrentHashMap>() + private val entries = PlaceholderEntries() private val adapters = ConcurrentHashMap() private val formatterRegistry = PlaceholderFormatterRegistry() private val entryLookup = PlaceholderEntryLookup(entries, PluginId.of(SYSTEM_NAMESPACE)) @@ -64,6 +76,11 @@ class PlaceholderHub( if (reported.size < MAXIMUM_REPORTED && reported.add(message)) issues(message) } + /** Like [report], for a failure that carries its exception. */ + private fun reportFailure(message: String, error: Throwable) { + if (reported.size < MAXIMUM_REPORTED && reported.add(message)) failures(message, error) + } + private fun find(consumer: PluginId, reference: String): PlaceholderEntryLookup.Match { PlaceholderAddress.parse(reference)?.let { return addresses.find(it) } if (reference.contains('/')) return PlaceholderEntryLookup.Match(null, emptyMap()) @@ -149,7 +166,7 @@ class PlaceholderHub( synchronized(mutationLock) { check(!closed.get()) { "Placeholder scope $owner is closed" } val full = id(owner, key.value) - require(entries.putIfAbsent(full, entry) == null) { "Placeholder $full is already registered" } + require(entries.add(full, entry)) { "Placeholder $full is already registered" } owned += full val address = plugin?.let { PlaceholderAddress.of(it, module, key.value) } if (address != null && !addresses.add(address, entry)) { @@ -214,15 +231,7 @@ class PlaceholderHub( values[reference]?.let { return CompletableFuture.completedFuture(format(consumer, it, pieces.drop(1), playerId, values)) } val (entry, params) = find(consumer, reference) if (entry == null) { - val external = adapters.values.asSequence() - .filter { adapter -> - adapter.state == PlaceholderAdapterState.AVAILABLE || - adapter.state == PlaceholderAdapterState.REGISTERED - } - .mapNotNull { adapter -> - runCatchingNonFatal { adapter.resolve(playerId, reference) }.getOrNull() - } - .firstOrNull() + val external = resolveExternally(playerId, reference) if (external == null) report("Placeholder {$reference} is not registered (asked by $consumer)") return CompletableFuture.completedFuture(external) } @@ -236,11 +245,21 @@ class PlaceholderHub( return (entry as PlaceholderEntry).resolve(request) .thenApply { format(consumer, it, pipeline, playerId, values, request, entry.formats) } .exceptionally { error -> - report("Placeholder {$reference} failed: ${error.cause?.message ?: error.message}") + reportFailure("Placeholder {$reference} failed: ${error.cause?.message ?: error.message}", error.cause ?: error) null } } + private fun resolveExternally(playerId: UUID?, reference: String): Any? = + adapters.values.asSequence() + .filter { it.state == PlaceholderAdapterState.AVAILABLE || it.state == PlaceholderAdapterState.REGISTERED } + .mapNotNull { adapter -> + runCatchingNonFatal { adapter.resolve(playerId, reference) } + .onFailure { reportFailure("Placeholder {$reference} failed in an outside placeholder system: ${it.message}", it) } + .getOrNull() + } + .firstOrNull() + private fun updateFor( consumer: PluginId, expression: String, @@ -262,9 +281,13 @@ class PlaceholderHub( } /** Lets every available outside system (PlaceholderAPI) replace what is left of its own tokens. */ - private fun renderExternal(text: String, playerId: UUID?): String = adapters.values + private fun renderExternal(text: String, playerId: UUID?): String = if ('%' !in text) text else adapters.values .filter { it.state == PlaceholderAdapterState.AVAILABLE || it.state == PlaceholderAdapterState.REGISTERED } - .fold(text) { current, adapter -> runCatchingNonFatal { adapter.render(playerId, current) }.getOrDefault(current) } + .fold(text) { current, adapter -> + runCatchingNonFatal { adapter.render(playerId, current) } + .onFailure { reportFailure("An outside placeholder system failed to render text: ${it.message}", it) } + .getOrDefault(current) + } private fun templateRenderer(consumer: PluginId) = PlaceholderTemplateRenderer( resolve = { expression, playerId, values -> resolveFor(consumer, expression, playerId, values).exceptionally { null } }, diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPublicationBinding.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPublicationBinding.kt similarity index 75% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPublicationBinding.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPublicationBinding.kt index 4c411d640..26f0cdb93 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPublicationBinding.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPublicationBinding.kt @@ -1,10 +1,10 @@ package org.pnfolder.pnlibrary.core.placeholders -import org.pnfolder.pnlibrary.api.placeholders.ExternalPlaceholderRegistration -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapter -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterState -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderPublication -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderResolver +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapter +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapterState +import org.pnfolder.pnlibrary.api.placeholders.model.ExternalPlaceholderRegistration +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderPublication +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderResolver import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import java.util.Locale @@ -34,6 +34,7 @@ class PlaceholderPublicationBinding( else -> delegate?.state ?: PlaceholderAdapterState.UNAVAILABLE } + /** Publishes through [adapter] when it is the one this binding waits for; a failure marks the binding as failed. */ @Synchronized fun attach(adapter: PlaceholderAdapter) { if (closed.get() || adapter.id.lowercase(Locale.ROOT) != adapterId) return @@ -45,6 +46,7 @@ class PlaceholderPublicationBinding( .onFailure { publicationFailed = true } } + /** Withdraws the publication and clears a failure so the next adapter gets a fresh try. */ @Synchronized fun detach() { closeDelegate() diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholdersCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholdersCommand.kt similarity index 89% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholdersCommand.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholdersCommand.kt index 0f22b4578..37cb91e96 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholdersCommand.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholdersCommand.kt @@ -1,13 +1,14 @@ package org.pnfolder.pnlibrary.core.placeholders import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.commands.ArgumentType +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command import org.pnfolder.pnlibrary.api.plugin.PluginId +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderInfo import java.util.UUID import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException @@ -44,6 +45,7 @@ private fun list(hub: PlaceholderHub, context: CommandContext, requested: Int) { context.sender.send(Component.text("Проверить: /pn placeholders test <адрес> [uuid игрока]", ChatPalette.FAINT)) } +/** One line of the placeholder list. */ fun row(info: PlaceholderInfo): Component { val color = if (info.enabled) ChatPalette.TEXT else ChatPalette.FAINT val format = info.format?.let { " |$it" }.orEmpty() diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/BuiltInPlaceholders.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/BuiltInPlaceholders.kt similarity index 69% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/BuiltInPlaceholders.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/BuiltInPlaceholders.kt index 069f11174..0ba712609 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/BuiltInPlaceholders.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/BuiltInPlaceholders.kt @@ -1,25 +1,29 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.builtin -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAccess -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapter -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderCachePolicy -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderKey -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderPublication +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapter +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderCachePolicy +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderPublication +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderAddress +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderAddressIndex +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderEntries +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderEntry import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import java.util.Locale import java.util.concurrent.CompletableFuture -import java.util.concurrent.ConcurrentHashMap /** The placeholders of the library itself, `pnlibrary/main:*`, readable by every plugin. */ class BuiltInPlaceholders( - private val entries: ConcurrentHashMap>, + private val entries: PlaceholderEntries, private val addresses: PlaceholderAddressIndex, private val adapterLookup: (String) -> PlaceholderAdapter?, ) { private val owner = PluginId.of(PnLibraryIdentity.PRODUCT_ID) + /** Registers the server and runtime placeholders and the `defaultValue` command. */ fun registerAll(platform: PlatformIdentity, valueStore: GlobalPlaceholderValueStore) { add("server.platform", String::class.java) { platform.type.displayName } add("server.implementation", String::class.java) { platform.implementationName } @@ -28,6 +32,7 @@ class BuiltInPlaceholders( registerDefaultValueCommand(valueStore) } + /** Registers one read-only library placeholder, [key], whose value comes from [value] on every read. */ fun add(key: String, type: Class, value: () -> T) { val typedKey = PlaceholderKey.of(key, type) val entry = PlaceholderEntry( @@ -35,8 +40,8 @@ class BuiltInPlaceholders( key = typedKey, resolver = { CompletableFuture.completedFuture(value()) }, updater = null, - access = PlaceholderAccess.shared(), - updateAccess = PlaceholderAccess.ownerOnly(), + access = PluginAccess.shared(), + updateAccess = PluginAccess.ownerOnly(), cachePolicy = PlaceholderCachePolicy.none(), fallback = null, adapterLookup = adapterLookup, @@ -55,8 +60,8 @@ class BuiltInPlaceholders( CompletableFuture.completedFuture(commands.resolve(request.parameters["value"].orEmpty(), request.playerId)) }, null, - PlaceholderAccess.shared(), - PlaceholderAccess.ownerOnly(), + PluginAccess.shared(), + PluginAccess.ownerOnly(), cachePolicy = PlaceholderCachePolicy.none(), fallback = null, adapterLookup = adapterLookup, diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/DefaultValueCommandResolver.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/DefaultValueCommandResolver.kt similarity index 89% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/DefaultValueCommandResolver.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/DefaultValueCommandResolver.kt index 71bacf331..43b38f224 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/DefaultValueCommandResolver.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/DefaultValueCommandResolver.kt @@ -1,10 +1,11 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.builtin -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderValueScope +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderValueScope import java.util.UUID /** Parses the bracket-delimited `defaultValue_*` command surface published to PlaceholderAPI. */ class DefaultValueCommandResolver(private val store: GlobalPlaceholderValueStore) { + /** Runs the command (for example `set_[name]_[value]`) and returns its text, or null when it is malformed or unknown. */ fun resolve(command: String, playerId: UUID?): String? { val operation = command.substringBefore('_').lowercase() val arguments = command.substringAfter('_', "") diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/GlobalPlaceholderValueStore.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/GlobalPlaceholderValueStore.kt similarity index 93% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/GlobalPlaceholderValueStore.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/GlobalPlaceholderValueStore.kt index 666805063..99ef148f2 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/GlobalPlaceholderValueStore.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/GlobalPlaceholderValueStore.kt @@ -1,7 +1,7 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.builtin -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderValueScope -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderValueStore +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderValueScope +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderValueStore import java.util.Locale import java.util.UUID import java.util.concurrent.ConcurrentHashMap diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/LibraryPlaceholders.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/LibraryPlaceholders.kt similarity index 81% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/LibraryPlaceholders.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/LibraryPlaceholders.kt index b4106c333..5466ae61e 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/LibraryPlaceholders.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/LibraryPlaceholders.kt @@ -1,6 +1,7 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.builtin import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity +import org.pnfolder.pnlibrary.core.placeholders.PlaceholderHub /** The library's own placeholders, `pnlibrary/main:...`, readable by every plugin. */ class LibraryPlaceholders( @@ -9,6 +10,7 @@ class LibraryPlaceholders( private val pluginCount: () -> Int, private val statistics: () -> Map, ) { + /** Registers the library's placeholders: version, plugin count, uptime and the statistics. */ fun register() { hub.library("version", String::class.java) { PnLibraryIdentity.VERSION } hub.library("plugins", Int::class.javaObjectType, pluginCount) diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderAddress.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderAddress.kt similarity index 93% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderAddress.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderAddress.kt index 712fb8554..5f3a8b332 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderAddress.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderAddress.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.entries /** * Full address of a placeholder: `plugin/module:name`. @@ -18,6 +18,7 @@ data class PlaceholderAddress(val plugin: String, val module: String, val name: fun forPlaceholderApi(prefix: String) = "${prefix}_$module~$name" companion object { + /** The module of a plugin that has no modules. */ const val DEFAULT_MODULE = "main" private val PART = Regex("[a-z0-9][a-z0-9_-]*") private val NAME = Regex("[a-zA-Z0-9_.{}-]+") diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderAddressIndex.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderAddressIndex.kt new file mode 100644 index 000000000..9f07f63fc --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderAddressIndex.kt @@ -0,0 +1,80 @@ +package org.pnfolder.pnlibrary.core.placeholders.entries + +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArrayList + +/** Finds placeholders by their readable `plugin/module:name` address. */ +class PlaceholderAddressIndex { + private class Registered(val address: PlaceholderAddress, val entry: PlaceholderEntry<*>) + + /** Everything one module registered: exact names for direct lookup, parameterized ones kept apart for the pattern search. */ + private class ModuleSlots { + val exact = ConcurrentHashMap() + val patterns = CopyOnWriteArrayList() + } + + private val modulesByPlugin = ConcurrentHashMap>() + + /** Adds [entry] under [address]; returns `false` when the address is taken. */ + fun add(address: PlaceholderAddress, entry: PlaceholderEntry<*>): Boolean { + val slots = modulesByPlugin.computeIfAbsent(address.plugin) { ConcurrentHashMap() } + .computeIfAbsent(address.module) { ModuleSlots() } + val registered = Registered(address, entry) + if (slots.exact.putIfAbsent(address.name, registered) != null) return false + if (entry.pattern != null) slots.patterns += registered + return true + } + + /** Removes [entry] from [address]; a newer entry registered there is left alone. */ + fun remove(address: PlaceholderAddress, entry: PlaceholderEntry<*>) { + val slots = modulesByPlugin[address.plugin]?.get(address.module) ?: return + val registered = slots.exact[address.name]?.takeIf { it.entry === entry } ?: return + if (slots.exact.remove(address.name, registered)) slots.patterns.remove(registered) + } + + /** Every address with its entry, ordered for display. */ + fun all(): List>> = + modulesByPlugin.values.flatMap { modules -> modules.values.flatMap { it.exact.values } } + .map { it.address to it.entry } + .sortedBy { it.first.toString() } + + /** Finds the exact entry, or the most specific pattern of the same plugin and module. */ + fun find(address: PlaceholderAddress): PlaceholderEntryLookup.Match { + val slots = modulesByPlugin[address.plugin]?.get(address.module) ?: return NOTHING + return search(listOf(slots), address.name) + } + + /** Finds [name] in any module of [plugin]; the module `main` comes first, the rest by name. */ + fun findInPlugin(plugin: String, name: String): PlaceholderEntryLookup.Match { + val modules = modulesByPlugin[plugin] ?: return NOTHING + val ordered = modules.entries.sortedWith(compareBy({ it.key != MAIN }, { it.key })).map { it.value } + return search(ordered, name) + } + + private fun search(scope: List, name: String): PlaceholderEntryLookup.Match { + val lowered = name.lowercase() + for (slots in scope) { + slots.exact[lowered]?.let { return PlaceholderEntryLookup.Match(it.entry, emptyMap()) } + } + var best: PlaceholderEntry<*>? = null + var bestSpecificity = Int.MIN_VALUE + var bestParameters = emptyMap() + for (slots in scope) { + for (registered in slots.patterns) { + val pattern = registered.entry.pattern ?: continue + val parameters = pattern.match(name) ?: continue + if (best == null || pattern.specificity > bestSpecificity) { + best = registered.entry + bestSpecificity = pattern.specificity + bestParameters = parameters + } + } + } + return if (best == null) NOTHING else PlaceholderEntryLookup.Match(best, bestParameters) + } + + private companion object { + const val MAIN = PlaceholderAddress.DEFAULT_MODULE + val NOTHING = PlaceholderEntryLookup.Match(null, emptyMap()) + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntries.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntries.kt new file mode 100644 index 000000000..9c681b0fe --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntries.kt @@ -0,0 +1,50 @@ +package org.pnfolder.pnlibrary.core.placeholders.entries + +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArrayList + +/** Registered entries by `owner:key` id, with the parameterized ones also kept per owner so a pattern search skips everything else. */ +class PlaceholderEntries { + private val byId = ConcurrentHashMap>() + private val patternsByOwner = ConcurrentHashMap>>() + + val values: Collection> get() = byId.values + + operator fun get(id: String): PlaceholderEntry<*>? = byId[id] + + /** Adds [entry] under [id]; returns `false` when the id is taken. */ + fun add(id: String, entry: PlaceholderEntry<*>): Boolean { + if (byId.putIfAbsent(id, entry) != null) return false + if (entry.pattern != null) patternsByOwner.computeIfAbsent(entry.owner) { CopyOnWriteArrayList() } += entry + return true + } + + /** Puts [entry] under [id], replacing what was there. */ + operator fun set(id: String, entry: PlaceholderEntry<*>) { + remove(id) + add(id, entry) + } + + /** Removes [entry] from [id]; a newer entry registered there is left alone. */ + fun remove(id: String, entry: PlaceholderEntry<*>): Boolean { + if (!byId.remove(id, entry)) return false + forgetPattern(entry) + return true + } + + fun remove(id: String): PlaceholderEntry<*>? = byId.remove(id)?.also(::forgetPattern) + + /** The parameterized entries of [owner], in registration order. */ + fun patternsOf(owner: PluginId): List> = patternsByOwner[owner].orEmpty() + + private fun forgetPattern(entry: PlaceholderEntry<*>) { + if (entry.pattern != null) patternsByOwner[entry.owner]?.remove(entry) + } + + companion object { + fun of(entries: Map>) = PlaceholderEntries().also { index -> + entries.forEach { (id, entry) -> index.add(id, entry) } + } + } +} diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderEntry.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntry.kt similarity index 70% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderEntry.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntry.kt index dd6ed44d4..18dff27b7 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderEntry.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntry.kt @@ -1,21 +1,25 @@ -package org.pnfolder.pnlibrary.core.placeholders - -import org.pnfolder.pnlibrary.api.placeholders.ExternalPlaceholderRegistration -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAccess -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapter -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderCachePolicy -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderCacheScope -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderKey -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderPublication +package org.pnfolder.pnlibrary.core.placeholders.entries + import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRegistration -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRequest import org.pnfolder.pnlibrary.api.placeholders.PlaceholderUpdater +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapter +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderCachePolicy +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderCacheScope +import org.pnfolder.pnlibrary.api.placeholders.model.ExternalPlaceholderRegistration +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderPublication +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.core.placeholders.PlaceholderPublicationBinding +import org.pnfolder.pnlibrary.core.placeholders.formatters.PlaceholderFormatterRegistry import java.util.Collections import java.util.Locale import java.util.concurrent.CompletableFuture +import java.util.concurrent.CompletionException import java.util.concurrent.CompletionStage +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException @@ -27,8 +31,8 @@ class PlaceholderEntry( override val key: PlaceholderKey, private val resolver: (PlaceholderRequest) -> CompletionStage, private val updater: PlaceholderUpdater?, - val access: PlaceholderAccess, - private val updateAccess: PlaceholderAccess, + val access: PluginAccess, + private val updateAccess: PluginAccess, private val cachePolicy: PlaceholderCachePolicy, private val fallback: T?, private val adapterLookup: (String) -> PlaceholderAdapter?, @@ -43,6 +47,10 @@ class PlaceholderEntry( private val cache = Collections.synchronizedMap(LinkedHashMap>()) private val publicationBindings = Collections.synchronizedList(mutableListOf()) private val publishedNames = mutableListOf() + private val warming = ConcurrentHashMap.newKeySet() + + /** The key as a compiled pattern when it has braces, built once here instead of on every lookup. */ + val pattern: PlaceholderPatternMatcher.Compiled? = PlaceholderPatternMatcher.compile(key.value) private val stale: MutableMap = Collections.synchronizedMap( object : LinkedHashMap() { override fun removeEldestEntry(eldest: MutableMap.MutableEntry) = size > MAXIMUM_STALE @@ -76,10 +84,12 @@ class PlaceholderEntry( cache.clear() } + /** Sets what runs once when the entry is closed, so the hub can forget it. */ fun whenClosed(callback: () -> Unit) { closeCallback = callback } + /** Reads the value for [request] from the cache or the resolver; a missing value becomes the fallback. */ fun resolve(request: PlaceholderRequest): CompletionStage { if (!isEnabled) return CompletableFuture.completedFuture(fallback) @@ -95,6 +105,7 @@ class PlaceholderEntry( } } + /** Changes the value on behalf of [consumer] and clears the cache; fails when the placeholder is read-only or [consumer] may not. */ fun update(consumer: PluginId, request: PlaceholderRequest, value: String): T? { check(updateAccess.allows(owner, consumer)) { "Plugin $consumer cannot update ${owner.value}:${key.value}" @@ -106,6 +117,7 @@ class PlaceholderEntry( /** What this placeholder was asked to publish outside, for the administrator's list. */ val publishedAs: List get() = synchronized(publishedNames) { publishedNames.toList() } + /** Publishes the placeholder to an outside system, now if its adapter is present and when it arrives otherwise. */ fun publish(publication: PlaceholderPublication) { synchronized(publishedNames) { publishedNames += publication } val binding = PlaceholderPublicationBinding(publication, owner, key.value, ::published) @@ -115,32 +127,57 @@ class PlaceholderEntry( /** * The value for an outside system that wants an answer now. Waits at most [PlaceholderAdapter.WAIT_MILLIS_KEY] milliseconds - * (the caller says how long in the request values); when the value is late, the last known one is returned - * and the late result is kept for the next ask. + * (the caller says how long in the request values; zero never waits); when the value is late, the last known one + * is returned and the late result is kept for the next ask. */ private fun published(request: PlaceholderRequest): Any? { val staleKey = request.playerId.toString() + request.parameters.toSortedMap() + val waitMillis = (request.values[PlaceholderAdapter.WAIT_MILLIS_KEY] as? Long) ?: DEFAULT_WAIT_MILLIS + val value = if (waitMillis <= 0) warmUp(request, staleKey) else await(request, staleKey, waitMillis) + val answer = value ?: stale[staleKey] ?: fallback + return publishedFormat?.invoke(answer, request) ?: answer + } + + private fun await(request: PlaceholderRequest, staleKey: String, waitMillis: Long): Any? { val stage = resolve(request) stage.thenAccept { value -> if (value != null) stale[staleKey] = value } - val waitMillis = (request.values[PlaceholderAdapter.WAIT_MILLIS_KEY] as? Long) ?: DEFAULT_WAIT_MILLIS - val value: Any? = try { - if (waitMillis <= 0) stage.toCompletableFuture().getNow(null) - else stage.toCompletableFuture().get(waitMillis, TimeUnit.MILLISECONDS) + return try { + stage.toCompletableFuture().get(waitMillis, TimeUnit.MILLISECONDS) } catch (_: TimeoutException) { null } catch (_: ExecutionException) { null } - val answer = value ?: stale[staleKey] ?: fallback - return publishedFormat?.invoke(answer, request) ?: answer } + /** Starts the resolution without waiting, unless one for the same key is already running; gives the value only if it is ready. */ + private fun warmUp(request: PlaceholderRequest, staleKey: String): Any? { + if (!warming.add(staleKey)) return null + val stage = try { + resolve(request) + } catch (error: Throwable) { + warming.remove(staleKey) + throw error + } + stage.whenComplete { value, _ -> + if (value != null) stale[staleKey] = value + warming.remove(staleKey) + } + return try { + stage.toCompletableFuture().getNow(null) + } catch (_: CompletionException) { + null + } + } + + /** Publishes through [adapter] every publication that asked for it. */ fun attach(adapter: PlaceholderAdapter) { publicationBindings.toList() .filter { binding -> binding.adapterId == adapter.id.lowercase(Locale.ROOT) } .forEach { binding -> binding.attach(adapter) } } + /** Withdraws every publication that went through the adapter [adapterId]. */ fun detach(adapterId: String) { publicationBindings.toList() .filter { binding -> binding.adapterId == adapterId.lowercase(Locale.ROOT) } @@ -188,6 +225,7 @@ private data class CachedPlaceholderValue( val value: T?, val writtenAtMillis: Long, ) { + /** Whether the value is older than the policy allows. */ fun expired(policy: PlaceholderCachePolicy): Boolean = System.currentTimeMillis() - writtenAtMillis >= policy.expireAfterWrite.toMillis() } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntryLookup.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntryLookup.kt new file mode 100644 index 000000000..4f3aa2984 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntryLookup.kt @@ -0,0 +1,63 @@ +package org.pnfolder.pnlibrary.core.placeholders.entries + +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.util.Locale +import java.util.concurrent.atomic.AtomicLong + +/** Resolves exact and patterned placeholder references across plugin namespaces. */ +class PlaceholderEntryLookup( + private val entries: PlaceholderEntries, + private val systemNamespace: PluginId, +) { + constructor(entries: Map>, systemNamespace: PluginId) : + this(PlaceholderEntries.of(entries), systemNamespace) + + private val scanned = AtomicLong() + + /** How many pattern candidates searches have looked at so far; only tests read it. */ + val candidatesScanned: Long get() = scanned.get() + + /** The entry found, or null, with the values taken from the pattern's parameters. */ + data class Match( + val entry: PlaceholderEntry<*>?, + val parameters: Map, + ) + + /** Finds the most specific entry visible under the namespace encoded in [reference]. */ + fun find(consumer: PluginId, reference: String): Match { + val separator = reference.indexOf(':') + val namespace = if (separator > 0) { + PluginId.of(reference.substring(0, separator)) + } else { + consumer + } + val key = if (separator > 0) reference.substring(separator + 1) else reference + + exact(namespace, key)?.let { return Match(it, emptyMap()) } + if (separator < 0) { + exact(systemNamespace, key)?.let { return Match(it, emptyMap()) } + } + + return bestPattern(namespace, key) + } + + private fun bestPattern(namespace: PluginId, key: String): Match { + var best: PlaceholderEntry<*>? = null + var bestSpecificity = Int.MIN_VALUE + var bestParameters = emptyMap() + for (entry in entries.patternsOf(namespace)) { + scanned.incrementAndGet() + val pattern = entry.pattern ?: continue + val parameters = pattern.match(key) ?: continue + if (best == null || pattern.specificity > bestSpecificity) { + best = entry + bestSpecificity = pattern.specificity + bestParameters = parameters + } + } + return Match(best, bestParameters) + } + + private fun exact(owner: PluginId, key: String): PlaceholderEntry<*>? = + entries["${owner.value}:${key.lowercase(Locale.ROOT)}"] +} diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderInfo.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderInfo.kt similarity index 80% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderInfo.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderInfo.kt index a568333b6..fb403b7ec 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderInfo.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderInfo.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.entries /** One placeholder as the administrator sees it in `/pn placeholders`. */ data class PlaceholderInfo( diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderPatternMatcher.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderPatternMatcher.kt new file mode 100644 index 000000000..cf633b12f --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderPatternMatcher.kt @@ -0,0 +1,64 @@ +package org.pnfolder.pnlibrary.core.placeholders.entries + +import java.util.concurrent.atomic.AtomicLong + +/** + * Matches a concrete placeholder key against a parameterized key pattern. + * + * Parameters use braces, for example `player.stat.{name}` matches + * `player.stat.kills` and returns `name=kills`. A parameter consumes exactly + * one dot-delimited segment; literal portions of a pattern are matched + * verbatim. + */ +object PlaceholderPatternMatcher { + private val parameter = Regex("\\{([a-zA-Z0-9_-]+)}") + private val compilationCounter = AtomicLong() + private val evaluationCounter = AtomicLong() + + /** How many patterns were compiled since start; tests use it to prove registration compiles once. */ + val compilations: Long get() = compilationCounter.get() + + /** How many times a compiled pattern was tried against a key; tests use it to count candidates. */ + val evaluations: Long get() = evaluationCounter.get() + + /** A pattern with its regular expression built once, at registration. */ + class Compiled internal constructor( + private val names: List, + private val regex: Regex, + /** How many characters of the pattern are fixed text; a pattern with more of them is the more specific one. */ + val specificity: Int, + ) { + /** Returns captured parameters, or `null` when [value] does not match. */ + fun match(value: String): Map? { + evaluationCounter.incrementAndGet() + val result = regex.matchEntire(value) ?: return null + return names.indices.associate { index -> names[index] to result.groupValues[index + 1] } + } + } + + /** Builds the matcher of [pattern]; `null` when the pattern has no parameter. */ + fun compile(pattern: String): Compiled? { + val tokens = parameter.findAll(pattern).toList() + if (tokens.isEmpty()) return null + + compilationCounter.incrementAndGet() + var cursor = 0 + val expression = buildString { + append('^') + tokens.forEach { token -> + append(Regex.escape(pattern.substring(cursor, token.range.first))) + append("([^.]+)") + cursor = token.range.last + 1 + } + append(Regex.escape(pattern.substring(cursor))) + append('$') + } + return Compiled(tokens.map { it.groupValues[1] }, Regex(expression), specificity(pattern)) + } + + /** How many characters of [pattern] are fixed text; a pattern with more of them is the more specific one. */ + fun specificity(pattern: String): Int = parameter.replace(pattern, "").length + + /** Returns captured parameters, or `null` when [value] does not match [pattern]. */ + fun match(pattern: String, value: String): Map? = compile(pattern)?.match(value) +} diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderBuiltInFormatters.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderBuiltInFormatters.kt similarity index 98% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderBuiltInFormatters.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderBuiltInFormatters.kt index cbe589eb4..a4182684d 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderBuiltInFormatters.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderBuiltInFormatters.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.formatters import org.pnfolder.pnlibrary.common.text.RussianText import java.math.BigDecimal @@ -45,6 +45,7 @@ object PlaceholderBuiltInFormatters { return scaled.toPlainString() + suffix } + /** Makes the first character upper case. */ fun capitalize(value: Any): String = value.toString().replaceFirstChar { it.titlecase(Locale.ROOT) } diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderFormatterRegistry.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderFormatterRegistry.kt similarity index 92% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderFormatterRegistry.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderFormatterRegistry.kt index c1b229268..cd2a9c3a7 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderFormatterRegistry.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderFormatterRegistry.kt @@ -1,7 +1,7 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.formatters import org.pnfolder.pnlibrary.api.placeholders.PlaceholderFormatter -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRequest +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity import java.util.Locale @@ -13,6 +13,7 @@ class PlaceholderFormatterRegistry { private val byAddress = ConcurrentHashMap>() private val systemOwner = PluginId.of(SYSTEM_NAMESPACE) + /** Registers the formatters every plugin can use without an owner prefix. */ fun registerBuiltIns() { register(systemOwner, "upper", Any::class.java) { value, _, _ -> value.toString().uppercase(Locale.ROOT) } register(systemOwner, "lower", Any::class.java) { value, _, _ -> value.toString().lowercase(Locale.ROOT) } @@ -41,6 +42,7 @@ class PlaceholderFormatterRegistry { register(systemOwner, "date", Any::class.java) { value, arguments, _ -> PlaceholderBuiltInFormatters.date(value, arguments) } } + /** Registers formatter [name] of [owner] for values of [type]; the name must be lower case letters, digits, `_` or `-`. */ fun register( owner: PluginId, name: String, @@ -61,11 +63,13 @@ class PlaceholderFormatterRegistry { byAddress[address.lowercase(Locale.ROOT)] = FormatterDefinition(owner, type, formatter) } + /** Removes every formatter and format address registered by [owner]. */ fun removeOwnedBy(owner: PluginId) { formatters.entries.removeIf { (_, definition) -> definition.owner == owner } byAddress.entries.removeIf { (_, definition) -> definition.owner == owner } } + /** Applies the formatters of [pipeline] to [value] in order; [own] are the formats of the placeholder's entry. */ fun format( consumer: PluginId, value: Any?, diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderTemplateRenderer.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderTemplateRenderer.kt similarity index 68% rename from modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderTemplateRenderer.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderTemplateRenderer.kt index 9b7ffefd6..2b00b5730 100644 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderTemplateRenderer.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderTemplateRenderer.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.formatters import java.util.UUID import java.util.concurrent.CompletableFuture @@ -9,37 +9,15 @@ class PlaceholderTemplateRenderer( private val resolve: (String, UUID?, Map) -> CompletionStage, private val format: (Any?, List, UUID?, Map) -> Any?, ) { + /** Fills the conditionals and `{name}` expressions of [template] with [values] and resolved placeholders. */ fun render( template: String, playerId: UUID?, values: Map, ): CompletionStage = renderConditions(template, playerId, values, MAXIMUM_CONDITIONAL_DEPTH) - .thenCompose { output -> renderLocalExpressions(output, playerId, values) } .thenCompose { output -> renderOrdinaryExpressions(output, playerId, values) } - private fun renderLocalExpressions( - template: String, - playerId: UUID?, - values: Map, - ): CompletionStage { - val expressions = LOCAL_EXPRESSION.findAll(template) - .map { match -> match.value } - .distinct() - .mapNotNull { token -> LocalPlaceholderExpression.parse(token)?.let { token to it } } - .toList() - var result: CompletionStage = CompletableFuture.completedFuture(template) - expressions.forEach { (token, expression) -> - result = result.thenCompose { current -> - resolve(expression.reference, playerId, values).thenApply { value -> - val formatted = format(value, expression.formatters, playerId, values) - current.replace(token, formatted?.toString() ?: token) - } - } - } - return result - } - private fun renderOrdinaryExpressions( template: String, playerId: UUID?, @@ -79,7 +57,6 @@ class PlaceholderTemplateRenderer( private companion object { const val MAXIMUM_CONDITIONAL_DEPTH = 16 - val LOCAL_EXPRESSION = Regex("\\[[^\\[\\]]+]") val ORDINARY_EXPRESSION = Regex("\\{([^{}]+)}") val CONDITIONAL = Regex("\\{\\?([^{}]+)}([\\s\\S]*?)(?:\\{:}([\\s\\S]*?))?\\{/}") } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/LibraryWords.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/LibraryWords.kt new file mode 100644 index 000000000..23df37964 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/LibraryWords.kt @@ -0,0 +1,18 @@ +package org.pnfolder.pnlibrary.core.plugin + +import org.pnfolder.pnlibrary.api.config.ConfigScope +import org.pnfolder.pnlibrary.api.config.type +import org.pnfolder.pnlibrary.api.currency.BalanceRequirement +import org.pnfolder.pnlibrary.api.currency.ChargeAction +import org.pnfolder.pnlibrary.api.currency.GiveAction +import org.pnfolder.pnlibrary.api.scenario.actions.Action +import org.pnfolder.pnlibrary.api.scenario.requirements.Requirement + +/** Configuration words the library itself adds for every plugin; a plugin may still publish its own word with a higher priority. */ +internal object LibraryWords { + fun register(scope: ConfigScope) { + scope.type().name("charge").everywhere().register() + scope.type().name("give").everywhere().register() + scope.type().name("balance").everywhere().register() + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/PluginRegistryImpl.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/PluginRegistryImpl.kt index aa3ea1a05..375389181 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/PluginRegistryImpl.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/PluginRegistryImpl.kt @@ -1,17 +1,17 @@ package org.pnfolder.pnlibrary.core.plugin -import org.pnfolder.pnlibrary.api.actions.ActionService -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.CommandError -import org.pnfolder.pnlibrary.api.commands.CommandErrorHandler import org.pnfolder.pnlibrary.api.commands.CommandRegistration +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.error.CommandError +import org.pnfolder.pnlibrary.api.commands.error.CommandErrorHandler import org.pnfolder.pnlibrary.api.config.ConfigScope import org.pnfolder.pnlibrary.api.cooldowns.CooldownService import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticRegistration import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsService import org.pnfolder.pnlibrary.api.downloads.DownloadRegistration -import org.pnfolder.pnlibrary.api.events.EventScope -import org.pnfolder.pnlibrary.api.events.EventService +import org.pnfolder.pnlibrary.api.events.bus.EventScope +import org.pnfolder.pnlibrary.api.events.bus.EventService +import org.pnfolder.pnlibrary.api.libraries.ModuleLibraries import org.pnfolder.pnlibrary.api.logging.LoggingService import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.api.metrics.MetricsController @@ -21,37 +21,45 @@ import org.pnfolder.pnlibrary.api.plugin.ModuleContext import org.pnfolder.pnlibrary.api.plugin.ModuleId import org.pnfolder.pnlibrary.api.plugin.PluginBuilder import org.pnfolder.pnlibrary.api.plugin.PluginId -import org.pnfolder.pnlibrary.api.plugin.PluginLifecycle -import org.pnfolder.pnlibrary.api.plugin.PluginMessages -import org.pnfolder.pnlibrary.api.plugin.PluginMetadata import org.pnfolder.pnlibrary.api.plugin.PluginRegistration import org.pnfolder.pnlibrary.api.plugin.PluginRegistry +import org.pnfolder.pnlibrary.api.plugin.control.PluginModule +import org.pnfolder.pnlibrary.api.plugin.lifecycle.PluginLifecycle +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMessages +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata import org.pnfolder.pnlibrary.api.remote.RemotePolicySettings import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity +import org.pnfolder.pnlibrary.api.scenario.actions.ActionService import org.pnfolder.pnlibrary.api.services.ServiceManager import org.pnfolder.pnlibrary.api.tasks.TaskScope import org.pnfolder.pnlibrary.api.text.ComponentService -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor import org.pnfolder.pnlibrary.api.updates.UpdateRegistration import org.pnfolder.pnlibrary.api.updates.UpdateService +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.config.ConfigurationRuntime -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup -import org.pnfolder.pnlibrary.core.commands.CommandFeedbackScope -import org.pnfolder.pnlibrary.core.commands.CommandService -import org.pnfolder.pnlibrary.core.downloads.DirectDownloads +import org.pnfolder.pnlibrary.core.commands.engine.CommandFeedbackScope +import org.pnfolder.pnlibrary.core.commands.engine.CommandService +import org.pnfolder.pnlibrary.core.downloads.fetch.DirectDownloads +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup import org.pnfolder.pnlibrary.core.expansions.LocalizationExpansion +import org.pnfolder.pnlibrary.core.plugin.module.LibraryFetcher import org.pnfolder.pnlibrary.core.plugin.module.ModuleActionService +import org.pnfolder.pnlibrary.core.plugin.module.ModuleCommands +import org.pnfolder.pnlibrary.core.plugin.module.ModuleController import org.pnfolder.pnlibrary.core.plugin.module.ModuleDefinitionBuilder import org.pnfolder.pnlibrary.core.plugin.module.ModuleDependencyValidator import org.pnfolder.pnlibrary.core.plugin.module.ModuleExpansions +import org.pnfolder.pnlibrary.core.plugin.module.ModuleLibrariesImpl import org.pnfolder.pnlibrary.core.plugin.module.ModuleLifecycleReporter import org.pnfolder.pnlibrary.core.plugin.module.ModuleMessages import org.pnfolder.pnlibrary.core.plugin.module.ModuleMetadataFactory +import org.pnfolder.pnlibrary.core.plugin.module.ModulePreferences import org.pnfolder.pnlibrary.core.plugin.module.ModuleProductResolver import org.pnfolder.pnlibrary.core.plugin.module.ModuleResourceFactory import org.pnfolder.pnlibrary.core.plugin.module.ModuleResources -import org.pnfolder.pnlibrary.core.plugin.module.ModuleServiceKeyFactory +import org.pnfolder.pnlibrary.core.plugin.module.ScenarioDefinitions +import org.pnfolder.pnlibrary.core.plugin.module.moduleServiceKey import org.pnfolder.pnlibrary.core.remote.RemotePolicyMonitor import org.pnfolder.pnlibrary.core.services.ServiceRegistry import org.pnfolder.pnlibrary.core.tasks.TaskService @@ -88,8 +96,11 @@ internal class PluginRegistryImpl( private val commands: CommandService? = null, private val directDownloads: DirectDownloads? = null, libraryVersion: String? = null, + private val modulePreferences: ModulePreferences = ModulePreferences(), + private val libraryFetcher: LibraryFetcher = LibraryFetcher.THROUGH_LIBBY, ) : PluginRegistry { + private val scenarioDefinitions = ScenarioDefinitions() private val plugins = IdentityHashMap() private val productDescriptors = linkedMapOf().apply { libraryVersion?.let(SemanticVersion::tryParse)?.let { put(PnLibraryIdentity.PRODUCT_ID, ProductDescriptor.library(it.toString())) } @@ -147,6 +158,7 @@ internal class PluginRegistryImpl( serviceKey: PluginId, definition: ModuleDefinitionBuilder, productDescriptor: ProductDescriptor?, + module: PluginModule?, ): Context { val owner = parent.owner val metadata = metadataFactory.create(owner, id, definition) @@ -159,6 +171,7 @@ internal class PluginRegistryImpl( resources = resources, placeholderApiEnabled = definition.placeholderApiEnabled, productId = productDescriptor?.id?.value, + module = module, ) } @@ -169,7 +182,11 @@ internal class PluginRegistryImpl( val nativeId: PluginId, private val registrationId: Long, ) : PluginRegistration { + override val id: PluginId get() = nativeId private val moduleContexts = linkedMapOf() + override val libraries: ModuleLibraries = ModuleLibrariesImpl.through( + "p-${nativeId.value}-$registrationId", PluginRegistryImpl::class.java.classLoader, owner, null, libraryFetcher, identity.type, + ) private val pluginClosed = AtomicBoolean(false) override val isClosed: Boolean get() = pluginClosed.get() @@ -180,6 +197,15 @@ internal class PluginRegistryImpl( } override fun registerModule(id: ModuleId, configure: Consumer): ModuleContext = + start(id, null, configure) + + override fun registerModule(id: ModuleId, module: PluginModule, configure: Consumer): ModuleContext = + start(id, module, configure) + + private fun start(id: ModuleId, module: PluginModule?, configure: Consumer): ModuleContext = + register(id, module, configure).also { (it as Context).control.start() } + + private fun register(id: ModuleId, module: PluginModule?, configure: Consumer): ModuleContext = synchronized(plugins) { synchronized(moduleContexts) { check(!pluginClosed.get()) { "Plugin context is closed" } check(!closed.get()) { "PluginRegistry is closed" } @@ -191,8 +217,8 @@ internal class PluginRegistryImpl( } definition.bindUpdatesTo(descriptor) dependencyValidator.validate(definition.dependencies, productDescriptors) - val serviceKey = ModuleServiceKeyFactory.create(registrationId, nativeId, id) - createContext(this, id, serviceKey, definition, descriptor).also { context -> + val serviceKey = moduleServiceKey(registrationId, nativeId, id) + createContext(this, id, serviceKey, definition, descriptor, module).also { context -> moduleContexts[id] = context if (descriptor != null) productDescriptors[descriptor.id.value] = descriptor try { @@ -241,6 +267,7 @@ internal class PluginRegistryImpl( private val resources: ModuleResources, private val placeholderApiEnabled: Boolean, private val productId: String?, + module: PluginModule?, ) : ModuleContext { private val owner: Any get() = parent.owner private val contextClosed = AtomicBoolean(false) @@ -251,6 +278,13 @@ internal class PluginRegistryImpl( commandFeedback.handlers[type] = handler } override val isClosed: Boolean get() = contextClosed.get() + override val libraries = ModuleLibrariesImpl.through( + key.value, PluginRegistryImpl::class.java.classLoader, parent.owner, parent.libraries, libraryFetcher, identity.type, + ) + override val control = ModuleController(key.value, module, modulePreferences) { + resources.tasks.cancelAll() + moduleCommands.drain().asReversed().forEach { it.close() } + }.also { it.bind(this) } override val tasks: TaskScope get() = resources.tasks override val events: EventScope get() = resources.events override val services: ServiceManager get() = resources.services @@ -279,7 +313,7 @@ internal class PluginRegistryImpl( isClosed = { isClosed }, ) override val messages: PluginMessages = ModuleMessages(owner, logging) - override val actions: ActionService = ModuleActionService(resources) + override val actions: ActionService = ModuleActionService(resources, scenarioDefinitions, key.value) override fun close() { parent.detach(id)?.closeInternal() @@ -287,6 +321,7 @@ internal class PluginRegistryImpl( fun closeInternal() { if (!contextClosed.compareAndSet(false, true)) return + control.stop() productId?.let { value -> synchronized(plugins) { productDescriptors.remove(value) } } val registrations = moduleCommands.drain() ResourceCleanup.closeAll( diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/SharedFeatures.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/SharedFeatures.kt index 0e99a6ab9..88c935bfd 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/SharedFeatures.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/SharedFeatures.kt @@ -4,6 +4,7 @@ import org.pnfolder.pnlibrary.api.expansions.ExpansionManager import org.pnfolder.pnlibrary.core.placeholders.PlaceholderHub import org.pnfolder.pnlibrary.currency.CurrencyRuntime +/** Library-wide features shared by all modules: placeholders, currency and expansions. */ internal class SharedFeatures( val placeholders: PlaceholderHub, val currency: CurrencyRuntime, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/HidingLifecycleBox.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/HidingLifecycleBox.kt similarity index 93% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/HidingLifecycleBox.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/HidingLifecycleBox.kt index 933a75920..d0158566c 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/HidingLifecycleBox.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/HidingLifecycleBox.kt @@ -1,7 +1,7 @@ -package org.pnfolder.pnlibrary.core.plugin +package org.pnfolder.pnlibrary.core.plugin.module import org.pnfolder.pnlibrary.api.logging.MessageBox -import org.pnfolder.pnlibrary.api.plugin.LifecycleRow +import org.pnfolder.pnlibrary.api.plugin.lifecycle.LifecycleRow /** * A lifecycle card that lets the plugin hide the rows pnLibrary adds by itself before any of its own rows are added. diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/cooldowns/InMemoryCooldowns.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/InMemoryCooldowns.kt similarity index 78% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/cooldowns/InMemoryCooldowns.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/InMemoryCooldowns.kt index 4d6d792d6..734080423 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/cooldowns/InMemoryCooldowns.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/InMemoryCooldowns.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.cooldowns +package org.pnfolder.pnlibrary.core.plugin.module import org.pnfolder.pnlibrary.api.cooldowns.CooldownResult import org.pnfolder.pnlibrary.api.cooldowns.CooldownService @@ -7,12 +7,14 @@ import java.util.Locale import java.util.UUID import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger /** In-memory, thread-safe cooldowns keyed by subject and action, measured on the monotonic clock. */ internal class InMemoryCooldowns : CooldownService { private data class Key(val subject: UUID, val action: String) private val deadlines = ConcurrentHashMap() private val closed = AtomicBoolean(false) + private val writes = AtomicInteger() override val size: Int get() { cleanup() @@ -24,6 +26,7 @@ internal class InMemoryCooldowns : CooldownService { checkOpen() val key = Key(subject, normalized(action)) val now = System.nanoTime() + sweepSometimes() while (true) { val current = deadlines[key] if (current != null && current > now) return CooldownResult.denied(nanos(current - now)) @@ -48,6 +51,7 @@ internal class InMemoryCooldowns : CooldownService { override fun set(subject: UUID, action: String, duration: Duration) { validate(action, duration) checkOpen() + sweepSometimes() if (duration.isZero) deadlines.remove(Key(subject, normalized(action))) else deadlines[Key(subject, normalized(action))] = deadline(System.nanoTime(), duration) } @@ -64,10 +68,30 @@ internal class InMemoryCooldowns : CooldownService { } override fun reset(subject: UUID, action: String) = deadlines.remove(Key(subject, normalized(action))) != null override fun clear() = deadlines.clear() + + override fun clear(subject: UUID): Int { + var removed = 0 + deadlines.keys.removeIf { key -> (key.subject == subject).also { if (it) removed++ } } + return removed + } + + override fun active(subject: UUID): Map { + checkOpen() + val now = System.nanoTime() + return deadlines.entries.asSequence() + .filter { it.key.subject == subject && it.value > now } + .sortedByDescending { it.value } + .associate { it.key.action to nanos(it.value - now) } + } override fun close() { if (closed.compareAndSet(false, true)) clear() } + /** Every few hundred writes, drops the entries nobody asked about again, so the map cannot grow without bound. */ + private fun sweepSometimes() { + if (writes.incrementAndGet() % SWEEP_EVERY == 0) cleanup() + } + private fun cleanup() { val now = System.nanoTime() deadlines.entries.removeIf { it.value <= now } @@ -90,4 +114,8 @@ internal class InMemoryCooldowns : CooldownService { Long.MAX_VALUE } private fun nanos(value: Long) = Duration.ofNanos(value.coerceAtLeast(0)) + + private companion object { + const val SWEEP_EVERY = 256 + } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/LibraryFetcher.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/LibraryFetcher.kt new file mode 100644 index 000000000..b53ef2918 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/LibraryFetcher.kt @@ -0,0 +1,58 @@ +package org.pnfolder.pnlibrary.core.plugin.module + +import org.pnfolder.pnlibrary.api.libraries.LibraryScope +import org.pnfolder.pnlibrary.api.libraries.ModuleLibrary +import org.pnfolder.pnlibrary.spi.libraries.ExternalLibraries + +/** Downloads one library for [owner]; tests replace it, the runtime asks the Libby loader of the platform. */ +internal fun interface LibraryFetcher { + /** Returns the class loader that holds an isolated library, or `null` for any other scope. */ + fun fetch(loaderOwner: ClassLoader, owner: String, plugin: Any?, library: ModuleLibrary): ClassLoader? + + companion object { + /** + * Tries every place in [ModuleLibrary.allSources] in turn, as many as there are. A source is checked against its own + * sum, or not at all when it has none. The first one that gives a jar wins; when none does, the error lists the + * reason of each. + */ + val THROUGH_LIBBY = LibraryFetcher { loader, owner, plugin, library -> + val failures = mutableListOf() + for (source in SourceHealth.order(library.allSources)) { + try { + return@LibraryFetcher ExternalLibraries.load( + loader, owner, library.group, library.artifact, library.version, library.classifier, + source.sha256, + if (source.direct) source.url else null, if (source.direct) emptyList() else listOf(source.url), + library.scope == LibraryScope.ISOLATED, plugin.takeIf { library.scope == LibraryScope.PLUGIN }, + ) + } catch (failure: IllegalStateException) { + SourceHealth.failed(source.url) + failures += "${source.name}: ${failure.message}" + } + } + throw IllegalStateException("Cannot load ${library.coordinates}: ${failures.joinToString("; ").ifEmpty { "no source to look in" }}") + } + } +} + +/** + * Remembers, in memory only, which places failed in the last few minutes, so the next library does not wait on a dead mirror + * first: such a place is tried last. The order the author wrote is kept otherwise, and nothing is saved to disk. + */ +internal object SourceHealth { + private const val MEMORY_MILLIS = 5 * 60_000L + private val failedAt = java.util.concurrent.ConcurrentHashMap() + + fun failed(url: String, now: Long = System.currentTimeMillis()) { + failedAt[url] = now + } + + /** [sources] in their own order, except that places that failed within the last five minutes go to the end. */ + fun order(sources: List, now: Long = System.currentTimeMillis()): + List { + val (bad, good) = sources.partition { (failedAt[it.url] ?: Long.MIN_VALUE).let { at -> at != Long.MIN_VALUE && now - at < MEMORY_MILLIS } } + return good + bad + } + + fun forgetAll() = failedAt.clear() +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleActionService.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleActionService.kt index 359acc15d..2a987a8e3 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleActionService.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleActionService.kt @@ -1,23 +1,34 @@ package org.pnfolder.pnlibrary.core.plugin.module -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.actions.ActionService import org.pnfolder.pnlibrary.api.audiences.LibraryAudience -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.checks.Requirement -import org.pnfolder.pnlibrary.api.text.ComponentSerializerType +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.scenario.actions.Action +import org.pnfolder.pnlibrary.api.scenario.actions.ActionContext +import org.pnfolder.pnlibrary.api.scenario.actions.ActionService +import org.pnfolder.pnlibrary.api.scenario.actions.DefinitionConflict +import org.pnfolder.pnlibrary.api.scenario.actions.DefinitionScope +import org.pnfolder.pnlibrary.api.scenario.expression.Expression +import org.pnfolder.pnlibrary.api.scenario.expression.ExpressionFunction +import org.pnfolder.pnlibrary.api.scenario.requirements.Requirement +import org.pnfolder.pnlibrary.api.text.serializer.ComponentSerializerType +/** + * Action service of one module: every context gets the module's text, logger, tasks, placeholders and services, + * and sees the names the module defined plus the ones defined for the whole library. + */ internal class ModuleActionService( private val resources: ModuleResources, + private val shared: ScenarioDefinitions, + private val owner: String, ) : ActionService { + private val own = ScenarioDefinitions() + private val lookup = LayeredLookup(own, shared) + override fun context( player: LibraryPlayer, allPlayers: LibraryAudience, values: Map, serializerType: ComponentSerializerType, - templates: Map>, - checks: Map, ) = ActionContext( player = player, allPlayers = allPlayers, @@ -26,8 +37,21 @@ internal class ModuleActionService( tasks = resources.tasks, serializerType = serializerType, values = values, - templates = templates, - checks = checks, + serviceLookup = { type -> resources.services.get(type) }, + lookup = lookup, placeholders = resources.placeholders, ) + + private fun target(scope: DefinitionScope) = if (scope == DefinitionScope.LIBRARY) shared else own + + override fun define(name: String, action: Action, scope: DefinitionScope, conflict: DefinitionConflict) = + target(scope).defineAction(name, action, owner, conflict) + + override fun defineRequirement(name: String, requirement: Requirement, scope: DefinitionScope, conflict: DefinitionConflict) = + target(scope).defineRequirement(name, requirement, owner, conflict) + + override fun defineFunction(name: String, function: ExpressionFunction, scope: DefinitionScope, conflict: DefinitionConflict): AutoCloseable { + require(!Expression.isBuiltin(name.trim().lowercase())) { "'$name' is a function of the expression language itself" } + return target(scope).defineFunction(name, function, owner, conflict) + } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/ModuleCommands.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleCommands.kt similarity index 81% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/ModuleCommands.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleCommands.kt index 7f86a5664..059dbd82e 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/ModuleCommands.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleCommands.kt @@ -1,9 +1,9 @@ -package org.pnfolder.pnlibrary.core.plugin +package org.pnfolder.pnlibrary.core.plugin.module -import org.pnfolder.pnlibrary.api.commands.CommandDefinition import org.pnfolder.pnlibrary.api.commands.CommandRegistration -import org.pnfolder.pnlibrary.core.commands.CommandFeedbackScope -import org.pnfolder.pnlibrary.core.commands.CommandService +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.core.commands.engine.CommandFeedbackScope +import org.pnfolder.pnlibrary.core.commands.engine.CommandService /** The commands one module registered, so closing the module takes them all back. */ internal class ModuleCommands( diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleController.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleController.kt new file mode 100644 index 000000000..420ec4f2a --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleController.kt @@ -0,0 +1,131 @@ +package org.pnfolder.pnlibrary.core.plugin.module + +import org.pnfolder.pnlibrary.api.plugin.ModuleContext +import org.pnfolder.pnlibrary.api.plugin.control.ModuleControl +import org.pnfolder.pnlibrary.api.plugin.control.ModuleState +import org.pnfolder.pnlibrary.api.plugin.control.PluginModule +import org.pnfolder.pnlibrary.common.lang.Failures +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CompletionStage + +/** + * Runs the hooks of one [PluginModule] and keeps its state. Changes run one at a time; a hook that throws leaves the + * module [ModuleState.FAILED] and the error is kept instead of being thrown at the caller. + * + * @param release takes back what the library gave the module while it ran (tasks, commands) + */ +internal class ModuleController( + private val key: String, + private val module: PluginModule?, + private val preferences: ModulePreferences, + private val release: () -> Unit, +) : ModuleControl { + private lateinit var context: ModuleContext + + @Volatile override var state: ModuleState = ModuleState.ENABLED + private set + @Volatile override var lastError: Throwable? = null + private set + + override val isControllable: Boolean get() = module != null + override val autoStart: Boolean get() = preferences.autoStart(key) + + fun bind(context: ModuleContext) { + this.context = context + } + + /** First start at registration: stays off when an administrator turned the module off for good. */ + fun start() { + if (module == null) return + if (!autoStart) state = ModuleState.DISABLED else runEnable() + } + + /** Last stop when the module or its plugin goes away; errors are kept, never thrown. */ + fun stop() { + if (module != null && state == ModuleState.ENABLED) runDisable() + } + + override fun enable(): CompletionStage = change { if (state != ModuleState.ENABLED) runEnable() } + + override fun disable(): CompletionStage = change { + if (state == ModuleState.ENABLED) runDisable() else if (state == ModuleState.FAILED) { + release() + state = ModuleState.DISABLED + } + } + + override fun restart(): CompletionStage = change { + if (state == ModuleState.ENABLED) runDisable() + runEnable() + } + + override fun reload(): CompletionStage = change { + if (state == ModuleState.ENABLED) { + val inPlace = try { + module!!.onReload(context) + } catch (failure: Throwable) { + Failures.rethrowIfFatal(failure) + error(failure) + return@change + } + if (!inPlace) { + runDisable() + runEnable() + } + } + } + + override fun setAutoStart(enabled: Boolean) { + requireControllable() + preferences.setAutoStart(key, enabled) + } + + private fun change(action: () -> Unit): CompletionStage { + requireControllable() + synchronized(this) { + lastError = null + action() + } + return CompletableFuture.completedFuture(state) + } + + private fun requireControllable() { + if (module == null) throw UnsupportedOperationException("This module has no enable and disable hooks") + } + + private fun runEnable() = guarded(ModuleState.ENABLED) { + for (library in module!!.libraries()) { + try { + context.libraries.load(library) + } catch (failure: Exception) { + if (library.required) throw failure + context.logger.warning("Optional library $library was not loaded: ${failure.message}") + } + } + module.onEnable(context) + } + + private fun runDisable() = guarded(ModuleState.DISABLED) { + try { + module!!.onDisable(context) + } finally { + release() + } + } + + private fun guarded(target: ModuleState, block: () -> Unit) { + try { + block() + state = target + } catch (failure: Throwable) { + Failures.rethrowIfFatal(failure) + error(failure) + } + } + + private fun error(failure: Throwable) { + lastError = failure + state = ModuleState.FAILED + runCatching { context.logger.error("Module $key failed: ${failure.message}", failure) } + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDefinitionBuilder.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDefinitionBuilder.kt index 95e146e2d..3a6109019 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDefinitionBuilder.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDefinitionBuilder.kt @@ -1,15 +1,16 @@ package org.pnfolder.pnlibrary.core.plugin.module import org.pnfolder.pnlibrary.api.dependencies.PluginDependency -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticContainer +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticContainer import org.pnfolder.pnlibrary.api.downloads.FileDownloads -import org.pnfolder.pnlibrary.api.metrics.MetricsBuilder +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsBuilder import org.pnfolder.pnlibrary.api.plugin.PluginBuilder -import org.pnfolder.pnlibrary.api.plugin.PluginMetadataBuilder -import org.pnfolder.pnlibrary.api.plugin.PluginOptions +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadataBuilder +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginOptions import org.pnfolder.pnlibrary.api.remote.RemotePolicySettings -import org.pnfolder.pnlibrary.api.updates.PluginUpdateRequest -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.backup.UpdateConfigurationBackup +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest import java.nio.file.Path import java.util.function.Consumer @@ -25,6 +26,7 @@ internal class ModuleDefinitionBuilder : PluginBuilder { var metadataName: String? = null var metadataVersion: String? = null var metadataAuthors: String? = null + var metadataDescription: String? = null var metrics: ModuleMetricsDefinition = ModuleMetricsDefinition() private set var diagnosticsDirectory: Path? = null @@ -96,10 +98,17 @@ internal class ModuleDefinitionBuilder : PluginBuilder { .automaticDownload(source.automaticDownload) .supportedApi(descriptor.supportedApi.minimum, descriptor.supportedApi.maximum) .also { target -> copyArtifactRules(source, target) } - .also { target -> source.configurationBackup?.let { target.configurationBackup(it.root, *it.files.toTypedArray()) } } + .also { target -> source.configurationBackup?.let { copyBackups(it, target) } } + .also { target -> source.exports.forEach { target.backupExport(it.kind, it.name, it.fileName, it.export) } } .build() } + private fun copyBackups(source: UpdateConfigurationBackup, target: PluginUpdateRequest.Builder) { + source.files.groupBy(source::labelOf).forEach { (label, files) -> + target.backup(label.kind, label.name, source.root, *files.toTypedArray()) + } + } + private fun copyArtifactRules( source: PluginUpdateRequest, target: PluginUpdateRequest.Builder, @@ -143,6 +152,10 @@ internal class ModuleDefinitionBuilder : PluginBuilder { definition.metadataVersion = value.requireMetadata("version") } + override fun description(value: String): PluginMetadataBuilder = apply { + definition.metadataDescription = value.requireMetadata("description") + } + override fun authors(value: String): PluginMetadataBuilder = apply { definition.metadataAuthors = value.requireMetadata("authors") } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDependencyValidator.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDependencyValidator.kt index 0cc84ac0d..a5eeed11b 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDependencyValidator.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDependencyValidator.kt @@ -1,11 +1,12 @@ package org.pnfolder.pnlibrary.core.plugin.module import org.pnfolder.pnlibrary.api.dependencies.PluginDependency -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership +/** Checks that a module's declared plugin dependencies are present and downloadable. */ internal class ModuleDependencyValidator( private val platform: PlatformOwnership, private val downloadsAvailable: () -> Boolean, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleExpansions.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleExpansions.kt index 1e3b26c25..80089fe02 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleExpansions.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleExpansions.kt @@ -2,7 +2,7 @@ package org.pnfolder.pnlibrary.core.plugin.module import org.pnfolder.pnlibrary.api.expansions.Expansion import org.pnfolder.pnlibrary.api.expansions.ExpansionManager -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup import org.pnfolder.pnlibrary.core.expansions.ModuleBinding import org.pnfolder.pnlibrary.core.expansions.ModuleBoundExpansion diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleLibrariesImpl.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleLibrariesImpl.kt new file mode 100644 index 000000000..f3f56ba7e --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleLibrariesImpl.kt @@ -0,0 +1,64 @@ +package org.pnfolder.pnlibrary.core.plugin.module + +import org.pnfolder.pnlibrary.api.libraries.ModuleLibraries +import org.pnfolder.pnlibrary.api.libraries.ModuleLibrary +import org.pnfolder.pnlibrary.api.platform.PlatformType +import java.net.URL +import java.net.URLClassLoader + +/** + * The libraries of one module or plugin. [fetch] downloads one library and returns its isolated class loader, or `null` + * for a shared one; in the runtime it asks the Libby loader, in tests it is replaced. A module has its plugin's libraries + * as [parent]. + */ +internal class ModuleLibrariesImpl( + private val parent: ModuleLibraries? = null, + private val platform: PlatformType? = null, + private val fetch: (ModuleLibrary) -> ClassLoader?, +) : ModuleLibraries { + private val libraries = LinkedHashSet() + private var isolated: ClassLoader? = null + private val empty by lazy { URLClassLoader(emptyArray(), null) } + + override val classLoader: ClassLoader @Synchronized get() = isolated ?: empty + + override val loaded: List @Synchronized get() = libraries.toList() + + override val available: List get() = ((parent?.available ?: emptyList()) + loaded).distinct() + + @Synchronized + override fun load(library: ModuleLibrary) { + if (!library.appliesTo(platform)) return + if (library in libraries || parent?.isLoaded(library) == true) return + val holder = fetch(library) + if (holder != null) isolated = holder + libraries += library + } + + override fun loadClass(name: String): Class<*> { + val own = synchronized(this) { isolated } + if (own != null) { + try { + return own.loadClass(name) + } catch (_: ClassNotFoundException) { + // not here: the plugin's libraries, then the shared ones + } + } + return parent?.loadClass(name) ?: javaClass.classLoader.loadClass(name) + } + + @Synchronized + override fun remove(library: ModuleLibrary): Boolean = libraries.remove(library) + + companion object { + /** Libraries that [fetcher] downloads on behalf of [owner] and [plugin]; [classLoader] belongs to the runtime. */ + fun through( + owner: String, + classLoader: ClassLoader, + plugin: Any? = null, + parent: ModuleLibraries? = null, + fetcher: LibraryFetcher = LibraryFetcher.THROUGH_LIBBY, + platform: PlatformType? = null, + ) = ModuleLibrariesImpl(parent, platform) { library -> fetcher.fetch(classLoader, owner, plugin, library) } + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleLifecycleReporter.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleLifecycleReporter.kt index 8486f9c7e..732ec77b6 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleLifecycleReporter.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleLifecycleReporter.kt @@ -2,13 +2,13 @@ package org.pnfolder.pnlibrary.core.plugin.module import org.pnfolder.pnlibrary.api.logging.LoggingService import org.pnfolder.pnlibrary.api.logging.MessageBox -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterRegistry -import org.pnfolder.pnlibrary.api.plugin.LifecycleRow +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderAdapterRegistry import org.pnfolder.pnlibrary.api.plugin.ModuleId -import org.pnfolder.pnlibrary.api.plugin.PluginLifecycle -import org.pnfolder.pnlibrary.api.plugin.PluginMetadata -import org.pnfolder.pnlibrary.core.plugin.HidingLifecycleBox +import org.pnfolder.pnlibrary.api.plugin.lifecycle.LifecycleRow +import org.pnfolder.pnlibrary.api.plugin.lifecycle.PluginLifecycle +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata +/** Prints the startup and shutdown summary of a module and registers its placeholders on enable. */ internal class ModuleLifecycleReporter( private val owner: Any, private val moduleId: ModuleId, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMessages.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMessages.kt index 67654247e..075821e16 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMessages.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMessages.kt @@ -2,8 +2,9 @@ package org.pnfolder.pnlibrary.core.plugin.module import org.pnfolder.pnlibrary.api.logging.LoggingService import org.pnfolder.pnlibrary.api.logging.MessageBox -import org.pnfolder.pnlibrary.api.plugin.PluginMessages +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMessages +/** Plugin message helpers bound to one module owner. */ internal class ModuleMessages( private val owner: Any, private val logging: LoggingService, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetadataFactory.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetadataFactory.kt index dfcacc115..803627ec6 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetadataFactory.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetadataFactory.kt @@ -1,11 +1,12 @@ package org.pnfolder.pnlibrary.core.plugin.module import org.pnfolder.pnlibrary.api.plugin.ModuleId -import org.pnfolder.pnlibrary.api.plugin.PluginMetadata +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata import org.pnfolder.pnlibrary.common.jvm.JavaRuntime import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership +/** Builds module metadata from the definition, falling back to the native plugin descriptor. */ internal class ModuleMetadataFactory( private val ownership: PlatformOwnership, private val identity: PlatformIdentity, @@ -21,6 +22,7 @@ internal class ModuleMetadataFactory( platformImplementation = identity.implementationName, javaVersion = System.getProperty("java.version", "unknown"), javaFeature = JavaRuntime.feature, + description = definition.metadataDescription ?: nativeMetadata["description"]?.takeIf(String::isNotBlank), ) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/ModuleMetrics.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetrics.kt similarity index 94% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/ModuleMetrics.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetrics.kt index 96fea174a..a8fc5ecbe 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/ModuleMetrics.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetrics.kt @@ -1,10 +1,10 @@ -package org.pnfolder.pnlibrary.core.plugin +package org.pnfolder.pnlibrary.core.plugin.module -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter import org.pnfolder.pnlibrary.api.metrics.MetricsController -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.metrics.MetricsService import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.core.plugin.module.ModuleMetricsDefinition import java.util.concurrent.atomic.AtomicBoolean diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetricsDefinition.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetricsDefinition.kt index f3622768a..3e11721c4 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetricsDefinition.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetricsDefinition.kt @@ -1,9 +1,10 @@ package org.pnfolder.pnlibrary.core.plugin.module -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration import java.util.function.Consumer +/** Metrics settings declared by a module: providers, enabled flag and extra configurers. */ internal data class ModuleMetricsDefinition( val providers: List = emptyList(), val enabled: Boolean = false, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModulePreferences.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModulePreferences.kt new file mode 100644 index 000000000..4aee09463 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModulePreferences.kt @@ -0,0 +1,39 @@ +package org.pnfolder.pnlibrary.core.plugin.module + +import com.google.gson.Gson +import com.google.gson.JsonObject +import org.pnfolder.pnlibrary.common.io.AtomicFiles +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.nio.file.Path + +/** + * Which modules an administrator keeps switched off across restarts, saved as `modules/preferences.json` + * (`{"disabled": ["plugin:module"]}`). Without a [file] the choices live only in memory. + */ +internal class ModulePreferences(private val file: Path? = null) { + private val disabled = linkedSetOf() + + init { + file?.takeIf { Files.isRegularFile(it) }?.let { path -> + runCatching { + val root = Gson().fromJson(String(Files.readAllBytes(path), StandardCharsets.UTF_8), JsonObject::class.java) + root?.getAsJsonArray("disabled")?.forEach { disabled += it.asString } + } + } + } + + /** Whether the module starts with the server. */ + @Synchronized + fun autoStart(key: String): Boolean = key !in disabled + + /** Remembers the choice and writes it to disk. */ + @Synchronized + fun setAutoStart(key: String, enabled: Boolean) { + if (!(if (enabled) disabled.remove(key) else disabled.add(key))) return + val path = file ?: return + Files.createDirectories(path.parent) + val root = JsonObject().apply { add("disabled", Gson().toJsonTree(disabled.toList())) } + AtomicFiles.write(path, Gson().toJson(root).toByteArray(StandardCharsets.UTF_8)) + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleProductResolver.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleProductResolver.kt index 47a980e23..84162836c 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleProductResolver.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleProductResolver.kt @@ -1,10 +1,11 @@ package org.pnfolder.pnlibrary.core.plugin.module import org.pnfolder.pnlibrary.api.plugin.ModuleId -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor import org.pnfolder.pnlibrary.api.version.PnLibraryApi import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership +/** Resolves the product descriptor of a module from its definition or the native plugin. */ internal class ModuleProductResolver( private val platform: PlatformOwnership, ) { diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleResourceFactory.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleResourceFactory.kt index a619ce6d9..5f70bec6a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleResourceFactory.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleResourceFactory.kt @@ -6,33 +6,34 @@ import org.pnfolder.pnlibrary.api.currency.CurrencyStorageFactory import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticRegistration import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsService import org.pnfolder.pnlibrary.api.downloads.DownloadRegistration -import org.pnfolder.pnlibrary.api.events.EventScope -import org.pnfolder.pnlibrary.api.events.EventService +import org.pnfolder.pnlibrary.api.events.bus.EventScope +import org.pnfolder.pnlibrary.api.events.bus.EventService import org.pnfolder.pnlibrary.api.logging.LoggingService -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter import org.pnfolder.pnlibrary.api.metrics.MetricsService -import org.pnfolder.pnlibrary.api.metrics.TelemetryError +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.error.TelemetryError import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService import org.pnfolder.pnlibrary.api.plugin.ModuleId import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.api.tasks.TaskScope -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor import org.pnfolder.pnlibrary.api.updates.UpdateRegistration import org.pnfolder.pnlibrary.api.updates.UpdateService +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor import org.pnfolder.pnlibrary.config.ConfigurationRuntime -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup -import org.pnfolder.pnlibrary.core.cooldowns.InMemoryCooldowns -import org.pnfolder.pnlibrary.core.downloads.CompositeDownloadRegistration -import org.pnfolder.pnlibrary.core.downloads.DirectDownloads +import org.pnfolder.pnlibrary.core.downloads.dependencies.CompositeDownloadRegistration +import org.pnfolder.pnlibrary.core.downloads.fetch.DirectDownloads +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup import org.pnfolder.pnlibrary.core.metrics.ErrorPipeline import org.pnfolder.pnlibrary.core.placeholders.PlaceholderHub -import org.pnfolder.pnlibrary.core.plugin.ModuleMetrics +import org.pnfolder.pnlibrary.core.plugin.module.InMemoryCooldowns import org.pnfolder.pnlibrary.core.services.ServiceRegistry import org.pnfolder.pnlibrary.core.tasks.TaskService import org.pnfolder.pnlibrary.core.text.CachedComponents import org.pnfolder.pnlibrary.core.text.ComponentCache +import org.pnfolder.pnlibrary.core.text.MiniText import org.pnfolder.pnlibrary.currency.CurrencyRuntime +/** Creates the scoped resources of one module and rolls back already created ones if a later step fails. */ internal class ModuleResourceFactory( private val events: EventService, private val tasks: TaskService, @@ -47,6 +48,8 @@ internal class ModuleResourceFactory( private val directDownloads: DirectDownloads?, private val componentCache: ComponentCache, ) { + private val miniText = MiniText() + fun create( owner: Any, moduleId: ModuleId, @@ -70,7 +73,7 @@ internal class ModuleResourceFactory( try { taskScope = tasks.scope(owner, moduleKey) eventScope = events.scope(moduleKey, pluginId, moduleId) - configScope = configurations.scope(owner, moduleKey) + configScope = configurations.scope(owner, moduleKey, pluginId, moduleId) placeholderScope = placeholders.scope(moduleKey, definition.placeholderApiEnabled, pluginId.value, moduleId.value) currencyScope = currency.scope(moduleKey, placeholderScope) @@ -78,13 +81,17 @@ internal class ModuleResourceFactory( serviceScope.register(CurrencyStorageFactory::class.java, currency.storages) // Resolve the live session on every capture, including after disable/restart. - errorReporter = ErrorPipeline(object : ErrorReporter { - override fun capture(error: TelemetryError) { - metricsController?.sessionErrorReporter()?.capture(error) - } + val moduleLogger = logging.logger(owner, moduleId.value) + errorReporter = ErrorPipeline( + object : ErrorReporter { + override fun capture(error: TelemetryError) { + metricsController?.sessionErrorReporter()?.capture(error) + } - override fun close() = Unit - }) + override fun close() = Unit + }, + onForwardingFailure = { moduleLogger.warning("An error report could not be sent to the error tracker", it) }, + ) metricsController = ModuleMetrics( owner, metrics, @@ -110,7 +117,7 @@ internal class ModuleResourceFactory( logger = logging.logger(owner, moduleId.value), configs = configScope, placeholders = placeholderScope, - components = CachedComponents(placeholderScope, componentCache), + components = CachedComponents(placeholderScope, componentCache, miniText, { moduleLogger.warning(it) }), cooldowns = InMemoryCooldowns(), currency = currencyScope, metrics = metricsController, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleResources.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleResources.kt index ca48fe4d5..6872d1537 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleResources.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleResources.kt @@ -6,18 +6,19 @@ import org.pnfolder.pnlibrary.api.currency.CurrencyService import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticRegistration import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsService import org.pnfolder.pnlibrary.api.downloads.DownloadRegistration -import org.pnfolder.pnlibrary.api.events.EventScope +import org.pnfolder.pnlibrary.api.events.bus.EventScope import org.pnfolder.pnlibrary.api.logging.PnLogger -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter import org.pnfolder.pnlibrary.api.metrics.MetricsController +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.api.tasks.TaskScope import org.pnfolder.pnlibrary.api.text.ComponentService import org.pnfolder.pnlibrary.api.updates.UpdateRegistration -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup import org.pnfolder.pnlibrary.core.services.ServiceScope +/** Per-module resources (tasks, events, services, config, placeholders and so on) closed together with the module. */ internal class ModuleResources( val tasks: TaskScope, val events: EventScope, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleRuntimeSummary.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleRuntimeSummary.kt index 56f3ad44f..7cba41851 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleRuntimeSummary.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleRuntimeSummary.kt @@ -1,10 +1,11 @@ package org.pnfolder.pnlibrary.core.plugin.module -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration -import org.pnfolder.pnlibrary.api.plugin.PluginMetadata +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata import org.pnfolder.pnlibrary.api.updates.UpdateRegistration +/** Formats runtime facts of a module into short lines for the startup summary. */ internal object ModuleRuntimeSummary { fun platform(metadata: PluginMetadata): String = if (metadata.platformImplementation.equals(metadata.platform.displayName, ignoreCase = true)) { diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleServiceKey.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleServiceKey.kt new file mode 100644 index 000000000..cb87153e4 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleServiceKey.kt @@ -0,0 +1,20 @@ +package org.pnfolder.pnlibrary.core.plugin.module + +import org.pnfolder.pnlibrary.api.plugin.ModuleId +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.nio.charset.StandardCharsets +import java.security.MessageDigest + +/** Derives the service owner key of a live module registration. */ +internal fun moduleServiceKey(registrationId: Long, nativePlugin: PluginId, module: ModuleId): PluginId { + // The same plugin and module IDs may appear again after a reload. The registration ID + // keeps service ownership tied to one live plugin instance rather than its public name. + val identity = "${nativePlugin.value}\u0000${module.value}\u0000$registrationId" + val identityHash = MessageDigest.getInstance("SHA-256") + .digest(identity.toByteArray(StandardCharsets.UTF_8)) + .joinToString("") { byte -> "%02x".format(byte) } + + return PluginId.of( + "m-${nativePlugin.value.take(18)}-${module.value.take(18)}-${identityHash.take(16)}", + ) +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleServiceKeyFactory.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleServiceKeyFactory.kt deleted file mode 100644 index fa7ee0301..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleServiceKeyFactory.kt +++ /dev/null @@ -1,21 +0,0 @@ -package org.pnfolder.pnlibrary.core.plugin.module - -import org.pnfolder.pnlibrary.api.plugin.ModuleId -import org.pnfolder.pnlibrary.api.plugin.PluginId -import java.nio.charset.StandardCharsets -import java.security.MessageDigest - -internal object ModuleServiceKeyFactory { - fun create(registrationId: Long, nativePlugin: PluginId, module: ModuleId): PluginId { - // The same plugin and module IDs may appear again after a reload. The registration ID - // keeps service ownership tied to one live plugin instance rather than its public name. - val identity = "${nativePlugin.value}\u0000${module.value}\u0000$registrationId" - val identityHash = MessageDigest.getInstance("SHA-256") - .digest(identity.toByteArray(StandardCharsets.UTF_8)) - .joinToString("") { byte -> "%02x".format(byte) } - - return PluginId.of( - "m-${nativePlugin.value.take(18)}-${module.value.take(18)}-${identityHash.take(16)}", - ) - } -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ScenarioDefinitions.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ScenarioDefinitions.kt new file mode 100644 index 000000000..afe865958 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ScenarioDefinitions.kt @@ -0,0 +1,59 @@ +package org.pnfolder.pnlibrary.core.plugin.module + +import org.pnfolder.pnlibrary.api.scenario.actions.Action +import org.pnfolder.pnlibrary.api.scenario.actions.DefinitionConflict +import org.pnfolder.pnlibrary.api.scenario.actions.ScenarioLookup +import org.pnfolder.pnlibrary.api.scenario.expression.ExpressionFunction +import org.pnfolder.pnlibrary.api.scenario.requirements.Requirement + +/** Named actions, requirements and expression functions of one level (one module, or the whole library). */ +internal class ScenarioDefinitions : ScenarioLookup { + private class Entry(val value: T, val owner: String) + + private val actions = HashMap>() + private val requirements = HashMap>() + private val functions = HashMap>() + + @Synchronized override fun action(name: String): Action? = actions[name]?.value + @Synchronized override fun requirement(name: String): Requirement? = requirements[name]?.value + @Synchronized override fun function(name: String): ExpressionFunction? = functions[name]?.value + + fun defineAction(name: String, value: Action, owner: String, conflict: DefinitionConflict) = + define(actions, "action", name, value, owner, conflict) + + fun defineRequirement(name: String, value: Requirement, owner: String, conflict: DefinitionConflict) = + define(requirements, "requirement", name, value, owner, conflict) + + fun defineFunction(name: String, value: ExpressionFunction, owner: String, conflict: DefinitionConflict) = + define(functions, "function", name, value, owner, conflict) + + @Synchronized + private fun define( + map: MutableMap>, kind: String, rawName: String, value: T, owner: String, conflict: DefinitionConflict, + ): AutoCloseable { + val name = rawName.trim().lowercase() + require(NAME.matches(name)) { "A $kind name may contain only letters, digits, dots, hyphens and underscores, but was '$rawName'" } + val entry = Entry(value, owner) + val existing = map[name] + if (existing != null) when (conflict) { + DefinitionConflict.KEEP -> return AutoCloseable { } + DefinitionConflict.FAIL -> throw IllegalArgumentException("The $kind '$name' is already defined by $owner") + DefinitionConflict.REPLACE -> require(existing.owner == owner) { + "The $kind '$name' belongs to ${existing.owner} and cannot be replaced by $owner" + } + } + map[name] = entry + return AutoCloseable { synchronized(this) { if (map[name] === entry) map.remove(name) } } + } + + private companion object { + val NAME = Regex("[a-z0-9][a-z0-9_.-]{0,63}") + } +} + +/** Looks in the module's own definitions first, then in the ones shared by the whole library. */ +internal class LayeredLookup(private val own: ScenarioLookup, private val shared: ScenarioLookup) : ScenarioLookup { + override fun action(name: String) = own.action(name) ?: shared.action(name) + override fun requirement(name: String) = own.requirement(name) ?: shared.requirement(name) + override fun function(name: String) = own.function(name) ?: shared.function(name) +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/proxy/ProxyLink.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/proxy/ProxyLink.kt index e8b9fdd29..b372ce1f8 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/proxy/ProxyLink.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/proxy/ProxyLink.kt @@ -4,13 +4,13 @@ import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.core.commands.proxy.ProxyControlCommand import org.pnfolder.pnlibrary.core.link.Link import org.pnfolder.pnlibrary.core.link.LinkReceiver -import org.pnfolder.pnlibrary.core.link.LinkSecret -import org.pnfolder.pnlibrary.core.link.LinkTransport -import org.pnfolder.pnlibrary.core.link.NetworkPublisher -import org.pnfolder.pnlibrary.core.link.RemoteExecutor -import org.pnfolder.pnlibrary.core.menu.MenuDataServer +import org.pnfolder.pnlibrary.core.link.remote.LinkTransport +import org.pnfolder.pnlibrary.core.link.remote.RemoteExecutor +import org.pnfolder.pnlibrary.core.link.report.NetworkPublisher +import org.pnfolder.pnlibrary.core.link.wire.LinkSecret import org.pnfolder.pnlibrary.core.menu.OwnerInfo import org.pnfolder.pnlibrary.core.menu.ProxyMenu +import org.pnfolder.pnlibrary.core.menu.data.MenuDataServer import java.nio.file.Path /** @@ -21,6 +21,8 @@ import java.nio.file.Path * @param folder the pnLibrary folder, where `link.key` and `groups.tsv` live * @param warn receives a problem with `link.key` * @param describe the plugin behind a registration owner, or null + * @param holds whether the player of that name, connected to this proxy, has the permission; menu actions asked + * by a game server run only for such a player * @param platformName the proxy software and its version, shown in the network map * @param players how many players are online on the whole proxy * @param broadcast sends the network map to every game server @@ -31,13 +33,14 @@ class ProxyLink( warn: (String) -> Unit, transport: LinkTransport, describe: (Any?) -> OwnerInfo?, + holds: (viewer: String, permission: String) -> Boolean, platformName: () -> String, players: () -> Int, private val broadcast: (ByteArray) -> Unit, ) : AutoCloseable { private val link = Link(LinkSecret.readOrCreate(folder, warn), folder, transport) private val control = ProxyControlCommand(library, link) - private val data: MenuDataServer = ProxyMenu.server(library, link, control, describe) + private val data: MenuDataServer = ProxyMenu.server(library, link, control, describe, holds) private val publisher = if (link.enabled) NetworkPublisher(library, link, platformName, players) else null /** Hand it the messages the platform receives from game servers. */ diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/PolicyCompilers.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/PolicyCompilers.kt index 73133c820..8e27b1606 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/PolicyCompilers.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/PolicyCompilers.kt @@ -1,5 +1,6 @@ package org.pnfolder.pnlibrary.core.remote +import org.pnfolder.pnlibrary.spi.libraries.OptionalLibrary import java.nio.charset.StandardCharsets import java.nio.file.Path import javax.tools.Diagnostic @@ -9,8 +10,8 @@ import javax.tools.JavaFileObject import javax.tools.ToolProvider /** - * Compiles a policy with the server's javac, or with ECJ when the server runs a JRE without a compiler. The platform - * loader puts ECJ on the plugin classpath at start (see LibraryLoader), so it is only looked up here. + * Compiles a policy with the server's javac, or with ECJ when the server runs a JRE without a compiler. The first time one is needed, the + * loader downloads ECJ through Libby (see LibraryLoader); a server with javac downloads nothing. */ internal class PolicyCompilers( private val systemCompiler: () -> JavaCompiler? = ToolProvider::getSystemJavaCompiler, @@ -26,11 +27,10 @@ internal class PolicyCompilers( } private fun ecj(): JavaCompiler { - val type = try { - Class.forName(ECJ_COMPILER, true, ecjLoader) - } catch (missing: ClassNotFoundException) { - throw IllegalStateException("Java compiler is unavailable: the server runs a JRE and ECJ was not loaded at start", missing) + check(OptionalLibrary("compiler", ECJ_COMPILER, ecjLoader).ensure()) { + "Java compiler is unavailable: the server runs a JRE and ECJ could not be downloaded" } + val type = Class.forName(ECJ_COMPILER, true, ecjLoader) return type.getDeclaredConstructor().newInstance() as JavaCompiler } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyEngine.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyEngine.kt index bc71c285f..6bff57e8a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyEngine.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyEngine.kt @@ -13,7 +13,6 @@ import java.nio.file.Files import java.nio.file.Paths import java.util.Comparator -/** Shared source loader used by every platform adapter. */ internal class RemotePolicyEngine(private val compilers: PolicyCompilers) { fun check(url: String, context: RemotePolicyContext): RemotePolicyResult { diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyFailureInterpreter.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyFailureInterpreter.kt index 35e3c70fe..f598e184e 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyFailureInterpreter.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyFailureInterpreter.kt @@ -12,7 +12,7 @@ internal object RemotePolicyFailureInterpreter { if (isNetwork(error)) return "Нет доступа к интернету: политику не удалось скачать" val message = error.message.orEmpty() if (isCompilerMissing(error)) { - return "На сервере нет компилятора Java (это JRE), а запасной не загрузился при старте: проверьте интернет и перезапустите сервер" + return "На сервере нет компилятора Java (это JRE), а запасной скачать не удалось: проверьте интернет сервера и повторите" } if (message.contains("compil", ignoreCase = true)) { return "Не удалось скомпилировать политику" diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyMonitor.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyMonitor.kt index b917a8318..01e53a566 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyMonitor.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyMonitor.kt @@ -2,15 +2,15 @@ package org.pnfolder.pnlibrary.core.remote import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.api.plugin.ModuleContext -import org.pnfolder.pnlibrary.api.plugin.PluginMetadata +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata import org.pnfolder.pnlibrary.api.remote.DenyAction import org.pnfolder.pnlibrary.api.remote.PolicyErrorAction import org.pnfolder.pnlibrary.api.remote.RemotePolicyContext import org.pnfolder.pnlibrary.api.remote.RemotePolicyExplanation import org.pnfolder.pnlibrary.api.remote.RemotePolicySettings -import org.pnfolder.pnlibrary.api.tasks.TaskExecution import org.pnfolder.pnlibrary.api.tasks.TaskScope -import org.pnfolder.pnlibrary.api.tasks.TaskSpec +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.spi.platform.PlatformExecution import org.pnfolder.pnlibrary.spi.platform.PlatformOwnerControl diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyNoticeRenderer.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyNoticeRenderer.kt index 6d81091d7..8d352722d 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyNoticeRenderer.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyNoticeRenderer.kt @@ -1,7 +1,7 @@ package org.pnfolder.pnlibrary.core.remote -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.plugin.PluginMetadata +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata import org.pnfolder.pnlibrary.api.remote.DenyAction import org.pnfolder.pnlibrary.api.remote.RemotePolicyExplanation import org.pnfolder.pnlibrary.api.remote.RemotePolicyResult @@ -10,7 +10,7 @@ import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity import org.pnfolder.pnlibrary.common.text.RussianText import org.pnfolder.pnlibrary.console.ConsoleCard import org.pnfolder.pnlibrary.console.ConsoleTree -import org.pnfolder.pnlibrary.core.ui.ConsoleStyle +import org.pnfolder.pnlibrary.core.text.ConsoleStyle import org.pnfolder.pnlibrary.spi.platform.PlatformLogging /** Prints the console card with the result of a remote compatibility check. */ diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/DiagnosticsSettings.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/DiagnosticsSettings.kt deleted file mode 100644 index 783cbb2e5..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/DiagnosticsSettings.kt +++ /dev/null @@ -1,100 +0,0 @@ -package org.pnfolder.pnlibrary.core.runtime - -import org.pnfolder.pnlibrary.api.config.ConfigComment -import org.pnfolder.pnlibrary.api.config.ConfigNewLine -import org.pnfolder.pnlibrary.api.config.ConfigRange -import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig -import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal - -/** - * Content of `plugins/pnLibrary/config.yml`: only what an administrator has a reason to change. - * - * Everything else (what goes into a report, how long reports and history are kept, how a report is sent, the wording of - * the standard command answers) is fixed by the defaults of [PnLibraryConfig], so there is nothing to get wrong. - */ -@ConfigComment( - "pnLibrary: настройки (config.yml)", - "", - "Диагностический отчёт собирает сведения о сервере и плагинах, чтобы упростить поддержку.", - "Отчёт всегда сохраняется на сервере и отправляется в службу поддержки только в зашифрованном виде.", - "В отчёт всегда входят конфигурации плагинов (секретные значения скрываются) и последние записи журнала.", -) -internal class DiagnosticsSettings { - @field:ConfigComment( - "=== Приватность ===", - "Скрывать ли в отчёте личные данные игроков: имена, UUID, адреса, пинг и названия текущих серверов.", - "По умолчанию false: данные показываются, так проблему разобрать проще. Поставьте true, чтобы скрыть их.", - ) - var privacy: Boolean = false - - @field:ConfigComment( - "Значения в файлах настроек плагинов, которые никогда не попадут в отчёт.", - "Пароли, токены и ключи pnLibrary скрывает сама. Здесь перечисляют то, что скрыть нужно дополнительно.", - "", - "Как заполнять. Допустим, у плагина есть файл plugins/pnExample/config.yml:", - "", - " database:", - " host: localhost", - " password: qwerty123 <- не должен попасть в отчёт", - " discord:", - " webhook-url: https://... <- и это тоже", - " messages:", - " welcome: Привет <- а это можно показывать", - "", - "Тогда ниже пишем путь к каждому значению: раздел, точка, ключ (от корня файла).", - "Путь без названия файла действует на файлы ВСЕХ плагинов. Чтобы скрыть значение только в одном файле", - "одного плагина, впереди пишут папка плагина, файл и двоеточие:", - "", - "excluded-paths:", - " - database.password # во всех файлах всех плагинов", - " - pnExample/config.yml:discord.webhook-url # только в этом файле этого плагина", - " - pnShop/messages.yml:database # весь раздел database, только в этом файле", - "", - "Если указать только раздел (например, database), скроется весь раздел целиком.", - "Плагин может сам пометить свои поля аннотацией @ConfigSecret: тогда они скрыты без записи здесь.", - ) - var excludedPaths: List = emptyList() - - @field:ConfigNewLine - @field:ConfigComment( - "=== Хранение ===", - "Сколько дней хранить историю диагностики (от 30 до 365).", - ) - @field:ConfigRange(min = 30.0, max = 365.0) - var historyRetentionDays: Int = 30 - - @field:ConfigNewLine - @field:ConfigComment( - "=== Журнал событий ===", - "Писать ли в журнал предупреждения и ошибки плагинов, которые не подключены к pnLibrary.", - "По умолчанию выключено: в журнале только pnLibrary и плагины, которые пишут через неё.", - ) - var journalForeignPlugins: Boolean = false - - @field:ConfigNewLine - @field:ConfigComment( - "=== Время ===", - "Часовой пояс для всех времён, которые показывает pnLibrary (журнал, обновления).", - "Хранится время всегда в UTC, поэтому смена пояса ничего не портит. Примеры: UTC, Europe/Moscow.", - "При создании файла подставляется часовой пояс сервера.", - ) - var timeZone: String = java.time.ZoneId.systemDefault().id - - @field:ConfigNewLine - @field:ConfigComment( - "=== Сообщения ===", - "Что видит игрок, если у него нет права на команду pnLibrary или другого плагина,", - "у которого нет собственного сообщения (до 256 символов).", - ) - var noPermissionMessage: String = "Недостаточно прав для этой команды." - - fun toConfig(): PnLibraryConfig = PnLibraryConfig( - historyRetentionDays = historyRetentionDays, - excludedPaths = excludedPaths.toList(), - privacy = privacy, - noPermissionMessage = noPermissionMessage, - journalForeignPlugins = journalForeignPlugins, - timeZone = timeZone.trim().takeIf { runCatchingNonFatal { java.time.ZoneId.of(it) }.isSuccess } - ?: java.time.ZoneId.systemDefault().id, - ) -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/LibraryInfoCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/LibraryInfoCommand.kt index a0f2b1e55..4ec95b4c8 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/LibraryInfoCommand.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/LibraryInfoCommand.kt @@ -1,10 +1,10 @@ package org.pnfolder.pnlibrary.core.runtime import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity import org.pnfolder.pnlibrary.api.version.PnLibraryApi diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryConfigLoader.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryConfigLoader.kt deleted file mode 100644 index 3313b3eef..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryConfigLoader.kt +++ /dev/null @@ -1,18 +0,0 @@ -package org.pnfolder.pnlibrary.core.runtime - -import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig -import org.pnfolder.pnlibrary.config.LibraryConfigFiles -import java.nio.file.Path -import java.util.function.Supplier - -/** Loads the installed runtime configuration from `plugins/pnLibrary/config.yml`. */ -internal object PnLibraryConfigLoader { - @JvmStatic - fun load(dataFolder: Path, warning: (String) -> Unit = {}): PnLibraryConfig = - LibraryConfigFiles.load( - file = dataFolder.resolve("config.yml"), - type = DiagnosticsSettings::class.java, - defaults = Supplier { DiagnosticsSettings() }, - warning = warning, - ).toConfig() -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryImpl.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryImpl.kt index b27c35df7..7b148c8e7 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryImpl.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryImpl.kt @@ -1,21 +1,22 @@ package org.pnfolder.pnlibrary.core.runtime import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.activity.ActivityService import org.pnfolder.pnlibrary.api.audiences.AudienceService import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition import org.pnfolder.pnlibrary.api.commands.CommandRegistration +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition import org.pnfolder.pnlibrary.api.config.ConfigurationService import org.pnfolder.pnlibrary.api.diagnostics.DebugRequest -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticReport -import org.pnfolder.pnlibrary.api.events.EventService +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticReport +import org.pnfolder.pnlibrary.api.events.bus.EventService import org.pnfolder.pnlibrary.api.expansions.ExpansionManager +import org.pnfolder.pnlibrary.api.logging.LogLevel import org.pnfolder.pnlibrary.api.logging.LoggingService import org.pnfolder.pnlibrary.api.metrics.MetricsService import org.pnfolder.pnlibrary.api.metrics.PluginMetrics -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterRegistry -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderValueStore +import org.pnfolder.pnlibrary.api.network.NetworkProxy +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderValueStore +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderAdapterRegistry import org.pnfolder.pnlibrary.api.platform.PlatformProvider import org.pnfolder.pnlibrary.api.plugin.PluginRegistry import org.pnfolder.pnlibrary.api.runtime.PnLibrary @@ -23,32 +24,36 @@ import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity import org.pnfolder.pnlibrary.api.runtime.PnLibraryProvider import org.pnfolder.pnlibrary.api.services.ServiceManager -import org.pnfolder.pnlibrary.api.tasks.TaskId import org.pnfolder.pnlibrary.api.tasks.TaskScope -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot import org.pnfolder.pnlibrary.api.updates.UpdateService import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.common.time.DisplayZone -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup -import org.pnfolder.pnlibrary.core.commands.standardCommandFeedback +import org.pnfolder.pnlibrary.core.commands.engine.standardCommandFeedback +import org.pnfolder.pnlibrary.core.commands.settings.SettingsCommand import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticsRegistry -import org.pnfolder.pnlibrary.core.diagnostics.configFileDiagnostics -import org.pnfolder.pnlibrary.core.diagnostics.diagnosticCommand +import org.pnfolder.pnlibrary.core.diagnostics.command.diagnosticCommand +import org.pnfolder.pnlibrary.core.diagnostics.config.reportConfigFile import org.pnfolder.pnlibrary.core.events.EventDispatcher -import org.pnfolder.pnlibrary.core.events.EventHistory +import org.pnfolder.pnlibrary.core.events.inspect.history.EventHistory +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup import org.pnfolder.pnlibrary.core.journal.JournalDetail import org.pnfolder.pnlibrary.core.journal.JournalGroup +import org.pnfolder.pnlibrary.core.lifecycle.MountableCommands import org.pnfolder.pnlibrary.core.lifecycle.RuntimeResources import org.pnfolder.pnlibrary.core.lifecycle.registerRuntimeCommand +import org.pnfolder.pnlibrary.core.lifecycle.taskSnapshots import org.pnfolder.pnlibrary.core.logging.ModuleLogging -import org.pnfolder.pnlibrary.core.metrics.MetricsSessions +import org.pnfolder.pnlibrary.core.metrics.session.MetricsSessions import org.pnfolder.pnlibrary.core.observability.SupportRuntime -import org.pnfolder.pnlibrary.core.placeholders.LibraryPlaceholders +import org.pnfolder.pnlibrary.core.placeholders.builtin.LibraryPlaceholders import org.pnfolder.pnlibrary.core.placeholders.placeholdersCommand -import org.pnfolder.pnlibrary.core.platform.NativePlatform +import org.pnfolder.pnlibrary.core.plugin.LibraryWords import org.pnfolder.pnlibrary.core.plugin.PluginRegistryImpl import org.pnfolder.pnlibrary.core.plugin.SharedFeatures +import org.pnfolder.pnlibrary.core.plugin.module.ModulePreferences import org.pnfolder.pnlibrary.core.remote.RemotePolicyMonitor import org.pnfolder.pnlibrary.core.remote.RemotePolicyNoticeRenderer import org.pnfolder.pnlibrary.core.runtime.details.RuntimeDiagnosticsAssembler @@ -56,12 +61,19 @@ import org.pnfolder.pnlibrary.core.runtime.details.RuntimeFeatureSet import org.pnfolder.pnlibrary.core.runtime.details.RuntimeJournal import org.pnfolder.pnlibrary.core.runtime.details.RuntimeMetricsBootstrap import org.pnfolder.pnlibrary.core.runtime.lifecycle.RuntimeShutdownPlan +import org.pnfolder.pnlibrary.core.runtime.platform.NativePlatform import org.pnfolder.pnlibrary.core.runtime.platform.PlatformRegistration import org.pnfolder.pnlibrary.core.runtime.platform.PlatformRuntimeContext import org.pnfolder.pnlibrary.core.runtime.platform.PlatformServiceSet +import org.pnfolder.pnlibrary.core.settings.LegacySettingsImport +import org.pnfolder.pnlibrary.core.settings.LibraryInfoFiles +import org.pnfolder.pnlibrary.core.settings.SettingPickerHook +import org.pnfolder.pnlibrary.core.settings.SettingsStore import org.pnfolder.pnlibrary.core.stats.StatsRuntime import org.pnfolder.pnlibrary.core.tasks.TaskControl import org.pnfolder.pnlibrary.spi.commands.PlatformCommandDispatcher +import org.pnfolder.pnlibrary.updates.paths.LegacyPathsMigration +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths import java.nio.file.Path import java.nio.file.Paths import java.time.ZoneId @@ -76,7 +88,7 @@ internal class PnLibraryImpl( override val owner: Any, private val platform: PlatformRuntimeContext, override val diagnostics: DiagnosticsRegistry, - private val config: PnLibraryConfig = PnLibraryConfig(), + presetConfig: PnLibraryConfig? = null, private val onClose: () -> Unit = {}, ) : PnLibrary, PlatformRegistration, RuntimeResources { private val closedFlag = AtomicBoolean(false) @@ -88,13 +100,35 @@ internal class PnLibraryImpl( val dataFolder: Path = platform.dataFolder ?: platform.ownership.ownerDataFolder(owner) ?: Paths.get("plugins", owner.javaClass.simpleName) + init { + org.pnfolder.pnlibrary.core.commands.modules.DiskUsage.pluginsFolder = dataFolder.toAbsolutePath().parent + } + private val paths = LibraryPaths(dataFolder) + + /** Every setting an administrator may change; the command `/pn settings` and the menu edit it. */ + private val settings: SettingsStore + private val config: PnLibraryConfig init { - DisplayZone.zone = ZoneId.of(config.timeZone) + val warn = { text: String -> platform.logging.log(owner, LogLevel.WARNING, text) } + // The old files are moved into data and read once, before the settings are used. + LegacyPathsMigration(paths, warn).run() + settings = SettingsStore(paths.settings, warn).also { LegacySettingsImport(paths, warn).run(it) } + config = presetConfig ?: settings.config() + DisplayZone.zone = ZoneId.of(settings.current().timeZone) + settings.onChange { DisplayZone.zone = ZoneId.of(it.timeZone) } + // Help and settings overview for administrators: written again at every start and after every change. + LibraryInfoFiles(paths, settings::values, version, warning = warn).also { files -> + files.refresh() + settings.onChange { files.refreshSettings() } + } } // Support and journal come first: every later part reports its failures through them. - private val journalRuntime = RuntimeJournal(dataFolder, config, platform.ownership, startedAtMillis, EVENTS_COMMAND) + private val journalRuntime = RuntimeJournal( + paths.journal, config, platform.ownership, startedAtMillis, EVENTS_COMMAND, + onWriteFailure = ::reportJournalFailure, + ) // Written by init and close, read by error reports from any thread. @Volatile private var libraryMetrics: PluginMetrics? = null @@ -107,7 +141,7 @@ internal class PnLibraryImpl( platformLogging = platform.logging, diagnostics = diagnostics, config = config, - dataFolder = dataFolder, + paths = paths, runtimeDiagnostics = { runtimeDiagnostics.assemble() }, journal = journalRuntime::record, onRuntimeError = ::reportRuntimeError, @@ -122,8 +156,12 @@ internal class PnLibraryImpl( capture = support.capture, ) - private val features = RuntimeFeatureSet(platform, dataFolder, support.capture).also { set -> - set.configurations.fileListener = configFileDiagnostics(diagnostics) + private val features = RuntimeFeatureSet(owner, platform, paths, support.capture, settings).also { set -> + set.configurations.fileListener = { file -> + val handles = listOfNotNull(diagnostics.reportConfigFile(file), set.updates.databaseSources.register(file)) + AutoCloseable { handles.forEach(AutoCloseable::close) } + } + LibraryWords.register(set.configurations.scope(owner)) } private val platformServices = PlatformServiceSet( commandAdapter = platform.commandAdapter, @@ -131,19 +169,24 @@ internal class PnLibraryImpl( taskAdapter = platform.taskAdapter, platformLogging = support.capture, taskHistoryCapacity = config.taskHistoryCapacity, - taskHistoryFile = dataFolder.resolve("task-history.tsv"), + taskHistoryFile = paths.taskHistory, errorLogger = support::recordRuntimeError, commandFeedback = standardCommandFeedback(config), + onAudienceFailure = { error -> + support.recordRuntimeError(owner, "[pnLibrary/audiences] A message could not be delivered to a player", error) + }, ) private val tasks = platformServices.tasks private val commands = platformServices.commands private val eventService = EventDispatcher( - EventHistory(dataFolder.resolve("event-history.tsv"), config.eventHistoryDays, { DisplayZone.zone }), + EventHistory( + paths.eventHistory, config.eventHistoryDays, { DisplayZone.zone }, + onFailure = { support.recordRuntimeError(owner, "[pnLibrary/events] The event history could not be read or saved", it) }, + ), ) { pluginId, message, error -> support.recordRuntimeError(owner, "[$pluginId] $message", error) } private val platformProvider = NativePlatform() override val observability get() = support.service - override val activity: ActivityService get() = support.service override val metrics: MetricsService get() = metricsService override val configurations: ConfigurationService get() = features.configurations override val updates: UpdateService get() = features.updates @@ -153,6 +196,7 @@ internal class PnLibraryImpl( override val expansions: ExpansionManager get() = features.expansions override val events: EventService get() = eventService override val platforms: PlatformProvider get() = platformProvider + override val proxy: NetworkProxy? = platform.networkProxy override val placeholderAdapters: PlaceholderAdapterRegistry get() = features.placeholders override val placeholderValues: PlaceholderValueStore get() = features.placeholderValues @@ -172,6 +216,7 @@ internal class PnLibraryImpl( shared = SharedFeatures(features.placeholders, features.currency, features.expansions, features.libraryExpansions), commands = commands, directDownloads = features.downloads, + modulePreferences = ModulePreferences(dataFolder.resolve("modules").resolve("preferences.json")), ) private val runtimeDiagnostics: RuntimeDiagnosticsAssembler = RuntimeDiagnosticsAssembler( version = version, @@ -187,7 +232,9 @@ internal class PnLibraryImpl( commands = commands, journal = journalRuntime::summary, ) - private val stats = StatsRuntime(::taskSnapshots, { events.inspector.events() }, journalRuntime.store) + private val stats = StatsRuntime(::taskSnapshots, { events.inspector.events() }, journalRuntime.store) { error -> + support.recordRuntimeError(owner, "[pnLibrary/stats] Could not record statistics", error) + } private val mountable = LinkedHashMap() fun init() { @@ -200,10 +247,11 @@ internal class PnLibraryImpl( ).start() stats.start() // The platform's `/pn` control command mounts these as its subcommands. - mountable["debug"] = diagnosticCommand(this, "/pn debug") - mountable["events"] = journalRuntime.command() - mountable["stats"] = stats.command() - mountable["placeholders"] = placeholdersCommand(features.placeholders) + mountable[MountableCommands.DEBUG] = diagnosticCommand(this, "/pn debug") + mountable[MountableCommands.EVENTS] = journalRuntime.command() + mountable[MountableCommands.STATS] = stats.command() + mountable[MountableCommands.PLACEHOLDERS] = placeholdersCommand(features.placeholders) + mountable[MountableCommands.SETTINGS] = SettingsCommand(settings, settingPicker).definition() LibraryPlaceholders(features.placeholders, startedAtMillis, { plugins.all().size }, stats::values).register() registerRuntimeCommand(libraryInfoCommand(this, platform.identity) { platform.ownership.ownerDetails(owner)["version"] ?: "неизвестна" @@ -253,6 +301,12 @@ internal class PnLibraryImpl( override fun registerPlatform(type: Class, implementation: T): AutoCloseable = platformProvider.register(type, implementation) + override fun dependencyDownloads() = features.downloads + + override fun librarySettings(): SettingsStore = settings + + override val settingPicker = SettingPickerHook() + override fun taskSnapshots(): List = tasks.query().filterNot { it.hidden } override fun cancelTask(id: String): TaskControl = @@ -272,6 +326,12 @@ internal class PnLibraryImpl( override fun placeholderInfos() = features.placeholders.describe() + /** The journal cannot record its own failure, so the console and the error tracker get it directly. */ + private fun reportJournalFailure(error: Throwable) { + platform.logging.console(owner, "[pnLibrary/journal] Could not write to the journal: ${error.javaClass.simpleName}: ${error.message}") + reportRuntimeError(owner, error) + } + private fun reportRuntimeError(logOwner: Any, error: Throwable) { libraryMetrics?.errorReporter?.capture( throwable = error, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryLauncher.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryLauncher.kt index 036860f0b..2b353eed3 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryLauncher.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryLauncher.kt @@ -30,7 +30,7 @@ internal object PnLibraryLauncher { * * @param owner native plugin instance that owns the runtime * @param platform prepared platform capabilities from the native boundary - * @param config already validated runtime configuration + * @param config a ready runtime configuration; `null` builds it from the stored settings (`data/settings.json`) * @return the active runtime, which may be an instance created by an earlier call */ @JvmStatic @@ -39,7 +39,7 @@ internal object PnLibraryLauncher { fun bootstrap( owner: Any, platform: PlatformRuntimeContext, - config: PnLibraryConfig = PnLibraryConfig(), + config: PnLibraryConfig? = null, ): PnLibrary { requireNotNull(owner) { "Owner plugin must not be null" } requireNotNull(platform) { "Platform context must not be null" } @@ -50,7 +50,7 @@ internal object PnLibraryLauncher { owner = owner, platform = platform, diagnostics = globalRegistry, - config = config, + presetConfig = config, onClose = { instance = null }, ) instance = created diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryRuntimeHost.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryRuntimeHost.kt index b384cb442..e6799caa1 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryRuntimeHost.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryRuntimeHost.kt @@ -179,5 +179,68 @@ class PnLibraryRuntimeHost private constructor( throw error } } + + } +} + +/** + * Entry point for starting a pnLibrary runtime. + * + * ```kotlin + * val host = PnLibraryRuntime.builder() + * .owner(plugin) + * .adapter(platformAdapter) + * .platform(velocityPlatformImpl) + * .launch(platformAdapter::markReady) + * ``` + */ +class PnLibraryRuntime private constructor() { + + companion object { + @JvmStatic + fun builder(): Builder = Builder() + } + + class Builder internal constructor() { + private var owner: Any? = null + private var adapter: PlatformAdapter? = null + private val registrations = mutableListOf<(PnLibraryRuntimeHost) -> Unit>() + + fun owner(owner: Any): Builder { + this.owner = owner + return this + } + + fun adapter(adapter: PlatformAdapter): Builder { + this.adapter = adapter + return this + } + + inline fun platform(implementation: T): Builder = + platform(T::class.java, implementation) + + fun platform(type: Class, implementation: T): Builder { + registrations.add { host -> host.registerPlatform(type, implementation) } + return this + } + + fun launch(onReady: () -> Unit = {}): PnLibraryRuntimeHost { + val owner = requireNotNull(owner) { "owner is not set" } + val adapter = requireNotNull(adapter) { "adapter is not set" } + val host = try { + PnLibraryRuntimeHost.start(owner, adapter) + } catch (error: Throwable) { + runCatchingNonFatal { adapter.close() }.onFailure(error::addSuppressed) + throw error + } + return try { + registrations.forEach { it(host) } + onReady() + host + } catch (error: Throwable) { + runCatchingNonFatal { host.close() }.onFailure(error::addSuppressed) + throw error + } + } } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/ProxyRuntime.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/ProxyRuntime.kt new file mode 100644 index 000000000..7bf21e6dc --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/ProxyRuntime.kt @@ -0,0 +1,99 @@ +package org.pnfolder.pnlibrary.core.runtime + +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup +import org.pnfolder.pnlibrary.core.link.LinkReceiver +import org.pnfolder.pnlibrary.core.link.wire.LinkCodec +import org.pnfolder.pnlibrary.core.menu.OwnerInfo +import org.pnfolder.pnlibrary.core.proxy.ProxyLink +import org.pnfolder.pnlibrary.core.updates.catalog.ProxyUpdateReminder +import org.pnfolder.pnlibrary.spi.platform.ProxyPlatformAdapter +import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskHandle +import java.time.Duration + +/** + * Shared runtime logic for all proxy platforms (Velocity, BungeeCord). + * + * Uses the platform adapter for scheduling and proxy access, plus two platform-specific + * hooks — [registerLinkReceiver] and [describe] — that cannot go through the adapter + * because their types live in core rather than spi. + */ +class ProxyRuntime( + private val adapter: ProxyPlatformAdapter, + private val registerLinkReceiver: (LinkReceiver) -> AutoCloseable, + private val describe: (Any?) -> OwnerInfo?, +) : AutoCloseable { + private val proxy get() = adapter.networkProxy + + private var link: ProxyLink? = null + private var linkListener: AutoCloseable? = null + private var networkTask: PlatformTaskHandle? = null + private var reminderTask: PlatformTaskHandle? = null + + /** Connects to the game servers and starts the periodic tasks; [close] undoes whatever got started. */ + fun start(host: PnLibraryRuntimeHost) { + connectLink(host) + startUpdateReminder(host) + } + + private fun connectLink(host: PnLibraryRuntimeHost) { + val proxyLink = createLink(host) + proxy.registerChannel(LinkCodec.CHANNEL) + linkListener = registerLinkReceiver(proxyLink.receiver) + link = proxyLink + + if (!proxyLink.announces) return + networkTask = adapter.taskAdapter.buildTask() + .task(proxyLink::announce) + .delay(Duration.ofSeconds(ProxyLink.NETWORK_DELAY_SECONDS)) + .every(Duration.ofSeconds(ProxyLink.NETWORK_PERIOD_SECONDS)) + .schedule() + } + + private fun createLink(host: PnLibraryRuntimeHost) = ProxyLink( + library = host.library, + folder = adapter.dataFolder, + warn = adapter::warn, + transport = { name, bytes -> proxy.server(name)?.send(LinkCodec.CHANNEL, bytes) ?: false }, + describe = describe, + holds = { viewer, permission -> proxy.player(viewer)?.hasPermission(permission) == true }, + platformName = { "${proxy.name} ${proxy.version}" }, + players = { proxy.playerCount }, + broadcast = { bytes -> + proxy.servers.forEach { runCatchingNonFatal { it.send(LinkCodec.CHANNEL, bytes) } } + }, + ) + + private fun startUpdateReminder(host: PnLibraryRuntimeHost) { + val period = Duration.ofSeconds(ProxyUpdateReminder.INTERVAL_SECONDS) + reminderTask = adapter.taskAdapter.buildTask() + .task { + proxy.players + .filter { ProxyUpdateReminder.canSee(it::hasPermission) } + .forEach { ProxyUpdateReminder.send(host.library, it.uniqueId) } + } + .delay(period) + .every(period) + .schedule() + } + + /** Stops scheduled tasks, unregisters the link listener and channel, then closes the link. */ + override fun close() { + val network = networkTask + val reminder = reminderTask + val listener = linkListener + val proxyLink = link + networkTask = null + reminderTask = null + linkListener = null + link = null + + ResourceCleanup.closeAll( + { network?.cancel() }, + { reminder?.cancel() }, + { listener?.close() }, + { proxy.unregisterChannel(LinkCodec.CHANNEL) }, + { proxyLink?.close() }, + ) + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeAnalytics.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeAnalytics.kt index b17e6b918..e7b0a26d6 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeAnalytics.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeAnalytics.kt @@ -1,5 +1,6 @@ package org.pnfolder.pnlibrary.core.runtime.details +/** Builds the analytics section of the diagnostics report. */ internal object RuntimeAnalytics { fun of( taskCount: Int, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeConfigurationDetails.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeConfigurationDetails.kt index ffdcbac7a..5559219d6 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeConfigurationDetails.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeConfigurationDetails.kt @@ -2,6 +2,7 @@ package org.pnfolder.pnlibrary.core.runtime.details import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig +/** Renders the library configuration as a map for the diagnostics report. */ internal object RuntimeConfigurationDetails { fun of(config: PnLibraryConfig): Map = linkedMapOf( "privacy" to config.privacy, @@ -15,7 +16,6 @@ internal object RuntimeConfigurationDetails { "taskHistoryCapacity" to config.taskHistoryCapacity, "keepReports" to config.keepReports, "maxReportBytes" to config.maxReportBytes, - "excludedPathCount" to config.excludedPaths.size, "redactionRuleCount" to (config.secretKeyPatterns.size + config.redactValuePatterns.size), ) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeDiagnosticsAssembler.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeDiagnosticsAssembler.kt index fed3f7bda..104a78ce0 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeDiagnosticsAssembler.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeDiagnosticsAssembler.kt @@ -3,14 +3,15 @@ package org.pnfolder.pnlibrary.core.runtime.details import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig import org.pnfolder.pnlibrary.api.updates.UpdateService import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.commands.CommandRegistry +import org.pnfolder.pnlibrary.core.commands.engine.CommandRegistry import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticsRegistry -import org.pnfolder.pnlibrary.core.metrics.MetricsSessions +import org.pnfolder.pnlibrary.core.metrics.session.MetricsSessions import org.pnfolder.pnlibrary.core.observability.SupportRuntime import org.pnfolder.pnlibrary.core.tasks.TaskService import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import java.nio.file.Path +/** Collects the runtime state of the library into a diagnostics report. */ internal class RuntimeDiagnosticsAssembler( private val version: String, private val isClosed: () -> Boolean, @@ -27,7 +28,7 @@ internal class RuntimeDiagnosticsAssembler( ) { fun assemble(): Map { val taskSnapshots = tasks.query() - val updateSnapshots = updates.all() + val updateSnapshots = updates.products.all() val taskFailures = taskSnapshots.count { it.lastFailure != null } val failedUpdates = updateSnapshots.count { it.snapshot.state.name.equals("FAILED", ignoreCase = true) } val diagnosticSummary = diagnostics.diagnosticSummary() @@ -91,7 +92,7 @@ internal class RuntimeDiagnosticsAssembler( private fun updateGraph(): Map = linkedMapOf( - "current" to updates.currentPlan().orElse(null)?.let(RuntimeUpdateDetails::of), - "history" to updates.history().map(RuntimeUpdateDetails::of), + "current" to updates.plans.current().orElse(null)?.let(RuntimeUpdateDetails::of), + "history" to updates.plans.recent().map(RuntimeUpdateDetails::of), ) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeFeatureSet.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeFeatureSet.kt index 72c600c68..6d340ffdf 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeFeatureSet.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeFeatureSet.kt @@ -4,46 +4,56 @@ import org.pnfolder.pnlibrary.api.currency.CurrencyProviderRegistry import org.pnfolder.pnlibrary.api.expansions.Expansion import org.pnfolder.pnlibrary.api.logging.LogLevel import org.pnfolder.pnlibrary.config.ConfigurationServiceImpl -import org.pnfolder.pnlibrary.core.downloads.DirectDownloads -import org.pnfolder.pnlibrary.core.downloads.DownloadConfiguration +import org.pnfolder.pnlibrary.core.downloads.fetch.DirectDownloads +import org.pnfolder.pnlibrary.core.downloads.settings.downloads import org.pnfolder.pnlibrary.core.expansions.ExpansionRegistry import org.pnfolder.pnlibrary.core.expansions.LocalizationExpansion -import org.pnfolder.pnlibrary.core.placeholders.GlobalPlaceholderValueStore import org.pnfolder.pnlibrary.core.placeholders.PlaceholderHub +import org.pnfolder.pnlibrary.core.placeholders.builtin.GlobalPlaceholderValueStore import org.pnfolder.pnlibrary.core.runtime.platform.PlatformRuntimeContext import org.pnfolder.pnlibrary.core.services.ServiceRegistry -import org.pnfolder.pnlibrary.core.ui.ConsoleStyle -import org.pnfolder.pnlibrary.core.updates.service.UpdateServiceImpl +import org.pnfolder.pnlibrary.core.settings.SettingsStore +import org.pnfolder.pnlibrary.core.text.ConsoleStyle import org.pnfolder.pnlibrary.currency.CurrencyFeature import org.pnfolder.pnlibrary.currency.CurrencyRuntime import org.pnfolder.pnlibrary.spi.platform.PlatformLogging -import java.nio.file.Path +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import org.pnfolder.pnlibrary.updates.policy.UpdateTiming +import org.pnfolder.pnlibrary.updates.service.UpdateServiceImpl +/** Creates the feature services of the library runtime ( + services, + configs, + updates and so on, +); [owner] is the pnLibrary plugin that log lines are written for. */ internal class RuntimeFeatureSet( + owner: Any, platform: PlatformRuntimeContext, - dataFolder: Path, + paths: LibraryPaths, logging: PlatformLogging, + settings: SettingsStore, ) { val services = ServiceRegistry() val configurations: ConfigurationServiceImpl = ConfigurationServiceImpl(platform.ownership, logging) val updates = UpdateServiceImpl( - logging, platform.ownership, platform.ownership, platform.identity, platform.readiness, dataFolder, + logging, platform.ownership, platform.ownership, platform.identity, platform.readiness, paths, ConsoleStyle.THEME, + settings.current().let { UpdateTiming(it.updateCheckInterval, it.updateConnectTimeout, it.updateReadTimeout) }, ) - private val downloadConfiguration = DownloadConfiguration.load(dataFolder.resolve("downloads.yml")) { - logging.log(this, LogLevel.WARNING, it) - } val downloads: DirectDownloads = DirectDownloads( platform.identity, platform.ownership, platform.ownership, platform.readiness, - logging, dataFolder, downloadConfiguration, + logging, paths, { settings.current().downloads() }, + saveAutomatic = { settings.set("downloads.automatic", it.toString()) }, ) val placeholderValues = GlobalPlaceholderValueStore() - val placeholders: PlaceholderHub = PlaceholderHub(platform.identity, placeholderValues) { problem -> - logging.log(this, LogLevel.WARNING, problem) - } - val currency: CurrencyRuntime = CurrencyFeature() + val placeholders: PlaceholderHub = PlaceholderHub( + platform.identity, placeholderValues, + issues = { problem -> logging.log(owner, LogLevel.WARNING, problem) }, + failures = { problem, error -> logging.log(owner, LogLevel.ERROR, problem, error) }, + ) + val currency: CurrencyRuntime = CurrencyFeature { message, error -> logging.log(owner, LogLevel.ERROR, message, error) } private val onExpansionFailure: (Expansion, Exception) -> Unit = { expansion, error -> - logging.log(this, LogLevel.WARNING, "Expansion '${expansion.id}' failed: ${error.message}", error) + logging.log(owner, LogLevel.WARNING, "Expansion '${expansion.id}' failed: ${error.message}", error) } /** Expansions of plugins; the public `PnLibrary.expansions`. */ @@ -55,6 +65,6 @@ internal class RuntimeFeatureSet( init { services.register(CurrencyProviderRegistry::class.java, currency.providers) // Item and entity names exist on game servers only; proxies get no loader and no cache folder. - if (platform.identity.isServer) libraryExpansions.register(LocalizationExpansion(dataFolder.resolve("localization"))) + if (platform.identity.isServer) libraryExpansions.register(LocalizationExpansion(paths.localization)) } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeJournal.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeJournal.kt index 97b59b8e5..4e8c87d25 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeJournal.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeJournal.kt @@ -1,31 +1,37 @@ package org.pnfolder.pnlibrary.core.runtime.details -import org.pnfolder.pnlibrary.api.commands.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition import org.pnfolder.pnlibrary.api.logging.LogLevel import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig +import org.pnfolder.pnlibrary.common.concurrent.FailureThrottle import org.pnfolder.pnlibrary.common.concurrent.ManagedWorker import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.core.journal.JournalLevel -import org.pnfolder.pnlibrary.core.journal.JournalQueries import org.pnfolder.pnlibrary.core.journal.JournalRecord -import org.pnfolder.pnlibrary.core.journal.JournalStore -import org.pnfolder.pnlibrary.core.journal.journalCommand +import org.pnfolder.pnlibrary.core.journal.store.JournalQueries +import org.pnfolder.pnlibrary.core.journal.store.JournalStore import org.pnfolder.pnlibrary.core.journal.toJournalLevel +import org.pnfolder.pnlibrary.core.journal.view.journalCommand import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership import java.nio.file.Path import java.time.Duration +import java.util.concurrent.ConcurrentLinkedQueue +import java.util.concurrent.RejectedExecutionException +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong /** Owns journal storage, asynchronous writes, failure counters and draining at shutdown. */ internal class RuntimeJournal( - dataFolder: Path, + journalFolder: Path, config: PnLibraryConfig, private val ownership: PlatformOwnership, startedAtMillis: Long, private val eventsCommand: String, + private val onWriteFailure: (Throwable) -> Unit = {}, ) : AutoCloseable { val store = JournalStore( - dataFolder.resolve("journal"), + journalFolder, mapOf( JournalLevel.INFO to Duration.ofDays(config.journalInfoDays.toLong()), JournalLevel.WARNING to Duration.ofDays(config.journalWarningDays.toLong()), @@ -35,19 +41,73 @@ internal class RuntimeJournal( val queries = JournalQueries(store, config, startedAtMillis, eventsCommand) private val worker = ManagedWorker("pnLibrary-journal") private val failures = AtomicLong() + private val writeFailureThrottle = FailureThrottle() + private val pending = ConcurrentLinkedQueue() + private val pendingCount = AtomicInteger() + private val drainScheduled = AtomicBoolean() - fun record(owner: Any, level: LogLevel, message: String, error: Throwable?) { + fun record(owner: Any, level: LogLevel, message: String, error: Throwable?, context: Map = emptyMap()) { + val details = buildMap { + error?.let { put("exception", it.javaClass.name); put(JournalRecord.STACKTRACE, JournalRecord.stackTraceOf(it)) } + context.forEach { (k, v) -> if (v != null) put(k, v.toString()) } + } val record = JournalRecord( timeMillis = System.currentTimeMillis(), level = level.toJournalLevel(), source = ownership.ownerDetails(owner)["id"] ?: owner.javaClass.simpleName, type = if (error != null) "ERROR" else "LOG", message = message, - details = error?.let { - mapOf("exception" to it.javaClass.name, JournalRecord.STACKTRACE to JournalRecord.stackTraceOf(it)) - }.orEmpty(), + details = details, ) - worker.submit { store.append(record) }.exceptionally { failures.incrementAndGet(); null } + if (pendingCount.get() >= QUEUE_CAPACITY) { + fail(1, RejectedExecutionException("Journal queue is full: $QUEUE_CAPACITY records wait for the disk")) + return + } + pending.add(record) + pendingCount.incrementAndGet() + scheduleDrain() + } + + private fun scheduleDrain() { + if (!drainScheduled.compareAndSet(false, true)) return + try { + worker.submit(::drain).exceptionally { failure -> + drainScheduled.set(false) + fail(pendingCount.get().coerceAtLeast(1), failure.cause ?: failure) + null + } + } catch (error: IllegalStateException) { + drainScheduled.set(false) + fail(pendingCount.get().coerceAtLeast(1), error) + throw error + } + } + + /** Writes everything that accumulated while the previous write ran as one batch, until the queue stays empty. */ + private fun drain() { + do { + while (true) { + val batch = ArrayList() + while (batch.size < MAX_BATCH) batch.add(pending.poll() ?: break) + if (batch.isEmpty()) break + pendingCount.addAndGet(-batch.size) + write(batch) + } + drainScheduled.set(false) + } while (pending.isNotEmpty() && drainScheduled.compareAndSet(false, true)) + } + + private fun write(batch: List) { + try { + store.appendAll(batch) { _, error -> fail(1, error) } + } catch (error: Exception) { + fail(batch.size, error) + } + } + + private fun fail(records: Int, cause: Throwable) { + failures.addAndGet(records.toLong()) + if (writeFailureThrottle.shouldReport(cause.javaClass.name)) onWriteFailure(cause) } /** The `/pn events` command over this journal. */ @@ -55,4 +115,10 @@ internal class RuntimeJournal( fun summary(): Map = store.summary() + ("failedWrites" to failures.get()) override fun close() = worker.close() + + private companion object { + /** Records that may wait for the disk; a burst beyond this is counted in `failedWrites` and reported. */ + const val QUEUE_CAPACITY = 8_192 + const val MAX_BATCH = 1_024 + } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeMetricsBootstrap.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeMetricsBootstrap.kt index b26e89ca4..1c44634cc 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeMetricsBootstrap.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeMetricsBootstrap.kt @@ -1,13 +1,14 @@ package org.pnfolder.pnlibrary.core.runtime.details -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.metrics.MetricsSessions +import org.pnfolder.pnlibrary.core.metrics.session.MetricsSessions import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity +/** Starts the library's own metrics session and reports failure as a warning instead of failing startup. */ internal class RuntimeMetricsBootstrap( private val registry: MetricsSessions, private val platform: PlatformIdentity, @@ -38,7 +39,7 @@ internal class RuntimeMetricsBootstrap( } }.onFailure { error -> runCatchingNonFatal { openedSession?.close() } - warning("Metrics could not be started: ${error.message ?: error.javaClass.simpleName}") + warning("Metrics could not be started: ${error.message ?: "${error.javaClass.simpleName} in ${error.stackTrace.firstOrNull() ?: "unknown place"}"}") }.getOrNull() } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeRemotePolicy.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeRemotePolicy.kt index 613f3a540..2b7aa8f70 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeRemotePolicy.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeRemotePolicy.kt @@ -1,7 +1,7 @@ package org.pnfolder.pnlibrary.core.runtime.details import org.pnfolder.pnlibrary.api.plugin.ModuleId -import org.pnfolder.pnlibrary.api.plugin.PluginMetadata +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata import org.pnfolder.pnlibrary.api.remote.DenyAction import org.pnfolder.pnlibrary.api.remote.RemotePolicySettings import org.pnfolder.pnlibrary.api.runtime.PnLibrary @@ -15,6 +15,7 @@ import org.pnfolder.pnlibrary.core.remote.RemotePolicyNoticeRenderer import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter import java.util.concurrent.atomic.AtomicBoolean +/** Validates the remote policy the library applies to itself. */ internal object RuntimeRemotePolicy { fun validated(policy: RemotePolicySettings): RemotePolicySettings { require(policy.onDeny == DenyAction.DISABLE_PLUGIN) { @@ -51,8 +52,13 @@ internal object RuntimeRemotePolicy { val startup = monitor.checkAtStartup(owner, metadata, policy, logger, policy.startupTimeout) if (startup == null) { // Falling back to disabling the owner is safe; only fatal JVM errors must not be swallowed here. - val guarded = runCatchingNonFatal { platform.disableDependents(owner) }.getOrDefault(false) - if (!guarded) runCatchingNonFatal { platform.disableOwner(owner) } + val guarded = runCatchingNonFatal { platform.disableDependents(owner) } + .onFailure { logger.error("Could not disable the plugins that depend on pnLibrary after the policy denied it", it) } + .getOrDefault(false) + if (!guarded) { + runCatchingNonFatal { platform.disableOwner(owner) } + .onFailure { logger.critical("The policy denied pnLibrary but it could not be disabled", it) } + } throw PolicyDeniedException("${metadata.name} ${metadata.version}") } val started = AtomicBoolean(false) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeTaskDetails.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeTaskDetails.kt index 6af2aaba3..59194851f 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeTaskDetails.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeTaskDetails.kt @@ -1,7 +1,8 @@ package org.pnfolder.pnlibrary.core.runtime.details -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +/** Renders task snapshots as maps for the diagnostics report. */ internal object RuntimeTaskDetails { fun entries(snapshots: List): List> = snapshots.map { task -> diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeUpdateDetails.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeUpdateDetails.kt index bdddb8857..9e89e1478 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeUpdateDetails.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeUpdateDetails.kt @@ -1,8 +1,9 @@ package org.pnfolder.pnlibrary.core.runtime.details -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot import org.pnfolder.pnlibrary.api.updates.UpdateRegistration +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +/** Renders update registrations as maps for the diagnostics report. */ internal object RuntimeUpdateDetails { fun registration(value: UpdateRegistration): Map { val snapshot = value.snapshot diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeUpdateMonitor.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeUpdateMonitor.kt index e36d00ada..0e00a6d7a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeUpdateMonitor.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeUpdateMonitor.kt @@ -2,12 +2,13 @@ package org.pnfolder.pnlibrary.core.runtime.details import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.PluginUpdateRequest -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor import org.pnfolder.pnlibrary.api.updates.UpdateRegistration +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership +/** Registers the library itself with the update service. */ internal object RuntimeUpdateMonitor { data class Registration( val currentVersion: String, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeUpdateSummary.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeUpdateSummary.kt index db32e4015..5fc02d701 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeUpdateSummary.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeUpdateSummary.kt @@ -4,6 +4,7 @@ import org.pnfolder.pnlibrary.api.updates.UpdateRegistration import java.time.Duration import java.time.Instant +/** Summarizes update registrations for the diagnostics report. */ internal object RuntimeUpdateSummary { fun of(registrations: List): Map { val latestPublishedAtByChannel: Map = registrations diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeBootstrapCoordinator.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeBootstrapCoordinator.kt index 7229544c7..5c694d434 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeBootstrapCoordinator.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeBootstrapCoordinator.kt @@ -1,12 +1,11 @@ package org.pnfolder.pnlibrary.core.runtime.lifecycle -import org.pnfolder.pnlibrary.api.logging.LogLevel import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.runtime.PnLibraryConfigLoader import org.pnfolder.pnlibrary.core.runtime.PnLibraryLauncher import org.pnfolder.pnlibrary.core.runtime.platform.PlatformRuntimeContext +/** Creates the library instance and its update monitor, undoing partial work if startup fails. */ internal object RuntimeBootstrapCoordinator { data class Started( val library: PnLibrary, @@ -16,11 +15,7 @@ internal object RuntimeBootstrapCoordinator { ) fun start(owner: Any, context: PlatformRuntimeContext): Started { - val library = PnLibraryLauncher.bootstrap( - owner, - context, - PnLibraryConfigLoader.load(context.dataFolder) { context.logging.log(owner, LogLevel.WARNING, it) }, - ) + val library = PnLibraryLauncher.bootstrap(owner, context) return try { val runtime = RuntimeStartup.start(owner, library, context.identity, context.ownership) Started(runtime.library, runtime.currentVersion, runtime.updateMonitor, context.summaryName) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeShutdown.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeShutdown.kt index 0cc50cedc..581039f39 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeShutdown.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeShutdown.kt @@ -2,6 +2,7 @@ package org.pnfolder.pnlibrary.core.runtime.lifecycle import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +/** Ordered list of shutdown actions; all run even if some fail. */ internal class RuntimeShutdown { private val actions = mutableListOf<() -> Unit>() diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeShutdownPlan.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeShutdownPlan.kt index e50218969..197959c65 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeShutdownPlan.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeShutdownPlan.kt @@ -1,12 +1,6 @@ package org.pnfolder.pnlibrary.core.runtime.lifecycle -/** - * The fixed order in which a composed runtime releases its services. - * - * Plugins close first, shared services follow, and the provider, platform, and owner hooks run - * last. Every step runs even when an earlier one fails; failures are rethrown together by - * [RuntimeShutdown]. - */ +// Every step runs even when an earlier one fails; all failures are rethrown together by RuntimeShutdown. internal class RuntimeShutdownPlan( private val plugins: AutoCloseable, private val commands: AutoCloseable, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeStartup.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeStartup.kt index 9b81e718c..b6561fe66 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeStartup.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/lifecycle/RuntimeStartup.kt @@ -6,6 +6,7 @@ import org.pnfolder.pnlibrary.core.runtime.details.RuntimeUpdateMonitor import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership +/** Starts the library instance and registers it for updates. */ internal object RuntimeStartup { data class Started( val library: PnLibrary, diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/platform/NativePlatform.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/NativePlatform.kt similarity index 95% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/platform/NativePlatform.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/NativePlatform.kt index 96920b9b0..681083cb6 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/platform/NativePlatform.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/NativePlatform.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.platform +package org.pnfolder.pnlibrary.core.runtime.platform import org.pnfolder.pnlibrary.api.platform.PlatformProvider import java.util.concurrent.ConcurrentHashMap diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/audiences/PlatformAudiences.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformAudiences.kt similarity index 86% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/audiences/PlatformAudiences.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformAudiences.kt index d96a56a40..ff599ad1e 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/audiences/PlatformAudiences.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformAudiences.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.audiences +package org.pnfolder.pnlibrary.core.runtime.platform import net.kyori.adventure.sound.Sound import net.kyori.adventure.text.Component @@ -6,7 +6,8 @@ import org.pnfolder.pnlibrary.api.audiences.AudienceSender import org.pnfolder.pnlibrary.api.audiences.AudienceService import org.pnfolder.pnlibrary.api.audiences.Delivery import org.pnfolder.pnlibrary.api.audiences.LibraryAudience -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.common.concurrent.FailureThrottle import org.pnfolder.pnlibrary.common.lang.Failures import org.pnfolder.pnlibrary.spi.audiences.PlatformAudienceAdapter import java.time.Duration @@ -18,8 +19,10 @@ import java.util.concurrent.atomic.AtomicBoolean /** Resolves consoles, players and composite audiences through the platform adapter; returns empty results once closed. */ internal class PlatformAudiences( private val adapter: PlatformAudienceAdapter, + private val onDeliveryFailure: (Throwable) -> Unit = {}, ) : AudienceService, AutoCloseable { private val closed = AtomicBoolean(false) + private val failureThrottle = FailureThrottle() override fun console(): AudienceSender = if (closed.get()) CLOSED_CONSOLE else adapter.console() override fun player(uniqueId: UUID): LibraryPlayer? = if (closed.get()) null else adapter.player(uniqueId) @@ -30,7 +33,7 @@ internal class PlatformAudiences( override fun combine(audiences: Iterable): LibraryAudience = CompositeAudience(audiences) override fun close() { closed.set(true) } - private class DynamicAudience(private val receivers: () -> Iterable) : LibraryAudience { + private inner class DynamicAudience(private val receivers: () -> Iterable) : LibraryAudience { override fun sendMessage(text: Component) = CompositeAudience(receivers()).sendMessage(text) override fun actionBar(text: Component) = CompositeAudience(receivers()).actionBar(text) override fun playSound(sound: Sound) = CompositeAudience(receivers()).playSound(sound) @@ -38,7 +41,7 @@ internal class PlatformAudiences( CompositeAudience(receivers()).showTitle(title, subtitle, fadeIn, stay, fadeOut) } - private class CompositeAudience(receivers: Iterable) : LibraryAudience { + private inner class CompositeAudience(receivers: Iterable) : LibraryAudience { private val receivers = receivers.filterDistinctByIdentity() override fun sendMessage(text: Component) = each { it.sendMessage(text) } override fun actionBar(text: Component) = each { it.actionBar(text) } @@ -63,6 +66,7 @@ internal class PlatformAudiences( operation(receiver) } catch (error: Throwable) { Failures.rethrowIfFatal(error) + if (failureThrottle.shouldReport(error.javaClass.name)) onDeliveryFailure(error) } } } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformRegistration.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformRegistration.kt index 6566739e0..73d858e11 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformRegistration.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformRegistration.kt @@ -1,5 +1,6 @@ package org.pnfolder.pnlibrary.core.runtime.platform +/** Registers a platform adapter implementation and returns a handle that unregisters it. */ internal interface PlatformRegistration { fun registerPlatform(type: Class, implementation: T): AutoCloseable } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformRuntimeContext.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformRuntimeContext.kt index d1f30f502..5a2155ca7 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformRuntimeContext.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformRuntimeContext.kt @@ -1,5 +1,6 @@ package org.pnfolder.pnlibrary.core.runtime.platform +import org.pnfolder.pnlibrary.api.network.NetworkProxy import org.pnfolder.pnlibrary.spi.audiences.PlatformAudienceAdapter import org.pnfolder.pnlibrary.spi.commands.PlatformCommandAdapter import org.pnfolder.pnlibrary.spi.metrics.PlatformMetricsFactory @@ -16,6 +17,7 @@ import org.pnfolder.pnlibrary.spi.platform.PlatformShutdown import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskAdapter import java.nio.file.Path +/** All platform adapters the runtime needs, gathered in one place. */ internal data class PlatformRuntimeContext( val identity: PlatformIdentity, val execution: PlatformExecution, @@ -31,6 +33,7 @@ internal data class PlatformRuntimeContext( val dataFolder: Path, val binding: PlatformBinding, val shutdown: PlatformShutdown, + val networkProxy: NetworkProxy?, ) { val summaryName: String get() = if (identity.implementationName.equals(identity.type.displayName, ignoreCase = true)) { @@ -55,4 +58,5 @@ internal fun PlatformAdapter.toRuntimeContext(): PlatformRuntimeContext = Platfo dataFolder = dataFolder, binding = this, shutdown = this, + networkProxy = networkProxy, ) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformServiceSet.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformServiceSet.kt index 5c656b9a9..a46c6cfb8 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformServiceSet.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformServiceSet.kt @@ -1,9 +1,9 @@ package org.pnfolder.pnlibrary.core.runtime.platform import org.pnfolder.pnlibrary.api.tasks.TaskServiceSettings -import org.pnfolder.pnlibrary.core.audiences.PlatformAudiences -import org.pnfolder.pnlibrary.core.commands.CommandRegistry -import org.pnfolder.pnlibrary.core.commands.StandardCommandFeedback +import org.pnfolder.pnlibrary.core.commands.engine.CommandRegistry +import org.pnfolder.pnlibrary.core.commands.engine.StandardCommandFeedback +import org.pnfolder.pnlibrary.core.runtime.platform.PlatformAudiences import org.pnfolder.pnlibrary.core.tasks.ScheduledTasks import org.pnfolder.pnlibrary.core.tasks.TaskHistoryStore import org.pnfolder.pnlibrary.spi.audiences.PlatformAudienceAdapter @@ -12,6 +12,7 @@ import org.pnfolder.pnlibrary.spi.platform.PlatformLogging import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskAdapter import java.nio.file.Path +/** Services built on top of platform adapters: commands, audiences and tasks. */ internal class PlatformServiceSet( commandAdapter: PlatformCommandAdapter, audienceAdapter: PlatformAudienceAdapter, @@ -21,6 +22,7 @@ internal class PlatformServiceSet( taskHistoryFile: Path? = null, errorLogger: (Any, String, Throwable) -> Unit, commandFeedback: StandardCommandFeedback = StandardCommandFeedback(), + onAudienceFailure: (Throwable) -> Unit = {}, ) { val tasks = ScheduledTasks( adapter = taskAdapter, @@ -29,5 +31,5 @@ internal class PlatformServiceSet( store = taskHistoryFile?.let(::TaskHistoryStore), ) val commands = CommandRegistry(commandAdapter, platformLogging, commandFeedback) - val audiences = PlatformAudiences(audienceAdapter) + val audiences = PlatformAudiences(audienceAdapter, onAudienceFailure) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/services/ServiceRegistry.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/services/ServiceRegistry.kt index 1aa12fb5b..b84ba7d3c 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/services/ServiceRegistry.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/services/ServiceRegistry.kt @@ -6,6 +6,9 @@ import java.util.Collections import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicLong +/** Module view whose registrations are removed together when the module closes. */ +internal interface ServiceScope : ServiceManager, AutoCloseable + /** Thread-safe implementation of the typed, plugin-owned service registry. */ internal class ServiceRegistry : ServiceManager, AutoCloseable { private val lock = Any() diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/services/ServiceScope.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/services/ServiceScope.kt deleted file mode 100644 index 37b04f006..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/services/ServiceScope.kt +++ /dev/null @@ -1,6 +0,0 @@ -package org.pnfolder.pnlibrary.core.services - -import org.pnfolder.pnlibrary.api.services.ServiceManager - -/** Module view whose registrations are removed together when the module closes. */ -internal interface ServiceScope : ServiceManager, AutoCloseable diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/ChoiceSource.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/ChoiceSource.kt new file mode 100644 index 000000000..891fc07f3 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/ChoiceSource.kt @@ -0,0 +1,141 @@ +package org.pnfolder.pnlibrary.core.settings + +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.util.Locale +import kotlin.math.abs + +/** + * One way to put a list of choices in order, for example by alphabet or by UTC offset. + * + * @property label the name shown on the sorting button + * @property sort puts the values in order as they are at the moment [Instant] (an offset changes with summer time) + */ +internal class ChoiceOrder(val label: String, val sort: (List, Instant) -> List) + +/** + * A list of values a setting is chosen from, for settings that have too many values for a switch. + * + * The list is computed where it is needed (java.time is on every server, proxy and client), so the link between a proxy + * and a game server sends only the [id], never the values. + * + * @property id the name sent over the link and used by the menu to find the list again + * @property all every value, alphabetically and without repeats + * @property orders the ways to sort the list; the first one is shown at first + * @param curated the values worth showing first to somebody who does not know the name, in the order they are shown; + * values that are not in [all] are dropped + * @param cycled the values a click on the menu button rolls through, in their order; empty means every value of [all] + * @property details lines `label to value` that tell about a value, so it can be picked without knowing its name + */ +internal class ChoiceSource( + val id: String, + val all: List, + val orders: List = listOf(ALPHABET), + curated: List = emptyList(), + cycled: List = emptyList(), + private val details: (String, Instant) -> List> = { _, _ -> emptyList() }, +) { + /** The curated values, in their own order. */ + val popular: List = curated.filter { it in all } + + /** The values a click rolls through: the [cycled] ones that exist, or all values. */ + val cycle: List = cycled.filter { it in all }.ifEmpty { all } + + /** + * The values the rolling switcher shows for the [current] one: the [cycle], with [current] put first when it is not + * in it (a zone nobody listed as popular is still shown, as the value in use). + */ + fun rolling(current: String): List = if (current in cycle) cycle else listOf(current) + cycle + + /** + * The value after [current] (or before it, when [backwards]) in the [cycle], wrapping around. A [current] outside + * the cycle moves to the first value, or to the last one when [backwards]. + */ + fun step(current: String, backwards: Boolean): String { + val at = cycle.indexOf(current) + return when { + at >= 0 -> cycle[Math.floorMod(at + if (backwards) -1 else 1, cycle.size)] + backwards -> cycle.last() + else -> cycle.first() + } + } + + /** The lore lines of [value] as they are at the moment [at]. */ + fun lore(value: String, at: Instant = Instant.now()): List> = details(value, at) + + /** + * What the picker shows: the values that contain [filter] (see [matches]) sorted by the order number [order], or, with + * no filter, either the [popular] ones or everything. + */ + fun view(order: Int, onlyPopular: Boolean, filter: String, at: Instant = Instant.now()): List { + val sorted = orders[order.coerceIn(orders.indices)].sort(all, at) + return when { + filter.isNotBlank() -> sorted.filter { matches(it, filter) } + onlyPopular -> popular + else -> sorted + } + } + + companion object { + /** The id of [ZONES]. */ + const val ZONE_ID = "zones" + + private val ALPHABET = ChoiceOrder("по алфавиту") { values, _ -> values.sorted() } + private val REGIONS = listOf("Africa", "America", "Antarctica", "Asia", "Atlantic", "Australia", "Europe", "Indian", "Pacific") + private val EXTRA = setOf("UTC", "Etc/UTC") + private val CLOCK = DateTimeFormatter.ofPattern("HH:mm") + private val BLANKS = Regex("\\s+") + private const val SECONDS_IN_HOUR = 3600 + private const val SECONDS_IN_MINUTE = 60 + + private val POPULAR_ZONES = listOf( + "UTC", "Europe/London", "Europe/Berlin", "Europe/Kyiv", "Europe/Minsk", "Europe/Moscow", "Europe/Istanbul", "Asia/Dubai", + "Asia/Tashkent", "Asia/Almaty", "Asia/Kolkata", "Asia/Bangkok", "Asia/Shanghai", "Asia/Tokyo", "Australia/Sydney", + "Pacific/Auckland", "America/Sao_Paulo", "America/New_York", "America/Chicago", "America/Denver", "America/Los_Angeles", + ) + + private val BY_OFFSET = ChoiceOrder("по смещению UTC") { values, at -> + val offsets = values.associateWith { offsetSeconds(it, at) } + values.sortedWith(compareBy({ offsets.getValue(it) }, { it })) + } + + /** + * Time zones a person would look for: `Europe/Moscow`, `America/New_York` and `UTC`. Legacy aliases (`US/Pacific`, + * `SystemV/AST4`) and the `Etc/GMT+N` series are left out; they only make the list longer. Each zone tells the time + * there now and its offset from UTC; the order is by that offset, then by name, or by alphabet. + */ + val ZONES: ChoiceSource by lazy { + val ids = ZoneId.getAvailableZoneIds().filter { id -> id in EXTRA || REGIONS.any { id.startsWith("$it/") } }.sorted() + ChoiceSource(ZONE_ID, ids, listOf(BY_OFFSET, ALPHABET), POPULAR_ZONES) { zone, at -> + listOf("Смещение" to offsetText(offsetSeconds(zone, at)), "Сейчас там" to localTime(zone, at)) + } + } + + /** The source named [id], or `null` when there is none. */ + fun named(id: String): ChoiceSource? = if (id == ZONE_ID) ZONES else null + + /** The offset of [zone] from UTC at the moment [at], in seconds, summer time included. */ + fun offsetSeconds(zone: String, at: Instant): Int = ZoneId.of(zone).rules.getOffset(at).totalSeconds + + /** An offset as `UTC`, `UTC+03:00` or `UTC-05:00`. */ + fun offsetText(seconds: Int): String { + if (seconds == 0) return "UTC" + val sign = if (seconds < 0) "-" else "+" + val minutes = abs(seconds) % SECONDS_IN_HOUR / SECONDS_IN_MINUTE + return String.format(Locale.ROOT, "UTC%s%02d:%02d", sign, abs(seconds) / SECONDS_IN_HOUR, minutes) + } + + /** The time of day in [zone] at the moment [at], as `21:45`. */ + fun localTime(zone: String, at: Instant): String = at.atZone(ZoneId.of(zone)).format(CLOCK) + + /** + * Whether [value] contains [query], ignoring the case and the difference between `_`, `/` and a space, so that + * `new york` finds `America/New_York`. + */ + fun matches(value: String, query: String): Boolean = normalize(value).contains(normalize(query)) + + private fun normalize(text: String): String = + text.lowercase(Locale.ROOT).replace('_', ' ').replace('/', ' ').trim().replace(BLANKS, " ") + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/LegacySettingsImport.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/LegacySettingsImport.kt new file mode 100644 index 000000000..8aeece88c --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/LegacySettingsImport.kt @@ -0,0 +1,92 @@ +package org.pnfolder.pnlibrary.core.settings + +import org.pnfolder.pnlibrary.common.io.AtomicFiles +import org.pnfolder.pnlibrary.common.io.TextFiles +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import org.yaml.snakeyaml.LoaderOptions +import org.yaml.snakeyaml.Yaml +import org.yaml.snakeyaml.constructor.SafeConstructor +import java.nio.file.Files +import java.nio.file.Path + +/** + * Takes the values of the old `config.yml` and `downloads.yml` (and the download choice kept in `downloads/preferences.state`) + * into the [SettingsStore] once, then renames the files to `*.yml.old` so nothing is imported twice. + * + * A key that the store already holds is never replaced: what an administrator set with a command wins over an old file. + * It never throws; what could not be read is reported through [warning] and the file is left where it is. + */ +internal class LegacySettingsImport( + private val paths: LibraryPaths, + private val warning: (String) -> Unit = {}, +) { + /** Imports into [store] every old file that exists. */ + fun run(store: SettingsStore) { + val held = store.values().filter { it.changed }.map { it.spec.key }.toSet() + importYaml(paths.legacyConfig, "", store, held) + importYaml(paths.legacyDownloadsConfig, "downloads.", store, held) + importDownloadChoice(store, held) + } + + private fun importYaml(file: Path, prefix: String, store: SettingsStore, held: Set) { + if (!Files.isRegularFile(file)) return + val root = try { + Yaml(SafeConstructor(LoaderOptions())).load(TextFiles.read(file)) as? Map<*, *> ?: emptyMap() + } catch (error: Exception) { + warning("${file.fileName} не прочитан и остался на месте: ${error.message?.lineSequence()?.firstOrNull()}") + return + } + flatten(root, prefix).forEach { (key, value) -> take(store, held, file.fileName.toString(), key, value) } + retire(file) + } + + /** `destinations: {cache: true}` becomes `destinations.cache`; keys of the old files were already in the kebab case. */ + private fun flatten(map: Map<*, *>, prefix: String): Map = buildMap { + map.forEach { (name, value) -> + val key = prefix + name + if (value is Map<*, *>) putAll(flatten(value, "$key.")) else put(key, value) + } + } + + private fun take(store: SettingsStore, held: Set, source: String, key: String, value: Any?) { + val spec = SettingsRegistry[key] + if (spec == null) { + warning("$source: параметр «$key» больше не существует, пропущен.") + return + } + if (key in held || value == null) return + try { + val text = value.toString() + if (spec.normalize(text) != spec.default) store.set(key, text) + } catch (error: SettingException) { + warning("$source: ${spec.key} не перенесён: ${error.message}") + } + } + + /** The old `/pn deps auto` choice beat `downloads.yml`, so it beats it here too. */ + private fun importDownloadChoice(store: SettingsStore, held: Set) { + val file = paths.downloads.resolve("preferences.state") + if (!Files.isRegularFile(file)) return + val choice = runCatchingNonFatal { + Files.readAllLines(file).firstOrNull { it.startsWith("automatic=") }?.substringAfter('=')?.trim()?.toBooleanStrictOrNull() + }.getOrNull() + if (choice != null && "downloads.automatic" !in held) { + runCatchingNonFatal { store.set("downloads.automatic", choice.toString()) } + .onFailure { warning("Выбор автозагрузки не перенесён: ${it.message}") } + } + runCatchingNonFatal { Files.deleteIfExists(file) } + } + + private fun retire(file: Path) { + val old = file.resolveSibling("${file.fileName}.old") + runCatchingNonFatal { AtomicFiles.move(file, old) } + .onSuccess { + warning( + "${file.fileName} больше не используется: настройки перенесены в data/settings.json и меняются командой /pn settings. " + + "Файл сохранён как ${old.fileName}.", + ) + } + .onFailure { warning("${file.fileName} не удалось переименовать в ${old.fileName}: ${it.message}") } + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/LibraryCommandGuide.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/LibraryCommandGuide.kt new file mode 100644 index 000000000..442aeb4ba --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/LibraryCommandGuide.kt @@ -0,0 +1,382 @@ +package org.pnfolder.pnlibrary.core.settings + +/** Where a command exists. */ +internal enum class GuideScope(val note: String?) { + EVERYWHERE(null), + GAME_SERVER("Есть только на игровом сервере."), + PROXY("Есть только на прокси (BungeeCord, Velocity)."), +} + +/** + * One line of the command guide. + * + * @param usage the command as it is typed, or the name of a right that has no command + * @param permission the permission node, or `null` when the entry needs none + * @param description what it does, one short sentence + * @param orAdmin whether `pnlibrary.admin` opens the command too + * @param scope where the command exists + * @param note one more thing the administrator should know, or `null` + */ +internal class GuideEntry( + val usage: String, + val permission: String?, + val description: String, + val orAdmin: Boolean = false, + val scope: GuideScope = GuideScope.EVERYWHERE, + val note: String? = null, +) { + /** Whether [permission] is a pattern such as `pnlibrary.currency.<валюта>.list`, not one node of plugin.yml. */ + val isPattern: Boolean get() = permission?.contains('<') == true +} + +internal class GuideSection(val title: String, val entries: List) + +/** + * The one list of every `/pn` command and every permission of the library: the text of `Команды.txt` is made from it and + * a test keeps it equal to the permissions of `plugin.yml`. + * + * Whoever adds a command or a permission adds it here; nothing else lists them. + */ +internal object LibraryCommandGuide { + private const val ADMIN = "pnlibrary.admin" + + val sections: List = listOf( + GuideSection( + "Обновления", + listOf( + GuideEntry( + "/pn", ADMIN, "Список плагинов и их обновлений. Без этого права команда покажет только то, что разрешено вам.", + note = "Сама команда /pn доступна всем.", + ), + GuideEntry("/pn status [плагин]", "pnlibrary.updates.view", "Состояние обновлений: версии, канал, что готово к установке.", orAdmin = true), + GuideEntry("/pn check", "pnlibrary.updates.view", "Проверить прямо сейчас, есть ли новые версии плагинов.", orAdmin = true), + GuideEntry( + "/pn updates [list|available] [страница]", "pnlibrary.updates.view", + "Каталог плагинов; available показывает только те, что можно обновить.", orAdmin = true, + ), + GuideEntry("/pn updates info <плагин>", "pnlibrary.updates.view", "Карточка плагина: версии, канал, состояние.", orAdmin = true), + GuideEntry( + "/pn updates settings <плагин>", "pnlibrary.updates.view", "Настройки обновления плагина: канал, автозагрузка, пауза.", + orAdmin = true, + ), + GuideEntry("/pn updates history [страница]", "pnlibrary.updates.view", "История обновлений всех плагинов.", orAdmin = true), + GuideEntry("/pn updates history plugin <плагин> [страница]", "pnlibrary.updates.view", "История обновлений одного плагина.", orAdmin = true), + GuideEntry( + "/pn updates set <плагин> channel ", + "pnlibrary.updates.settings", + "Выбрать канал выпусков; default возвращает выбор плагина.", + note = "Сейчас публикуется только канал dev.", + ), + GuideEntry( + "/pn updates set <плагин> auto ", + "pnlibrary.updates.settings", + "Включить или выключить автозагрузку обновлений одного плагина.", + ), + GuideEntry( + "/pn updates set <плагин> hold <срок|off>", + "pnlibrary.updates.settings", + "Поставить обновления плагина на паузу от 1m до 7d (например 3d) или снять паузу.", + ), + GuideEntry("/pn updates set all auto ", "pnlibrary.updates.settings", "Включить или выключить автозагрузку сразу для всех плагинов."), + GuideEntry( + "/pn updates backups [plugin <плагин>] [since <7d|дата>] [sort ] [страница]", + "pnlibrary.updates.rollback", + "Резервные наборы, сохранённые перед обновлениями; можно отфильтровать и отсортировать.", + ), + GuideEntry( + "/pn updates backups restore <набор> <плагин> [confirm] <база>", + "pnlibrary.updates.settings", + "Вернуть сохранённую базу данных плагина; без confirm только предупредит.", + note = "Нужно и право pnlibrary.updates.rollback.", + ), + GuideEntry( + "/pn updates backups files <набор> <плагин>", + "pnlibrary.updates.settings", + "Выложить сохранённые файлы плагина в папку, чтобы взять их руками.", + note = "Нужно и право pnlibrary.updates.rollback.", + ), + GuideEntry( + "/pn updates backups delete <набор>", + "pnlibrary.updates.settings", + "Удалить резервный набор.", + note = "Нужно и право pnlibrary.updates.rollback.", + ), + GuideEntry( + "/pn updates rollback <набор> [configs]", + "pnlibrary.updates.rollback", + "Откатиться к резервному набору (с configs вместе с конфигурациями); спросит подтверждение.", + ), + GuideEntry( + "/pn update <плагин>", + "pnlibrary.updates.download", + "Найти, скачать и проверить обновление плагина; оно применится после перезапуска.", + orAdmin = true, + ), + GuideEntry( + "/pn update confirm <код>", + "pnlibrary.updates.download", + "Подтвердить действие по коду из сообщения (откат, перезапуск).", + orAdmin = true, + note = "Само действие требует своего права: rollback или restart.", + ), + GuideEntry( + "/pn update rollback", + "pnlibrary.updates.rollback", + "Откатить весь подготовленный план обновления; спросит подтверждение.", + note = "Нужно и право на /pn update (updates.download или admin).", + ), + GuideEntry( + "/pn update restart", + "pnlibrary.updates.restart", + "Перезапустить сервер, чтобы применить подготовленные обновления: сразу, через 5 минут или когда все выйдут.", + scope = GuideScope.GAME_SERVER, + note = "Нужно и право на /pn update. На прокси перезапускайте прокси как обычно.", + ), + GuideEntry( + "/pn update restart cancel", + "pnlibrary.updates.download", + "Отменить запланированный перезапуск.", + orAdmin = true, + scope = GuideScope.GAME_SERVER, + ), + GuideEntry( + "(уведомления об обновлениях)", + "pnlibrary.updates.notify", + "Получать сообщения об обновлениях при входе и по таймеру.", + orAdmin = true, + ), + GuideEntry( + "(установка новых компонентов)", + "pnlibrary.updates.install", + "Зарезервировано под установку новых компонентов.", + note = "Сейчас ни одна команда это право не проверяет.", + ), + ), + ), + GuideSection( + "Журнал и диагностика", + listOf( + GuideEntry( + "/pn events [info|warning|error|all] [страница]", + "pnlibrary.events.view", + "Журнал событий и ошибок, повторы свёрнуты в одну строку.", + note = "Это же право показывает сводку ошибок при входе на сервер.", + ), + GuideEntry("/pn events <номер>", "pnlibrary.events.view", "Карточка записи: полный текст, стек ошибки или все повторы."), + GuideEntry( + "/pn debug [all|плагин] [--full|--config|--logs] [--local]", + "pnlibrary.debug", + "Собрать зашифрованный отчёт для поддержки. --config добавляет конфигурации, --logs журнал, --full всё сразу, --local не отправлять.", + ), + GuideEntry("/pn stats", "pnlibrary.stats", "Сводка: задачи, события, ошибки и предупреждения за сутки и прошлые срезы."), + GuideEntry("/pn support", "pnlibrary.updates.view", "Ссылка на поддержку pnFolder.", orAdmin = true), + ), + ), + GuideSection( + "Плагины, задачи и события", + listOf( + GuideEntry( + "/pn tasks [today|week|older|any] [all|active|failed|done] [страница]", + "pnlibrary.tasks", + "Задачи всех плагинов; по умолчанию сегодняшние.", + ), + GuideEntry("/pn tasks view <номер>", "pnlibrary.tasks", "Одна задача: для чего она, владелец, времена, последняя ошибка."), + GuideEntry("/pn tasks run <номер>", "pnlibrary.tasks", "Запустить ждущую задачу сразу, если плагин не запрещает."), + GuideEntry("/pn tasks cancel <номер>", "pnlibrary.tasks", "Остановить незавершённую задачу, если плагин не запрещает."), + GuideEntry("/pn bus [all|listened|called|denied] [страница]", "pnlibrary.events.bus", "События плагинов со счётчиками слушателей и вызовов."), + GuideEntry("/pn bus view <событие>", "pnlibrary.events.bus", "Одно событие: счётчики и слушатели по порядку вызова."), + GuideEntry("/pn bus [страница]", "pnlibrary.events.bus", "Все слушатели, самые медленные и те, что падали."), + GuideEntry("/pn bus plugin <плагин> [страница]", "pnlibrary.events.bus", "Слушатели одного плагина со временем и сбоями."), + GuideEntry("/pn bus top [calls|denied]", "pnlibrary.events.bus", "Десять самых вызываемых или самых отменяемых событий."), + GuideEntry("/pn bus range [1h|24h|7d|30d]", "pnlibrary.events.bus", "Вызовы за час, сутки, неделю или месяц."), + GuideEntry( + "/pn bus history [day <дата>|of <событие>] [страница]", + "pnlibrary.events.bus", + "История по дням, по одному дню или по одному событию.", + ), + GuideEntry("/pn bus export [csv|json]", "pnlibrary.events.bus", "Записать счётчики в файл рядом с историей."), + GuideEntry("/pn bus trace [off] <событие>", "pnlibrary.events.bus", "Включить или выключить запись вызовов события."), + GuideEntry("/pn bus traces [событие]", "pnlibrary.events.bus", "Записанные вызовы: что было до и после каждого слушателя."), + GuideEntry("/pn bus clear", "pnlibrary.events.bus", "Забыть записанные вызовы."), + GuideEntry("/pn placeholders [страница]", "pnlibrary.placeholders", "Список плейсхолдеров: тип, формат, имена в PlaceholderAPI."), + GuideEntry("/pn placeholders test <адрес> [uuid игрока]", "pnlibrary.placeholders", "Вычислить плейсхолдер вручную."), + GuideEntry("/pn deps", "pnlibrary.deps", "Недостающие плагины: ссылки и код для установки."), + GuideEntry("/pn deps install <код>", "pnlibrary.deps", "Скачать недостающие плагины по коду; потом перезапустите сервер."), + GuideEntry("/pn deps auto ", "pnlibrary.deps", "Скачивать недостающие плагины самим или только по команде."), + ), + ), + GuideSection( + "Настройки и конфигурации", + listOf( + GuideEntry("/pn settings [list] [страница]", "pnlibrary.settings", "Все настройки библиотеки со значениями; подробнее в файле Настройки.txt."), + GuideEntry("/pn settings get <ключ>", "pnlibrary.settings", "Одна настройка: значение, границы, когда заработает."), + GuideEntry("/pn settings set <ключ> <значение>", "pnlibrary.settings", "Изменить настройку; значение сохраняется в data/settings.json."), + GuideEntry("/pn settings reset <ключ>", "pnlibrary.settings", "Вернуть настройку к значению по умолчанию."), + GuideEntry( + "/pn settings pick <ключ> [часть названия]", + "pnlibrary.settings", + "Открыть в меню список значений настройки (часовой пояс: time-zone), только подходящие под часть названия; " + + "new york находит America/New_York.", + scope = GuideScope.GAME_SERVER, + note = "Только для игрока.", + ), + GuideEntry("/pn configs [страница]", "pnlibrary.configs", "Файлы настроек всех плагинов: класс и состояние. Значений из файлов не показывает."), + GuideEntry("/pn configs info <файл>", "pnlibrary.configs", "Один файл: где лежит, загружен ли, что пропущено."), + GuideEntry("/pn configs reload <файл>", "pnlibrary.configs", "Прочитать файл заново; при ошибке остаётся старое значение."), + GuideEntry("/pn configs validate <файл>", "pnlibrary.configs", "Проверить загруженное значение, ничего не записывая."), + GuideEntry("/pn configs settings <файл>", "pnlibrary.configs", "Настройки файла, которые можно менять в игре."), + GuideEntry("/pn configs types <тип>", "pnlibrary.configs", "Слова, которые понимает составной тип, и плагин, добавивший каждое."), + GuideEntry( + "/pn configs edit <файл> <путь> <значение>", + "pnlibrary.configs.edit", + "Изменить одну такую настройку и сохранить файл.", + note = "Нужно и право pnlibrary.configs.", + ), + ), + ), + GuideSection( + "Сеть серверов", + listOf( + GuideEntry("/pn servers", "pnlibrary.servers", "Серверы сети: версия pnLibrary, игроки, плагины.", orAdmin = true), + GuideEntry("/pn servers <сервер>", "pnlibrary.servers", "Один сервер: платформа и состояние обновления каждого плагина.", orAdmin = true), + GuideEntry( + "/pn servers <сервер> check", + "pnlibrary.updates.view", + "Попросить сервер проверить обновления.", + note = "Нужно и право на /pn servers.", + ), + GuideEntry( + "/pn servers <сервер> update <плагин>", + "pnlibrary.updates.download", + "Попросить сервер скачать обновление плагина.", + note = "Нужно и право на /pn servers.", + ), + GuideEntry( + "/pn servers <сервер> auto <плагин> ", + "pnlibrary.updates.settings", + "Включить или выключить автозагрузку плагина на сервере.", + note = "Нужно и право на /pn servers.", + ), + GuideEntry("/pn groups", "pnlibrary.groups", "Группы серверов и сколько серверов в порядке.", orAdmin = true, scope = GuideScope.PROXY), + GuideEntry( + "/pn groups <группа>", + "pnlibrary.groups", + "Состав группы или удаление группы.", + orAdmin = true, + scope = GuideScope.PROXY, + ), + GuideEntry("/pn groups create <группа>", "pnlibrary.groups", "Создать пустую группу.", orAdmin = true, scope = GuideScope.PROXY), + GuideEntry( + "/pn groups <группа> <сервер>", + "pnlibrary.groups", + "Добавить сервер в группу или убрать.", + orAdmin = true, + scope = GuideScope.PROXY, + ), + GuideEntry( + "/pn groups <группа> <плагин>", + "pnlibrary.groups", + "Плагин обязателен для группы или больше нет.", + orAdmin = true, + scope = GuideScope.PROXY, + ), + GuideEntry( + "/pn groups <группа> <сервер> [плагин]", + "pnlibrary.groups", + "Чем один сервер отличается от группы: показать, не нужен плагин, нужен лишний, сбросить.", + orAdmin = true, + scope = GuideScope.PROXY, + ), + GuideEntry("/pn groups of <сервер>", "pnlibrary.groups", "В каких группах состоит сервер.", orAdmin = true, scope = GuideScope.PROXY), + GuideEntry( + "/pn groups check <группа>", + "pnlibrary.updates.view", + "Все серверы группы проверят обновления.", + scope = GuideScope.PROXY, + note = "Нужно и право на /pn groups.", + ), + GuideEntry( + "/pn groups update <группа>", + "pnlibrary.updates.download", + "Все серверы группы скачают доступные обновления.", + scope = GuideScope.PROXY, + note = "Нужно и право на /pn groups.", + ), + ), + ), + GuideSection( + "Меню и валюты", + listOf( + GuideEntry( + "/pn gui", + "pnlibrary.updates.view", + "Меню в инвентаре: плагины, обновления, история, ошибки, настройки.", + orAdmin = true, + scope = GuideScope.GAME_SERVER, + note = "Только игрок: в консоли нет инвентаря.", + ), + GuideEntry("/pn money list", "pnlibrary.currency.list", "Список валют."), + GuideEntry( + "/pn money <валюта> …", + "pnlibrary.currency.<валюта>.<действие>", + "Баланс, история, начисление, списание, установка, обнуление и перевод игроку.", + scope = GuideScope.GAME_SERVER, + note = "Право своё для каждой валюты и действия; плагин валюты может задать другое начало через permissionPrefix.", + ), + GuideEntry( + "/pn money <код>", + null, + "Подтвердить или отменить опасную операцию с валютой.", + scope = GuideScope.GAME_SERVER, + note = "Только консоль.", + ), + ), + ), + ) + + /** How to read the list: the rules that hold for all entries. */ + val notes: List = listOf( + "Консоль выполняет все команды без прав.", + "«Право: A или pnlibrary.admin» значит, что подойдёт любое из двух. Если в заметке сказано «нужно и право …», нужны оба.", + "Подкоманды /pn updates … требуют ещё pnlibrary.updates.view или pnlibrary.admin, " + + "подкоманды /pn update … требуют ещё pnlibrary.updates.download или pnlibrary.admin.", + "На игровом сервере команда называется /pn (есть и /pnlib, /pnlibrary). " + + "На прокси она называется /pnproxy (есть и /pnp), в этом файле она везде записана как /pn.", + ) + + /** Every entry of every section. */ + val entries: List = sections.flatMap(GuideSection::entries) + + /** Every permission node the guide names, patterns excluded, plus `pnlibrary.admin`. */ + val permissions: Set = entries.filterNot(GuideEntry::isPattern).mapNotNull(GuideEntry::permission).toSet() + ADMIN + + /** The permissions that exist only on a proxy and so are not declared in the Bukkit plugin.yml. */ + val proxyOnly: Set = entries.partition { it.scope == GuideScope.PROXY } + .let { (proxy, others) -> proxy.mapNotNull(GuideEntry::permission).toSet() - others.mapNotNull(GuideEntry::permission).toSet() - ADMIN } + + /** The lines of the guide between the heading and the signature of `Команды.txt`. */ + fun lines(): List = buildList { + for (section in sections) { + add("") + add(section.title) + add("-".repeat(section.title.length)) + for (entry in section.entries) { + add("") + add(entry.usage) + add(" Право: ${rights(entry)}") + add(" ${entry.description}") + entry.scope.note?.let { add(" $it") } + entry.note?.let { add(" $it") } + } + } + } + + private fun rights(entry: GuideEntry): String { + val permission = entry.permission ?: return "не нужно" + return when { + permission == ADMIN -> permission + entry.orAdmin -> "$permission или $ADMIN" + else -> permission + } + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/LibraryInfoFiles.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/LibraryInfoFiles.kt new file mode 100644 index 000000000..6a2976f4d --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/LibraryInfoFiles.kt @@ -0,0 +1,203 @@ +package org.pnfolder.pnlibrary.core.settings + +import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity +import org.pnfolder.pnlibrary.common.io.AtomicFiles +import org.pnfolder.pnlibrary.common.io.TextFiles +import org.pnfolder.pnlibrary.updates.paths.InfoFileNames +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import java.io.IOException +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.Files +import java.nio.file.InvalidPathException +import java.nio.file.Path +import java.time.Clock +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter +import java.util.concurrent.atomic.AtomicBoolean + +/** + * The three text files an administrator can open in the library's own folder: the help (`Помощь.txt`), the overview of + * every setting with its current value (`Настройки.txt`) and the list of every command and permission (`Команды.txt`). + * + * The text is ours and lives here, in code. All files are created again at every start and the overview also after every + * change of a setting, so the links ([supportUrl], [repositoryUrl]) and the values are always those of the running library. + * Nothing is cached anywhere else, and edits made by hand are lost. + * + * A file is rewritten only when its text changed, ignoring the line with the creation time: this way a start that changes + * nothing leaves the files and their modification times alone. Writing never throws; the first failure is reported once + * through [warning] and the library goes on. + * + * @param values the settings with their values now + * @param version the library version shown at the end of every file + * @param clock the source of the creation time + */ +internal class LibraryInfoFiles( + private val paths: LibraryPaths, + private val values: () -> List, + private val version: String, + private val clock: Clock = Clock.systemUTC(), + private val supportUrl: String = PnLibraryIdentity.SUPPORT_URL, + private val repositoryUrl: String = PnLibraryIdentity.REPOSITORY_URL, + private val warning: (String) -> Unit = {}, +) { + private val warned = AtomicBoolean(false) + + /** Writes every file; call it once the settings are loaded. */ + fun refresh() { + refreshHelp() + refreshSettings() + refreshCommands() + } + + /** Writes the help file. */ + fun refreshHelp() = publish(paths.help, helpText()) + + /** Writes the settings overview; call it after a setting changed. */ + fun refreshSettings() = publish(paths.settingsOverview, settingsText()) + + /** Writes the list of commands and permissions. */ + fun refreshCommands() = publish(paths.commandGuide, commandsText()) + + /** The text of the help file. */ + fun helpText(): String = lines( + "Помощь pnLibrary", + "================", + "", + "pnLibrary — общая библиотека плагинов pnFolder для серверов Minecraft.", + "Она ведёт настройки, обновления, диагностику и меню для всех наших плагинов.", + "", + "Нужна помощь или есть вопрос?", + " Напишите нам в Discord: $supportUrl", + "", + "Хотите улучшить плагин или заказать новый?", + " Идею, как улучшить плагин, присылайте туда же, в Discord: $supportUrl", + " Бесплатный плагин тоже можно заказать там же: просто напишите нам.", + "", + "Код и документация", + " GitHub: $repositoryUrl", + " Документация: $repositoryUrl/tree/main/docs", + "", + "Все команды и права", + " Полный список с правами лежит в файле ${paths.commandGuide.preferred}.", + "", + "Самые полезные команды", + " /pn updates каталог плагинов и их обновления", + " /pn check проверить, есть ли новые версии", + " /pn update <плагин> подготовить обновление плагина", + " /pn settings настройки библиотеки (все они перечислены в файле ${paths.settingsOverview.preferred})", + " /pn debug собрать отчёт для поддержки", + " /pn support ссылка на поддержку", + " /pn gui меню", + "", + "Где библиотека хранит свои данные", + " В папке data/ рядом с этим файлом.", + "", + "Этот файл создаётся заново при каждом запуске, ваши правки не сохранятся.", + "", + *signature(), + ) + + /** The text of the settings overview. */ + fun settingsText(): String { + val settings = values() + return lines( + "Настройки pnLibrary", + "===================", + "", + "ВАЖНО: этот файл только для чтения, это справка.", + "Здесь показано, какие настройки есть и какие у них сейчас значения.", + "Если вы поменяете что-то в этом файле, ничего не изменится: библиотека перезапишет его.", + "Менять настройки нужно командой или в меню, как описано ниже.", + "", + "Как изменить настройку:", + " /pn settings list все настройки со значениями", + " /pn settings get <ключ> одна настройка подробно", + " /pn settings set <ключ> <значение> изменить", + " /pn settings reset <ключ> вернуть значение по умолчанию", + " Или в меню: /pn gui, раздел «Настройки», «Параметры библиотеки».", + "Изменённые значения хранятся в data/settings.json, править его руками не нужно.", + "", + "Этот файл создаётся заново при каждом запуске и после каждого изменения настройки, ваши правки не сохранятся.", + "", + "Настроек: ${settings.size}", + *settings.flatMap(::describe).toTypedArray(), + "", + *signature(), + ) + } + + /** The text of the command guide: the header, how to read it and [LibraryCommandGuide]. */ + fun commandsText(): String = lines( + "Команды и права pnLibrary", + "=========================", + "", + "Все права по умолчанию у операторов; назначайте их в LuckPerms или другом менеджере прав.", + "Этот файл создаётся заново при каждом запуске, ваши правки не сохранятся.", + "", + "Как читать этот файл", + *LibraryCommandGuide.notes.map { " $it" }.toTypedArray(), + *LibraryCommandGuide.lines().toTypedArray(), + "", + *signature(), + ) + + private fun describe(value: SettingValue): List { + val spec = value.spec + return listOfNotNull( + "", + "${spec.key} (${spec.title})", + " Сейчас: ${spec.display(value.current)}${if (value.changed) " (изменено администратором)" else " (по умолчанию)"}", + " По умолчанию: ${spec.display(spec.default)}", + " Тип: ${spec.kind.label}", + spec.range().takeIf(String::isNotEmpty)?.let { " Границы: $it" }, + spec.examples.takeIf(List::isNotEmpty)?.let { " Примеры: ${it.joinToString(", ")}" }, + " Начнёт работать: ${spec.applies.label}", + " ${spec.description}", + " Изменить: /pn settings set ${spec.key} ${spec.examples.firstOrNull() ?: if (spec.kind == SettingKind.SWITCH) "включено" else "<значение>"}", + ) + } + + private fun signature(): Array = + arrayOf("${PnLibraryIdentity.NAME} $version", "$CREATED${TIME.format(clock.instant())} UTC") + + private fun lines(vararg text: String): String = text.joinToString("\n", postfix = "\n") + + /** + * Writes [text] under the Russian name, or under the ASCII one when the server cannot create a file with a Russian + * name: a JVM that runs with a non-UTF-8 file-name encoding (`sun.jnu.encoding`, common on Linux hosts with the C + * locale) fails with [InvalidPathException] or [IOException] for such a name. + */ + private fun publish(names: InfoFileNames, text: String) { + try { + try { + writeIfChanged(paths.pluginFolder.resolve(names.preferred), text) + } catch (error: Exception) { + if (error !is InvalidPathException && error !is IOException) throw error + writeIfChanged(paths.pluginFolder.resolve(names.ascii), text) + } + } catch (error: Exception) { + if (warned.compareAndSet(false, true)) { + warning("Не удалось записать файл ${names.preferred} в папку плагина: ${error.message}. Работе это не мешает.") + } + } + } + + private fun writeIfChanged(target: Path, text: String) { + val existing = if (Files.isRegularFile(target)) readOrNull(target) else null + if (existing != null && withoutTime(existing) == withoutTime(text)) return + AtomicFiles.write(target, text.toByteArray(UTF_8)) + } + + private fun readOrNull(file: Path): String? = try { + TextFiles.read(file, UTF_8) + } catch (_: IOException) { + null + } + + private fun withoutTime(text: String): List = text.lines().filterNot { it.startsWith(CREATED) } + + private companion object { + const val CREATED = "Создан: " + val TIME: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneOffset.UTC) + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/LibrarySettings.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/LibrarySettings.kt new file mode 100644 index 000000000..ffe4a5642 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/LibrarySettings.kt @@ -0,0 +1,48 @@ +package org.pnfolder.pnlibrary.core.settings + +import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig +import org.pnfolder.pnlibrary.updates.policy.UpdateDefaults +import java.time.Duration +import java.time.ZoneId + +/** + * Every setting of the library an administrator may change, with its default value. + * + * Each property has exactly one entry in [SettingsRegistry], which knows its key, limits and description; a test fails + * when a property is added here without one. The values are kept by [SettingsStore] in `data/settings.json`. + */ +internal data class LibrarySettings( + /** Whether personal data of players is left out of diagnostic reports. */ + val privacy: Boolean = false, + /** Days the diagnostic history is kept. */ + val historyRetentionDays: Int = 30, + /** Whether warnings and errors of plugins that are not connected to pnLibrary go to the journal too. */ + val journalForeignPlugins: Boolean = false, + /** Zone id used for every time pnLibrary shows. */ + val timeZone: String = ZoneId.systemDefault().id, + /** What a player sees without the permission for a command. */ + val noPermissionMessage: String = "Недостаточно прав для этой команды.", + /** Whether plugins may download files through pnLibrary at all. */ + val downloadsEnabled: Boolean = true, + /** Whether downloads that a plugin starts itself, without a command, are allowed. */ + val downloadsAutomatic: Boolean = true, + /** Whether a file may be saved into the data folder of the plugin that asked for it. */ + val downloadsToDataFolder: Boolean = true, + /** Whether a file may be saved into the shared cache of pnLibrary. */ + val downloadsToCache: Boolean = true, + /** How often the release catalogs are asked for new versions. */ + val updateCheckInterval: Duration = UpdateDefaults.CHECK_INTERVAL, + /** How long to wait for a connection while downloading an update file. */ + val updateConnectTimeout: Duration = UpdateDefaults.CONNECT_TIMEOUT, + /** How long to wait for data from a silent server while downloading an update file. */ + val updateReadTimeout: Duration = UpdateDefaults.READ_TIMEOUT, +) { + /** The runtime policy of diagnostics and command answers; everything not listed here keeps its default. */ + fun toConfig(): PnLibraryConfig = PnLibraryConfig( + historyRetentionDays = historyRetentionDays, + privacy = privacy, + noPermissionMessage = noPermissionMessage, + journalForeignPlugins = journalForeignPlugins, + timeZone = timeZone, + ) +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingPickerHook.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingPickerHook.kt new file mode 100644 index 000000000..a328af48e --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingPickerHook.kt @@ -0,0 +1,13 @@ +package org.pnfolder.pnlibrary.core.settings + +import org.pnfolder.pnlibrary.api.commands.CommandContext + +/** + * The link between `/pn settings pick` and the inventory menu: a platform that has menus sets [opener], the command calls it. + * A platform without menus (a proxy) leaves it empty, and the command says so. + */ +class SettingPickerHook { + /** Opens the list of values of the setting `key`, narrowed to `filter`, for the player who ran the command; `false` when it cannot. */ + @Volatile + var opener: ((context: CommandContext, key: String, filter: String) -> Boolean)? = null +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingSpec.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingSpec.kt new file mode 100644 index 000000000..3824ec3c2 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingSpec.kt @@ -0,0 +1,71 @@ +package org.pnfolder.pnlibrary.core.settings + +/** What kind of value a setting holds; it decides how the value is typed, checked and shown. */ +internal enum class SettingKind(val label: String) { + SWITCH("вкл/выкл"), + NUMBER("число"), + TEXT("текст"), + TIME("время"), + CHOICE("выбор из списка"), +} + +/** When a changed value starts to work. */ +internal enum class SettingApply(val label: String) { + LIVE("сразу"), + RESTART("после перезапуска"), +} + +/** A value that cannot be accepted for a setting; [message] says why, in words for the administrator. */ +internal class SettingException(message: String) : IllegalArgumentException(message) + +/** + * One setting: its key, kind, limits, description and how to read and change it in [LibrarySettings]. + * + * @property key the name used in commands and in `settings.json`, such as `downloads.enabled` + * @property title the short name shown in the menu + * @property field the property of [LibrarySettings] it controls + * @property min lowest number, or lowest length in milliseconds for a time + * @property max highest number, or highest length in milliseconds for a time + * @property choices the list a [SettingKind.CHOICE] setting is chosen from + */ +internal class SettingSpec( + val key: String, + val title: String, + val field: String, + val kind: SettingKind, + val description: String, + val applies: SettingApply, + val min: Long? = null, + val max: Long? = null, + val examples: List = emptyList(), + val choices: ChoiceSource? = null, + private val read: (LibrarySettings) -> Any, + private val write: (LibrarySettings, Any) -> LibrarySettings, + private val parse: (String) -> Any, + private val show: (Any) -> String, +) { + /** The value of this setting in [settings], as the text an administrator would type. */ + fun valueIn(settings: LibrarySettings): String = show(read(settings)) + + /** The default value as text. */ + val default: String get() = valueIn(LibrarySettings()) + + /** [value] (from [valueIn] or [default]) as people read it: a switch says `включено` or `выключено`, the rest is as is. */ + fun display(value: String): String = if (kind == SettingKind.SWITCH) SettingTexts.switchWord(value == "true") else value + + /** [settings] with this setting changed to [text]. + * @throws SettingException when [text] is not acceptable */ + fun apply(settings: LibrarySettings, text: String): LibrarySettings = write(settings, parse(text)) + + /** [text] as it is shown after being accepted (`1h30m` and `90m` are the same time). + * @throws SettingException when [text] is not acceptable */ + fun normalize(text: String): String = show(parse(text)) + + /** The range in words, or an empty text when the value has no range. */ + fun range(): String = when { + kind == SettingKind.NUMBER && min != null && max != null -> "от $min до $max" + kind == SettingKind.TIME && min != null && max != null -> "от ${SettingTexts.duration(min)} до ${SettingTexts.duration(max)}" + kind == SettingKind.TEXT && max != null -> "до $max символов" + else -> "" + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingTexts.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingTexts.kt new file mode 100644 index 000000000..32cc8b6ed --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingTexts.kt @@ -0,0 +1,68 @@ +package org.pnfolder.pnlibrary.core.settings + +import java.time.Duration + +/** Reading and writing the values of settings as text. */ +internal object SettingTexts { + private val PART = Regex("""(\d+(?:[.,]\d+)?)\s*(ms|мс|сек|с|s|мин|м|m|ч|h|д|d)""") + private val ON = setOf("true", "on", "yes", "да", "вкл", "включено", "1") + private val OFF = setOf("false", "off", "no", "нет", "выкл", "выключено", "0") + private const val DAY = 86_400_000L + private const val HOUR = 3_600_000L + private const val MINUTE = 60_000L + private const val SECOND = 1_000L + + /** `true` or `false` from the usual words for them. */ + fun switch(text: String): Boolean = when (text.trim().lowercase()) { + in ON -> true + in OFF -> false + else -> throw SettingException("Нужно значение вкл или выкл (можно также включено, выключено, true, false, on, off, да, нет).") + } + + /** How a switch is read by people: `включено` or `выключено`; the stored value stays `true` or `false`. */ + fun switchWord(on: Boolean): String = if (on) "включено" else "выключено" + + /** A whole number inside [min]..[max]. */ + fun number(text: String, min: Long, max: Long): Int { + val value = text.trim().toLongOrNull() ?: throw SettingException("Нужно целое число от $min до $max.") + if (value !in min..max) throw SettingException("Число $value вне допустимых границ: от $min до $max.") + return value.toInt() + } + + /** A length of time such as `6h`, `1h30m`, `90 мин` or `45s`, inside [min]..[max] milliseconds. */ + fun duration(text: String, min: Long, max: Long): Duration { + val cleaned = text.trim().lowercase() + val parts = PART.findAll(cleaned).toList() + if (parts.isEmpty() || parts.joinToString("") { it.value }.replace(" ", "") != cleaned.replace(" ", "")) { + throw SettingException("Нужно время с единицей, например 30s, 15m, 6h, 1h30m (с, м, ч, д тоже годятся).") + } + val millis = parts.sumOf { part -> (part.groupValues[1].replace(',', '.').toDouble() * millisOf(part.groupValues[2])).toLong() } + if (millis !in min..max) { + throw SettingException("Время ${duration(millis)} вне допустимых границ: от ${duration(min)} до ${duration(max)}.") + } + return Duration.ofMillis(millis) + } + + /** A length of time as `1д2ч30м15с`, the shortest form that reads back to the same time. */ + fun duration(value: Duration): String = duration(value.toMillis()) + + fun duration(millis: Long): String { + if (millis <= 0) return "0с" + var rest = millis + return buildString { + for ((size, name) in listOf(DAY to "д", HOUR to "ч", MINUTE to "м", SECOND to "с", 1L to "мс")) { + val count = rest / size + rest %= size + if (count > 0) append(count).append(name) + } + } + } + + private fun millisOf(letters: String): Long = when (letters) { + "ms", "мс" -> 1L + "с", "s", "сек" -> SECOND + "м", "m", "мин" -> MINUTE + "ч", "h" -> HOUR + else -> DAY + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingsRegistry.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingsRegistry.kt new file mode 100644 index 000000000..58a4a45d0 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingsRegistry.kt @@ -0,0 +1,135 @@ +package org.pnfolder.pnlibrary.core.settings + +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import java.time.Duration +import java.time.ZoneId +import kotlin.reflect.KProperty1 + +/** + * The one list of every setting of the library: key, type, default, limits, description and when a change works. + * + * Nothing about the settings is described anywhere else; the command, the menu and the documentation read this list. + * A test checks that each property of [LibrarySettings] appears here exactly once. + */ +internal object SettingsRegistry { + private const val SECOND = 1_000L + private const val MINUTE = 60 * SECOND + private const val DAY = 24 * 60 * MINUTE + + val all: List = listOf( + switch( + "privacy", "Приватность отчёта", LibrarySettings::privacy, SettingApply.RESTART, + "Скрывать ли в диагностическом отчёте личные данные игроков: имена, UUID, адреса, пинг и названия текущих серверов.", + ) { s, v -> s.copy(privacy = v) }, + number( + "history-retention-days", "Хранение истории", LibrarySettings::historyRetentionDays, SettingApply.RESTART, 30, 365, + "Сколько дней хранить историю диагностики.", + ) { s, v -> s.copy(historyRetentionDays = v) }, + switch( + "journal-foreign-plugins", "Журнал: чужие плагины", LibrarySettings::journalForeignPlugins, SettingApply.RESTART, + "Писать ли в журнал предупреждения и ошибки плагинов, которые не подключены к pnLibrary.", + ) { s, v -> s.copy(journalForeignPlugins = v) }, + zone( + "time-zone", "Часовой пояс", LibrarySettings::timeZone, SettingApply.LIVE, + "Часовой пояс для всех времён, которые показывает pnLibrary. Хранится время всегда в UTC, смена пояса ничего не портит.", + listOf("UTC", "Europe/Moscow"), + ) { s, v -> s.copy(timeZone = v) }, + text( + "no-permission-message", "Текст без права", LibrarySettings::noPermissionMessage, SettingApply.RESTART, 256, + "Что видит игрок без права на команду pnLibrary или другого плагина, у которого нет собственного сообщения.", + ) { s, v -> s.copy(noPermissionMessage = v) }, + switch( + "downloads.enabled", "Загрузки", LibrarySettings::downloadsEnabled, SettingApply.LIVE, + "Система загрузок. Выключена: все запросы плагинов на загрузку файлов отклоняются.", + ) { s, v -> s.copy(downloadsEnabled = v) }, + switch( + "downloads.automatic", "Автозагрузка", LibrarySettings::downloadsAutomatic, SettingApply.LIVE, + "Разрешить загрузки, которые плагин запускает сам, без команды администратора (в том числе недостающие плагины).", + ) { s, v -> s.copy(downloadsAutomatic = v) }, + switch( + "downloads.destinations.data-folder", "Загрузки в папку плагина", LibrarySettings::downloadsToDataFolder, SettingApply.LIVE, + "Разрешить сохранять скачанные файлы в папку данных плагина, который их запросил.", + ) { s, v -> s.copy(downloadsToDataFolder = v) }, + switch( + "downloads.destinations.cache", "Загрузки в кэш", LibrarySettings::downloadsToCache, SettingApply.LIVE, + "Разрешить сохранять скачанные файлы в общий кэш pnLibrary.", + ) { s, v -> s.copy(downloadsToCache = v) }, + time( + "updates.check-interval", "Проверка обновлений", LibrarySettings::updateCheckInterval, SettingApply.RESTART, 15 * MINUTE, 7 * DAY, + "Как часто опрашивать каталоги релизов о новых версиях; первая проверка идёт при запуске.", + listOf("6h", "30m"), + ) { s, v -> s.copy(updateCheckInterval = v) }, + time( + "updates.connect-timeout", "Ожидание соединения", LibrarySettings::updateConnectTimeout, SettingApply.RESTART, SECOND, 2 * MINUTE, + "Сколько ждать соединения при скачивании файла обновления.", + listOf("10s"), + ) { s, v -> s.copy(updateConnectTimeout = v) }, + time( + "updates.read-timeout", "Ожидание данных", LibrarySettings::updateReadTimeout, SettingApply.RESTART, 5 * SECOND, 10 * MINUTE, + "Сколько ждать данных от молчащего сервера при скачивании файла обновления.", + listOf("30s", "2m"), + ) { s, v -> s.copy(updateReadTimeout = v) }, + ) + + private val byKey: Map = all.associateBy { it.key } + + /** The setting named [key], or `null`. */ + operator fun get(key: String): SettingSpec? = byKey[key] + + private fun switch( + key: String, title: String, property: KProperty1, applies: SettingApply, description: String, + write: (LibrarySettings, Boolean) -> LibrarySettings, + ) = SettingSpec( + key, title, property.name, SettingKind.SWITCH, description, applies, + read = { property.get(it) }, write = { s, v -> write(s, v as Boolean) }, + parse = SettingTexts::switch, show = { it.toString() }, + ) + + private fun number( + key: String, title: String, property: KProperty1, applies: SettingApply, min: Long, max: Long, description: String, + write: (LibrarySettings, Int) -> LibrarySettings, + ) = SettingSpec( + key, title, property.name, SettingKind.NUMBER, description, applies, min, max, + read = { property.get(it) }, write = { s, v -> write(s, v as Int) }, + parse = { SettingTexts.number(it, min, max) }, show = { it.toString() }, + ) + + private fun text( + key: String, title: String, property: KProperty1, applies: SettingApply, maxLength: Long, description: String, + write: (LibrarySettings, String) -> LibrarySettings, + ) = SettingSpec( + key, title, property.name, SettingKind.TEXT, description, applies, max = maxLength, + read = { property.get(it) }, write = { s, v -> write(s, v as String) }, + parse = { + val value = it.trim() + if (value.isEmpty() || value.length > maxLength) throw SettingException("Текст должен быть от 1 до $maxLength символов.") + value + }, + show = { it.toString() }, + ) + + private fun zone( + key: String, title: String, property: KProperty1, applies: SettingApply, description: String, examples: List, + write: (LibrarySettings, String) -> LibrarySettings, + ) = SettingSpec( + key, title, property.name, SettingKind.CHOICE, description, applies, examples = examples, choices = ChoiceSource.ZONES, + read = { property.get(it) }, write = { s, v -> write(s, v as String) }, + parse = { + val value = it.trim() + if (runCatchingNonFatal { ZoneId.of(value) }.isFailure) { + throw SettingException("Неизвестный часовой пояс «$value». Примеры: UTC, Europe/Moscow.") + } + value + }, + show = { it.toString() }, + ) + + private fun time( + key: String, title: String, property: KProperty1, applies: SettingApply, min: Long, max: Long, description: String, + examples: List, write: (LibrarySettings, Duration) -> LibrarySettings, + ) = SettingSpec( + key, title, property.name, SettingKind.TIME, description, applies, min, max, examples, + read = { property.get(it) }, write = { s, v -> write(s, v as Duration) }, + parse = { SettingTexts.duration(it, min, max) }, show = { SettingTexts.duration(it as Duration) }, + ) +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingsStore.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingsStore.kt new file mode 100644 index 000000000..6ef5a4d43 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/settings/SettingsStore.kt @@ -0,0 +1,159 @@ +package org.pnfolder.pnlibrary.core.settings + +import com.google.gson.GsonBuilder +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import com.google.gson.JsonPrimitive +import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig +import org.pnfolder.pnlibrary.common.io.AtomicFiles +import org.pnfolder.pnlibrary.common.io.TextFiles +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import java.io.IOException +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption +import java.util.concurrent.CopyOnWriteArrayList + +/** What changed when a setting was set or reset. */ +internal data class SettingChange(val spec: SettingSpec, val before: String, val after: String) + +/** A setting with its value now; [changed] says whether an administrator set it, as opposed to the default. */ +internal data class SettingValue(val spec: SettingSpec, val current: String, val changed: Boolean) + +/** + * The values of the library's settings, kept in one file (`data/settings.json`). + * + * Only what an administrator changed is written, so a default that is improved later reaches every server that never + * touched it. A value that cannot be read (unknown key, wrong type, outside its limits) is ignored with a warning and + * the default is used; a file that is not JSON at all is moved aside as `settings.json.broken`. Loading never throws. + * + * @param warning receives the problems found while reading, in words for the administrator + */ +internal class SettingsStore( + private val file: Path, + private val warning: (String) -> Unit = {}, +) { + private val gson = GsonBuilder().setPrettyPrinting().create() + private val listeners = CopyOnWriteArrayList<(LibrarySettings) -> Unit>() + + /** Key to the value as text, for what was set; the single source of truth together with the registry. */ + @Volatile + private var overrides: Map = load() + + @Volatile + private var settings: LibrarySettings = build(overrides) + + /** The values in force now. */ + fun current(): LibrarySettings = settings + + /** The runtime policy built from the values in force now. */ + fun config(): PnLibraryConfig = settings.toConfig() + + /** Every setting in registry order with its value now. */ + fun values(): List = SettingsRegistry.all.map { SettingValue(it, it.valueIn(settings), it.key in overrides) } + + /** The setting named [key] with its value now. + * @throws SettingException when there is no such setting */ + fun value(key: String): SettingValue { + val spec = specOf(key) + return SettingValue(spec, spec.valueIn(settings), key in overrides) + } + + /** Calls [listener] with the new values after every change; it runs on the thread that changed them. */ + fun onChange(listener: (LibrarySettings) -> Unit) { + listeners += listener + } + + /** + * Sets [key] to [text] and saves the file. + * + * @throws SettingException when the key is unknown, the value is not acceptable or the file cannot be written; + * nothing changes then + */ + @Synchronized + fun set(key: String, text: String): SettingChange { + val spec = specOf(key) + val next = overrides + (key to spec.normalize(text)) + return commit(spec, next) + } + + /** Returns [key] to its default and saves the file. + * @throws SettingException when the key is unknown or the file cannot be written */ + @Synchronized + fun reset(key: String): SettingChange { + val spec = specOf(key) + return commit(spec, overrides - key) + } + + private fun specOf(key: String): SettingSpec = + SettingsRegistry[key] ?: throw SettingException("Такой настройки нет: $key. Список: /pn settings list") + + private fun commit(spec: SettingSpec, next: Map): SettingChange { + val before = spec.valueIn(settings) + val built = build(next) + save(next) + overrides = next + settings = built + listeners.forEach { listener -> + runCatchingNonFatal { listener(built) }.onFailure { warning("Настройка ${spec.key} сохранена, но применить её сразу не вышло: ${it.message}") } + } + return SettingChange(spec, before, spec.valueIn(built)) + } + + private fun build(values: Map): LibrarySettings = + values.entries.fold(LibrarySettings()) { settings, (key, text) -> specOf(key).apply(settings, text) } + + private fun save(values: Map) { + val json = JsonObject() + SettingsRegistry.all.filter { it.key in values }.forEach { spec -> + val text = requireNotNull(values[spec.key]) + json.add( + spec.key, + when (spec.kind) { + SettingKind.SWITCH -> JsonPrimitive(text.toBoolean()) + SettingKind.NUMBER -> JsonPrimitive(text.toLong()) + SettingKind.TEXT, SettingKind.TIME, SettingKind.CHOICE -> JsonPrimitive(text) + }, + ) + } + try { + AtomicFiles.write(file, gson.toJson(json).toByteArray(UTF_8)) + } catch (error: IOException) { + throw SettingException("Не удалось сохранить ${file.fileName}: ${error.message}") + } + } + + private fun load(): Map { + if (!Files.isRegularFile(file)) return emptyMap() + val root = try { + JsonParser.parseString(TextFiles.read(file, UTF_8)).asJsonObject + } catch (_: Exception) { + moveAside() + return emptyMap() + } + val accepted = linkedMapOf() + root.entrySet().forEach { (key, element) -> + val spec = SettingsRegistry[key] + when { + spec == null -> warning("${file.fileName}: настройки «$key» нет, значение пропущено.") + !element.isJsonPrimitive -> warning("${file.fileName}: у настройки $key не то значение, берётся ${spec.default}.") + else -> try { + accepted[key] = spec.normalize(element.asString) + } catch (error: SettingException) { + warning("${file.fileName}: настройка $key: ${error.message} Берётся значение по умолчанию: ${spec.default}.") + } + } + } + return accepted + } + + private fun moveAside() { + val broken = file.resolveSibling("${file.fileName}.broken") + val outcome = runCatchingNonFatal { Files.move(file, broken, StandardCopyOption.REPLACE_EXISTING) } + warning( + if (outcome.isSuccess) "${file.fileName} не читается, значения по умолчанию; файл сохранён как ${broken.fileName}." + else "${file.fileName} не читается, значения по умолчанию.", + ) + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsCollector.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsCollector.kt index 7da790273..b07744b81 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsCollector.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsCollector.kt @@ -1,10 +1,10 @@ package org.pnfolder.pnlibrary.core.stats -import org.pnfolder.pnlibrary.api.events.EventInfo -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskStatus +import org.pnfolder.pnlibrary.api.events.inspect.EventInfo +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus import org.pnfolder.pnlibrary.core.journal.JournalLevel -import org.pnfolder.pnlibrary.core.journal.JournalStore +import org.pnfolder.pnlibrary.core.journal.store.JournalStore import org.pnfolder.pnlibrary.core.stats.StatsSnapshot import java.time.Duration diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsCommand.kt index 6ed37243d..225a226b4 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsCommand.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsCommand.kt @@ -2,10 +2,10 @@ package org.pnfolder.pnlibrary.core.stats import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.TextColor -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command -import org.pnfolder.pnlibrary.core.journal.ago +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command +import org.pnfolder.pnlibrary.core.journal.view.ago import org.pnfolder.pnlibrary.core.stats.StatsSnapshot /** diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsRecorder.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsRecorder.kt index b12675530..8dd50db28 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsRecorder.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsRecorder.kt @@ -4,7 +4,7 @@ import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.core.journal.JournalLevel import org.pnfolder.pnlibrary.core.journal.JournalRecord -import org.pnfolder.pnlibrary.core.journal.JournalStore +import org.pnfolder.pnlibrary.core.journal.store.JournalStore import org.pnfolder.pnlibrary.core.stats.StatsSnapshot import java.time.Duration import java.util.concurrent.Executors @@ -17,6 +17,7 @@ import java.util.concurrent.TimeUnit internal class StatsRecorder( private val collector: StatsCollector, private val journal: JournalStore, + private val onFailure: (Throwable) -> Unit = {}, ) : AutoCloseable { private val executor = Executors.newSingleThreadScheduledExecutor { task -> Thread(task, "pnLibrary-stats").apply { isDaemon = true } @@ -26,7 +27,7 @@ internal class StatsRecorder( executor.scheduleWithFixedDelay({ record() }, EVERY.toMinutes(), EVERY.toMinutes(), TimeUnit.MINUTES) } - /** Stores the current numbers; a failure is swallowed because statistics must never disturb the server. */ + /** Stores the current numbers; a failure goes to [onFailure] and never to the caller, so statistics cannot disturb the server. */ fun record() { runCatchingNonFatal { val snapshot = collector.collect() @@ -40,7 +41,7 @@ internal class StatsRecorder( details = snapshot.toDetails(), ), ) - } + }.onFailure(onFailure) } /** The stored snapshots of the last [days] days, newest first. */ diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsRuntime.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsRuntime.kt index 3c205b5e8..074da33cf 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsRuntime.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/stats/StatsRuntime.kt @@ -1,18 +1,19 @@ package org.pnfolder.pnlibrary.core.stats -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.events.EventInfo -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.core.journal.JournalStore +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.events.inspect.EventInfo +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.core.journal.store.JournalStore /** The statistics of the server as one part: taking a snapshot, keeping hourly ones in the journal, and `/pn stats`. */ internal class StatsRuntime( tasks: () -> List, events: () -> List, journal: JournalStore, + onFailure: (Throwable) -> Unit = {}, ) : AutoCloseable { private val collector = StatsCollector(tasks, events, journal) - private val recorder = StatsRecorder(collector, journal) + private val recorder = StatsRecorder(collector, journal, onFailure) @Volatile private var last: StatsSnapshot? = null diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/ManagedTask.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/ManagedTask.kt index 9d3ae26c2..efd25d6fe 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/ManagedTask.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/ManagedTask.kt @@ -1,15 +1,16 @@ package org.pnfolder.pnlibrary.core.tasks -import org.pnfolder.pnlibrary.api.tasks.TaskContext import org.pnfolder.pnlibrary.api.tasks.TaskHandle -import org.pnfolder.pnlibrary.api.tasks.TaskId -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskSpec -import org.pnfolder.pnlibrary.api.tasks.TaskStatus -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskLag +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.run.LagResponse +import org.pnfolder.pnlibrary.api.tasks.run.TaskContext +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskAdapter import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskHandle -import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest import java.time.Duration import java.time.Instant import java.util.concurrent.atomic.AtomicBoolean @@ -29,12 +30,17 @@ internal class ManagedTask( private val adapter: PlatformTaskAdapter, private val errorLogger: (Any, String, Throwable) -> Unit, private val onTerminal: (ManagedTask) -> Unit, + private val spawn: (TaskSpec, TaskId) -> TaskHandle = { _, _ -> error("This task cannot start other tasks") }, + private val parentId: TaskId? = null, ) : TaskHandle { override val id = TaskId.random() private val state = AtomicReference(TaskStatus.SCHEDULED) private val running = AtomicBoolean(false) private val runs = AtomicLong() private val skipped = AtomicLong() + private val failedRuns = AtomicLong() + private val failureStreak = AtomicLong() + private val linkedChildren = java.util.concurrent.ConcurrentLinkedQueue() private val cancelled = AtomicBoolean(false) private val native = AtomicReference() private val created = Instant.now() @@ -49,23 +55,33 @@ internal class ManagedTask( @Volatile private var lastDuration: Duration? = null + @Volatile private var lastLag: Duration? = null + + @Volatile private var worstLag: Duration? = null + override val status: TaskStatus get() = state.get() override val isCancelled: Boolean get() = cancelled.get() fun attach(handle: PlatformTaskHandle) { native.set(handle) - if (status.isOver()) handle.cancel() + if (status.isTerminal) handle.cancel() } /** The run the platform scheduled. */ fun invoke() = exclusively(onBusy = { skipped.incrementAndGet() }) { + val planned = nextRun ?: created.plus(spec.delay) nextRun = null when { spec.cancellationConditions.any { it.asBoolean } -> cancel() spec.conditions.any { !it.asBoolean } -> skip() - else -> { - runAction() - if (spec.interval == null) complete() else waitUntil(Instant.now().plus(spec.interval)) + tooLate(planned) -> skip() + else -> when (lagResponse(planned)) { + LagResponse.CANCEL -> cancel() + LagResponse.SKIP -> skip() + LagResponse.RUN -> { + runAction(planned) + if (spec.interval == null) complete() else waitUntil(Instant.now().plus(spec.interval)) + } } } } @@ -73,15 +89,16 @@ internal class ManagedTask( /** Starts a waiting task now, on its own execution context, and leaves its schedule as it was. */ fun runNow(): Boolean { if (status != TaskStatus.SCHEDULED) return false - adapter.schedule( - PlatformTaskRequest(spec.execution.kind, spec.execution.target, Duration.ZERO, null, Runnable { runRequested() }, owner = owner), - ) + adapter.buildTask() + .task { runRequested() } + .execution(spec.execution.kind, spec.execution.target) + .schedule() return true } private fun runRequested() = exclusively(onBusy = {}) { val plannedNext = nextRun - runAction() + runAction(Instant.now()) if (spec.interval != null) return@exclusively waitUntil(plannedNext) complete() native.get()?.cancel() @@ -89,12 +106,13 @@ internal class ManagedTask( /** Runs [body] unless the task is over; while another run is still going, calls [onBusy] instead. */ private inline fun exclusively(onBusy: () -> Unit, body: () -> Unit) { - if (status.isOver()) return + if (status.isTerminal) return if (!running.compareAndSet(false, true)) return onBusy() try { body() } catch (error: Throwable) { - fail(error) + failedRuns.incrementAndGet() + if (!survive(error)) fail(error) } finally { running.set(false) } @@ -106,8 +124,43 @@ internal class ManagedTask( if (spec.interval == null) complete() else nextRun = Instant.now().plus(spec.interval) } - private fun runAction() { + /** Notes how late the run is and lets the lag handler decide what happens to it. */ + private fun lagResponse(planned: Instant): LagResponse { + val report = TaskLag(id, spec.name, runs.get() + 1, planned, Instant.now(), spec.interval) + lastLag = report.lag + if (worstLag.let { it == null || report.lag > it }) worstLag = report.lag + val handler = spec.lagHandler ?: return LagResponse.RUN + if (!report.isOver(spec.lagThreshold)) return LagResponse.RUN + return try { + handler.handle(report) + } catch (error: Throwable) { + runCatching { errorLogger(owner, "[pnLibrary/tasks] Lag handler of task ${spec.name ?: id} failed", error) } + LagResponse.RUN + } + } + + /** Whether a run planned for [planned] started later than the task allows. */ + private fun tooLate(planned: Instant): Boolean = + spec.maxLag?.let { Duration.between(planned, Instant.now()) > it } == true + + /** A repeating task may survive some failures in a row: the failure is logged and the next interval tries again. */ + private fun survive(error: Throwable): Boolean { + val interval = spec.interval ?: return false + val streak = failureStreak.incrementAndGet() + if (streak > spec.tolerateFailures) return false + failure = describe(error) + runCatching { + errorLogger(owner, "[pnLibrary/tasks] Task ${spec.name ?: id} failed ($streak of ${spec.tolerateFailures} tolerated), trying again", error) + }.onFailure(error::addSuppressed) + waitUntil(Instant.now().plus(interval)) + return true + } + + private fun describe(error: Throwable) = "${error.javaClass.simpleName}: ${error.message.orEmpty()}" + + private fun runAction(plannedAt: Instant) { if (!state.compareAndSet(TaskStatus.SCHEDULED, TaskStatus.RUNNING)) return + val previousStart = started val runStartedAt = Instant.now() started = runStartedAt val number = runs.incrementAndGet() @@ -115,21 +168,44 @@ internal class ManagedTask( spec.action.run(object : TaskContext { override val id = this@ManagedTask.id override val name = spec.name + override val key = spec.key + override val tags = spec.tags + override val executionKind = spec.execution.kind + override val parentId = this@ManagedTask.parentId + override val execution = spec.execution + override val interval = spec.interval override val runNumber = number - override val scheduledAt = created.plus(spec.delay) + override val skippedCount get() = skipped.get() + override val scheduledAt = plannedAt override val startedAt = runStartedAt + override val previousStartedAt = previousStart + override val isCancelled get() = cancelled.get() override fun cancel() = this@ManagedTask.cancel() + override fun snapshot() = this@ManagedTask.snapshot() + override fun spawn(spec: TaskSpec) = spawnChild(spec) }) + failureStreak.set(0) lastDuration = Duration.ofNanos(System.nanoTime() - clock) } + /** Starts [child] under this task; a child that asked for it is cancelled when this task is. */ + private fun spawnChild(child: TaskSpec): TaskHandle { + val handle = spawn(child, id) + if (child.cancelWithParent) { + linkedChildren.removeIf { it.status.isTerminal } + linkedChildren += handle + if (cancelled.get()) handle.cancel() + } + return handle + } + private fun waitUntil(next: Instant?) { if (state.compareAndSet(TaskStatus.RUNNING, TaskStatus.SCHEDULED)) nextRun = next } private fun fail(error: Throwable) { val failed = end(TaskStatus.FAILED) - if (failed) failure = "${error.javaClass.simpleName}: ${error.message.orEmpty()}" + if (failed) failure = describe(error) ResourceCleanup.suppressInto( error, { native.get()?.cancel() }, @@ -152,6 +228,7 @@ internal class ManagedTask( try { native.get()?.cancel() } finally { + linkedChildren.forEach(TaskHandle::cancel) onTerminal(this) } return true @@ -159,8 +236,8 @@ internal class ManagedTask( /** Moves the task to the final [status]; false when it was already over. */ private fun end(status: TaskStatus): Boolean { - val previous = state.getAndUpdate { if (it.isOver()) it else status } - if (previous.isOver()) return false + val previous = state.getAndUpdate { if (it.isTerminal) it else status } + if (previous.isTerminal) return false completed = Instant.now() return true } @@ -177,6 +254,10 @@ internal class ManagedTask( nextRunAt = nextRun, runCount = runs.get(), skippedCount = skipped.get(), + failedCount = failedRuns.get(), + parentId = parentId, + lastLag = lastLag, + worstLag = worstLag, lastStartedAt = started, lastCompletedAt = completed, lastFailure = failure, @@ -191,8 +272,6 @@ internal class ManagedTask( ) } -private fun TaskStatus.isOver() = this == TaskStatus.COMPLETED || this == TaskStatus.CANCELLED || this == TaskStatus.FAILED - /** The class that holds the action; a lambda reports the class it was written in. */ private fun sourceOf(type: Class<*>): String = type.name.substringBefore("\$\$Lambda").substringBefore('/') diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/ScheduledTasks.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/ScheduledTasks.kt index 33e41c561..a776e3e9a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/ScheduledTasks.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/ScheduledTasks.kt @@ -1,23 +1,21 @@ package org.pnfolder.pnlibrary.core.tasks import org.pnfolder.pnlibrary.api.plugin.PluginId -import org.pnfolder.pnlibrary.api.tasks.TaskConflictPolicy import org.pnfolder.pnlibrary.api.tasks.TaskHandle -import org.pnfolder.pnlibrary.api.tasks.TaskId -import org.pnfolder.pnlibrary.api.tasks.TaskQuery import org.pnfolder.pnlibrary.api.tasks.TaskScope import org.pnfolder.pnlibrary.api.tasks.TaskServiceSettings -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskSpec -import org.pnfolder.pnlibrary.core.cleanup.ResourceCleanup +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskQuery +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.spec.TaskConflictPolicy +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskAdapter -import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest import java.util.Collections import java.util.IdentityHashMap import java.util.LinkedHashMap import java.util.concurrent.atomic.AtomicBoolean -/** Schedules tasks through the platform adapter, grouped into per-plugin scopes and kept in a bounded history. */ internal class ScheduledTasks( private val adapter: PlatformTaskAdapter, private val settings: TaskServiceSettings = TaskServiceSettings(), @@ -83,14 +81,17 @@ internal class ScheduledTasks( active.values.filter { belongs(it.owner, it.scopeToken) }.map { it.snapshot() } + history.values.filter { belongs(it.owner, it.scopeToken) }.map { it.snapshot } } - return Collections.unmodifiableList(all.filter { TaskQueryMatcher.matches(it, query) }) + return Collections.unmodifiableList(all.filter { query.matches(it) }) } private inner class Scope(override val owner: Any, private val scopeId: PluginId) : TaskScope { private val scopeToken = Any() private val scopeClosed = AtomicBoolean(false) - override fun schedule(spec: TaskSpec): TaskHandle { + override fun schedule(spec: TaskSpec): TaskHandle = scheduleUnder(spec, null) + + /** Schedules [spec] as a task of this scope, started by task [parent] when there is one. */ + private fun scheduleUnder(spec: TaskSpec, parent: TaskId?): TaskHandle { check(!scopeClosed.get() && !closed.get()) { "TaskScope is closed" } synchronized(lock) { val existing = spec.key?.let { key -> @@ -101,13 +102,15 @@ internal class ScheduledTasks( TaskConflictPolicy.KEEP_EXISTING -> return existing TaskConflictPolicy.REPLACE -> existing.cancel() } - val managed = newTask(owner, scopeToken, spec) + val managed = newTask(owner, scopeToken, spec, ::scheduleUnder, parent) active[managed.id] = managed val native = try { - adapter.schedule(PlatformTaskRequest( - spec.execution.kind, spec.execution.target, spec.delay, spec.interval, Runnable { managed.invoke() }, - owner = owner, - )) + val builder = adapter.buildTask() + .task { managed.invoke() } + .execution(spec.execution.kind, spec.execution.target) + .delay(spec.delay) + spec.interval?.let(builder::every) + builder.schedule() } catch (error: Throwable) { active.remove(managed.id) throw error @@ -146,8 +149,8 @@ internal class ScheduledTasks( } } - private fun newTask(owner: Any, scopeToken: Any, spec: TaskSpec) = - ManagedTask(owner, scopeToken, spec, adapter, errorLogger, ::archive) + private fun newTask(owner: Any, scopeToken: Any, spec: TaskSpec, spawn: (TaskSpec, TaskId) -> TaskHandle, parent: TaskId?) = + ManagedTask(owner, scopeToken, spec, adapter, errorLogger, ::archive, spawn, parent) /** Moves a finished task from the active list to the history; does nothing if it was already moved. */ private fun archive(task: ManagedTask) { diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskHistoryStore.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskHistoryStore.kt index 2c7f288c6..94078557a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskHistoryStore.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskHistoryStore.kt @@ -1,26 +1,18 @@ package org.pnfolder.pnlibrary.core.tasks -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskId -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import org.pnfolder.pnlibrary.common.io.TsvRecords import java.nio.file.Path import java.time.Duration import java.time.Instant -/** - * The finished tasks kept on disk, one tab-separated line each, so the history survives a restart. - * - * The first line holds the format version. Lines of the first format (16 fields) still load, with the newer fields at - * their defaults. A line that cannot be read is skipped, so a damaged file never stops - * the server from starting. Text fields escape tab, line break and backslash. - */ +// Older format (16 fields) still loads; newer fields default. Unreadable lines are skipped silently. internal class TaskHistoryStore(private val file: Path) { - /** The saved snapshots, oldest first; empty when there is no file or it cannot be read. */ fun load(): List = TsvRecords.read(file).mapNotNull { fields -> runCatching { parse(fields) }.getOrNull() } - /** Replaces the file with [snapshots]; a failure is ignored because the history is only a convenience. */ fun save(snapshots: List) { TsvRecords.write(file, HEADER, snapshots.map(::format)) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskQueryMatcher.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskQueryMatcher.kt deleted file mode 100644 index 95db46ac9..000000000 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskQueryMatcher.kt +++ /dev/null @@ -1,26 +0,0 @@ -package org.pnfolder.pnlibrary.core.tasks - -import org.pnfolder.pnlibrary.api.tasks.TaskQuery -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot - -/** Applies every optional [TaskQuery] criterion to a task snapshot. */ -internal object TaskQueryMatcher { - fun matches(snapshot: TaskSnapshot, query: TaskQuery): Boolean = - matchesIdentity(snapshot, query) && - matchesName(snapshot, query) && - matchesState(snapshot, query) && - snapshot.tags.containsAll(query.tags) - - private fun matchesIdentity(snapshot: TaskSnapshot, query: TaskQuery): Boolean = - (query.id == null || snapshot.id == query.id) && - (query.key == null || snapshot.key == query.key) - - private fun matchesName(snapshot: TaskSnapshot, query: TaskQuery): Boolean { - val fragment = query.nameContains ?: return true - return snapshot.name?.contains(fragment, ignoreCase = true) == true - } - - private fun matchesState(snapshot: TaskSnapshot, query: TaskQuery): Boolean = - (query.statuses.isEmpty() || snapshot.status in query.statuses) && - (query.executionKinds.isEmpty() || snapshot.executionKind in query.executionKinds) -} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskService.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskService.kt index 12f712ca1..125390b7a 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskService.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskService.kt @@ -2,50 +2,22 @@ package org.pnfolder.pnlibrary.core.tasks import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.api.tasks.TaskHandle -import org.pnfolder.pnlibrary.api.tasks.TaskId -import org.pnfolder.pnlibrary.api.tasks.TaskQuery import org.pnfolder.pnlibrary.api.tasks.TaskScope -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskQuery +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot -/** - * Cross-platform scheduling service with owner-scoped resource management. - * - * Repeated calls to [scope] with the same owner object return the same scope. Owner identity is - * used instead of [Any.equals], so distinct but equal objects receive distinct scopes. Platform - * adapters decide the exact global and entity execution model, including Folia region dispatch. - * Scope creation, lookup, queries, cancellation, and shutdown are safe from arbitrary threads. - * Query results are detached immutable snapshots; task actions run in the execution context - * selected by `TaskSpec.execution`, not necessarily on the calling thread. - */ +// Owner identity (not equals) is used for scope lookup — distinct but equal objects get distinct scopes. internal interface TaskService : AutoCloseable { - /** Returns the active scope associated with [owner], creating it when necessary. */ fun scope(owner: Any): TaskScope - - /** Returns an independently owned module scope for the native owner. */ fun scope(owner: Any, scopeId: PluginId): TaskScope = scope(owner) - - /** Returns the task identified by [id] across all active scopes. */ fun get(id: TaskId): TaskHandle? = null - - /** Returns the task identified by [id] or fails when unavailable. */ fun require(id: TaskId): TaskHandle = get(id) ?: error("Task $id is unavailable") - - /** Returns detached snapshots across all scopes that match [query]. */ fun query(query: TaskQuery = TaskQuery.all()): List = emptyList() - - /** Returns detached snapshots belonging to [owner] that match [query]. */ fun query(owner: Any, query: TaskQuery = TaskQuery.all()): List = emptyList() - - /** Cancels the task identified by [id] and reports whether it was active. */ fun cancel(id: TaskId): Boolean = get(id)?.cancelIfActive() ?: false - - /** Cancels the task for an administrator; a task made with `cancellable = false` refuses. */ fun cancelByAdmin(id: TaskId): TaskControl = TaskControl.UNAVAILABLE - - /** Runs the waiting repeating task now, outside its schedule; a task made with `runnableNow = false` refuses. */ fun runNow(id: TaskId): TaskControl = TaskControl.UNAVAILABLE - - /** Closes and removes [owner]'s scope when one exists. */ fun close(owner: Any) override fun close() diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/CachedComponents.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/CachedComponents.kt index ac214128a..4957d47c7 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/CachedComponents.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/CachedComponents.kt @@ -1,18 +1,17 @@ package org.pnfolder.pnlibrary.core.text import net.kyori.adventure.text.Component -import net.kyori.adventure.text.minimessage.MiniMessage import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService -import org.pnfolder.pnlibrary.api.text.ComponentCachePolicy -import org.pnfolder.pnlibrary.api.text.ComponentCacheScope -import org.pnfolder.pnlibrary.api.text.ComponentCacheStatistics -import org.pnfolder.pnlibrary.api.text.ComponentSerializer -import org.pnfolder.pnlibrary.api.text.ComponentSerializerType import org.pnfolder.pnlibrary.api.text.ComponentService import org.pnfolder.pnlibrary.api.text.ComponentTemplate +import org.pnfolder.pnlibrary.api.text.cache.ComponentCachePolicy +import org.pnfolder.pnlibrary.api.text.cache.ComponentCacheScope +import org.pnfolder.pnlibrary.api.text.cache.ComponentCacheStatistics +import org.pnfolder.pnlibrary.api.text.serializer.ComponentSerializer +import org.pnfolder.pnlibrary.api.text.serializer.ComponentSerializerType import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import java.util.Collections import java.util.UUID @@ -23,6 +22,8 @@ import java.util.concurrent.atomic.AtomicLong internal class CachedComponents( private val placeholders: PlaceholderService, private val sharedCache: ComponentCache, + private val mini: MiniText, + private val warn: (String) -> Unit, ) : ComponentService { private val serializers = ComponentSerializerType.values().associateWith(::serializerFor) private var cachePolicy = ComponentCachePolicy() @@ -88,14 +89,15 @@ internal class CachedComponents( override val type = type override fun deserialize(input: String): Component = when (type) { ComponentSerializerType.ADAPTIVE -> adaptive(input) - ComponentSerializerType.MINI_MESSAGE -> MINI.deserialize(input) + ComponentSerializerType.MINI_MESSAGE -> mini.deserialize(input, warn) ComponentSerializerType.LEGACY_AMPERSAND -> AMP.deserialize(input) ComponentSerializerType.LEGACY_SECTION -> SECTION.deserialize(input) ComponentSerializerType.ADVENTURE_JSON -> GSON.deserialize(input) ComponentSerializerType.PLAIN_TEXT -> Component.text(input) } override fun serialize(component: Component): String = when (type) { - ComponentSerializerType.ADAPTIVE, ComponentSerializerType.MINI_MESSAGE -> MINI.serialize(component) + ComponentSerializerType.ADAPTIVE, ComponentSerializerType.MINI_MESSAGE -> + mini.serialize(component, warn, AMP::serialize) ComponentSerializerType.LEGACY_AMPERSAND -> AMP.serialize(component) ComponentSerializerType.LEGACY_SECTION -> SECTION.serialize(component) ComponentSerializerType.ADVENTURE_JSON -> GSON.serialize(component) @@ -108,7 +110,7 @@ internal class CachedComponents( val trimmed = input.trimStart() if ((trimmed.startsWith('{') || trimmed.startsWith('[')) && runCatchingNonFatal { GSON.deserialize(input) }.isSuccess) return GSON.deserialize(input) - return MINI.deserialize(toMiniMessage(input)) + return mini.deserialize(toMiniMessage(input), warn) } private fun toMiniMessage(source: String): String { @@ -119,11 +121,10 @@ internal class CachedComponents( } companion object { - private val MINI = MiniMessage.miniMessage() - private val AMP = LegacyComponentSerializer.legacyAmpersand() - private val SECTION = LegacyComponentSerializer.legacySection() - private val GSON = GsonComponentSerializer.gson() - private val PLAIN = PlainTextComponentSerializer.plainText() + private val AMP by lazy { LegacyComponentSerializer.legacyAmpersand() } + private val SECTION by lazy { LegacyComponentSerializer.legacySection() } + private val GSON by lazy { GsonComponentSerializer.gson() } + private val PLAIN by lazy { PlainTextComponentSerializer.plainText() } private val OLD_GRADIENT = Regex("<&?#([0-9a-fA-F]{6})>([^<]*)") private val HEX = Regex("(?i)(?)") private val LEGACY = Regex("&([0-9a-fk-or])", RegexOption.IGNORE_CASE) diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/ui/ConsoleStyle.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/ConsoleStyle.kt similarity index 91% rename from modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/ui/ConsoleStyle.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/ConsoleStyle.kt index bd9f678ea..f4d501061 100644 --- a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/ui/ConsoleStyle.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/ConsoleStyle.kt @@ -1,12 +1,12 @@ -package org.pnfolder.pnlibrary.core.ui +package org.pnfolder.pnlibrary.core.text import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.TextColor import net.kyori.adventure.text.format.TextDecoration import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.chat.color +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.color import org.pnfolder.pnlibrary.console.ConsoleTheme /** diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/CoreFormatting.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/CoreFormatting.kt new file mode 100644 index 000000000..6df452c6e --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/CoreFormatting.kt @@ -0,0 +1,47 @@ +package org.pnfolder.pnlibrary.core.text + +import java.time.LocalDate +import java.time.format.DateTimeFormatter +import java.util.Locale + +internal const val NANOS_PER_MICRO = 1_000L +internal const val NANOS_PER_MILLI = 1_000_000L +internal const val BAR_WIDTH = 12 +internal const val WRAP_WIDTH = 44 +internal val DAY: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMMM", Locale("ru")) +private val DAY_YEAR: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMMM yyyy", Locale("ru")) +private const val WRAP_LINES = 8 + +internal fun shortName(name: String): String = name.substringAfterLast('.') + +internal fun nanosText(nanos: Long): String = + if (nanos >= NANOS_PER_MILLI) "%.1f мс".format(nanos / NANOS_PER_MILLI.toDouble()) + else "%.1f мкс".format(nanos / NANOS_PER_MICRO.toDouble()) + +internal fun dayTitle(date: LocalDate, today: LocalDate): String = when (date) { + today -> "Сегодня" + today.minusDays(1) -> "Вчера" + else -> (if (date.year == today.year) DAY else DAY_YEAR).format(date) +} + +internal fun wrapText(text: String, width: Int = WRAP_WIDTH, limit: Int = WRAP_LINES): List { + val lines = ArrayList() + for (raw in text.lines()) { + var line = StringBuilder() + for (word in raw.trim().split(' ')) { + if (line.isNotEmpty() && line.length + 1 + word.length > width) { + lines += line.toString() + line = StringBuilder() + } + var rest = word + while (rest.length > width) { + lines += rest.take(width) + rest = rest.drop(width) + } + if (line.isNotEmpty()) line.append(' ') + line.append(rest) + } + lines += line.toString() + } + return if (lines.size > limit) lines.take(limit) + "…" else lines +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/MiniMessageLite.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/MiniMessageLite.kt new file mode 100644 index 000000000..862d9c844 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/MiniMessageLite.kt @@ -0,0 +1,122 @@ +package org.pnfolder.pnlibrary.core.text + +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.format.NamedTextColor +import net.kyori.adventure.text.format.TextColor +import net.kyori.adventure.text.format.TextDecoration + +/** + * MiniMessage subset for servers whose own Adventure is too old for the real one. It only calls long-standing + * Adventure methods (`Component.text`, `color`, `decoration`, `append`). Colors by name, `#rrggbb`, `color:`, + * decorations, `reset`, `br`/`newline` and escaping with a backslash match MiniMessage; unknown tags stay plain text. + * `gradient`, `transition` and `rainbow` degrade to their first color or to no color. + */ +internal object MiniMessageLite { + private class Entry(val name: String, val color: TextColor?, val decoration: Pair?) + + private val COLORS: Map = mapOf( + "black" to NamedTextColor.BLACK, "dark_blue" to NamedTextColor.DARK_BLUE, + "dark_green" to NamedTextColor.DARK_GREEN, "dark_aqua" to NamedTextColor.DARK_AQUA, + "dark_red" to NamedTextColor.DARK_RED, "dark_purple" to NamedTextColor.DARK_PURPLE, + "gold" to NamedTextColor.GOLD, "gray" to NamedTextColor.GRAY, "grey" to NamedTextColor.GRAY, + "dark_gray" to NamedTextColor.DARK_GRAY, "dark_grey" to NamedTextColor.DARK_GRAY, + "blue" to NamedTextColor.BLUE, "green" to NamedTextColor.GREEN, "aqua" to NamedTextColor.AQUA, + "red" to NamedTextColor.RED, "light_purple" to NamedTextColor.LIGHT_PURPLE, + "yellow" to NamedTextColor.YELLOW, "white" to NamedTextColor.WHITE, + ) + private val DECORATIONS: Map = mapOf( + "bold" to TextDecoration.BOLD, "b" to TextDecoration.BOLD, + "italic" to TextDecoration.ITALIC, "i" to TextDecoration.ITALIC, "em" to TextDecoration.ITALIC, + "underlined" to TextDecoration.UNDERLINED, "u" to TextDecoration.UNDERLINED, + "strikethrough" to TextDecoration.STRIKETHROUGH, "st" to TextDecoration.STRIKETHROUGH, + "obfuscated" to TextDecoration.OBFUSCATED, "obf" to TextDecoration.OBFUSCATED, + ) + private val COLOR_PREFIXES = setOf("color", "c", "colour") + private val FADES = setOf("gradient", "transition", "rainbow") + + fun deserialize(input: String): Component { + val stack = ArrayList() + val text = StringBuilder() + val parts = ArrayList() + var i = 0 + while (i < input.length) { + val c = input[i] + if (c == '\\' && input.startsWith("<", i + 1)) { + text.append('<') + i += 2 + continue + } + val end = if (c == '<') tagEnd(input, i) else -1 + if (end < 0 || !apply(input.substring(i + 1, end), stack, text, parts)) { + text.append(c) + i++ + continue + } + i = end + 1 + } + flush(text, stack, parts) + return parts.fold(Component.text()) { builder, part -> builder.append(part) }.build() + } + + private fun tagEnd(input: String, start: Int): Int { + for (j in start + 1 until input.length) { + if (input[j] == '>') return j + if (input[j] == '<') return -1 + } + return -1 + } + + /** Returns false for an unknown tag or a closing tag with nothing open, so the caller keeps it as text. */ + private fun apply(tag: String, stack: MutableList, text: StringBuilder, parts: MutableList): Boolean { + val lower = tag.lowercase() + val closing = lower.startsWith("/") + val negated = lower.startsWith("!") + val body = lower.removePrefix("/").removePrefix("!") + val args = body.split(':') + val name = args[0] + if (!closing && !negated && (name == "br" || name == "newline")) { + flush(text, stack, parts) + parts += Component.text("\n") + return true + } + if (!closing && !negated && name == "reset") { + flush(text, stack, parts) + stack.clear() + return true + } + val entry = entryFor(name, args, negated, closing) ?: return false + val index = if (closing) stack.indexOfLast { it.name == entry.name } else -1 + if (closing && index < 0) return false + flush(text, stack, parts) + if (closing) while (stack.size > index) stack.removeAt(stack.size - 1) else stack += entry + return true + } + + private fun entryFor(name: String, args: List, negated: Boolean, closing: Boolean): Entry? { + DECORATIONS[name]?.let { return Entry(it.name, null, it to !negated) } + if (negated) return null + if (name in COLOR_PREFIXES && closing) return Entry("color", null, null) + if (name in COLOR_PREFIXES) return parseColor(args.getOrNull(1))?.let { Entry("color", it, null) } + if (name in FADES) return Entry(name, args.drop(1).firstNotNullOfOrNull(::parseColor), null) + return parseColor(name)?.let { Entry(name, it, null) } + } + + private fun parseColor(value: String?): TextColor? { + if (value == null) return null + COLORS[value]?.let { return it } + val hex = value.removePrefix("#") + if (!value.startsWith("#") || hex.length != 6 || hex.any { Character.digit(it, 16) < 0 }) return null + return TextColor.color(hex.toInt(16)) + } + + private fun flush(text: StringBuilder, stack: List, parts: MutableList) { + if (text.isEmpty()) return + var part = Component.text(text.toString()) + stack.lastOrNull { it.color != null }?.color?.let { part = part.color(it) } + for ((decoration, state) in stack.mapNotNull { it.decoration }.associate { it }) { + part = part.decoration(decoration, state) + } + parts += part + text.setLength(0) + } +} diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/MiniText.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/MiniText.kt new file mode 100644 index 000000000..4c647bc17 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/text/MiniText.kt @@ -0,0 +1,33 @@ +package org.pnfolder.pnlibrary.core.text + +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.minimessage.MiniMessage +import java.util.concurrent.atomic.AtomicBoolean + +/** + * MiniMessage when the server's Adventure can run it, otherwise [MiniMessageLite]. Availability is checked once; + * only linkage errors count as "too old", any other failure is a real bug and propagates. + */ +internal class MiniText(private val factory: () -> MiniMessage = MiniMessage::miniMessage) { + private val probe: Result by lazy { + try { + Result.success(factory().also { it.deserialize("x") }) + } catch (error: LinkageError) { + Result.failure(error) + } + } + private val warned = AtomicBoolean(false) + + fun deserialize(input: String, warn: (String) -> Unit): Component = + available(warn)?.deserialize(input) ?: MiniMessageLite.deserialize(input) + + fun serialize(component: Component, warn: (String) -> Unit, fallback: (Component) -> String): String = + available(warn)?.serialize(component) ?: fallback(component) + + private fun available(warn: (String) -> Unit): MiniMessage? = probe.getOrElse { error -> + if (warned.compareAndSet(false, true)) { + warn("Adventure сервера слишком старый для MiniMessage, включён упрощённый разбор (${error.javaClass.simpleName}: ${error.message})") + } + null + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupQuery.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupQuery.kt similarity index 100% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupQuery.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupQuery.kt diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupsScreen.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupsScreen.kt similarity index 95% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupsScreen.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupsScreen.kt index 54953519a..0bee0b78a 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupsScreen.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupsScreen.kt @@ -1,14 +1,16 @@ package org.pnfolder.pnlibrary.core.updates.catalog import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup import org.pnfolder.pnlibrary.common.text.RussianText +import org.pnfolder.pnlibrary.updates.history.BackupItemText import java.time.Instant import java.time.ZoneId /** Retained rollback sets with their age; paths and file contents are never shown. */ internal class BackupsScreen(routes: UpdateCatalogRoutes, now: Instant, zone: ZoneId) : CatalogStyle(routes, now, zone) { + /** One page of backups matching [query]. */ fun backups(all: List, page: Int, query: BackupQuery = BackupQuery()): List { require(page > 0) { "Page must be positive" } val backups = query.apply(all) @@ -71,7 +73,7 @@ internal class BackupsScreen(routes: UpdateCatalogRoutes, now: Instant, zone: Zo ) + backup.components.map { component -> hoverField("Вернёт", text("${component.product} ${component.backupVersion?.let(::version) ?: "?"}", ChatPalette.TEXT) .append(text(" (сейчас ${component.updatedVersion?.let(::version) ?: "?"})", ChatPalette.SOFT))) - } + hoverField("Конфигураций", text("${backup.configurationFiles}", ChatPalette.TEXT)) + } + backup.items.map { hoverField("Сохранено", text(BackupItemText.describe(it), ChatPalette.TEXT)) } var row = text(" ").append(text(restores, ChatPalette.TEXT)) .append(text(" ")).append(text(backup.createdAt?.let(::age) ?: "дата не записана", ChatPalette.SOFT)) .hoverEvent(tooltip(*card.toTypedArray())) diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogLabels.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogLabels.kt similarity index 81% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogLabels.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogLabels.kt index eb93e6fbd..1cec5ce20 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogLabels.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogLabels.kt @@ -1,9 +1,9 @@ package org.pnfolder.pnlibrary.core.updates.catalog import net.kyori.adventure.text.format.TextColor -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.updates.UpdateState -import org.pnfolder.pnlibrary.core.updates.install.ComponentLedger +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.updates.state.UpdateState +import org.pnfolder.pnlibrary.updates.install.ComponentOperation /** The words and colors of update states and history operations, shared by every catalog page. */ object CatalogLabels { @@ -13,6 +13,7 @@ object CatalogLabels { /** States that need the administrator's attention. */ val PROBLEMS: Set = setOf(UpdateState.FAILED, UpdateState.BLOCKED, UpdateState.INCOMPATIBLE) + /** Color that marks [state] in lists. */ fun stateColor(state: UpdateState): TextColor = when (state) { UpdateState.UP_TO_DATE -> ChatPalette.OK UpdateState.UPDATE_AVAILABLE -> ChatPalette.INFO @@ -22,6 +23,7 @@ object CatalogLabels { UpdateState.CHECKING -> ChatPalette.LABEL } + /** Short user-facing name of [state]. */ fun stateLabel(state: UpdateState): String = when (state) { UpdateState.UP_TO_DATE -> "актуально" UpdateState.UPDATE_AVAILABLE -> "доступно обновление" @@ -43,16 +45,17 @@ object CatalogLabels { else -> stateLabel(state) } + /** User-facing name of a history [operation]. */ fun operationLabel(operation: String): String = when (operation) { "CHECK" -> "проверка" "STAGE" -> "обновление" "ROLLBACK" -> "откат" "HEALTH" -> "проверка запуска" "HEALTH_ROLLBACK" -> "проверка отката" - ComponentLedger.OPERATION_ADDED -> "установка" - ComponentLedger.OPERATION_REMOVED -> "удаление" - ComponentLedger.OPERATION_VERSION_CHANGED -> "смена версии" - ComponentLedger.OPERATION_SETTINGS_CHANGED -> "настройки" + ComponentOperation.ADDED -> "установка" + ComponentOperation.REMOVED -> "удаление" + ComponentOperation.VERSION_CHANGED -> "смена версии" + ComponentOperation.SETTINGS_CHANGED -> "настройки" else -> "состояние" } } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogScreen.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogScreen.kt similarity index 95% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogScreen.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogScreen.kt index 552b5c8e6..f9e13846f 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogScreen.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogScreen.kt @@ -2,15 +2,16 @@ package org.pnfolder.pnlibrary.core.updates.catalog import net.kyori.adventure.text.Component import net.kyori.adventure.text.event.ClickEvent -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import java.time.Instant import java.time.ZoneId /** The plugin list, the server status card and the join notice: pages built from catalog rows. */ internal class CatalogScreen(routes: UpdateCatalogRoutes, now: Instant, zone: ZoneId) : CatalogStyle(routes, now, zone) { + /** One page of the plugin list, optionally only those with pending updates. */ fun catalog(snapshots: List, page: Int, updatesOnly: Boolean): List { require(page > 0) { "Page must be positive" } val selected = snapshots.filter { !updatesOnly || it.state in CatalogLabels.PENDING }.sortedBy { it.product.lowercase() } @@ -48,6 +49,7 @@ internal class CatalogScreen(routes: UpdateCatalogRoutes, now: Instant, zone: Zo return framed(result) } + /** The summary screen: key facts, counters and available actions. */ fun status(facts: List>, snapshots: List, support: String?): List { val result = mutableListOf(header("Состояние", if (snapshots.isEmpty()) null else summary(snapshots)), blank()) facts.forEach { (label, value) -> result += field(label, text(value, ChatPalette.TEXT)) } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogStyle.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogStyle.kt similarity index 89% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogStyle.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogStyle.kt index 82b360181..793f9d070 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogStyle.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogStyle.kt @@ -4,11 +4,13 @@ import net.kyori.adventure.text.Component import net.kyori.adventure.text.event.ClickEvent import net.kyori.adventure.text.format.TextColor import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot import org.pnfolder.pnlibrary.common.text.RussianText +import org.pnfolder.pnlibrary.updates.policy.color +import org.pnfolder.pnlibrary.updates.policy.commandName import java.time.Duration import java.time.Instant import java.time.LocalDate @@ -31,8 +33,9 @@ internal open class CatalogStyle( /** Whether this reader may change settings by clicking. */ val clickable: Boolean = routes.interactive && routes.editable + /** Colored tag with the channel name. */ fun channelTag(channel: UpdateChannel): Component = - text(UpdateChannelLabels.channelName(channel), UpdateChannelLabels.channelColor(channel)) + text(channel.commandName(), channel.color()) /** * The current version, then an arrow and the highlighted new one when there is an update. With [changelog] @@ -57,6 +60,7 @@ internal open class CatalogStyle( fun updateTarget(snapshot: UpdateSnapshot): String? = snapshot.latestVersion?.takeIf { it != snapshot.currentVersion && snapshot.state in CatalogLabels.PENDING } + /** Publication time of [version] if the snapshot knows it. */ fun releasedAt(snapshot: UpdateSnapshot, version: String): Instant? = snapshot.availableReleases.firstOrNull { it.version == version }?.publishedAt @@ -73,6 +77,7 @@ internal open class CatalogStyle( return if (elapsed.toDays() < AGE_DAYS) RussianText.ago(elapsed) else DAY_YEAR.format(at.atZone(zone)) } + /** Heading for a history day: today, yesterday or the date. */ fun dayLabel(day: LocalDate): String { val today = now.atZone(zone).toLocalDate() return when { @@ -83,8 +88,10 @@ internal open class CatalogStyle( } } + /** Time of day in the display zone. */ fun clock(at: Instant): String = CLOCK.format(at.atZone(zone)) + /** Date and time in the display zone. */ fun fullTime(at: Instant): String = FULL_TIME.format(at.atZone(zone)) /** `[Изменения]` that opens the changelog, or the link itself for a reader that cannot click. */ @@ -92,6 +99,7 @@ internal open class CatalogStyle( if (!routes.interactive) text(" $link", ChatPalette.LABEL) else text(" ").append(linkButton("Изменения", link, "Открыть список изменений", ChatPalette.INFO)) + /** Button that opens the support link. */ fun supportButton(link: String): Component = linkButton("Поддержка", link, "Открыть поддержку pnFolder", ChatPalette.WARN) /** Previous and next page buttons around the page number; nothing for a single page. */ @@ -115,6 +123,7 @@ internal open class CatalogStyle( return if (offset >= size) emptyList() else drop(offset.toInt()).take(UpdateCatalogView.PAGE_SIZE) } + /** Number of pages for [total] items, at least one. */ fun pageCount(total: Int): Int = maxOf(1, (total + UpdateCatalogView.PAGE_SIZE - 1) / UpdateCatalogView.PAGE_SIZE) companion object { diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/HistoryScreen.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/HistoryScreen.kt similarity index 87% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/HistoryScreen.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/HistoryScreen.kt index dac5136b5..841a4cabb 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/HistoryScreen.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/HistoryScreen.kt @@ -4,10 +4,10 @@ import net.kyori.adventure.text.Component import net.kyori.adventure.text.event.ClickEvent import net.kyori.adventure.text.event.HoverEvent import net.kyori.adventure.text.format.TextColor -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.updates.UpdateState -import org.pnfolder.pnlibrary.api.updates.backup.UpdateHistoryEntry -import org.pnfolder.pnlibrary.core.updates.install.ComponentLedger +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.state.UpdateState +import org.pnfolder.pnlibrary.updates.install.ComponentOperation import java.time.Instant import java.time.LocalDate import java.time.ZoneId @@ -18,6 +18,7 @@ internal class HistoryScreen(routes: UpdateCatalogRoutes, now: Instant, zone: Zo /** What an event led to: a short label for the row and the full wording for its hover card. */ private class Outcome(val label: String, val color: TextColor, val detail: String = label) + /** One page of history entries grouped by day. */ fun history(entries: List, page: Int, totalPages: Int?, product: String?): List { require(page > 0) { "Page must be positive" } val result = mutableListOf(header("История", product?.let { text(it, ChatPalette.SOFT) })) @@ -64,8 +65,8 @@ internal class HistoryScreen(routes: UpdateCatalogRoutes, now: Instant, zone: Zo val product = change.product.toString() val transition = when (entry.operation) { "ROLLBACK", "HEALTH_ROLLBACK" -> text("откат к ${change.from?.let { version(it.toString()) } ?: "не установлено"}", ChatPalette.SOFT) - ComponentLedger.OPERATION_ADDED -> text(version(change.to.toString()), ChatPalette.SOFT) - ComponentLedger.OPERATION_REMOVED, ComponentLedger.OPERATION_SETTINGS_CHANGED -> + ComponentOperation.ADDED -> text(version(change.to.toString()), ChatPalette.SOFT) + ComponentOperation.REMOVED, ComponentOperation.SETTINGS_CHANGED -> text(version((change.from ?: change.to).toString()), ChatPalette.SOFT) else -> versions(change.from?.toString() ?: "-", change.to.toString()) } @@ -91,10 +92,10 @@ internal class HistoryScreen(routes: UpdateCatalogRoutes, now: Instant, zone: Zo ).toTypedArray()) private fun outcome(entry: UpdateHistoryEntry): Outcome = when { - entry.operation == ComponentLedger.OPERATION_ADDED -> Outcome("установлен", ChatPalette.OK) - entry.operation == ComponentLedger.OPERATION_REMOVED -> Outcome("удалён", ChatPalette.DANGER) - entry.operation == ComponentLedger.OPERATION_VERSION_CHANGED -> Outcome("изменена вручную", ChatPalette.ORANGE, "версия изменена вручную") - entry.operation == ComponentLedger.OPERATION_SETTINGS_CHANGED -> + entry.operation == ComponentOperation.ADDED -> Outcome("установлен", ChatPalette.OK) + entry.operation == ComponentOperation.REMOVED -> Outcome("удалён", ChatPalette.DANGER) + entry.operation == ComponentOperation.VERSION_CHANGED -> Outcome("изменена вручную", ChatPalette.ORANGE, "версия изменена вручную") + entry.operation == ComponentOperation.SETTINGS_CHANGED -> Outcome(entry.message?.takeIf { it.isNotBlank() }?.take(MAX_LINE) ?: "настройки изменены", ChatPalette.WARN) entry.state == UpdateState.FAILED -> Outcome("ошибка", ChatPalette.DANGER) entry.operation == "HEALTH" && entry.state == UpdateState.UP_TO_DATE -> Outcome("применено", ChatPalette.OK, "применено после перезапуска") diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProductScreens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProductScreens.kt similarity index 90% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProductScreens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProductScreens.kt index b77855dfe..3587a9989 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProductScreens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProductScreens.kt @@ -3,13 +3,14 @@ package org.pnfolder.pnlibrary.core.updates.catalog import net.kyori.adventure.text.Component import net.kyori.adventure.text.event.ClickEvent import net.kyori.adventure.text.format.TextColor -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.common.text.RussianText -import org.pnfolder.pnlibrary.core.updates.catalog.UpdateChannelLabels.channelColor -import org.pnfolder.pnlibrary.core.updates.catalog.UpdateChannelLabels.channelHint -import org.pnfolder.pnlibrary.core.updates.catalog.UpdateChannelLabels.channelName +import org.pnfolder.pnlibrary.updates.policy.color +import org.pnfolder.pnlibrary.updates.policy.commandName +import org.pnfolder.pnlibrary.updates.policy.hint import java.time.Duration import java.time.Instant import java.time.ZoneId @@ -27,7 +28,7 @@ internal class ProductScreens(routes: UpdateCatalogRoutes, now: Instant, zone: Z snapshot.latestChangelogUrl?.takeIf(::safeLink)?.takeIf { update != null }?.let { version = version.append(changelogButton(it)) } result += version releasedAt(snapshot, update ?: snapshot.currentVersion)?.let { result += field("Выпущена", text(released(it), ChatPalette.TEXT)) } - result += field("Канал", channelTag(snapshot.channel)).hoverEvent(tooltip(text(channelHint(snapshot.channel), ChatPalette.TEXT))) + result += field("Канал", channelTag(snapshot.channel)).hoverEvent(tooltip(text(snapshot.channel.hint(), ChatPalette.TEXT))) .append(change(product, "Выбрать другой канал обновлений")) otherChannels(snapshot)?.let { result += it } result += field("Автозагрузка", if (snapshot.automaticDownload) text("включена", ChatPalette.OK) else text("выключена", ChatPalette.DANGER)) @@ -67,8 +68,8 @@ internal class ProductScreens(routes: UpdateCatalogRoutes, now: Instant, zone: Z if (clickable) result += note("Нажмите на кнопку, чтобы выбрать. ${glyph('✔')} — выбрано сейчас.") if (clickable) result += note("Пауза — не дольше 7 дней.") result += blank() - result += choices("Канал", UpdateCatalogView.CHANNELS.map { it to channelName(it) }, snapshot.channel, ::channelColor) { channel -> - routes.set(product, "channel", channelName(channel)) to channelHint(channel) + result += choices("Канал", UpdateCatalogView.CHANNELS.map { it to it.commandName() }, snapshot.channel, UpdateChannel::color) { channel -> + routes.set(product, "channel", channel.commandName()) to channel.hint() } if (clickable) { actions( @@ -95,7 +96,7 @@ internal class ProductScreens(routes: UpdateCatalogRoutes, now: Instant, zone: Z if (!routes.interactive || !routes.editable) { result += commandHints( routes.set(product, "channel", - "<${UpdateCatalogView.CHANNELS.joinToString("|") { channelName(it) }}|default>") to "канал (default: как задал плагин)", + "<${UpdateCatalogView.CHANNELS.joinToString("|") { it.commandName() }}|default>") to "канал (default: как задал плагин)", routes.set(product, "auto", "") to "автозагрузка", routes.set(product, "hold", "<${UpdateCatalogView.HOLD_PERIODS.joinToString("|")}|off>") to "пауза", ) @@ -113,13 +114,13 @@ internal class ProductScreens(routes: UpdateCatalogRoutes, now: Instant, zone: Z val entries = newest.map { (channel, release) -> val entry = channelTag(channel).append(text(" ${version(release.version)}", ChatPalette.TEXT)) val card = listOfNotNull( - text("${channelName(channel)} ${version(release.version)}", channelColor(channel)), + text("${channel.commandName()} ${version(release.version)}", channel.color()), release.publishedAt?.let { hoverField("Выпущена", text(released(it), ChatPalette.TEXT)) }, - text(channelHint(channel), ChatPalette.LABEL), - text("» Нажмите, чтобы переключиться на ${channelName(channel)}", ChatPalette.LABEL).takeIf { clickable }, + text(channel.hint(), ChatPalette.LABEL), + text("» Нажмите, чтобы переключиться на ${channel.commandName()}", ChatPalette.LABEL).takeIf { clickable }, ) val shown = entry.hoverEvent(tooltip(*card.toTypedArray())) - if (clickable) shown.clickEvent(ClickEvent.runCommand(routes.set(snapshot.product, "channel", channelName(channel)))) else shown + if (clickable) shown.clickEvent(ClickEvent.runCommand(routes.set(snapshot.product, "channel", channel.commandName()))) else shown } return field("Другие каналы", entries.drop(1).fold(entries.first()) { line, entry -> line.append(dot()).append(entry) }) } @@ -152,7 +153,7 @@ internal class ProductScreens(routes: UpdateCatalogRoutes, now: Instant, zone: Z }.fold(Component.empty()) { line, period -> line.append(period) } private fun holdText(until: Instant?): String = - if (until == null) "задана в updates.yml" else "до ${fullTime(until)} · ${RussianText.remaining(Duration.between(now, until))}" + if (until == null) "не задана" else "до ${fullTime(until)} · ${RussianText.remaining(Duration.between(now, until))}" /** `3d` as `3 д`, the way periods read everywhere else. */ private fun periodLabel(period: String): String = period.dropLast(1) + when (period.last()) { diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateCommand.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateCommand.kt similarity index 86% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateCommand.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateCommand.kt index 59a27d27b..3aae60ac1 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateCommand.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateCommand.kt @@ -1,18 +1,18 @@ package org.pnfolder.pnlibrary.core.updates.catalog import org.pnfolder.pnlibrary.api.chat.ChatNotice -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.commands.ArgumentType -import org.pnfolder.pnlibrary.api.commands.CommandBuilder +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandContext import org.pnfolder.pnlibrary.api.commands.CommandSender +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandBuilder import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot import org.pnfolder.pnlibrary.api.updates.UpdateRegistration -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.core.exceptions.rootMessage import java.time.Duration import java.util.UUID @@ -42,7 +42,7 @@ class ProxyUpdateCommand(private val library: PnLibrary) { permission(ADMIN, VIEW) executes { status(it, null) } argument("plugin", ArgumentType.string()) { - suggests { productNames() } + suggests { library.updateProductNames() } executes { status(it, it.get("plugin")) } } } @@ -65,7 +65,7 @@ class ProxyUpdateCommand(private val library: PnLibrary) { root.literal("update") { permission(ADMIN, DOWNLOAD) argument("plugin", ArgumentType.string()) { - suggests { productNames() } + suggests { library.updateProductNames() } executes { update(it, it.get("plugin")) } } literal("confirm") { @@ -87,13 +87,11 @@ class ProxyUpdateCommand(private val library: PnLibrary) { say(sender, ChatTone.INFO, "Команды pnLibrary, доступные вам:", available.joinToString(" ").ifEmpty { "нет" }) } - private fun productNames(): List = library.updates.all().map { it.snapshot.product } - // --- status and check -------------------------------------------------------------------------------------- private fun status(context: CommandContext, requested: String?) { val sender = context.sender - val entries = if (requested == null) library.updates.all() else listOfNotNull(library.updates.get(requested)) + val entries = if (requested == null) library.updates.products.all() else listOfNotNull(library.updates.products.get(requested)) if (requested != null && entries.isEmpty()) return notRegistered(sender, requested) val facts = listOf( "Java" to (System.getProperty("java.version") ?: "?"), @@ -104,7 +102,7 @@ class ProxyUpdateCommand(private val library: PnLibrary) { private fun check(context: CommandContext) { say(context.sender, ChatTone.PROGRESS, "Проверяю обновления…") - library.updates.checkNow(actor(context.sender)).whenComplete { _, error -> + library.updates.plans.check(context.sender.asUpdateActor()).whenComplete { _, error -> if (error != null) fail(context.sender, "Не удалось проверить обновления", error) else catalog.showAvailable(context) } } @@ -114,9 +112,9 @@ class ProxyUpdateCommand(private val library: PnLibrary) { private fun update(context: CommandContext, name: String) { val sender = context.sender if (!sender.hasPermission(DOWNLOAD)) return say(sender, ChatTone.FAILURE, "Недостаточно прав для загрузки обновлений.") - val registration = library.updates.get(name) ?: return notRegistered(sender, name) + val registration = library.updates.products.get(name) ?: return notRegistered(sender, name) say(sender, ChatTone.PROGRESS, "Ищу совместимое обновление ${registration.snapshot.product}…") - library.updates.checkNow(actor(sender)).whenComplete { result, error -> + library.updates.plans.check(sender.asUpdateActor()).whenComplete { result, error -> if (error != null) fail(sender, "Проверка обновления не удалась", error) else stage(sender, registration, result) } } @@ -128,7 +126,7 @@ class ProxyUpdateCommand(private val library: PnLibrary) { } val transition = "${change.product} v${change.from} » v${change.to}" say(sender, ChatTone.PROGRESS, "Найдено $transition. Скачиваю и проверяю…") - library.updates.stage(result.id, actor(sender)).whenComplete { _, error -> + library.updates.plans.stage(result.id, sender.asUpdateActor()).whenComplete { _, error -> if (error != null) fail(sender, "Не удалось подготовить обновление", error) else say(sender, ChatTone.SUCCESS, "Обновление $transition подготовлено.", "Перезапустите прокси, чтобы применить его.") } @@ -139,7 +137,7 @@ class ProxyUpdateCommand(private val library: PnLibrary) { private fun rollbackPlan(context: CommandContext) { val sender = context.sender if (!sender.hasPermission(ROLLBACK)) return say(sender, ChatTone.FAILURE, "Недостаточно прав для отката обновлений.") - val plan = library.updates.currentPlan().orElse(null) + val plan = library.updates.plans.current().orElse(null) ?: return say(sender, ChatTone.WARNING, "Нет плана обновления, который можно откатить.") ask( sender, plan.id, plan.revision, UpdateAction.PLAN_ROLLBACK, "Откат обновления", @@ -180,14 +178,18 @@ class ProxyUpdateCommand(private val library: PnLibrary) { } when (grant.action) { UpdateAction.PLAN_ROLLBACK -> { - val current = library.updates.currentPlan().orElse(null) + val current = library.updates.plans.current().orElse(null) if (current == null || current.id != grant.plan || current.revision != grant.revision) { return say(sender, ChatTone.FAILURE, "План обновления изменился; запросите откат заново.") } - library.updates.rollback(actor(sender)).whenComplete { _, error -> done(error) } + library.updates.backups.rollback(sender.asUpdateActor()).whenComplete { _, error -> done(error) } } - UpdateAction.ROLLBACK -> library.updates.rollback(grant.plan, false, actor(sender)).whenComplete { _, error -> done(error) } - UpdateAction.ROLLBACK_CONFIGS -> library.updates.rollback(grant.plan, true, actor(sender)).whenComplete { _, error -> done(error) } + UpdateAction.ROLLBACK -> + library.updates.backups.rollback(grant.plan, sender.asUpdateActor(), restoreConfigurations = false) + .whenComplete { _, error -> done(error) } + UpdateAction.ROLLBACK_CONFIGS -> + library.updates.backups.rollback(grant.plan, sender.asUpdateActor(), restoreConfigurations = true) + .whenComplete { _, error -> done(error) } UpdateAction.RESTART, UpdateAction.RESTART_LATER, UpdateAction.RESTART_EMPTY -> say(sender, ChatTone.WARNING, "Перезапустите прокси его обычной командой.") } @@ -207,16 +209,12 @@ class ProxyUpdateCommand(private val library: PnLibrary) { say(sender, ChatTone.FAILURE, "Плагин $product не зарегистрирован в pnLibrary.") private fun fail(sender: CommandSender, title: String, error: Throwable) { - val cause = generateSequence(error) { it.cause }.last() - say(sender, ChatTone.FAILURE, "$title.", cause.message ?: cause.javaClass.simpleName) + say(sender, ChatTone.FAILURE, "$title.", error.rootMessage()) } private fun identityOf(sender: CommandSender): UUID = UUID.nameUUIDFromBytes(sender.id.toByteArray()) - private fun actor(sender: CommandSender): UpdateActor = - UpdateActor(if (sender.isConsole) UpdateActor.Kind.CONSOLE else UpdateActor.Kind.PLAYER, sender.id, sender.name) - - private companion object { + internal companion object { val ROUTES = UpdateCatalogRoutes("/pn updates", update = { product -> "/pn update $product" }, check = "/pn check") val CONFIRMATION_TIME: Duration = Duration.ofSeconds(30) const val ADMIN = "pnlibrary.admin" diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateReminder.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateReminder.kt new file mode 100644 index 000000000..e68ab6b1b --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateReminder.kt @@ -0,0 +1,21 @@ +package org.pnfolder.pnlibrary.core.updates.catalog + +import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity +import org.pnfolder.pnlibrary.updates.policy.UpdateDefaults +import java.util.UUID + +/** The chat reminder of proxies: who gets it, how often, and the text. It reads known state and never asks GitHub. */ +object ProxyUpdateReminder { + val INTERVAL_SECONDS: Long = UpdateDefaults.REMINDER_INTERVAL.seconds + + /** Whether the sender may see update reminders. */ + fun canSee(hasPermission: (String) -> Boolean): Boolean = hasPermission("pnlibrary.admin") || hasPermission("pnlibrary.updates.notify") + + /** Sends the notice to [player] when an update is available or waits for a restart; sends nothing otherwise. */ + fun send(library: PnLibrary, player: UUID) { + val audience = library.audiences.player(player) ?: return + val snapshots = library.updates.products.all().map { it.snapshot } + UpdateCatalogView.announcement(snapshots, ProxyUpdateCommand.ROUTES, PnLibraryIdentity.SUPPORT_URL).forEach(audience::sendMessage) + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogCommands.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogCommands.kt similarity index 64% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogCommands.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogCommands.kt index 77239c431..d6f551fdb 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogCommands.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogCommands.kt @@ -1,12 +1,13 @@ package org.pnfolder.pnlibrary.core.updates.catalog import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.commands.ArgumentType import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandNodeBuilder +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandNodeBuilder import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.backup.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.core.exceptions.rootCause import java.util.Locale import java.util.concurrent.CompletableFuture @@ -41,10 +42,6 @@ class UpdateCatalogCommands( ) { private val settings = UpdateCatalogSettingsCommands(library, ::ready, ::routesFor, deliver, onSaved) - /** - * A setting that was just saved: [setting] names it, for example "Канал", [from] is what it was and [to] what it - * is now, both as short words such as "stable" or "включена". - */ /** * A setting that was changed from a player or console command. * @@ -76,14 +73,14 @@ class UpdateCatalogCommands( addLiteral("info") { viewPermission?.let(::permission) argument("plugin", ArgumentType.string()) { - suggests { productNames() } + suggests { library.updateProductNames() } executes(::showInfo) } } addLiteral("settings") { viewPermission?.let(::permission) argument("plugin", ArgumentType.string()) { - suggests { productNames() } + suggests { library.updateProductNames() } executes { showSettings(it, it.get("plugin")) } } } @@ -94,14 +91,28 @@ class UpdateCatalogCommands( private fun installSettings(addLiteral: (String, CommandNodeBuilder.() -> Unit) -> Unit) { addLiteral("set") { managePermission?.let(::permission) + literal("all") { + literal("auto") { + argument("value", ArgumentType.string()) { + suggests { UpdateCatalogSettingsCommands.SWITCH_SUGGESTIONS } + executes(settings::setAllAutomatic) + } + } + } argument("plugin", ArgumentType.string()) { - suggests { productNames() } + suggests { library.updateProductNames() } literal("channel") { argument("value", ArgumentType.string()) { suggests { settings.available().map { it.name.lowercase(Locale.ROOT) } + UpdateCatalogSettingsCommands.DEFAULT_CHANNEL } executes(settings::setChannel) } } + literal("java") { + argument("value", ArgumentType.string()) { + suggests { listOf("8", "11", "17", "21", UpdateCatalogSettingsCommands.DEFAULT_CHANNEL) } + executes(settings::setJava) + } + } literal("auto") { argument("value", ArgumentType.string()) { suggests { UpdateCatalogSettingsCommands.SWITCH_SUGGESTIONS } @@ -125,7 +136,7 @@ class UpdateCatalogCommands( argument("page", ArgumentType.integer()) { executes { showHistory(it, product = null) } } literal("plugin") { argument("product", ArgumentType.string()) { - suggests { productNames() } + suggests { library.updateProductNames() } executes { showHistory(it, product = it.get("product")) } argument("page", ArgumentType.integer()) { executes { showHistory(it, product = it.get("product")) } @@ -136,6 +147,29 @@ class UpdateCatalogCommands( addLiteral("backups") { (backupsPermission ?: viewPermission)?.let(::permission) backupFilters(emptySet()) + literal("restore") { + managePermission?.let(::permission) + argument("backupId", ArgumentType.string()) { + argument("backupPlugin", ArgumentType.string()) { + suggests { library.updateProductNames() } + literal("confirm") { argument("databaseName", ArgumentType.greedyString()) { executes { restoreDatabase(it, true) } } } + argument("databaseName", ArgumentType.greedyString()) { executes { restoreDatabase(it, false) } } + } + } + } + literal("files") { + managePermission?.let(::permission) + argument("backupId", ArgumentType.string()) { + argument("backupPlugin", ArgumentType.string()) { + suggests { library.updateProductNames() } + executes(::extractBackup) + } + } + } + literal("delete") { + managePermission?.let(::permission) + argument("backupId", ArgumentType.string()) { executes(::deleteBackup) } + } } } @@ -149,7 +183,7 @@ class UpdateCatalogCommands( if ("plugin" !in used) { literal("plugin") { argument("backupPlugin", ArgumentType.string()) { - suggests { productNames() } + suggests { library.updateProductNames() } backupFilters(used + "plugin") } } @@ -177,8 +211,6 @@ class UpdateCatalogCommands( /** Shows the first page of components with an available or prepared update. */ fun showAvailable(context: CommandContext) = showCatalog(context, updatesOnly = true) - private fun productNames(): List = library.updates.all().map { it.snapshot.product } - /** Routes for this sender: no buttons when it cannot click, ASCII for the console, read-only without permission. */ private fun routesFor(context: CommandContext): UpdateCatalogRoutes = routes.copy( interactive = routes.interactive && context.sender.supportsInteraction, @@ -189,24 +221,24 @@ class UpdateCatalogCommands( private fun showCatalog(context: CommandContext, updatesOnly: Boolean) { if (!ready(context)) return val page = requestedPage(context) ?: return - UpdateCatalogView.catalog(library.updates.all().map { it.snapshot }, page, updatesOnly, routesFor(context)) + UpdateCatalogView.catalog(library.updates.products.all().map { it.snapshot }, page, updatesOnly, routesFor(context)) .forEach(context.sender::send) } private fun showInfo(context: CommandContext) { if (!ready(context)) return val snapshot = snapshotOf(context, context.get("plugin")) ?: return - UpdateCatalogView.info(snapshot, routesFor(context), library.updates.heldUntil(snapshot.product)).forEach(context.sender::send) + UpdateCatalogView.info(snapshot, routesFor(context), library.updates.settings.heldUntil(snapshot.product)).forEach(context.sender::send) } private fun showSettings(context: CommandContext, requested: String) { if (!ready(context)) return val snapshot = snapshotOf(context, requested) ?: return - UpdateCatalogView.settings(snapshot, routesFor(context), library.updates.heldUntil(snapshot.product)).forEach(context.sender::send) + UpdateCatalogView.settings(snapshot, routesFor(context), library.updates.settings.heldUntil(snapshot.product)).forEach(context.sender::send) } private fun snapshotOf(context: CommandContext, requested: String): UpdateSnapshot? { - val registration = library.updates.get(requested) + val registration = library.updates.products.get(requested) if (registration == null) context.sender.send(error("Плагин $requested не зарегистрирован в pnLibrary.")) return registration?.snapshot } @@ -214,8 +246,8 @@ class UpdateCatalogCommands( private fun showHistory(context: CommandContext, product: String?) { if (!ready(context)) return val page = requestedPage(context) ?: return - val entries = library.updates.historyPage(page, product).toCompletableFuture() - val total = library.updates.historyCount(product).toCompletableFuture() + val entries = library.updates.history.page(page, product).toCompletableFuture() + val total = library.updates.history.count(product).toCompletableFuture() CompletableFuture.allOf(entries, total).whenComplete { _, failure -> deliver(Runnable { if (failure != null) { @@ -233,11 +265,68 @@ class UpdateCatalogCommands( .forEach(context.sender::send) } + /** Without `confirm` it only warns and shows the command that does it: a database cannot be put back by accident. */ + private fun restoreDatabase(context: CommandContext, confirmed: Boolean) { + if (!ready(context)) return + val sender = context.sender + val id = runCatching { java.util.UUID.fromString(context.get("backupId")) }.getOrNull() + ?: return sender.send(error("Некорректный ID резервного набора.")) + val plugin = context.get("backupPlugin") + val name = context.get("databaseName") + if (!confirmed) { + sender.send(error("База «$name» плагина $plugin будет заменена сохранённой: всё, что записано в неё после копии, пропадёт.")) + sender.send( + Component.text("Текущее состояние сохранится отдельной копией."), + ) + sender.send( + Component.text("Если согласны, выполните: /pn updates backups restore $id $plugin confirm $name"), + ) + return + } + val actor = sender.asUpdateActor() + library.updates.backups.restoreDatabase(id, plugin, name, actor).whenComplete { _, failure -> + deliver(Runnable { + if (failure == null) sender.send(Component.text("База «$name» возвращена. Перезапустите плагин $plugin.")) + else sender.send(error("Не удалось вернуть базу: ${failure.rootCause().message}")) + }) + } + } + + /** Hands out the saved databases and exports of a plugin as plain files, for what the library cannot put back itself. */ + private fun extractBackup(context: CommandContext) { + if (!ready(context)) return + val sender = context.sender + val id = runCatching { java.util.UUID.fromString(context.get("backupId")) }.getOrNull() + ?: return sender.send(error("Некорректный ID резервного набора.")) + val plugin = context.get("backupPlugin") + val actor = sender.asUpdateActor() + library.updates.backups.extract(id, plugin, actor).whenComplete { folder, failure -> + deliver(Runnable { + if (failure == null) sender.send(Component.text("Файлы плагина $plugin лежат в папке: $folder")) + else sender.send(error("Не удалось выдать файлы: ${failure.rootCause().message}")) + }) + } + } + + private fun deleteBackup(context: CommandContext) { + if (!ready(context)) return + val sender = context.sender + val id = runCatching { java.util.UUID.fromString(context.get("backupId")) }.getOrNull() + ?: return sender.send(error("Некорректный ID резервного набора.")) + val actor = sender.asUpdateActor() + library.updates.backups.delete(id, actor).whenComplete { _, failure -> + deliver(Runnable { + if (failure == null) sender.send(Component.text("Резервный набор $id удалён.")) + else sender.send(error("Не удалось удалить набор: ${failure.rootCause().message}")) + }) + } + } + private fun showBackups(context: CommandContext) { if (!ready(context)) return val page = requestedPage(context) ?: return val query = backupQuery(context) ?: return - library.updates.backups().whenComplete { backups, failure -> + library.updates.backups.list().whenComplete { backups, failure -> deliver(Runnable { if (failure != null) context.sender.send(error("Не удалось прочитать резервные наборы.")) else UpdateCatalogView.backups(backups, page, routesFor(context), query = query).forEach(context.sender::send) @@ -258,8 +347,7 @@ class UpdateCatalogCommands( } private fun historyFailure(failure: Throwable, product: String?): String { - val cause = generateSequence(failure) { it.cause }.last() - return if (product != null && cause is IllegalArgumentException) "Некорректное имя плагина: $product." + return if (product != null && failure.rootCause() is IllegalArgumentException) "Некорректное имя плагина: $product." else "Не удалось прочитать историю обновлений." } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogRoutes.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogRoutes.kt similarity index 100% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogRoutes.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogRoutes.kt diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogSettingsCommands.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogSettingsCommands.kt similarity index 66% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogSettingsCommands.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogSettingsCommands.kt index cd4c6393e..01c2e62e8 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogSettingsCommands.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogSettingsCommands.kt @@ -2,17 +2,18 @@ package org.pnfolder.pnlibrary.core.updates.catalog import net.kyori.adventure.text.Component import org.pnfolder.pnlibrary.api.chat.ChatNotice -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandContext import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.common.text.RussianText -import org.pnfolder.pnlibrary.core.updates.engine.FreezeDuration +import org.pnfolder.pnlibrary.core.exceptions.rootCause +import org.pnfolder.pnlibrary.updates.engine.FreezeDuration import java.time.Duration import java.util.Locale import java.util.concurrent.CompletionStage @@ -42,7 +43,7 @@ internal class UpdateCatalogSettingsCommands( val value = context.get("value") if (value.equals(DEFAULT_CHANNEL, ignoreCase = true)) { change(context, "Канал", { it.channel.name.lowercase(Locale.ROOT) }, "как задал плагин") { product, actor -> - library.updates.setChannel(product, null, actor) + library.updates.settings.channel(product, null, actor) } return } @@ -56,13 +57,42 @@ internal class UpdateCatalogSettingsCommands( return } change(context, "Канал", { it.channel.name.lowercase(Locale.ROOT) }, channel.name.lowercase(Locale.ROOT)) { product, - actor -> library.updates.setChannel(product, channel, actor) } + actor -> library.updates.settings.channel(product, channel, actor) } } + /** `java` command: chooses the Java build of a release that has several, or `default` to let the library pick one. */ + fun setJava(context: CommandContext) { + val value = context.get("value") + val java = value.toIntOrNull() + if (java == null && !value.equals(DEFAULT_CHANNEL, ignoreCase = true)) { + context.sender.send(catalogError("Укажите версию Java, например 17, или default.")) + return + } + change(context, "Сборка Java", { it.javaBuild?.toString() ?: "подбирается" }, java?.toString() ?: "подбирается") { product, actor -> + library.updates.settings.javaBuild(product, java, actor) + } + } + + /** `automatic` command: toggles automatic downloads. */ fun setAutomatic(context: CommandContext) { val enabled = switch(context) ?: return change(context, "Автозагрузка", { if (it.automaticDownload) "включена" else "выключена" }, if (enabled) "включена" else "выключена") { product, actor -> - library.updates.setAutomaticDownload(product, enabled, actor) + library.updates.settings.automaticDownload(product, enabled, actor) + } + } + + /** Turns automatic download on or off for all plugins at once, whatever was chosen for single ones. */ + fun setAllAutomatic(context: CommandContext) { + val enabled = switch(context) ?: return + if (!ready(context)) return + val sender = context.sender + val actor = sender.asUpdateActor() + library.updates.settings.automaticDownloadForAll(enabled, actor).whenComplete { _, failure -> + deliver(Runnable { + val text = if (failure != null) failure.rootCause().message ?: "Не удалось изменить настройку." + else "Сохранено. Автозагрузка для всех плагинов: ${if (enabled) "включена" else "выключена"}." + sender.send(if (failure != null) catalogError(text) else Component.text(text, ChatPalette.OK)) + }) } } @@ -78,7 +108,10 @@ internal class UpdateCatalogSettingsCommands( } } change(context, "Пауза", { if (it.state == UpdateState.FROZEN) "на паузе" else "нет" }, - if (duration == null) "нет" else RussianText.period(duration)) { product, actor -> library.updates.setHeld(product, duration, actor) } + if (duration == null) "нет" else RussianText.period(duration), + ) { product, actor -> + if (duration == null) library.updates.settings.release(product, actor) else library.updates.settings.hold(product, duration, actor) + } } private fun switch(context: CommandContext): Boolean? { @@ -98,17 +131,16 @@ internal class UpdateCatalogSettingsCommands( if (!ready(context)) return val product = context.get("plugin") val sender = context.sender - val before = library.updates.get(product)?.snapshot?.let(current) ?: value - val actor = UpdateActor(if (sender.isConsole) UpdateActor.Kind.CONSOLE else UpdateActor.Kind.PLAYER, sender.id, sender.name) + val before = library.updates.products.get(product)?.snapshot?.let(current) ?: value + val actor = sender.asUpdateActor() apply(product, actor).whenComplete { snapshot, failure -> deliver(Runnable { if (failure != null) { - val cause = generateSequence(failure) { it.cause }.last() - sender.send(catalogError(cause.message ?: "Не удалось изменить настройку.")) + sender.send(catalogError(failure.rootCause().message ?: "Не удалось изменить настройку.")) } else { val routes = routesFor(context) val arrow = if (routes.ascii) "->" else "→" - val card = UpdateCatalogView.settings(snapshot, routes, library.updates.heldUntil(snapshot.product)) + val card = UpdateCatalogView.settings(snapshot, routes, library.updates.settings.heldUntil(snapshot.product)) (card + UpdateCatalogView.notice(ChatNotice(ChatTone.SUCCESS, "Сохранено. $setting: $before $arrow $value."), routes)).forEach(sender::send) onSaved(context, UpdateCatalogCommands.SettingSaved(snapshot.product, setting, before, value)) } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogSupport.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogSupport.kt new file mode 100644 index 000000000..4ead96847 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogSupport.kt @@ -0,0 +1,12 @@ +package org.pnfolder.pnlibrary.core.updates.catalog + +import org.pnfolder.pnlibrary.api.commands.CommandSender +import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor + +/** The update actor that stands for this sender in the update history. */ +internal fun CommandSender.asUpdateActor(): UpdateActor = + UpdateActor(if (isConsole) UpdateActor.Kind.CONSOLE else UpdateActor.Kind.PLAYER, id, name) + +/** The names of all plugins registered for updates, for tab completion. */ +internal fun PnLibrary.updateProductNames(): List = updates.products.all().map { it.snapshot.product } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogView.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogView.kt similarity index 97% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogView.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogView.kt index bb015d0e0..05058ffa6 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogView.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogView.kt @@ -5,10 +5,10 @@ import org.pnfolder.pnlibrary.api.chat.ChatKit import org.pnfolder.pnlibrary.api.chat.ChatNotice import org.pnfolder.pnlibrary.api.chat.ChatReader import org.pnfolder.pnlibrary.api.chat.ConfirmChoice -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup -import org.pnfolder.pnlibrary.api.updates.backup.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot import java.time.Instant import java.time.ZoneId diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateConfirmationTokens.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateConfirmationTokens.kt similarity index 79% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateConfirmationTokens.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateConfirmationTokens.kt index 25def616f..7ecc5d54e 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateConfirmationTokens.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateConfirmationTokens.kt @@ -28,16 +28,10 @@ enum class UpdateAction { ROLLBACK_CONFIGS, } -/** - * Issues single-use grants bound to a player, update plan, revision, and action. - * - * Grants expire according to the supplied clock; mismatched requests cannot consume them. - */ class UpdateConfirmationTokens( private val random: SecureRandom = SecureRandom(), private val clock: () -> Instant = Instant::now, ) { - /** Immutable authorization captured when a token is issued. */ data class Grant( val player: UUID, val plan: UUID, @@ -48,7 +42,6 @@ class UpdateConfirmationTokens( private val grants = ConcurrentHashMap() - /** Issues an unpredictable token for a strictly positive lifetime. */ fun issue( player: UUID, plan: UUID, @@ -63,7 +56,6 @@ class UpdateConfirmationTokens( return token } - /** Consumes a matching, unexpired grant atomically; a token can succeed only once. */ fun consume( token: String, player: UUID, @@ -80,10 +72,6 @@ class UpdateConfirmationTokens( return grants.remove(token, grant) } - /** - * Consumes the grant of [token] for [player] whatever its action, and returns it, or `null` when the token is - * unknown, expired, already used or was issued to someone else. - */ fun redeem(token: String, player: UUID): Grant? { val grant = grants[token] ?: return null if (grant.player != player) return null @@ -94,7 +82,6 @@ class UpdateConfirmationTokens( return grant.takeIf { grants.remove(token, it) } } - /** Removes expired grants and returns the number still active. */ fun cleanup(): Int { val now = clock() grants.entries.removeIf { !now.isBefore(it.value.expiresAt) } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateStatusMessages.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateStatusMessages.kt similarity index 93% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateStatusMessages.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateStatusMessages.kt index ca922ff5b..e88fb9d41 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateStatusMessages.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateStatusMessages.kt @@ -1,12 +1,12 @@ package org.pnfolder.pnlibrary.core.updates.catalog import org.pnfolder.pnlibrary.api.chat.ChatNotice -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.BlockedReason -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.state.BlockedReason +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState /** Pure, platform-independent wording of the update state used by the update commands. */ object UpdateStatusMessages { diff --git a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/CatboxUploader.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/CatboxUploader.kt similarity index 88% rename from modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/CatboxUploader.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/CatboxUploader.kt index a0591be94..98fc6b1af 100644 --- a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/CatboxUploader.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/CatboxUploader.kt @@ -6,7 +6,6 @@ import java.net.URI import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path -import java.time.Instant /** * Uploads an encrypted `.pnsupport` file through Catbox's multipart API. @@ -18,9 +17,7 @@ class CatboxUploader( private val endpoint: URI = URI.create("https://catbox.moe/user/api.php"), ) : UploadProvider { init { - require(endpoint.scheme.equals("https", ignoreCase = true)) { - "Catbox endpoint must use HTTPS" - } + UploadHttp.requireHttps(endpoint, "Catbox endpoint") } override val backendId: String = "catbox" @@ -51,7 +48,7 @@ class CatboxUploader( if (uri.scheme != "https" || uri.host != "files.catbox.moe" || uri.path.isNullOrBlank()) { throw IOException("Catbox rejected the report: ${link.take(256)}") } - return UploadReceipt(uri, uri.path.substringAfterLast('/'), "", Instant.now().epochSecond, 0, backendId) + return UploadReceipt.permanent(uri, uri.path.substringAfterLast('/'), backendId) } private companion object { diff --git a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/EncryptedReportUploader.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/EncryptedReportUploader.kt similarity index 69% rename from modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/EncryptedReportUploader.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/EncryptedReportUploader.kt index d7524c1bf..c6fb69e3e 100644 --- a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/EncryptedReportUploader.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/EncryptedReportUploader.kt @@ -2,9 +2,8 @@ package org.pnfolder.pnlibrary.core.upload import com.google.gson.Gson import com.google.gson.JsonObject -import java.io.ByteArrayOutputStream import java.io.IOException -import java.io.InputStream +import java.io.OutputStream import java.net.HttpURLConnection import java.net.URI import java.nio.charset.StandardCharsets @@ -21,9 +20,7 @@ class EncryptedReportUploader @JvmOverloads constructor( ) : UploadProvider { init { - if (requireHttps && (!"https".equals(endpoint.scheme, ignoreCase = true) || !"https".equals(publicBase.scheme, ignoreCase = true))) { - throw IllegalArgumentException("Encrypted upload URLs must use HTTPS") - } + require(!requireHttps || (isHttps(endpoint) && isHttps(publicBase))) { "Encrypted upload URLs must use HTTPS" } val path = publicBase.path require(path != null && path.endsWith("/")) { "Encrypted publicBase path must end with /" } } @@ -32,27 +29,27 @@ class EncryptedReportUploader @JvmOverloads constructor( @Throws(IOException::class) override fun upload(payload: String): UploadReceipt { - return uploadBytes(payload.toByteArray(StandardCharsets.UTF_8), "application/json; charset=UTF-8") + val body = payload.toByteArray(StandardCharsets.UTF_8) + return send(body.size.toLong(), "application/json; charset=UTF-8") { it.write(body) } } + /** Streams the file instead of loading it whole, so a report of up to 64 MB does not take as much heap. */ override fun uploadFile(file: Path, contentType: String): UploadReceipt { val size = Files.size(file) if (size > MAX_UPLOAD_BYTES) throw IOException("Report is too large to upload: $size bytes") - return uploadBytes(Files.readAllBytes(file), contentType) + return send(size, contentType) { output -> Files.newInputStream(file).use { it.copyTo(output) } } } - private fun uploadBytes(body: ByteArray, contentType: String): UploadReceipt { + private fun send(length: Long, contentType: String, write: (OutputStream) -> Unit): UploadReceipt { val connection = open(endpoint, "POST") connection.setRequestProperty("Content-Type", contentType) connection.doOutput = true - connection.setFixedLengthStreamingMode(body.size) + connection.setFixedLengthStreamingMode(length) try { - connection.outputStream.use { it.write(body) } + connection.outputStream.use(write) val status = connection.responseCode - if (status != 200 && status != 201) { - throw IOException("Encrypted storage HTTP $status") - } - val response = connection.inputStream.use { readLimited(it, 16_384) } + if (status != 200 && status != 201) throw IOException("Encrypted storage HTTP $status") + val response = connection.inputStream.use { UploadHttp.readBounded(it) } return parseReceipt(String(response, StandardCharsets.UTF_8)) } finally { connection.disconnect() @@ -94,29 +91,15 @@ class EncryptedReportUploader @JvmOverloads constructor( } private fun open(uri: URI, method: String): HttpURLConnection { - val connection = uri.toURL().openConnection() as HttpURLConnection - connection.connectTimeout = 5_000 - connection.readTimeout = 15_000 - connection.instanceFollowRedirects = false - connection.requestMethod = method + val connection = UploadHttp.open(uri, method, connectTimeoutMs = 5_000, readTimeoutMs = 15_000) connection.setRequestProperty("Accept", "application/json") - connection.setRequestProperty("User-Agent", "pnLibrary-Diagnostics") return connection } private fun ensureSlash(path: String?): String = if (path == null || path.endsWith("/")) path ?: "" else "$path/" - private fun readLimited(input: InputStream, limit: Int): ByteArray { - val out = ByteArrayOutputStream() - val buffer = ByteArray(4096) - var n: Int - while (input.read(buffer).also { n = it } != -1) { - out.write(buffer, 0, n) - if (out.size() > limit) throw IOException("Response exceeds limit of $limit bytes") - } - return out.toByteArray() - } + private fun isHttps(uri: URI) = "https".equals(uri.scheme, ignoreCase = true) /** Shared JSON codec for validated storage receipts. */ companion object { diff --git a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/FileIoUploader.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/FileIoUploader.kt similarity index 80% rename from modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/FileIoUploader.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/FileIoUploader.kt index 6dff00b8c..299501d16 100644 --- a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/FileIoUploader.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/FileIoUploader.kt @@ -5,7 +5,6 @@ import java.io.IOException import java.net.URI import java.nio.file.Files import java.nio.file.Path -import java.time.Instant /** * Uploads an encrypted report to file.io as a single-download fallback. @@ -19,9 +18,7 @@ import java.time.Instant */ class FileIoUploader(private val endpoint: URI = URI.create("https://file.io")) : UploadProvider { init { - require(endpoint.scheme.equals("https", ignoreCase = true)) { - "file.io endpoint must use HTTPS" - } + UploadHttp.requireHttps(endpoint, "file.io endpoint") } override val backendId = "fileio" @@ -39,12 +36,11 @@ class FileIoUploader(private val endpoint: URI = URI.create("https://file.io")) } catch (exception: RuntimeException) { throw IOException("Invalid file.io response", exception) } - if (!json.get("success")?.asBoolean.orFalse()) throw IOException("file.io rejected the report") + if (json.get("success")?.asBoolean != true) throw IOException("file.io rejected the report") val link = URI.create(json.get("link")?.asString ?: throw IOException("file.io response has no link")) if (link.scheme != "https" || link.host != "file.io") throw IOException("Invalid file.io link") - return UploadReceipt(link, json.get("key")?.asString.orEmpty(), "", Instant.now().epochSecond, 0, backendId) + return UploadReceipt.permanent(link, json.get("key")?.asString.orEmpty(), backendId) } - private fun Boolean?.orFalse() = this ?: false private companion object { const val MAX_BYTES = 2L * 1024 * 1024 * 1024 } } diff --git a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/MultipartFileClient.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/MultipartFileClient.kt similarity index 76% rename from modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/MultipartFileClient.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/MultipartFileClient.kt index 80e438911..0aa8772ed 100644 --- a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/MultipartFileClient.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/MultipartFileClient.kt @@ -2,7 +2,6 @@ package org.pnfolder.pnlibrary.core.upload import java.io.ByteArrayOutputStream import java.io.IOException -import java.io.InputStream import java.net.HttpURLConnection import java.net.URI import java.nio.charset.StandardCharsets @@ -31,9 +30,7 @@ object MultipartFileClient { file: Path, contentType: String, ): String { - require(endpoint.scheme.equals("https", ignoreCase = true)) { - "Multipart endpoint must use HTTPS" - } + UploadHttp.requireHttps(endpoint, "Multipart endpoint") require(FIELD_NAME.matches(fileField)) { "Invalid multipart file field name" } require(isSafeHeaderValue(contentType)) { "Invalid multipart content type" } require(fields.keys.all(FIELD_NAME::matches)) { "Invalid multipart field name" } @@ -48,7 +45,8 @@ object MultipartFileClient { output.write(suffix) } if (connection.responseCode !in 200..299) throw IOException("${endpoint.host} HTTP ${connection.responseCode}") - return connection.inputStream.use { readBounded(it, endpoint) }.trim() + val body = connection.inputStream.use { UploadHttp.readBounded(it, what = endpoint.host) } + return String(body, StandardCharsets.UTF_8).trim() } finally { connection.disconnect() } @@ -60,7 +58,7 @@ object MultipartFileClient { fields.forEach { (name, value) -> prefix.write("--$boundary\r\nContent-Disposition: form-data; name=\"$name\"\r\n\r\n$value\r\n".toByteArray()) } - val safeName = file.fileName.toString().replace(Regex("[^A-Za-z0-9._-]"), "_") + val safeName = file.fileName.toString().replace(UNSAFE_FILE_NAME_CHARS, "_") val fileHeaders = buildString { append("--$boundary\r\n") append("Content-Disposition: form-data; name=\"$fileField\"; filename=\"$safeName\"\r\n") @@ -71,32 +69,16 @@ object MultipartFileClient { } private fun open(endpoint: URI, boundary: String, length: Long): HttpURLConnection { - val connection = endpoint.toURL().openConnection() as HttpURLConnection - connection.connectTimeout = 10_000 - connection.readTimeout = 30_000 - connection.instanceFollowRedirects = false - connection.requestMethod = "POST" + val connection = UploadHttp.open(endpoint, "POST", connectTimeoutMs = 10_000, readTimeoutMs = 30_000) connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=$boundary") - connection.setRequestProperty("User-Agent", "pnLibrary-Diagnostics") connection.doOutput = true connection.setFixedLengthStreamingMode(length) return connection } - private fun readBounded(input: InputStream, endpoint: URI): String { - val result = ByteArrayOutputStream() - val buffer = ByteArray(1024) - while (true) { - val count = input.read(buffer) - if (count < 0) break - result.write(buffer, 0, count) - if (result.size() > 16_384) throw IOException("${endpoint.host} response is too large") - } - return result.toString(StandardCharsets.UTF_8.name()) - } - private fun isSafeHeaderValue(value: String): Boolean = value.isNotBlank() && value.none { it == '\r' || it == '\n' || it.code < 0x20 } private val FIELD_NAME = Regex("[A-Za-z0-9_-]{1,64}") + private val UNSAFE_FILE_NAME_CHARS = Regex("[^A-Za-z0-9._-]") } diff --git a/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadHttp.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadHttp.kt new file mode 100644 index 000000000..e8506a071 --- /dev/null +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadHttp.kt @@ -0,0 +1,46 @@ +package org.pnfolder.pnlibrary.core.upload + +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.io.InputStream +import java.net.HttpURLConnection +import java.net.URI + +/** HTTP plumbing shared by the upload providers: timeouts, HTTPS rule and a bounded response read. */ +internal object UploadHttp { + const val USER_AGENT = "pnLibrary-Diagnostics" + + /** Largest response body that is read; the hosting services never send more. */ + const val MAX_RESPONSE_BYTES = 16_384 + + private const val READ_BUFFER_BYTES = 4096 + + fun requireHttps(uri: URI, what: String) { + require(uri.scheme.equals("https", ignoreCase = true)) { "$what must use HTTPS" } + } + + /** Opens a connection that never follows redirects, so a foreign host cannot send us elsewhere. */ + fun open(uri: URI, method: String, connectTimeoutMs: Int, readTimeoutMs: Int): HttpURLConnection { + val connection = uri.toURL().openConnection() as HttpURLConnection + connection.connectTimeout = connectTimeoutMs + connection.readTimeout = readTimeoutMs + connection.instanceFollowRedirects = false + connection.requestMethod = method + connection.setRequestProperty("User-Agent", USER_AGENT) + return connection + } + + /** Reads the response but stops after [limit] bytes, so a hostile server cannot fill the memory. */ + @Throws(IOException::class) + fun readBounded(input: InputStream, limit: Int = MAX_RESPONSE_BYTES, what: String = "Response"): ByteArray { + val result = ByteArrayOutputStream() + val buffer = ByteArray(READ_BUFFER_BYTES) + while (true) { + val count = input.read(buffer) + if (count < 0) break + result.write(buffer, 0, count) + if (result.size() > limit) throw IOException("$what exceeds limit of $limit bytes") + } + return result.toByteArray() + } +} diff --git a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedger.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedger.kt similarity index 69% rename from modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedger.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedger.kt index d5eba9d25..db532c7f2 100644 --- a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedger.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedger.kt @@ -6,31 +6,14 @@ import java.net.URI import java.nio.file.Path import java.time.Clock -/** - * Schedules and executes deletion of remotely uploaded diagnostic reports. - * - * Receipts without deletion tokens and policies with `deleteAfterDays <= 0` are - * intentionally ignored. Network failures retain the entry for a later cleanup - * attempt. JSON and filesystem concerns are delegated to [UploadLedgerPersistence]. - * - * @param file local JSON ledger path; deletion tokens never enter report archives - * @param clock time source used for deterministic scheduling and cleanup - */ +// Receipts without a delete token or deleteAfterDays <= 0 are intentionally skipped. +// Network failures keep the entry for the next cleanup attempt. class UploadLedger @JvmOverloads constructor( file: Path, private val clock: Clock = Clock.systemUTC(), ) { private val persistence = UploadLedgerPersistence(file, clock) - /** - * Records a future deletion for [receipt]. - * - * If the backend did not provide a creation timestamp, the current [clock] - * instant becomes the scheduling baseline. - * - * @param deleteAfterDays whole days to retain the remote report - * @throws IOException if ledger persistence fails - */ @Synchronized @Throws(IOException::class) fun record(receipt: UploadReceipt, deleteAfterDays: Int) { @@ -50,15 +33,6 @@ class UploadLedger @JvmOverloads constructor( persistence.write(entries) } - /** - * Attempts every due remote deletion and persists unfinished entries. - * - * Entries scheduled in the future and entries whose provider rejects or fails - * deletion remain in the ledger. - * - * @return number of entries successfully removed remotely - * @throws IOException if reading or rewriting the ledger fails - */ @Synchronized @Throws(IOException::class) fun cleanup(uploader: UploadProvider): Int { @@ -76,7 +50,6 @@ class UploadLedger @JvmOverloads constructor( return deleted } - /** Safe operational view; deletion tokens and report links are never exposed. */ @Synchronized fun diagnosticSnapshot(): Map { // Diagnostics must render even with an unreadable ledger; cleanup() surfaces the I/O error. diff --git a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerPersistence.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerPersistence.kt similarity index 97% rename from modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerPersistence.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerPersistence.kt index 07911d94a..d6126f6c5 100644 --- a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerPersistence.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerPersistence.kt @@ -79,7 +79,7 @@ class UploadLedgerPersistence( StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING, ) - move(temporary, file) + AtomicFiles.move(temporary, file) applyOwnerOnlyPermissions() } finally { Files.deleteIfExists(temporary) @@ -97,10 +97,6 @@ class UploadLedgerPersistence( } } - private fun move(source: Path, target: Path) { - AtomicFiles.move(source, target) - } - private fun applyOwnerOnlyPermissions() { try { Files.setPosixFilePermissions( diff --git a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadProvider.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadProvider.kt similarity index 100% rename from modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadProvider.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadProvider.kt diff --git a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadProviderChain.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadProviderChain.kt similarity index 100% rename from modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadProviderChain.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadProviderChain.kt diff --git a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadReceipt.kt b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadReceipt.kt similarity index 63% rename from modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadReceipt.kt rename to modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadReceipt.kt index dcbfa1242..26e098e4c 100644 --- a/modules/upload/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadReceipt.kt +++ b/modules/core/src/main/kotlin/org/pnfolder/pnlibrary/core/upload/UploadReceipt.kt @@ -1,6 +1,7 @@ package org.pnfolder.pnlibrary.core.upload import java.net.URI +import java.time.Instant /** * Receipt returned by a successful upload operation. @@ -20,7 +21,20 @@ data class UploadReceipt( val expiresEpochSeconds: Long, val backend: String, ) { + /** Whether the provider gave a token that deletes the upload. */ fun canDelete(): Boolean = deleteToken.isNotBlank() override fun toString(): String = link.toString() + + companion object { + /** A receipt for a backend that gives no delete token and no expiry; the upload counts as made now. */ + fun permanent(link: URI, id: String, backend: String): UploadReceipt = UploadReceipt( + link = link, + id = id, + deleteToken = "", + createdEpochSeconds = Instant.now().epochSecond, + expiresEpochSeconds = 0, + backend = backend, + ) + } } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/PnLibraryConfigLoaderTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/PnLibraryConfigLoaderTest.kt deleted file mode 100644 index 98ed9d031..000000000 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/PnLibraryConfigLoaderTest.kt +++ /dev/null @@ -1,65 +0,0 @@ -package org.pnfolder.pnlibrary.core - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Assertions.assertThrows -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.core.runtime.PnLibraryConfigLoader -import java.nio.file.Files -import java.nio.file.Path - -class PnLibraryConfigLoaderTest { - @TempDir lateinit var temporary: Path - - @Test - fun `creates a commented file with defaults and loads user values`() { - val defaults = PnLibraryConfigLoader.load(temporary) - val file = temporary.resolve("config.yml") - assertTrue(Files.isRegularFile(file)) - assertEquals("encrypted", defaults.uploadMode) - assertEquals(false, defaults.privacy) - val text = Files.readString(file) - assertTrue(text.contains("privacy: false")) - assertTrue(text.contains("# Скрывать ли в отчёте личные данные")) - assertTrue(text.contains("database.password")) - assertFalse(text.contains("upload")) - assertFalse(text.contains("log-records")) - assertEquals(true, defaults.upload) - assertEquals(200, defaults.logRecords) - - Files.writeString(file, """ - history-retention-days: 60 - privacy: true - """.trimIndent()) - - val configured = PnLibraryConfigLoader.load(temporary) - assertEquals(60, configured.historyRetentionDays) - assertEquals(true, configured.privacy) - assertTrue(Files.readString(file).contains("# Скрывать ли в отчёте личные данные")) - } - - @Test - fun `removes unknown keys after a backup and reports them`() { - val file = temporary.resolve("config.yml") - Files.writeString(file, "privcy: false\nprivacy: false\n") - val warnings = mutableListOf() - - val config = PnLibraryConfigLoader.load(temporary, warnings::add) - - assertFalse(config.privacy) - assertTrue(warnings.any { it.contains("privcy") }) - assertFalse(Files.readString(file).contains("privcy")) - assertTrue(Files.list(temporary).use { files -> files.anyMatch { it.fileName.toString().endsWith(".bak") } }) - } - - @Test - fun `rejects values outside the documented range`() { - Files.writeString(temporary.resolve("config.yml"), "history-retention-days: 7\n") - - val error = assertThrows(IllegalArgumentException::class.java) { PnLibraryConfigLoader.load(temporary) } - - assertTrue(error.message.orEmpty().contains("history-retention-days")) - } -} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ActionChecksTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ActionChecksTest.kt deleted file mode 100644 index 995c58380..000000000 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ActionChecksTest.kt +++ /dev/null @@ -1,328 +0,0 @@ -@file:OptIn(org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi::class) - -package org.pnfolder.pnlibrary.core.actions - -import net.kyori.adventure.sound.Sound -import net.kyori.adventure.text.Component -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Assertions.assertThrows -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.mockito.Mockito.mock -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.actions.builtin.CommandAction -import org.pnfolder.pnlibrary.api.actions.builtin.CommandRunner -import org.pnfolder.pnlibrary.api.actions.builtin.IfAction -import org.pnfolder.pnlibrary.api.actions.builtin.RequireAction -import org.pnfolder.pnlibrary.api.actions.builtin.StopAction -import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.audiences.ItemQuery -import org.pnfolder.pnlibrary.api.audiences.LibraryAudience -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.audiences.PlayerEffect -import org.pnfolder.pnlibrary.api.audiences.PlayerParticle -import org.pnfolder.pnlibrary.api.checks.Requirement -import org.pnfolder.pnlibrary.api.checks.builtin.Comparison -import org.pnfolder.pnlibrary.api.checks.builtin.ExperienceCheck -import org.pnfolder.pnlibrary.api.checks.builtin.ItemCheck -import org.pnfolder.pnlibrary.api.checks.builtin.LengthCheck -import org.pnfolder.pnlibrary.api.checks.builtin.NearCheck -import org.pnfolder.pnlibrary.api.checks.builtin.PermissionsCheck -import org.pnfolder.pnlibrary.api.checks.builtin.RegexCheck -import org.pnfolder.pnlibrary.api.checks.builtin.TypeCheck -import org.pnfolder.pnlibrary.api.checks.builtin.ValueCheck -import org.pnfolder.pnlibrary.api.checks.builtin.ValueType -import org.pnfolder.pnlibrary.api.checks.internal.CheckSerializer -import org.pnfolder.pnlibrary.api.logging.PnLogger -import org.pnfolder.pnlibrary.api.tasks.TaskScope -import org.pnfolder.pnlibrary.api.text.ComponentService -import java.util.UUID - -class ActionChecksTest { - private val log = mutableListOf() - - private fun context(player: FakePlayer = FakePlayer()): ActionContext = ActionContext( - player = player, - allPlayers = mock(LibraryAudience::class.java), - components = mock(ComponentService::class.java), - logger = mock(PnLogger::class.java), - tasks = mock(TaskScope::class.java), - ) - - private val recording = Action { log += "ran" } - - private fun say(text: String) = Action { log += text } - - private fun atLeast(key: String, value: String) = ValueCheck(key, Comparison.GREATER_OR_EQUAL, value) - - // ---- stop and command ---- - - @Test - fun `stop in a branch ends the whole invocation`() { - val ctx = context().setValue("slots", 0) - - ctx.execute(listOf(IfAction( - check = atLeast("slots", "1"), - thenActions = listOf(recording), - elseActions = listOf(StopAction()), - ), recording)) - - assertEquals(emptyList(), log) - assertTrue(ctx.stopped) - } - - @Test - fun `without stop the rest of the list runs`() { - val ctx = context().setValue("slots", 3) - - ctx.execute(listOf(IfAction( - check = atLeast("slots", "1"), - thenActions = listOf(recording), - elseActions = listOf(StopAction()), - ), recording)) - - assertEquals(listOf("ran", "ran"), log) - assertFalse(ctx.stopped) - } - - @Test - fun `command replaces the player name and strips the leading slash`() { - val player = FakePlayer() - val ctx = context(player) - - CommandAction("/give [player] apple 1", CommandRunner.CONSOLE).execute(ctx) - CommandAction("spawn", CommandRunner.PLAYER).execute(ctx) - - assertEquals(listOf("console: give Alice apple 1", "player: spawn"), player.commands) - } - - @Test - fun `unknown placeholders stay visible in the command text`() { - val player = FakePlayer() - - CommandAction("say [missing]").execute(context(player)) - - assertEquals(listOf("console: say [missing]"), player.commands) - } - - // ---- requirements ---- - - private fun shop( - minimum: Int = 0, - stopAtSuccess: Boolean = false, - ) = RequireAction(requirement = Requirement( - entries = linkedMapOf( - "space" to Requirement.Entry(atLeast("slots", "1"), deny = listOf(say("no space")), success = listOf(say("space ok"))), - "money" to Requirement.Entry(atLeast("money", "100"), deny = listOf(say("no money"))), - "vip" to Requirement.Entry(atLeast("vip", "1"), optional = true, success = listOf(say("vip ok"))), - "bonus" to Requirement.Entry(atLeast("bonus", "1"), optional = true, success = listOf(say("bonus ok"))), - ), - minimum = minimum, - stopAtSuccess = stopAtSuccess, - success = listOf(say("given")), - deny = listOf(say("denied")), - )) - - @Test - fun `requirements run the success actions of matched checks and then the shared success`() { - val ctx = context().setValue("slots", 2).setValue("money", 150) - - ctx.execute(listOf(shop(), recording)) - - assertEquals(listOf("space ok", "given", "ran"), log) - } - - @Test - fun `the first failed requirement runs its own deny then the shared one and stops the chain`() { - val ctx = context().setValue("slots", 0).setValue("money", 0) - - ctx.execute(listOf(shop(), recording)) - - assertEquals(listOf("no space", "denied"), log) - assertTrue(ctx.stopped) - } - - @Test - fun `optional requirements may fail unless a minimum is set`() { - val ctx = context().setValue("slots", 1).setValue("money", 100) - - shop().execute(ctx) - - assertEquals(listOf("space ok", "given"), log) - } - - @Test - fun `minimum counts only optional requirements and still needs all required ones`() { - val both = context().setValue("slots", 1).setValue("money", 100).setValue("vip", 1).setValue("bonus", 1) - val one = context().setValue("slots", 1).setValue("money", 100).setValue("vip", 1) - val none = context().setValue("slots", 1).setValue("money", 100) - - shop(minimum = 2).execute(both) - assertEquals(listOf("space ok", "vip ok", "bonus ok", "given"), log) - - log.clear() - shop(minimum = 2).execute(one) - assertEquals(listOf("denied"), log) - - log.clear() - shop(minimum = 1).execute(none) - assertEquals(listOf("denied"), log) - } - - @Test - fun `stop-at-success skips optional checks once the minimum is reached`() { - val ctx = context().setValue("slots", 1).setValue("money", 100).setValue("vip", 1).setValue("bonus", 1) - - shop(minimum = 1, stopAtSuccess = true).execute(ctx) - - assertEquals(listOf("space ok", "vip ok", "given"), log) - } - - @Test - fun `a bang before the type inverts a check`() { - val action = RequireAction(requirement = Requirement( - entries = linkedMapOf("not banned" to Requirement.Entry(CheckSerializer.parse( - mapOf("type" to "!>=", "input" to "banned", "output" to "1"), - ))), - success = listOf(say("welcome")), - )) - - action.execute(context().setValue("banned", 0)) - assertEquals(listOf("welcome"), log) - - log.clear() - action.execute(context().setValue("banned", 1)) - assertEquals(emptyList(), log) - } - - @Test - fun `a requirement without a check counts as failed`() { - val action = RequireAction(requirement = Requirement( - entries = linkedMapOf("empty" to Requirement.Entry(null, deny = listOf(say("bad")))), - success = listOf(say("given")), - )) - - action.execute(context()) - - assertEquals(listOf("bad"), log) - } - - @Test - fun `minimum above the number of optional checks never passes`() { - val requirement = Requirement(entries = mapOf("a" to Requirement.Entry(atLeast("a", "1"))), minimum = 1) - - assertFalse(requirement.check(context().setValue("a", 5))) - assertThrows(IllegalArgumentException::class.java) { Requirement(minimum = -1) } - } - - // ---- conditions ---- - - @Test - fun `permissions need all entries or the minimum`() { - val ctx = context(FakePlayer(permissions = setOf("a.use", "b.use"))) - - assertTrue(PermissionsCheck(listOf("a.use", "b.use")).matches(ctx)) - assertFalse(PermissionsCheck(listOf("a.use", "c.use")).matches(ctx)) - assertTrue(PermissionsCheck(listOf("a.use", "c.use"), minimum = 1).matches(ctx)) - assertFalse(PermissionsCheck(emptyList()).matches(ctx)) - } - - @Test - fun `has-item passes the description to the player and compares the count`() { - val player = FakePlayer(items = mapOf("diamond" to 5)) - val ctx = context(player) - - assertTrue(ItemCheck("diamond", 5, nameContains = "Key").matches(ctx)) - assertFalse(ItemCheck("diamond", 6).matches(ctx)) - assertFalse(ItemCheck("", 1).matches(ctx)) - assertEquals(ItemQuery("diamond", null, "Key", null, true), player.queries.first()) - } - - @Test - fun `has-item never matches on a platform without inventories`() { - assertFalse(ItemCheck("diamond").matches(context(FakePlayer(inventory = false)))) - } - - @Test - fun `has-exp compares points or levels`() { - val ctx = context(FakePlayer(points = 500.0, levels = 12.0)) - - assertTrue(ExperienceCheck(500).matches(ctx)) - assertFalse(ExperienceCheck(501).matches(ctx)) - assertTrue(ExperienceCheck(12, level = true).matches(ctx)) - assertFalse(ExperienceCheck(13, level = true).matches(ctx)) - } - - @Test - fun `is-near compares the distance in the named world`() { - val ctx = context(FakePlayer(distance = 4.0)) - - assertTrue(NearCheck("world,10,64,10", 5.0).matches(ctx)) - assertFalse(NearCheck("world,10,64,10", 3.0).matches(ctx)) - assertFalse(NearCheck("nether,10,64,10", 5.0).matches(ctx)) - assertThrows(IllegalArgumentException::class.java) { NearCheck("world,10,64", 5.0) } - } - - @Test - fun `regex must match the whole value`() { - val ctx = context().setValue("code", "AB-123") - - assertTrue(RegexCheck("code", "[A-Z]{2}-\\d+").matches(ctx)) - assertFalse(RegexCheck("code", "\\d+").matches(ctx)) - assertTrue(RegexCheck("id-[code]", "id-AB-123").matches(ctx)) - assertThrows(IllegalArgumentException::class.java) { RegexCheck("code", "[") } - } - - @Test - fun `length checks the range`() { - val ctx = context().setValue("word", "hello") - - assertTrue(LengthCheck("word", 3, 5).matches(ctx)) - assertFalse(LengthCheck("word", 6, 10).matches(ctx)) - assertThrows(IllegalArgumentException::class.java) { LengthCheck("word", 5, 3) } - } - - @Test - fun `is-type recognizes numbers and uuids`() { - val ctx = context().setValue("n", "42").setValue("d", "4.5").setValue("u", UUID.randomUUID().toString()) - - assertTrue(TypeCheck("n", ValueType.INT).matches(ctx)) - assertFalse(TypeCheck("d", ValueType.INT).matches(ctx)) - assertTrue(TypeCheck("d", ValueType.DOUBLE).matches(ctx)) - assertTrue(TypeCheck("u", ValueType.UUID).matches(ctx)) - assertFalse(TypeCheck("n", ValueType.UUID).matches(ctx)) - } - - private class FakePlayer( - private val permissions: Set = emptySet(), - private val items: Map = emptyMap(), - private val inventory: Boolean = true, - private val points: Double = 0.0, - private val levels: Double = 0.0, - private val distance: Double = 0.0, - ) : LibraryPlayer { - val commands = mutableListOf() - val queries = mutableListOf() - override val uniqueId: UUID = UUID.randomUUID() - override val name = "Alice" - override fun hasPermission(permission: String) = permission in permissions - override fun sendMessage(text: Component) = Unit - override fun actionBar(text: Component) = Unit - override fun playSound(sound: Sound) = Delivery.Delivered - override fun applyEffect(effect: PlayerEffect) = Delivery.Unsupported - override fun spawnParticle(particle: PlayerParticle) = Delivery.Unsupported - override fun runCommand(command: String, asConsole: Boolean): Delivery { - commands += (if (asConsole) "console: " else "player: ") + command - return Delivery.Delivered - } - override fun countItems(query: ItemQuery): Int? { - queries += query - return if (inventory) items[query.material] ?: 0 else null - } - override fun experience(asLevels: Boolean): Double = if (asLevels) levels else points - override fun distanceTo(world: String, x: Double, y: Double, z: Double): Double? = - if (world == "world") distance else null - } -} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ActionExtrasTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ActionExtrasTest.kt deleted file mode 100644 index a9af036dd..000000000 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ActionExtrasTest.kt +++ /dev/null @@ -1,208 +0,0 @@ -@file:OptIn(org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi::class) - -package org.pnfolder.pnlibrary.core.actions - -import net.kyori.adventure.sound.Sound -import net.kyori.adventure.text.Component -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Assertions.assertThrows -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.mockito.Mockito.mock -import org.mockito.Mockito.mockingDetails -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.actions.builtin.DelayAction -import org.pnfolder.pnlibrary.api.actions.builtin.RunAction -import org.pnfolder.pnlibrary.api.actions.builtin.StopAction -import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.audiences.LibraryAudience -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.audiences.PlayerEffect -import org.pnfolder.pnlibrary.api.audiences.PlayerParticle -import org.pnfolder.pnlibrary.api.checks.builtin.Comparison -import org.pnfolder.pnlibrary.api.checks.builtin.NotCheck -import org.pnfolder.pnlibrary.api.checks.builtin.PermissionCheck -import org.pnfolder.pnlibrary.api.checks.builtin.RegexCheck -import org.pnfolder.pnlibrary.api.checks.builtin.ValueCheck -import org.pnfolder.pnlibrary.api.checks.internal.RequirementSerializer -import org.pnfolder.pnlibrary.api.config.ConfigSerializationContext -import org.pnfolder.pnlibrary.api.logging.PnLogger -import org.pnfolder.pnlibrary.api.tasks.TaskScope -import org.pnfolder.pnlibrary.api.text.ComponentService -import java.time.Duration -import java.util.UUID - -class ActionExtrasTest { - private val log = mutableListOf() - private val logger = mock(PnLogger::class.java) - private val tasks = mock(TaskScope::class.java) - - private fun context(player: Recorder = Recorder(), templates: Map> = emptyMap()) = ActionContext( - player = player, - allPlayers = mock(LibraryAudience::class.java), - components = mock(ComponentService::class.java), - logger = logger, - tasks = tasks, - templates = templates, - ) - - private fun say(text: String) = Action { log += text } - - private fun warnings(): List = - mockingDetails(logger).invocations.filter { it.method.name == "warning" }.map { it.arguments[0].toString() } - - private fun requirement(vararg pairs: Pair) = RequirementSerializer.deserialize( - mapOf(*pairs), - ConfigSerializationContext("test", Any::class.java, Any::class.java, emptyList(), null), - ).entries.values.single() - - // ---- [wait] ---- - - @Test - fun `a wait pauses only what comes after it`() { - val ctx = context() - - ctx.execute(listOf(say("before"), DelayAction(Duration.ofSeconds(2)), say("after"))) - - assertEquals(listOf("before"), log) - assertEquals(1, mockingDetails(tasks).invocations.count { it.method.name == "schedule" }) - } - - @Test - fun `a wait at the end schedules nothing`() { - context().execute(listOf(say("only"), DelayAction(Duration.ofSeconds(2)))) - - assertEquals(listOf("only"), log) - assertEquals(0, mockingDetails(tasks).invocations.count { it.method.name == "schedule" }) - } - - // ---- [run] templates ---- - - @Test - fun `run executes the named template`() { - val ctx = context(templates = mapOf("refuse" to listOf(say("refused"), say("sound")))) - - ctx.execute(listOf(RunAction("refuse"), say("after"))) - - assertEquals(listOf("refused", "sound", "after"), log) - } - - @Test - fun `an unknown template warns with a suggestion and continues`() { - val ctx = context(templates = mapOf("refuse" to listOf(say("refused")))) - - ctx.execute(listOf(RunAction("refuze"), say("after"))) - - assertEquals(listOf("after"), log) - assertTrue(warnings().single().contains("Did you mean 'refuse'?"), warnings().toString()) - } - - @Test - fun `templates that call each other forever are stopped`() { - val ctx = context(templates = mapOf("a" to listOf(say("a"), RunAction("a")))) - - ctx.execute(listOf(RunAction("a"))) - - assertEquals(ActionContext.MAX_TEMPLATE_DEPTH, log.size) - assertTrue(warnings().single().contains("called too deeply"), warnings().toString()) - } - - @Test - fun `a stop inside a template ends the whole chain`() { - val ctx = context(templates = mapOf("quit" to listOf(StopAction()))) - - ctx.execute(listOf(RunAction("quit"), say("never"))) - - assertEquals(emptyList(), log) - assertTrue(ctx.stopped) - } - - @Test - fun `a platform without titles produces a warning, not an error`() { - val ctx = context(Recorder(titles = false)) - // the mocked component service returns nothing, so use a message-free title through the player directly - val player = Recorder(titles = false) - assertFalse(player.showTitle(Component.empty(), Component.empty(), Duration.ZERO, Duration.ZERO, Duration.ZERO).isDelivered) - assertEquals(emptyList(), log) - assertEquals(emptyList(), warnings()) - assertTrue(ctx.player is Recorder) - } - - // ---- requirement shortcuts ---- - - @Test - fun `an if line replaces the type`() { - val req = requirement("if" to "%vault_eco_balance% >= 100") - - assertEquals(ValueCheck("%vault_eco_balance%", Comparison.GREATER_OR_EQUAL, "100"), req.check) - } - - @Test - fun `a requirement can be only a line of text`() { - val req = RequirementSerializer.deserialize( - "%x% < 5", - ConfigSerializationContext("t", Any::class.java, Any::class.java, emptyList(), null), - ).entries.values.single() - - assertEquals(ValueCheck("%x%", Comparison.LESS_THAN, "5"), req.check) - assertEquals(emptyList(), req.deny) - } - - @Test - fun `expressions cover comparisons, words, permissions and negation`() { - fun parse(text: String) = RequirementSerializer.deserialize( - text, - ConfigSerializationContext("t", Any::class.java, Any::class.java, emptyList(), null), - ).entries.values.single().check - - assertEquals(ValueCheck("%a%", Comparison.NUMBER_EQUALS, "5"), parse("%a% == 5")) - assertEquals(ValueCheck("%a%", Comparison.GREATER_THAN, "5"), parse("%a%>5")) - assertEquals(ValueCheck("%rank%", Comparison.EQUALS, "vip", ignoreCase = true), parse("%rank% is vip")) - assertEquals(ValueCheck("%n%", Comparison.CONTAINS, "Al", ignoreCase = false), parse("%n% contains Al")) - assertEquals(RegexCheck("%code%", "[A-Z]{2}-\\d+"), parse("%code% matches [A-Z]{2}-\\d+")) - assertEquals(PermissionCheck("shop.use"), parse("permission shop.use")) - assertEquals(NotCheck(PermissionCheck("shop.banned")), parse("!permission shop.banned")) - assertEquals(NotCheck(PermissionCheck("shop.banned")), parse("not permission shop.banned")) - } - - @Test - fun `mixed or unreadable requirements are rejected with a reason`() { - assertTrue(assertThrows(IllegalArgumentException::class.java) { requirement("if" to "%a% >= 1", - "type" to "has permission") }.message!!.contains("either 'if' or 'type'")) - assertTrue(assertThrows(IllegalArgumentException::class.java) { requirement("if" to "%a% >= 1", "deny" to "x", - "deny_commands" to listOf("[message] y")) }.message!!.contains("either 'deny' or 'deny_commands'")) - assertTrue(assertThrows(IllegalArgumentException::class.java) { requirement("if" to "banana") }.message!!.contains("Cannot read requirement 'banana'")) - } - - @Test - fun `a typo next to the new short keys is suggested`() { - val message = assertThrows(IllegalArgumentException::class.java) { - requirement("type" to "has permission", "permission" to "x", "dney" to "no") - }.message!! - - assertTrue(message.contains("Did you mean 'deny'?"), message) - } - - @Test - fun `a typo next to an if line is reported too`() { - val message = assertThrows(IllegalArgumentException::class.java) { - requirement("if" to "%a% >= 1", "dney" to "no") - }.message!! - - assertTrue(message.contains("Unknown key 'dney' next to 'if'") && message.contains("Did you mean 'deny'?"), message) - } - - private class Recorder(private val titles: Boolean = true) : LibraryPlayer { - override val uniqueId: UUID = UUID.randomUUID() - override val name = "Alex" - override fun hasPermission(permission: String) = false - override fun sendMessage(text: Component) = Unit - override fun actionBar(text: Component) = Unit - override fun playSound(sound: Sound) = Delivery.Delivered - override fun applyEffect(effect: PlayerEffect) = Delivery.Unsupported - override fun spawnParticle(particle: PlayerParticle) = Delivery.Unsupported - override fun showTitle(title: Component, subtitle: Component, fadeIn: Duration, stay: Duration, fadeOut: Duration) = Delivery.of(titles) - } -} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ActionFormatTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ActionFormatTest.kt deleted file mode 100644 index 84fe84c9f..000000000 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ActionFormatTest.kt +++ /dev/null @@ -1,374 +0,0 @@ -@file:OptIn(org.pnfolder.pnlibrary.api.internal.InternalPnLibraryApi::class) - -package org.pnfolder.pnlibrary.core.actions - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Assertions.assertInstanceOf -import org.junit.jupiter.api.Assertions.assertThrows -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import org.mockito.Mockito.mock -import org.mockito.Mockito.mockingDetails -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.actions.builtin.CommandAction -import org.pnfolder.pnlibrary.api.actions.builtin.DelayAction -import org.pnfolder.pnlibrary.api.actions.builtin.MessageAction -import org.pnfolder.pnlibrary.api.actions.builtin.RequireAction -import org.pnfolder.pnlibrary.api.actions.builtin.RunAction -import org.pnfolder.pnlibrary.api.actions.builtin.SoundAction -import org.pnfolder.pnlibrary.api.actions.builtin.TitleAction -import org.pnfolder.pnlibrary.api.audiences.LibraryAudience -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.checks.Requirement -import org.pnfolder.pnlibrary.api.checks.builtin.Comparison -import org.pnfolder.pnlibrary.api.checks.builtin.ExperienceCheck -import org.pnfolder.pnlibrary.api.checks.builtin.ItemCheck -import org.pnfolder.pnlibrary.api.checks.builtin.LengthCheck -import org.pnfolder.pnlibrary.api.checks.builtin.NotCheck -import org.pnfolder.pnlibrary.api.checks.builtin.PermissionCheck -import org.pnfolder.pnlibrary.api.checks.builtin.PermissionsCheck -import org.pnfolder.pnlibrary.api.checks.builtin.RegexCheck -import org.pnfolder.pnlibrary.api.checks.builtin.TypeCheck -import org.pnfolder.pnlibrary.api.checks.builtin.ValueCheck -import org.pnfolder.pnlibrary.api.checks.builtin.ValueType -import org.pnfolder.pnlibrary.api.checks.internal.CheckSerializer -import org.pnfolder.pnlibrary.api.checks.internal.RequirementSerializer -import org.pnfolder.pnlibrary.api.config.ConfigOptions -import org.pnfolder.pnlibrary.api.config.ConfigSerializationContext -import org.pnfolder.pnlibrary.api.config.yaml -import org.pnfolder.pnlibrary.api.logging.PnLogger -import org.pnfolder.pnlibrary.api.plugin.PluginId -import org.pnfolder.pnlibrary.api.tasks.TaskScope -import org.pnfolder.pnlibrary.api.text.ComponentService -import org.pnfolder.pnlibrary.config.ConfigurationServiceImpl -import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership -import java.io.File -import java.nio.file.Files -import java.nio.file.Path -import java.time.Duration -import java.util.logging.Logger - -class ActionFormatTest { - @TempDir - lateinit var directory: Path - - // ---- conditions ---- - - private fun condition(vararg pairs: Pair) = CheckSerializer.parse(mapOf(*pairs)) - - @Test - fun `permission types read their fields`() { - assertEquals(PermissionCheck("shop.use"), condition("type" to "has permission", "permission" to "shop.use")) - assertEquals( - PermissionsCheck(listOf("a", "b"), 1), - condition("type" to "has permissions", "permissions" to listOf("a", "b"), "minimum" to 1), - ) - } - - @Test - fun `a bang negates and the spelling of keys does not matter`() { - val negated = condition("type" to "!has permission", "permission" to "shop.use") - assertEquals(NotCheck(PermissionCheck("shop.use")), negated) - - val item = condition("type" to "has-item", "material" to "diamond", "amount" to 3, "name-contains" to "Key", "loreContains" to "Rare") - assertEquals(ItemCheck("diamond", 3, nameContains = "Key", loreContains = "Rare", ignoreCase = false), item) - } - - @Test - fun `string types and comparators read input and output`() { - assertEquals( - ValueCheck("%player_world%", Comparison.EQUALS, "world", ignoreCase = false), - condition("type" to "string equals", "input" to "%player_world%", "output" to "world"), - ) - assertEquals( - ValueCheck("a", Comparison.EQUALS, "b", ignoreCase = true), - condition("type" to "string equals ignorecase", "input" to "a", "output" to "b"), - ) - assertEquals( - ValueCheck("%vault_eco_balance%", Comparison.GREATER_OR_EQUAL, "100"), - condition("type" to ">=", "input" to "%vault_eco_balance%", "output" to 100), - ) - assertEquals(ValueCheck("x", Comparison.NUMBER_EQUALS, "5"), condition("type" to "==", "input" to "x", "output" to 5)) - } - - @Test - fun `other types read their fields`() { - assertEquals(ExperienceCheck(30, true), condition("type" to "has exp", "amount" to 30, "level" to true)) - assertEquals(LengthCheck("x", 2, 8), condition("type" to "string length", "input" to "x", "min" to 2, "max" to 8)) - assertEquals(TypeCheck("x", ValueType.UUID), condition("type" to "is object", "input" to "x", "object" to "uuid")) - assertEquals(RegexCheck("x", "[a-z]+"), condition("type" to "regex matches", "input" to "x", "regex" to "[a-z]+")) - } - - @Test - fun `unknown types and missing fields fail with a clear reason`() { - assertTrue(assertThrows(IllegalArgumentException::class.java) { condition("type" to "has wings") }.message!!.contains("has wings")) - assertTrue(assertThrows(IllegalArgumentException::class.java) { condition("type" to "has permission") }.message!!.contains("permission")) - assertThrows(IllegalArgumentException::class.java) { condition("permission" to "x") } - } - - @Test - fun `a mistyped type suggests the closest one`() { - val message = assertThrows(IllegalArgumentException::class.java) { condition("type" to "has permision") }.message!! - - assertTrue(message.contains("Did you mean 'has permission'?"), message) - } - - @Test - fun `an unknown key is reported instead of silently ignored`() { - val message = assertThrows(IllegalArgumentException::class.java) { - condition("type" to "has permission", "permision" to "shop.use") - }.message!! - - assertTrue(message.contains("Unknown key 'permision'") && message.contains("Did you mean 'permission'?"), message) - } - - @Test - fun `a typo in deny_commands next to a requirement is reported`() { - val message = assertThrows(IllegalArgumentException::class.java) { - RequirementSerializer.deserialize( - mapOf("type" to "has permission", "permission" to "shop.use", "deny_comands" to listOf("[message] no")), - ConfigSerializationContext("shop.requirements.a", Any::class.java, Any::class.java, emptyList(), null), - ) - }.message!! - - assertTrue(message.contains("Did you mean 'deny_commands'?"), message) - } - - @Test - fun `conditions written back read the same`() { - listOf( - PermissionCheck("a.b"), - PermissionsCheck(listOf("a", "b"), 2), - ExperienceCheck(5, true), - LengthCheck("x", 1, 9), - ValueCheck("x", Comparison.GREATER_THAN, "5"), - ValueCheck("x", Comparison.EQUALS, "y", ignoreCase = false), - NotCheck(PermissionCheck("a")), - ).forEach { original -> - val written = CheckSerializer.describe(original)!! - assertEquals(original, CheckSerializer.parse(written), written.toString()) - } - } - - // ---- a real YAML file ---- - - data class ShopConfig( - var buy: List = emptyList(), - var gate: Requirement = Requirement(), - ) - - class Owner(val folder: File) { - val logger: Logger = Logger.getLogger("action-format-test") - } - - /** Gives each [Owner] its folder and logger, as a real platform does for its plugins. */ - object OwnerPlatform : PlatformOwnership { - override fun ownerDataFolder(owner: Any): java.nio.file.Path? = (owner as? Owner)?.folder?.toPath() - - override fun ownerLogger(owner: Any): Logger? = (owner as? Owner)?.logger - } - - @Test - fun `a line of text is rejected at its entry with the object to write instead`() { - Files.writeString( - directory.resolve("shop.yml"), - listOf("buy:", " - type: message", " message: fine", " - \"[console] give %player_name% apple\"") - .joinToString("\n") + "\n", - ) - - val service = ConfigurationServiceImpl(ActionFormatTest.OwnerPlatform) - service.use { - val scope = it.scope(Owner(directory.toFile()), PluginId.of("tester")) - val error = assertThrows(IllegalArgumentException::class.java) { - scope.yaml("shop.yml", ConfigOptions.DEFAULT) { ShopConfig() }.load() - } - - val message = error.message!! - assertTrue(message.contains("at buy[1]"), message) - assertTrue(message.contains("type: console") && message.contains("command: give %player_name% apple"), message) - } - } - - @Test - fun `a typo inside a requirement is reported once at the requirement`() { - Files.writeString( - directory.resolve("shop.yml"), - listOf( - "buy:", - " - type: requirements", - " requirements:", - " rich:", - " type: has permission", - " permission: shop.use", - " deny_comands:", - " - type: message", - " message: no", - ).joinToString("\n") + "\n", - ) - - val service = ConfigurationServiceImpl(ActionFormatTest.OwnerPlatform) - service.use { - val scope = it.scope(Owner(directory.toFile()), PluginId.of("tester")) - val error = assertThrows(IllegalArgumentException::class.java) { - scope.yaml("shop.yml", ConfigOptions.DEFAULT) { ShopConfig() }.load() - } - - val message = error.message!! - assertTrue(message.contains("at buy[0].requirement.requirements.rich"), message) - assertTrue(message.contains("Did you mean 'deny_commands'?"), message) - assertEquals(1, Regex("Invalid configuration value at").findAll(message).count(), message) - } - } - - @Test - fun `a minimum above the optional count read from yaml warns and cannot pass`() { - Files.writeString( - directory.resolve("shop.yml"), - listOf( - "gate:", - " minimum_requirements: 2", - " requirements:", - " a:", - " type: has permission", - " permission: shop.use", - " deny_commands:", - " - type: log", - " text: no", - ).joinToString(System.lineSeparator()) + System.lineSeparator(), - ) - val service = ConfigurationServiceImpl(ActionFormatTest.OwnerPlatform) - service.use { - val scope = it.scope(Owner(directory.toFile()), PluginId.of("tester")) - val gate = scope.yaml("shop.yml", ConfigOptions.DEFAULT) { ShopConfig() }.load().value.gate - val logger = mock(PnLogger::class.java) - val context = ActionContext( - player = mock(LibraryPlayer::class.java), - allPlayers = mock(LibraryAudience::class.java), - components = mock(ComponentService::class.java), - logger = logger, - tasks = mock(TaskScope::class.java), - ) - - assertFalse(gate.test(context)) - - val warnings = mockingDetails(logger).invocations.filter { call -> call.method.name == "warning" } - assertTrue(warnings.any { call -> call.arguments[0].toString().contains("can never pass") }, warnings.toString()) - } - } - - @Test - fun `a yaml file with titles, waits, templates and short requirements loads`() { - Files.writeString( - directory.resolve("shop.yml"), - listOf( - "buy:", - " - type: title", - " title: '&aWelcome'", - " subtitle: '&7Hi'", - " - type: delay", - " duration: 2s", - " - type: run", - " name: refuse", - " - type: requirements", - " requirements:", - " rich:", - " if: \"%vault_eco_balance% >= 100\"", - " deny:", - " - type: message", - " message: '&cNeed 100'", - " sober: \"%drunk% == 0\"", - ).joinToString("\n") + "\n", - ) - - val service = ConfigurationServiceImpl(ActionFormatTest.OwnerPlatform) - service.use { - val scope = it.scope(Owner(directory.toFile()), PluginId.of("tester")) - val loaded = scope.yaml("shop.yml", ConfigOptions.DEFAULT) { ShopConfig() }.load().value - - assertInstanceOf(TitleAction::class.java, loaded.buy[0]) - assertEquals(DelayAction(Duration.ofSeconds(2)), loaded.buy[1]) - assertEquals(RunAction("refuse"), loaded.buy[2]) - val requirements = (loaded.buy[3] as RequireAction).requirement!! - assertEquals(listOf("rich", "sober"), requirements.entries.keys.toList()) - assertEquals(1, requirements.entries.getValue("rich").deny.size) - assertEquals( - ValueCheck("%drunk%", Comparison.NUMBER_EQUALS, "0"), - requirements.entries.getValue("sober").check, - ) - } - } - - @Test - fun `a yaml file written in the menu style loads`() { - Files.writeString( - directory.resolve("shop.yml"), - """ - buy: - - type: message - message: "&aHello %player_name%" - - type: sound - sound: ENTITY_PLAYER_LEVELUP - - type: delay - duration: 1s - do: - - type: console - command: give %player_name% diamond 1 - - type: requirements - requirements: - rich: - type: ">=" - input: "%vault_eco_balance%" - output: 100 - deny_commands: - - type: message - message: "&cNot enough" - vip: - type: has permission - permission: shop.vip - optional: true - success_commands: - - type: message - message: VIP discount - not_banned: - type: "!has permission" - permission: shop.banned - minimum_requirements: 1 - stop_at_success: true - deny_commands: - - type: sound - sound: ENTITY_VILLAGER_NO - success_commands: - - type: console - command: eco take %player_name% 100 - gate: - requirements: - near: - type: is near - location: "world,0,64,0" - distance: 10 - """.trimIndent() + "\n", - ) - - val service = ConfigurationServiceImpl(ActionFormatTest.OwnerPlatform) - service.use { - val scope = it.scope(Owner(directory.toFile()), PluginId.of("tester")) - val loaded = scope.yaml("shop.yml", ConfigOptions.DEFAULT) { ShopConfig() }.load().value - - assertEquals(MessageAction(listOf("&aHello %player_name%")), loaded.buy[0]) - assertInstanceOf(SoundAction::class.java, loaded.buy[1]) - assertInstanceOf(DelayAction::class.java, loaded.buy[2]) - val requirements = (loaded.buy[3] as RequireAction).requirement!! - assertEquals(listOf("rich", "vip", "not_banned"), requirements.entries.keys.toList()) - assertEquals(1, requirements.minimum) - assertTrue(requirements.stopAtSuccess) - assertEquals(1, requirements.entries.getValue("rich").deny.size) - assertTrue(requirements.entries.getValue("vip").optional) - assertEquals(NotCheck(PermissionCheck("shop.banned")), requirements.entries.getValue("not_banned").check) - assertEquals(listOf(CommandAction("eco take %player_name% 100")), requirements.success) - assertEquals(1, loaded.gate.entries.size) - } - } -} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ActionNodeTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ActionNodeTest.kt deleted file mode 100644 index 764dbf56d..000000000 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ActionNodeTest.kt +++ /dev/null @@ -1,181 +0,0 @@ -package org.pnfolder.pnlibrary.core.actions - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertInstanceOf -import org.junit.jupiter.api.Assertions.assertThrows -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.builtin.DelayAction -import org.pnfolder.pnlibrary.api.actions.builtin.GroupAction -import org.pnfolder.pnlibrary.api.actions.builtin.IfAction -import org.pnfolder.pnlibrary.api.actions.builtin.MessageAction -import org.pnfolder.pnlibrary.api.actions.builtin.RepeatAction -import org.pnfolder.pnlibrary.api.actions.builtin.RunAction -import org.pnfolder.pnlibrary.api.checks.builtin.ChanceCheck -import org.pnfolder.pnlibrary.api.checks.builtin.PermissionCheck -import org.pnfolder.pnlibrary.api.config.ConfigOptions -import org.pnfolder.pnlibrary.api.config.yaml -import org.pnfolder.pnlibrary.api.plugin.PluginId -import org.pnfolder.pnlibrary.config.ConfigurationServiceImpl -import java.nio.file.Files -import java.nio.file.Path -import java.time.Duration - -class ActionNodeTest { - @TempDir - lateinit var directory: Path - - private fun load(vararg lines: String): List { - Files.writeString(directory.resolve("join.yml"), lines.joinToString("\n") + "\n") - ConfigurationServiceImpl(ActionFormatTest.OwnerPlatform).use { - val scope = it.scope(ActionFormatTest.Owner(directory.toFile()), PluginId.of("tester")) - return scope.yaml("join.yml", ConfigOptions.DEFAULT) { - ActionFormatTest.ShopConfig() - }.load().value.buy - } - } - - @Test - fun `every node is written with a type and wrappers hold their actions under do`() { - val actions = load( - "buy:", - " - type: message", - " message: Hello, %player_name%", - " - type: delay", - " duration: 2s", - " do:", - " - type: message", - " message: Later", - " - type: chance", - " probability: 10%", - " do:", - " - type: message", - " message: Lucky", - " - type: if", - " check:", - " type: permission", - " permission: group.vip", - " do:", - " - type: message", - " message: VIP", - " else:", - " - type: message", - " message: Buy VIP", - " - type: repeat", - " times: 3", - " every: 1s", - " do:", - " - type: message", - " message: Tick", - " - type: group", - " do:", - " - type: message", - " message: One", - ) - - assertEquals(MessageAction(listOf("Hello, %player_name%")), actions[0]) - assertEquals(DelayAction(Duration.ofSeconds(2), listOf(MessageAction(listOf("Later")))), actions[1]) - assertEquals( - IfAction(ChanceCheck(0.1), listOf(MessageAction(listOf("Lucky")))), - actions[2], - ) - assertEquals( - IfAction( - check = PermissionCheck("group.vip"), - thenActions = listOf(MessageAction(listOf("VIP"))), - elseActions = listOf(MessageAction(listOf("Buy VIP"))), - ), - actions[3], - ) - assertEquals(RepeatAction(3, Duration.ofSeconds(1), listOf(MessageAction(listOf("Tick")))), actions[4]) - assertEquals(GroupAction(listOf(MessageAction(listOf("One")))), actions[5]) - } - - @Test - fun `wrappers nest and the messages list still reads`() { - val actions = load( - "buy:", - " - type: message", - " messages: [old]", - " - type: delay", - " duration: 1s", - " do:", - " - type: chance", - " probability: 50%", - " do:", - " - type: message", - " message: Inner", - ) - - assertEquals(MessageAction(listOf("old")), actions[0]) - val delay = actions[1] as DelayAction - assertInstanceOf(IfAction::class.java, delay.thenActions.single()) - } - - @Test - fun `a bad percentage is reported at its own entry`() { - val error = assertThrows(IllegalArgumentException::class.java) { - load("buy:", " - type: chance", " probability: 150%", " do: []") - } - - assertTrue(error.message!!.contains("at buy[0]") && error.message!!.contains("0% to 100%"), error.message) - } - - @Test - fun `run is the template call and group is the sequence`() { - val actions = load( - "buy:", - " - type: run", - " name: refuse", - " - type: group", - " do:", - " - type: message", - " message: One", - ) - - assertEquals(RunAction("refuse"), actions[0]) - assertInstanceOf(GroupAction::class.java, actions[1]) - } - - @Test - fun `a chance without else and one with else read the same way`() { - val actions = load( - "buy:", - " - type: chance", - " probability: 25%", - " do:", - " - type: message", - " message: Won", - " else:", - " - type: message", - " message: Lost", - ) - - assertEquals( - IfAction( - check = ChanceCheck(0.25), - thenActions = listOf(MessageAction(listOf("Won"))), - elseActions = listOf(MessageAction(listOf("Lost"))), - ), - actions.single(), - ) - } - - @Test - fun `a repeat needs a sensible number of times`() { - assertThrows(IllegalArgumentException::class.java) { RepeatAction(times = 0) } - assertThrows(IllegalArgumentException::class.java) { RepeatAction(times = RepeatAction.MAX_TIMES + 1) } - assertEquals(1, RepeatAction().times) - } - - @Test - fun `a check that is neither a name nor an object is rejected`() { - val error = assertThrows(IllegalArgumentException::class.java) { - load("buy:", " - type: if", " check: 5", " do: []") - } - - assertTrue(error.message!!.contains("at buy[0]"), error.message) - } -} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/CheckSystemTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/CheckSystemTest.kt deleted file mode 100644 index bf2e520a5..000000000 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/CheckSystemTest.kt +++ /dev/null @@ -1,278 +0,0 @@ -package org.pnfolder.pnlibrary.core.actions - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Assertions.assertThrows -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import org.mockito.Mockito.mock -import org.mockito.Mockito.mockingDetails -import org.mockito.Mockito.`when` -import org.pnfolder.pnlibrary.api.actions.Action -import org.pnfolder.pnlibrary.api.actions.ActionContext -import org.pnfolder.pnlibrary.api.actions.builtin.CommandAction -import org.pnfolder.pnlibrary.api.actions.builtin.CommandRunner -import org.pnfolder.pnlibrary.api.actions.builtin.LogAction -import org.pnfolder.pnlibrary.api.actions.builtin.SoundAction -import org.pnfolder.pnlibrary.api.actions.builtin.TitleAction -import org.pnfolder.pnlibrary.api.audiences.LibraryAudience -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.checks.Requirement -import org.pnfolder.pnlibrary.api.checks.builtin.PermissionCheck -import org.pnfolder.pnlibrary.api.config.ConfigOptions -import org.pnfolder.pnlibrary.api.config.yaml -import org.pnfolder.pnlibrary.api.logging.PnLogger -import org.pnfolder.pnlibrary.api.plugin.PluginId -import org.pnfolder.pnlibrary.api.tasks.TaskScope -import org.pnfolder.pnlibrary.api.text.ComponentService -import org.pnfolder.pnlibrary.config.ConfigurationServiceImpl -import java.nio.file.Files -import java.nio.file.Path -import java.time.Duration - -class CheckSystemTest { - @TempDir - lateinit var directory: Path - - data class ShopFile( - var checks: Map = emptyMap(), - var buy: List = emptyList(), - ) - - private val logger = mock(PnLogger::class.java) - - private fun load(vararg lines: String): ShopFile { - Files.writeString(directory.resolve("shop.yml"), lines.joinToString("\n") + "\n") - ConfigurationServiceImpl(ActionFormatTest.OwnerPlatform).use { - val scope = it.scope(ActionFormatTest.Owner(directory.toFile()), PluginId.of("tester")) - return scope.yaml("shop.yml", ConfigOptions.DEFAULT) { ShopFile() }.load().value - } - } - - private fun player(vararg permissions: String): LibraryPlayer = mock(LibraryPlayer::class.java).also { player -> - `when`(player.name).thenReturn("Alex") - permissions.forEach { `when`(player.hasPermission(it)).thenReturn(true) } - } - - private fun context(file: ShopFile, player: LibraryPlayer, money: Int = 0) = ActionContext( - player = player, - allPlayers = mock(LibraryAudience::class.java), - components = mock(ComponentService::class.java), - logger = logger, - tasks = mock(TaskScope::class.java), - values = mapOf("money" to money), - checks = file.checks, - ) - - /** Texts written by `type: log` actions, in order. */ - private fun logged(): List = - mockingDetails(logger).invocations.filter { it.method.name == "info" }.map { it.arguments[0].toString() } - - private fun warnings(): List = - mockingDetails(logger).invocations.filter { it.method.name == "warning" }.map { it.arguments[0].toString() } - - private val shop = arrayOf( - "checks:", - " has-100:", - " check:", - " type: '>='", - " input: money", - " output: 100", - " deny:", - " - type: log", - " text: no money", - " success:", - " - type: log", - " text: paid", - " vip:", - " check:", - " type: permission", - " permission: group.vip", - "buy:", - " - type: require", - " check: has-100", - " - type: log", - " text: bought", - " - type: if", - " check: vip", - " do:", - " - type: log", - " text: vip bonus", - " else:", - " - type: log", - " text: no bonus", - ) - - @Test - fun `a named check passes, runs its success and the chain goes on`() { - val file = load(*shop) - val ctx = context(file, player("group.vip"), money = 150) - - ctx.execute(file.buy) - - assertEquals(listOf("paid", "bought", "vip bonus"), logged()) - assertFalse(ctx.stopped) - } - - @Test - fun `a failed require runs the check's deny written with type and stops`() { - val file = load(*shop) - val ctx = context(file, player(), money = 40) - - ctx.execute(file.buy) - - assertEquals(listOf("no money"), logged()) - assertTrue(ctx.stopped) - } - - @Test - fun `if only asks a named check and keeps going`() { - val file = load(*shop) - - context(file, player(), money = 150).execute(file.buy) - - assertEquals(listOf("paid", "bought", "no bonus"), logged()) - } - - @Test - fun `checks work on their own from code`() { - val file = load(*shop) - val rich = context(file, player(), money = 500) - val poor = context(file, player(), money = 5) - - assertTrue(file.checks.getValue("has-100").check(rich)) - assertFalse(file.checks.getValue("has-100").check(poor)) - assertEquals(emptyList(), logged()) - assertFalse(file.checks.getValue("has-100").test(poor)) - assertEquals(listOf("no money"), logged()) - } - - @Test - fun `all, any, not and at-least combine checks`() { - val file = load( - "checks:", - " staff:", - " check:", - " type: any", - " checks:", - " - type: permission", - " permission: group.admin", - " - type: permission", - " permission: group.mod", - " trader:", - " check:", - " type: all", - " checks:", - " - type: permission", - " permission: shop.use", - " - type: not", - " check:", - " type: permission", - " permission: shop.banned", - " veteran:", - " check:", - " type: at-least", - " count: 2", - " checks:", - " - staff", - " - trader", - " - type: '>='", - " input: money", - " output: 10", - ) - val checks = file.checks - - assertTrue(checks.getValue("staff").check(context(file, player("group.mod")))) - assertFalse(checks.getValue("staff").check(context(file, player()))) - assertTrue(checks.getValue("trader").check(context(file, player("shop.use")))) - assertFalse(checks.getValue("trader").check(context(file, player("shop.use", "shop.banned")))) - assertTrue(checks.getValue("veteran").check(context(file, player("shop.use"), money = 20))) - assertFalse(checks.getValue("veteran").check(context(file, player("shop.use")))) - } - - @Test - fun `an unknown check name warns with a suggestion`() { - val file = load(*shop, " - type: require", " check: has-10") - - context(file, player("group.vip"), money = 150).execute(file.buy) - - assertTrue(warnings().any { it.contains("Unknown check 'has-10'") && it.contains("has-100") }, warnings().toString()) - } - - @Test - fun `sound and title read the friendly names`() { - val file = load( - "buy:", - " - type: sound", - " sound: ENTITY_VILLAGER_NO", - " - type: title", - " title: Hi", - " fade-in: 1s", - " stay: 3s", - " fade-out: 2s", - ) - - assertEquals(SoundAction("entity.villager.no"), file.buy[0]) - assertEquals( - TitleAction("Hi", fadeIn = Duration.ofSeconds(1), stay = Duration.ofSeconds(3), fadeOut = Duration.ofSeconds(2)), - file.buy[1], - ) - } - - @Test - fun `a line of text in deny is rejected`() { - val error = assertThrows(IllegalArgumentException::class.java) { - load("checks:", " a:", " check: b", " deny:", " - '[message] no'") - } - - assertTrue(error.message!!.contains("checks.a.deny[0]") && error.message!!.contains("type: message"), error.message) - } - - @Test - fun `default checks are written with type and read back the same`() { - val defaults = ShopFile( - checks = mapOf( - "vip" to Requirement( - PermissionCheck("group.vip"), - deny = listOf(LogAction("no vip")), - success = listOf(CommandAction("say hi", CommandRunner.CONSOLE)), - ), - ), - ) - ConfigurationServiceImpl(ActionFormatTest.OwnerPlatform).use { - val scope = it.scope(ActionFormatTest.Owner(directory.toFile()), PluginId.of("tester")) - scope.yaml("written.yml", ConfigOptions.DEFAULT) { defaults }.load() - } - val text = Files.readString(directory.resolve("written.yml")) - assertTrue(text.contains("type: log") && !text.contains("[log]"), text) - - Files.copy(directory.resolve("written.yml"), directory.resolve("shop.yml")) - assertEquals(defaults.checks, load(*Files.readAllLines(directory.resolve("written.yml")).toTypedArray()).checks) - } - - @Test - fun `console and player types run commands`() { - val file = load( - "buy:", - " - type: console", - " command: give %player_name% apple", - " - type: player", - " command: spawn", - ) - - assertEquals( - listOf(CommandAction("give %player_name% apple", CommandRunner.CONSOLE), CommandAction("spawn", CommandRunner.PLAYER)), - file.buy, - ) - } - - @Test - fun `a chance probability over 100 percent is rejected at its entry`() { - val error = assertThrows(IllegalArgumentException::class.java) { - load("buy:", " - type: chance", " probability: 150%", " do: []") - } - - assertTrue(error.message!!.contains("buy[0]") && error.message!!.contains("0% to 100%"), error.message) - } -} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ExpressionTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ExpressionTest.kt new file mode 100644 index 000000000..83b54a74c --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ExpressionTest.kt @@ -0,0 +1,191 @@ +package org.pnfolder.pnlibrary.core.actions + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.mockito.ArgumentMatchers.anyString +import org.mockito.Mockito.mock +import org.mockito.Mockito.`when` +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.logging.PnLogger +import org.pnfolder.pnlibrary.api.scenario.actions.Action +import org.pnfolder.pnlibrary.api.scenario.actions.ActionContext +import org.pnfolder.pnlibrary.api.scenario.actions.ActionResult +import org.pnfolder.pnlibrary.api.scenario.actions.DefinitionConflict +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.AttemptAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.CallAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.ErrorHandler +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.RandomAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.RandomOption +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.SetAction +import org.pnfolder.pnlibrary.api.scenario.expression.Expression +import org.pnfolder.pnlibrary.api.scenario.expression.ExpressionException +import org.pnfolder.pnlibrary.api.scenario.requirements.Requirement +import org.pnfolder.pnlibrary.api.scenario.requirements.Verdict +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.ExpressionRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.RefRequirement +import org.pnfolder.pnlibrary.api.tasks.TaskScope +import org.pnfolder.pnlibrary.api.text.ComponentService +import org.pnfolder.pnlibrary.core.plugin.module.LayeredLookup +import org.pnfolder.pnlibrary.core.plugin.module.ScenarioDefinitions +import java.util.UUID + +/** The calculator, named definitions, calls and typed error handlers. */ +class ExpressionTest { + private val player = mock(LibraryPlayer::class.java).also { + `when`(it.uniqueId).thenReturn(UUID.randomUUID()) + `when`(it.name).thenReturn("Alice") + `when`(it.experience(true)).thenReturn(12.0) + `when`(it.hasPermission(anyString())).thenAnswer { call -> call.getArgument(0) == "shop.vip" } + } + private val shared = ScenarioDefinitions() + private val own = ScenarioDefinitions() + private val log = mutableListOf() + + private fun context(vararg values: Pair) = ActionContext( + player = player, + allPlayers = player, + components = mock(ComponentService::class.java), + logger = mock(PnLogger::class.java), + tasks = mock(TaskScope::class.java), + values = mapOf(*values), + lookup = LayeredLookup(own, shared), + ) + + private fun calc(text: String, ctx: ActionContext = context()) = Expression.parse(text).text(ctx) + + @Test + fun `arithmetic follows the usual precedence`() { + assertEquals("14", calc("2 + 3 * 4")) + assertEquals("20", calc("(2 + 3) * 4")) + assertEquals("512", calc("2 ^ 3 ^ 2")) + assertEquals("-1", calc("1 - 2")) + assertEquals("2.5", calc("5 / 2")) + assertEquals("1", calc("10 % 3")) + assertEquals("ab3", calc("'ab' + 3")) + } + + @Test + fun `logic, comparison and the condition operator`() { + assertEquals("true", calc("1 < 2 && 2 <= 2 && 3 != 4 && !(1 > 2)")) + assertEquals("yes", calc("5 >= 10 ? 'big' : 5 >= 3 ? 'yes' : 'no'")) + assertEquals("true", calc("false || true && true")) + assertEquals("true", calc("'Abc' == 'Abc'")) + } + + @Test + fun `values come from the run, and text that looks like a number is a number`() { + val ctx = context("balance" to "250", "rank" to "vip", "weird-name" to 7) + + assertEquals("25", calc("balance / 10", ctx)) + assertEquals("true", calc("rank == 'vip'", ctx)) + assertEquals("14", calc("{weird-name} * 2", ctx)) + assertEquals("false", calc("unknown_name > 1", ctx)) + } + + @Test + fun `functions about the player and about numbers`() { + assertEquals("true", calc("level() >= 10 && permission('shop.vip') && !permission('admin')")) + assertEquals("3", calc("min(5, 3, 9)")) + assertEquals("10", calc("clamp(50, 1, 10)")) + assertEquals("3.14", calc("round(3.14159, 2)")) + assertEquals("4", calc("sqrt(16)")) + assertEquals("3", calc("len('abc')")) + assertEquals("true", calc("contains(upper('admin team'), 'ADMIN')")) + assertEquals("yes", calc("if(level() > 5, 'yes', 'no')")) + } + + @Test + fun `a plugin function joins the language`() { + own.defineFunction("kills", { _, _ -> 120.0 }, "shop", DefinitionConflict.FAIL) + + assertEquals("true", calc("kills() >= 100")) + } + + @Test + fun `mistakes are reported with a position, and a bad calculation is simply not met`() { + assertThrows(ExpressionException::class.java) { Expression.parse("1 +") } + assertThrows(ExpressionException::class.java) { Expression.parse("(1 + 2") } + assertThrows(ExpressionException::class.java) { ExpressionRequirement("2 $ 3") } + val verdict = ExpressionRequirement("'a' * 2").test(context()) + assertTrue(verdict is Verdict.Unmet) + assertFalse(ExpressionRequirement("1 / 0 > 1").test(context()).isMet) + } + + @Test + fun `a calculation inside a text and the set action`() { + val ctx = context("base" to 200) + SetAction("price", expression = "base * 0.9").run(ctx) + SetAction("label", value = "{player} pays {price}").run(ctx) + + assertEquals("180", ctx.format("{= price}")) + assertEquals("Alice pays 180", ctx.value("label")) + assertEquals("level 24", ctx.format("level {= level() * 2}")) + assertEquals("{= 1 +}", ctx.format("{= 1 +}")) + } + + @Test + fun `a defined action is called with arguments that do not leak`() { + own.defineAction("greet", Action { c -> log += c.format("hello {who}"); ActionResult.Done }, "shop", DefinitionConflict.FAIL) + val ctx = context() + + val result = ctx.execute(listOf(CallAction("greet", mapOf("who" to "{= 1 + 1}")), CallAction("greet", mapOf("who" to "Bob")))) + + assertEquals(ActionResult.Done, result) + assertEquals(listOf("hello 2", "hello Bob"), log) + assertEquals(null, ctx.value("who")) + assertTrue(ctx.execute(listOf(CallAction("nope"))) is ActionResult.Failed) + } + + @Test + fun `a module name wins over a library one and conflicts follow the policy`() { + shared.defineRequirement("vip", Requirement { Verdict.Unmet("library") }, "lib", DefinitionConflict.FAIL) + own.defineRequirement("vip", Requirement { Verdict.Met }, "shop", DefinitionConflict.FAIL) + + assertTrue(RefRequirement("vip").test(context()).isMet) + assertThrows(IllegalArgumentException::class.java) { + own.defineRequirement("vip", Requirement { Verdict.Met }, "shop", DefinitionConflict.FAIL) + } + own.defineRequirement("vip", Requirement { Verdict.Unmet("kept?") }, "shop", DefinitionConflict.KEEP) + assertTrue(RefRequirement("vip").test(context()).isMet) + own.defineRequirement("vip", Requirement { Verdict.Unmet("replaced") }, "shop", DefinitionConflict.REPLACE) + assertEquals(Verdict.Unmet("replaced"), RefRequirement("vip").test(context())) + assertThrows(IllegalArgumentException::class.java) { + own.defineRequirement("vip", Requirement { Verdict.Met }, "other-plugin", DefinitionConflict.REPLACE) + } + assertEquals(Verdict.Unmet("requirement 'zzz' is not defined"), RefRequirement("zzz").test(context())) + } + + @Test + fun `an error handler is chosen by the failure code`() { + val failing = Action { ActionResult.Failed("currency.insufficient-funds", "poor") } + fun say(text: String) = Action { c -> log += c.format(text); ActionResult.Done } + val attempt = AttemptAction( + steps = listOf(failing), + handlers = listOf( + ErrorHandler(listOf("shop.closed"), listOf(say("closed"))), + ErrorHandler(listOf("currency.*"), listOf(say("money: {error_code}"))), + ), + fail = listOf(say("other")), + ) + + context().execute(listOf(attempt)) + context().execute(listOf(AttemptAction(listOf(Action { ActionResult.Failed("x.y", "boom") }), attempt.handlers, attempt.fail))) + + assertEquals(listOf("money: currency.insufficient-funds", "other"), log) + } + + @Test + fun `random picks by weight`() { + val ctx = context() + val rare = RandomOption(0.0001, listOf(Action { log += "rare"; ActionResult.Done })) + val common = RandomOption(1e9, listOf(Action { log += "common"; ActionResult.Done })) + val only = RandomAction(listOf(rare, common)) + + repeat(20) { ctx.execute(listOf(only)) } + + assertTrue(log.count { it == "common" } >= 19) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ScenarioTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ScenarioTest.kt new file mode 100644 index 000000000..c5c8be7cc --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/actions/ScenarioTest.kt @@ -0,0 +1,189 @@ +package org.pnfolder.pnlibrary.core.actions + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.mockito.ArgumentMatchers.anyString +import org.mockito.Mockito.mock +import org.mockito.Mockito.`when` +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.currency.ChargeAction +import org.pnfolder.pnlibrary.api.currency.Currency +import org.pnfolder.pnlibrary.api.currency.CurrencyRejectReason +import org.pnfolder.pnlibrary.api.currency.CurrencyResult +import org.pnfolder.pnlibrary.api.currency.CurrencyService +import org.pnfolder.pnlibrary.api.logging.PnLogger +import org.pnfolder.pnlibrary.api.scenario.actions.Action +import org.pnfolder.pnlibrary.api.scenario.actions.ActionContext +import org.pnfolder.pnlibrary.api.scenario.actions.ActionResult +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.AttemptAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.IfAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.RequireAction +import org.pnfolder.pnlibrary.api.scenario.actions.builtin.StopAction +import org.pnfolder.pnlibrary.api.scenario.requirements.Requirement +import org.pnfolder.pnlibrary.api.scenario.requirements.Verdict +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.AllRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.AnyRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.CompareOperator +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.CompareRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.NotRequirement +import org.pnfolder.pnlibrary.api.scenario.requirements.builtin.PermissionRequirement +import org.pnfolder.pnlibrary.api.tasks.TaskScope +import org.pnfolder.pnlibrary.api.text.ComponentService +import java.math.BigDecimal +import java.util.UUID +import java.util.concurrent.CompletableFuture + +/** Scenarios: order, quiet stops, failures with undo, money and requirements. */ +class ScenarioTest { + private val id = UUID.randomUUID() + private val player = mock(LibraryPlayer::class.java).also { + `when`(it.uniqueId).thenReturn(id) + `when`(it.name).thenReturn("Alice") + } + private val money = mock(Currency::class.java).also { + `when`(it.format(BigDecimal(100))).thenReturn("100 coins") + } + private val log = mutableListOf() + + private fun context(permissions: Set = emptySet()): ActionContext { + `when`(player.hasPermission(anyString())).thenAnswer { it.getArgument(0) in permissions } + val currencies = mock(CurrencyService::class.java) + `when`(currencies.get("money")).thenReturn(money) + return ActionContext( + player = player, + allPlayers = player, + components = mock(ComponentService::class.java), + logger = mock(PnLogger::class.java), + tasks = mock(TaskScope::class.java), + services = mapOf(CurrencyService::class.java to currencies), + ) + } + + private fun step(name: String, result: ActionResult = ActionResult.Done) = Action { log += name; result } + + private fun pays() { + `when`(money.withdraw(id, BigDecimal(100))).thenReturn(CompletableFuture.completedFuture(CurrencyResult.success())) + `when`(money.deposit(id, BigDecimal(100))).thenAnswer { + log += "refund" + CompletableFuture.completedFuture(CurrencyResult.success()) + } + } + + @Test + fun `steps run in order and a stop ends the list quietly`() { + val result = context().execute(listOf(step("a"), StopAction("enough"), step("b"))) + + assertEquals(ActionResult.Stopped("enough"), result) + assertEquals(listOf("a"), log) + } + + @Test + fun `a failure undoes earlier steps in reverse order and ends the list`() { + val registering = { name: String -> + Action { c -> c.onUndo(name) { log += "undo $name" }; ActionResult.Done } + } + + val result = context().execute( + listOf(registering("one"), registering("two"), step("boom", ActionResult.Failed("x", "broken")), step("after")), + ) + + assertEquals(ActionResult.Failed("x", "broken"), result) + assertEquals(listOf("boom", "undo two", "undo one"), log) + } + + @Test + fun `a thrown exception becomes a failure`() { + val result = context().execute(listOf(Action { error("oops") })) + + assertTrue(result is ActionResult.Failed && result.code == "action.error" && result.message == "oops") + } + + @Test + fun `an unmet requirement runs deny with the reason and stops`() { + val deny = Action { c -> log += c.format("no: {reason}"); ActionResult.Done } + + val result = context().execute(listOf(RequireAction(PermissionRequirement("shop.use"), listOf(deny)), step("after"))) + + assertTrue(result is ActionResult.Stopped) + assertEquals(listOf("no: missing permission shop.use"), log) + } + + @Test + fun `if chooses a branch and the list goes on`() { + val action = IfAction(PermissionRequirement("vip"), listOf(step("vip")), listOf(step("normal"))) + + context(setOf("vip")).execute(listOf(action, step("end"))) + context().execute(listOf(action, step("end"))) + + assertEquals(listOf("vip", "end", "normal", "end"), log) + } + + @Test + fun `a charge that cannot be paid fails with a code and attempt shows the error`() { + `when`(money.withdraw(id, BigDecimal(100))).thenReturn( + CompletableFuture.completedFuture(CurrencyResult.rejected(CurrencyRejectReason.INSUFFICIENT_FUNDS)), + ) + val attempt = AttemptAction( + steps = listOf(ChargeAction("money", "100"), step("give")), + fail = listOf(Action { c -> log += c.format("{error_code}"); ActionResult.Done }), + ) + + val result = context().execute(listOf(attempt, step("after"))) + + assertTrue(result is ActionResult.Stopped) + assertEquals(listOf("currency.insufficient-funds"), log) + } + + @Test + fun `a charge is given back when a later step fails`() { + pays() + val attempt = AttemptAction( + steps = listOf(ChargeAction("money", "100"), step("give", ActionResult.Failed("give", "no room"))), + fail = listOf(step("shown")), + ) + + context().execute(listOf(attempt)) + + assertEquals(listOf("give", "refund", "shown"), log) + } + + @Test + fun `a charge without attempt is given back and the failure reaches the caller`() { + pays() + + val result = context().execute(listOf(ChargeAction("money", "100"), step("give", ActionResult.Failed("give", "no room")))) + + assertTrue(result is ActionResult.Failed) + assertEquals(listOf("give", "refund"), log) + } + + @Test + fun `requirements compare values from any source and combine`() { + val ctx = context(setOf("a")).setValue("balance", "250") + val enough = CompareRequirement("{balance}", CompareOperator.GREATER_OR_EQUAL, "100") + val rich = CompareRequirement("{balance}", CompareOperator.GREATER, "1000") + + assertTrue(enough.test(ctx).isMet) + assertEquals(Verdict.Unmet("250 is not greater 1000"), rich.test(ctx)) + assertTrue(AllRequirement(listOf(enough, PermissionRequirement("a"))).test(ctx).isMet) + assertTrue(AnyRequirement(listOf(rich, enough)).test(ctx).isMet) + assertTrue(NotRequirement(rich).test(ctx).isMet) + assertEquals("'x' is not a number", (CompareRequirement("x", CompareOperator.LESS, "1").test(ctx) as Verdict.Unmet).reason) + assertTrue(Requirement { Verdict.Met }.test(ctx).isMet) + } + + @Test + fun `undo false keeps what the block did`() { + pays() + val attempt = AttemptAction( + steps = listOf(ChargeAction("money", "100"), step("give", ActionResult.Failed("give", "no room"))), + fail = listOf(step("shown")), + undo = false, + ) + + context().execute(listOf(attempt)) + + assertEquals(listOf("give", "shown"), log) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/configs/ConfigsCommandTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/configs/ConfigsCommandTest.kt new file mode 100644 index 000000000..a3e8e09e7 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/configs/ConfigsCommandTest.kt @@ -0,0 +1,170 @@ +package org.pnfolder.pnlibrary.core.commands.configs + +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.mockito.Mockito.mock +import org.mockito.Mockito.`when` +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.CommandSender +import org.pnfolder.pnlibrary.api.config.ConfigApply +import org.pnfolder.pnlibrary.api.config.ConfigEditable +import org.pnfolder.pnlibrary.api.config.ConfigPolymorphic +import org.pnfolder.pnlibrary.api.config.ConfigType +import org.pnfolder.pnlibrary.api.config.ConfigTypes +import org.pnfolder.pnlibrary.api.config.type +import org.pnfolder.pnlibrary.api.config.yaml +import org.pnfolder.pnlibrary.api.plugin.ModuleId +import org.pnfolder.pnlibrary.api.plugin.PluginId +import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.config.ConfigurationServiceImpl +import org.pnfolder.pnlibrary.core.commands.engine.CommandRoute +import org.pnfolder.pnlibrary.core.commands.engine.CommandTreeRouter +import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership +import java.nio.file.Files +import java.nio.file.Path +import java.util.logging.Logger + +@ConfigPolymorphic +@ConfigTypes(ConfigType(CoinPrize::class, "coin")) +interface Prize + +class CoinPrize : Prize +class GemPrize : Prize +data class PrizeFile(var prizes: List = listOf(CoinPrize())) + +class TunedFile { + @field:ConfigEditable("Приветствие", "Текст при входе.") + var greeting: String = "Привет" + + @field:ConfigEditable("Пул", "Сколько соединений.", apply = ConfigApply.RESTART) + var pool: Int = 10 +} + +class ConfigsCommandTest { + @TempDir lateinit var folder: Path + + private class Owner(val folder: Path) + + private val platform = object : PlatformOwnership { + override fun ownerDataFolder(owner: Any): Path? = (owner as? Owner)?.folder + override fun ownerLogger(owner: Any): Logger? = Logger.getLogger("configs-command-test") + } + private val service = ConfigurationServiceImpl(platform) + private val library = mock(PnLibrary::class.java).also { `when`(it.configurations).thenReturn(service) } + private val definition = ConfigsCommand(library).definition() + private val sent = mutableListOf() + private val sender = object : CommandSender { + override val id = "console" + override val name = "Console" + override val isConsole = true + override fun hasPermission(permission: String) = true + override fun send(message: Component) { + sent += PlainTextComponentSerializer.plainText().serialize(message) + } + } + + private fun scope(plugin: String) = service.scope( + Owner(folder.resolve("plugins").resolve(plugin)), PluginId.of("$plugin-main"), PluginId.of(plugin), ModuleId.of("main"), + ) + + private fun run(vararg words: String): String { + sent.clear() + val route = CommandTreeRouter().route(definition, CommandContext(sender, words.toList(), "configs", words.joinToString(" "))) + (route as CommandRoute.Executable).node.execution.execute(route.context).toCompletableFuture().join() + return sent.joinToString("\n") + } + + @Test + fun `the command lists files under their identifiers`() { + scope("quests").yaml("prizes.yml") { PrizeFile() } + + val text = run() + + assertTrue(text.contains("quests/main:prizes.yml"), text) + assertTrue(text.contains("PrizeFile"), text) + } + + @Test + fun `info shows where the file lies and never the values`() { + val config = scope("quests").yaml("prizes.yml") { PrizeFile() } + config.load() + + val text = run("info", "quests/main:prizes.yml") + + assertTrue(text.contains("prizes.yml"), text) + assertTrue(text.contains("загружен: да"), text) + assertFalse(text.contains("CoinPrize@"), "values stay out of the report") + } + + @Test + fun `an unknown or malformed identifier is answered, not thrown`() { + scope("quests").yaml("prizes.yml") { PrizeFile() } + + assertTrue(run("info", "quests/main:nope.yml").contains("Такого файла нет")) + assertTrue(run("info", "quests").contains("Неверный адрес")) + } + + @Test + fun `reload reads the file again and reports a broken file without losing the old value`() { + val config = scope("quests").yaml("prizes.yml") { PrizeFile() } + config.load() + assertTrue(run("reload", "quests/main:prizes.yml").contains("прочитан заново")) + + Files.writeString(folder.resolve("plugins/quests/prizes.yml"), "prizes: [unclosed") + assertTrue(run("reload", "quests/main:prizes.yml").contains("не прочитан")) + assertTrue(config.isLoaded) + } + + @Test + fun `validate says when a file is not loaded and when it is fine`() { + val config = scope("quests").yaml("prizes.yml") { PrizeFile() } + assertTrue(run("validate", "quests/main:prizes.yml").contains("не загружен")) + + config.load() + assertTrue(run("validate", "quests/main:prizes.yml").contains("проблем нет")) + } + + @Test + fun `types lists the words of a polymorphic type and who added them`() { + scope("quests").yaml("prizes.yml") { PrizeFile() } + scope("questgems").type().name("gem").into("quests").register() + + val text = run("types", "Prize") + + assertTrue(text.contains("coin"), text) + assertTrue(text.contains("gem"), text) + assertTrue(text.contains("questgems"), text) + assertEquals(1, text.lines().count { it.contains("объявлен в самом типе") }) + assertTrue(run("types", "Nothing").contains("Такого типа нет")) + } + + @Test + fun `settings lists editable fields and edit changes one and saves the file`() { + val config = scope("quests").yaml("tuned.yml") { TunedFile() } + config.load() + + val listing = run("settings", "quests/main:tuned.yml") + assertTrue(listing.contains("greeting = Привет"), listing) + assertTrue(listing.contains("нужен перезапуск"), listing) + + val done = run("edit", "quests/main:tuned.yml", "greeting", "Добро пожаловать сюда") + assertTrue(done.contains("Файл сохранён"), done) + assertEquals("Добро пожаловать сюда", config.get().greeting) + + val restart = run("edit", "quests/main:tuned.yml", "pool", "20") + assertTrue(restart.contains("перезапуск"), restart) + } + + @Test + fun `edit answers a wrong value instead of throwing`() { + scope("quests").yaml("tuned.yml") { TunedFile() }.load() + + assertTrue(run("edit", "quests/main:tuned.yml", "pool", "many").contains("Не изменено")) + assertTrue(run("edit", "quests/main:tuned.yml", "nothing", "1").contains("Такой настройки нет")) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/deps/DepsCommandTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/deps/DepsCommandTest.kt new file mode 100644 index 000000000..32c5a6de2 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/deps/DepsCommandTest.kt @@ -0,0 +1,114 @@ +package org.pnfolder.pnlibrary.core.commands.deps + +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.mockito.Mockito.mock +import org.mockito.Mockito.verify +import org.mockito.Mockito.`when` +import org.mockito.Mockito.withSettings +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.CommandSender +import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.core.commands.engine.CommandRoute +import org.pnfolder.pnlibrary.core.commands.engine.CommandTreeRouter +import org.pnfolder.pnlibrary.core.downloads.dependencies.MissingDependency +import org.pnfolder.pnlibrary.core.downloads.dependencies.MissingGroup +import org.pnfolder.pnlibrary.core.downloads.fetch.DirectDownloads +import org.pnfolder.pnlibrary.core.lifecycle.RuntimeResources +import java.net.URI + +class DepsCommandTest { + private val downloads = mock(DirectDownloads::class.java) + private val library = mock(PnLibrary::class.java, withSettings().extraInterfaces(RuntimeResources::class.java)) + private val sent = mutableListOf() + private val sender = object : CommandSender { + override val id = "console" + override val name = "Console" + override val isConsole = true + override fun hasPermission(permission: String) = true + override fun send(message: Component) { + sent += PlainTextComponentSerializer.plainText().serialize(message) + } + } + private val definition = DepsCommand(library).definition() + + init { + `when`((library as RuntimeResources).dependencyDownloads()).thenReturn(downloads) + `when`(downloads.automatic()).thenReturn(false) + } + + private fun run(vararg words: String): String { + sent.clear() + val route = CommandTreeRouter().route(definition, CommandContext(sender, words.toList(), "deps", words.joinToString(" "))) + (route as CommandRoute.Executable).node.execution.execute(route.context).toCompletableFuture().join() + return sent.joinToString("\n") + } + + private fun group(registered: Boolean) = MissingGroup( + "Shop", "a1b2c3", + listOf( + MissingDependency( + "Vault", "1.7.0", URI("https://example.org/vault"), listOf(URI("https://example.org/Vault.jar")), + title = "Экономика", description = "Нужна для денег.", required = true, + ), + MissingDependency("Optional", "2.0.0", null, emptyList(), required = false), + ), + if (registered) mock(org.pnfolder.pnlibrary.api.downloads.DownloadRegistration::class.java) else null, + ) + + @Test + fun `nothing missing is said plainly`() { + `when`(downloads.missingGroups()).thenReturn(emptyList()) + + val text = run() + + assertTrue(text.contains("выключена"), text) + assertTrue(text.contains("Всё нужное установлено"), text) + } + + @Test + fun `a missing group shows title, why, required or not, links and the install command`() { + `when`(downloads.missingGroups()).thenReturn(listOf(group(registered = true))) + + val text = run() + + assertTrue(text.contains("Shop просит"), text) + assertTrue(text.contains("Экономика (Vault) 1.7.0+ | обязательный"), text) + assertTrue(text.contains("Нужна для денег."), text) + assertTrue(text.contains("https://example.org/Vault.jar"), text) + assertTrue(text.contains("Optional 2.0.0+ | необязательный"), text) + assertTrue(text.contains("/pn deps install a1b2c3"), text) + } + + @Test + fun `a group without a direct link tells to download by hand`() { + `when`(downloads.missingGroups()).thenReturn(listOf(group(registered = false))) + + assertTrue(run().contains("Скачайте по ссылкам")) + } + + @Test + fun `auto on and off save the choice`() { + run("auto", "on") + run("auto", "off") + + verify(downloads).setAutomatic(true) + verify(downloads).setAutomatic(false) + } + + @Test + fun `an unknown code is refused`() { + `when`(downloads.installGroup("zzz")).thenReturn(null) + + assertTrue(run("install", "zzz").contains("Такого кода нет")) + } + + @Test + fun `the command is named deps and has install and auto`() { + assertEquals("deps", definition.name) + assertTrue(definition.root.children.map { it.name }.containsAll(listOf("install", "auto"))) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandHelpersTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandHelpersTest.kt new file mode 100644 index 000000000..20376fade --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandHelpersTest.kt @@ -0,0 +1,27 @@ +package org.pnfolder.pnlibrary.core.commands.engine + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.util.concurrent.CompletableFuture + +class CommandHelpersTest { + @Test + fun `page count rounds up and is never below one`() { + assertEquals(1, pageCount(0, 10)) + assertEquals(1, pageCount(10, 10)) + assertEquals(2, pageCount(11, 10)) + } + + @Test + fun `ready suggestions are returned`() { + assertEquals(listOf("a"), CompletableFuture.completedFuture(listOf("a")).suggestionsWithin(50)) + } + + @Test + fun `late or failed suggestions give an empty list`() { + assertTrue(CompletableFuture>().suggestionsWithin(10).isEmpty()) + val failed = CompletableFuture>().also { it.completeExceptionally(IllegalStateException("x")) } + assertTrue(failed.suggestionsWithin(10).isEmpty()) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/CommandRegistryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandRegistryTest.kt similarity index 96% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/CommandRegistryTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandRegistryTest.kt index 5a869aa01..4ba1d3f12 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/CommandRegistryTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandRegistryTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.commands +package org.pnfolder.pnlibrary.core.commands.engine import net.kyori.adventure.text.Component import org.junit.jupiter.api.Assertions.assertEquals @@ -7,18 +7,18 @@ import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.commands.ArgumentType -import org.pnfolder.pnlibrary.api.commands.BadUsage import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.CommandError -import org.pnfolder.pnlibrary.api.commands.CommandErrorHandler import org.pnfolder.pnlibrary.api.commands.CommandSender -import org.pnfolder.pnlibrary.api.commands.InvalidArgument -import org.pnfolder.pnlibrary.api.commands.NoPermission -import org.pnfolder.pnlibrary.api.commands.command -import org.pnfolder.pnlibrary.api.commands.ensure -import org.pnfolder.pnlibrary.api.commands.fail +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command +import org.pnfolder.pnlibrary.api.commands.error.BadUsage +import org.pnfolder.pnlibrary.api.commands.error.CommandError +import org.pnfolder.pnlibrary.api.commands.error.CommandErrorHandler +import org.pnfolder.pnlibrary.api.commands.error.InvalidArgument +import org.pnfolder.pnlibrary.api.commands.error.NoPermission +import org.pnfolder.pnlibrary.api.commands.error.ensure +import org.pnfolder.pnlibrary.api.commands.error.fail import org.pnfolder.pnlibrary.api.logging.LogLevel import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.spi.commands.PlatformCommandAdapter @@ -120,7 +120,7 @@ class CommandRegistryTest { ).toCompletableFuture().join() assertEquals("builders", selected) - assertEquals(listOf("Команда не выполнилась."), sender.messages.map(::textOf)) + assertEquals(listOf("Не удалось выполнить команду."), sender.messages.map(::textOf)) assertTrue(platform.errors.any { it.message == "private predicate" }) } @@ -228,7 +228,7 @@ class CommandRegistryTest { val suggestions = native.dispatcher .suggest(native.command, context(sender)).toCompletableFuture().join() - assertEquals(listOf("Команда не выполнилась."), sender.messages.map(::textOf)) + assertEquals(listOf("Не удалось выполнить команду."), sender.messages.map(::textOf)) assertTrue(suggestions.isEmpty()) assertEquals(2, platform.errors.size) assertTrue(platform.errors.any { it.message == "private detail" }) diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/CommandTreeRouterTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandTreeRouterTest.kt similarity index 93% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/CommandTreeRouterTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandTreeRouterTest.kt index 593aa1c13..1c7213d4c 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/CommandTreeRouterTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/engine/CommandTreeRouterTest.kt @@ -1,14 +1,14 @@ -package org.pnfolder.pnlibrary.core.commands +package org.pnfolder.pnlibrary.core.commands.engine import net.kyori.adventure.text.Component import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.commands.ArgumentType import org.pnfolder.pnlibrary.api.commands.CommandContext import org.pnfolder.pnlibrary.api.commands.CommandSender -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.command class CommandTreeRouterTest { @Test @@ -55,11 +55,12 @@ class CommandTreeRouterTest { assertEquals(listOf("public"), deniedSuggestions) assertEquals(listOf("public", "secret"), allowedSuggestions) - val deniedUsage = (router.route(definition, context(listOf("builders"))) as CommandRoute.Problem).error as org.pnfolder.pnlibrary.api.commands.BadUsage + val problem = router.route(definition, context(listOf("builders"))) as CommandRoute.Problem + val deniedUsage = problem.error as org.pnfolder.pnlibrary.api.commands.error.BadUsage assertEquals("/group public", deniedUsage.usage) assertTrue( (router.route(definition, context(listOf("builders", "secret", "delete"))) as CommandRoute.Problem).error - is org.pnfolder.pnlibrary.api.commands.NoPermission, + is org.pnfolder.pnlibrary.api.commands.error.NoPermission, ) assertFalse(router.suggest(definition, context(listOf("other", "secret", ""), setOf("groups.secret"))) .toCompletableFuture().join().contains("delete")) @@ -97,7 +98,7 @@ class CommandTreeRouterTest { val router = CommandTreeRouter() fun usageOf(arguments: List) = - ((router.route(definition, context(arguments)) as CommandRoute.Problem).error as org.pnfolder.pnlibrary.api.commands.BadUsage).usage + ((router.route(definition, context(arguments)) as CommandRoute.Problem).error as org.pnfolder.pnlibrary.api.commands.error.BadUsage).usage assertEquals("/amount ", usageOf(emptyList())) assertEquals("/amount ", usageOf(listOf("wrong"))) } @@ -126,7 +127,7 @@ class CommandTreeRouterTest { assertEquals(listOf(emptyList(), listOf("view", "abc")), seen) // The permission of the mounted command stays its own, and the control command's does not leak into it. val denied = router.route(control, context(listOf("events"), setOf("control.admin"))) - assertTrue((denied as CommandRoute.Problem).error is org.pnfolder.pnlibrary.api.commands.NoPermission) + assertTrue((denied as CommandRoute.Problem).error is org.pnfolder.pnlibrary.api.commands.error.NoPermission) val suggestions = router.suggest(control, context(listOf(""), setOf("events.view"))).toCompletableFuture().join() assertEquals(listOf("events"), suggestions) } @@ -190,7 +191,7 @@ class CommandTreeRouterTest { assertTrue(unknown is CommandRoute.Executable) assertEquals(listOf("whatever", "else"), (unknown as CommandRoute.Executable).context.arguments) assertEquals("reload", (known as CommandRoute.Executable).node.name) - assertTrue((refused as CommandRoute.Problem).error is org.pnfolder.pnlibrary.api.commands.UnknownArgument) + assertTrue((refused as CommandRoute.Problem).error is org.pnfolder.pnlibrary.api.commands.error.UnknownArgument) } @Test diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/TabSuggestionsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/engine/TabSuggestionsTest.kt similarity index 93% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/TabSuggestionsTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/engine/TabSuggestionsTest.kt index a874efd36..3126b7949 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/TabSuggestionsTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/engine/TabSuggestionsTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.commands +package org.pnfolder.pnlibrary.core.commands.engine import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/events/EventBusCommandTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/events/EventBusCommandTest.kt index 92339e90d..a3cdf5334 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/events/EventBusCommandTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/events/EventBusCommandTest.kt @@ -10,13 +10,13 @@ import org.mockito.Mockito.`when` import org.pnfolder.pnlibrary.api.commands.CommandContext import org.pnfolder.pnlibrary.api.commands.CommandSender import org.pnfolder.pnlibrary.api.events.Event -import org.pnfolder.pnlibrary.api.events.EventPriority +import org.pnfolder.pnlibrary.api.events.listener.EventPriority import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.core.commands.CommandRoute -import org.pnfolder.pnlibrary.core.commands.CommandTreeRouter +import org.pnfolder.pnlibrary.core.commands.engine.CommandRoute +import org.pnfolder.pnlibrary.core.commands.engine.CommandTreeRouter import org.pnfolder.pnlibrary.core.events.EventDispatcher -import org.pnfolder.pnlibrary.core.events.EventHistory +import org.pnfolder.pnlibrary.core.events.inspect.history.EventHistory import java.util.function.Consumer class EventBusCommandTest { diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/groups/GroupsCommandTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/groups/GroupsCommandTest.kt new file mode 100644 index 000000000..09845a9ea --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/groups/GroupsCommandTest.kt @@ -0,0 +1,103 @@ +package org.pnfolder.pnlibrary.core.commands.groups + +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.CommandSender +import org.pnfolder.pnlibrary.core.commands.engine.CommandRoute +import org.pnfolder.pnlibrary.core.commands.engine.CommandTreeRouter +import org.pnfolder.pnlibrary.core.link.Link +import java.nio.file.Path + +class GroupsCommandTest { + @TempDir lateinit var directory: Path + + private val link by lazy { Link(null, directory) } + private val definition by lazy { GroupsCommand(link) { emptyList() }.definition() } + private val sent = mutableListOf() + private val sender = object : CommandSender { + override val id = "console" + override val name = "Console" + override val isConsole = true + override fun hasPermission(permission: String) = true + override fun send(message: Component) { + sent += PlainTextComponentSerializer.plainText().serialize(message) + } + } + + private fun run(vararg words: String): String { + sent.clear() + val route = CommandTreeRouter().route(definition, CommandContext(sender, words.toList(), "groups", words.joinToString(" "))) + (route as CommandRoute.Executable).node.execution.execute(route.context).toCompletableFuture().join() + return sent.joinToString("\n") + } + + @Test + fun `a group is created once and a bad name is refused`() { + assertTrue(run("create", "grief").contains("создана")) + assertTrue(run("create", "grief").contains("уже есть")) + assertTrue(run("create", "x".repeat(40)).contains("Не подходит имя")) + assertNotNull(link.groups().get("GRIEF")) + } + + @Test + fun `join, require and a per-server difference are saved in the group`() { + run("create", "grief") + + run("join", "grief", "grief-1") + run("require", "grief", "Shop") + run("skip", "grief", "grief-1", "Shop") + run("extra", "grief", "grief-1", "Quests") + val group = link.groups().get("grief")!! + + assertEquals(setOf("grief-1"), group.servers) + assertEquals(setOf("Shop"), group.plugins) + assertEquals(setOf("Quests"), group.wanted("grief-1")) + assertTrue(group.customized("grief-1")) + } + + @Test + fun `reset returns a server to what the rest have and leave takes it out`() { + run("create", "grief") + run("join", "grief", "grief-1") + run("require", "grief", "Shop") + run("skip", "grief", "grief-1", "Shop") + + run("reset", "grief", "grief-1") + assertEquals(setOf("Shop"), link.groups().get("grief")!!.wanted("grief-1")) + + run("leave", "grief", "grief-1") + assertTrue(link.groups().get("grief")!!.servers.isEmpty()) + } + + @Test + fun `drop removes a plugin from the group`() { + run("create", "grief") + run("require", "grief", "Shop") + + run("drop", "grief", "shop") + + assertTrue(link.groups().get("grief")!!.plugins.isEmpty()) + } + + @Test + fun `delete removes the group and an unknown group is reported`() { + run("create", "grief") + + assertTrue(run("delete", "grief").contains("удалена")) + assertNull(link.groups().get("grief")) + assertTrue(run("delete", "grief").contains("Нет группы")) + assertTrue(run("join", "ghost", "s1").contains("Нет группы")) + } + + @Test + fun `info on an unknown group does not crash`() { + assertTrue(run("info", "ghost").isNotBlank()) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/modules/DiskUsageTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/modules/DiskUsageTest.kt new file mode 100644 index 000000000..adf0860ad --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/modules/DiskUsageTest.kt @@ -0,0 +1,66 @@ +package org.pnfolder.pnlibrary.core.commands.modules + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Files +import java.nio.file.Path + +class DiskUsageTest { + @TempDir + lateinit var plugins: Path + + private fun write(relative: String, size: Int) { + val file = plugins.resolve(relative) + Files.createDirectories(file.parent) + Files.write(file, ByteArray(size)) + } + + @Test + fun `splits a plugin folder by kind and adds the jar to the same plugin`() { + write("Shop-1.2.3.jar", 1000) + write("Shop/config.yml", 10) + write("Shop/players.db", 200) + write("Shop/logs/latest.log", 30) + write("Shop/lib/hikari.jar", 400) + val report = DiskUsage.scan(plugins, emptyList()) + val row = report.rows.single() + assertEquals("Shop", row.name) + assertEquals(DiskRow("Shop", 1000, 10, 400, 30, 200), row) + assertEquals(1640L, row.total) + } + + @Test + fun `a jar without a folder is a plugin of its own and the biggest comes first`() { + write("Small-1.0.jar", 5) + write("Big/data.bin", 500) + val report = DiskUsage.scan(plugins, emptyList()) + assertEquals(listOf("Big", "Small"), report.rows.map { it.name }) + assertEquals(505L, report.total) + } + + @Test + fun `registered libraries count once even when listed twice, missing files count zero`() { + write("lib.jar", 70) + val file = plugins.resolve("lib.jar").toString() + val report = DiskUsage.scan(plugins, listOf(file, file, plugins.resolve("none.jar").toString())) + assertEquals(70L, report.registeredLibraries) + } + + @Test + fun `a missing plugins folder gives an empty report`() { + val report = DiskUsage.scan(plugins.resolve("nowhere"), emptyList()) + assertTrue(report.rows.isEmpty()) + assertEquals(-1L, report.free) + } + + @Test + fun `sizes read the same in the command and the menu`() { + assertEquals("12 Б", DiskUsage.format(12)) + assertEquals("320 КБ", DiskUsage.format(320 * 1024L)) + assertEquals("1.5 МБ", DiskUsage.format(1_572_864)) + assertEquals("2.00 ГБ", DiskUsage.format(2L * 1024 * 1024 * 1024)) + assertEquals("неизвестно", DiskUsage.format(-1)) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/modules/LibraryRowTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/modules/LibraryRowTest.kt new file mode 100644 index 000000000..6a008cfae --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/modules/LibraryRowTest.kt @@ -0,0 +1,40 @@ +package org.pnfolder.pnlibrary.core.commands.modules + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class LibraryRowTest { + private fun row(owner: String) = LibraryRow(owner, "Hikari", "g:a:1", "1", null, emptyList(), true, true, false, false) + + @Test + fun `a plugin owns its own libraries and those of its modules but not another plugin's`() { + assertTrue(row("shop").belongsTo("shop")) + assertTrue(row("shop:cart").belongsTo("shop")) + assertTrue(row("shop:cart").belongsTo("shop:cart")) + assertFalse(row("shop:cart").belongsTo("shop:other")) + assertFalse(row("shopping").belongsTo("shop")) + } + + @Test + fun `whose library it is is told in words and split into plugin and module`() { + assertEquals("плагину shop", row("shop").ownerText) + assertEquals("модулю cart плагина shop", row("shop:cart").ownerText) + assertEquals("shop", row("shop:cart").plugin) + assertEquals("cart", row("shop:cart").module) + assertNull(row("shop").module) + } + + @Test + fun `the place is counted from the server folder and split into folder and file`() { + val root = java.nio.file.Paths.get("srv") + val place = LibraryRow.placeOf(root.resolve("plugins/pnLibrary/libs/a/b-1.jar").toString(), root) + assertEquals("plugins/pnLibrary/libs/a/b-1.jar", place) + val row = row("shop").copy(place = place) + assertEquals("plugins/pnLibrary/libs/a", row.folder) + assertEquals("b-1.jar", row.fileName) + assertNull(row("shop").folder) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/modules/ModulesCommandTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/modules/ModulesCommandTest.kt new file mode 100644 index 000000000..c1ceacf53 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/modules/ModulesCommandTest.kt @@ -0,0 +1,111 @@ +package org.pnfolder.pnlibrary.core.commands.modules + +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.mockito.Mockito.mock +import org.mockito.Mockito.`when` +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.CommandSender +import org.pnfolder.pnlibrary.api.plugin.ModuleContext +import org.pnfolder.pnlibrary.api.plugin.control.ModuleState +import org.pnfolder.pnlibrary.api.plugin.control.PluginModule +import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.core.commands.engine.CommandRoute +import org.pnfolder.pnlibrary.core.commands.engine.CommandTreeRouter +import org.pnfolder.pnlibrary.core.plugin.PluginRegistryImplTest + +class ModulesCommandTest { + private class Switchable : PluginModule { + override fun onEnable(context: ModuleContext) {} + override fun onDisable(context: ModuleContext) {} + } + + private val registry = PluginRegistryImplTest.registry() + private val library = mock(PnLibrary::class.java).also { `when`(it.plugins).thenReturn(registry) } + private val sent = mutableListOf() + private val sender = object : CommandSender { + override val id = "console" + override val name = "Console" + override val isConsole = true + override fun hasPermission(permission: String) = true + override fun send(message: Component) { + sent += PlainTextComponentSerializer.plainText().serialize(message) + } + } + private val definition = ModulesCommand(library).definition() + + private fun run(vararg words: String): String { + sent.clear() + val route = CommandTreeRouter().route(definition, CommandContext(sender, words.toList(), "modules", words.joinToString(" "))) + (route as CommandRoute.Executable).node.execution.execute(route.context).toCompletableFuture().join() + return sent.joinToString("\n") + } + + @Test + fun `an empty server says there are no modules`() { + assertTrue(run().contains("Модулей пока нет")) + registry.close() + } + + @Test + fun `the list shows every module with its state and a module without hooks is marked`() { + val plugin = registry.register(Any()) + val shop = plugin.registerModule("shop", Switchable()) + plugin.registerModule("plain") + + val text = run() + + assertTrue(text.contains(":shop"), text) + assertTrue(text.contains("работает"), text) + assertTrue(text.contains("без переключателя"), text) + assertEquals(ModuleState.ENABLED, shop.control.state) + registry.close() + } + + @Test + fun `disable and enable switch the module and view shows the state`() { + val module = registry.register(Any()).registerModule("shop", Switchable()) + val name = ModuleLabels.named(library).single().first + + run("disable", name) + assertEquals(ModuleState.DISABLED, module.control.state) + assertTrue(run("view", name).contains("выключен")) + + run("enable", name) + assertEquals(ModuleState.ENABLED, module.control.state) + registry.close() + } + + @Test + fun `an unknown module is refused with a pointer to the list`() { + val text = run("view", "nothing:here") + + assertTrue(text.contains("Такого модуля нет"), text) + registry.close() + } + + @Test + fun `auto off keeps the module from starting with the server`() { + val module = registry.register(Any()).registerModule("shop", Switchable()) + val name = ModuleLabels.named(library).single().first + + run("auto", name, "off") + + assertEquals(false, module.control.autoStart) + assertTrue(run().contains("не включается сам")) + registry.close() + } + + @Test + fun `plugins lists each plugin with its modules`() { + registry.register(Any()).registerModule("shop", Switchable()) + + val text = run("plugins") + + assertTrue(text.contains("модулей 1"), text) + registry.close() + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ProxyControlCommandTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ProxyControlCommandTest.kt index d0285384c..38bdcfb09 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ProxyControlCommandTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ProxyControlCommandTest.kt @@ -6,11 +6,11 @@ import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.mockito.Mockito.mock import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandNodeKind import org.pnfolder.pnlibrary.api.commands.CommandSender +import org.pnfolder.pnlibrary.api.commands.definition.CommandNodeKind import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.core.commands.CommandRoute -import org.pnfolder.pnlibrary.core.commands.CommandTreeRouter +import org.pnfolder.pnlibrary.core.commands.engine.CommandRoute +import org.pnfolder.pnlibrary.core.commands.engine.CommandTreeRouter import org.pnfolder.pnlibrary.core.link.Link class ProxyControlCommandTest { diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ServersCommandTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ServersCommandTest.kt new file mode 100644 index 000000000..03e24f2c3 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/proxy/ServersCommandTest.kt @@ -0,0 +1,89 @@ +package org.pnfolder.pnlibrary.core.commands.proxy + +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.CommandSender +import org.pnfolder.pnlibrary.core.commands.engine.CommandRoute +import org.pnfolder.pnlibrary.core.commands.engine.CommandTreeRouter +import org.pnfolder.pnlibrary.core.link.Link +import org.pnfolder.pnlibrary.core.link.report.LinkPlugin +import org.pnfolder.pnlibrary.core.link.report.LinkReport +import org.pnfolder.pnlibrary.core.link.report.NetworkServer +import java.time.Instant + +class ServersCommandTest { + private fun report(players: Int, vararg plugins: LinkPlugin) = LinkReport("Paper 1.21", "0.1.0", players, plugins.toList(), Instant.now()) + + private val servers = listOf( + NetworkServer("lobby", true, report(3, LinkPlugin("shop", "1.0", "1.1", "UPDATE_AVAILABLE"))), + NetworkServer("games", false, report(0)), + ) + private val sent = mutableListOf() + private val sender = object : CommandSender { + override val id = "console" + override val name = "Console" + override val isConsole = true + override fun hasPermission(permission: String) = true + override fun send(message: Component) { + sent += PlainTextComponentSerializer.plainText().serialize(message) + } + } + + private fun run(shown: List, link: Link = Link.OFF, vararg words: String): String { + sent.clear() + val definition = ServersCommand(link) { shown }.definition() + val route = CommandTreeRouter().route(definition, CommandContext(sender, words.toList(), "servers", words.joinToString(" "))) + (route as CommandRoute.Executable).node.execution.execute(route.context).toCompletableFuture().join() + return sent.joinToString("\n") + } + + @Test + fun `the list shows each server with its state, players and the number of updates`() { + val text = run(servers) + + assertTrue(text.contains("lobby"), text) + assertTrue(text.contains("на связи"), text) + assertTrue(text.contains("games"), text) + assertTrue(text.contains("нет связи"), text) + assertTrue(text.contains("3 игрока"), text) + assertTrue(text.contains("обновлений: 1"), text) + } + + @Test + fun `an empty list explains what to do about the key`() { + assertTrue(run(emptyList()).contains("link.key")) + } + + @Test + fun `one server shows its plugins with versions and the update state`() { + val text = run(servers, Link.OFF, "lobby") + + assertTrue(text.contains("shop"), text) + assertTrue(text.contains("v1.0 >> v1.1"), text) + } + + @Test + fun `the name is matched without regard to case and an unknown server is refused`() { + assertTrue(run(servers, Link.OFF, "LOBBY").contains("pnLibrary")) + assertTrue(run(servers, Link.OFF, "ghost").contains("не присылал отчёт")) + } + + @Test + fun `a request without a link key says why it was not sent`() { + val text = run(servers, Link.OFF, "lobby", "check") + + assertTrue(text.contains("нет файла link.key"), text) + } + + @Test + fun `the permission is the same for the list and its words`() { + val definition = ServersCommand(Link.OFF) { servers }.definition() + + assertEquals("servers", definition.name) + assertTrue(definition.root.children.single().children.map { it.name }.containsAll(listOf("check", "update", "auto"))) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/settings/SettingsCommandTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/settings/SettingsCommandTest.kt new file mode 100644 index 000000000..de8004ba3 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/settings/SettingsCommandTest.kt @@ -0,0 +1,184 @@ +package org.pnfolder.pnlibrary.core.commands.settings + +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.commands.CommandContext +import org.pnfolder.pnlibrary.api.commands.CommandSender +import org.pnfolder.pnlibrary.core.commands.engine.CommandRoute +import org.pnfolder.pnlibrary.core.commands.engine.CommandTreeRouter +import org.pnfolder.pnlibrary.core.settings.SettingPickerHook +import org.pnfolder.pnlibrary.core.settings.SettingsStore +import java.nio.file.Path + +class SettingsCommandTest { + @TempDir lateinit var directory: Path + + private val store by lazy { SettingsStore(directory.resolve("data/settings.json")) } + private val hook = SettingPickerHook() + private val definition by lazy { SettingsCommand(store, hook).definition() } + private var console = true + private val sent = mutableListOf() + private val sender = object : CommandSender { + override val id = "console" + override val name = "Console" + override val isConsole get() = console + override fun hasPermission(permission: String) = true + override fun send(message: Component) { + sent += PlainTextComponentSerializer.plainText().serialize(message) + } + } + + private fun run(vararg words: String): String { + sent.clear() + val route = CommandTreeRouter().route(definition, CommandContext(sender, words.toList(), "settings", words.joinToString(" "))) + (route as CommandRoute.Executable).node.execution.execute(route.context).toCompletableFuture().join() + return sent.joinToString("\n") + } + + @Test + fun `the list shows every setting with its value and marks the changed ones`() { + store.set("privacy", "true") + + val first = run("list") + val second = run("list", "2") + + assertTrue(first.contains("privacy = включено (по умолчанию выключено)"), first) + assertTrue(first.contains("history-retention-days = 30"), first) + assertTrue(second.contains("страница 2/2"), second) + assertTrue(second.contains("updates.read-timeout = 30с"), second) + assertEquals(first, run(), "the bare command is the list") + } + + @Test + fun `get shows value default limits and when a change works`() { + val text = run("get", "history-retention-days") + + assertTrue(text.contains("значение: 30 (по умолчанию)"), text) + assertTrue(text.contains("допустимо: от 30 до 365"), text) + assertTrue(text.contains("заработает: после перезапуска"), text) + assertTrue(run("get", "downloads.enabled").contains("заработает: сразу")) + assertTrue(run("get", "nope").contains("Такой настройки нет")) + } + + @Test + fun `set saves the value and says when it starts to work`() { + val live = run("set", "downloads.automatic", "off") + val later = run("set", "history-retention-days", "90") + + assertFalse(store.current().downloadsAutomatic) + assertEquals(90, store.current().historyRetentionDays) + assertTrue(live.contains("downloads.automatic: включено → выключено. Сохранено."), live) + assertFalse(live.contains("перезапуска"), live) + assertTrue(later.contains("30 → 90"), later) + assertTrue(later.contains("после перезапуска"), later) + } + + @Test + fun `a text with spaces is taken whole`() { + run("set", "no-permission-message", "Нет", "права", "на", "это") + + assertEquals("Нет права на это", store.current().noPermissionMessage) + } + + @Test + fun `a wrong value or key is answered with the reason and nothing changes`() { + val range = run("set", "history-retention-days", "7") + val word = run("set", "privacy", "maybe") + val time = run("set", "updates.check-interval", "5m") + val key = run("set", "nope", "1") + + assertTrue(range.contains("Не изменено") && range.contains("от 30 до 365"), range) + assertTrue(word.contains("Не изменено") && word.contains("вкл или выкл"), word) + assertTrue(time.contains("Не изменено") && time.contains("вне допустимых границ"), time) + assertTrue(key.contains("Такой настройки нет"), key) + assertEquals(org.pnfolder.pnlibrary.core.settings.LibrarySettings(), store.current()) + } + + @Test + fun `reset returns a setting to its default`() { + run("set", "privacy", "true") + + val text = run("reset", "privacy") + + assertTrue(text.contains("включено → выключено"), text) + assertFalse(store.current().privacy) + assertTrue(run("reset", "nope").contains("Такой настройки нет")) + } + + private fun suggest(vararg words: String): List = + CommandTreeRouter().suggest(definition, CommandContext(sender, words.toList(), "settings", words.joinToString(" "))).toCompletableFuture().join() + + @Test + fun `keys and values are suggested`() { + val keys = suggest("set", "") + assertTrue("downloads.enabled" in keys && "privacy" in keys && "updates.check-interval" in keys, keys.toString()) + assertEquals(listOf("downloads.destinations.cache", "downloads.destinations.data-folder"), suggest("get", "downloads.dest").sorted()) + assertEquals(listOf("включено", "выключено"), suggest("set", "privacy", "").sorted()) + assertTrue("6h" in suggest("set", "updates.check-interval", "")) + run("set", "privacy", "true") + assertEquals(listOf("privacy"), suggest("reset", "")) + } + + @Test + fun `a switch is shown and understood in Russian everywhere in the command`() { + assertTrue(run("list").contains("privacy = выключено"), "the list") + val get = run("get", "privacy") + assertTrue(get.contains("значение: выключено (по умолчанию)"), get) + assertFalse(get.contains("false") || get.contains("true"), get) + listOf("вкл", "включено", "да", "on", "true").forEach { word -> + run("reset", "privacy") + run("set", "privacy", word) + assertTrue(store.current().privacy, word) + } + listOf("выкл", "выключено", "нет", "off", "false").forEach { word -> + run("set", "privacy", "включено") + run("set", "privacy", word) + assertFalse(store.current().privacy, word) + } + run("set", "privacy", "включено") + assertTrue(run("get", "privacy").contains("по умолчанию: выключено")) + } + + @Test + fun `a time zone is completed from the list of zones`() { + val zones = suggest("set", "time-zone", "") + + assertTrue("Europe/Moscow" in zones && "UTC" in zones && "America/New_York" in zones, zones.size.toString()) + assertEquals(zones.size, zones.toSet().size) + } + + @Test + fun `pick opens the list of a choice setting for a player with the words after the key as the filter`() { + console = false + val opened = mutableListOf>() + hook.opener = { _, key, filter -> opened.add(key to filter) } + + run("pick", "time-zone") + run("pick", "time-zone", "new", "york") + + assertEquals(listOf("time-zone" to "", "time-zone" to "new york"), opened) + } + + @Test + fun `pick refuses the console, a setting without a list and a platform without menus`() { + val opened = mutableListOf() + hook.opener = { _, key, _ -> opened.add(key) } + + assertTrue(run("pick", "time-zone").contains("меню игрока")) + console = false + assertTrue(run("pick", "privacy").contains("Нет настройки с выбором из списка")) + hook.opener = null + assertTrue(run("pick", "time-zone").contains("Меню здесь недоступно")) + assertTrue(opened.isEmpty()) + } + + @Test + fun `pick completes only the settings that have a list`() { + assertEquals(listOf("time-zone"), suggest("pick", "")) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskCommandTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskCommandTest.kt index 0b965cbf5..fcaddc44e 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskCommandTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskCommandTest.kt @@ -10,12 +10,12 @@ import org.mockito.Mockito.withSettings import org.pnfolder.pnlibrary.api.commands.CommandContext import org.pnfolder.pnlibrary.api.commands.CommandSender import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskId -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskStatus -import org.pnfolder.pnlibrary.core.commands.CommandRoute -import org.pnfolder.pnlibrary.core.commands.CommandTreeRouter +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.core.commands.engine.CommandRoute +import org.pnfolder.pnlibrary.core.commands.engine.CommandTreeRouter import org.pnfolder.pnlibrary.core.lifecycle.RuntimeResources import org.pnfolder.pnlibrary.core.tasks.TaskControl import java.time.Instant diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskLabelsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskLabelsTest.kt new file mode 100644 index 000000000..218b5eda7 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/commands/tasks/TaskLabelsTest.kt @@ -0,0 +1,90 @@ +package org.pnfolder.pnlibrary.core.commands.tasks + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import java.time.Duration +import java.time.Instant + +class TaskLabelsTest { + @Test + fun `a span is written in the largest fitting unit and drops empty remainders`() { + assertEquals("250 мс", TaskLabels.span(Duration.ofMillis(250))) + assertEquals("5 с", TaskLabels.span(Duration.ofSeconds(5))) + assertEquals("3 мин", TaskLabels.span(Duration.ofMinutes(3))) + assertEquals("2 ч", TaskLabels.span(Duration.ofHours(2))) + assertEquals("2 ч 30 мин", TaskLabels.span(Duration.ofMinutes(150))) + assertEquals("1 ч 10 мин", TaskLabels.span(Duration.ofMinutes(70))) + assertEquals("3 д", TaskLabels.span(Duration.ofDays(3))) + assertEquals("1 д 10 ч", TaskLabels.span(Duration.ofHours(34))) + } + + @Test + fun `ago says just now, how long ago, or how long until`() { + assertEquals("только что", TaskLabels.ago(Instant.now().minusSeconds(10))) + assertEquals("только что", TaskLabels.ago(Instant.now().plusSeconds(10))) + assertTrue(TaskLabels.ago(Instant.now().minus(Duration.ofMinutes(5))).endsWith("назад")) + assertTrue(TaskLabels.ago(Instant.now().plus(Duration.ofHours(2).plusSeconds(30))).startsWith("через")) + } + + @Test + fun `every status has its own words`() { + assertEquals(TaskStatus.values().size, TaskStatus.values().map(TaskLabels::label).toSet().size) + } + + @Test + fun `a lag is mentioned only when it is noticeable`() { + assertNull(TaskLabels.lag(task(worstLag = Duration.ofMillis(400)))) + assertTrue(TaskLabels.lag(task(worstLag = Duration.ofSeconds(3), lastLag = Duration.ofSeconds(1)))!!.contains("наибольшее 3 с")) + } + + @Test + fun `stop and run answers say why not`() { + assertEquals("да", TaskLabels.stopAnswer(task())) + assertTrue(TaskLabels.stopAnswer(task(cancellable = false)).contains("плагин запретил")) + assertTrue(TaskLabels.runAnswer(task(status = TaskStatus.RUNNING)).contains("выполняется")) + assertFalse(TaskLabels.runAnswer(task(status = TaskStatus.COMPLETED)).startsWith("да")) + } + + @Test + fun `the title falls back from name to key to a short id`() { + assertEquals("cleanup", TaskLabels.title(task(name = "cleanup"))) + assertEquals("k1", TaskLabels.title(task(name = null, key = "k1"))) + assertEquals(TaskLabels.SHORT_ID, TaskLabels.title(task(name = null, key = null)).length) + } + + @Test + fun `an older finished task falls out of today and the week but active ones always stay`() { + val old = task(status = TaskStatus.COMPLETED, created = Instant.now().minus(Duration.ofDays(30)), completed = Instant.now().minus(Duration.ofDays(30))) + val running = task(status = TaskStatus.RUNNING, created = Instant.now().minus(Duration.ofDays(30))) + + assertFalse(TaskPeriod.TODAY.keep(old)) + assertFalse(TaskPeriod.WEEK.keep(old)) + assertTrue(TaskPeriod.OLDER.keep(old)) + assertTrue(TaskPeriod.ANY.keep(old)) + assertTrue(TaskPeriod.TODAY.keep(running)) + assertFalse(TaskPeriod.OLDER.keep(running)) + } + + private fun task( + name: String? = "task", + key: String? = null, + status: TaskStatus = TaskStatus.SCHEDULED, + created: Instant = Instant.now(), + completed: Instant? = null, + cancellable: Boolean = true, + lastLag: Duration? = null, + worstLag: Duration? = null, + ) = TaskSnapshot( + id = TaskId.random(), name = name, key = key, ownerName = "pnTest", executionKind = TaskExecution.Kind.GLOBAL, + status = status, tags = emptySet(), createdAt = created, nextRunAt = null, runCount = 0, skippedCount = 0, + lastStartedAt = null, lastCompletedAt = completed, lastFailure = null, cancellable = cancellable, + lastLag = lastLag, worstLag = worstLag, + ) +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/ConfigReaderTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigReaderTest.kt similarity index 72% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/ConfigReaderTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigReaderTest.kt index 2ee17893d..15b92a564 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/ConfigReaderTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigReaderTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core +package org.pnfolder.pnlibrary.core.diagnostics import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull @@ -6,7 +6,7 @@ import org.junit.jupiter.api.Assumptions.assumeTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticConfiguration -import org.pnfolder.pnlibrary.core.diagnostics.ConfigReader +import org.pnfolder.pnlibrary.core.diagnostics.config.ConfigReader import java.nio.file.Files import java.nio.file.Path @@ -52,28 +52,6 @@ class ConfigReaderTest { assertEquals("[REDACTED VALUE]", data["licenseKey"]) } - @Test - fun `administrator path with a file prefix hides the value only in that file`() { - val plugin = Files.createDirectory(dataFolder.resolve("pnExample")) - plugin.resolve("config.yml").toFile().writeText("note: a\nother: b") - plugin.resolve("messages.yml").toFile().writeText("note: a\nother: b") - val reader = ConfigReader( - dataFolder, - org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig( - excludedPaths = listOf("pnExample/config.yml:note", "other"), - ), - ) - - fun values(file: String): Map { - @Suppress("UNCHECKED_CAST") - val data = reader.readAndRedact(DiagnosticConfiguration.builder(file).build(), plugin)["data"] as Map - return data - } - - assertEquals(mapOf("note" to "[EXCLUDED BY RULE]", "other" to "[EXCLUDED BY RULE]"), values("config.yml")) - assertEquals(mapOf("note" to "a", "other" to "[EXCLUDED BY RULE]"), values("messages.yml")) - } - @Test fun `blocks path traversal`() { val spec = DiagnosticConfiguration.builder("config.yml").build() diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigRedactionTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigRedactionTest.kt index e1bfb13bc..0d65304fd 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigRedactionTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigRedactionTest.kt @@ -2,7 +2,10 @@ package org.pnfolder.pnlibrary.core.diagnostics import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.core.diagnostics.config.ConfigRedaction +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticRedactor import java.util.regex.Pattern class ConfigRedactionTest { @@ -28,4 +31,18 @@ class ConfigRedactionTest { val result = redaction(values = listOf(Pattern.compile("leak"))).requested(mapOf("note" to "a leak here")) assertFalse(result["note"].toString().contains("leak")) } + + @Test + fun `wildcard path hides a secret inside every value of a map and every list item`() { + val data = mapOf( + "accounts" to mapOf("alice" to mapOf("pin" to "1111", "name" to "A"), "bob" to mapOf("pin" to "2222")), + "users" to listOf(mapOf("pin" to "3333", "name" to "C")), + ) + val redaction = redaction(setOf("accounts.*.pin", "users.pin")) + for (result in listOf(redaction.requested(data), redaction.redact(data))) { + val text = result.toString() + for (secret in listOf("1111", "2222", "3333")) assertFalse(text.contains(secret), text) + assertTrue(text.contains("name=A") && text.contains("name=C"), text) + } + } } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigurationDocumentCodecTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigurationDocumentCodecTest.kt index 7a6170c96..de0a0f905 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigurationDocumentCodecTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/ConfigurationDocumentCodecTest.kt @@ -5,6 +5,7 @@ import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource +import org.pnfolder.pnlibrary.core.diagnostics.config.ConfigurationDocumentCodec import java.util.stream.Stream class ConfigurationDocumentCodecTest { diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/DiagnosticCommandExecutorTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommandExecutorTest.kt similarity index 87% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/DiagnosticCommandExecutorTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommandExecutorTest.kt index a4238a006..4fa196cdc 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/DiagnosticCommandExecutorTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommandExecutorTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core +package org.pnfolder.pnlibrary.core.diagnostics import org.junit.jupiter.api.Assertions.assertInstanceOf import org.junit.jupiter.api.Assertions.assertTrue @@ -6,12 +6,13 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig -import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticCommandEvent -import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticCommandExecutor +import org.pnfolder.pnlibrary.core.diagnostics.command.DiagnosticCommandEvent +import org.pnfolder.pnlibrary.core.diagnostics.command.DiagnosticCommandExecutor import org.pnfolder.pnlibrary.core.runtime.PnLibraryLauncher import org.pnfolder.pnlibrary.core.runtime.platform.toRuntimeContext import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskAdapter +import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskBuilder import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskHandle import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest import java.nio.file.Files @@ -59,7 +60,8 @@ class DiagnosticCommandExecutorTest { override val type = PlatformType.BUKKIT override val id = "test" override val taskAdapter = object : PlatformTaskAdapter { - override fun schedule(request: PlatformTaskRequest): PlatformTaskHandle { + override fun buildTask() = PlatformTaskBuilder(::dispatch) + private fun dispatch(request: PlatformTaskRequest): PlatformTaskHandle { request.callback.run() return PlatformTaskHandle { false } } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommandTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommandTest.kt index 395e0f9d3..87044c04f 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommandTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticCommandTest.kt @@ -10,15 +10,18 @@ import org.pnfolder.pnlibrary.api.chat.ChatKit import org.pnfolder.pnlibrary.api.chat.ChatReader import org.pnfolder.pnlibrary.api.commands.CommandContext import org.pnfolder.pnlibrary.api.commands.CommandSender -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticReport +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticReport import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.plugin.ModuleContext import org.pnfolder.pnlibrary.api.plugin.ModuleId import org.pnfolder.pnlibrary.api.plugin.PluginId -import org.pnfolder.pnlibrary.api.plugin.PluginMetadata import org.pnfolder.pnlibrary.api.plugin.PluginRegistration import org.pnfolder.pnlibrary.api.plugin.PluginRegistry +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.core.diagnostics.command.DiagnosticCommandEvent +import org.pnfolder.pnlibrary.core.diagnostics.command.diagnosticCommand +import org.pnfolder.pnlibrary.core.diagnostics.command.render import java.lang.reflect.Method import java.lang.reflect.Proxy import java.nio.file.Paths diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticIncidentLogTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticIncidentLogTest.kt new file mode 100644 index 000000000..383830a62 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticIncidentLogTest.kt @@ -0,0 +1,72 @@ +package org.pnfolder.pnlibrary.core.diagnostics + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticLevel +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticValueSanitizer + +class DiagnosticIncidentLogTest { + private fun log(capacity: Int) = DiagnosticIncidentLog(capacity, DiagnosticValueSanitizer()) + + private fun DiagnosticIncidentLog.add(code: String, message: String = "m") = + record("plugin", DiagnosticLevel.WARNING, "component", code, message, null, emptyMap()) + + @Test + fun `the same incident is counted, not repeated`() { + val incidents = log(10) + + repeat(3) { incidents.add("A") } + + val snapshot = incidents.snapshot() + assertEquals(1, snapshot.size) + assertEquals(3L, snapshot.single()["occurrenceCount"]) + } + + @Test + fun `the oldest incident leaves when the log is full`() { + val incidents = log(2) + + incidents.add("A") + incidents.add("B") + incidents.add("C") + + assertEquals(listOf("B", "C"), incidents.snapshot().map { it["code"] }) + } + + @Test + fun `the timeline stops growing and the rest is counted as omitted`() { + val incidents = log(10) + + repeat(600) { incidents.add("A") } + + val incident = incidents.snapshot().single() + assertEquals(600L, incident["occurrenceCount"]) + assertEquals(500, (incident["occurrenceTimeline"] as List<*>).size) + assertEquals(100L, incident["omittedOccurrences"]) + } + + @Test + fun `a snapshot is a copy that later records do not change`() { + val incidents = log(10) + incidents.add("A") + val before = incidents.snapshot() + + incidents.add("A") + + assertEquals(1L, before.single()["occurrenceCount"]) + assertEquals(1, (before.single()["occurrenceTimeline"] as List<*>).size) + } + + @Test + fun `the summary counts incidents and occurrences`() { + val incidents = log(10) + incidents.add("A") + incidents.add("A") + incidents.add("B") + + val summary = incidents.summary() + + assertEquals(2, summary["incidentCount"]) + assertEquals(3L, summary["occurrenceCount"]) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/DiagnosticRedactorTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticRedactorTest.kt similarity index 88% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/DiagnosticRedactorTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticRedactorTest.kt index aac982967..69a88fe7d 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/DiagnosticRedactorTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticRedactorTest.kt @@ -1,9 +1,9 @@ -package org.pnfolder.pnlibrary.core +package org.pnfolder.pnlibrary.core.diagnostics import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticRedactor +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticRedactor class DiagnosticRedactorTest { diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticValueSanitizerTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticValueSanitizerTest.kt index 450bef367..ea3d605dc 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticValueSanitizerTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticValueSanitizerTest.kt @@ -3,7 +3,8 @@ package org.pnfolder.pnlibrary.core.diagnostics import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticLevel +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticLevel +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticValueSanitizer class DiagnosticValueSanitizerTest { private val sanitizer = DiagnosticValueSanitizer() diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticsRegistrationLifecycleTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticsRegistrationLifecycleTest.kt index a6162f118..5571c331e 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticsRegistrationLifecycleTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticsRegistrationLifecycleTest.kt @@ -4,8 +4,8 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticLevel import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsContributor +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticLevel class DiagnosticsRegistrationLifecycleTest { @Test @@ -47,4 +47,21 @@ class DiagnosticsRegistrationLifecycleTest { assertEquals(1L, before["occurrenceCount"]) assertEquals(1, (before["occurrenceTimeline"] as List<*>).size) } + + @Test + fun `a failing listener is reported and does not reject the event`() { + val registry = DiagnosticsRegistry() + val failures = mutableListOf() + registry.onInternalFailure = { what, _ -> failures += what } + registry.onEventsChanged { throw IllegalStateException("disk full") } + registry.onActivityEvent { _, _, _, _, _, _, _ -> throw IllegalStateException("bridge broke") } + + registry.record("demo", DiagnosticLevel.WARNING, "db", "slow", "Slow query", null, emptyMap()) + + assertEquals(1, (registry.eventSnapshot()["demo"] as List<*>).size) + assertEquals( + setOf("The diagnostic activity listener failed", "The diagnostic history callback failed"), + failures.toSet(), + ) + } } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/DiagnosticsRegistryConfigurationTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticsRegistryConfigurationTest.kt similarity index 93% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/DiagnosticsRegistryConfigurationTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticsRegistryConfigurationTest.kt index cefd635df..d052b8068 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/DiagnosticsRegistryConfigurationTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/DiagnosticsRegistryConfigurationTest.kt @@ -1,10 +1,10 @@ -package org.pnfolder.pnlibrary.core +package org.pnfolder.pnlibrary.core.diagnostics import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticContainer -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticLevel +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticContainer +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticLevel import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticsRegistry import java.nio.file.Path diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/SecureConfigurationFileReaderTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/SecureConfigReaderTest.kt similarity index 83% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/SecureConfigurationFileReaderTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/SecureConfigReaderTest.kt index 739ddef9b..d874fd80b 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/SecureConfigurationFileReaderTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/diagnostics/SecureConfigReaderTest.kt @@ -5,10 +5,11 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.core.diagnostics.config.SecureConfigReader import java.nio.file.Files import java.nio.file.Path -class SecureConfigurationFileReaderTest { +class SecureConfigReaderTest { @TempDir lateinit var temporaryDirectory: Path @@ -17,7 +18,7 @@ class SecureConfigurationFileReaderTest { val expected = "enabled: true\n".toByteArray() Files.write(temporaryDirectory.resolve("config.yml"), expected) - val result = SecureConfigurationFileReader().read(temporaryDirectory, "config.yml") + val result = SecureConfigReader().read(temporaryDirectory, "config.yml") assertArrayEquals(expected, result.content) assertNull(result.error) @@ -25,7 +26,7 @@ class SecureConfigurationFileReaderTest { @Test fun `rejects traversal and forbidden extensions`() { - val reader = SecureConfigurationFileReader() + val reader = SecureConfigReader() Files.write(temporaryDirectory.resolve("cache.db"), byteArrayOf(1)) val traversal = reader.read(temporaryDirectory, "../outside.yml") @@ -39,7 +40,7 @@ class SecureConfigurationFileReaderTest { fun `rejects files larger than the configured byte budget`() { Files.write(temporaryDirectory.resolve("large.yml"), ByteArray(5)) - val result = SecureConfigurationFileReader(maximumBytes = 4) + val result = SecureConfigReader(maximumBytes = 4) .read(temporaryDirectory, "large.yml") assertEquals("[file exceeds size limit of 4 bytes (5 bytes)]", result.error) diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DependencyDownloadReporterTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DependencyDownloadReporterTest.kt deleted file mode 100644 index 4e5736cc3..000000000 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DependencyDownloadReporterTest.kt +++ /dev/null @@ -1,41 +0,0 @@ -package org.pnfolder.pnlibrary.core.downloads - -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.downloads.DownloadDestination -import org.pnfolder.pnlibrary.api.downloads.FileDownloads -import org.pnfolder.pnlibrary.api.logging.LogLevel -import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter -import java.lang.reflect.Proxy - -class DependencyDownloadReporterTest { - @Test - fun `renders staged dependency and human readable failure cards`() { - val output = mutableListOf() - val platform = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(PlatformAdapter::class.java)) { _, method, arguments -> - when (method.name) { - "getType" -> PlatformType.BUKKIT - "ownerDetails" -> mapOf("name" to "Demo") - "console" -> output += arguments!![1] as String - "details" -> emptyMap() - else -> null - } - } as PlatformAdapter - val reporter = DependencyDownloadReporter(platform, platform) - val declaration = FileDownloads.builder().file("dependency:Vault") { - it.url("https://example.org/Vault.jar") - .destination(DownloadDestination.DATA_FOLDER, "Vault.jar") - }.build().files.single() - - reporter.staged(Any(), listOf(declaration)) - reporter.failure( - Any(), - IllegalArgumentException("скачанный JAR объявляет Wrong, ожидался Vault"), - LogLevel.ERROR, - ) - - assertTrue(output.any { it.contains("Vault.jar") }) - assertTrue(output.any { it.contains("В скачанном файле указано имя Wrong") }) - } -} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DependencyDownloadRequestFactoryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DependencyDownloadRequestFactoryTest.kt deleted file mode 100644 index 886e40d3b..000000000 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DependencyDownloadRequestFactoryTest.kt +++ /dev/null @@ -1,40 +0,0 @@ -package org.pnfolder.pnlibrary.core.downloads - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertNull -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.dependencies.ExternalPluginDependency -import java.nio.file.Path - -class DependencyDownloadRequestFactoryTest { - @TempDir - lateinit var directory: Path - - @Test - fun `creates a safe request only for missing automatic dependencies`() { - val dependency = ExternalPluginDependency.builder("Unsafe Plugin!", "1.2.0") - .url("https://example.org/plugin.jar") - .automaticDownload(true) - .build() - val plan = DependencyDownloadRequestFactory(directory).create(listOf(dependency), emptyMap()) - - requireNotNull(plan) - assertEquals(directory.resolve("update"), plan.request.dataDirectory) - assertEquals("Unsafe-Plugin.jar", plan.request.files.single().relativePath) - assertEquals(dependency.external, plan.requirements["dependency:Unsafe Plugin!"]) - } - - @Test - fun `does not request an already compatible dependency`() { - val dependency = ExternalPluginDependency.builder("Vault", "1.7.3") - .url("https://example.org/Vault.jar") - .automaticDownload(true) - .build() - - assertNull(DependencyDownloadRequestFactory(directory).create( - listOf(dependency), - mapOf("vault" to "1.7.3"), - )) - } -} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadBatchTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadBatchTest.kt index e16a54b74..e01bda93f 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadBatchTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadBatchTest.kt @@ -11,6 +11,7 @@ import org.pnfolder.pnlibrary.api.downloads.DownloadDestination import org.pnfolder.pnlibrary.api.downloads.DownloadState import org.pnfolder.pnlibrary.api.downloads.FileDownload import org.pnfolder.pnlibrary.api.downloads.FileDownloads +import org.pnfolder.pnlibrary.core.downloads.settings.DownloadConfiguration import java.util.concurrent.CompletionException import java.util.concurrent.Executor import java.util.concurrent.Executors @@ -119,7 +120,7 @@ class DownloadBatchTest { request = FileDownloads.builder().file(key) { it.url("https://example.org/manual.bin").destination(DownloadDestination.DATA_FOLDER, "manual.bin") }.build(), - configuration = DownloadConfiguration(), + configuration = { DownloadConfiguration() }, executor = executor, managerIsClosed = managerIsClosed, install = install, @@ -141,7 +142,7 @@ class DownloadBatchTest { try { val registration = DownloadBatch( request = request, - configuration = DownloadConfiguration(), + configuration = { DownloadConfiguration() }, executor = executor, managerIsClosed = { false }, install = { declarations, _ -> installed += declarations.map { it.key } }, diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadConfigurationTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadConfigurationTest.kt deleted file mode 100644 index e6e2971dd..000000000 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadConfigurationTest.kt +++ /dev/null @@ -1,54 +0,0 @@ -package org.pnfolder.pnlibrary.core.downloads - -import org.junit.jupiter.api.Assertions.* -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.downloads.DownloadDestination -import java.nio.file.Files -import java.nio.file.Path - -class DownloadConfigurationTest { - @TempDir lateinit var directory: Path - - @Test - fun `creates a conservative commented file separate from updates`() { - val path = directory.resolve("downloads.yml") - val configuration = DownloadConfiguration.load(path) - - assertTrue(configuration.enabled) - assertFalse(configuration.automatic) - val text = Files.readString(path) - assertTrue(text.contains("enabled: true")) - assertTrue(text.contains("data-folder: true")) - assertTrue(text.contains("# Включить систему загрузок")) - } - - @Test - fun `reads destination policy without host allowlists`() { - val path = directory.resolve("downloads.yml") - Files.writeString(path, """ - enabled: true - automatic: true - destinations: - data-folder: true - cache: false - """.trimIndent()) - - val configuration = DownloadConfiguration.load(path) - - assertTrue(configuration.automatic) - assertEquals(setOf(DownloadDestination.DATA_FOLDER), configuration.destinations) - } - - @Test - fun `removes stale keys and reports them`() { - val path = directory.resolve("downloads.yml") - Files.writeString(path, "downloads:\n enabled: true\nplugins: false\n") - val warnings = mutableListOf() - - DownloadConfiguration.load(path, warnings::add) - - assertTrue(warnings.any { it.contains("plugins") }) - assertFalse(Files.readString(path).contains("plugins:")) - } -} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/CompositeDownloadRegistrationTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/CompositeDownloadRegistrationTest.kt similarity index 97% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/CompositeDownloadRegistrationTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/CompositeDownloadRegistrationTest.kt index 2e4e663b3..787743aa7 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/CompositeDownloadRegistrationTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/CompositeDownloadRegistrationTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.dependencies import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertSame diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DependencyDownloadReporterTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DependencyDownloadReporterTest.kt new file mode 100644 index 000000000..6261be7a7 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DependencyDownloadReporterTest.kt @@ -0,0 +1,100 @@ +package org.pnfolder.pnlibrary.core.downloads.dependencies + +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.downloads.DownloadDestination +import org.pnfolder.pnlibrary.api.downloads.DownloadRegistration +import org.pnfolder.pnlibrary.api.downloads.FileDownloads +import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter +import java.lang.reflect.Proxy +import java.net.URI + +class DependencyDownloadReporterTest { + @Test + fun `renders staged dependency and human readable failure cards`() { + val output = mutableListOf() + val platform = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(PlatformAdapter::class.java)) { _, method, arguments -> + when (method.name) { + "getType" -> PlatformType.BUKKIT + "ownerDetails" -> mapOf("name" to "Demo") + "console" -> output += arguments!![1] as String + "details" -> emptyMap() + else -> null + } + } as PlatformAdapter + val reporter = DependencyDownloadReporter(platform, platform) + val declaration = FileDownloads.builder().file("dependency:Vault") { + it.url("https://example.org/Vault.jar") + .destination(DownloadDestination.DATA_FOLDER, "Vault.jar") + }.build().files.single() + + reporter.staged(Any(), listOf(declaration)) + reporter.failure( + Any(), + IllegalArgumentException("скачанный JAR объявляет Wrong, ожидался Vault"), + LogLevel.ERROR, + ) + + assertTrue(output.any { it.contains("Vault.jar") }) + assertTrue(output.any { it.contains("В скачанном файле указано имя Wrong") }) + } + + private fun platformInto(output: MutableList) = + Proxy.newProxyInstance(javaClass.classLoader, arrayOf(PlatformAdapter::class.java)) { _, method, arguments -> + when (method.name) { + "getType" -> PlatformType.VELOCITY + "ownerDetails" -> mapOf("name" to "Demo") + "console" -> output += arguments!![1] as String + "details" -> emptyMap() + else -> null + } + } as PlatformAdapter + + private fun group(): MissingGroup { + val registration = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(DownloadRegistration::class.java)) { _, _, _ -> null } as DownloadRegistration + val vault = MissingDependency("Vault", "1.7.0", null, listOf(URI.create("https://example.org/Vault.jar"))) + return MissingGroup("Demo", "abc123", listOf(vault), registration) + } + + @Test + fun `the command in the advice is the one that works on this platform`() { + val onProxy = mutableListOf() + platformInto(onProxy).let { DependencyDownloadReporter(it, it, "pnproxy").missing(Any(), group(), false) } + val onServer = mutableListOf() + platformInto(onServer).let { DependencyDownloadReporter(it, it).missing(Any(), group(), false) } + + assertTrue(onProxy.any { it.contains("pnproxy deps install abc123") }) + assertTrue(onProxy.any { it.contains("pnproxy deps auto on") }) + assertTrue(onServer.any { it.contains("pn deps install abc123") && !it.contains("pnproxy") }) + } + + @Test + fun `the notice tells what each plugin is for, whether it is required, and how its file is checked`() { + val output = mutableListOf() + val registration = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(DownloadRegistration::class.java)) { _, _, _ -> null } as DownloadRegistration + val group = MissingGroup( + "Demo", "abc123", + listOf( + MissingDependency( + "Vault", "1.7.0", null, listOf(URI.create("https://example.org/Vault.jar"), URI.create("https://mirror.example.org/Vault.jar")), + title = "Экономика", description = "Нужна для денег и магазинов.", required = true, checked = true, + ), + MissingDependency("Essentials", "2.20.0", URI.create("https://example.org/essentials"), emptyList(), required = false), + ), + registration, + ) + + platformInto(output).let { DependencyDownloadReporter(it, it).missing(Any(), group, false) } + + val text = output.joinToString(" ") + assertTrue(text.contains("Обязательные")) + assertTrue(text.contains("Необязательные")) + assertTrue(text.contains("Экономика (Vault) 1.7.0+")) + assertTrue(text.contains("Нужна для денег и магазинов.")) + assertTrue(text.contains("mirror.example.org/Vault.jar")) + assertTrue(text.contains("SHA-256 автора")) + assertTrue(text.contains("Essentials 2.20.0+")) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DependencyDownloadRequestFactoryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DependencyDownloadRequestFactoryTest.kt new file mode 100644 index 000000000..cdd27fddb --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DependencyDownloadRequestFactoryTest.kt @@ -0,0 +1,78 @@ +package org.pnfolder.pnlibrary.core.downloads.dependencies + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.platform.PlatformType +import java.nio.file.Path + +class DependencyDownloadRequestFactoryTest { + @TempDir + lateinit var directory: Path + + @Test + fun `creates a safe request only for missing automatic dependencies`() { + val dependency = ExternalPluginDependency.builder("Unsafe Plugin!", "1.2.0") + .url("https://example.org/plugin.jar") + .automaticDownload(true) + .build() + val plan = DependencyDownloadRequestFactory(directory.resolve("update"), PlatformType.BUKKIT) { "1.21.4" }.create(listOf(dependency), emptyMap()) + + requireNotNull(plan) + assertEquals(directory.resolve("update"), plan.request.dataDirectory) + assertEquals("Unsafe-Plugin.jar", plan.request.files.single().relativePath) + assertEquals(dependency.external, plan.requirements["dependency:Unsafe Plugin!"]) + } + + @Test + fun `does not request an already compatible dependency`() { + val dependency = ExternalPluginDependency.builder("Vault", "1.7.3") + .url("https://example.org/Vault.jar") + .automaticDownload(true) + .build() + + assertNull(DependencyDownloadRequestFactory(directory.resolve("update"), PlatformType.BUKKIT) { "1.21.4" }.create( + listOf(dependency), + mapOf("vault" to "1.7.3"), + )) + } + + @Test + fun `downloads the file made for this server and checks only its checksum`() { + val old = "a".repeat(64) + val modern = "b".repeat(64) + val dependency = ExternalPluginDependency.builder("Vault", "1.7.0") + .variant("https://example.org/Vault-old.jar", old, minecraftBefore = "1.20") + .variant("https://example.org/Vault-proxy.jar", "c".repeat(64), platforms = setOf(PlatformType.VELOCITY)) + .variant("https://example.org/Vault-new.jar", modern, minecraftFrom = "1.20", label = "для 1.20 и новее") + .build() + + val plan = requireNotNull( + DependencyDownloadRequestFactory(directory.resolve("update"), PlatformType.BUKKIT) { "1.21.4" }.create(listOf(dependency), emptyMap()), + ) + val source = plan.request.files.single().source + assertEquals("https://example.org/Vault-new.jar", source.uri.toString()) + assertEquals(modern, source.sha256) + + val older = DependencyDownloadRequestFactory(directory.resolve("update"), PlatformType.BUKKIT) { "1.16.5" } + assertEquals(old, older.fileFor(dependency)?.sha256) + val unknown = DependencyDownloadRequestFactory(directory.resolve("update"), PlatformType.BUNGEECORD) { null } + assertNull(unknown.fileFor(dependency)) + } + + @Test + fun `a file may carry its own size limit`() { + val dependency = ExternalPluginDependency.builder("Vault", "1.7.0") + .url("https://example.org/Vault.jar") + .maxBytes(2_000_000) + .build() + + val plan = requireNotNull( + DependencyDownloadRequestFactory(directory.resolve("update"), PlatformType.BUKKIT) { null }.create(listOf(dependency), emptyMap()), + ) + + assertEquals(2_000_000L, plan.request.files.single().source.maxBytes) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadedDependencyStoreTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DownloadedDependencyStoreTest.kt similarity index 94% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadedDependencyStoreTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DownloadedDependencyStoreTest.kt index 5f36d76e2..eb4150945 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadedDependencyStoreTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/dependencies/DownloadedDependencyStoreTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.dependencies import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/AtomicDownloadPublisherTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/AtomicDownloadPublisherTest.kt similarity index 98% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/AtomicDownloadPublisherTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/AtomicDownloadPublisherTest.kt index bfe18beea..819785d08 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/AtomicDownloadPublisherTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/AtomicDownloadPublisherTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.fetch import org.junit.jupiter.api.Assertions.assertArrayEquals import org.junit.jupiter.api.Assertions.assertFalse diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DirectDownloadsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/DirectDownloadsTest.kt similarity index 95% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DirectDownloadsTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/DirectDownloadsTest.kt index 4da8abd09..61225fa81 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DirectDownloadsTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/DirectDownloadsTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.fetch import org.junit.jupiter.api.Assertions.assertArrayEquals import org.junit.jupiter.api.Assertions.assertEquals @@ -7,13 +7,15 @@ import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.dependencies.ExternalPluginDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency import org.pnfolder.pnlibrary.api.downloads.DownloadDestination import org.pnfolder.pnlibrary.api.downloads.DownloadState import org.pnfolder.pnlibrary.api.downloads.FileDownloads import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.core.updates.engine.TrustedHttpClient +import org.pnfolder.pnlibrary.core.downloads.settings.DownloadConfiguration import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths import java.io.ByteArrayOutputStream import java.lang.reflect.Proxy import java.net.URI @@ -203,9 +205,8 @@ class DirectDownloadsTest { return bytes.also { require(it.size <= maximumBytes) } } } - return DirectDownloads(platform, platform, platform, platform, platform, directory.resolve("plugins/pnLibrary"), DownloadConfiguration( - automatic = automatic, - ), http) + val paths = LibraryPaths(directory.resolve("plugins/pnLibrary")) + return DirectDownloads(platform, platform, platform, platform, platform, paths, { DownloadConfiguration(automatic = automatic) }, http = http) } private fun pluginJar(name: String, version: String): ByteArray = ByteArrayOutputStream().also { output -> diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadArtifactPreparerTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/DownloadArtifactPreparerTest.kt similarity index 90% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadArtifactPreparerTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/DownloadArtifactPreparerTest.kt index ab0f6bc50..13d6a30ba 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/DownloadArtifactPreparerTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/DownloadArtifactPreparerTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.downloads +package org.pnfolder.pnlibrary.core.downloads.fetch import org.junit.jupiter.api.Assertions.assertArrayEquals import org.junit.jupiter.api.Assertions.assertEquals @@ -10,7 +10,8 @@ import org.junit.jupiter.api.io.TempDir import org.pnfolder.pnlibrary.api.downloads.DownloadDestination import org.pnfolder.pnlibrary.api.downloads.FileDownloads import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.core.updates.engine.TrustedHttpClient +import org.pnfolder.pnlibrary.core.downloads.settings.DownloadConfiguration +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient import java.net.URI import java.nio.file.Files import java.nio.file.Path @@ -35,7 +36,7 @@ class DownloadArtifactPreparerTest { val preparer = DownloadArtifactPreparer( platform = PlatformType.BUKKIT, libraryData = directory.resolve("plugins/pnLibrary"), - configuration = DownloadConfiguration(), + configuration = { DownloadConfiguration() }, http = http, ) @@ -54,7 +55,7 @@ class DownloadArtifactPreparerTest { val http = object : TrustedHttpClient(Duration.ofSeconds(1), Duration.ofSeconds(1)) { override fun get(uri: URI, maximumBytes: Int) = "invalid jar".toByteArray() } - val preparer = DownloadArtifactPreparer(PlatformType.BUKKIT, libraryData, DownloadConfiguration(), http) + val preparer = DownloadArtifactPreparer(PlatformType.BUKKIT, libraryData, { DownloadConfiguration() }, http) val failure = IllegalArgumentException("Plugin identity does not match") assertSame(failure, assertThrows(IllegalArgumentException::class.java) { diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/SourceFetcherTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/SourceFetcherTest.kt new file mode 100644 index 000000000..475b97747 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/downloads/fetch/SourceFetcherTest.kt @@ -0,0 +1,59 @@ +package org.pnfolder.pnlibrary.core.downloads.fetch + +import org.junit.jupiter.api.Assertions.assertArrayEquals +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.downloads.DirectDownloadSource +import org.pnfolder.pnlibrary.common.io.Digests +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient +import java.net.URI +import java.time.Duration + +class SourceFetcherTest { + private val first = "https://a.example.org/x.jar" + private val second = "https://b.example.org/x.jar" + + private fun client(answers: MutableMap) = + object : TrustedHttpClient(Duration.ofSeconds(1), Duration.ofSeconds(1)) { + override fun get(uri: URI, maximumBytes: Int): ByteArray = answers[uri.toString()] ?: error("нет ответа") + } + + private fun source(vararg mirrors: String, sha: String? = null) = DirectDownloadSource.builder().url(first) + .also { builder -> mirrors.forEach(builder::mirror) } + .also { builder -> if (sha != null) builder.sha256(sha) } + .build() + + @Test + fun `without a checksum the first address that answers is used and nothing is compared`() { + val answers = mutableMapOf(first to "jar1".toByteArray(), second to "other".toByteArray()) + + assertArrayEquals("jar1".toByteArray(), SourceFetcher(client(answers)).fetch(source(second), 100)) + } + + @Test + fun `a mirror answers when the first address is down`() { + val result = SourceFetcher(client(mutableMapOf(second to "jar1".toByteArray()))).fetch(source(second), 100) + + assertEquals("jar1", String(result)) + } + + @Test + fun `with a checksum only the file that matches is taken`() { + val good = "jar1".toByteArray() + val answers = mutableMapOf(first to "evil".toByteArray(), second to good) + + val result = SourceFetcher(client(answers)).fetch(source(second, sha = Digests.sha256(good)), 100) + + assertArrayEquals(good, result) + } + + @Test + fun `with a checksum nothing is taken when no file matches`() { + val answers = mutableMapOf(first to "evil".toByteArray(), second to "worse".toByteArray()) + + assertThrows(IllegalArgumentException::class.java) { + SourceFetcher(client(answers)).fetch(source(second, sha = Digests.sha256("jar1".toByteArray())), 100) + } + } +} diff --git a/modules/events/src/test/kotlin/org/pnfolder/pnlibrary/core/events/EventDispatcherTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/events/EventDispatcherTest.kt similarity index 94% rename from modules/events/src/test/kotlin/org/pnfolder/pnlibrary/core/events/EventDispatcherTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/events/EventDispatcherTest.kt index e9ba906b3..021c97474 100644 --- a/modules/events/src/test/kotlin/org/pnfolder/pnlibrary/core/events/EventDispatcherTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/events/EventDispatcherTest.kt @@ -4,6 +4,12 @@ import net.kyori.adventure.text.Component import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.events.* +import org.pnfolder.pnlibrary.api.events.bus.* +import org.pnfolder.pnlibrary.api.events.bus.DispatchMode +import org.pnfolder.pnlibrary.api.events.inspect.* +import org.pnfolder.pnlibrary.api.events.listener.* +import org.pnfolder.pnlibrary.api.events.listener.EventHandler +import org.pnfolder.pnlibrary.api.events.listener.Listener import org.pnfolder.pnlibrary.api.plugin.ModuleId import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.api.runtime.PnLibrary @@ -12,6 +18,20 @@ import java.lang.reflect.Proxy import java.util.function.Consumer class EventDispatcherTest { + @Test + fun `a one-time listener runs once and cancelling it first prevents the run`() { + val calls = mutableListOf() + EventDispatcher { _, _, _ -> }.use { events -> + val scope = events.scope(PluginId.of("test")) + scope.on().listenOnce { calls += "once" } + scope.on().listenOnce { calls += "never" }.close() + events.callEvent(TestEvent()) + events.callEvent(TestEvent()) + assertEquals(listOf("once"), calls) + assertEquals(0, events.inspector.listenerCount(TestEvent::class.java)) + } + } + @Test fun `call returns only after listeners run in priority order`() { val calls = mutableListOf() @@ -355,9 +375,9 @@ class EventDispatcherTest { events.callEventAsync(TestEvent()).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS) events.callEvent(TestEvent()) val (async, sync) = events.inspector.traces() - assertEquals(org.pnfolder.pnlibrary.api.events.DispatchMode.ASYNC, async.mode) + assertEquals(org.pnfolder.pnlibrary.api.events.bus.DispatchMode.ASYNC, async.mode) assertEquals("pnLibrary-events", async.thread) - assertEquals(org.pnfolder.pnlibrary.api.events.DispatchMode.SYNC, sync.mode) + assertEquals(org.pnfolder.pnlibrary.api.events.bus.DispatchMode.SYNC, sync.mode) assertEquals(caller, sync.thread) } } @@ -370,7 +390,7 @@ class EventDispatcherTest { val event = TestEvent() assertEquals(null, event.dispatchMode) events.callEvent(event) - assertEquals(org.pnfolder.pnlibrary.api.events.DispatchMode.SYNC, event.dispatchMode) + assertEquals(org.pnfolder.pnlibrary.api.events.bus.DispatchMode.SYNC, event.dispatchMode) events.callEventAsync(event).toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS) assertEquals("pnLibrary-events", event.dispatchThread?.name) assertEquals(listOf(false, true), seen.toList()) diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/events/inspect/history/EventHistoryCountingTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/events/inspect/history/EventHistoryCountingTest.kt new file mode 100644 index 000000000..3065be19b --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/events/inspect/history/EventHistoryCountingTest.kt @@ -0,0 +1,151 @@ +package org.pnfolder.pnlibrary.core.events.inspect.history + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.core.events.inspect.history.EventHistory +import java.lang.management.ManagementFactory +import java.nio.file.Files +import java.nio.file.Path +import java.time.Instant +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.ZoneOffset +import java.time.temporal.ChronoUnit +import java.util.TreeMap + +class EventHistoryCountingTest { + private val zone = ZoneId.of("Europe/Moscow") + + /** The counting as it was before: two tree maps behind one lock, a fresh local time for every call. */ + private class Old(private val retentionDays: Int, private val zone: ZoneId) { + class Counts(var calls: Long = 0, var denied: Long = 0) + + val days = TreeMap>() + val hours = TreeMap>() + + fun record(eventType: String, denied: Boolean, now: LocalDateTime = LocalDateTime.now(zone)) { + val today = now.toLocalDate() + synchronized(days) { + val counts = days.getOrPut(today) { HashMap() }.getOrPut(eventType) { Counts() } + counts.calls++ + if (denied) counts.denied++ + val hourly = hours.getOrPut(now.truncatedTo(ChronoUnit.HOURS)) { HashMap() }.getOrPut(eventType) { Counts() } + hourly.calls++ + if (denied) hourly.denied++ + val keep = minOf(retentionDays, 30) * 24L + hours.headMap(now.truncatedTo(ChronoUnit.HOURS).minusHours(keep - 1)).clear() + if (days.firstKey().isBefore(today.minusDays(retentionDays.toLong() - 1))) days.headMap(today.minusDays(retentionDays.toLong() - 1)).clear() + } + } + + fun dayTotals() = days.flatMap { (d, m) -> m.map { Triple("$d ${it.key}", it.value.calls, it.value.denied) } }.sortedBy { it.first } + fun hourTotals() = hours.flatMap { (d, m) -> m.map { Triple("$d ${it.key}", it.value.calls, it.value.denied) } }.sortedBy { it.first } + } + + private fun newHistory(file: Path?, clockMillis: () -> Long) = + EventHistory(file, 30, zone = { zone }, flushEveryMillis = Long.MAX_VALUE, now = clockMillis) + + @Test + fun `sums per day and hour equal the old counting across hour, day and retention changes`() { + val start = Instant.parse("2026-11-01T20:00:00Z").toEpochMilli() + var millis = start + val fresh = newHistory(null) { millis } + val old = Old(30, zone) + val types = listOf("a.Buy", "a.Join", "b.Quit", "c.Move") + // 50 days in steps of 7 minutes 13 seconds so hours, days and the retention edge are all crossed + var index = 0 + while (millis < start + 50L * 86_400_000) { + val type = types[index % types.size] + val denied = index % 5 == 0 + fresh.record(type, denied) + old.record(type, denied, LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), zone)) + millis += 433_000 + index++ + } + assertEquals(old.dayTotals(), fresh.entries().map { Triple("${it.date} ${it.eventType}", it.calls, it.denied) }.sortedBy { it.first }) + assertEquals(old.hourTotals(), fresh.hourly().map { Triple("${it.hour} ${it.eventType}", it.calls, it.denied) }.sortedBy { it.first }) + assertTrue(fresh.entries().map { it.date }.toSet().size == 30) + } + + @Test + fun `the file keeps its format and loads back to the same sums`(@TempDir dir: Path) { + val file = dir.resolve("history.tsv") + val millis = Instant.parse("2026-11-09T10:15:00Z").toEpochMilli() + newHistory(file) { millis }.use { history -> + repeat(3) { history.record("a.Buy", denied = it == 0) } + history.record("a.Join", denied = false) + } + val lines = Files.readAllLines(file) + assertEquals("# pnLibrary event history v1", lines.first()) + assertEquals( + listOf("2026-11-09\ta.Buy\t3\t1", "2026-11-09\ta.Join\t1\t0", "2026-11-09T13:00\ta.Buy\t3\t1", "2026-11-09T13:00\ta.Join\t1\t0"), + lines.drop(1).sorted(), + ) + val loaded = newHistory(file) { millis } + assertEquals(3L, loaded.entries("a.Buy").single().calls) + assertEquals(1L, loaded.hourly("a.Join").single().calls) + } + + @Test + fun `counting takes no lock and several threads lose no call`() { + val history = EventHistory(null, 30) + val old = Old(30, ZoneId.systemDefault()) + val threads = 8 + val perThread = 40_000 + val bean = ManagementFactory.getThreadMXBean() + + fun blockedWhile(work: (Int) -> Unit): Long { + val blocked = java.util.concurrent.atomic.AtomicLong() + val workers = List(threads) { n -> + Thread { + repeat(perThread) { work(n) } + blocked.addAndGet(bean.getThreadInfo(Thread.currentThread().id).blockedCount) + }.also(Thread::start) + } + workers.forEach(Thread::join) + return blocked.get() + } + + history.record("a.Buy", false) // creates the map entries, which is the only part that locks + old.record("a.Buy", false) + val blockedNew = blockedWhile { history.record("a.Buy", it == 0) } + val blockedOld = blockedWhile { old.record("a.Buy", it == 0) } + + assertEquals(threads.toLong() * perThread + 1, history.entries("a.Buy").single().calls) + assertEquals(perThread.toLong(), history.entries("a.Buy").single().denied) + // a monitor per call would be thousands; a bucket change once a minute may block a thread or two + assertTrue(blockedNew <= threads, "threads blocked on a monitor while counting: $blockedNew (old counting: $blockedOld)") + } + + @Test + fun `a call allocates at most half of what the old counting did`() { + val history = EventHistory(null, 30) + val old = Old(30, ZoneId.systemDefault()) + val bean = ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean + val id = Thread.currentThread().id + repeat(50_000) { history.record("a.Buy", false); old.record("a.Buy", false) } + + val before = bean.getThreadAllocatedBytes(id) + repeat(200_000) { history.record("a.Buy", it % 3 == 0) } + val fresh = bean.getThreadAllocatedBytes(id) - before + val middle = bean.getThreadAllocatedBytes(id) + repeat(200_000) { old.record("a.Buy", it % 3 == 0) } + val previous = bean.getThreadAllocatedBytes(id) - middle + + assertTrue(fresh * 2 <= previous, "new $fresh bytes, old $previous bytes for 200000 calls") + } + + @Test + fun `the zone of a later minute is honoured`() { + var millis = Instant.parse("2026-11-09T21:59:30Z").toEpochMilli() + val history = EventHistory(null, 30, zone = { ZoneOffset.UTC }, now = { millis }) + history.record("a.Buy", false) + millis += 60_000 + history.record("a.Buy", false) + + assertEquals(listOf(LocalDateTime.parse("2026-11-09T22:00"), LocalDateTime.parse("2026-11-09T21:00")), history.hourly().map { it.hour }) + } +} diff --git a/modules/events/src/test/kotlin/org/pnfolder/pnlibrary/core/events/EventHistoryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/events/inspect/history/EventHistoryTest.kt similarity index 82% rename from modules/events/src/test/kotlin/org/pnfolder/pnlibrary/core/events/EventHistoryTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/events/inspect/history/EventHistoryTest.kt index 926054d40..bc7065dbc 100644 --- a/modules/events/src/test/kotlin/org/pnfolder/pnlibrary/core/events/EventHistoryTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/events/inspect/history/EventHistoryTest.kt @@ -1,9 +1,10 @@ -package org.pnfolder.pnlibrary.core.events +package org.pnfolder.pnlibrary.core.events.inspect.history import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.core.events.inspect.history.EventHistory import java.nio.file.Files import java.nio.file.Path import java.time.LocalDate @@ -71,4 +72,19 @@ class EventHistoryTest { } assertTrue(EventHistory(null, 30).export(json = false) == null) } + + @Test + fun `a history that cannot be written is reported once`(@TempDir dir: Path) { + val blocker = dir.resolve("blocker") + Files.writeString(blocker, "a file where the folder should be") + val failures = mutableListOf() + val history = EventHistory(blocker.resolve("history.tsv"), 30, onFailure = { failures += it }) + + history.record("a.Buy", denied = false) + history.flush() + history.record("a.Buy", denied = false) + history.flush() + + assertEquals(1, failures.size) + } } diff --git a/modules/events/src/test/kotlin/org/pnfolder/pnlibrary/core/events/PlayerLifecyclePublisherTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/events/player/PlayerLifecyclePublisherTest.kt similarity index 94% rename from modules/events/src/test/kotlin/org/pnfolder/pnlibrary/core/events/PlayerLifecyclePublisherTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/events/player/PlayerLifecyclePublisherTest.kt index 865568e4a..52fae9631 100644 --- a/modules/events/src/test/kotlin/org/pnfolder/pnlibrary/core/events/PlayerLifecyclePublisherTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/events/player/PlayerLifecyclePublisherTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.events +package org.pnfolder.pnlibrary.core.events.player import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull @@ -7,12 +7,13 @@ import org.junit.jupiter.api.Test import org.mockito.Mockito.mock import org.mockito.Mockito.`when` import org.pnfolder.pnlibrary.api.audiences.AudienceService -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer import org.pnfolder.pnlibrary.api.events.player.PlayerJoinedEvent import org.pnfolder.pnlibrary.api.events.player.PlayerLeftEvent import org.pnfolder.pnlibrary.api.events.player.PlayerLifecycleEvent import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.core.events.EventDispatcher import java.util.UUID import java.util.function.Consumer diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/cleanup/ResourceCleanupTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/exceptions/ResourceCleanupTest.kt similarity index 96% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/cleanup/ResourceCleanupTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/exceptions/ResourceCleanupTest.kt index 765bb63e8..58016a829 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/cleanup/ResourceCleanupTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/exceptions/ResourceCleanupTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.cleanup +package org.pnfolder.pnlibrary.core.exceptions import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertSame diff --git a/modules/journal/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalDigestTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalDigestTest.kt similarity index 98% rename from modules/journal/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalDigestTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalDigestTest.kt index b7660368d..dc23f85bf 100644 --- a/modules/journal/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalDigestTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalDigestTest.kt @@ -5,6 +5,7 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.core.journal.view.joinDigest import java.time.Duration import java.time.Instant diff --git a/modules/journal/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalQueriesTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalQueriesTest.kt similarity index 96% rename from modules/journal/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalQueriesTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalQueriesTest.kt index 0c4794adb..b69d5440e 100644 --- a/modules/journal/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalQueriesTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalQueriesTest.kt @@ -5,6 +5,8 @@ import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig +import org.pnfolder.pnlibrary.core.journal.store.JournalQueries +import org.pnfolder.pnlibrary.core.journal.store.JournalStore import java.nio.file.Path import java.time.Clock import java.time.Duration diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalStoreBatchTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalStoreBatchTest.kt new file mode 100644 index 000000000..be063d5c3 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalStoreBatchTest.kt @@ -0,0 +1,166 @@ +package org.pnfolder.pnlibrary.core.journal + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertSame +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig +import org.pnfolder.pnlibrary.core.journal.store.JournalQueries +import org.pnfolder.pnlibrary.core.journal.store.JournalStore +import java.nio.file.Files +import java.nio.file.Path +import java.time.Clock +import java.time.Duration +import java.time.Instant +import java.time.ZoneId +import java.time.ZoneOffset + +class JournalStoreBatchTest { + @TempDir lateinit var directory: Path + + private val day = Instant.parse("2026-10-19T10:00:00Z") + private val retention = JournalLevel.values().associateWith { Duration.ofDays(30) } + + private fun corpus(count: Int) = List(count) { index -> + JournalRecord( + day.toEpochMilli() + index, + JournalLevel.values()[index % 3], + "src${index % 4}", + "LOG", + "message $index", + if (index % 7 == 0) mapOf("exception" to "X", JournalRecord.STACKTRACE to "trace $index") else emptyMap(), + ) + } + + private fun store(folder: Path, clock: Clock = Clock.fixed(day, ZoneOffset.UTC)) = JournalStore(folder, retention, clock) + + private fun throwing(): (JournalRecord, Throwable) -> Unit = { _, error -> throw error } + + @Test + fun `a batch reads back exactly like the same records appended one by one`() { + val one = Files.createDirectory(directory.resolve("one")) + val batch = Files.createDirectory(directory.resolve("batch")) + val records = corpus(900) + store(one).apply { records.forEach(::append) } + store(batch).appendAll(records, throwing()) + + val expected = store(one).read(limit = 100_000) + assertEquals(900, expected.size) + assertEquals(expected, store(batch).read(limit = 100_000)) + val errors = setOf(JournalLevel.ERROR) + assertEquals(store(one).read(levels = errors, limit = 50), store(batch).read(levels = errors, limit = 50)) + } + + @Test + fun `blocks of the old one record format and new batches live in one file`() { + store(directory).append(JournalRecord(day.toEpochMilli(), JournalLevel.INFO, "a", "LOG", "legacy")) + val reopened = store(directory) + reopened.appendAll(corpus(30).filter { it.level == JournalLevel.INFO }, throwing()) + + assertEquals(1, Files.list(directory).use { it.count() }) + assertTrue(reopened.read(limit = 100).any { it.message == "legacy" }) + assertEquals(11, reopened.read(limit = 100).size) + } + + @Test + fun `a thousand records cost at most three listings and one block per chunk`() { + val journal = store(directory) + val records = corpus(1_000).map { it.copy(level = JournalLevel.INFO) } + records.chunked(250).forEach { journal.appendAll(it, throwing()) } + + assertTrue(journal.directoryListings <= 3, "listings: ${journal.directoryListings}") + assertTrue(journal.blocksWritten.get() <= 1_000 / 250, "blocks: ${journal.blocksWritten.get()}") + assertEquals(1_000, journal.read(limit = 100_000).size) + } + + @Test + fun `single appends no longer list the folder per record`() { + val journal = store(directory) + corpus(1_000).map { it.copy(level = JournalLevel.INFO) }.forEach(journal::append) + + assertTrue(journal.directoryListings <= 3, "listings: ${journal.directoryListings}") + assertEquals(1_000, journal.read(limit = 100_000).size) + } + + @Test + fun `a full segment rolls over to the next number and survives a restart`() { + val clock = Clock.fixed(day, ZoneOffset.UTC) + val small = JournalStore(directory, retention, clock, maximumSegmentBytes = 2_000) + val records = corpus(600).map { it.copy(level = JournalLevel.WARNING) } + records.chunked(20).forEach { small.appendAll(it, throwing()) } + val restarted = JournalStore(directory, retention, clock, maximumSegmentBytes = 2_000) + restarted.appendAll(listOf(records.first().copy(message = "after restart")), throwing()) + + val names = Files.list(directory).use { stream -> stream.map { it.fileName.toString() }.sorted().toList() } + assertTrue(names.size > 3, names.toString()) + assertEquals(601, restarted.read(limit = 100_000).size) + } + + @Test + fun `the disk budget is checked again after a minute without a new segment`() { + var now = day.toEpochMilli() + val clock = object : Clock() { + override fun getZone(): ZoneId = ZoneOffset.UTC + override fun withZone(zone: ZoneId): Clock = this + override fun instant(): Instant = Instant.ofEpochMilli(now) + } + val journal = JournalStore(directory, retention, clock, maximumSegmentBytes = 1_000_000, maximumDiskBytes = 1_000_000) + val info = corpus(1).first().copy(level = JournalLevel.INFO) + journal.append(info) + val before = journal.directoryListings + journal.append(info) + assertEquals(before, journal.directoryListings) + + now += 61_000 + journal.append(info) + assertEquals(before + 1, journal.directoryListings) + } + + @Test + fun `an oversized record is rejected without losing its neighbours`() { + val journal = JournalStore(directory, retention, Clock.fixed(day, ZoneOffset.UTC), maximumSegmentBytes = 400, maximumDiskBytes = 400) + val noise = java.util.Random(7) + val incompressible = String(CharArray(4_000) { ('a' + noise.nextInt(26)) }) + val bad = JournalRecord(day.toEpochMilli(), JournalLevel.INFO, "a", "LOG", incompressible) + val good = JournalRecord(day.toEpochMilli() + 1, JournalLevel.INFO, "a", "LOG", "small") + val rejected = mutableListOf() + journal.appendAll(listOf(good, bad)) { record, _ -> rejected += record } + + assertEquals(listOf("small"), journal.read().map { it.message }) + assertEquals(listOf(bad), rejected) + } + + @Test + fun `fingerprint keeps its old value and is computed once`() { + val record = JournalRecord(1, JournalLevel.ERROR, "shop", "ERROR", "boom\nsecond line", mapOf("exception" to "java.lang.Boom")) + val key = listOf("ERROR", "shop", "boom", "java.lang.Boom").joinToString("\u0000") + assertEquals("%08x".format(key.hashCode()), record.fingerprint) + assertSame(record.fingerprint, record.fingerprint) + val short = JournalRecord(1, JournalLevel.INFO, "", "LOG", "") + val shortKey = listOf("INFO", "", "", "").joinToString("\u0000") + assertEquals("%08x".format(shortKey.hashCode()), short.fingerprint) + repeat(300) { i -> + val r = JournalRecord(i.toLong(), JournalLevel.WARNING, "s$i", "LOG", "m$i") + val k = listOf("WARNING", "s$i", "m$i", "").joinToString("\u0000") + assertEquals("%08x".format(k.hashCode()), r.fingerprint) + } + } + + @Test + fun `join notice is built once for a wave of joins within the cache period`() { + val journal = store(directory) + journal.append(JournalRecord(day.toEpochMilli(), JournalLevel.ERROR, "shop", "ERROR", "payout failed")) + var now = day.toEpochMilli() + 60_000 + val queries = JournalQueries(journal, PnLibraryConfig(), day.toEpochMilli(), "/pn events") { now } + + val first = queries.joinNotice() + val listings = journal.directoryListings + repeat(50) { assertSame(first, queries.joinNotice()) } + assertEquals(listings, journal.directoryListings) + + now += 46_000 + queries.joinNotice() + assertTrue(journal.directoryListings > listings) + } +} diff --git a/modules/journal/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalStoreTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalStoreTest.kt similarity index 99% rename from modules/journal/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalStoreTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalStoreTest.kt index 2bc16ff1e..d33ef0349 100644 --- a/modules/journal/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalStoreTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalStoreTest.kt @@ -5,6 +5,7 @@ import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.core.journal.store.JournalStore import java.nio.file.Files import java.nio.file.Path import java.time.Clock diff --git a/modules/journal/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalTimeAndTraceTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalTimeAndTraceTest.kt similarity index 92% rename from modules/journal/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalTimeAndTraceTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalTimeAndTraceTest.kt index 30f3d53b4..759a68c9e 100644 --- a/modules/journal/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalTimeAndTraceTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/journal/JournalTimeAndTraceTest.kt @@ -7,8 +7,14 @@ import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.core.journal.view.CARD_TRACE_LINES +import org.pnfolder.pnlibrary.core.journal.view.ago +import org.pnfolder.pnlibrary.core.journal.view.agoColor +import org.pnfolder.pnlibrary.core.journal.view.span +import org.pnfolder.pnlibrary.core.journal.view.traceLine +import org.pnfolder.pnlibrary.core.journal.view.traceView import java.time.Instant import java.time.ZoneOffset diff --git a/modules/link/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkLimitsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkLimitsTest.kt similarity index 89% rename from modules/link/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkLimitsTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkLimitsTest.kt index af69d12f1..d4733ad9e 100644 --- a/modules/link/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkLimitsTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkLimitsTest.kt @@ -7,6 +7,12 @@ import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.core.link.report.LinkPlugin +import org.pnfolder.pnlibrary.core.link.report.LinkReport +import org.pnfolder.pnlibrary.core.link.report.NetworkReport +import org.pnfolder.pnlibrary.core.link.report.NetworkServer +import org.pnfolder.pnlibrary.core.link.wire.LinkCodec +import org.pnfolder.pnlibrary.core.link.wire.LinkSecret import java.nio.file.Files import java.nio.file.Path import java.time.Instant diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkRegistryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkRegistryTest.kt new file mode 100644 index 000000000..30b7e30a4 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkRegistryTest.kt @@ -0,0 +1,33 @@ +package org.pnfolder.pnlibrary.core.link + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.core.link.report.LinkReport +import java.time.Instant + +class LinkRegistryTest { + private fun report(players: Int) = LinkReport("paper", "1.0", players, emptyList(), Instant.EPOCH) + + @Test + fun `a newer report replaces the old one and lookup ignores case`() { + val registry = LinkRegistry() + registry.accept("Lobby", report(1)) + registry.accept("Lobby", report(5)) + + assertEquals(5, registry.get("lobby")!!.report.players) + assertEquals(1, registry.all().size) + assertNull(registry.get("other")) + } + + @Test + fun `servers are listed by name and can be cleared`() { + val registry = LinkRegistry() + registry.accept("beta", report(0)) + registry.accept("Alpha", report(0)) + + assertEquals(listOf("Alpha", "beta"), registry.all().map { it.name }) + registry.clear() + assertEquals(0, registry.all().size) + } +} diff --git a/modules/link/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkTest.kt similarity index 92% rename from modules/link/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkTest.kt index 842e03713..b7372593e 100644 --- a/modules/link/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/LinkTest.kt @@ -8,6 +8,21 @@ import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.core.link.remote.DataCall +import org.pnfolder.pnlibrary.core.link.remote.DataClient +import org.pnfolder.pnlibrary.core.link.remote.DataHandler +import org.pnfolder.pnlibrary.core.link.remote.LinkNames +import org.pnfolder.pnlibrary.core.link.remote.LinkTransport +import org.pnfolder.pnlibrary.core.link.remote.RemoteAction +import org.pnfolder.pnlibrary.core.link.remote.RemoteRequest +import org.pnfolder.pnlibrary.core.link.remote.RemoteResult +import org.pnfolder.pnlibrary.core.link.report.LinkPlugin +import org.pnfolder.pnlibrary.core.link.report.LinkReport +import org.pnfolder.pnlibrary.core.link.report.NetworkReport +import org.pnfolder.pnlibrary.core.link.report.NetworkServer +import org.pnfolder.pnlibrary.core.link.wire.DataChunks +import org.pnfolder.pnlibrary.core.link.wire.LinkCodec +import org.pnfolder.pnlibrary.core.link.wire.LinkSecret import java.nio.file.Path import java.time.Duration import java.time.Instant diff --git a/modules/link/src/test/kotlin/org/pnfolder/pnlibrary/core/link/ServerGroupsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/ServerGroupsTest.kt similarity index 96% rename from modules/link/src/test/kotlin/org/pnfolder/pnlibrary/core/link/ServerGroupsTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/ServerGroupsTest.kt index 84a22d4ff..7ceeb8c61 100644 --- a/modules/link/src/test/kotlin/org/pnfolder/pnlibrary/core/link/ServerGroupsTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/ServerGroupsTest.kt @@ -6,6 +6,9 @@ import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.core.link.report.LinkPlugin +import org.pnfolder.pnlibrary.core.link.report.LinkReport +import org.pnfolder.pnlibrary.core.link.report.NetworkServer import java.nio.file.Path import java.time.Instant diff --git a/modules/link/src/test/kotlin/org/pnfolder/pnlibrary/core/link/RemoteExecutorTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/remote/RemoteExecutorTest.kt similarity index 70% rename from modules/link/src/test/kotlin/org/pnfolder/pnlibrary/core/link/RemoteExecutorTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/remote/RemoteExecutorTest.kt index 78d0efe64..a587831b5 100644 --- a/modules/link/src/test/kotlin/org/pnfolder/pnlibrary/core/link/RemoteExecutorTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/remote/RemoteExecutorTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.link +package org.pnfolder.pnlibrary.core.link.remote import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse @@ -7,9 +7,11 @@ import org.junit.jupiter.api.Test import org.mockito.Mockito.mock import org.mockito.Mockito.`when` import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.updates.UpdateActor +import org.pnfolder.pnlibrary.api.updates.UpdateProducts import org.pnfolder.pnlibrary.api.updates.UpdateService -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.UpdateSettings +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot import java.time.Duration import java.time.Instant import java.util.UUID @@ -21,15 +23,20 @@ class RemoteExecutorTest { private val calls = mutableListOf() private var automaticAnswer: CompletionStage = CompletableFuture.completedFuture(null) - private val updates: UpdateService = mock(UpdateService::class.java) { call -> + private val settings: UpdateSettings = mock(UpdateSettings::class.java) { call -> when (call.method.name) { - "setAutomaticDownload" -> { + "automaticDownload" -> { calls += Call(call.getArgument(0), call.getArgument(1), call.getArgument(2)) automaticAnswer } else -> null } } + private val products: UpdateProducts = mock(UpdateProducts::class.java) + private val updates: UpdateService = mock(UpdateService::class.java).also { + `when`(it.settings).thenReturn(settings) + `when`(it.products).thenReturn(products) + } private val library = mock(PnLibrary::class.java).also { `when`(it.updates).thenReturn(updates) } private var now = Instant.parse("2026-11-04T10:00:00Z") private val executor = RemoteExecutor(library) { now } @@ -63,6 +70,23 @@ class RemoteExecutorTest { assertTrue(results.single().text.contains("диск полон")) } + @Test + fun `an action that throws is logged as an error and refused`() { + val logger = mock(org.pnfolder.pnlibrary.api.logging.PnLogger::class.java) + val logging = mock(org.pnfolder.pnlibrary.api.logging.LoggingService::class.java) + val owner = Any() + `when`(logging.logger(owner, "link")).thenReturn(logger) + `when`(library.logging).thenReturn(logging) + `when`(library.owner).thenReturn(owner) + val failure = IllegalStateException("update service is down") + `when`(products.get("shop")).thenThrow(failure) + + run(request(action = RemoteAction.UPDATE)) + + org.mockito.Mockito.verify(logger).error(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.eq(failure)) + assertFalse(results.single().ok) + } + @Test fun `a request that was already carried out is refused`() { val same = request() diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkFrameTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkFrameTest.kt new file mode 100644 index 000000000..387665f0b --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkFrameTest.kt @@ -0,0 +1,109 @@ +package org.pnfolder.pnlibrary.core.link.wire + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.core.link.remote.DataCall +import org.pnfolder.pnlibrary.core.link.remote.DataChunk +import org.pnfolder.pnlibrary.core.link.remote.RemoteAction +import org.pnfolder.pnlibrary.core.link.remote.RemoteRequest +import org.pnfolder.pnlibrary.core.link.remote.RemoteResult +import org.pnfolder.pnlibrary.core.link.report.LinkPlugin +import org.pnfolder.pnlibrary.core.link.report.LinkReport +import org.pnfolder.pnlibrary.core.link.report.NetworkReport +import java.time.Duration +import java.time.Instant +import java.time.temporal.ChronoUnit +import java.util.UUID +import java.util.concurrent.atomic.AtomicInteger +import javax.crypto.Mac + +class LinkFrameTest { + private val key = ByteArray(32) { it.toByte() } + private val now = Instant.now().truncatedTo(ChronoUnit.MILLIS) + private val id = UUID(1, 2) + private val report = LinkReport("Paper", "0.1.0", 4, listOf(LinkPlugin("shop", "1.0", "1.1", "UPDATE_AVAILABLE")), now) + private val request = RemoteRequest(id, "lobby", "survival", "admin", RemoteAction.CHECK, null, now) + private val result = RemoteResult(id, "survival", true, "done", now) + private val call = DataCall(id, "lobby", "survival", "admin", "plugins", "{}", now) + private val chunk = DataChunk(id, "survival", true, 0, 1, byteArrayOf(1, 2, 3), now) + + private fun valid(): List = listOf( + LinkCodec.encode(report, key), LinkCodec.encodeRequest(request, key), LinkCodec.encodeResult(result, key), + LinkCodec.encodeCall(call, key), LinkCodec.encodeChunk(chunk, key), + ) + + private fun show(value: Any?): String = when (value) { + null -> "null" + is DataChunk -> "chunk(${value.id},${value.to},${value.ok},${value.index},${value.count},${value.bytes.toList()},${value.sentAt})" + else -> value.toString() + } + + /** The receiver's previous chain: one signature check per decoder until one accepts. */ + private fun chain(message: ByteArray, at: Instant): String = show( + LinkCodec.decode(message, key, at) ?: LinkCodec.decodeRequest(message, key, at) ?: LinkCodec.decodeResult(message, key, at) + ?: LinkCodec.decodeCall(message, key, at) ?: LinkCodec.decodeChunk(message, key, at), + ) + + private fun frame(message: ByteArray, at: Instant, signer: FrameSigner = CachedHmac()): String = show( + when (val decoded = LinkCodec.decodeFrame(message, key, at, signer)) { + null -> null + is LinkFrame.Report -> decoded.report + is LinkFrame.Request -> decoded.request + is LinkFrame.Result -> decoded.result + is LinkFrame.Call -> decoded.call + is LinkFrame.Chunk -> decoded.chunk + }, + ) + + /** Valid frames of every kind, forged, foreign, stale, cut and extended ones. */ + private fun corpus(): List { + val frames = valid() + val other = ByteArray(32) { 9 } + return frames + frames.flatMap { message -> + listOf( + message.copyOf().also { it[0] = (it[0] + 1).toByte() }, + message.copyOf().also { it[5] = (it[5] + 1).toByte() }, + message.copyOf().also { it[message.size - 1] = (it[message.size - 1] + 1).toByte() }, + message.copyOf(message.size - 1), message.copyOf(40), message + byteArrayOf(0), byteArrayOf(), + ) + } + listOf( + LinkCodec.encode(report, other), LinkCodec.encodeRequest(request, other), LinkCodec.encodeChunk(chunk, other), + LinkCodec.encodeNetwork(NetworkReport(report, emptyList(), now, emptyList()), key), + LinkCodec.encodeChunk(DataChunk(id, "x", true, 5, 2, byteArrayOf(), now), key), + ) + } + + @Test + fun `one frame decoder answers exactly as the chain of five decoders did`() { + listOf(now, now.plus(Duration.ofMinutes(10)), now.minus(Duration.ofMinutes(10)), now.plus(Duration.ofMinutes(1))).forEach { at -> + corpus().forEachIndexed { index, message -> assertEquals(chain(message, at), frame(message, at), "frame $index at $at") } + } + valid().forEach { assertNotNull(LinkCodec.decodeFrame(it, key, now)) } + assertNull(LinkCodec.decodeFrame(valid()[0], ByteArray(32) { 7 }, now)) + } + + @Test + fun `a frame of any kind costs one signature check where the chain cost up to five`() { + val checks = AtomicInteger() + val counting = FrameSigner { bytes, signKey -> checks.incrementAndGet(); CachedHmac().sign(bytes, signKey) } + valid().forEach { message -> + checks.set(0) + assertNotNull(LinkCodec.decodeFrame(message, key, now, counting)) + assertEquals(1, checks.get()) + } + } + + @Test + fun `a thread gets one Mac per key however many frames it signs`() { + val created = AtomicInteger() + val signer = CachedHmac { created.incrementAndGet(); Mac.getInstance("HmacSHA256") } + val message = ByteArray(100) { it.toByte() } + val expected = CachedHmac().sign(message, key) + repeat(100) { assertEquals(expected.toList(), signer.sign(message, key).toList()) } + assertEquals(1, created.get()) + signer.sign(message, ByteArray(32) { 5 }) + assertEquals(2, created.get()) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkSecretTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkSecretTest.kt new file mode 100644 index 000000000..cc955d479 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/wire/LinkSecretTest.kt @@ -0,0 +1,28 @@ +package org.pnfolder.pnlibrary.core.link.wire + +import org.junit.jupiter.api.Assertions.assertArrayEquals +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assumptions.assumeTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.attribute.PosixFilePermissions + +class LinkSecretTest { + @Test + fun `creates the key once and reads the same key back`(@TempDir folder: Path) { + val key = LinkSecret.readOrCreate(folder) + assertNotNull(key) + assertArrayEquals(key, LinkSecret.readOrCreate(folder)) + } + + @Test + fun `the key file is private to its owner`(@TempDir folder: Path) { + assumeTrue(folder.fileSystem.supportedFileAttributeViews().contains("posix")) + LinkSecret.readOrCreate(folder) + val permissions = Files.getPosixFilePermissions(folder.resolve(LinkSecret.FILE)) + assertEquals("rw-------", PosixFilePermissions.toString(permissions)) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/wire/ReportWireTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/wire/ReportWireTest.kt new file mode 100644 index 000000000..8d7b36927 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/link/wire/ReportWireTest.kt @@ -0,0 +1,37 @@ +package org.pnfolder.pnlibrary.core.link.wire + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.core.link.report.LinkPlugin +import org.pnfolder.pnlibrary.core.link.report.LinkReport +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.DataInputStream +import java.io.DataOutputStream +import java.time.Instant + +class ReportWireTest { + private fun roundTrip(report: LinkReport, limit: Int): LinkReport { + val bytes = ByteArrayOutputStream() + ReportWire.write(DataOutputStream(bytes), report, limit) + return ReportWire.read(DataInputStream(ByteArrayInputStream(bytes.toByteArray()))) + } + + @Test + fun `a report survives the wire and a missing latest version stays null`() { + val report = LinkReport("paper", "1.2", 7, listOf(LinkPlugin("shop", "1.0", null, "ok")), Instant.ofEpochMilli(1234)) + + val back = roundTrip(report, 10) + + assertEquals(report, back) + assertNull(back.plugins.single().latest) + } + + @Test + fun `only the first plugins up to the limit are sent`() { + val plugins = (1..5).map { LinkPlugin("p$it", "1", "2", "ok") } + + assertEquals(2, roundTrip(LinkReport("paper", "1", 0, plugins, Instant.EPOCH), 2).plugins.size) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticCaptureTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticCaptureTest.kt index 5117fd076..b9bd920bb 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticCaptureTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticCaptureTest.kt @@ -24,7 +24,7 @@ class DiagnosticCaptureTest { capture.observe(owner, level, message, error) } } - capture = DiagnosticCapture(ownership, native, buffer, { _, _, _, _ -> journaled++ }) { _, _, _ -> observed++ } + capture = DiagnosticCapture(ownership, native, buffer, { _, _, _, _, _ -> journaled++ }) { _, _, _ -> observed++ } val error = IllegalStateException("failure") repeat(2) { capture.log(this, LogLevel.ERROR, "command failed", error) } assertEquals(1, printed) @@ -48,7 +48,7 @@ class DiagnosticCaptureTest { val native = object : PlatformLogging { override fun log(owner: Any, level: LogLevel, message: String, error: Throwable?) { printed++ } } - val capture = DiagnosticCapture(ownership, native, buffer, { _, _, _, _ -> journaled++ }) { _, _, _ -> observed++ } + val capture = DiagnosticCapture(ownership, native, buffer, { _, _, _, _, _ -> journaled++ }) { _, _, _ -> observed++ } val error = IllegalStateException("failure") capture.write(this, LogLevel.ERROR, "noisy but harmless", error, false) @@ -71,7 +71,7 @@ class DiagnosticCaptureTest { val native = object : PlatformLogging { override fun log(owner: Any, level: LogLevel, message: String, error: Throwable?) { printed++ } } - val capture = DiagnosticCapture(ownership, native, DiagnosticLogBuffer(), { _, _, _, _ -> journaled++ }) + val capture = DiagnosticCapture(ownership, native, DiagnosticLogBuffer(), { _, _, _, _, _ -> journaled++ }) capture.write(this, LogLevel.DEBUG, "detail", null) capture.write(this, LogLevel.DEBUG, "skipped detail", null, false) @@ -89,7 +89,7 @@ class DiagnosticCaptureTest { Thread { capture.observe(owner, level, message, error) }.apply { start() }.join() } } - capture = DiagnosticCapture(ownership, native, DiagnosticLogBuffer(), { _, _, _, _ -> journaled++ }) + capture = DiagnosticCapture(ownership, native, DiagnosticLogBuffer(), { _, _, _, _, _ -> journaled++ }) capture.log(this, LogLevel.WARNING, "disk is slow", null) assertEquals(1, journaled) @@ -103,8 +103,48 @@ class DiagnosticCaptureTest { val native = object : PlatformLogging { override fun log(owner: Any, level: LogLevel, message: String, error: Throwable?) { printed++ } } - val capture = DiagnosticCapture(ownership, native, journal = { _, _, _, _ -> error("journal") }) { _, _, _ -> error("metrics") } + val capture = DiagnosticCapture(ownership, native, journal = { _, _, _, _, _ -> error("journal") }) { _, _, _ -> error("metrics") } capture.log(this, LogLevel.ERROR, "failure", IllegalStateException()) - assertEquals(1, printed) + // The line itself plus one report for each of the two broken stages. + assertEquals(3, printed) + } + + @Test + fun `a stage that fails is reported once to the console and does not stop the other stages`() { + val buffer = DiagnosticLogBuffer() + val printed = mutableListOf>() + val native = object : PlatformLogging { + override fun log(owner: Any, level: LogLevel, message: String, error: Throwable?) { + printed += level to error + } + } + var reports = 0 + val capture = DiagnosticCapture( + ownership, native, buffer, + journal = { _, _, _, _, _ -> throw IllegalStateException("journal broke") }, + onError = { _, _, _ -> reports++; throw IllegalStateException("report broke") }, + ) + + repeat(2) { capture.log(this, LogLevel.ERROR, "command failed", IllegalArgumentException("boom")) } + + assertEquals(2, reports) + assertEquals(2L, buffer.summary()["occurrenceCount"]) + val failures = printed.filter { (level, error) -> level == LogLevel.ERROR && error is IllegalStateException } + assertEquals(listOf("journal broke", "report broke"), failures.map { it.second?.message }) + } + + @Test + fun `an error logged as text only still reaches the error report`() { + val native = object : PlatformLogging { + override fun log(owner: Any, level: LogLevel, message: String, error: Throwable?) = Unit + } + val reported = mutableListOf>() + val capture = DiagnosticCapture(ownership, native, onError = { _, _, error -> reported += LogLevel.ERROR to error }) + + capture.log(this, LogLevel.ERROR, "text only", null) + capture.log(this, LogLevel.WARNING, "just a warning", null) + + assertEquals(1, reported.size) + assertEquals("text only", reported.single().second.message) } } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticLogBufferRepeatTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticLogBufferRepeatTest.kt new file mode 100644 index 000000000..506086bb3 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/DiagnosticLogBufferRepeatTest.kt @@ -0,0 +1,122 @@ +package org.pnfolder.pnlibrary.core.logging + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.core.diagnostics.redaction.DiagnosticRedactor +import org.pnfolder.pnlibrary.core.diagnostics.redaction.fingerprint +import org.pnfolder.pnlibrary.core.diagnostics.redaction.originFrame +import org.pnfolder.pnlibrary.core.diagnostics.redaction.significantCause +import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership +import java.security.MessageDigest +import java.util.UUID +import java.util.concurrent.atomic.AtomicInteger + +class DiagnosticLogBufferRepeatTest { + private val platform = object : PlatformOwnership { + override fun ownerDetails(owner: Any) = mapOf("name" to "shop") + } + + private class Counting { + val redacts = AtomicInteger() + val fingerprints = AtomicInteger() + private val redactor = DiagnosticRedactor() + + fun buffer() = DiagnosticLogBuffer( + capacity = 100, + redact = { redacts.incrementAndGet(); redactor.redact(it) }, + fingerprintOf = { context, message, error -> + fingerprints.incrementAndGet() + error.fingerprint(context, message) + }, + ) + } + + private fun cause(message: String, method: String) = IllegalStateException(message).apply { + stackTrace = arrayOf(StackTraceElement("ru.shop.Menu", method, "Menu.kt", 10)) + } + + /** What the buffer must report: every record redacted and fingerprinted on its own, as the old code did. */ + private fun expected(records: List>): Map> { + val redactor = DiagnosticRedactor() + val result = LinkedHashMap>() + for ((level, message, error) in records) { + val safe = redactor.redact(message).take(4_096) + val id = error.fingerprint(listOf(redactor.redact("shop").take(96), level.name), safe) + result.merge(id, safe to 1L) { old, _ -> old.first to old.second + 1 } + } + return result + } + + @Test + fun `ten thousand identical records redact and fingerprint once`() { + val counting = Counting() + val buffer = counting.buffer() + val error = cause("database unavailable", "load") + + repeat(10_000) { buffer.record(platform, this, LogLevel.ERROR, "Load failed", error) } + + // plugin name and message are redacted together on the first sight only + assertEquals(2, counting.redacts.get()) + assertEquals(1, counting.fingerprints.get()) + val incident = buffer.snapshot().single() + assertEquals(10_000L, (incident["occurrences"] as Map<*, *>)["count"]) + } + + @Test + fun `repeats with different ids and numbers still fold into the same incidents as before`() { + val records = ArrayList>() + repeat(300) { index -> + records += Triple(LogLevel.WARNING, "Player ${UUID(index.toLong(), 7)} lost ${10_000 + index} coins", null) + records += Triple(LogLevel.ERROR, "Load failed", cause("db down", "load")) + records += Triple(LogLevel.ERROR, "Load failed", cause("db down ${100_000 + index}", "load")) + records += Triple(LogLevel.ERROR, "Load failed", cause("db down", "save")) + records += Triple(LogLevel.WARNING, "token=secret$index at https://example.invalid/$index", null) + records += Triple(LogLevel.ERROR, "Other", null) + } + val counting = Counting() + val buffer = counting.buffer() + records.forEach { (level, message, error) -> buffer.record(platform, this, level, message, error) } + + val want = expected(records) + val got = buffer.snapshot().associate { + it["incidentId"] as String to ((it["message"] as String) to ((it["occurrences"] as Map<*, *>)["count"] as Long)) + } + assertEquals(want, got) + assertTrue(want.size >= 5, "corpus must produce several incidents: ${want.size}") + // identical records skip the SHA-256 step: the old code fingerprinted every one of the 1800 records + assertTrue(counting.fingerprints.get() <= records.size / 2 + 10, "fingerprints: ${counting.fingerprints.get()}") + } + + @Test + fun `fingerprint hex matches the old formatting`() { + val old = { context: List, message: String, error: Throwable? -> + val significant = error.significantCause() + val frame = error.originFrame() + val normalize = { v: String -> + v.replace(Regex("(?i)\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b"), "") + .replace(Regex("\\b\\d{4,}\\b"), "").replace(Regex("\\s+"), " ").trim() + } + val source = (context + listOf( + normalize(message), significant?.javaClass?.name.orEmpty(), normalize(significant?.message.orEmpty()), + frame?.className.orEmpty(), frame?.methodName.orEmpty(), + )).joinToString("\u0000") + MessageDigest.getInstance("SHA-256").digest(source.toByteArray(Charsets.UTF_8)).take(8) + .joinToString("") { "%02x".format(it) } + } + repeat(200) { i -> + val error = if (i % 2 == 0) cause("m$i", "f$i") else null + val context = listOf("plugin$i", "ERROR") + assertEquals(old(context, "message $i", error), error.fingerprint(context, "message $i")) + } + } + + @Test + fun `memory of raw keys stays bounded when every message is unique`() { + val buffer = DiagnosticLogBuffer(capacity = 50) + repeat(20_000) { buffer.record(platform, this, LogLevel.WARNING, "unique message number-$it x", null) } + + assertEquals(50, buffer.snapshot().size) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/ConsoleStyleTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/LogLevelMarksTest.kt similarity index 55% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/ConsoleStyleTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/LogLevelMarksTest.kt index a50654d2e..330c7d07a 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/ConsoleStyleTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/LogLevelMarksTest.kt @@ -4,13 +4,13 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.logging.LogLevel -class ConsoleStyleTest { +class LogLevelMarksTest { @Test fun successIsMarkedAndOtherLevelsAreUntouched() { - assertEquals("[OK] ready", ConsoleStyle.decorate(LogLevel.SUCCESS, "ready")) - assertEquals("[CRITICAL] down", ConsoleStyle.decorate(LogLevel.CRITICAL, "down")) + assertEquals("[OK] ready", LogLevelMarks.decorate(LogLevel.SUCCESS, "ready")) + assertEquals("[CRITICAL] down", LogLevelMarks.decorate(LogLevel.CRITICAL, "down")) listOf(LogLevel.INFO, LogLevel.WARNING, LogLevel.ERROR).forEach { - assertEquals("text", ConsoleStyle.decorate(it, "text")) + assertEquals("text", LogLevelMarks.decorate(it, "text")) } } } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/ModuleLoggingTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/ModuleLoggingTest.kt index f89042df8..d66e4be5f 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/ModuleLoggingTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/logging/ModuleLoggingTest.kt @@ -5,7 +5,7 @@ import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.logging.LogLevel import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.core.ui.ConsoleStyle +import org.pnfolder.pnlibrary.core.text.ConsoleStyle import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter import java.nio.file.Files diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/LibraryMenuTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/LibraryMenuTest.kt index 9edff4347..d51ade898 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/LibraryMenuTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/LibraryMenuTest.kt @@ -6,8 +6,18 @@ import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.core.placeholders.PlaceholderInfo +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.core.menu.data.MenuData +import org.pnfolder.pnlibrary.core.menu.screens.ConfigRow +import org.pnfolder.pnlibrary.core.menu.style.BACK +import org.pnfolder.pnlibrary.core.menu.style.CONFIGS +import org.pnfolder.pnlibrary.core.menu.style.FILTER +import org.pnfolder.pnlibrary.core.menu.style.HOME_CLOSE +import org.pnfolder.pnlibrary.core.menu.style.NEXT +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.menu.style.PLACEHOLDERS +import org.pnfolder.pnlibrary.core.menu.style.PREVIOUS +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderInfo import java.lang.reflect.Proxy import java.util.UUID import java.util.concurrent.CompletableFuture @@ -40,10 +50,11 @@ class LibraryMenuTest { } /** Facts that are all empty, except what a test gives: lists are empty, texts are plain, the rest is nothing. */ - private fun data(placeholders: List = emptyList()): MenuData = + private fun data(placeholders: List = emptyList(), configs: List = emptyList()): MenuData = Proxy.newProxyInstance(MenuData::class.java.classLoader, arrayOf(MenuData::class.java)) { _, method, _ -> when { method.name == "placeholders" -> placeholders + method.name == "configs" -> configs method.returnType == List::class.java -> emptyList() method.returnType == CompletionStage::class.java -> CompletableFuture.completedFuture(emptyList()) method.returnType == String::class.java -> "1.0" @@ -111,4 +122,60 @@ class LibraryMenuTest { assertEquals("Плейсхолдеров нет", viewer.opened.last().items.getValue(22).item!!.name.replace(Regex("§."), "")) } + + private fun file(id: String, editable: Int = 1) = ConfigRow(id, "Model", true, false, editable, null) + + private fun title(menu: Menu) = menu.title.replace(Regex("§."), "") + + @Test + fun `configurations go from plugins to modules to files and back`() { + val viewer = Viewer(setOf(CONFIGS)) + val files = listOf(file("shop/main:a.yml"), file("shop/main:b.yml"), file("shop/vip:c.yml"), file("clans/core:d.yml")) + LibraryMenu(data(configs = files), Host).home(viewer) + click(viewer, viewer.opened.last(), 21) + + val plugins = viewer.opened.last() + assertTrue(title(plugins).contains("Конфигурации")) + assertEquals(2, plugins.items.count { (slot, item) -> slot < PAGE_SIZE && item.item != null && item.handler != null }) + + assertNotNull(plugins.items[FILTER]?.handler) + click(viewer, plugins, FILTER) // every file of every plugin, with plugin and module named + assertEquals(4, viewer.opened.last().items.count { (slot, item) -> slot < PAGE_SIZE && item.item != null && item.handler != null }) + click(viewer, viewer.opened.last(), FILTER) // back to the plugins + + click(viewer, plugins, 0) // clans: one module, so its files are shown at once + assertTrue(title(viewer.opened.last()).contains("clans")) + assertNotNull(viewer.opened.last().items[FILTER]?.handler) // the choice between modules and files is always there + + click(viewer, plugins, 1) // shop: two modules + val shop = viewer.opened.last() + assertEquals(2, shop.items.count { (slot, item) -> slot < PAGE_SIZE && item.item != null && item.handler != null }) + assertNotNull(shop.items[FILTER]?.handler) + + click(viewer, shop, 0) // module main + val main = viewer.opened.last() + assertTrue(title(main).contains("shop · main")) + assertEquals(2, main.items.count { (slot, item) -> slot < PAGE_SIZE && item.item != null && item.handler != null }) + + click(viewer, main, BACK) + assertTrue(title(viewer.opened.last()).contains("shop")) + + click(viewer, shop, FILTER) // every file of the plugin, with its module named + val all = viewer.opened.last() + assertEquals(3, all.items.count { (slot, item) -> slot < PAGE_SIZE && item.item != null && item.handler != null }) + } + + @Test + fun `a plugin with many files is cut into pages`() { + val viewer = Viewer(setOf(CONFIGS)) + val files = (1..50).map { file("big/core:f$it.yml") } + LibraryMenu(data(configs = files), Host).home(viewer) + click(viewer, viewer.opened.last(), 21) + click(viewer, viewer.opened.last(), 0) + + val first = viewer.opened.last() + assertTrue(first.title.contains("1/2")) + click(viewer, first, NEXT) + assertTrue(viewer.opened.last().title.contains("2/2")) + } } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/LibrarySettingsMenuTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/LibrarySettingsMenuTest.kt new file mode 100644 index 000000000..30d553312 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/LibrarySettingsMenuTest.kt @@ -0,0 +1,343 @@ +package org.pnfolder.pnlibrary.core.menu + +import net.kyori.adventure.text.Component +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.core.menu.data.MenuData +import org.pnfolder.pnlibrary.core.menu.data.SettingOutcome +import org.pnfolder.pnlibrary.core.menu.data.SettingRow +import org.pnfolder.pnlibrary.core.menu.style.DATE_FILTER +import org.pnfolder.pnlibrary.core.menu.style.FILTER +import org.pnfolder.pnlibrary.core.menu.style.NEXT +import org.pnfolder.pnlibrary.core.menu.style.PAGE_SIZE +import org.pnfolder.pnlibrary.core.settings.ChoiceSource +import org.pnfolder.pnlibrary.core.settings.LibrarySettings +import org.pnfolder.pnlibrary.core.settings.SettingApply +import org.pnfolder.pnlibrary.core.settings.SettingsRegistry +import java.lang.reflect.Proxy +import java.util.UUID + +class LibrarySettingsMenuTest { + private class Viewer : MenuViewer { + val opened = mutableListOf() + override val id: UUID = UUID.randomUUID() + override val name = "Admin" + override val online = true + override val remote = false + override val actor = UpdateActor(UpdateActor.Kind.PLAYER, id.toString(), name) + override fun hasPermission(permission: String) = true + override fun open(menu: Menu) { opened += menu } + override fun close() {} + val sent = mutableListOf() + override fun send(lines: List) { sent += lines } + override fun runCommand(command: String) {} + } + + private object Host : MenuHost { + override fun sync(action: () -> Unit) = action() + override fun later(delayMillis: Long, action: () -> Unit) = action() + override fun async(action: () -> Unit) = action() + override fun openRemote(viewer: MenuViewer, target: String) = false + override fun owner(owner: Any?): OwnerInfo? = null + override fun ownerNamed(name: String): OwnerInfo? = null + override fun ownerOf(type: Class<*>?): OwnerInfo? = null + } + + private val changes = mutableListOf>() + + private fun rows(current: Map = emptyMap()): List = SettingsRegistry.all.map { spec -> + val value = current[spec.key] ?: spec.valueIn(LibrarySettings()) + SettingRow( + spec.key, spec.title, spec.kind.name, spec.description, value, spec.default, value != spec.default, spec.range(), spec.examples, + spec.applies == SettingApply.LIVE, spec.choices?.id.orEmpty(), + ) + } + + private fun data(settings: List): MenuData = + Proxy.newProxyInstance(MenuData::class.java.classLoader, arrayOf(MenuData::class.java)) { _, method, args -> + when { + method.name == "settings" -> settings + method.name == "changeSetting" -> { + changes += args[0] as String to args[1] as String? + SettingOutcome(true, "ok") + } + method.returnType == List::class.java -> emptyList() + method.returnType == String::class.java -> "1.0" + method.returnType == Int::class.javaPrimitiveType -> 0 + method.returnType == Boolean::class.javaPrimitiveType -> false + else -> null + } + } as MenuData + + private fun plain(text: String) = text.replace(Regex("§."), "") + + private fun click(viewer: Viewer, menu: Menu, slot: Int, how: ClickType = ClickType.LEFT) { + requireNotNull(menu.items.getValue(slot).handler).handle(MenuClick(viewer, slot, how)) + } + + private fun slotNamed(menu: Menu, name: String): Int = + menu.items.entries.first { (_, item) -> item.item?.name?.let(::plain) == name }.key + + private fun loreOf(menu: Menu, name: String): List = requireNotNull(menu.items.getValue(slotNamed(menu, name)).item).lore + + private fun settingsScreen(viewer: Viewer, settings: List): Menu { + LibraryMenu(data(settings), Host).home(viewer) + click(viewer, viewer.opened.last(), 20) + click(viewer, viewer.opened.last(), 22) + return viewer.opened.last() + } + + @Test + fun `a switch shows Russian words and marks the default option in grey italics`() { + val lore = loreOf(settingsScreen(Viewer(), rows()), "Приватность отчёта") + val text = lore.joinToString("\n") { plain(it) } + + assertTrue("включено" in text && "выключено (по умолчанию)" in text, text) + assertFalse("false" in text || "true" in text, text) + assertFalse("По умолчанию" in text, "the mark replaces the separate default line") + assertEquals(1, lore.count { "(по умолчанию)" in it }) + val marked = lore.single { "(по умолчанию)" in it } + assertTrue(marked.endsWith("§o(по умолчанию)"), "the note is italic and comes last") + assertTrue(marked.indexOf("§o") > marked.indexOf("выключено")) + } + + @Test + fun `the default mark follows the default, not the current value`() { + val text = loreOf(settingsScreen(Viewer(), rows(mapOf("downloads.enabled" to "false"))), "Загрузки").joinToString("\n") { plain(it) } + + assertTrue("включено (по умолчанию)" in text, text) + assertTrue("➤ выключено" in text, text) + } + + @Test + fun `a number shows its default only when it was changed`() { + val unchanged = loreOf(settingsScreen(Viewer(), rows()), "Хранение истории").joinToString("\n") { plain(it) } + val after = loreOf(settingsScreen(Viewer(), rows(mapOf("history-retention-days" to "90"))), "Хранение истории").joinToString("\n") { plain(it) } + + assertFalse("По умолчанию" in unchanged, unchanged) + assertTrue("По умолчанию" in after && "90" in after, after) + } + + private fun zoneList(viewer: Viewer, current: String = "Europe/Berlin"): Menu { + val screen = settingsScreen(viewer, rows(mapOf("time-zone" to current))) + click(viewer, screen, slotNamed(screen, "Часовой пояс"), ClickType.SHIFT_LEFT) + return viewer.opened.last() + } + + private fun titleOf(menu: Menu) = plain(menu.title) + + private fun nameAt(menu: Menu, slot: Int) = menu.items.getValue(slot).item?.name?.let(::plain) + + @Test + fun `a time zone opens one list with the time and offset of every zone, the current one green and not clickable`() { + val viewer = Viewer() + val list = zoneList(viewer) + val zones = ChoiceSource.ZONES + + assertTrue(titleOf(list).contains("Часовой пояс "), titleOf(list)) + assertTrue(titleOf(list).endsWith("1/${(zones.all.size - 1) / PAGE_SIZE + 1}"), titleOf(list)) + val first = nameAt(list, 0) + assertEquals(zones.view(0, false, "").first(), first, "the default order is by offset") + val lore = loreOf(list, first.orEmpty()).joinToString("\n") { plain(it) } + assertTrue(Regex("""\[ Сейчас там \] \d\d:\d\d""").containsMatchIn(lore), lore) + assertTrue(Regex("""\[ Смещение \] UTC([+-]\d\d:\d\d)?""").containsMatchIn(lore), lore) + val shown = zones.view(0, false, "") + val berlinPage = shown.indexOf("Europe/Berlin") / PAGE_SIZE + if (berlinPage == 0) assertNull(list.items.getValue(slotNamed(list, "Europe/Berlin")).handler) + assertEquals("Ввести в чате", nameAt(list, DATE_FILTER)) + assertEquals("Сортировка", nameAt(list, FILTER)) + assertEquals("Популярные", nameAt(list, 51)) + assertEquals("Поиск", nameAt(list, 52)) + } + + @Test + fun `the sort button cycles the order with a tooltip of options and the order survives paging`() { + val viewer = Viewer() + val list = zoneList(viewer) + val zones = ChoiceSource.ZONES + val tooltip = loreOf(list, "Сортировка").joinToString("\n") { plain(it) } + + assertTrue("➤ по смещению UTC" in tooltip && "по алфавиту" in tooltip, tooltip) + click(viewer, list, FILTER) + val alphabetical = viewer.opened.last() + assertEquals(zones.all.first(), nameAt(alphabetical, 0)) + assertTrue("➤ по алфавиту" in loreOf(alphabetical, "Сортировка").joinToString("\n") { plain(it) }) + + click(viewer, alphabetical, NEXT) + assertEquals(zones.all[PAGE_SIZE], nameAt(viewer.opened.last(), 0), "the next page keeps the alphabet") + assertTrue(titleOf(viewer.opened.last()).endsWith("2/${(zones.all.size - 1) / PAGE_SIZE + 1}")) + + click(viewer, alphabetical, FILTER) + assertEquals(zones.view(0, false, "").first(), nameAt(viewer.opened.last(), 0), "it cycles back") + } + + @Test + fun `the popular button shows the curated zones in their order and hides the sort`() { + val viewer = Viewer() + val list = zoneList(viewer) + assertTrue("➤ Все" in loreOf(list, "Популярные").joinToString("\n") { plain(it) }) + + click(viewer, list, 51) + val popular = viewer.opened.last() + + assertTrue(titleOf(popular).contains("популярные"), titleOf(popular)) + ChoiceSource.ZONES.popular.forEachIndexed { index, zone -> assertEquals(zone, nameAt(popular, index)) } + assertNull(popular.items[FILTER]?.handler) + assertTrue("➤ Популярные" in loreOf(popular, "Популярные").joinToString("\n") { plain(it) }) + + click(viewer, popular, 51) + assertEquals(ChoiceSource.ZONES.view(0, false, "").first(), nameAt(viewer.opened.last(), 0)) + } + + @Test + fun `a click on a zone writes the setting`() { + val viewer = Viewer() + val list = zoneList(viewer) + click(viewer, list, 51) + val popular = viewer.opened.last() + + click(viewer, popular, slotNamed(popular, "Europe/Moscow")) + + assertEquals(listOf("time-zone" to "Europe/Moscow"), changes) + assertTrue(titleOf(viewer.opened.last()).contains("Параметры библиотеки"), "it returns to the settings") + } + + @Test + fun `pick opens the list narrowed by a filter, the reset button and the wheel on search clear it`() { + val viewer = Viewer() + val menu = LibraryMenu(data(rows()), Host) + + menu.pickSetting(viewer, "time-zone", "new york") + val found = viewer.opened.last() + assertTrue(titleOf(found).contains("«new york»"), titleOf(found)) + assertEquals("America/New_York", nameAt(found, 0)) + assertNull(found.items[1]?.handler, "only one zone matches") + assertEquals("Сбросить поиск", nameAt(found, 51)) + + click(viewer, found, 51) + assertFalse(titleOf(viewer.opened.last()).contains("«")) + assertNotNull(viewer.opened.last().items.getValue(1).handler) + + menu.pickSetting(viewer, "time-zone", "new york") + click(viewer, viewer.opened.last(), 52, ClickType.MIDDLE) + assertFalse(titleOf(viewer.opened.last()).contains("«")) + } + + @Test + fun `a search with no match says nothing was found and a wrong key is answered`() { + val viewer = Viewer() + val menu = LibraryMenu(data(rows()), Host) + + menu.pickSetting(viewer, "time-zone", "qqqq") + assertTrue(viewer.opened.last().items.values.any { it.item?.name?.let(::plain) == "Ничего не найдено" }) + + val before = viewer.opened.size + menu.pickSetting(viewer, "privacy", "") + assertEquals(before, viewer.opened.size, "a setting without a list opens nothing") + } + + @Test + fun `the search button puts the command with the key into the chat`() { + val viewer = Viewer() + val list = zoneList(viewer) + + click(viewer, list, 52) + + val command = viewer.sent.mapNotNull { it.clickEvent()?.value() } + assertEquals(listOf("/pn settings pick time-zone "), command) + } + + private fun zoneTooltip(menu: Menu) = loreOf(menu, "Часовой пояс").map { plain(it) } + + private fun clickZone(viewer: Viewer, current: String, how: ClickType): Menu { + val screen = settingsScreen(viewer, rows(mapOf("time-zone" to current))) + click(viewer, screen, slotNamed(screen, "Часовой пояс"), how) + return screen + } + + @Test + fun `a time zone shows the rolling window over every zone with counts, offset, local time and hints`() { + val text = zoneTooltip(settingsScreen(Viewer(), rows(mapOf("time-zone" to "Europe/Berlin")))).joinToString("\n") + val all = ChoiceSource.ZONES.all + + assertTrue("[ Значение ] Europe/Berlin" in text, text) + assertTrue("[ Вариант ] ${all.indexOf("Europe/Berlin") + 1} из ${all.size}" in text, text) + assertTrue(Regex("""\[ Смещение \] UTC([+-]\d\d:\d\d)?""").containsMatchIn(text), text) + assertTrue(Regex("""\[ Сейчас там \] \d\d:\d\d""").containsMatchIn(text), text) + assertTrue("➤ Europe/Berlin" in text, text) + assertTrue("▲ выше ещё" in text && "▼ ниже ещё" in text, text) + assertTrue("Клик следующий" in text && "Правый клик предыдущий" in text && "Shift + клик весь список" in text, text) + + val here = java.time.ZoneId.systemDefault().id + val unchanged = zoneTooltip(settingsScreen(Viewer(), rows(mapOf("time-zone" to here)))).joinToString("\n") + assertFalse("По умолчанию" in unchanged.substringBefore("➤"), "no default line while the zone is unchanged") + } + + @Test + fun `the window scrolls with the value and shows the lines above`() { + val text = zoneTooltip(settingsScreen(Viewer(), rows(mapOf("time-zone" to "Europe/Moscow")))).joinToString("\n") + + assertTrue("▲ выше ещё" in text && "▼ ниже ещё" in text, text) + assertTrue("➤ Europe/Moscow" in text, text) + } + + @Test + fun `a click rolls to the next zone, a right click to the previous one, and both wrap`() { + val all = ChoiceSource.ZONES.all + clickZone(Viewer(), "Europe/Berlin", ClickType.LEFT) + clickZone(Viewer(), "Europe/Berlin", ClickType.RIGHT) + clickZone(Viewer(), all.last(), ClickType.LEFT) + clickZone(Viewer(), all.first(), ClickType.RIGHT) + + val berlin = all.indexOf("Europe/Berlin") + assertEquals(listOf("time-zone"), changes.map { it.first }.distinct()) + assertEquals(listOf(all[berlin + 1], all[berlin - 1], all.first(), all.last()), changes.map { it.second }) + } + + @Test + fun `a click writes the value and shows the same page again`() { + val viewer = Viewer() + clickZone(viewer, "Europe/Berlin", ClickType.LEFT) + + assertTrue(titleOf(viewer.opened.last()).contains("Параметры библиотеки")) + } + + @Test + fun `an unknown zone is shown first, counted without a number, and a click goes to the first zone`() { + val all = ChoiceSource.ZONES.all + val lines = zoneTooltip(settingsScreen(Viewer(), rows(mapOf("time-zone" to "US/Pacific")))) + val text = lines.joinToString("\n") + + assertTrue("[ Вариант ] — из ${all.size}" in text, text) + assertTrue(lines.any { "US/Pacific" in it && "➤" in it }, text) + + clickZone(Viewer(), "US/Pacific", ClickType.LEFT) + clickZone(Viewer(), "US/Pacific", ClickType.RIGHT) + assertEquals(listOf(all.first(), all.last()), changes.map { it.second }) + } + + @Test + fun `Shift click opens the full list of all zones and writes nothing`() { + val list = zoneList(Viewer(), "Europe/Samara") + + assertTrue(changes.isEmpty()) + assertTrue(titleOf(list).endsWith("1/${(ChoiceSource.ZONES.all.size - 1) / PAGE_SIZE + 1}"), titleOf(list)) + } + + @Test + fun `the wheel resets a changed zone and shows the default only then`() { + val viewer = Viewer() + val screen = settingsScreen(viewer, rows(mapOf("time-zone" to "Asia/Tokyo"))) + val text = zoneTooltip(screen).joinToString("\n") + assertTrue("[ По умолчанию ]" in text && "Колёсико вернуть значение по умолчанию" in text, text) + + click(viewer, screen, slotNamed(screen, "Часовой пояс"), ClickType.MIDDLE) + + assertEquals(listOf("time-zone" to null), changes) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/MenuScreensSmokeTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/MenuScreensSmokeTest.kt new file mode 100644 index 000000000..8466f65b8 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/MenuScreensSmokeTest.kt @@ -0,0 +1,91 @@ +package org.pnfolder.pnlibrary.core.menu + +import net.kyori.adventure.text.Component +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.core.commands.tasks.TaskPeriod +import org.pnfolder.pnlibrary.core.commands.tasks.TaskState +import org.pnfolder.pnlibrary.core.menu.data.MenuData +import org.pnfolder.pnlibrary.core.menu.screens.Filter +import org.pnfolder.pnlibrary.core.stats.StatsSnapshot +import java.lang.reflect.Proxy +import java.util.UUID +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CompletionStage + +/** Opens every list screen over a server that has nothing, so a screen that cannot show emptiness fails here. */ +class MenuScreensSmokeTest { + private class Viewer : MenuViewer { + val opened = mutableListOf() + override val id: UUID = UUID.randomUUID() + override val name = "Admin" + override val online = true + override val remote = false + override val actor = UpdateActor(UpdateActor.Kind.PLAYER, id.toString(), name) + override fun hasPermission(permission: String) = true + override fun open(menu: Menu) { opened += menu } + override fun close() {} + override fun send(lines: List) {} + override fun runCommand(command: String) {} + } + + private object Host : MenuHost { + override fun sync(action: () -> Unit) = action() + override fun later(delayMillis: Long, action: () -> Unit) = action() + override fun async(action: () -> Unit) = action() + override fun openRemote(viewer: MenuViewer, target: String) = false + override fun owner(owner: Any?): OwnerInfo? = null + override fun ownerNamed(name: String): OwnerInfo? = null + override fun ownerOf(type: Class<*>?): OwnerInfo? = null + } + + private fun emptyData(): MenuData = + Proxy.newProxyInstance(MenuData::class.java.classLoader, arrayOf(MenuData::class.java)) { _, method, _ -> + when { + method.name == "stats" -> StatsSnapshot(0, 0, 0, 0, 0, 0, 0, 0, 0, emptyList()) + method.returnType == List::class.java -> emptyList() + method.returnType == Map::class.java -> emptyMap() + method.returnType == CompletionStage::class.java -> CompletableFuture.completedFuture(emptyList()) + method.returnType == String::class.java -> "1.0" + method.returnType == Int::class.javaPrimitiveType -> 0 + method.returnType == Long::class.javaPrimitiveType -> 0L + method.returnType == Boolean::class.javaPrimitiveType -> false + else -> null + } + } as MenuData + + @Test + fun `list screens open on an empty server`() { + val viewer = Viewer() + val router = MenuRouter(MenuSession(emptyData(), Host)) + val screens = mapOf Unit>( + "plugins" to { router.plugins(viewer, Filter.ALL, 0) }, + "history" to { router.history(viewer, null, 0) }, + "backups" to { router.backups(viewer, 0) }, + "journal" to { router.journal(viewer, null, 0) }, + "tasks" to { router.tasks(viewer, TaskPeriod.TODAY, TaskState.ALL, 0) }, + "modules" to { router.modules(viewer, null, 0) { } }, + "libraries" to { router.libraries(viewer, null, 0) { } }, + "disk" to { router.disk(viewer, 0) { } }, + "groups" to { router.groups(viewer, 0) }, + "placeholders" to { router.placeholders(viewer, 0) }, + "configs" to { router.configs(viewer, 0) }, + "missing" to { router.missingPlugins(viewer, 0) }, + "home" to { router.home(viewer) }, + "settings" to { router.settings(viewer) }, + "tools" to { router.tools(viewer) }, + "support" to { router.support(viewer) }, + "stats" to { router.stats(viewer) }, + "network" to { router.network(viewer, 0) }, + "bus" to { router.busHome(viewer) }, + "busDays" to { router.busDays(viewer, null, 0) }, + "busTraces" to { router.busTraces(viewer, null, 0) }, + "librarySettings" to { router.librarySettings(viewer, 0) }, + ) + val failed = screens.filter { (_, open) -> runCatching(open).isFailure }.keys + + assertTrue(failed.isEmpty(), "screens failed on an empty server: $failed") + assertTrue(viewer.opened.size >= screens.size - 4) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/MenuSessionTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/MenuSessionTest.kt new file mode 100644 index 000000000..6f2b1ffbc --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/MenuSessionTest.kt @@ -0,0 +1,91 @@ +package org.pnfolder.pnlibrary.core.menu + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.mockito.Mockito.mock +import org.mockito.Mockito.verify +import org.mockito.Mockito.`when` +import org.pnfolder.pnlibrary.core.menu.data.MenuData +import org.pnfolder.pnlibrary.core.menu.style.Row + +class MenuSessionTest { + private fun item(name: String) = ItemSpec(null, "STONE", null, name, emptyList()) + + private fun anyMenu(): Menu = org.mockito.ArgumentMatchers.any(Menu::class.java) ?: Menu("", 1, emptyMap()) + + private fun session() = MenuSession(mock(MenuData::class.java), mock(MenuHost::class.java)) + + private fun shown(session: MenuSession, rows: List, page: Int, perPage: Int = 3, total: Int = rows.size): Menu { + val viewer = mock(MenuViewer::class.java) + var menu: Menu? = null + org.mockito.Mockito.doAnswer { menu = it.getArgument(0); null }.`when`(viewer).open(anyMenu()) + session.list(viewer, "Список", rows, page, perPage, { _, _ -> }, { }, "пусто", total) + return menu!! + } + + @Test + fun `builder refuses slots outside the chest and more than six rows`() { + assertThrows(IllegalArgumentException::class.java) { Menus.chest("t").rows(7) } + assertThrows(IllegalArgumentException::class.java) { Menus.chest("t").rows(1).slot(9, item("x")) } + } + + @Test + fun `fill never overwrites a slot that is already set`() { + val menu = Menus.chest("t").rows(1).slot(0, item("own")).fill(item("pane")).build() + + assertEquals("own", menu.items.getValue(0).item!!.name) + assertEquals("pane", menu.items.getValue(1).item!!.name) + assertEquals(9, menu.items.size) + } + + @Test + fun `a middle page shows only its rows and both page buttons`() { + val rows = (1..7).map { Row(item("r$it")) } + + val menu = shown(session(), rows, page = 1) + + assertEquals("r4", menu.items.getValue(0).item!!.name) + assertEquals("r6", menu.items.getValue(2).item!!.name) + assertTrue(menu.title.contains("2/3")) + assertNotNull(menu.items.getValue(48).handler) + assertNotNull(menu.items.getValue(50).handler) + } + + @Test + fun `an empty list says so and a page past the end is pulled back`() { + val empty = shown(session(), emptyList(), page = 5) + assertTrue(empty.items.getValue(22).item!!.name.replace(Regex("§."), "").contains("пусто")) + assertTrue(empty.title.contains("1/1")) + + val last = shown(session(), (1..4).map { Row(item("r$it")) }, page = 99) + assertTrue(last.title.contains("2/2")) + assertNull(last.items.getValue(50).handler) + } + + @Test + fun `without the right the player gets a refusal and the action does not run`() { + val viewer = mock(MenuViewer::class.java) + var ran = false + + session().allowed(viewer, "pnlibrary.tasks") { ran = true } + + assertFalse(ran) + verify(viewer).send(org.mockito.ArgumentMatchers.anyList()) + } + + @Test + fun `an administrator passes every check`() { + val viewer = mock(MenuViewer::class.java) + `when`(viewer.hasPermission("pnlibrary.admin")).thenReturn(true) + var ran = false + + session().allowed(viewer, "pnlibrary.tasks") { ran = true } + + assertTrue(ran) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/MenuDataTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuDataTest.kt similarity index 63% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/MenuDataTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuDataTest.kt index e72479c8e..5b45ec31c 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/MenuDataTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/data/MenuDataTest.kt @@ -1,37 +1,38 @@ -package org.pnfolder.pnlibrary.core.menu +package org.pnfolder.pnlibrary.core.menu.data import net.kyori.adventure.text.Component import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.events.EventDay -import org.pnfolder.pnlibrary.api.events.EventTrace -import org.pnfolder.pnlibrary.api.events.ListenerInfo +import org.pnfolder.pnlibrary.api.events.inspect.ListenerInfo +import org.pnfolder.pnlibrary.api.events.inspect.history.EventDay +import org.pnfolder.pnlibrary.api.events.inspect.trace.EventTrace import org.pnfolder.pnlibrary.api.plugin.ModuleId import org.pnfolder.pnlibrary.api.plugin.PluginId -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskId -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskStatus -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackupComponent -import org.pnfolder.pnlibrary.api.updates.backup.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ProductChange import org.pnfolder.pnlibrary.api.updates.release.ReleaseSummary +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.core.journal.JournalGroup -import org.pnfolder.pnlibrary.core.link.DataCall -import org.pnfolder.pnlibrary.core.link.DataChunks -import org.pnfolder.pnlibrary.core.link.DataClient -import org.pnfolder.pnlibrary.core.link.LinkCodec import org.pnfolder.pnlibrary.core.link.ServerGroups +import org.pnfolder.pnlibrary.core.link.remote.DataCall +import org.pnfolder.pnlibrary.core.link.remote.DataClient +import org.pnfolder.pnlibrary.core.link.wire.DataChunks +import org.pnfolder.pnlibrary.core.link.wire.LinkCodec +import org.pnfolder.pnlibrary.core.menu.OwnerInfo import org.pnfolder.pnlibrary.core.tasks.TaskControl import java.lang.reflect.Proxy import java.time.Duration @@ -60,56 +61,56 @@ class MenuDataTest { private val listener = ListenerInfo(PluginId.of("shop"), ModuleId.of("core"), "a.b.Event", 3, true, "x", 10, 1, 500, 900) private val trace = EventTrace("a.b.Event", true, "ok", listOf(EventTrace.Step(PluginId.of("shop"), null, 1, false, false, 5, "a", "b")), at = now) - private fun roundTrip(value: T, type: java.lang.reflect.Type): T = MenuCalls.gson.fromJson(MenuCalls.gson.toJson(value), type) + private fun roundTrip(value: T, type: java.lang.reflect.Type): T = MenuWire.gson.fromJson(MenuWire.gson.toJson(value), type) @Test fun `update data survives the trip as json`() { - val back = roundTrip(listOf(snapshot), MenuCalls.typeOf>()).single() + val back = roundTrip(listOf(snapshot), MenuWire.typeOf>()).single() assertEquals("shop", back.product) assertEquals(UpdateState.UPDATE_AVAILABLE, back.state) assertEquals(ApiVersionRange(1, 2), back.supportedApi) assertEquals(now, back.availableReleases.single().publishedAt) - val history = roundTrip(listOf(entry), MenuCalls.typeOf>()).single() + val history = roundTrip(listOf(entry), MenuWire.typeOf>()).single() assertEquals(entry.id, history.id) assertEquals("shop", history.changes.single().product.value) assertEquals(SemanticVersion.parse("1.1.0"), history.changes.single().to) assertEquals("Admin", history.actor.name) - val saved = roundTrip(listOf(backup), MenuCalls.typeOf>()).single() + val saved = roundTrip(listOf(backup), MenuWire.typeOf>()).single() assertEquals("1.0.0", saved.components.single().backupVersion) assertEquals(3, saved.configurationFiles) } @Test fun `task and event data survive the trip as json`() { - val tasks = roundTrip(listOf(task), MenuCalls.typeOf>()).single() + val tasks = roundTrip(listOf(task), MenuWire.typeOf>()).single() assertEquals("shop:save", tasks.id.value) assertEquals(Duration.ofMinutes(5), tasks.interval) assertEquals(setOf("a"), tasks.tags) assertEquals(false, tasks.cancellable) - val listeners = roundTrip(listOf(listener), MenuCalls.typeOf>()).single() + val listeners = roundTrip(listOf(listener), MenuWire.typeOf>()).single() assertEquals("shop", listeners.plugin.value) assertEquals("core", listeners.module?.value) assertEquals(900, listeners.maxNanos) - val traces = roundTrip(listOf(trace), MenuCalls.typeOf>()).single() + val traces = roundTrip(listOf(trace), MenuWire.typeOf>()).single() assertEquals("shop", traces.steps.single().plugin.value) assertEquals(now, traces.at) - val day = roundTrip(listOf(EventDay(LocalDate.of(2026, 10, 30), "a.b.Event", 5, 1)), MenuCalls.typeOf>()).single() + val day = roundTrip(listOf(EventDay(LocalDate.of(2026, 10, 30), "a.b.Event", 5, 1)), MenuWire.typeOf>()).single() assertEquals(LocalDate.of(2026, 10, 30), day.date) - val about = roundTrip(EventAbout("p", "u", OwnerInfo("shop", "1.0", listOf("me"))), MenuCalls.typeOf()) + val about = roundTrip(EventAbout("p", "u", OwnerInfo("shop", "1.0", listOf("me"))), MenuWire.typeOf()) assertEquals(listOf("me"), about?.owner?.authors) - val plan = roundTrip(PlanInfo(UpdateState.BLOCKED, true, listOf("busy")), MenuCalls.typeOf()) + val plan = roundTrip(PlanInfo(UpdateState.BLOCKED, true, listOf("busy")), MenuWire.typeOf()) assertEquals(listOf("busy"), plan?.blockers) } /** A server whose facts are canned, and whose answers travel through the real link code. */ - private fun connected(vararg answers: Pair): RemoteMenuData { + private fun connected(vararg answers: Pair, holds: (String, String) -> Boolean = { _, _ -> true }): RemoteMenuData { val canned = answers.toMap() val seen = mutableListOf() val data = Proxy.newProxyInstance(MenuData::class.java.classLoader, arrayOf(MenuData::class.java)) { _, method, args -> @@ -122,7 +123,7 @@ class MenuDataTest { else -> value } } as MenuData - val server = MenuDataServer(data) { it.run() } + val server = MenuDataServer(data, { it.run() }, holds) lateinit var client: DataClient client = DataClient(key) { bytes -> val call: DataCall = LinkCodec.decodeCall(bytes, key)!! @@ -160,7 +161,7 @@ class MenuDataTest { @Test fun `the placeholders of a server travel through the link`() { - val info = org.pnfolder.pnlibrary.core.placeholders.PlaceholderInfo("pnclans/war:score", "Integer", "number", listOf("cl_war~score"), true) + val info = org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderInfo("pnclans/war:score", "Integer", "number", listOf("cl_war~score"), true) over("placeholders" to listOf(info)) { remote -> assertEquals(listOf(info), remote.placeholders()) } @@ -184,4 +185,34 @@ class MenuDataTest { assertEquals(listOf(Component.text("printed pn events full g1")), lines) } } + + @Test + fun `dangerous actions need a permission that this server confirms, not one the request claims`() { + val actor = UpdateActor(UpdateActor.Kind.PLAYER, "id", "Admin") + val denied = connected("rollback" to true, "command" to emptyList(), holds = { _, _ -> false }) + val error = org.junit.jupiter.api.Assertions.assertThrows(Exception::class.java) { + denied.rollback(UUID.randomUUID(), false, actor).toCompletableFuture().get() + } + assertTrue(generateSequence(error) { it.cause }.any { it.message?.contains("pnlibrary.updates.rollback") == true }) + + val granted = connected("rollback" to true, holds = { viewer, permission -> viewer == "Admin" && permission == "pnlibrary.updates.rollback" }) + assertTrue(granted.rollback(UUID.randomUUID(), false, actor).toCompletableFuture().get()) + } + + @Test + fun `settings travel through the link and a change needs the settings permission`() { + val actor = UpdateActor(UpdateActor.Kind.PLAYER, "id", "Admin") + val row = SettingRow("privacy", "Приватность отчёта", "SWITCH", "Прятать данные.", "false", "false", false, "", emptyList(), false) + val zone = SettingRow("time-zone", "Часовой пояс", "CHOICE", "Пояс.", "UTC", "UTC", false, "", listOf("UTC"), true, "zones") + val granted = connected( + "settings" to listOf(row, zone), "changeSetting" to SettingOutcome(true, "true", false), + holds = { viewer, permission -> viewer == "Admin" && permission == "pnlibrary.settings" }, + ) + assertEquals(listOf(row, zone), granted.settings()) + assertEquals(SettingOutcome(true, "true", false), granted.changeSetting("privacy", "true", actor)) + + val denied = connected("changeSetting" to SettingOutcome(true, "true"), holds = { _, _ -> false }) + val error = org.junit.jupiter.api.Assertions.assertThrows(Exception::class.java) { denied.changeSetting("privacy", "true", actor) } + assertTrue(generateSequence(error) { it.cause }.any { it.message?.contains("pnlibrary.settings") == true }) + } } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/style/ConfigLookTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/style/ConfigLookTest.kt new file mode 100644 index 000000000..5962c8340 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/style/ConfigLookTest.kt @@ -0,0 +1,56 @@ +package org.pnfolder.pnlibrary.core.menu.style + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.core.menu.screens.ConfigRow + +class ConfigLookTest { + private fun plain(text: String) = text.replace(Regex("§."), "") + + @Test + fun `a path is cut between its parts and never inside a name`() { + val path = "C:/Users/lpvan/Downloads/Server/Paper-Standalone/plugins/pnTest/external" + + val lines = ConfigLook.fact("Папка", path) + + assertEquals(path, lines.joinToString("") { it.second }) + assertEquals("Папка", lines.first().first) + assertTrue(lines.drop(1).all { it.first.isEmpty() }) + assertTrue(lines.dropLast(1).all { it.second.endsWith("/") }) + assertTrue(lines.all { it.second.length <= 38 }) + } + + @Test + fun `a class name breaks after its dots and a sentence keeps its words whole`() { + val classLines = ConfigLook.fact("Класс", "org.pnfolder.pnlibrary.example.configuration.VeryLongConfigurationClassName") + assertEquals("org.pnfolder.pnlibrary.example.configuration.VeryLongConfigurationClassName", classLines.joinToString("") { it.second }) + assertTrue(classLines.dropLast(1).all { it.second.endsWith(".") }) + + val words = "очень длинное значение которое никак не помещается в одну строку описания предмета" + val lines = ConfigLook.fact("Значение", words).map { it.second } + assertEquals(words.split(" "), lines.flatMap { it.split(" ") }) + } + + @Test + fun `a word longer than a whole line is cut as the last resort`() { + val lines = ConfigLook.softWrap("a".repeat(100), 20, 30) + + assertEquals("a".repeat(100), lines.joinToString("")) + assertTrue(lines.drop(1).all { it.length <= 30 } && lines.first().length <= 20) + } + + @Test + fun `a file shows its own name and names its plugin and module only when asked`() { + val row = ConfigRow("shop/main:sub/rewards.yml", "dev.shop.RewardsConfig", true, false, 2, null) + + val alone = ConfigLook.file(row, "shop", "main", "sub/rewards.yml", withPlugin = false, withModule = false) + val mixed = ConfigLook.file(row, "shop", "main", "sub/rewards.yml", withPlugin = true, withModule = true) + + assertTrue(plain(alone.name).endsWith("rewards.yml") && !plain(alone.name).contains("shop")) + assertTrue(alone.lore.none { plain(it).contains("Плагин") }) + assertTrue(mixed.lore.any { plain(it).contains("Плагин") } && mixed.lore.any { plain(it).contains("Модуль") }) + assertTrue(mixed.lore.any { plain(it).contains("Папка") }) + assertTrue(mixed.lore.any { plain(it).contains("dev.shop.RewardsConfig") }) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/style/ConfigNumbersTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/style/ConfigNumbersTest.kt new file mode 100644 index 000000000..2cf2804af --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/style/ConfigNumbersTest.kt @@ -0,0 +1,42 @@ +package org.pnfolder.pnlibrary.core.menu.style + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.config.ConfigSetting +import org.pnfolder.pnlibrary.api.config.ConfigSettingKind +import java.util.concurrent.TimeUnit + +class ConfigNumbersTest { + private fun number(value: String, step: Double = 1.0, unit: String = "", duration: TimeUnit? = null, min: Double? = null, max: Double? = null) = + ConfigSetting("p", "Число", "", ConfigSettingKind.INTEGER, value, min = min, max = max, step = step, unit = unit, duration = duration) + + @Test + fun `a time is written out in words`() { + assertEquals("5400 сек (1 ч 30 мин)", ConfigNumbers.shown(number("5400", duration = TimeUnit.SECONDS))) + assertEquals("0 с", ConfigNumbers.human(0)) + } + + @Test + fun `steps of seconds go through minutes to an hour`() { + val labels = ConfigNumbers.ladder(number("30", duration = TimeUnit.SECONDS)).map { it.first } + + assertEquals(listOf("1 с", "1 мин", "10 мин", "1 ч"), labels) + assertEquals(60.0, ConfigNumbers.ladder(number("30", duration = TimeUnit.SECONDS))[1].second) + } + + @Test + fun `a plain number steps by its step, ten times, a hundred and a thousand`() { + val ladder = ConfigNumbers.ladder(number("10", step = 5.0, unit = "блоков")) + + assertEquals(listOf("5 блоков", "50 блоков", "500 блоков", "5000 блоков"), ladder.map { it.first }) + } + + @Test + fun `steps wider than the bounds are dropped but two always remain`() { + val ladder = ConfigNumbers.ladder(number("5", min = 0.0, max = 20.0)) + + assertTrue(ladder.size >= 2) + assertTrue(ladder.all { it.second <= 20.0 || it.second == 10.0 }) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuTextTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuTextTest.kt new file mode 100644 index 000000000..050946352 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/menu/style/MenuTextTest.kt @@ -0,0 +1,44 @@ +package org.pnfolder.pnlibrary.core.menu.style + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.time.Duration +import java.time.Instant + +class MenuTextTest { + @Test + fun `time left picks the two largest units and never shows zero minutes`() { + assertEquals("1 мин", timeLeft(Duration.ofSeconds(5))) + assertEquals("2 ч 10 мин", timeLeft(Duration.ofMinutes(130))) + assertEquals("3 д 4 ч", timeLeft(Duration.ofHours(76))) + } + + @Test + fun `ago speaks of the past and the future`() { + val now = Instant.now() + + assertEquals("только что", ago(now.minusSeconds(10))) + assertEquals("5 мин назад", ago(now.minus(Duration.ofMinutes(5)).minusSeconds(5))) + assertTrue(ago(now.plus(Duration.ofHours(3))).startsWith("через ")) + } + + @Test + fun `progress bar is never empty and never longer than the widest bar`() { + val widest = progressBar(100, 100).length + + assertEquals(1, progressBar(0, 100).length) + assertEquals(widest, progressBar(500, 100).length) + assertEquals(1, progressBar(0, 0).length) + } + + @Test + fun `every menu permission is listed once`() { + val declared = MenuPermissions::class.java.declaredFields + .filter { it.type == String::class.java && java.lang.reflect.Modifier.isStatic(it.modifiers) } + .map { it.also { f -> f.isAccessible = true }.get(null) as String } + + assertEquals(declared.toSet(), MenuPermissions.ALL.toSet()) + assertEquals(MenuPermissions.ALL.size, MenuPermissions.ALL.toSet().size) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/AbstractMetricsSessionTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/AbstractMetricsSessionTest.kt index db39bacc8..cb7cef00a 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/AbstractMetricsSessionTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/AbstractMetricsSessionTest.kt @@ -4,7 +4,8 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.metrics.MetricsCredentials +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsCredentials +import org.pnfolder.pnlibrary.core.metrics.session.AbstractMetricsSession import java.util.function.Supplier class AbstractMetricsSessionTest { diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/CompositePluginMetricsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/CompositePluginMetricsTest.kt index 6f0579d09..02ccbd379 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/CompositePluginMetricsTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/CompositePluginMetricsTest.kt @@ -3,10 +3,11 @@ package org.pnfolder.pnlibrary.core.metrics import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider import org.pnfolder.pnlibrary.api.metrics.PluginMetrics -import org.pnfolder.pnlibrary.api.metrics.TelemetryError +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.error.TelemetryError +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.core.metrics.factory.CompositePluginMetrics import java.util.concurrent.atomic.AtomicInteger import java.util.function.Supplier diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/ErrorPipelineRedactionTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/ErrorPipelineRedactionTest.kt new file mode 100644 index 000000000..41c725eb2 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/ErrorPipelineRedactionTest.kt @@ -0,0 +1,45 @@ +package org.pnfolder.pnlibrary.core.metrics + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.error.TelemetryError +import java.util.UUID + +class ErrorPipelineRedactionTest { + /** The four replacements exactly as they were written inline before the patterns became constants. */ + private fun legacy(value: String?): String? = value + ?.replace(Regex("(?i)(Bearer\\s+)[A-Za-z0-9._~+/=-]+"), "$1[redacted]") + ?.replace(Regex("(?i)([?&](?:api_?key|token|secret)=)[^&\\s]+"), "$1[redacted]") + ?.replace(Regex("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"), "[uuid]") + ?.replace(Regex("(?i)(/home/|/Users/|C:\\\\Users\\\\)[^/\\\\\\s]+"), "$1[user]") + + @Test + fun `sanitized text equals the old inline regex result on a fixed corpus`() { + val corpus = listOf( + "Bearer abc.def-123 failed", + "GET /x?api_key=SECRET&token=t0k&other=1", + "player ${UUID(1, 2)} and ${UUID(3, 4).toString().uppercase()}", + "C:\\Users\\alice\\plugin\\Main.kt:10", + "/home/bob/server/plugins/a.jar and /Users/carol/x", + "nothing to hide", + "", + ) + val received = mutableListOf() + val pipeline = ErrorPipeline(object : ErrorReporter { + override fun capture(error: TelemetryError) { received += error } + override fun close() = Unit + }) + + corpus.forEachIndexed { index, text -> + pipeline.capture(TelemetryError("T$index", text, listOf(text), handled = true, attributes = mapOf("k" to text))) + } + + assertEquals(corpus.size, received.size) + corpus.forEachIndexed { index, text -> + assertEquals(legacy(text), received[index].message) + assertEquals(listOf(legacy(text)), received[index].stackTrace) + assertEquals(legacy(text), received[index].attributes["k"]) + } + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/ErrorPipelineTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/ErrorPipelineTest.kt index 20bf68de2..22be1e6a7 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/ErrorPipelineTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/ErrorPipelineTest.kt @@ -2,8 +2,8 @@ package org.pnfolder.pnlibrary.core.metrics import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter -import org.pnfolder.pnlibrary.api.metrics.TelemetryError +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.error.TelemetryError class ErrorPipelineTest { @Test @@ -31,4 +31,19 @@ class ErrorPipelineTest { assertEquals("Bearer [redacted]?token=[redacted]", received.single().message) assertEquals("C:\\Users\\[user]\\plugin\\Main.kt:10", received.single().stackTrace.single()) } + + @Test + fun `a failing tracker is reported once and does not reach the caller`() { + val failures = mutableListOf() + val delegate = object : ErrorReporter { + override fun capture(error: TelemetryError) = throw IllegalStateException("tracker is down") + override fun close() = Unit + } + val pipeline = ErrorPipeline(delegate, onForwardingFailure = { failures += it }) + + repeat(2) { index -> pipeline.capture(TelemetryError("a.Error", "failure $index", emptyList(), handled = true)) } + + assertEquals(listOf("tracker is down"), failures.map { it.message }) + assertEquals(2L, pipeline.diagnosticSnapshot()["forwardingFailures"]) + } } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/MetricsSessionsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/MetricsSessionsTest.kt similarity index 94% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/MetricsSessionsTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/MetricsSessionsTest.kt index 52d01fcc1..c503cd9aa 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/MetricsSessionsTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/MetricsSessionsTest.kt @@ -1,14 +1,14 @@ -package org.pnfolder.pnlibrary.core +package org.pnfolder.pnlibrary.core.metrics import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.core.metrics.MetricsSessions +import org.pnfolder.pnlibrary.core.metrics.session.MetricsSessions import org.pnfolder.pnlibrary.spi.metrics.PlatformMetricsFactory import java.util.concurrent.Executors import java.util.concurrent.TimeUnit diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/NativePluginMetricsFactoryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/NativePluginMetricsFactoryTest.kt index 71d5b7856..0e6fe311a 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/NativePluginMetricsFactoryTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/NativePluginMetricsFactoryTest.kt @@ -3,8 +3,9 @@ package org.pnfolder.pnlibrary.core.metrics import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration +import org.pnfolder.pnlibrary.core.metrics.factory.NativePluginMetricsFactory import org.pnfolder.pnlibrary.spi.metrics.NoopMetricsFactory class NativePluginMetricsFactoryTest { diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/ProviderMetricsFactoryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/ProviderMetricsFactoryTest.kt index e947bf1c3..da8a3874a 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/ProviderMetricsFactoryTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/metrics/ProviderMetricsFactoryTest.kt @@ -5,9 +5,11 @@ import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration +import org.pnfolder.pnlibrary.core.metrics.factory.CompositePluginMetrics +import org.pnfolder.pnlibrary.core.metrics.factory.ProviderMetricsFactory import org.pnfolder.pnlibrary.spi.metrics.NoopMetricsFactory class ProviderMetricsFactoryTest { diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/CompatibilityAdapterTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/CompatibilityAdapterTest.kt index 132599804..63a4e2821 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/CompatibilityAdapterTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/CompatibilityAdapterTest.kt @@ -3,29 +3,28 @@ package org.pnfolder.pnlibrary.core.observability import org.junit.jupiter.api.Assertions.assertArrayEquals import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.activity.ActivityCategory -import org.pnfolder.pnlibrary.api.activity.ActivityEvent -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticLevel -import org.pnfolder.pnlibrary.api.observability.ObservationLevel -import org.pnfolder.pnlibrary.api.observability.ObservationRequest +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticLevel +import org.pnfolder.pnlibrary.api.observability.observation.ObservationLevel +import org.pnfolder.pnlibrary.api.observability.observation.ObservationRequest import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticsRegistry +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths import java.nio.file.Files class CompatibilityAdapterTest { @Test - fun `new and activity entry points share one journal`() { - val runtime = ObservabilityRuntime(Files.createTempDirectory("compatibility")) + fun `observation records land in one journal in order`() { + val runtime = ObservabilityRuntime(LibraryPaths(Files.createTempDirectory("compatibility"))) val service = ObservabilityHub(DiagnosticsRegistry(), runtime) service.record(ObservationRequest(message = "new", level = ObservationLevel.NOTICE)) - service.record(ActivityEvent(type = "legacy", category = ActivityCategory.DIAGNOSTICS)) + service.record(ObservationRequest(message = "second")) - assertEquals(listOf("new", "legacy"), runtime.recent().map { it.message }) + assertEquals(listOf("new", "second"),runtime.recent().map { it.message }) } @Test fun `one diagnostic call creates one observation`() { - val runtime = ObservabilityRuntime(Files.createTempDirectory("diagnostic-compatibility")) + val runtime = ObservabilityRuntime(LibraryPaths(Files.createTempDirectory("diagnostic-compatibility"))) val registry = DiagnosticsRegistry() val service = ObservabilityHub(registry, runtime) registry.onActivityEvent { plugin, level, component, code, message, error, fields -> @@ -50,14 +49,13 @@ class CompatibilityAdapterTest { } @Test - fun `legacy byte attachment keeps its declared metadata without a temporary file`() { - val runtime = ObservabilityRuntime(Files.createTempDirectory("byte-attachment")) - val service = ObservabilityHub(DiagnosticsRegistry(), runtime) + fun `byte attachment keeps its declared metadata without a temporary file`() { + val runtime = ObservabilityRuntime(LibraryPaths(Files.createTempDirectory("byte-attachment"))) val bytes = "server output".toByteArray() - val attachment = service.attach("event-1", "latest.log", "text/x-log", bytes) + val attachment = runtime.attachBytes("event-1", "latest.log", "text/x-log", bytes) - assertEquals("latest.log", attachment.name) + assertEquals("latest.log", attachment.originalName) assertEquals("text/x-log", attachment.contentType) assertArrayEquals(bytes, runtime.attachmentBytes(runtime.attachments("event-1").single())) } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityRuntimeTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityRuntimeTest.kt index e6efd192e..c52b7926e 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityRuntimeTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/ObservabilityRuntimeTest.kt @@ -3,9 +3,11 @@ package org.pnfolder.pnlibrary.core.observability import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.observability.ComponentStatus -import org.pnfolder.pnlibrary.api.observability.ObservationLevel -import org.pnfolder.pnlibrary.api.observability.ObservationQuery +import org.pnfolder.pnlibrary.api.observability.observation.ObservationLevel +import org.pnfolder.pnlibrary.api.observability.observation.ObservationQuery +import org.pnfolder.pnlibrary.api.observability.report.ComponentStatus +import org.pnfolder.pnlibrary.core.observability.report.reportSnapshot +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths import java.nio.file.Files import java.util.concurrent.Executors import java.util.concurrent.TimeUnit @@ -15,7 +17,7 @@ class ObservabilityRuntimeTest { fun `capture stores one normalized observation and its files`() { val root = Files.createTempDirectory("observability-runtime") val log = root.resolve("latest.log").also { Files.writeString(it, "failure details") } - val runtime = ObservabilityRuntime(root, clock = { 123L }) + val runtime = ObservabilityRuntime(LibraryPaths(root), clock = { 123L }) val captured = runtime.capture { plugin("acceptance") @@ -33,7 +35,7 @@ class ObservabilityRuntimeTest { @Test fun `failure is recorded once with error details`() { val root = Files.createTempDirectory("observability-failure") - val runtime = ObservabilityRuntime(root) + val runtime = ObservabilityRuntime(LibraryPaths(root)) runtime.failure(IllegalStateException("database unavailable")) { plugin("acceptance") @@ -49,7 +51,7 @@ class ObservabilityRuntimeTest { @Test fun `status replaces the previous value for the same component`() { - val runtime = ObservabilityRuntime(Files.createTempDirectory("observability-status")) + val runtime = ObservabilityRuntime(LibraryPaths(Files.createTempDirectory("observability-status"))) runtime.status(ComponentStatus("acceptance", "database", "starting")) val ready = runtime.status(ComponentStatus("acceptance", "database", "ready")) @@ -59,7 +61,7 @@ class ObservabilityRuntimeTest { @Test fun `concurrent captures are not lost or duplicated`() { - val runtime = ObservabilityRuntime(Files.createTempDirectory("observability-concurrent")) + val runtime = ObservabilityRuntime(LibraryPaths(Files.createTempDirectory("observability-concurrent"))) val executor = Executors.newFixedThreadPool(8) repeat(100) { index -> @@ -75,7 +77,7 @@ class ObservabilityRuntimeTest { @Test fun `analytics exposes severity timeline and status health`() { - val runtime = ObservabilityRuntime(Files.createTempDirectory("observability-analytics")) + val runtime = ObservabilityRuntime(LibraryPaths(Files.createTempDirectory("observability-analytics"))) runtime.capture { plugin("alpha"); source("startup"); message("ready") } runtime.failure(IllegalStateException("broken")) { plugin("alpha"); source("database") } @@ -91,7 +93,7 @@ class ObservabilityRuntimeTest { @Test fun `support snapshot carries analytics alongside journal`() { - val runtime = ObservabilityRuntime(Files.createTempDirectory("observability-snapshot")) + val runtime = ObservabilityRuntime(LibraryPaths(Files.createTempDirectory("observability-snapshot"))) runtime.capture { message("startup") } val snapshot = runtime.reportSnapshot() diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationJournalThrottleTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationJournalThrottleTest.kt new file mode 100644 index 000000000..e4cfb7b7a --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationJournalThrottleTest.kt @@ -0,0 +1,73 @@ +package org.pnfolder.pnlibrary.core.observability + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.observability.observation.Observation +import org.pnfolder.pnlibrary.api.observability.observation.ObservationKeys +import org.pnfolder.pnlibrary.api.observability.observation.ObservationLevel +import org.pnfolder.pnlibrary.api.observability.observation.ObservationRequest +import org.pnfolder.pnlibrary.core.observability.store.MAX_OBSERVATIONS +import org.pnfolder.pnlibrary.core.observability.store.ObservationJournal +import org.pnfolder.pnlibrary.core.observability.store.retained +import java.nio.file.Files +import java.util.concurrent.atomic.AtomicInteger + +class ObservationJournalThrottleTest { + private val day = 24L * 60 * 60 * 1000 + + private fun observation(index: Int, at: Long, level: ObservationLevel = ObservationLevel.INFO, keepFor: Long? = null): Observation { + val data = if (keepFor == null) emptyMap() else mapOf(ObservationKeys.KEEP_UNTIL_MS to (at + keepFor).toString()) + return Observation.from(ObservationRequest(message = "event $index", level = level, data = data), timestamp = at) + } + + @Test + fun `recent equals what retention on every append would have kept, also after a reload`() { + val root = Files.createTempDirectory("observation-equivalence") + var now = 0L + val appended = ArrayList() + ObservationJournal(root.resolve("observations.jsonl"), clock = { now }).use { journal -> + repeat(400) { index -> + now = index * (day / 20) + val level = ObservationLevel.values()[index % ObservationLevel.values().size] + val keep = if (index % 11 == 0) 3 * day else null + val observation = observation(index, now, level, keep) + appended += observation + journal.append(observation) + assertEquals(appended.retained(now), journal.recent(), "after append $index") + } + } + ObservationJournal(root.resolve("observations.jsonl"), clock = { now }).use { reloaded -> + assertEquals(appended.retained(now), reloaded.recent()) + } + } + + @Test + fun `ten thousand appends run retention at most ten times`() { + val root = Files.createTempDirectory("observation-throttle") + val calls = AtomicInteger() + val journal = ObservationJournal(root.resolve("observations.jsonl"), clock = { 1_000 }, retain = { all, now -> + calls.incrementAndGet() + all.retained(now) + }) + journal.use { repeat(10_000) { index -> it.append(observation(index, 1_000)) } } + + assertTrue(calls.get() <= 10, "retention calls: ${calls.get()}") + ObservationJournal(root.resolve("observations.jsonl"), clock = { 1_000 }).use { assertEquals(10_000, it.recent().size) } + } + + @Test + fun `a full journal is cut by margin rather than rewritten on every append`() { + val root = Files.createTempDirectory("observation-bound") + val calls = AtomicInteger() + ObservationJournal(root.resolve("observations.jsonl"), clock = { 1_000 }, retain = { all, now -> + calls.incrementAndGet() + all.retained(now) + }).use { journal -> + repeat(MAX_OBSERVATIONS + 1_200) { journal.append(observation(it, 1_000)) } + assertEquals(MAX_OBSERVATIONS, journal.recent().size) + assertEquals("event 1200", journal.recent().first().message) + } + assertTrue(calls.get() <= 5, "retention calls: ${calls.get()}") + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationPersistenceTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationPersistenceTest.kt index 5efa935cf..0e024fdd7 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationPersistenceTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/ObservationPersistenceTest.kt @@ -5,9 +5,14 @@ import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.observability.Observation -import org.pnfolder.pnlibrary.api.observability.ObservationLevel -import org.pnfolder.pnlibrary.api.observability.ObservationRequest +import org.pnfolder.pnlibrary.api.observability.observation.Observation +import org.pnfolder.pnlibrary.api.observability.observation.ObservationLevel +import org.pnfolder.pnlibrary.api.observability.observation.ObservationRequest +import org.pnfolder.pnlibrary.core.observability.report.reportSnapshot +import org.pnfolder.pnlibrary.core.observability.store.AttachmentStore +import org.pnfolder.pnlibrary.core.observability.store.ObservationJournal +import org.pnfolder.pnlibrary.core.observability.store.retained +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption @@ -17,10 +22,10 @@ class ObservationPersistenceTest { fun `journal reloads valid observations and skips malformed lines`() { val root = Files.createTempDirectory("observations") val observation = Observation.from(ObservationRequest(message = "started"), timestamp = 100) - ObservationJournal(root, clock = { 100 }).use { it.append(observation) } - Files.writeString(root.resolve("observability/observations.jsonl"), "not-json\n", StandardOpenOption.APPEND) + ObservationJournal(root.resolve("observations.jsonl"), clock = { 100 }).use { it.append(observation) } + Files.writeString(root.resolve("observations.jsonl"), "not-json\n", StandardOpenOption.APPEND) - ObservationJournal(root, clock = { 100 }).use { journal -> + ObservationJournal(root.resolve("observations.jsonl"), clock = { 100 }).use { journal -> assertEquals(listOf(observation), journal.recent()) } } @@ -31,9 +36,9 @@ class ObservationPersistenceTest { val source = root.resolve("server.log").also { Files.writeString(it, "secret") } val observation = Observation.from(ObservationRequest(message = "failed", files = listOf(source))) - ObservationJournal(root).use { it.append(observation) } + ObservationJournal(root.resolve("observations.jsonl")).use { it.append(observation) } - ObservationJournal(root).use { journal -> + ObservationJournal(root.resolve("observations.jsonl")).use { journal -> assertEquals("failed", journal.recent().single().message) } } @@ -83,7 +88,7 @@ class ObservationPersistenceTest { timestamp = 1, ) - val retained = ObservationRetention.active(listOf(oldInfo, oldCritical), now) + val retained = listOf(oldInfo, oldCritical).retained(now) assertEquals(listOf(oldCritical), retained) } @@ -92,7 +97,7 @@ class ObservationPersistenceTest { fun `runtime removes expired observations during startup`() { val root = Files.createTempDirectory("observation-retention") val old = Observation.from(ObservationRequest(message = "expired"), timestamp = 1) - ObservationJournal(root, clock = { 1 }).use { it.append(old) } + ObservationJournal(root.resolve("observations.jsonl"), clock = { 1 }).use { it.append(old) } val runtime = ObservationRuntimeFixture.openAfterThirtyDays(root) @@ -104,7 +109,7 @@ class ObservationPersistenceTest { val root = Files.createTempDirectory("observation-live-retention") val old = Observation.from(ObservationRequest(message = "expired"), timestamp = 1) val current = Observation.from(ObservationRequest(message = "current"), timestamp = 30L * 24 * 60 * 60 * 1000) - ObservationJournal(root, clock = { current.timestamp }).use { journal -> + ObservationJournal(root.resolve("observations.jsonl"), clock = { current.timestamp }).use { journal -> journal.append(old) journal.append(current) @@ -112,9 +117,43 @@ class ObservationPersistenceTest { } } + @Test + fun `author retention overrides level in both directions`() { + val day = 24L * 60 * 60 * 1000 + var now = 0L + val runtime = ObservabilityRuntime(LibraryPaths(Files.createTempDirectory("observation-keep")), clock = { now }) + runtime.capture { + message("short critical"); level(ObservationLevel.CRITICAL); keepFor(java.time.Duration.ofDays(2)) + } + runtime.capture { + message("long info"); level(ObservationLevel.INFO); keepFor(java.time.Duration.ofDays(365)) + } + runtime.capture { message("plain info") } + + now = 10 * day + runtime.maintain() + + assertEquals(listOf("long info"), runtime.recent().map { it.message }) + assertEquals(365 * day, runtime.recent().single().data["pn.keepUntilMs"]!!.toLong()) + assertTrue(runtime.recent().single().data.keys.none { it == "pn.keepForMs" }) + } + + @Test + fun `report journal has readable dates and expiry`() { + val root = Files.createTempDirectory("observation-report") + val runtime = ObservabilityRuntime(LibraryPaths(root), clock = { 0 }) + runtime.capture { plugin("pnMarket"); source("auction"); message("lot lost"); keepFor(java.time.Duration.ofDays(1)) } + + val line = String(runtime.reportSnapshot().journal, Charsets.UTF_8) + + assertTrue(line.contains("\"timeUtc\":\"1970-01-01T00:00:00Z\""), line) + assertTrue(line.contains("\"expiresUtc\":\"1970-01-02T00:00:00Z\""), line) + assertTrue(line.contains("\"source\":\"auction\""), line) + } + private object ObservationRuntimeFixture { fun openAfterThirtyDays(root: Path): ObservabilityRuntime = ObservabilityRuntime( - root, + LibraryPaths(root), clock = { 30L * 24 * 60 * 60 * 1000 }, ) } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/EncryptedEnvelopeCodecTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/EncryptedEnvelopeCodecTest.kt similarity index 95% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/EncryptedEnvelopeCodecTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/EncryptedEnvelopeCodecTest.kt index 6ce595e9c..5efcde001 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/EncryptedEnvelopeCodecTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/EncryptedEnvelopeCodecTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core +package org.pnfolder.pnlibrary.core.observability.report import com.google.gson.Gson import com.google.gson.JsonObject @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.core.security.EncryptedEnvelopeCodec +import org.pnfolder.pnlibrary.core.observability.report.EncryptedEnvelopeCodec import java.security.KeyPairGenerator import java.util.Base64 diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/PythonDecryptionTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/PythonDecryptionTest.kt similarity index 95% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/PythonDecryptionTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/PythonDecryptionTest.kt index 64dba947d..5fc407b6a 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/PythonDecryptionTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/PythonDecryptionTest.kt @@ -1,10 +1,10 @@ -package org.pnfolder.pnlibrary.core +package org.pnfolder.pnlibrary.core.observability.report import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.core.security.EncryptedEnvelopeCodec +import org.pnfolder.pnlibrary.core.observability.report.EncryptedEnvelopeCodec import java.io.File import java.nio.file.Path import java.security.KeyPairGenerator diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportGeneratorTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportGeneratorTest.kt index 56101179d..e343061b9 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportGeneratorTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportGeneratorTest.kt @@ -4,7 +4,7 @@ import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import org.pnfolder.pnlibrary.api.diagnostics.DebugRequest -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticContainer +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticContainer import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticsRegistry @@ -27,6 +27,7 @@ class SupportReportGeneratorTest { } val generator = SupportReportGenerator( dataFolder = temporary, + reportsFolder = temporary.resolve("reports"), config = PnLibraryConfig(upload = false, uploadMode = "disabled"), diagnosticsRegistry = registry, platformIdentity = TestPlatform(), @@ -47,6 +48,35 @@ class SupportReportGeneratorTest { } } + @Test + fun `config files whose names collide after cleaning get distinct archive entries`() { + val registry = DiagnosticsRegistry() + val folder = temporary.resolve("pnMarket") + Files.createDirectories(folder) + Files.writeString(folder.resolve("./config.yml"), "x: 1\n") + Files.writeString(folder.resolve("config.yml"), "x: 2\n") + registry.register("pnMarket", folder, DiagnosticContainer.builder("pnMarket").configuration("./config.yml").configuration("config.yml").build()) + val generator = SupportReportGenerator( + dataFolder = temporary, + reportsFolder = temporary.resolve("reports"), + config = PnLibraryConfig(upload = false, uploadMode = "disabled"), + diagnosticsRegistry = registry, + platformIdentity = TestPlatform(), + platformDiagnostics = TestPlatform(), + encryptionCodec = null, + uploader = null, + uploadLedger = null, + diagnosticLogs = { emptyList() }, + ) + + val result = generator.generateAndSave(DebugRequest("all", configs = true, logs = false, local = true)) + ZipFile(result.localFile.toFile()).use { zip -> + val names = zip.entries().asSequence().map { it.name }.toSet() + assertTrue("pn-diagnostic/plugins/pnmarket/configuration/config.yml" in names) + assertTrue("pn-diagnostic/plugins/pnmarket/configuration/config-2.yml" in names) + } + } + private class TestPlatform : PlatformAdapter { override val type = PlatformType.BUKKIT override val id = "test" diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportRedactionTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportRedactionTest.kt index 1ed77d257..d96fc4565 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportRedactionTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/observability/report/SupportReportRedactionTest.kt @@ -6,7 +6,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import org.pnfolder.pnlibrary.api.diagnostics.DebugRequest import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticConfiguration -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticContainer +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticContainer import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticsRegistry @@ -35,7 +35,7 @@ class SupportReportRedactionTest { diagnosticsPlatform = platform, diagnosticLogs = { emptyList() }, diagnosticHistory = { emptyList() }, - observabilitySnapshot = { org.pnfolder.pnlibrary.core.observability.ObservabilityReportSnapshot(ByteArray(0), ByteArray(0), emptyMap()) }, + observabilitySnapshot = { org.pnfolder.pnlibrary.core.observability.report.ObservabilityReportSnapshot(ByteArray(0), ByteArray(0), emptyMap()) }, ).assemble(DebugRequest("all", configs = true, logs = false, local = true), encrypted = false) val file = temporary.resolve("report.zip") Files.write(file, bytes) diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/ActionPlaceholderKindsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/ActionPlaceholderKindsTest.kt similarity index 75% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/ActionPlaceholderKindsTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/ActionPlaceholderKindsTest.kt index c66435b51..445eea84d 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/ActionPlaceholderKindsTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/ActionPlaceholderKindsTest.kt @@ -4,25 +4,25 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.mockito.Mockito.mock import org.mockito.Mockito.`when` -import org.pnfolder.pnlibrary.api.actions.ActionContext import org.pnfolder.pnlibrary.api.audiences.LibraryAudience -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer import org.pnfolder.pnlibrary.api.logging.PnLogger -import org.pnfolder.pnlibrary.api.placeholders.ExternalPlaceholderRegistration -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapter -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterCapabilities -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterState -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderPublication -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderResolver +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapter +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapterCapabilities +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapterState +import org.pnfolder.pnlibrary.api.placeholders.model.ExternalPlaceholderRegistration +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderPublication +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderResolver import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.plugin.PluginId +import org.pnfolder.pnlibrary.api.scenario.actions.ActionContext import org.pnfolder.pnlibrary.api.tasks.TaskScope import org.pnfolder.pnlibrary.api.text.ComponentService import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter import java.nio.file.Files import java.util.UUID -/** `[value]`, `{placeholder}` and `%external%` read different sources, and formats chain after a bar. */ +/** `${value}`, `{placeholder}` and `%external%` read different sources, and formats chain after a bar. */ class ActionPlaceholderKindsTest { private val hub = PlaceholderHub(TestPlatform) private val service = hub.scope(PluginId.of("shop"), false).also { scope -> @@ -53,15 +53,22 @@ class ActionPlaceholderKindsTest { ) @Test - fun `each kind of brackets reads its own source`() { - val text = context().format("[same] {same} %server_tps% {money} [missing] {missing} %missing%") + fun `a message in square brackets with tags is text, not a placeholder name`() { + val prefix = "[pnTest]" - assertEquals("from-action from-library 19.9 1234567.891 [missing] {missing} %missing%", text) + assertEquals(prefix, context().text(prefix)) + } + + @Test + fun `a name is a value of the run first, then a placeholder, and percent signs are PlaceholderAPI`() { + val text = context().format("{same} {money} {papi:server_tps} %server_tps% {missing} %missing%") + + assertEquals("from-action 1234567.891 19.9 19.9 {missing} %missing%", text) } @Test fun `the player name is always available`() { - assertEquals("Alice Alice Alice", context().format("[player] {player_name} %player%")) + assertEquals("Alice Alice Alice", context().format("{player} {player_name} %player%")) } @Test @@ -70,7 +77,7 @@ class ActionPlaceholderKindsTest { assertEquals("1 234 567.891", ctx.format("{money|group}")) assertEquals("1.2M", ctx.format("{money|short}")) - assertEquals("3.14", ctx.format("[hp|number:2]")) + assertEquals("3.14", ctx.format("{hp|number:2}")) assertEquals("Vip", ctx.format("{rank|capitalize}")) assertEquals("VIP", ctx.format("{rank|upper}")) } @@ -96,14 +103,14 @@ class ActionPlaceholderKindsTest { fun `text that a placeholder produced is not read again`() { val ctx = context().setValue("echo", "{rank}") - assertEquals("{rank}", ctx.format("[echo]")) + assertEquals("{rank}", ctx.format("{echo}")) } @Test fun `reading a whole token returns the value itself`() { val ctx = context() - assertEquals(3.14159, ctx.read("[hp]")) + assertEquals(3.14159, ctx.read("{hp}")) assertEquals("vip", ctx.read("{rank}")) assertEquals("19.9", ctx.read("%server_tps%")) assertEquals("from-action", ctx.read("same")) diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderDefinitionBuilderTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderDefinitionBuilderTest.kt similarity index 87% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderDefinitionBuilderTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderDefinitionBuilderTest.kt index 47ca9c18e..d7d421f60 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderDefinitionBuilderTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderDefinitionBuilderTest.kt @@ -3,9 +3,10 @@ package org.pnfolder.pnlibrary.core.placeholders import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderKey -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRequest +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest import org.pnfolder.pnlibrary.api.plugin.PluginId +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderEntry class PlaceholderDefinitionBuilderTest { @Test diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderLookupSpeedTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderLookupSpeedTest.kt new file mode 100644 index 000000000..15dc97b98 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderLookupSpeedTest.kt @@ -0,0 +1,145 @@ +package org.pnfolder.pnlibrary.core.placeholders + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertSame +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderCachePolicy +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey +import org.pnfolder.pnlibrary.api.plugin.PluginAccess +import org.pnfolder.pnlibrary.api.plugin.PluginId +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderAddress +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderAddressIndex +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderEntry +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderEntryLookup +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderPatternMatcher +import java.util.concurrent.CompletableFuture + +class PlaceholderLookupSpeedTest { + private val names = listOf("score", "kills", "online", "player.{name}", "player.{name}.stat.{stat}", "top.{n}", "pre-{x}-post") + private val plugins = listOf("alpha", "beta") + private val modules = listOf("main", "war", "bank") + + private fun entry(owner: String, key: String) = PlaceholderEntry( + owner = PluginId.of(owner), + key = PlaceholderKey.of(key, String::class.java), + resolver = { CompletableFuture.completedFuture("v") }, + updater = null, + access = PluginAccess.shared(), + updateAccess = PluginAccess.ownerOnly(), + cachePolicy = PlaceholderCachePolicy.none(), + fallback = null, + adapterLookup = { null }, + ) + + private class Old(val known: List, Unit>>) { + fun search(name: String, inScope: (PlaceholderAddress) -> Boolean): Pair?, Map> { + val candidates = known.filter { inScope(it.first) }.sortedWith(compareBy({ it.first.module != "main" }, { it.first.module })) + val lowered = name.lowercase() + candidates.firstOrNull { it.first.name == lowered }?.let { return it.second to emptyMap() } + return candidates + .mapNotNull { (a, e, _) -> PlaceholderPatternMatcher.match(a.name, name)?.let { Triple(a, e, it) } } + .maxByOrNull { (a, _, _) -> PlaceholderPatternMatcher.specificity(a.name) } + ?.let { it.second to it.third } ?: (null to emptyMap()) + } + } + + private fun build(): Pair { + val index = PlaceholderAddressIndex() + val all = mutableListOf, Unit>>() + for (plugin in plugins) for (module in modules) for (name in names) { + val address = PlaceholderAddress(plugin, module, name) + val entry = entry("$plugin-$module", name) + assertTrue(index.add(address, entry)) + all += Triple(address, entry, Unit) + } + return index to Old(all) + } + + private val lookups: List = buildList { + addAll(listOf("score", "SCORE", "Kills", "online", "missing", "player.X", "player.Alex.stat.kills", "top.5", + "top.5.6", "pre-a-post", "pre--post", "player.", "player.a.b")) + repeat(40) { add("player.n$it.stat.s$it") } + repeat(40) { add("top.$it") } + repeat(40) { add("nothing$it") } + } + + @Test + fun `address search gives the same entries and parameters as the old scan`() { + val (index, old) = build() + var checked = 0 + for (plugin in plugins) for (module in modules) for (name in lookups) { + val expected = old.search(name) { it.plugin == plugin && it.module == module } + val actual = index.find(PlaceholderAddress(plugin, module, name.ifEmpty { "x" }).let { it }) + assertSame(expected.first, actual.entry, "$plugin/$module:$name") + assertEquals(expected.second, actual.parameters, "$plugin/$module:$name") + checked++ + } + for (plugin in plugins + "gamma") for (name in lookups) { + val expected = old.search(name) { it.plugin == plugin } + val actual = index.findInPlugin(plugin, name) + assertSame(expected.first, actual.entry, "$plugin:$name") + assertEquals(expected.second, actual.parameters, "$plugin:$name") + checked++ + } + assertTrue(checked > 600) + } + + @Test + fun `an exact address checks no pattern and compiles nothing`() { + val (index, _) = build() + val compilations = PlaceholderPatternMatcher.compilations + val evaluations = PlaceholderPatternMatcher.evaluations + + repeat(200) { + val address = PlaceholderAddress(plugins[it % 2], modules[it % 3], listOf("score", "kills", "online")[it % 3]) + assertTrue(index.find(address).entry != null) + } + repeat(50) { assertTrue(index.findInPlugin("alpha", "SCORE").entry != null) } + + assertEquals(0L, PlaceholderPatternMatcher.evaluations - evaluations) + assertEquals(0L, PlaceholderPatternMatcher.compilations - compilations) + } + + @Test + fun `a pattern lookup tries only the patterns of its module and compiles nothing`() { + val (index, _) = build() + val compilations = PlaceholderPatternMatcher.compilations + val evaluations = PlaceholderPatternMatcher.evaluations + + repeat(100) { index.find(PlaceholderAddress("alpha", "war", "player.n$it.stat.k")) } + + assertEquals(0L, PlaceholderPatternMatcher.compilations - compilations) + // four parameterized names in one module, against 84 registered entries in all + assertEquals(100L * 4, PlaceholderPatternMatcher.evaluations - evaluations) + } + + @Test + fun `entry lookup equals the old scan and an exact key checks no pattern`() { + val owner = PluginId.of("alpha") + val system = PluginId.of("pnlibrary") + val entries = names.associate { "alpha:${it}" to entry("alpha", it) } + ("beta:score" to entry("beta", "score")) + val lookup = PlaceholderEntryLookup(entries, system) + for (name in lookups) { + val expected = entries.values.filter { it.owner == owner } + .mapNotNull { e -> PlaceholderPatternMatcher.match(e.key.value, name)?.let { e to it } } + .maxByOrNull { (e, _) -> PlaceholderPatternMatcher.specificity(e.key.value) } + val actual = lookup.find(owner, name) + val exact = entries["alpha:${name.lowercase()}"] + assertSame(exact ?: expected?.first, actual.entry, name) + if (exact == null) assertEquals(expected?.second.orEmpty(), actual.parameters, name) + } + val evaluations = PlaceholderPatternMatcher.evaluations + repeat(500) { assertTrue(lookup.find(owner, "score").entry != null) } + assertEquals(0L, PlaceholderPatternMatcher.evaluations - evaluations) + } + + @Test + fun `patterns are compiled once at registration`() { + val before = PlaceholderPatternMatcher.compilations + val e = entry("alpha", "pattern.only.{x}") + assertEquals(1L, PlaceholderPatternMatcher.compilations - before) + repeat(10_000) { e.pattern!!.match("pattern.only.v$it") } + assertEquals(1L, PlaceholderPatternMatcher.compilations - before) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderMainThreadTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderMainThreadTest.kt new file mode 100644 index 000000000..58c7363c0 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderMainThreadTest.kt @@ -0,0 +1,142 @@ +package org.pnfolder.pnlibrary.core.placeholders + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapter +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapterCapabilities +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapterState +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderCachePolicy +import org.pnfolder.pnlibrary.api.placeholders.model.ExternalPlaceholderRegistration +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderPublication +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderResolver +import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.api.plugin.PluginAccess +import org.pnfolder.pnlibrary.api.plugin.PluginId +import org.pnfolder.pnlibrary.core.placeholders.entries.PlaceholderEntry +import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter +import java.nio.file.Files +import java.util.UUID +import java.util.concurrent.CompletableFuture +import java.util.concurrent.atomic.AtomicInteger + +class PlaceholderMainThreadTest { + private val owner = PluginId.of("demo") + private val player = UUID.randomUUID() + + private class Capture : PlaceholderAdapter { + override val id = "papi" + override val state = PlaceholderAdapterState.AVAILABLE + override val capabilities = PlaceholderAdapterCapabilities() + lateinit var resolver: PlaceholderResolver + override fun publish( + owner: PluginId, + key: String, + resolver: PlaceholderResolver, + publication: PlaceholderPublication, + ): ExternalPlaceholderRegistration { + this.resolver = resolver + return object : ExternalPlaceholderRegistration { + override val state = PlaceholderAdapterState.REGISTERED + override fun close() = Unit + } + } + } + + private fun slowEntry(resolves: AtomicInteger, millis: Long) = PlaceholderEntry( + owner = owner, + key = PlaceholderKey.of("slow", String::class.java), + resolver = { + resolves.incrementAndGet() + CompletableFuture.supplyAsync { Thread.sleep(millis); "fresh" } + }, + updater = null, + access = PluginAccess.shared(), + updateAccess = PluginAccess.ownerOnly(), + cachePolicy = PlaceholderCachePolicy.none(), + fallback = "fallback", + adapterLookup = { null }, + ) + + private fun request(waitMillis: Long) = + PlaceholderRequest(owner, owner, player, emptyMap(), mapOf(PlaceholderAdapter.WAIT_MILLIS_KEY to waitMillis)) + + @Test + fun `zero wait answers at once with the fallback and the next ask gets the fresh value`() { + val resolves = AtomicInteger() + val entry = slowEntry(resolves, 200) + val adapter = Capture() + entry.publish(PlaceholderPublication("papi")) + entry.attach(adapter) + adapter.resolver.resolve(request(0)) // warm the JIT paths so the timing below measures waiting only + + val started = System.nanoTime() + val first = adapter.resolver.resolve(request(0)) + val elapsedMillis = (System.nanoTime() - started) / 1_000_000.0 + + assertEquals("fallback", first) + assertTrue(elapsedMillis < 5, "answered in $elapsedMillis ms") + val deadline = System.nanoTime() + 5_000_000_000L + var later: Any? = first + while (later != "fresh" && System.nanoTime() < deadline) { + Thread.sleep(10) + later = adapter.resolver.resolve(request(0)) + } + assertEquals("fresh", later) + } + + @Test + fun `a warm-up still running is not started again`() { + val resolves = AtomicInteger() + val entry = slowEntry(resolves, 300) + val adapter = Capture() + entry.publish(PlaceholderPublication("papi")) + entry.attach(adapter) + + repeat(200) { adapter.resolver.resolve(request(0)) } + + assertEquals(1, resolves.get()) + } + + @Test + fun `a positive wait still waits for the value`() { + val entry = slowEntry(AtomicInteger(), 20) + val adapter = Capture() + entry.publish(PlaceholderPublication("papi")) + entry.attach(adapter) + + assertEquals("fresh", adapter.resolver.resolve(request(2_000))) + } + + @Test + fun `text without a percent sign never reaches the outside systems`() { + val renders = AtomicInteger() + val adapter = object : PlaceholderAdapter { + override val id = "counting" + override val state = PlaceholderAdapterState.AVAILABLE + override val capabilities = PlaceholderAdapterCapabilities() + override fun render(playerId: UUID?, text: String): String { renders.incrementAndGet(); return text.replace("%x%", "X") } + override fun publish(owner: PluginId, key: String, resolver: PlaceholderResolver, publication: PlaceholderPublication) = + error("unused") + } + val hub = PlaceholderHub(TestPlatform) + val scope = hub.scope(owner, false) + scope.adapters().register(adapter) + + repeat(100) { assertEquals("plain text", scope.render("plain text", null).toCompletableFuture().get()) } + assertEquals(0, renders.get()) + assertEquals("a X b", scope.render("a %x% b", null).toCompletableFuture().get()) + assertEquals(1, renders.get()) + } + + private object TestPlatform : PlatformAdapter { + override val type = PlatformType.BUKKIT + override val dataFolder = Files.createTempDirectory("pnlibrary-placeholder-test") + override fun diagnosticDetails(includeSensitive: Boolean): Map = emptyMap() + override fun executeGlobal(task: Runnable) = task.run() + override fun executeReply(recipient: Any, task: Runnable) = task.run() + override fun close() = Unit + } +} diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPublicationBindingTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPublicationBindingTest.kt similarity index 82% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPublicationBindingTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPublicationBindingTest.kt index 1dad21745..c2d679e77 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPublicationBindingTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPublicationBindingTest.kt @@ -3,12 +3,12 @@ package org.pnfolder.pnlibrary.core.placeholders import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.placeholders.ExternalPlaceholderRegistration -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapter -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterCapabilities -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterState -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderPublication -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderResolver +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapter +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapterCapabilities +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapterState +import org.pnfolder.pnlibrary.api.placeholders.model.ExternalPlaceholderRegistration +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderPublication +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderResolver import org.pnfolder.pnlibrary.api.plugin.PluginId class PlaceholderPublicationBindingTest { diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderRegistrationLifecycleTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderRegistrationLifecycleTest.kt similarity index 67% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderRegistrationLifecycleTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderRegistrationLifecycleTest.kt index 5268bfa77..c957ebdfc 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderRegistrationLifecycleTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderRegistrationLifecycleTest.kt @@ -1,5 +1,6 @@ package org.pnfolder.pnlibrary.core.placeholders +import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue @@ -26,6 +27,21 @@ class PlaceholderRegistrationLifecycleTest { assertThrows(IllegalStateException::class.java) { registration.enable() } } + @Test + fun `a resolver that throws is reported with its exception once`() { + val failures = mutableListOf>() + val service = PlaceholderHub(TestPlatform, failures = { message, error -> failures += message to error }) + .scope(PluginId.of("demo"), false) + service.register("broken", String::class.java) { + it.resolveAsync { java.util.concurrent.CompletableFuture.failedFuture(IllegalStateException("database is gone")) } + } + + repeat(2) { service.resolve("broken").toCompletableFuture().join() } + + assertEquals(1, failures.size) + assertEquals("database is gone", failures.single().second.message) + } + private object TestPlatform : PlatformAdapter { override val type = PlatformType.BUKKIT override val dataFolder = Files.createTempDirectory("pnlibrary-placeholder-test") diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderTreeTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderTreeTest.kt similarity index 99% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderTreeTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderTreeTest.kt index 1d1407f38..0bfdf48ef 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderTreeTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderTreeTest.kt @@ -11,7 +11,7 @@ import org.pnfolder.pnlibrary.api.placeholders.tree.formats import org.pnfolder.pnlibrary.api.placeholders.tree.from import org.pnfolder.pnlibrary.api.placeholders.tree.list import org.pnfolder.pnlibrary.api.placeholders.tree.none -import org.pnfolder.pnlibrary.api.placeholders.tree.placeholders +import org.pnfolder.pnlibrary.api.placeholders.tree.scope.placeholders import org.pnfolder.pnlibrary.api.placeholders.tree.table import org.pnfolder.pnlibrary.api.plugin.ModuleContext import org.pnfolder.pnlibrary.api.plugin.ModuleId diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/GlobalPlaceholderValueStoreTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/GlobalPlaceholderValueStoreTest.kt similarity index 97% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/GlobalPlaceholderValueStoreTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/GlobalPlaceholderValueStoreTest.kt index 3890e3383..5ed6e0b5c 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/GlobalPlaceholderValueStoreTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/builtin/GlobalPlaceholderValueStoreTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.builtin import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderAddressLookupTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderAddressLookupTest.kt similarity index 90% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderAddressLookupTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderAddressLookupTest.kt index 682430e39..c7749f4e1 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderAddressLookupTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderAddressLookupTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.entries import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse @@ -7,7 +7,9 @@ import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId +import org.pnfolder.pnlibrary.core.placeholders.PlaceholderHub import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter import java.nio.file.Files @@ -20,7 +22,7 @@ class PlaceholderAddressLookupTest { @Test fun `a placeholder is found by its full address from another plugin`() { val clans = scope("m-clans-war-1", "pnclans", "war") - clans.register("score", Int::class.javaObjectType) { it.resolve { 7 }.access(org.pnfolder.pnlibrary.api.placeholders.PlaceholderAccess.shared()) } + clans.register("score", Int::class.javaObjectType) { it.resolve { 7 }.access(org.pnfolder.pnlibrary.api.plugin.PluginAccess.shared()) } val other = scope("m-shop-main-1", "pnshop", "main") assertTrue(other.contains("pnclans/war:score")) @@ -33,7 +35,7 @@ class PlaceholderAddressLookupTest { val clans = scope("m-clans-war-1", "pnclans", "war") clans.register("player.{name}", String::class.java) { builder -> builder.resolve { request -> request.parameters.getValue("name") } - builder.access(org.pnfolder.pnlibrary.api.placeholders.PlaceholderAccess.shared()) + builder.access(org.pnfolder.pnlibrary.api.plugin.PluginAccess.shared()) } assertEquals("Alex", clans.resolve("pnclans/war:player.Alex").toCompletableFuture().get()) diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderAddressTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderAddressTest.kt similarity index 97% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderAddressTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderAddressTest.kt index 526925b25..f4ca0fa9a 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderAddressTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderAddressTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.entries import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntriesIndexTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntriesIndexTest.kt new file mode 100644 index 000000000..6f14e14e0 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntriesIndexTest.kt @@ -0,0 +1,113 @@ +package org.pnfolder.pnlibrary.core.placeholders.entries + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertSame +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderCachePolicy +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey +import org.pnfolder.pnlibrary.api.plugin.PluginAccess +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.util.Locale +import java.util.concurrent.CompletableFuture + +class PlaceholderEntriesIndexTest { + private val system = PluginId.of("pnlibrary") + private val patternKeys = listOf("player.{name}", "player.{name}.stat.{stat}", "top.{n}", "pre-{x}-post") + + private fun entry(owner: String, key: String) = PlaceholderEntry( + owner = PluginId.of(owner), + key = PlaceholderKey.of(key, String::class.java), + resolver = { CompletableFuture.completedFuture("v") }, + updater = null, + access = PluginAccess.shared(), + updateAccess = PluginAccess.ownerOnly(), + cachePolicy = PlaceholderCachePolicy.none(), + fallback = null, + adapterLookup = { null }, + ) + + private fun registry(exactPerOwner: Int, owners: List): Map> { + val all = linkedMapOf>() + for (owner in owners) { + for (key in patternKeys) all["$owner:${key.lowercase(Locale.ROOT)}"] = entry(owner, key) + for (i in 0 until exactPerOwner) all["$owner:key$i"] = entry(owner, "key$i") + } + all["pnlibrary:version"] = entry("pnlibrary", "version") + return all + } + + private fun oldFind(entries: Map>, consumer: String, reference: String): PlaceholderEntryLookup.Match { + val separator = reference.indexOf(':') + val namespace = if (separator > 0) reference.substring(0, separator) else consumer + val key = if (separator > 0) reference.substring(separator + 1) else reference + entries["$namespace:${key.lowercase(Locale.ROOT)}"]?.let { return PlaceholderEntryLookup.Match(it, emptyMap()) } + if (separator < 0) entries["pnlibrary:${key.lowercase(Locale.ROOT)}"]?.let { return PlaceholderEntryLookup.Match(it, emptyMap()) } + var best: PlaceholderEntry<*>? = null + var parameters = emptyMap() + for (entry in entries.values) { + val pattern = entry.pattern ?: continue + if (entry.owner.value != namespace) continue + val found = pattern.match(key) ?: continue + if (best == null || pattern.specificity > best.pattern!!.specificity) { + best = entry + parameters = found + } + } + return PlaceholderEntryLookup.Match(best, parameters) + } + + private val references: List = buildList { + addAll(listOf("key1", "KEY2", "version", "missing", "player.X", "player.Alex.stat.kills", "top.5", "top.5.6", + "pre-a-post", "pre--post", "player.", "alpha:player.Bob", "beta:top.7", "gamma:top.7", "alpha:key3", "alpha:nothing")) + repeat(60) { add("player.n$it.stat.s$it") } + repeat(60) { add("top.$it") } + repeat(60) { add("alpha:nothing$it") } + repeat(30) { add("beta:player.p$it") } + } + + @Test + fun `lookup through the owner index equals the old scan over all entries`() { + val entries = registry(exactPerOwner = 20, owners = listOf("alpha", "beta")) + val lookup = PlaceholderEntryLookup(entries, system) + var checked = 0 + for (consumer in listOf("alpha", "beta", "gamma")) for (reference in references) { + val expected = oldFind(entries, consumer, reference) + val actual = lookup.find(PluginId.of(consumer), reference) + assertSame(expected.entry, actual.entry, "$consumer/$reference") + assertEquals(expected.parameters, actual.parameters, "$consumer/$reference") + checked++ + } + assertTrue(checked > 200) + } + + @Test + fun `a miss or a pattern looks only at the owner's patterns however many entries exist`() { + val scanned = listOf(100, 2000).map { total -> + val entries = registry(exactPerOwner = total / 4, owners = listOf("alpha", "beta", "gamma", "delta")) + val lookup = PlaceholderEntryLookup(entries, system) + repeat(50) { lookup.find(PluginId.of("alpha"), "missing$it") } + repeat(50) { lookup.find(PluginId.of("alpha"), "player.n$it.stat.s$it") } + lookup.candidatesScanned + } + assertEquals(100L * patternKeys.size, scanned[0]) + assertEquals(scanned[0], scanned[1]) + } + + @Test + fun `removed and replaced entries leave the pattern index`() { + val entries = PlaceholderEntries() + val first = entry("alpha", "top.{n}") + assertTrue(entries.add("alpha:top.{n}", first)) + assertTrue(!entries.add("alpha:top.{n}", entry("alpha", "top.{n}"))) + assertEquals(listOf(first), entries.patternsOf(PluginId.of("alpha"))) + assertTrue(!entries.remove("alpha:top.{n}", entry("alpha", "top.{n}"))) + assertSame(first, entries.remove("alpha:top.{n}")) + assertTrue(entries.patternsOf(PluginId.of("alpha")).isEmpty()) + val second = entry("alpha", "top.{n}") + entries["alpha:top.{n}"] = second + assertEquals(listOf(second), entries.patternsOf(PluginId.of("alpha"))) + assertNull(PlaceholderEntryLookup(entries, system).find(PluginId.of("beta"), "top.1").entry) + } +} diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderEntryLookupTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntryLookupTest.kt similarity index 84% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderEntryLookupTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntryLookupTest.kt index aa3149ed3..2bee6da5d 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderEntryLookupTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntryLookupTest.kt @@ -1,11 +1,11 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.entries import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAccess -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderCachePolicy -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderKey +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderCachePolicy +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId import java.util.concurrent.CompletableFuture @@ -47,8 +47,8 @@ class PlaceholderEntryLookupTest { key = PlaceholderKey.of(key, String::class.java), resolver = { CompletableFuture.completedFuture("value") }, updater = null, - access = PlaceholderAccess.shared(), - updateAccess = PlaceholderAccess.ownerOnly(), + access = PluginAccess.shared(), + updateAccess = PluginAccess.ownerOnly(), cachePolicy = PlaceholderCachePolicy.none(), fallback = null, adapterLookup = { null }, diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderEntryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntryTest.kt similarity index 80% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderEntryTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntryTest.kt index eaedfc500..d13eb8e65 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderEntryTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderEntryTest.kt @@ -1,13 +1,13 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.entries import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAccess -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderCachePolicy -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderCacheScope -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderKey -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRequest +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderCachePolicy +import org.pnfolder.pnlibrary.api.placeholders.cache.PlaceholderCacheScope +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId import java.time.Duration import java.util.concurrent.CompletableFuture @@ -25,8 +25,8 @@ class PlaceholderEntryTest { CompletableFuture.completedFuture("online-${calls.incrementAndGet()}") }, updater = null, - access = PlaceholderAccess.ownerOnly(), - updateAccess = PlaceholderAccess.ownerOnly(), + access = PluginAccess.ownerOnly(), + updateAccess = PluginAccess.ownerOnly(), cachePolicy = PlaceholderCachePolicy(PlaceholderCacheScope.GLOBAL, 1, Duration.ofSeconds(60)), fallback = "offline", adapterLookup = { null }, @@ -56,8 +56,8 @@ class PlaceholderEntryTest { CompletableFuture.completedFuture(null) }, updater = null, - access = PlaceholderAccess.ownerOnly(), - updateAccess = PlaceholderAccess.ownerOnly(), + access = PluginAccess.ownerOnly(), + updateAccess = PluginAccess.ownerOnly(), cachePolicy = PlaceholderCachePolicy( scope = PlaceholderCacheScope.GLOBAL, maximumEntries = 1, diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPatternMatcherTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderPatternMatcherTest.kt similarity index 93% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPatternMatcherTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderPatternMatcherTest.kt index 6bba59c38..8a1e14a3f 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPatternMatcherTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/entries/PlaceholderPatternMatcherTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.entries import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderBuiltInFormattersTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderBuiltInFormattersTest.kt similarity index 97% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderBuiltInFormattersTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderBuiltInFormattersTest.kt index a21b1fd6f..8952ab52c 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderBuiltInFormattersTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderBuiltInFormattersTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.formatters import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderFormatterRegistryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderFormatterRegistryTest.kt similarity index 90% rename from modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderFormatterRegistryTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderFormatterRegistryTest.kt index 1825910bd..fcf13f7c1 100644 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderFormatterRegistryTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderFormatterRegistryTest.kt @@ -1,8 +1,8 @@ -package org.pnfolder.pnlibrary.core.placeholders +package org.pnfolder.pnlibrary.core.placeholders.formatters import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRequest +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest import org.pnfolder.pnlibrary.api.plugin.PluginId class PlaceholderFormatterRegistryTest { diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderTemplateRendererTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderTemplateRendererTest.kt new file mode 100644 index 000000000..143c16b32 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/formatters/PlaceholderTemplateRendererTest.kt @@ -0,0 +1,47 @@ +package org.pnfolder.pnlibrary.core.placeholders.formatters + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import java.util.concurrent.CompletableFuture + +class PlaceholderTemplateRendererTest { + @Test + fun `renderer handles conditions local expressions and ordinary expressions`() { + val values = mapOf( + "enabled" to true, + "status" to "online", + "name" to "Alex", + ) + val renderer = PlaceholderTemplateRenderer( + resolve = { expression, _, _ -> + val parts = expression.split('|') + val value = values[parts.first()] + CompletableFuture.completedFuture(if ("upper" in parts.drop(1)) value?.toString()?.uppercase() else value) + }, + format = { value, _, _, _ -> value }, + ) + + val rendered = renderer.render( + "{?enabled}Server {status|upper}: {name}{:}offline{/}", + playerId = null, + values = emptyMap(), + ).toCompletableFuture().join() + + assertEquals("Server ONLINE: Alex", rendered) + } + + @Test + fun `square brackets around tags stay text and ask no placeholder`() { + val asked = mutableListOf() + val renderer = PlaceholderTemplateRenderer( + resolve = { expression, _, _ -> asked += expression; CompletableFuture.completedFuture(null) }, + format = { value, _, _, _ -> value }, + ) + + val text = "[pnTest] hi" + val rendered = renderer.render(text, null, emptyMap()).toCompletableFuture().join() + + assertEquals(text, rendered) + assertEquals(emptyList(), asked) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/PluginRegistryImplTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/PluginRegistryImplTest.kt index f41d344ac..4bc3184d3 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/PluginRegistryImplTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/PluginRegistryImplTest.kt @@ -12,40 +12,46 @@ import org.mockito.Mockito.doThrow import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.Mockito.`when` -import org.pnfolder.pnlibrary.api.commands.CommandDefinition import org.pnfolder.pnlibrary.api.commands.CommandRegistration +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition import org.pnfolder.pnlibrary.api.dependencies.Dependencies -import org.pnfolder.pnlibrary.api.dependencies.ExternalPluginDependency import org.pnfolder.pnlibrary.api.dependencies.PluginDependency +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsService import org.pnfolder.pnlibrary.api.downloads.DownloadDestination import org.pnfolder.pnlibrary.api.downloads.DownloadRegistration import org.pnfolder.pnlibrary.api.downloads.FileDownloads import org.pnfolder.pnlibrary.api.events.Event -import org.pnfolder.pnlibrary.api.events.EventHandler -import org.pnfolder.pnlibrary.api.events.Listener +import org.pnfolder.pnlibrary.api.events.listener.EventHandler +import org.pnfolder.pnlibrary.api.events.listener.Listener import org.pnfolder.pnlibrary.api.logging.LoggingService import org.pnfolder.pnlibrary.api.logging.MessageBox import org.pnfolder.pnlibrary.api.logging.PnLogger -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.metrics.MetricsService import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.api.plugin.LifecycleRow import org.pnfolder.pnlibrary.api.plugin.PluginBuilder +import org.pnfolder.pnlibrary.api.plugin.lifecycle.LifecycleRow import org.pnfolder.pnlibrary.api.tasks.TaskScope -import org.pnfolder.pnlibrary.api.tasks.TaskSpec -import org.pnfolder.pnlibrary.api.updates.PluginUpdateRequest -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec +import org.pnfolder.pnlibrary.api.updates.UpdateBackups +import org.pnfolder.pnlibrary.api.updates.UpdateHistory +import org.pnfolder.pnlibrary.api.updates.UpdatePlans +import org.pnfolder.pnlibrary.api.updates.UpdateProducts import org.pnfolder.pnlibrary.api.updates.UpdateRegistration import org.pnfolder.pnlibrary.api.updates.UpdateService +import org.pnfolder.pnlibrary.api.updates.UpdateSettings +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest import org.pnfolder.pnlibrary.config.ConfigurationServiceImpl -import org.pnfolder.pnlibrary.core.commands.CommandService -import org.pnfolder.pnlibrary.core.downloads.DirectDownloads +import org.pnfolder.pnlibrary.core.commands.engine.CommandService +import org.pnfolder.pnlibrary.core.downloads.fetch.DirectDownloads import org.pnfolder.pnlibrary.core.events.EventDispatcher import org.pnfolder.pnlibrary.core.expansions.ExpansionRegistry import org.pnfolder.pnlibrary.core.placeholders.PlaceholderHub +import org.pnfolder.pnlibrary.core.plugin.module.LibraryFetcher import org.pnfolder.pnlibrary.core.remote.RemotePolicyMonitor import org.pnfolder.pnlibrary.core.remote.RemotePolicyNoticeRenderer import org.pnfolder.pnlibrary.core.services.ServiceRegistry @@ -54,8 +60,8 @@ import org.pnfolder.pnlibrary.core.tasks.TaskService import org.pnfolder.pnlibrary.currency.CurrencyFeature import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskAdapter +import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskBuilder import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskHandle -import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest import java.lang.reflect.Proxy import java.nio.file.Paths import java.util.function.Consumer @@ -397,12 +403,8 @@ class PluginRegistryImplTest { @Test fun `sibling modules receive isolated task scopes`() { - val nativeOwners = mutableListOf() val native = object : PlatformTaskAdapter { - override fun schedule(request: PlatformTaskRequest): PlatformTaskHandle { - nativeOwners += request.owner - return PlatformTaskHandle { true } - } + override fun buildTask() = PlatformTaskBuilder { PlatformTaskHandle { true } } } val tasks = ScheduledTasks(native) val owner = Any() @@ -414,8 +416,6 @@ class PluginRegistryImplTest { val spec = TaskSpec.builder().action { }.build() val firstTask = first.tasks.schedule(spec) val secondTask = second.tasks.schedule(spec) - assertSame(owner, nativeOwners[0]) - assertSame(owner, nativeOwners[1]) first.close() assertTrue(firstTask.isCancelled) assertFalse(secondTask.isCancelled) @@ -643,6 +643,7 @@ class PluginRegistryImplTest { directDownloads: DirectDownloads? = null, expansions: ExpansionRegistry = ExpansionRegistry { _, _ -> }, libraryExpansions: ExpansionRegistry = ExpansionRegistry { _, _ -> }, + libraryFetcher: LibraryFetcher = LibraryFetcher { _, _, _, _ -> null }, ): PluginRegistryImpl = PluginRegistryImpl( ownership = platform, @@ -660,6 +661,7 @@ class PluginRegistryImplTest { commands = commands, directDownloads = directDownloads, libraryVersion = libraryVersion, + libraryFetcher = libraryFetcher, ) private class RecordingUpdateService : UpdateService { @@ -677,8 +679,14 @@ class PluginRegistryImplTest { this.dependencies = dependencies return emptyProxy(UpdateRegistration::class.java) } - override fun all(): List = emptyList() - override fun get(product: String): UpdateRegistration? = null + override val products = object : UpdateProducts { + override fun all(): List = emptyList() + override fun get(product: String): UpdateRegistration? = null + } + override val plans: UpdatePlans get() = error("not used") + override val settings: UpdateSettings get() = error("not used") + override val backups: UpdateBackups get() = error("not used") + override val history: UpdateHistory get() = error("not used") } fun platform(): PlatformAdapter = proxy(PlatformAdapter::class.java) { methodName -> @@ -736,7 +744,7 @@ class PluginRegistryImplTest { val unregisteredOwners = mutableListOf() val registeredOwners = mutableListOf() override fun register(owner: Any, command: CommandDefinition, - feedback: org.pnfolder.pnlibrary.core.commands.CommandFeedbackScope?): CommandRegistration = + feedback: org.pnfolder.pnlibrary.core.commands.engine.CommandFeedbackScope?): CommandRegistration = object : CommandRegistration { init { registeredOwners += owner } override val command = command diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/cooldowns/InMemoryCooldownsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/InMemoryCooldownsTest.kt similarity index 52% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/cooldowns/InMemoryCooldownsTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/InMemoryCooldownsTest.kt index d422145e3..b77c35f5c 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/cooldowns/InMemoryCooldownsTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/InMemoryCooldownsTest.kt @@ -1,6 +1,7 @@ -package org.pnfolder.pnlibrary.core.cooldowns +package org.pnfolder.pnlibrary.core.plugin.module import org.junit.jupiter.api.Assertions.assertDoesNotThrow +import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue @@ -32,4 +33,29 @@ class InMemoryCooldownsTest { assertDoesNotThrow { service.clear() } assertThrows(IllegalStateException::class.java) { service.remaining(player, "example") } } + + @Test + fun `active lists the cooldowns of one player and clear removes only that player's`() { + val service = InMemoryCooldowns() + val player = UUID.randomUUID() + val other = UUID.randomUUID() + service.set(player, "kit", Duration.ofMinutes(10)) + service.set(player, "home", Duration.ofMinutes(1)) + service.set(other, "kit", Duration.ofMinutes(1)) + + assertEquals(listOf("kit", "home"), service.active(player).keys.toList()) + assertEquals(2, service.clear(player)) + assertTrue(service.active(player).isEmpty()) + assertTrue(service.has(other, "kit")) + } + + @Test + fun `expired entries of players nobody asks about are swept away`() { + val service = InMemoryCooldowns() + repeat(300) { service.set(UUID.randomUUID(), "once", Duration.ofNanos(1)) } + Thread.sleep(5) + repeat(300) { service.set(UUID.randomUUID(), "later", Duration.ofMinutes(1)) } + + assertTrue(service.size <= 300) + } } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/LibrarySourcesTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/LibrarySourcesTest.kt new file mode 100644 index 000000000..c90bac3c6 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/LibrarySourcesTest.kt @@ -0,0 +1,49 @@ +package org.pnfolder.pnlibrary.core.plugin.module + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.libraries.ModuleLibrary +import org.pnfolder.pnlibrary.api.platform.PlatformType + +class LibrarySourcesTest { + @Test + fun `a library for another platform is skipped without an error`() { + var fetched = 0 + val libraries = ModuleLibrariesImpl(null, PlatformType.VELOCITY) { fetched++; null } + libraries.load(ModuleLibrary.builder("g", "a", "1").platforms(PlatformType.BUKKIT).build()) + libraries.load(ModuleLibrary.builder("g", "b", "1").platforms(PlatformType.VELOCITY, PlatformType.BUNGEECORD).build()) + + assertEquals(1, fetched) + assertEquals(listOf("g:b:1"), libraries.loaded.map { it.coordinates }) + } + + @Test + fun `any number of sources are tried in the given order`() { + val library = ModuleLibrary.builder("g", "a", "1") + .source { link("https://one.example/a.jar") }.source { link("https://two.example/a.jar") } + .source { repository("https://repo1.example/") }.source { repository("https://repo2.example/") }.mavenCentral(false).build() + assertEquals( + listOf("https://one.example/a.jar", "https://two.example/a.jar", "https://repo1.example/", "https://repo2.example/"), + library.allSources.map { it.url }, + ) + } + + @Test + fun `a thousand alternatives are accepted`() { + val builder = ModuleLibrary.builder("g", "a", "1").mavenCentral(false) + repeat(1000) { index -> builder.source { repository("https://m$index.example/") } } + assertEquals(1000, builder.build().allSources.size) + } + + @Test + fun `a place that failed a moment ago is tried last and forgotten after five minutes`() { + SourceHealth.forgetAll() + val library = ModuleLibrary.builder("g", "a", "1") + .source { repository("https://one.example/") }.source { repository("https://two.example/") }.mavenCentral(false).build() + SourceHealth.failed("https://one.example/", now = 1_000) + + assertEquals(listOf("https://two.example/", "https://one.example/"), SourceHealth.order(library.allSources, now = 2_000).map { it.url }) + assertEquals(listOf("https://one.example/", "https://two.example/"), SourceHealth.order(library.allSources, now = 400_000).map { it.url }) + SourceHealth.forgetAll() + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleControlTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleControlTest.kt new file mode 100644 index 000000000..744a69c37 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleControlTest.kt @@ -0,0 +1,148 @@ +package org.pnfolder.pnlibrary.core.plugin.module + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.libraries.ModuleLibrary +import org.pnfolder.pnlibrary.api.plugin.ModuleContext +import org.pnfolder.pnlibrary.api.plugin.control.ModuleState +import org.pnfolder.pnlibrary.api.plugin.control.PluginModule +import org.pnfolder.pnlibrary.core.plugin.PluginRegistryImplTest +import java.nio.file.Path + +class ModuleControlTest { + private class Recording(private val failOn: String? = null, private val inPlace: Boolean = false) : PluginModule { + val calls = mutableListOf() + private fun step(name: String) { + calls += name + if (name == failOn) error("boom in $name") + } + override fun onEnable(context: ModuleContext) = step("enable") + override fun onDisable(context: ModuleContext) = step("disable") + override fun onReload(context: ModuleContext): Boolean { + step("reload") + return inPlace + } + } + + private fun registry() = PluginRegistryImplTest.registry() + + @Test + fun `a module starts at registration and can be disabled, enabled and restarted`() { + val module = Recording() + val registry = registry() + val context = registry.register(Any()).registerModule("shop", module) + + assertEquals(ModuleState.ENABLED, context.control.state) + context.control.disable() + assertEquals(ModuleState.DISABLED, context.control.state) + context.control.enable() + context.control.restart() + assertEquals(listOf("enable", "disable", "enable", "disable", "enable"), module.calls) + assertEquals(ModuleState.ENABLED, context.control.state) + registry.close() + } + + @Test + fun `reload restarts a module that cannot reload in place`() { + val stays = Recording(inPlace = true) + val restarts = Recording(inPlace = false) + val registry = registry() + registry.register(Any()).registerModule("one", stays).control.reload() + registry.register(Any()).registerModule("two", restarts).control.reload() + + assertEquals(listOf("enable", "reload"), stays.calls) + assertEquals(listOf("enable", "reload", "disable", "enable"), restarts.calls) + registry.close() + } + + @Test + fun `a failing hook leaves the module failed with the error and enabling tries again`() { + val module = Recording(failOn = "enable") + val registry = registry() + val context = registry.register(Any()).registerModule("shop", module) + + assertEquals(ModuleState.FAILED, context.control.state) + assertNotNull(context.control.lastError) + context.control.disable() + assertEquals(ModuleState.DISABLED, context.control.state) + assertNull(context.control.lastError) + registry.close() + } + + @Test + fun `a module that an administrator keeps off does not start with the server`(@TempDir directory: Path) { + val file = directory.resolve("modules").resolve("preferences.json") + val first = ModulePreferences(file) + first.setAutoStart("shop", false) + + assertFalse(ModulePreferences(file).autoStart("shop")) + assertTrue(ModulePreferences(file).autoStart("other")) + first.setAutoStart("shop", true) + assertTrue(ModulePreferences(file).autoStart("shop")) + } + + @Test + fun `a module without hooks is listed but cannot be switched`() { + val registry = registry() + val context = registry.register(Any()).registerModule("plain") + + assertFalse(context.control.isControllable) + assertEquals(ModuleState.ENABLED, context.control.state) + assertThrows(UnsupportedOperationException::class.java) { context.control.disable() } + registry.close() + } + + @Test + fun `closing the plugin runs the disable hook once`() { + val module = Recording() + val registry = registry() + registry.register(Any()).registerModule("shop", module) + registry.close() + + assertEquals(listOf("enable", "disable"), module.calls) + } + + private class WithLibrary(private val library: ModuleLibrary) : PluginModule { + var enabled = false + override fun libraries() = listOf(library) + override fun onEnable(context: ModuleContext) { + enabled = true + } + } + + @Test + fun `a required library that cannot be loaded fails the module and an optional one does not`() { + val required = WithLibrary(ModuleLibrary.of("com.example:missing:1")) + val optional = WithLibrary(ModuleLibrary.builder("com.example", "missing", "1").optional().build()) + val registry = PluginRegistryImplTest.registry(libraryFetcher = LibraryFetcher { _, _, _, _ -> error("offline") }) + + val failed = registry.register(Any()).registerModule("needs", required) + val started = registry.register(Any()).registerModule("wants", optional) + + assertEquals(ModuleState.FAILED, failed.control.state) + assertFalse(required.enabled) + assertNotNull(failed.control.lastError) + assertEquals(ModuleState.ENABLED, started.control.state) + assertTrue(optional.enabled) + registry.close() + } + + @Test + fun `the library lists every module and every library with who registered it`() { + val registry = registry() + val plugin = registry.register(Any()) + plugin.registerModule("one", Recording()).libraries.load(ModuleLibrary.of("g:a:1")) + plugin.registerModule("two", Recording()).libraries.load(ModuleLibrary.of("g:a:2")) + + assertEquals(2, registry.allModules().size) + assertEquals(listOf("one", "two"), registry.libraryUsage().map { it.module?.value }.sortedBy { it }) + assertEquals(2, plugin.allLibraries.size) + registry.close() + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDefinitionMetricsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDefinitionMetricsTest.kt index 4da86cde6..c6b197df3 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDefinitionMetricsTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDefinitionMetricsTest.kt @@ -3,7 +3,7 @@ package org.pnfolder.pnlibrary.core.plugin.module import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider import java.util.function.Consumer class ModuleDefinitionMetricsTest { diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDependencyValidatorTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDependencyValidatorTest.kt new file mode 100644 index 000000000..3d18c5fbf --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleDependencyValidatorTest.kt @@ -0,0 +1,56 @@ +package org.pnfolder.pnlibrary.core.plugin.module + +import org.junit.jupiter.api.Assertions.assertDoesNotThrow +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.mockito.Mockito.mock +import org.mockito.Mockito.`when` +import org.pnfolder.pnlibrary.api.dependencies.Dependencies +import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership + +class ModuleDependencyValidatorTest { + private fun validator(installed: Map, downloads: Boolean = false): ModuleDependencyValidator { + val platform = mock(PlatformOwnership::class.java) + `when`(platform.installedPlugins()).thenReturn(installed) + return ModuleDependencyValidator(platform) { downloads } + } + + private val vault = Dependencies.plugin("Vault", "1.7.0", "https://example.org/vault") + + @Test + fun `an installed plugin of a high enough version passes, names ignore case`() { + assertDoesNotThrow { validator(mapOf("vault" to "1.7.3")).validate(listOf(vault), emptyMap()) } + } + + @Test + fun `a missing plugin names its download page`() { + val error = assertThrows(IllegalArgumentException::class.java) { validator(emptyMap()).validate(listOf(vault), emptyMap()) } + + assertTrue(error.message!!.contains("Vault")) + assertTrue(error.message!!.contains("https://example.org/vault")) + } + + @Test + fun `a too old plugin is reported with both versions`() { + val error = assertThrows(IllegalArgumentException::class.java) { validator(mapOf("Vault" to "1.5.0")).validate(listOf(vault), emptyMap()) } + + assertTrue(error.message!!.contains("1.5.0")) + assertTrue(error.message!!.contains("1.7.0")) + } + + @Test + fun `an optional plugin never blocks`() { + val optional = Dependencies.plugin("Vault", "1.7.0", "https://example.org/vault", required = false) + + assertDoesNotThrow { validator(emptyMap()).validate(listOf(optional), emptyMap()) } + } + + @Test + fun `a missing plugin that can be downloaded automatically does not block`() { + val automatic = Dependencies.plugin("Vault", "1.7.0", "https://example.org/Vault.jar", "a".repeat(64)) + + assertDoesNotThrow { validator(emptyMap(), downloads = true).validate(listOf(automatic), emptyMap()) } + assertThrows(IllegalArgumentException::class.java) { validator(emptyMap(), downloads = false).validate(listOf(automatic), emptyMap()) } + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleLibrariesTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleLibrariesTest.kt new file mode 100644 index 000000000..5e0ee110e --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleLibrariesTest.kt @@ -0,0 +1,73 @@ +package org.pnfolder.pnlibrary.core.plugin.module + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertSame +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.libraries.ModuleLibrary +import java.net.URLClassLoader + +class ModuleLibrariesTest { + private val hikari = ModuleLibrary.of("com.zaxxer:HikariCP:5.1.0") + + @Test + fun `a library is fetched once and its isolated loader is kept`() { + val holder = URLClassLoader(emptyArray()) + var fetched = 0 + val libraries = ModuleLibrariesImpl(null) { fetched++; holder } + + libraries.load(hikari) + libraries.load(hikari) + + assertEquals(1, fetched) + assertSame(holder, libraries.classLoader) + assertEquals(listOf(hikari), libraries.loaded) + } + + @Test + fun `a shared library adds no loader and a failure is not remembered as loaded`() { + val shared = ModuleLibrary.builder("g", "a", "1").scope(org.pnfolder.pnlibrary.api.libraries.LibraryScope.LIBRARY).build() + val libraries = ModuleLibrariesImpl(null) { if (it == hikari) error("offline") else null } + + libraries.load(shared) + assertThrows(IllegalStateException::class.java) { libraries.load(hikari) } + assertEquals(listOf(shared), libraries.loaded) + } + + @Test + fun `a module sees the libraries of its plugin and does not fetch them twice`() { + var fetched = 0 + val plugin = ModuleLibrariesImpl(null) { fetched++; null } + val module = ModuleLibrariesImpl(plugin) { fetched++; null } + val own = ModuleLibrary.of("g:own:1") + + plugin.load(hikari) + module.load(hikari) + module.load(own) + + assertEquals(2, fetched) + assertEquals(listOf(own), module.loaded) + assertEquals(listOf(hikari, own), module.available) + assertEquals(listOf(hikari), plugin.available) + assertEquals(hikari, module.find("com.zaxxer", "HikariCP")) + } + + @Test + fun `remove takes a library off the list and tells whether it was there`() { + val libraries = ModuleLibrariesImpl(null) { null } + libraries.load(hikari) + + assertEquals(true, libraries.remove(hikari)) + assertEquals(false, libraries.remove(hikari)) + assertEquals(emptyList(), libraries.loaded) + } + + @Test + fun `a class is searched in the module loader first and then in the plugin loader`() { + val plugin = ModuleLibrariesImpl(null) { null } + val module = ModuleLibrariesImpl(plugin) { null } + + assertSame(String::class.java, module.loadClass("java.lang.String")) + assertThrows(ClassNotFoundException::class.java) { module.loadClass("no.such.Library") } + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/ModuleMetricsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetricsTest.kt similarity index 95% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/ModuleMetricsTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetricsTest.kt index 678bc8eab..0dc67faaa 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/ModuleMetricsTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleMetricsTest.kt @@ -1,16 +1,16 @@ -package org.pnfolder.pnlibrary.core.plugin +package org.pnfolder.pnlibrary.core.plugin.module import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.metrics.MetricsService import org.pnfolder.pnlibrary.api.metrics.PluginMetrics -import org.pnfolder.pnlibrary.api.metrics.TelemetryError +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.error.TelemetryError +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration import org.pnfolder.pnlibrary.core.plugin.module.ModuleMetricsDefinition import java.util.function.Consumer import java.util.function.Supplier diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleProductResolverTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleProductResolverTest.kt new file mode 100644 index 000000000..ee9397ba0 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleProductResolverTest.kt @@ -0,0 +1,56 @@ +package org.pnfolder.pnlibrary.core.plugin.module + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.mockito.Mockito.mock +import org.mockito.Mockito.`when` +import org.pnfolder.pnlibrary.api.dependencies.Dependencies +import org.pnfolder.pnlibrary.api.plugin.ModuleId +import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership + +class ModuleProductResolverTest { + private val owner = Any() + private val id = ModuleId.of("shop") + + private fun resolver(version: String?): ModuleProductResolver { + val platform = mock(PlatformOwnership::class.java) + `when`(platform.ownerDetails(owner)).thenReturn(if (version == null) emptyMap() else mapOf("version" to version)) + return ModuleProductResolver(platform) + } + + @Test + fun `a module with no updates, product or dependencies has no descriptor`() { + assertNull(resolver("1.0.0").resolve(owner, id, ModuleDefinitionBuilder())) + } + + @Test + fun `dependencies alone give a descriptor with the plugin's version`() { + val definition = ModuleDefinitionBuilder().apply { depends(Dependencies.plugin("Vault", "1.7.0", "https://example.org")) } + + val descriptor = resolver("2.3.4").resolve(owner, id, definition)!! + + assertEquals("shop", descriptor.id.value) + assertEquals("2.3.4", descriptor.version.toString()) + } + + @Test + fun `the version of the definition is used when the platform has none`() { + val definition = ModuleDefinitionBuilder().apply { + metadataVersion = "0.9.0" + depends(Dependencies.plugin("Vault", "1.7.0", "https://example.org")) + } + + assertEquals("0.9.0", resolver(null).resolve(owner, id, definition)!!.version.toString()) + } + + @Test + fun `no version anywhere is an error that names the module`() { + val definition = ModuleDefinitionBuilder().apply { depends(Dependencies.plugin("Vault", "1.7.0", "https://example.org")) } + + val error = assertThrows(IllegalStateException::class.java) { resolver(null).resolve(owner, id, definition) } + + assertEquals(true, error.message!!.contains("shop")) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleResourceFactoryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleResourceFactoryTest.kt index 5ac93e0e5..247e0faca 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleResourceFactoryTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleResourceFactoryTest.kt @@ -14,8 +14,8 @@ import org.pnfolder.pnlibrary.api.config.ConfigScope import org.pnfolder.pnlibrary.api.currency.CurrencyService import org.pnfolder.pnlibrary.api.currency.CurrencyStorageFactory import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticsService -import org.pnfolder.pnlibrary.api.events.EventScope -import org.pnfolder.pnlibrary.api.events.EventService +import org.pnfolder.pnlibrary.api.events.bus.EventScope +import org.pnfolder.pnlibrary.api.events.bus.EventService import org.pnfolder.pnlibrary.api.logging.LoggingService import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.api.metrics.MetricsService @@ -57,7 +57,7 @@ class ModuleResourceFactoryTest { private fun factory(): ModuleResourceFactory { `when`(events.scope(key, PluginId.of("native"), id)).thenReturn(eventScope) `when`(tasks.scope(owner, key)).thenReturn(taskScope) - `when`(configurations.scope(owner, key)).thenReturn(configScope) + `when`(configurations.scope(owner, key, PluginId.of("native"), id)).thenReturn(configScope) `when`(placeholders.scope(key, false, "native", id.value)).thenReturn(placeholderScope) `when`(currency.scope(key, placeholderScope)).thenReturn(currencyScope) `when`(currency.storages).thenReturn(storageFactory) diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleRuntimeSummaryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleRuntimeSummaryTest.kt index 3803f5fd6..5974506e4 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleRuntimeSummaryTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleRuntimeSummaryTest.kt @@ -3,11 +3,11 @@ package org.pnfolder.pnlibrary.core.plugin.module import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.plugin.ModuleId -import org.pnfolder.pnlibrary.api.plugin.PluginMetadata +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata class ModuleRuntimeSummaryTest { private val metadata = PluginMetadata( diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleServiceKeyFactoryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleServiceKeyTest.kt similarity index 65% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleServiceKeyFactoryTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleServiceKeyTest.kt index a107f13f1..16b5d4e28 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleServiceKeyFactoryTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/plugin/module/ModuleServiceKeyTest.kt @@ -6,15 +6,15 @@ import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.plugin.ModuleId import org.pnfolder.pnlibrary.api.plugin.PluginId -class ModuleServiceKeyFactoryTest { +class ModuleServiceKeyTest { @Test fun `creates stable instance scoped keys`() { val nativePlugin = PluginId.of("example") val module = ModuleId.of("main") - val first = ModuleServiceKeyFactory.create(7, nativePlugin, module) - assertEquals(first, ModuleServiceKeyFactory.create(7, nativePlugin, module)) - assertNotEquals(first, ModuleServiceKeyFactory.create(8, nativePlugin, module)) + val first = moduleServiceKey(7, nativePlugin, module) + assertEquals(first, moduleServiceKey(7, nativePlugin, module)) + assertNotEquals(first, moduleServiceKey(8, nativePlugin, module)) assertEquals("m-example-main-", first.value.substringBeforeLast('-') + "-") } } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/remote/PolicyCompilersTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/remote/PolicyCompilersTest.kt index d0799e84f..bfe6f761d 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/remote/PolicyCompilersTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/remote/PolicyCompilersTest.kt @@ -36,7 +36,7 @@ class PolicyCompilersTest { } @Test - fun `a JRE where ECJ was not loaded is reported as a missing compiler`() { + fun `a JRE where ECJ cannot be loaded is reported as a missing compiler`() { val root = Files.createTempDirectory("pn-no-ecj") val bare = ClassLoader.getSystemClassLoader().parent val failure = assertThrows(IllegalStateException::class.java) { diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyFailureInterpreterTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyFailureInterpreterTest.kt index 68b599680..850716160 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyFailureInterpreterTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyFailureInterpreterTest.kt @@ -31,7 +31,7 @@ class RemotePolicyFailureInterpreterTest { @Test fun `a server without javac is told to run on a JDK`() { assertEquals( - "На сервере нет компилятора Java (это JRE), а запасной не загрузился при старте: проверьте интернет и перезапустите сервер", + "На сервере нет компилятора Java (это JRE), а запасной скачать не удалось: проверьте интернет сервера и повторите", RemotePolicyFailureInterpreter.message(IllegalStateException("Java compiler is unavailable; run the server with a JDK")), ) } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyNoticeRendererTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyNoticeRendererTest.kt index 1cd452042..83ef7fb41 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyNoticeRendererTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/remote/RemotePolicyNoticeRendererTest.kt @@ -3,15 +3,15 @@ package org.pnfolder.pnlibrary.core.remote import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.plugin.ModuleId -import org.pnfolder.pnlibrary.api.plugin.PluginMetadata +import org.pnfolder.pnlibrary.api.plugin.metadata.PluginMetadata import org.pnfolder.pnlibrary.api.remote.DenyAction import org.pnfolder.pnlibrary.api.remote.RemotePolicyExplanation import org.pnfolder.pnlibrary.api.remote.RemotePolicyResult import org.pnfolder.pnlibrary.api.remote.RemotePolicySettings -import org.pnfolder.pnlibrary.core.ui.ConsoleStyle +import org.pnfolder.pnlibrary.core.text.ConsoleStyle import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter import java.lang.reflect.Proxy diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/PnLibraryLauncherTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryLauncherTest.kt similarity index 83% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/PnLibraryLauncherTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryLauncherTest.kt index 01a428c4e..cc5f1c753 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/PnLibraryLauncherTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/PnLibraryLauncherTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core +package org.pnfolder.pnlibrary.core.runtime import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull @@ -6,13 +6,14 @@ import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.diagnostics.DiagnosticContainer +import org.pnfolder.pnlibrary.api.diagnostics.report.DiagnosticContainer import org.pnfolder.pnlibrary.api.expansions.AbstractExpansion import org.pnfolder.pnlibrary.api.expansions.ExpansionState import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.api.runtime.PnLibraryProvider import org.pnfolder.pnlibrary.core.diagnostics.DiagnosticsRegistry +import org.pnfolder.pnlibrary.core.lifecycle.mountableCommand import org.pnfolder.pnlibrary.core.runtime.PnLibraryLauncher import org.pnfolder.pnlibrary.core.runtime.platform.toRuntimeContext import org.pnfolder.pnlibrary.localization.MinecraftLocalization @@ -40,6 +41,23 @@ class PnLibraryLauncherTest { assertEquals(null, PnLibraryProvider.getOrNull()) } + @Test + fun `old settings files are imported at startup and the settings command is mounted`() { + val platform = DummyPlatformAdapter() + Files.writeString(platform.dataFolder.resolve("config.yml"), "privacy: true\nhistory-retention-days: 45\n") + + val library = PnLibraryLauncher.bootstrap(DummyPlugin("pnMarket"), platform.toRuntimeContext()) + try { + assertTrue(library.configuration.privacy) + assertEquals(45, library.configuration.historyRetentionDays) + assertTrue(Files.exists(platform.dataFolder.resolve("config.yml.old"))) + assertTrue(Files.exists(platform.dataFolder.resolve("data/settings.json"))) + assertNotNull(library.mountableCommand("settings")) + } finally { + library.close() + } + } + @Test fun `the localization loader is neither a service nor a public expansion`() { val library = PnLibraryLauncher.bootstrap(DummyPlugin("pnMarket"), DummyPlatformAdapter().toRuntimeContext()) diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeConfigurationDetailsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeConfigurationDetailsTest.kt index 1bab2cd2e..b368cfaa9 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeConfigurationDetailsTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeConfigurationDetailsTest.kt @@ -9,14 +9,12 @@ class RuntimeConfigurationDetailsTest { @Test fun `configuration details expose counts without sensitive values`() { val config = PnLibraryConfig( - excludedPaths = listOf("secret.yml"), secretKeyPatterns = listOf("token"), redactValuePatterns = listOf("password"), ) val details = RuntimeConfigurationDetails.of(config) - assertEquals(1, details["excludedPathCount"]) assertEquals(2, details["redactionRuleCount"]) assertEquals(false, details.containsKey("token")) assertEquals(false, details.containsKey("password")) diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeRemotePolicyTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeRemotePolicyTest.kt index d67e6f992..24471a7a6 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeRemotePolicyTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeRemotePolicyTest.kt @@ -16,6 +16,9 @@ import org.pnfolder.pnlibrary.api.remote.RemotePolicySettings import org.pnfolder.pnlibrary.api.remote.ServerInfo import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.api.tasks.* +import org.pnfolder.pnlibrary.api.tasks.run.TaskContext +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec import org.pnfolder.pnlibrary.common.minecraft.MinecraftVersion import org.pnfolder.pnlibrary.core.lifecycle.RuntimeResources import org.pnfolder.pnlibrary.core.remote.PolicyDeniedException @@ -74,6 +77,19 @@ class RuntimeRemotePolicyTest { } } + @Test + fun `a denial that cannot disable the library is logged as critical`() { + val fixture = fixture(PlatformType.BUKKIT) + val failure = IllegalStateException("plugin manager is gone") + `when`(fixture.platform.disableDependents(fixture.owner)).thenThrow(failure) + `when`(fixture.platform.disableOwner(fixture.owner)).thenThrow(failure) + + assertThrows(PolicyDeniedException::class.java) { fixture.start(policy("StuckPolicy", false)) } + + verify(fixture.logger).error(anyString(), eq(failure)) + verify(fixture.logger).critical(anyString(), eq(failure)) + } + @Test fun `an allowed policy keeps the plugin running on all three platforms`() { for (type in listOf(PlatformType.BUKKIT, PlatformType.VELOCITY, PlatformType.BUNGEECORD)) { @@ -201,6 +217,7 @@ class RuntimeRemotePolicyTest { val library = mock(PnLibrary::class.java, withSettings().extraInterfaces(RuntimeResources::class.java)) val platform = mock(PlatformAdapter::class.java) val tasks = mock(TaskScope::class.java) + val logger = mock(PnLogger::class.java) val ready = mutableListOf() var task: TaskSpec? = null var closed = false @@ -211,7 +228,7 @@ class RuntimeRemotePolicyTest { `when`((library as RuntimeResources).runtimeTasks).thenReturn(tasks) val logging = mock(LoggingService::class.java) `when`(library.logging).thenReturn(logging) - `when`(logging.logger(owner, "remote-policy")).thenReturn(mock(PnLogger::class.java)) + `when`(logging.logger(owner, "remote-policy")).thenReturn(logger) `when`(platform.type).thenReturn(type) `when`(platform.implementationName).thenReturn(type.name) `when`(platform.ownerDetails(owner)).thenReturn(mapOf("name" to "pnLibrary", "authors" to "pnFolder")) diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeTaskDetailsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeTaskDetailsTest.kt index 878b6d91a..2141bc047 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeTaskDetailsTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeTaskDetailsTest.kt @@ -2,10 +2,10 @@ package org.pnfolder.pnlibrary.core.runtime import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskId -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import org.pnfolder.pnlibrary.core.runtime.details.RuntimeTaskDetails import java.time.Instant diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeUpdateSummaryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeUpdateSummaryTest.kt index 0825b662b..696f636c9 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeUpdateSummaryTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/RuntimeUpdateSummaryTest.kt @@ -2,11 +2,11 @@ package org.pnfolder.pnlibrary.core.runtime import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.updates.UpdateChannel import org.pnfolder.pnlibrary.api.updates.UpdateRegistration -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ReleaseSummary +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.core.runtime.details.RuntimeUpdateSummary import java.time.Instant diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeJournalBatchTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeJournalBatchTest.kt new file mode 100644 index 000000000..54e88dbc5 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeJournalBatchTest.kt @@ -0,0 +1,42 @@ +package org.pnfolder.pnlibrary.core.runtime.details + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig +import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership +import java.nio.file.Files + +class RuntimeJournalBatchTest { + private val ownership = object : PlatformOwnership { + override fun ownerDetails(owner: Any) = mapOf("id" to "plugin") + } + + @Test + fun `a burst is written in fewer blocks than records and nothing disappears without a count`() { + val folder = Files.createTempDirectory("pnlibrary-journal-batch") + val journal = RuntimeJournal(folder.resolve("journal"), PnLibraryConfig(), ownership, 0L, "/pn events") + val total = 20_000 + + repeat(total) { journal.record(this, if (it % 50 == 0) LogLevel.ERROR else LogLevel.INFO, "event $it", null) } + journal.close() + + val failed = journal.summary()["failedWrites"] as Long + val stored = journal.store.read(limit = 100_000).size + assertEquals(total.toLong(), stored + failed) + assertTrue(journal.store.blocksWritten.get() < total, "blocks: ${journal.store.blocksWritten.get()}") + } + + @Test + fun `records recorded one after another are all stored`() { + val folder = Files.createTempDirectory("pnlibrary-journal-seq") + val journal = RuntimeJournal(folder.resolve("journal"), PnLibraryConfig(), ownership, 0L, "/pn events") + + repeat(300) { journal.record(this, LogLevel.WARNING, "w $it", null) } + journal.close() + + assertEquals((0 until 300).map { "w $it" }.toSet(), journal.store.read(limit = 1_000).map { it.message }.toSet()) + assertEquals(0L, journal.summary()["failedWrites"]) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeJournalTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeJournalTest.kt new file mode 100644 index 000000000..47e8f947a --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/details/RuntimeJournalTest.kt @@ -0,0 +1,37 @@ +package org.pnfolder.pnlibrary.core.runtime.details + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.api.runtime.PnLibraryConfig +import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership +import java.nio.file.Files +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +class RuntimeJournalTest { + private val ownership = object : PlatformOwnership { + override fun ownerDetails(owner: Any) = mapOf("id" to "plugin") + } + + @Test + fun `a failed journal write is reported once instead of being lost`() { + val folder = Files.createTempDirectory("pnlibrary-journal-test") + Files.writeString(folder.resolve("journal"), "a file where the journal folder should be") + val reported = mutableListOf() + val first = CountDownLatch(1) + val journal = RuntimeJournal(folder.resolve("journal"), PnLibraryConfig(), ownership, 0L, "/pn events") { + reported += it + first.countDown() + } + + journal.record(this, LogLevel.ERROR, "one", null) + assertTrue(first.await(5, TimeUnit.SECONDS)) + journal.record(this, LogLevel.ERROR, "two", null) + journal.close() + + assertEquals(1, reported.size) + assertEquals(2L, journal.summary()["failedWrites"]) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/platform/NativePlatformTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/NativePlatformTest.kt similarity index 97% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/platform/NativePlatformTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/NativePlatformTest.kt index 6ffa962d8..224474655 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/platform/NativePlatformTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/NativePlatformTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.platform +package org.pnfolder.pnlibrary.core.runtime.platform import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertSame diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/audiences/PlatformAudiencesTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformAudiencesTest.kt similarity index 82% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/audiences/PlatformAudiencesTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformAudiencesTest.kt index d0bc2cd8e..e24e4a49a 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/audiences/PlatformAudiencesTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/runtime/platform/PlatformAudiencesTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.audiences +package org.pnfolder.pnlibrary.core.runtime.platform import net.kyori.adventure.key.Key import net.kyori.adventure.sound.Sound @@ -10,9 +10,9 @@ import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.audiences.AudienceSender import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.audiences.PlayerEffect -import org.pnfolder.pnlibrary.api.audiences.PlayerParticle +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.audiences.player.PlayerEffect +import org.pnfolder.pnlibrary.api.audiences.player.PlayerParticle import org.pnfolder.pnlibrary.spi.audiences.PlatformAudienceAdapter import java.util.UUID @@ -57,6 +57,19 @@ class PlatformAudiencesTest { assertEquals("NowOnline:bar", calls.last()) } + @Test + fun `a receiver that throws is reported once and the others still get the message`() { + val calls = mutableListOf() + val failures = mutableListOf() + val service = PlatformAudiences(RecordingAdapter(Sender("console"), mutableListOf())) { failures += it } + val composite = service.combine(listOf(Sender("broken", calls = calls, failMessages = true), Sender("last", calls = calls))) + + repeat(2) { composite.sendMessage(Component.text("hello")) } + + assertEquals(1, failures.size) + assertEquals(listOf("broken:message", "last:message", "broken:message", "last:message"), calls) + } + private open class Sender( override val name: String, private val console: Boolean = false, diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/ChoiceSourceTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/ChoiceSourceTest.kt new file mode 100644 index 000000000..2e61eb38b --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/ChoiceSourceTest.kt @@ -0,0 +1,133 @@ +package org.pnfolder.pnlibrary.core.settings + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.time.Instant +import java.time.ZoneId + +class ChoiceSourceTest { + private val zones = ChoiceSource.ZONES + private val winter = Instant.parse("2026-01-15T12:00:00Z") + private val summer = Instant.parse("2026-07-15T12:00:00Z") + + @Test + fun `zones are sorted, unique and contain the ones people look for`() { + assertEquals(zones.all.sorted(), zones.all) + assertEquals(zones.all.size, zones.all.toSet().size) + listOf("Europe/Moscow", "America/New_York", "Asia/Tokyo", "UTC", "Etc/UTC").forEach { assertTrue(it in zones.all, it) } + } + + @Test + fun `legacy aliases and the GMT series are left out`() { + assertFalse(zones.all.any { it.startsWith("SystemV/") || it.startsWith("Etc/GMT") || it.startsWith("US/") }) + assertTrue(zones.all.all { runCatching { ZoneId.of(it) }.isSuccess }) + } + + @Test + fun `the default order covers every zone by offset and then by name`() { + val shown = zones.view(0, false, "", winter) + + assertEquals(zones.all.toSet(), shown.toSet()) + assertEquals(zones.all.size, shown.size) + assertEquals(shown.sortedWith(compareBy({ ChoiceSource.offsetSeconds(it, winter) }, { it })), shown) + val plusThree = shown.filter { ChoiceSource.offsetSeconds(it, winter) == 3 * 3600 } + assertTrue("Europe/Moscow" in plusThree && "Africa/Nairobi" in plusThree && plusThree == plusThree.sorted()) + } + + @Test + fun `the offset order follows summer time and the alphabet order does not`() { + val berlinWinter = ChoiceSource.offsetSeconds("Europe/Berlin", winter) + val berlinSummer = ChoiceSource.offsetSeconds("Europe/Berlin", summer) + + assertEquals(3600, berlinWinter) + assertEquals(7200, berlinSummer) + assertEquals(zones.all, zones.view(1, false, "", winter)) + assertEquals(listOf("по смещению UTC", "по алфавиту"), zones.orders.map { it.label }) + } + + @Test + fun `popular zones are valid ids in the given order`() { + val wanted = listOf( + "UTC", "Europe/London", "Europe/Berlin", "Europe/Kyiv", "Europe/Minsk", "Europe/Moscow", "Europe/Istanbul", "Asia/Dubai", + "Asia/Tashkent", "Asia/Almaty", "Asia/Kolkata", "Asia/Bangkok", "Asia/Shanghai", "Asia/Tokyo", "Australia/Sydney", + "Pacific/Auckland", "America/Sao_Paulo", "America/New_York", "America/Chicago", "America/Denver", "America/Los_Angeles", + ) + + assertEquals(wanted.filter { it in zones.all }, zones.popular) + assertEquals(zones.popular, zones.view(0, true, "", winter)) + assertTrue(zones.popular.all { it in zones.all }) + assertEquals("UTC", zones.popular.first()) + val custom = ChoiceSource("x", listOf("a", "b"), curated = listOf("b", "missing", "a")) + assertEquals(listOf("b", "a"), custom.popular) + } + + @Test + fun `a filter ignores case and the difference between underscore, slash and space`() { + assertEquals(listOf("America/New_York"), zones.view(0, false, "new york", winter)) + assertEquals(listOf("America/New_York"), zones.view(0, false, "NEW_YORK", winter)) + assertEquals(listOf("America/New_York"), zones.view(0, false, "america/new_york", winter)) + assertTrue(zones.view(0, false, "moscow", winter) == listOf("Europe/Moscow")) + assertTrue(zones.view(0, false, "europe/", winter).all { it.startsWith("Europe/") }) + assertTrue(zones.view(0, false, "no such zone anywhere", winter).isEmpty()) + assertEquals(zones.view(0, false, "", winter), zones.view(0, false, " ", winter)) + assertEquals(zones.view(0, false, "york", winter), zones.view(0, true, "york", winter), "a filter searches everything") + } + + @Test + fun `offsets are written as UTC, UTC+03 00 and UTC-05 00`() { + assertEquals("UTC", ChoiceSource.offsetText(0)) + assertEquals("UTC+03:00", ChoiceSource.offsetText(3 * 3600)) + assertEquals("UTC-05:00", ChoiceSource.offsetText(-5 * 3600)) + assertEquals("UTC+05:30", ChoiceSource.offsetText(5 * 3600 + 1800)) + assertEquals("UTC-09:30", ChoiceSource.offsetText(-(9 * 3600 + 1800))) + } + + @Test + fun `a zone tells the time there and its current offset`() { + assertEquals(listOf("Смещение" to "UTC+03:00", "Сейчас там" to "15:00"), zones.lore("Europe/Moscow", winter)) + assertEquals(listOf("Смещение" to "UTC-05:00", "Сейчас там" to "07:00"), zones.lore("America/New_York", winter)) + assertEquals(listOf("Смещение" to "UTC-04:00", "Сейчас там" to "08:00"), zones.lore("America/New_York", summer)) + assertEquals(listOf("Смещение" to "UTC", "Сейчас там" to "12:00"), zones.lore("UTC", winter)) + assertTrue(ChoiceSource("x", listOf("a")).lore("a").isEmpty()) + } + + @Test + fun `the source is found again by the name that travels over the link`() { + val spec = requireNotNull(SettingsRegistry["time-zone"]) + + assertEquals(zones, ChoiceSource.named(zones.id)) + assertNull(ChoiceSource.named("nope")) + assertEquals(zones.id, spec.choices?.id) + assertEquals(SettingKind.CHOICE, spec.kind) + } + + @Test + fun `the cycle of zones is every zone and steps wrap around`() { + val all = zones.all + + assertEquals(all, zones.cycle) + assertEquals(all[1], zones.step(all[0], false)) + assertEquals(all.last(), zones.step(all[0], true)) + assertEquals(all.first(), zones.step(all.last(), false)) + } + + @Test + fun `a zone outside the cycle comes first in the rolling list and steps to the ends`() { + assertEquals(listOf("US/Pacific") + zones.cycle, zones.rolling("US/Pacific")) + assertEquals(zones.cycle, zones.rolling("Europe/Moscow")) + assertEquals(zones.cycle.first(), zones.step("US/Pacific", false)) + assertEquals(zones.cycle.last(), zones.step("US/Pacific", true)) + } + + @Test + fun `a source without a cycle rolls through all its values`() { + val source = ChoiceSource("letters", listOf("a", "b", "c")) + + assertEquals(listOf("a", "b", "c"), source.cycle) + assertEquals("a", source.step("c", false)) + assertEquals("c", source.step("a", true)) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/LegacySettingsImportTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/LegacySettingsImportTest.kt new file mode 100644 index 000000000..414924be9 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/LegacySettingsImportTest.kt @@ -0,0 +1,111 @@ +package org.pnfolder.pnlibrary.core.settings + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.downloads.DownloadDestination +import org.pnfolder.pnlibrary.core.downloads.settings.downloads +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import java.nio.file.Files +import java.nio.file.Path + +class LegacySettingsImportTest { + @TempDir lateinit var directory: Path + + private val warnings = mutableListOf() + private val paths by lazy { LibraryPaths(directory.resolve("plugins/pnLibrary")) } + + private fun write(file: Path, text: String) { + Files.createDirectories(file.parent) + Files.writeString(file, text) + } + + private fun import(): SettingsStore = + SettingsStore(paths.settings) { warnings += it }.also { LegacySettingsImport(paths) { text -> warnings += text }.run(it) } + + @Test + fun `the values of the old files are taken over once and the files are renamed`() { + write( + paths.legacyConfig, + "# header\nprivacy: true\nhistory-retention-days: 60\ntime-zone: Europe/Moscow\n" + + "no-permission-message: Нельзя\njournal-foreign-plugins: false\n", + ) + write(paths.legacyDownloadsConfig, "enabled: true\nautomatic: false\ndestinations:\n data-folder: true\n cache: false\n") + + val store = import() + + val settings = store.current() + assertTrue(settings.privacy) + assertEquals(60, settings.historyRetentionDays) + assertEquals("Europe/Moscow", settings.timeZone) + assertEquals("Нельзя", settings.noPermissionMessage) + assertFalse(settings.downloads().automatic) + assertEquals(setOf(DownloadDestination.DATA_FOLDER), settings.downloads().destinations) + assertFalse(Files.exists(paths.legacyConfig)) + assertFalse(Files.exists(paths.legacyDownloadsConfig)) + assertTrue(Files.exists(paths.legacyConfig.resolveSibling("config.yml.old"))) + assertTrue(Files.exists(paths.legacyDownloadsConfig.resolveSibling("downloads.yml.old"))) + assertEquals(setOf("privacy", "history-retention-days", "time-zone", "no-permission-message", "downloads.automatic", "downloads.destinations.cache"), + store.values().filter { it.changed }.map { it.spec.key }.toSet()) + + val again = SettingsStore(paths.settings) + LegacySettingsImport(paths).run(again) + assertEquals(settings, again.current(), "a second start changes nothing") + } + + @Test + fun `the download choice made in game beats the old file and is removed`() { + write(paths.legacyDownloadsConfig, "automatic: true\n") + write(paths.downloads.resolve("preferences.state"), "automatic=false\n") + + val store = import() + + assertFalse(store.current().downloadsAutomatic) + assertFalse(Files.exists(paths.downloads.resolve("preferences.state"))) + } + + @Test + fun `what was already set by command is not overwritten by an old file`() { + SettingsStore(paths.settings).set("history-retention-days", "120") + write(paths.legacyConfig, "history-retention-days: 45\nprivacy: true\n") + + val store = import() + + assertEquals(120, store.current().historyRetentionDays) + assertTrue(store.current().privacy) + } + + @Test + fun `an invalid or removed key is reported and the rest is still imported`() { + write(paths.legacyConfig, "history-retention-days: 7\nexcluded-paths:\n - plugins\nprivacy: true\n") + + val store = import() + + assertEquals(30, store.current().historyRetentionDays) + assertTrue(store.current().privacy) + assertTrue(warnings.any { it.contains("history-retention-days") }) + assertTrue(warnings.any { it.contains("excluded-paths") }) + } + + @Test + fun `a file that is not yaml stays where it is`() { + write(paths.legacyConfig, "privacy: [unclosed\n") + + val store = import() + + assertEquals(LibrarySettings(), store.current()) + assertTrue(Files.exists(paths.legacyConfig)) + assertTrue(warnings.any { it.contains("config.yml") }) + } + + @Test + fun `without old files nothing happens`() { + val store = import() + + assertEquals(LibrarySettings(), store.current()) + assertFalse(Files.exists(paths.settings)) + assertTrue(warnings.isEmpty()) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/LibraryCommandGuideTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/LibraryCommandGuideTest.kt new file mode 100644 index 000000000..b38b005ec --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/LibraryCommandGuideTest.kt @@ -0,0 +1,54 @@ +package org.pnfolder.pnlibrary.core.settings + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.nio.file.Files +import java.nio.file.Paths + +class LibraryCommandGuideTest { + /** The permissions the Bukkit plugin declares; the working directory of a core test is the module folder. */ + private val declared: Set = Files + .readAllLines(Paths.get("../../platforms/bukkit/runtime/src/main/resources/plugin.yml")) + .mapNotNull { Regex("""^ (pnlibrary\.[a-z.]+):\s*$""").find(it)?.groupValues?.get(1) } + .toSet() + + @Test + fun `every permission of plugin yml is in the guide`() { + assertTrue(declared.size >= 10, "plugin.yml permissions were not found") + val missing = declared - LibraryCommandGuide.permissions + assertTrue(missing.isEmpty(), "Команды.txt does not list: $missing") + } + + @Test + fun `every permission of the guide is declared in plugin yml or belongs to the proxy only`() { + val unknown = LibraryCommandGuide.permissions - declared - LibraryCommandGuide.proxyOnly + assertTrue(unknown.isEmpty(), "not in plugin.yml and not marked proxy-only: $unknown") + assertTrue(LibraryCommandGuide.proxyOnly.all { it !in declared }, "a proxy-only permission is declared for Bukkit") + } + + @Test + fun `every entry is complete and no command is listed twice`() { + LibraryCommandGuide.entries.forEach { entry -> + assertTrue(entry.usage.isNotBlank() && entry.description.isNotBlank(), entry.usage) + assertTrue(entry.permission == null || entry.permission.startsWith("pnlibrary."), entry.usage) + } + val usages = LibraryCommandGuide.entries.map { it.usage } + assertEquals(usages.size, usages.toSet().size, "a command is listed twice") + } + + @Test + fun `an entry without a permission says why`() { + LibraryCommandGuide.entries.filter { it.permission == null }.forEach { assertTrue(it.note != null, it.usage) } + } + + @Test + fun `the guide names every command word of the control command`() { + val words = LibraryCommandGuide.entries.map { it.usage.split(' ').getOrNull(1).orEmpty() }.toSet() + listOf( + "status", "check", "gui", "updates", "update", "events", "bus", "tasks", "stats", "placeholders", "settings", "configs", "deps", + "debug", "servers", "groups", "money", "support", + ) + .forEach { assertTrue(it in words, it) } + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/LibraryInfoFilesTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/LibraryInfoFilesTest.kt new file mode 100644 index 000000000..e74da29d4 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/LibraryInfoFilesTest.kt @@ -0,0 +1,171 @@ +package org.pnfolder.pnlibrary.core.settings + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.Files +import java.nio.file.Path +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset + +class LibraryInfoFilesTest { + @TempDir lateinit var directory: Path + + private val warnings = mutableListOf() + private val plugin: Path get() = directory.resolve("plugins/pnLibrary") + private val paths: LibraryPaths get() = LibraryPaths(plugin) + private val store by lazy { SettingsStore(paths.settings) } + + private fun files(now: String = "2026-11-15T12:30:00Z", pluginPaths: LibraryPaths = paths) = + LibraryInfoFiles(pluginPaths, store::values, "1.2.3", Clock.fixed(Instant.parse(now), ZoneOffset.UTC)) { warnings += it } + + private fun read(name: String): String = Files.readString(plugin.resolve(name), UTF_8) + + @Test + fun `the help carries the current links, the commands, the version and the time`() { + val text = files().helpText() + + assertTrue(PnLibraryIdentity.SUPPORT_URL in text) + assertTrue(PnLibraryIdentity.REPOSITORY_URL in text) + assertTrue("${PnLibraryIdentity.REPOSITORY_URL}/tree/main/docs" in text) + listOf("/pn settings", "/pn debug", "/pn updates", "заказать", "data/", "Команды.txt", "Настройки.txt").forEach { assertTrue(it in text, it) } + assertTrue("Этот файл создаётся заново при каждом запуске, ваши правки не сохранятся." in text) + assertTrue(text.trimEnd().endsWith("${PnLibraryIdentity.NAME} 1.2.3\nСоздан: 2026-11-15 12:30 UTC"), text) + } + + @Test + fun `the links are the ones given, not remembered ones`() { + val text = LibraryInfoFiles(paths, store::values, "1", supportUrl = "https://example.org/help", repositoryUrl = "https://example.org/code").helpText() + + assertTrue("https://example.org/help" in text) + assertTrue("https://example.org/code/tree/main/docs" in text) + } + + @Test + fun `the overview lists every setting with its value, default, limits and description`() { + val text = files().settingsText() + + SettingsRegistry.all.forEach { spec -> + assertTrue(spec.key in text, spec.key) + assertTrue(spec.title in text, spec.key) + assertTrue(spec.description in text, spec.key) + assertTrue(spec.display(spec.default) in text, spec.key) + if (spec.range().isNotEmpty()) assertTrue(spec.range() in text, spec.key) + } + assertTrue("/pn settings set" in text) + assertTrue("Этот файл создаётся заново" in text) + } + + @Test + fun `the overview shows the new value after a change`() { + val files = files() + files.refresh() + assertTrue("Сейчас: 30 (по умолчанию)" in read("Настройки.txt")) + + store.onChange { files.refreshSettings() } + store.set("history-retention-days", "120") + + assertTrue("Сейчас: 120 (изменено администратором)" in read("Настройки.txt"), read("Настройки.txt")) + assertTrue(warnings.isEmpty(), warnings.toString()) + } + + @Test + fun `the help keeps its list of useful commands short`() { + val lines = files().helpText().lines() + val start = lines.indexOf("Самые полезные команды") + + assertTrue(start >= 0) + assertTrue(lines.drop(start + 1).takeWhile { it.startsWith(" /pn") }.size <= 8, lines.toString()) + } + + @Test + fun `the command file has the header, every permission and the creation time`() { + val text = files().commandsText() + + assertTrue("Все права по умолчанию у операторов; назначайте их в LuckPerms или другом менеджере прав." in text) + assertTrue("Этот файл создаётся заново при каждом запуске, ваши правки не сохранятся." in text) + LibraryCommandGuide.entries.forEach { entry -> + assertTrue(entry.usage in text, entry.usage) + entry.permission?.let { assertTrue(it in text, it) } + } + assertTrue(text.trimEnd().endsWith("${PnLibraryIdentity.NAME} 1.2.3\nСоздан: 2026-11-15 12:30 UTC"), text) + } + + @Test + fun `the three files are written as UTF-8 under their Russian names`() { + files().refresh() + + assertTrue(Files.isRegularFile(plugin.resolve("Команды.txt"))) + assertFalse(Files.exists(plugin.resolve("COMMANDS.txt"))) + assertFalse(read("Команды.txt").contains('\r')) + + assertTrue(Files.isRegularFile(plugin.resolve("Помощь.txt"))) + assertTrue(Files.isRegularFile(plugin.resolve("Настройки.txt"))) + assertFalse(Files.exists(plugin.resolve("HELP.txt"))) + assertFalse(read("Помощь.txt").contains('\r')) + assertEquals("Помощь pnLibrary", read("Помощь.txt").lines().first()) + } + + @Test + fun `a start that changes nothing leaves the files alone, only the time line is ignored`() { + files("2026-11-15T12:30:00Z").refresh() + val before = read("Помощь.txt") + + files("2026-11-16T08:00:00Z").refresh() + + assertEquals(before, read("Помощь.txt")) + assertTrue("Все права по умолчанию у операторов" in read("Команды.txt")) + } + + @Test + fun `a new version rewrites the files`() { + files().refresh() + LibraryInfoFiles(paths, store::values, "9.9.9").refresh() + + assertTrue("${PnLibraryIdentity.NAME} 9.9.9" in read("Помощь.txt")) + } + + @Test + fun `when the Russian name cannot be used the ASCII names are written`() { + // A folder in the way makes the Russian name unusable, as an unmappable name does on a non-UTF-8 JVM. + Files.createDirectories(plugin.resolve("Помощь.txt/inside")) + Files.createDirectories(plugin.resolve("Настройки.txt/inside")) + Files.createDirectories(plugin.resolve("Команды.txt/inside")) + + files().refresh() + + assertTrue(Files.isRegularFile(plugin.resolve("HELP.txt"))) + assertTrue(Files.isRegularFile(plugin.resolve("SETTINGS.txt"))) + assertTrue(Files.isRegularFile(plugin.resolve("COMMANDS.txt"))) + assertTrue(PnLibraryIdentity.SUPPORT_URL in read("HELP.txt")) + assertTrue(warnings.isEmpty(), warnings.toString()) + } + + @Test + fun `a failure never throws and is reported once`() { + Files.createDirectories(directory.resolve("plugins")) + Files.writeString(plugin, "not a folder") + val files = files() + + files.refresh() + files.refresh() + + assertEquals(1, warnings.size, warnings.toString()) + } + + @Test + fun `switches are written in Russian in the overview`() { + val text = files().settingsText() + + assertTrue("Сейчас: выключено (по умолчанию)" in text, text) + assertTrue("По умолчанию: включено" in text, text) + assertTrue("/pn settings set privacy включено" in text, text) + assertFalse(Regex("""(Сейчас|По умолчанию): (true|false)""").containsMatchIn(text), text) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/SettingsRegistryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/SettingsRegistryTest.kt new file mode 100644 index 000000000..3e2acb8cc --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/SettingsRegistryTest.kt @@ -0,0 +1,103 @@ +package org.pnfolder.pnlibrary.core.settings + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.lang.reflect.Modifier +import java.nio.file.Files +import java.nio.file.Paths +import java.time.Duration + +class SettingsRegistryTest { + private val fields = LibrarySettings::class.java.declaredFields.filter { !Modifier.isStatic(it.modifiers) }.map { it.name } + + @Test + fun `every setting of the library has exactly one entry in the registry`() { + assertTrue(fields.isNotEmpty()) + val covered = SettingsRegistry.all.map { it.field } + assertEquals(fields.sorted(), covered.sorted(), "a field without an entry (or an entry without a field)") + assertEquals(covered.size, covered.toSet().size, "two entries for one field") + assertEquals(SettingsRegistry.all.size, SettingsRegistry.all.map { it.key }.toSet().size, "a key is used twice") + } + + @Test + fun `the default of every setting is accepted by that setting`() { + SettingsRegistry.all.forEach { spec -> + assertEquals(spec.default, spec.normalize(spec.default), spec.key) + assertEquals(LibrarySettings(), spec.apply(LibrarySettings(), spec.default), spec.key) + assertTrue(spec.description.isNotBlank() && spec.title.isNotBlank(), spec.key) + } + assertEquals(LibrarySettings().toConfig().historyRetentionDays, 30) + } + + @Test + fun `the docs describe every setting and every permission of plugin yml`() { + val docs = Files.readString(Paths.get("../../docs/settings.md")) + val missing = SettingsRegistry.all.map { it.key }.filterNot { "`$it`" in docs } + assertTrue(missing.isEmpty(), "docs/settings.md does not describe: $missing") + val pluginYml = Paths.get("../../platforms/bukkit/runtime/src/main/resources/plugin.yml") + val declared = Files.readAllLines(pluginYml).mapNotNull { Regex("""^ (pnlibrary\.[a-z.]+):\s*$""").find(it)?.groupValues?.get(1) } + assertTrue(declared.size >= 10, "plugin.yml permissions were not found") + val unlisted = declared.filterNot { it in docs } + assertTrue(unlisted.isEmpty(), "docs/settings.md does not mention: $unlisted") + } + + @Test + fun `switches read the usual words and refuse the rest`() { + val spec = requireNotNull(SettingsRegistry["privacy"]) + assertEquals("true", spec.normalize("ON")) + assertEquals("false", spec.normalize(" нет ")) + assertThrows(SettingException::class.java) { spec.normalize("maybe") } + } + + @Test + fun `numbers stay inside their limits`() { + val spec = requireNotNull(SettingsRegistry["history-retention-days"]) + assertEquals("365", spec.normalize("365")) + assertTrue(assertThrows(SettingException::class.java) { spec.normalize("366") }.message.orEmpty().contains("от 30 до 365")) + assertThrows(SettingException::class.java) { spec.normalize("30.5") } + assertThrows(SettingException::class.java) { spec.normalize("") } + } + + @Test + fun `times are typed with units in either language and written in the shortest form`() { + val spec = requireNotNull(SettingsRegistry["updates.check-interval"]) + assertEquals("1ч30м", spec.normalize("90m")) + assertEquals("1ч30м", spec.normalize("1h 30 мин")) + assertEquals("6ч", spec.normalize("6h")) + assertEquals(Duration.ofHours(12), spec.apply(LibrarySettings(), "12h").updateCheckInterval) + assertThrows(SettingException::class.java) { spec.normalize("5m") } + assertThrows(SettingException::class.java) { spec.normalize("8d") } + assertThrows(SettingException::class.java) { spec.normalize("6") } + } + + @Test + fun `a time zone and a message are checked`() { + val zone = requireNotNull(SettingsRegistry["time-zone"]) + assertEquals("Europe/Moscow", zone.normalize(" Europe/Moscow ")) + assertThrows(SettingException::class.java) { zone.normalize("Mars/Base") } + val message = requireNotNull(SettingsRegistry["no-permission-message"]) + assertThrows(SettingException::class.java) { message.normalize(" ") } + assertThrows(SettingException::class.java) { message.normalize("я".repeat(257)) } + } + + @Test + fun `a switch is read in Russian and shown in Russian while it is stored as true or false`() { + val spec = requireNotNull(SettingsRegistry["privacy"]) + listOf("вкл", "включено", "Да", "true", "on").forEach { assertEquals("true", spec.normalize(it), it) } + listOf("выкл", "выключено", "нет", "false", "off").forEach { assertEquals("false", spec.normalize(it), it) } + assertEquals("включено", spec.display("true")) + assertEquals("выключено", spec.display(spec.default)) + assertEquals("30", requireNotNull(SettingsRegistry["history-retention-days"]).display("30")) + } + + @Test + fun `the time zone is a choice from the list of zones and still accepts any known zone id`() { + val zone = requireNotNull(SettingsRegistry["time-zone"]) + + assertEquals(SettingKind.CHOICE, zone.kind) + assertTrue("Europe/Moscow" in zone.choices?.all.orEmpty()) + assertEquals("Asia/Tokyo", zone.normalize("Asia/Tokyo")) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/SettingsStoreTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/SettingsStoreTest.kt new file mode 100644 index 000000000..746b23c29 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/settings/SettingsStoreTest.kt @@ -0,0 +1,137 @@ +package org.pnfolder.pnlibrary.core.settings + +import com.google.gson.JsonParser +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Files +import java.nio.file.Path +import java.time.Duration + +class SettingsStoreTest { + @TempDir lateinit var directory: Path + + private val warnings = mutableListOf() + private val file: Path get() = directory.resolve("data/settings.json") + + private fun store() = SettingsStore(file) { warnings += it } + + @Test + fun `a new server has the defaults and no file`() { + val store = store() + + assertEquals(LibrarySettings(), store.current()) + assertFalse(Files.exists(file)) + assertTrue(store.values().none { it.changed }) + assertTrue(warnings.isEmpty()) + } + + @Test + fun `a value survives a restart and only changed values are written`() { + val first = store() + first.set("privacy", "true") + first.set("updates.check-interval", "90m") + first.set("downloads.destinations.cache", "off") + + val second = store() + + assertTrue(second.current().privacy) + assertEquals(Duration.ofMinutes(90), second.current().updateCheckInterval) + assertFalse(second.current().downloadsToCache) + val changed = second.values().filter { it.changed }.map { it.spec.key }.toSet() + assertEquals(setOf("privacy", "updates.check-interval", "downloads.destinations.cache"), changed) + val json = JsonParser.parseString(Files.readString(file)).asJsonObject + assertEquals(setOf("privacy", "updates.check-interval", "downloads.destinations.cache"), json.keySet()) + assertTrue(json.get("privacy").asJsonPrimitive.isBoolean) + assertEquals("1ч30м", json.get("updates.check-interval").asString) + assertTrue(warnings.isEmpty()) + } + + @Test + fun `reset returns a setting to its default and removes it from the file`() { + val store = store() + store.set("history-retention-days", "90") + + val change = store.reset("history-retention-days") + + assertEquals("90", change.before) + assertEquals("30", change.after) + assertEquals(30, store.current().historyRetentionDays) + assertFalse(JsonParser.parseString(Files.readString(file)).asJsonObject.has("history-retention-days")) + } + + @Test + fun `an invalid value is refused and nothing changes`() { + val store = store() + store.set("history-retention-days", "60") + + assertThrows(SettingException::class.java) { store.set("history-retention-days", "7") } + assertThrows(SettingException::class.java) { store.set("no-such-key", "1") } + assertThrows(SettingException::class.java) { store.reset("no-such-key") } + + assertEquals(60, store().current().historyRetentionDays) + } + + @Test + fun `invalid values in the file fall back to the defaults with a warning`() { + Files.createDirectories(file.parent) + Files.writeString( + file, + """{"history-retention-days": 7, "privacy": "maybe", "time-zone": "Mars/Base", "mystery": 1,""" + + """ "journal-foreign-plugins": true, "downloads.enabled": [1]}""", + ) + + val store = store() + + assertEquals(30, store.current().historyRetentionDays) + assertFalse(store.current().privacy) + assertEquals(LibrarySettings().timeZone, store.current().timeZone) + assertTrue(store.current().downloadsEnabled) + assertTrue(store.current().journalForeignPlugins, "a valid value next to broken ones is kept") + assertEquals(5, warnings.size, warnings.toString()) + assertTrue(warnings.any { it.contains("history-retention-days") }) + assertTrue(warnings.any { it.contains("mystery") }) + } + + @Test + fun `a file that is not json is moved aside and the defaults are used`() { + Files.createDirectories(file.parent) + Files.writeString(file, "{ not json") + + val store = store() + + assertEquals(LibrarySettings(), store.current()) + assertTrue(Files.exists(directory.resolve("data/settings.json.broken"))) + assertEquals(1, warnings.size) + store.set("privacy", "true") + assertTrue(store().current().privacy) + } + + @Test + fun `listeners hear about a change and the config follows it`() { + val store = store() + val heard = mutableListOf() + store.onChange { heard += it.timeZone } + + store.set("time-zone", "Europe/Moscow") + + assertEquals(listOf("Europe/Moscow"), heard) + assertEquals("Europe/Moscow", store.config().timeZone) + store.set("privacy", "true") + assertTrue(store.config().privacy) + } + + @Test + fun `a failing listener does not undo a saved change`() { + val store = store() + store.onChange { error("boom") } + + store.set("privacy", "true") + + assertTrue(store.current().privacy) + assertTrue(warnings.single().contains("privacy")) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/stats/StatsCollectorTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/stats/StatsCollectorTest.kt index aecdf6844..22e27883f 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/stats/StatsCollectorTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/stats/StatsCollectorTest.kt @@ -4,10 +4,10 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.events.EventInfo +import org.pnfolder.pnlibrary.api.events.inspect.EventInfo import org.pnfolder.pnlibrary.core.journal.JournalLevel import org.pnfolder.pnlibrary.core.journal.JournalRecord -import org.pnfolder.pnlibrary.core.journal.JournalStore +import org.pnfolder.pnlibrary.core.journal.store.JournalStore import java.nio.file.Path import java.time.Duration @@ -63,4 +63,15 @@ class StatsCollectorTest { assertEquals(1, history.single().errors24h) assertTrue(journal.read(levels = setOf(JournalLevel.INFO)).none { it.type == StatsSnapshot.RECORD_TYPE }) } + + @Test + fun `a snapshot that cannot be taken is reported and does not reach the caller`() { + val journal = journal() + val failures = mutableListOf() + val broken = StatsCollector({ throw IllegalStateException("tasks unavailable") }, { emptyList() }, journal) + + StatsRecorder(broken, journal) { failures += it }.record() + + assertEquals(listOf("tasks unavailable"), failures.map { it.message }) + } } diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/ManagedTaskTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/ManagedTaskTest.kt index 3a609a4a3..f99edb6dd 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/ManagedTaskTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/ManagedTaskTest.kt @@ -6,11 +6,12 @@ import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.tasks.TaskConflictPolicy -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskSpec -import org.pnfolder.pnlibrary.api.tasks.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.spec.TaskConflictPolicy +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskAdapter +import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskBuilder import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskHandle import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest import java.time.Duration @@ -125,7 +126,9 @@ class ManagedTaskTest { private class FakeAdapter : PlatformTaskAdapter { val requests = mutableListOf() - override fun schedule(request: PlatformTaskRequest): PlatformTaskHandle { + override fun buildTask() = PlatformTaskBuilder(::dispatch) + + private fun dispatch(request: PlatformTaskRequest): PlatformTaskHandle { requests += request return object : PlatformTaskHandle { override fun cancel() = true diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/ScheduledTasksTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/ScheduledTasksTest.kt similarity index 56% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/ScheduledTasksTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/ScheduledTasksTest.kt index 464a6f85f..6d101a87a 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/ScheduledTasksTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/ScheduledTasksTest.kt @@ -1,9 +1,17 @@ -package org.pnfolder.pnlibrary.core +package org.pnfolder.pnlibrary.core.tasks import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.api.tasks.* +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskQuery +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.spec.TaskConflictPolicy +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec +import org.pnfolder.pnlibrary.api.tasks.spec.schedule +import org.pnfolder.pnlibrary.api.tasks.spec.spawn import org.pnfolder.pnlibrary.core.tasks.ScheduledTasks import org.pnfolder.pnlibrary.core.tasks.TaskControl import org.pnfolder.pnlibrary.spi.tasks.* @@ -73,19 +81,6 @@ class ScheduledTasksTest { service.close() } - @Test - fun `native task request retains scope owner identity`() { - val adapter = RecordingAdapter() - val owner = Any() - val service = ScheduledTasks(adapter) - try { - service.scope(owner).schedule(spec("owned")) - assertSame(owner, adapter.requests.single().owner) - } finally { - service.close() - } - } - @Test fun `task can cancel itself and native handle is cancelled`() { val adapter = RecordingAdapter() @@ -97,6 +92,179 @@ class ScheduledTasksTest { assertTrue(adapter.handles[0].cancelled.get()) } + @Test + fun `the context reports the run, the plan, the settings and cancels after a limit`() { + val adapter = RecordingAdapter() + val scope = ScheduledTasks(adapter).scope(Any()) + val seen = mutableListOf() + val handle = scope.schedule(TaskSpec.builder().name("ctx").key("k").tag("t").interval(Duration.ofSeconds(1)) + .action { c -> + seen += "${c.runNumber}:${c.isFirstRun}:${c.every(2)}:${c.key}:${c.tags}:${c.isRepeating}:${c.previousStartedAt != null}" + check(!c.lag.isNegative) + check(c.snapshot().runCount == c.runNumber) + c.cancelAfter(3) + }.build()) + + repeat(3) { adapter.fire(0) } + + assertEquals(listOf("1:true:false:k:[t]:true:false", "2:false:true:k:[t]:true:true", "3:false:false:k:[t]:true:true"), seen) + assertEquals(TaskStatus.CANCELLED, handle.status) + } + + @Test + fun `a task starts a follow-up that stays in the same scope`() { + val adapter = RecordingAdapter() + val scope = ScheduledTasks(adapter).scope(Any()) + val ran = mutableListOf() + scope.schedule(TaskSpec.builder().name("parent").action { c -> + c.later(Duration.ofSeconds(5)) { ran += "later" } + }.build()) + + adapter.fire(0) + + assertEquals(2, adapter.requests.size) + assertEquals(Duration.ofSeconds(5), adapter.requests[1].delay) + val child = scope.query(TaskQuery.builder().tag("subtask").build()).single() + assertEquals("parent / later", child.name) + adapter.fire(1) + assertEquals(listOf("later"), ran) + } + + @Test + fun `each run of a repeating task is planned one interval after the previous start`() { + val adapter = RecordingAdapter() + val scope = ScheduledTasks(adapter).scope(Any()) + val planned = mutableListOf() + scope.schedule(TaskSpec.builder().interval(Duration.ofSeconds(10)).action { planned += it.scheduledAt }.build()) + + repeat(2) { adapter.fire(0) } + + assertTrue(planned[1].isAfter(planned[0].plusSeconds(9))) + } + + @Test + fun `a run that starts later than max lag is skipped`() { + val adapter = RecordingAdapter() + val scope = ScheduledTasks(adapter).scope(Any()) + val ran = AtomicBoolean() + val handle = scope.schedule(TaskSpec.builder().maxLag(Duration.ofMillis(1)).interval(Duration.ofSeconds(1)) + .action { ran.set(true) }.build()) + + Thread.sleep(30) + adapter.fire(0) + + assertFalse(ran.get()) + assertEquals(1, handle.snapshot().skippedCount) + assertEquals(TaskStatus.SCHEDULED, handle.status) + } + + @Test + fun `a repeating task survives tolerated failures in a row and then fails`() { + val adapter = RecordingAdapter() + val scope = ScheduledTasks(adapter).scope(Any()) + val handle = scope.schedule(TaskSpec.builder().interval(Duration.ofSeconds(1)).tolerateFailures(2) + .action { error("boom") }.build()) + + adapter.fire(0) + adapter.fire(0) + assertEquals(TaskStatus.SCHEDULED, handle.status) + adapter.fire(0) + + assertEquals(TaskStatus.FAILED, handle.status) + assertEquals(3, handle.snapshot().failedCount) + } + + @Test + fun `a success resets the failure count`() { + val adapter = RecordingAdapter() + val scope = ScheduledTasks(adapter).scope(Any()) + var fail = true + val handle = scope.schedule(TaskSpec.builder().interval(Duration.ofSeconds(1)).tolerateFailures(1) + .action { if (fail) error("boom") }.build()) + + adapter.fire(0) + fail = false + adapter.fire(0) + fail = true + adapter.fire(0) + + assertEquals(TaskStatus.SCHEDULED, handle.status) + } + + @Test + fun `a lag handler hears about a late run and can skip it`() { + val adapter = RecordingAdapter() + val scope = ScheduledTasks(adapter).scope(Any()) + val heard = mutableListOf() + val ran = AtomicBoolean() + val handle = scope.schedule(TaskSpec.builder().interval(Duration.ofMillis(10)) + .onLag(Duration.ofMillis(5)) { lag -> heard += lag; org.pnfolder.pnlibrary.api.tasks.run.LagResponse.SKIP } + .action { ran.set(true) }.build()) + + Thread.sleep(50) + adapter.fire(0) + + assertFalse(ran.get()) + assertEquals(1, heard.size) + assertTrue(heard[0].missedRuns >= 3) + assertTrue(handle.snapshot().worstLag!! >= Duration.ofMillis(40)) + assertEquals(1, handle.snapshot().skippedCount) + } + + @Test + fun `a lag handler can cancel the task for good`() { + val adapter = RecordingAdapter() + val scope = ScheduledTasks(adapter).scope(Any()) + val ran = AtomicBoolean() + val handle = scope.schedule(TaskSpec.builder().interval(Duration.ofMillis(10)) + .onLag(Duration.ofMillis(5)) { org.pnfolder.pnlibrary.api.tasks.run.LagResponse.CANCEL } + .action { ran.set(true) }.build()) + + Thread.sleep(50) + adapter.fire(0) + + assertFalse(ran.get()) + assertEquals(TaskStatus.CANCELLED, handle.status) + assertNull(handle.snapshot().nextRunAt) + } + + @Test + fun `a lag handler that throws does not stop the run`() { + val adapter = RecordingAdapter() + val scope = ScheduledTasks(adapter).scope(Any()) + val ran = AtomicBoolean() + scope.schedule(TaskSpec.builder().interval(Duration.ofMillis(10)) + .onLag(Duration.ofMillis(1)) { error("handler broke") } + .action { ran.set(true) }.build()) + + Thread.sleep(20) + adapter.fire(0) + + assertTrue(ran.get()) + } + + @Test + fun `a subtask knows its parent and a linked one is cancelled with it`() { + val adapter = RecordingAdapter() + val scope = ScheduledTasks(adapter).scope(Any()) + val parent = scope.schedule(TaskSpec.builder().name("parent").interval(Duration.ofSeconds(1)).action { c -> + if (c.runNumber == 1L) { + c.repeat(3, Duration.ofSeconds(1)) { } + c.later(Duration.ofSeconds(1)) { } + } + }.build()) + + adapter.fire(0) + + val children = scope.query(TaskQuery.builder().tag("subtask").build()) + assertEquals(2, children.size) + assertTrue(children.all { it.parentId == parent.id }) + parent.cancel() + val states = scope.query(TaskQuery.builder().tag("subtask").build()).associate { it.name to it.status } + assertEquals(TaskStatus.CANCELLED, states["parent / repeat"]) + assertEquals(TaskStatus.SCHEDULED, states["parent / later"]) + } + @Test fun `duplicate names are listed while keyed conflicts follow policy`() { val adapter = RecordingAdapter() @@ -296,6 +464,75 @@ class ScheduledTasksTest { assertEquals(TaskStatus.FAILED, task.status) } + private class RewardTask(private val log: MutableList) : org.pnfolder.pnlibrary.api.tasks.spec.ScheduledTask() { + override val name = "Награда" + override val delay: Duration = Duration.ofMinutes(1) + override val cancelWithParent = true + override fun run(context: org.pnfolder.pnlibrary.api.tasks.run.TaskContext) { log += "reward" } + } + + /** The examples of `docs/tasks.md`: if they stop compiling or working, the documentation is wrong. */ + @Test + fun `a task built with the DSL starts subtasks of every kind`() { + val adapter = RecordingAdapter() + val scope = ScheduledTasks(adapter).scope(Any()) + val log = mutableListOf() + scope.schedule { + name = "Ивент" + key = "event" + conflictPolicy = TaskConflictPolicy.REPLACE + tag("event") + execution = org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution.global() + interval = Duration.ofSeconds(1) + maxLag = Duration.ofSeconds(10) + tolerateFailures = 3 + condition { true } + cancelWhen { false } + whenLate(Duration.ofSeconds(1)) { log += "late" } + onLag(Duration.ofSeconds(2)) { org.pnfolder.pnlibrary.api.tasks.run.LagResponse.RUN } + run { ctx -> + if (ctx.isFirstRun) { + ctx.spawn { + name = "Таймер" + interval = Duration.ofSeconds(1) + cancelWithParent = true + run { log += "tick" } + } + ctx.spawn(RewardTask(log)) + ctx.later(Duration.ofSeconds(5)) { log += "later" } + ctx.repeat(2, Duration.ofSeconds(1)) { log += "repeat" } + } + } + } + + adapter.fire(0) + + val all = scope.query(TaskQuery.all()) + val parent = all.single { it.name == "Ивент" } + val children = all.filter { it.parentId == parent.id } + assertEquals(setOf("Таймер", "Награда", "Ивент / later", "Ивент / repeat"), children.map { it.name }.toSet()) + } + + @Test + fun `a ready spec can be started as a subtask many times`() { + val adapter = RecordingAdapter() + val scope = ScheduledTasks(adapter).scope(Any()) + val timer = TaskSpec.builder().name("Таймер").cancelWithParent(true).action { }.build() + scope.schedule( + TaskSpec.builder() + .name("Ивент") + .whenLate(Duration.ofSeconds(1)) { } + .onLag(Duration.ofSeconds(2)) { org.pnfolder.pnlibrary.api.tasks.run.LagResponse.SKIP } + .action { ctx -> ctx.spawn(timer); ctx.spawn(timer) } + .build(), + ) + + adapter.fire(0) + + assertEquals(3, adapter.requests.size) + assertEquals(2, scope.query(TaskQuery.all()).count { it.parentId != null }) + } + private fun spec(name: String) = TaskSpec.builder().name(name).action { }.build() private class RecordingAdapter( private val fireDuringSchedule: Boolean = false, @@ -306,7 +543,9 @@ class ScheduledTasksTest { var closed = false private set - override fun schedule(request: PlatformTaskRequest): PlatformTaskHandle { + override fun buildTask() = PlatformTaskBuilder(::dispatch) + + private fun dispatch(request: PlatformTaskRequest): PlatformTaskHandle { requests += request val failure = if (handles.size == failingCancelIndex) IllegalStateException("native cancellation failed") else null val handle = NativeHandle(failure) diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/TaskHistoryStoreTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskHistoryStoreTest.kt similarity index 90% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/TaskHistoryStoreTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskHistoryStoreTest.kt index 42fdd4e37..bb0a75c54 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/TaskHistoryStoreTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/tasks/TaskHistoryStoreTest.kt @@ -1,12 +1,12 @@ -package org.pnfolder.pnlibrary.core +package org.pnfolder.pnlibrary.core.tasks import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskId -import org.pnfolder.pnlibrary.api.tasks.TaskSnapshot -import org.pnfolder.pnlibrary.api.tasks.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.info.TaskId +import org.pnfolder.pnlibrary.api.tasks.info.TaskSnapshot +import org.pnfolder.pnlibrary.api.tasks.info.TaskStatus +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import org.pnfolder.pnlibrary.core.tasks.TaskHistoryStore import java.nio.file.Files import java.nio.file.Path diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/ui/ConsoleStyleTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/text/ConsoleStyleTest.kt similarity index 91% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/ui/ConsoleStyleTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/text/ConsoleStyleTest.kt index fef1a11fe..c29eb816c 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/ui/ConsoleStyleTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/text/ConsoleStyleTest.kt @@ -1,9 +1,9 @@ -package org.pnfolder.pnlibrary.core.ui +package org.pnfolder.pnlibrary.core.text import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone class ConsoleStyleTest { @Test diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/text/MiniMessageLiteTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/text/MiniMessageLiteTest.kt new file mode 100644 index 000000000..f8349af81 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/text/MiniMessageLiteTest.kt @@ -0,0 +1,93 @@ +package org.pnfolder.pnlibrary.core.text + +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.TextComponent +import net.kyori.adventure.text.format.Style +import net.kyori.adventure.text.format.TextDecoration +import net.kyori.adventure.text.minimessage.MiniMessage +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertSame +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.mockito.Mockito +import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService +import org.pnfolder.pnlibrary.api.text.serializer.ComponentSerializerType + +class MiniMessageLiteTest { + private data class Run(val text: String, val color: Int?, val decorations: Set) + + private fun runs(component: Component): List { + val result = ArrayList() + fun walk(node: Component, parent: Style) { + val style = node.style().merge(parent, Style.Merge.Strategy.IF_ABSENT_ON_TARGET) + if (node is TextComponent && node.content().isNotEmpty()) { + val decorations = TextDecoration.values().filter { style.decoration(it) == TextDecoration.State.TRUE }.toSet() + val previous = result.lastOrNull() + val newline = node.content() == "\n" && previous != null + result += if (newline) Run("\n", previous!!.color, previous.decorations) + else Run(node.content(), style.color()?.value(), decorations) + } + node.children().forEach { walk(it, style) } + } + walk(component, Style.empty()) + return result.fold(ArrayList()) { merged, run -> + val last = merged.lastOrNull() + if (last != null && last.color == run.color && last.decorations == run.decorations) { + merged[merged.size - 1] = last.copy(text = last.text + run.text) + } else merged += run + merged + } + } + + private val samples = listOf( + "plain", "red", "ab", "abcd", "abc", + "<#ff8800>hex tail", "xy", "x", "c", + "bn", "b", "i", "e", "x", "u", "u", + "s", "s", "o", "o", + "both red only", "x", "ab", "ab", "ab", "abc", + "line
two", "linetwo", "a \\ literal", "text", "1 < 2 and 3 > 2", + "Upper", "dgg2lw", "xy", + "unclosed nest", "<>empty", "doublestill", "neg", + "abc", "kbgagba", + ) + + @Test + fun `lite matches MiniMessage on the supported subset`() { + val real = MiniMessage.miniMessage() + for (sample in samples) { + assertEquals(runs(real.deserialize(sample)), runs(MiniMessageLite.deserialize(sample)), "input: $sample") + } + } + + @Test + fun `gradient keeps the text and the first color`() { + assertEquals(listOf(Run("go", 0xFF0000, emptySet())), runs(MiniMessageLite.deserialize("go"))) + } + + private fun components(mini: MiniText, warnings: MutableList) = CachedComponents( + Mockito.mock(PlaceholderService::class.java), ComponentCache(), mini, warnings::add, + ) + + private fun brokenFactory(): () -> MiniMessage = { throw NoSuchMethodError("Component.compact()") } + + @Test + fun `an old Adventure switches to lite parsing and warns once`() { + val warnings = ArrayList() + val components = components(MiniText(brokenFactory()), warnings) + val first = components.deserialize("hi", ComponentSerializerType.MINI_MESSAGE) + components.deserialize("&aok", ComponentSerializerType.ADAPTIVE) + components.serialize(first) + assertEquals(listOf(Run("hi", 0xFF5555, emptySet())), runs(first)) + assertEquals(1, warnings.size) + } + + @Test + fun `an unexpected failure is not swallowed`() { + val boom = IllegalStateException("boom") + val components = components(MiniText({ throw boom }), ArrayList()) + val thrown = assertThrows(IllegalStateException::class.java) { + components.deserialize("x", ComponentSerializerType.MINI_MESSAGE) + } + assertSame(boom, thrown) + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupQueryTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupQueryTest.kt similarity index 98% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupQueryTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupQueryTest.kt index df3435077..bf1a6d0c3 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupQueryTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/BackupQueryTest.kt @@ -4,9 +4,9 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.updates.ProductId import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackupComponent +import org.pnfolder.pnlibrary.api.updates.product.ProductId import java.time.Instant import java.time.ZoneOffset import java.util.UUID diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogLabelsTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogLabelsTest.kt new file mode 100644 index 000000000..cc9657996 --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/CatalogLabelsTest.kt @@ -0,0 +1,34 @@ +package org.pnfolder.pnlibrary.core.updates.catalog + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.updates.state.UpdateState + +class CatalogLabelsTest { + @Test + fun `every state has a label, a short label and a color`() { + UpdateState.entries.forEach { state -> + assertTrue(CatalogLabels.stateLabel(state).isNotBlank(), state.name) + assertTrue(CatalogLabels.shortStateLabel(state).length <= CatalogLabels.stateLabel(state).length, state.name) + CatalogLabels.stateColor(state) + } + } + + @Test + fun `short labels shorten only the long wordings`() { + assertEquals("ждёт перезапуска", CatalogLabels.shortStateLabel(UpdateState.UPDATE_STAGED)) + assertEquals("актуально", CatalogLabels.shortStateLabel(UpdateState.UP_TO_DATE)) + } + + @Test + fun `pending and problem sets do not overlap`() { + assertTrue(CatalogLabels.PENDING.intersect(CatalogLabels.PROBLEMS).isEmpty()) + } + + @Test + fun `an unknown operation reads as a state change`() { + assertEquals("откат", CatalogLabels.operationLabel("ROLLBACK")) + assertEquals("состояние", CatalogLabels.operationLabel("SOMETHING")) + } +} diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateCommandTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateCommandTest.kt index 681e2d60d..eb51d19bc 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateCommandTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/ProxyUpdateCommandTest.kt @@ -4,20 +4,30 @@ import net.kyori.adventure.text.Component import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition import org.pnfolder.pnlibrary.api.commands.CommandSender -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command import org.pnfolder.pnlibrary.api.dependencies.PluginDependency import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.api.updates.* import org.pnfolder.pnlibrary.api.updates.backup.* -import org.pnfolder.pnlibrary.core.commands.CommandRoute -import org.pnfolder.pnlibrary.core.commands.CommandTreeRouter +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState +import org.pnfolder.pnlibrary.core.commands.engine.CommandRoute +import org.pnfolder.pnlibrary.core.commands.engine.CommandTreeRouter import java.lang.reflect.Proxy import java.time.Duration +import java.time.Instant import java.util.Optional import java.util.UUID import java.util.concurrent.CompletableFuture +import java.util.concurrent.CompletionStage class ProxyUpdateCommandTest { @Test @@ -125,28 +135,57 @@ class ProxyUpdateCommandTest { var automaticSet: Pair? = null var heldSet: Pair? = null private fun snapshot() = UpdateSnapshot("pnlibrary", "1.0.0", null, UpdateChannel.BETA, UpdateState.UP_TO_DATE, 17, 8, false, null, null) - override fun setChannel(product: String, channel: UpdateChannel?, actor: UpdateActor) = - CompletableFuture.completedFuture(snapshot()).also { channelSet = product to channel; this.actor = actor } - override fun setAutomaticDownload(product: String, enabled: Boolean, actor: UpdateActor) = - CompletableFuture.completedFuture(snapshot()).also { automaticSet = product to enabled } - override fun setHeld(product: String, duration: Duration?, actor: UpdateActor) = - CompletableFuture.completedFuture(snapshot()).also { heldSet = product to duration } override fun register(owner: Any, product: ProductDescriptor, request: PluginUpdateRequest, dependencies: List): UpdateRegistration = error("not used") - override fun all(): List = emptyList() - override fun get(product: String): UpdateRegistration? = null - override fun currentPlan(): Optional = Optional.of(current) - override fun stage(planId: UUID, actor: UpdateActor) = CompletableFuture.completedFuture(current).also { - staged = planId - this.actor = actor + + override val products = object : UpdateProducts { + override fun all(): List = emptyList() + override fun get(product: String): UpdateRegistration? = null + } + + override val plans = object : UpdatePlans { + override fun check(actor: UpdateActor): CompletionStage = CompletableFuture.completedFuture(current) + override fun current(): Optional = Optional.of(current) + override fun recent(): List = emptyList() + override fun stage(planId: UUID, actor: UpdateActor) = CompletableFuture.completedFuture(current).also { + staged = planId + this@Updates.actor = actor + } + } + + override val settings = object : UpdateSettings { + override fun channel(product: String, channel: UpdateChannel?, actor: UpdateActor) = + CompletableFuture.completedFuture(snapshot()).also { channelSet = product to channel; this@Updates.actor = actor } + override fun automaticDownload(product: String, enabled: Boolean, actor: UpdateActor) = + CompletableFuture.completedFuture(snapshot()).also { automaticSet = product to enabled } + override fun automaticDownloadForAll(enabled: Boolean, actor: UpdateActor) = + CompletableFuture.completedFuture(listOf(snapshot())) + override fun hold(product: String, duration: Duration, actor: UpdateActor) = + CompletableFuture.completedFuture(snapshot()).also { heldSet = product to duration } + override fun release(product: String, actor: UpdateActor) = + CompletableFuture.completedFuture(snapshot()).also { heldSet = product to null } + override fun heldUntil(product: String): Instant? = null + override fun javaBuild(product: String, java: Int?, actor: UpdateActor) = CompletableFuture.completedFuture(snapshot()) + } + + override val history = object : UpdateHistory { + override fun page(page: Int, product: String?) = + CompletableFuture.completedFuture>(emptyList()).also { pages.add(page) } + override fun count(product: String?) = CompletableFuture.completedFuture(0) } - override fun historyPage(page: Int, - product: String?) = CompletableFuture.completedFuture>(emptyList()).also { pages.add(page) } - override fun historyCount(product: String?) = CompletableFuture.completedFuture(0) - override fun rollback(transactionId: UUID, actor: UpdateActor) = CompletableFuture.completedFuture(current).also { rolledBack = transactionId } - override fun rollback(transactionId: UUID, restoreConfigurations: Boolean, actor: UpdateActor) = CompletableFuture.completedFuture(current).also { - rolledBack = transactionId - this.restoreConfigurations = restoreConfigurations + + override val backups = object : UpdateBackups { + override fun list() = CompletableFuture.completedFuture>(emptyList()) + override fun rollback(actor: UpdateActor) = CompletableFuture.completedFuture(current) + override fun rollback(transactionId: UUID, actor: UpdateActor, restoreConfigurations: Boolean) = + CompletableFuture.completedFuture(current).also { + rolledBack = transactionId + this@Updates.restoreConfigurations = restoreConfigurations + } + override fun delete(transactionId: UUID, actor: UpdateActor) = CompletableFuture.completedFuture(null) + override fun restoreDatabase(transactionId: UUID, product: String, name: String, actor: UpdateActor) = + CompletableFuture.completedFuture(null) + override fun extract(transactionId: UUID, product: String, actor: UpdateActor) = CompletableFuture.completedFuture("") } } } diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogViewTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogViewTest.kt similarity index 97% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogViewTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogViewTest.kt index c647c553d..12240263d 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogViewTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCatalogViewTest.kt @@ -13,20 +13,20 @@ import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.chat.ChatNotice -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackupComponent -import org.pnfolder.pnlibrary.api.updates.backup.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ProductChange import org.pnfolder.pnlibrary.api.updates.release.ReleaseSummary +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.SemanticVersion -import org.pnfolder.pnlibrary.core.updates.install.ComponentLedger +import org.pnfolder.pnlibrary.updates.install.ComponentOperation import java.time.Instant import java.time.ZoneOffset import java.util.UUID @@ -208,10 +208,10 @@ class UpdateCatalogViewTest { message, ) val text = text(history(listOf( - component(ComponentLedger.OPERATION_ADDED, null, "1.0.0"), - component(ComponentLedger.OPERATION_REMOVED, "1.0.0", "1.0.0"), - component(ComponentLedger.OPERATION_VERSION_CHANGED, "1.0.0", "1.1.0"), - component(ComponentLedger.OPERATION_SETTINGS_CHANGED, "1.0.0", "1.0.0", "канал: stable → beta"), + component(ComponentOperation.ADDED, null, "1.0.0"), + component(ComponentOperation.REMOVED, "1.0.0", "1.0.0"), + component(ComponentOperation.VERSION_CHANGED, "1.0.0", "1.1.0"), + component(ComponentOperation.SETTINGS_CHANGED, "1.0.0", "1.0.0", "канал: stable → beta"), ))) assertTrue(text.contains("shop v1.0.0 установлен"), text) assertTrue(text.contains("shop v1.0.0 удалён")) diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateConfirmationTokensTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateConfirmationTokensTest.kt similarity index 100% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateConfirmationTokensTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateConfirmationTokensTest.kt diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateStatusMessagesTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateStatusMessagesTest.kt new file mode 100644 index 000000000..1fa7fbf7d --- /dev/null +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateStatusMessagesTest.kt @@ -0,0 +1,64 @@ +package org.pnfolder.pnlibrary.core.updates.catalog + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.chat.style.ChatTone +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.state.BlockedReason +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState +import org.pnfolder.pnlibrary.api.version.SemanticVersion +import java.util.UUID + +class UpdateStatusMessagesTest { + private fun plugin(state: UpdateState, product: String = "shop", message: String? = null) = UpdateSnapshot( + product, "1.0.0", "1.1.0", UpdateChannel.STABLE, state, 17, 17, false, null, message, + ) + + private fun plan(state: UpdateState, blockers: List = emptyList(), message: String? = null) = + UpdatePlanSnapshot(UUID.randomUUID(), 0, state, null, blockers, message) + + @Test + fun `a plugin without changes is up to date`() { + val notice = UpdateStatusMessages.status(plan(UpdateState.UP_TO_DATE) to plugin(UpdateState.UP_TO_DATE)).single() + + assertEquals(ChatTone.SUCCESS, notice.tone) + assertTrue(notice.text.startsWith("Плагин shop")) + } + + @Test + fun `a frozen plugin is reported as paused`() { + val notice = UpdateStatusMessages.status(plan(UpdateState.UP_TO_DATE) to plugin(UpdateState.FROZEN)).single() + + assertEquals(ChatTone.WARNING, notice.tone) + } + + @Test + fun `a blocked plan lists each reason after the headline`() { + val reasons = listOf(BlockedReason.Frozen(ProductId.of("shop"))) + val notices = UpdateStatusMessages.status(plan(UpdateState.BLOCKED, reasons) to plugin(UpdateState.UPDATE_AVAILABLE)) + + assertEquals(2, notices.size) + assertEquals(ChatTone.FAILURE, notices[0].tone) + assertTrue(notices[1].text.startsWith("Причина:")) + } + + @Test + fun `a failure message ends with exactly one period`() { + val notice = UpdateStatusMessages.status(plan(UpdateState.FAILED, message = "нет сети.") to plugin(UpdateState.UP_TO_DATE)).single() + + assertEquals("нет сети.", notice.detail) + } + + @Test + fun `an older required api advises updating the library`() { + val range = org.pnfolder.pnlibrary.api.version.ApiVersionRange(5, 6) + val text = UpdateStatusMessages.blocker(BlockedReason.ApiMismatch(ProductId.of("shop"), range, 3)) + + assertTrue(text.contains("Сначала обновите библиотеку")) + assertTrue(SemanticVersion.parse("1.0.0").toString().isNotEmpty()) + } +} diff --git a/modules/upload/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/EncryptedReportUploaderTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/EncryptedReportUploaderTest.kt similarity index 100% rename from modules/upload/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/EncryptedReportUploaderTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/EncryptedReportUploaderTest.kt diff --git a/modules/upload/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/MultipartFileClientTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/MultipartFileClientTest.kt similarity index 100% rename from modules/upload/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/MultipartFileClientTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/MultipartFileClientTest.kt diff --git a/modules/upload/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerPolicyTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerPolicyTest.kt similarity index 100% rename from modules/upload/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerPolicyTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerPolicyTest.kt diff --git a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/UploadLedgerTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerTest.kt similarity index 96% rename from modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/UploadLedgerTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerTest.kt index 45307a48e..d57b36ece 100644 --- a/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/UploadLedgerTest.kt +++ b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/UploadLedgerTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core +package org.pnfolder.pnlibrary.core.upload import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test diff --git a/modules/upload/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/UploadProviderChainTest.kt b/modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/UploadProviderChainTest.kt similarity index 100% rename from modules/upload/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/UploadProviderChainTest.kt rename to modules/core/src/test/kotlin/org/pnfolder/pnlibrary/core/upload/UploadProviderChainTest.kt diff --git a/modules/events/build.gradle.kts b/modules/events/build.gradle.kts deleted file mode 100644 index d7301a09a..000000000 --- a/modules/events/build.gradle.kts +++ /dev/null @@ -1,50 +0,0 @@ -plugins { - alias(libs.plugins.kotlin.jvm) - `java-library` - alias(libs.plugins.maven.publish) -} - -base { archivesName = "${rootProject.property("pnlibrary.name")}-events" } - -dependencies { - api(project(":modules:api")) - implementation(project(":modules:common")) - implementation(libs.kotlin.stdlib) - - testImplementation(libs.junit.jupiter) - testImplementation(libs.mockito.core) - testRuntimeOnly(libs.junit.launcher) -} - -mavenPublishing { - publishToMavenCentral() - signAllPublications() - coordinates("io.github.pnfolder", "pnlibrary-events", project.version.toString()) - pom { - name.set("pnLibrary events") - description.set("Event bus implementation for pnLibrary.") - inceptionYear.set("2026") - url.set("https://github.com/${rootProject.property("pnlibrary.repository")}") - licenses { - license { - name.set(providers.gradleProperty("POM_LICENSE_NAME")) - url.set(providers.gradleProperty("POM_LICENSE_URL")) - distribution.set(providers.gradleProperty("POM_LICENSE_DIST").orElse("repo")) - } - } - developers { - rootProject.property("pnlibrary.authors").toString().split(",").map(String::trim).forEach { author -> - developer { - id.set(author) - name.set(author) - url.set("https://github.com/" + rootProject.property("pnlibrary.organization")) - } - } - } - scm { - url.set("https://github.com/${rootProject.property("pnlibrary.repository")}") - connection.set("scm:git:git://github.com/${rootProject.property("pnlibrary.repository")}.git") - developerConnection.set("scm:git:ssh://git@github.com/${rootProject.property("pnlibrary.repository")}.git") - } - } -} diff --git a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventHistory.kt b/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventHistory.kt deleted file mode 100644 index f5b30feff..000000000 --- a/modules/events/src/main/kotlin/org/pnfolder/pnlibrary/core/events/EventHistory.kt +++ /dev/null @@ -1,188 +0,0 @@ -package org.pnfolder.pnlibrary.core.events - -import org.pnfolder.pnlibrary.api.events.EventDay -import org.pnfolder.pnlibrary.api.events.EventHour -import org.pnfolder.pnlibrary.common.concurrent.ManagedWorker -import org.pnfolder.pnlibrary.common.io.AtomicFiles -import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import java.nio.file.Files -import java.nio.file.Path -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.ZoneId -import java.time.temporal.ChronoUnit -import java.util.TreeMap -import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicLong - -/** - * Per-day call counters of every event type, kept for [retentionDays] and stored in a small text file so the - * history survives restarts. - * - * Counting is a map update under a lock. Writing happens on a background worker at most once per [flushEveryMillis] - * and once more on [close], so a crash loses at most a minute of counts. A retention of `0` keeps nothing. - * The file starts with a `# pnLibrary event history v1` line and then holds one `dateeventcallsdenied` - * line per day and event; lines that do not fit that shape are ignored. Hourly counters of the last 30 days at most - * are stored the same way, with `yyyy-MM-ddTHH:00` in the first column. - */ -class EventHistory( - private val file: Path?, - private val retentionDays: Int, - private val zone: () -> ZoneId = { ZoneId.systemDefault() }, - private val clock: () -> Long = System::currentTimeMillis, - private val flushEveryMillis: Long = 60_000, -) : AutoCloseable { - private class Counts(var calls: Long = 0, var denied: Long = 0) - - private val days = TreeMap>() - private val hours = TreeMap>() - private val dirty = AtomicBoolean(false) - private val lastFlush = AtomicLong(clock()) - private val worker = if (file != null && retentionDays > 0) ManagedWorker("pnLibrary-event-history") else null - - /** How many days are kept; `0` means the history is off. */ - val retention: Int get() = retentionDays - - init { - if (file != null && retentionDays > 0) runCatchingNonFatal { load(file) } - } - - fun record(eventType: String, denied: Boolean) { - if (retentionDays <= 0) return - val now = LocalDateTime.now(zone()) - val today = now.toLocalDate() - synchronized(days) { - val counts = days.getOrPut(today) { HashMap() }.getOrPut(eventType) { Counts() } - counts.calls++ - if (denied) counts.denied++ - val hourly = hours.getOrPut(now.truncatedTo(ChronoUnit.HOURS)) { HashMap() }.getOrPut(eventType) { Counts() } - hourly.calls++ - if (denied) hourly.denied++ - pruneHours(now) - if (days.firstKey().isBefore(today.minusDays(retentionDays.toLong() - 1))) prune(today) - } - dirty.set(true) - val tick = clock() - val previous = lastFlush.get() - if (tick - previous >= flushEveryMillis && lastFlush.compareAndSet(previous, tick)) { - worker?.let { runCatchingNonFatal { it.submit { flush() } } } - } - } - - /** The recorded days, newest first and then by event name; only [eventType] when given. */ - fun entries(eventType: String? = null): List = synchronized(days) { - days.descendingMap().flatMap { (date, events) -> - events.entries.sortedBy { it.key }.filter { eventType == null || it.key == eventType } - .map { EventDay(date, it.key, it.value.calls, it.value.denied) } - } - } - - /** The recorded hours, newest first and then by event name; only [eventType] when given. */ - fun hourly(eventType: String? = null): List = synchronized(days) { - hours.descendingMap().flatMap { (hour, events) -> - events.entries.sortedBy { it.key }.filter { eventType == null || it.key == eventType } - .map { EventHour(hour, it.key, it.value.calls, it.value.denied) } - } - } - - /** Writes days and hours to `event-history.csv` or `event-history.json` beside the history file; `null` if not possible. */ - fun export(json: Boolean): Path? { - val source = file ?: return null - if (retentionDays <= 0) return null - val days = entries() - val hours = hourly() - val text = if (json) { - fun quote(value: String) = "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" - buildString { - append("{\"days\":[") - append(days.joinToString(",") { """{"date":"${it.date}","event":${quote(it.eventType)},"calls":${it.calls},"denied":${it.denied}}""" }) - append("],\"hours\":[") - append(hours.joinToString(",") { """{"hour":"${it.hour}","event":${quote(it.eventType)},"calls":${it.calls},"denied":${it.denied}}""" }) - append("]}").append(NL) - } - } else { - fun cell(value: String) = if (value.any { it == ',' || it == '"' }) "\"" + value.replace("\"", "\"\"") + "\"" else value - buildString { - append("period,time,event,calls,denied").append(NL) - days.forEach { append("day,${it.date},${cell(it.eventType)},${it.calls},${it.denied}").append(NL) } - hours.forEach { append("hour,${it.hour},${cell(it.eventType)},${it.calls},${it.denied}").append(NL) } - } - } - val target = source.resolveSibling(if (json) "event-history.json" else "event-history.csv") - return runCatchingNonFatal { AtomicFiles.write(target, text.toByteArray(Charsets.UTF_8)); target }.getOrNull() - } - - private fun pruneHours(now: LocalDateTime) { - val keep = minOf(retentionDays, MAX_HOURLY_DAYS) * 24L - hours.headMap(now.truncatedTo(ChronoUnit.HOURS).minusHours(keep - 1)).clear() - } - - private fun prune(today: LocalDate) { - val oldest = today.minusDays(retentionDays.toLong() - 1) - days.headMap(oldest).clear() - } - - private fun load(source: Path) { - if (!Files.isRegularFile(source)) return - val today = LocalDate.now(zone()) - synchronized(days) { - Files.readAllLines(source).forEach { line -> - val parts = line.split('\t') - if (parts.size != 4) return@forEach - if ('T' in parts[0]) { - val hour = runCatchingNonFatal { LocalDateTime.parse(parts[0]) }.getOrNull() ?: return@forEach - val calls = parts[2].toLongOrNull() ?: return@forEach - val denied = parts[3].toLongOrNull() ?: return@forEach - val counts = hours.getOrPut(hour) { HashMap() }.getOrPut(parts[1]) { Counts() } - counts.calls += calls - counts.denied += denied - return@forEach - } - val date = runCatchingNonFatal { LocalDate.parse(parts[0]) }.getOrNull() ?: return@forEach - val calls = parts[2].toLongOrNull() ?: return@forEach - val denied = parts[3].toLongOrNull() ?: return@forEach - val counts = days.getOrPut(date) { HashMap() }.getOrPut(parts[1]) { Counts() } - counts.calls += calls - counts.denied += denied - } - prune(today) - pruneHours(LocalDateTime.now(zone())) - } - } - - /** Writes the file now when something changed; the write goes to a temporary file first. */ - fun flush() { - val target = file ?: return - if (retentionDays <= 0 || !dirty.getAndSet(false)) return - val text = synchronized(days) { - buildString { - append(HEADER).append('\n') - days.forEach { (date, events) -> - events.forEach { (name, counts) -> - append("$date\t$name\t${counts.calls}\t${counts.denied}\n") - } - } - hours.forEach { (hour, events) -> - events.forEach { (name, counts) -> - append("$hour\t$name\t${counts.calls}\t${counts.denied}\n") - } - } - } - } - runCatchingNonFatal { - Files.createDirectories(target.parent) - AtomicFiles.write(target, text.toByteArray(Charsets.UTF_8)) - }.onFailure { dirty.set(true) } - } - - override fun close() { - worker?.close() - flush() - } - - private companion object { - const val HEADER = "# pnLibrary event history v1" - const val MAX_HOURLY_DAYS = 30 - const val NL = '\n' - } -} diff --git a/modules/features/config-api/api/config-api.api b/modules/features/config-api/api/config-api.api index 40188e7cb..550cb141e 100644 --- a/modules/features/config-api/api/config-api.api +++ b/modules/features/config-api/api/config-api.api @@ -1,3 +1,17 @@ +public abstract interface annotation class org/pnfolder/pnlibrary/api/config/BackupDatabase : java/lang/annotation/Annotation { + public abstract fun kind ()Lorg/pnfolder/pnlibrary/api/config/DatabaseKind; + public abstract fun name ()Ljava/lang/String; + public abstract fun tables ()[Ljava/lang/String; +} + +public abstract interface annotation class org/pnfolder/pnlibrary/api/config/BackupDatabase$Container : java/lang/annotation/Annotation { + public abstract fun value ()[Lorg/pnfolder/pnlibrary/api/config/BackupDatabase; +} + +public abstract interface annotation class org/pnfolder/pnlibrary/api/config/BackupTable : java/lang/annotation/Annotation { + public abstract fun database ()Ljava/lang/String; +} + public final class org/pnfolder/pnlibrary/api/config/CommentPolicy : java/lang/Enum { public static final field ADD_MISSING Lorg/pnfolder/pnlibrary/api/config/CommentPolicy; public static final field PRESERVE Lorg/pnfolder/pnlibrary/api/config/CommentPolicy; @@ -6,10 +20,93 @@ public final class org/pnfolder/pnlibrary/api/config/CommentPolicy : java/lang/E public static fun values ()[Lorg/pnfolder/pnlibrary/api/config/CommentPolicy; } +public final class org/pnfolder/pnlibrary/api/config/ConfigAddress { + public static final field Companion Lorg/pnfolder/pnlibrary/api/config/ConfigAddress$Companion; + public synthetic fun (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;Ljava/lang/String;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun equals (Ljava/lang/Object;)Z + public static final fun everywhere ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public static final fun file (Lorg/pnfolder/pnlibrary/api/config/ConfigId;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun getLevel ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress$Level; + public final fun getModule ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public final fun getPath ()Ljava/lang/String; + public final fun getPlugin ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun getRoot ()Lorg/pnfolder/pnlibrary/api/config/ConfigRoot; + public fun hashCode ()I + public final fun inFile (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun inFile (Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public static synthetic fun inFile$default (Lorg/pnfolder/pnlibrary/api/config/ConfigAddress;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun inModule (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun inModule (Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun isAll ()Z + public final fun matches (Lorg/pnfolder/pnlibrary/api/config/ConfigId;)Z + public static final fun module (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public static final fun module (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun overlaps (Lorg/pnfolder/pnlibrary/api/config/ConfigAddress;)Z + public static final fun parse (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public static final fun plugin (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public static final fun plugin (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigAddress$Companion { + public final fun everywhere ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun file (Lorg/pnfolder/pnlibrary/api/config/ConfigId;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun module (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun module (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun parse (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun plugin (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun plugin (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigAddress$Level : java/lang/Enum { + public static final field ALL Lorg/pnfolder/pnlibrary/api/config/ConfigAddress$Level; + public static final field FILE Lorg/pnfolder/pnlibrary/api/config/ConfigAddress$Level; + public static final field MODULE Lorg/pnfolder/pnlibrary/api/config/ConfigAddress$Level; + public static final field PLUGIN Lorg/pnfolder/pnlibrary/api/config/ConfigAddress$Level; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigAddress$Level; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/config/ConfigAddress$Level; +} + public abstract interface annotation class org/pnfolder/pnlibrary/api/config/ConfigAlias : java/lang/annotation/Annotation { public abstract fun value ()[Ljava/lang/String; } +public final class org/pnfolder/pnlibrary/api/config/ConfigApply : java/lang/Enum { + public static final field LIVE Lorg/pnfolder/pnlibrary/api/config/ConfigApply; + public static final field RELOAD Lorg/pnfolder/pnlibrary/api/config/ConfigApply; + public static final field RESTART Lorg/pnfolder/pnlibrary/api/config/ConfigApply; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigApply; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/config/ConfigApply; +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigChange { + public fun (Lorg/pnfolder/pnlibrary/api/config/ConfigId;Lorg/pnfolder/pnlibrary/api/config/ConfigChangeCause;Ljava/util/List;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/config/ConfigChangeCause; + public final fun component3 ()Ljava/util/List; + public final fun copy (Lorg/pnfolder/pnlibrary/api/config/ConfigId;Lorg/pnfolder/pnlibrary/api/config/ConfigChangeCause;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/config/ConfigChange; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/config/ConfigChange;Lorg/pnfolder/pnlibrary/api/config/ConfigId;Lorg/pnfolder/pnlibrary/api/config/ConfigChangeCause;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigChange; + public fun equals (Ljava/lang/Object;)Z + public final fun getCause ()Lorg/pnfolder/pnlibrary/api/config/ConfigChangeCause; + public final fun getId ()Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public final fun getPaths ()Ljava/util/List; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigChangeCause : java/lang/Enum { + public static final field EDITED Lorg/pnfolder/pnlibrary/api/config/ConfigChangeCause; + public static final field LOADED Lorg/pnfolder/pnlibrary/api/config/ConfigChangeCause; + public static final field RELOADED Lorg/pnfolder/pnlibrary/api/config/ConfigChangeCause; + public static final field RESET Lorg/pnfolder/pnlibrary/api/config/ConfigChangeCause; + public static final field SAVED Lorg/pnfolder/pnlibrary/api/config/ConfigChangeCause; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigChangeCause; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/config/ConfigChangeCause; +} + public final class org/pnfolder/pnlibrary/api/config/ConfigChanges { public final fun get (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/Value; public final fun put (Ljava/lang/String;Ljava/lang/Object;)V @@ -45,9 +142,112 @@ public final class org/pnfolder/pnlibrary/api/config/ConfigDocument { public final fun transform (Ljava/lang/String;Ljava/util/function/UnaryOperator;)Lorg/pnfolder/pnlibrary/api/config/ConfigDocument; } +public abstract interface annotation class org/pnfolder/pnlibrary/api/config/ConfigDuration : java/lang/annotation/Annotation { + public abstract fun unit ()Ljava/util/concurrent/TimeUnit; +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigEditException : java/lang/IllegalArgumentException { + public fun (Ljava/lang/String;Ljava/lang/Throwable;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/Throwable;ILkotlin/jvm/internal/DefaultConstructorMarker;)V +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigEditResult { + public fun (Lorg/pnfolder/pnlibrary/api/config/ConfigSetting;Ljava/lang/String;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/config/ConfigSetting; + public final fun component2 ()Ljava/lang/String; + public final fun copy (Lorg/pnfolder/pnlibrary/api/config/ConfigSetting;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigEditResult; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/config/ConfigEditResult;Lorg/pnfolder/pnlibrary/api/config/ConfigSetting;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigEditResult; + public fun equals (Ljava/lang/Object;)Z + public final fun getPrevious ()Ljava/lang/String; + public final fun getSetting ()Lorg/pnfolder/pnlibrary/api/config/ConfigSetting; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public abstract interface annotation class org/pnfolder/pnlibrary/api/config/ConfigEditable : java/lang/annotation/Annotation { + public abstract fun apply ()Lorg/pnfolder/pnlibrary/api/config/ConfigApply; + public abstract fun description ()Ljava/lang/String; + public abstract fun title ()Ljava/lang/String; +} + +public abstract interface annotation class org/pnfolder/pnlibrary/api/config/ConfigHint : java/lang/annotation/Annotation { + public abstract fun examples ()[Ljava/lang/String; + public abstract fun format ()Ljava/lang/String; + public abstract fun strict ()Z + public abstract fun values ()[Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigId { + public static final field Companion Lorg/pnfolder/pnlibrary/api/config/ConfigId$Companion; + public fun (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;Ljava/lang/String;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public final fun component3 ()Lorg/pnfolder/pnlibrary/api/config/ConfigRoot; + public final fun component4 ()Ljava/lang/String; + public final fun copy (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/config/ConfigId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/ModuleId;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public fun equals (Ljava/lang/Object;)Z + public final fun getAddress ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun getDirectory ()Ljava/lang/String; + public final fun getFileName ()Ljava/lang/String; + public final fun getModule ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public final fun getModuleAddress ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun getPath ()Ljava/lang/String; + public final fun getPlugin ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun getRoot ()Lorg/pnfolder/pnlibrary/api/config/ConfigRoot; + public fun hashCode ()I + public static final fun of (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public static final fun of (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;)Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public static final fun parse (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigId$Companion { + public final fun of (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public final fun of (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;)Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public static synthetic fun of$default (Lorg/pnfolder/pnlibrary/api/config/ConfigId$Companion;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public final fun parse (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigId; +} + public abstract interface annotation class org/pnfolder/pnlibrary/api/config/ConfigIgnore : java/lang/annotation/Annotation { } +public final class org/pnfolder/pnlibrary/api/config/ConfigInfo { + public fun (Lorg/pnfolder/pnlibrary/api/config/ConfigId;Ljava/lang/Class;Ljava/nio/file/Path;ZZLjava/time/Instant;ZLjava/util/List;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/config/ConfigApply;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/config/ConfigId;Ljava/lang/Class;Ljava/nio/file/Path;ZZLjava/time/Instant;ZLjava/util/List;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/config/ConfigApply;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public final fun component10 ()Lorg/pnfolder/pnlibrary/api/config/ConfigApply; + public final fun component2 ()Ljava/lang/Class; + public final fun component3 ()Ljava/nio/file/Path; + public final fun component4 ()Z + public final fun component5 ()Z + public final fun component6 ()Ljava/time/Instant; + public final fun component7 ()Z + public final fun component8 ()Ljava/util/List; + public final fun component9 ()Ljava/util/List; + public final fun copy (Lorg/pnfolder/pnlibrary/api/config/ConfigId;Ljava/lang/Class;Ljava/nio/file/Path;ZZLjava/time/Instant;ZLjava/util/List;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/config/ConfigApply;)Lorg/pnfolder/pnlibrary/api/config/ConfigInfo; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/config/ConfigInfo;Lorg/pnfolder/pnlibrary/api/config/ConfigId;Ljava/lang/Class;Ljava/nio/file/Path;ZZLjava/time/Instant;ZLjava/util/List;Ljava/util/List;Lorg/pnfolder/pnlibrary/api/config/ConfigApply;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigInfo; + public fun equals (Ljava/lang/Object;)Z + public final fun getAddress ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun getExists ()Z + public final fun getFile ()Ljava/nio/file/Path; + public final fun getId ()Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public final fun getLoadedAt ()Ljava/time/Instant; + public final fun getModelType ()Ljava/lang/Class; + public final fun getModule ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public final fun getModuleAddress ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun getPath ()Ljava/lang/String; + public final fun getPendingApply ()Lorg/pnfolder/pnlibrary/api/config/ConfigApply; + public final fun getPlugin ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun getProblems ()Ljava/util/List; + public final fun getReadOnly ()Z + public final fun getRoot ()Lorg/pnfolder/pnlibrary/api/config/ConfigRoot; + public final fun getSkippedUnknownTypes ()Ljava/util/List; + public fun hashCode ()I + public final fun isLoaded ()Z + public fun toString ()Ljava/lang/String; +} + public abstract interface annotation class org/pnfolder/pnlibrary/api/config/ConfigKey : java/lang/annotation/Annotation { public abstract fun value ()Ljava/lang/String; } @@ -110,17 +310,23 @@ public final class org/pnfolder/pnlibrary/api/config/ConfigOptions { public fun (Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;Lorg/pnfolder/pnlibrary/api/config/CommentPolicy;Z)V public fun (Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;Lorg/pnfolder/pnlibrary/api/config/CommentPolicy;ZLorg/pnfolder/pnlibrary/api/config/ConfigSteps;)V public fun (Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;Lorg/pnfolder/pnlibrary/api/config/CommentPolicy;ZLorg/pnfolder/pnlibrary/api/config/ConfigSteps;Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;Lorg/pnfolder/pnlibrary/api/config/CommentPolicy;ZLorg/pnfolder/pnlibrary/api/config/ConfigSteps;Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;Lorg/pnfolder/pnlibrary/api/config/CommentPolicy;ZLorg/pnfolder/pnlibrary/api/config/ConfigSteps;Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy;Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy;)V + public fun (Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;Lorg/pnfolder/pnlibrary/api/config/CommentPolicy;ZLorg/pnfolder/pnlibrary/api/config/ConfigSteps;Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy;Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;)V + public fun (Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;Lorg/pnfolder/pnlibrary/api/config/CommentPolicy;ZLorg/pnfolder/pnlibrary/api/config/ConfigSteps;Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy;Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;Z)V + public synthetic fun (Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;Lorg/pnfolder/pnlibrary/api/config/CommentPolicy;ZLorg/pnfolder/pnlibrary/api/config/ConfigSteps;Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy;Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V public static final fun builder ()Lorg/pnfolder/pnlibrary/api/config/ConfigOptions$Builder; public final fun component1 ()Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy; + public final fun component10 ()Z public final fun component2 ()Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy; public final fun component3 ()Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy; public final fun component4 ()Lorg/pnfolder/pnlibrary/api/config/CommentPolicy; public final fun component5 ()Z public final fun component6 ()Lorg/pnfolder/pnlibrary/api/config/ConfigSteps; public final fun component7 ()Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy; - public final fun copy (Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;Lorg/pnfolder/pnlibrary/api/config/CommentPolicy;ZLorg/pnfolder/pnlibrary/api/config/ConfigSteps;Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy;)Lorg/pnfolder/pnlibrary/api/config/ConfigOptions; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/config/ConfigOptions;Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;Lorg/pnfolder/pnlibrary/api/config/CommentPolicy;ZLorg/pnfolder/pnlibrary/api/config/ConfigSteps;Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigOptions; + public final fun component8 ()Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy; + public final fun component9 ()Lorg/pnfolder/pnlibrary/api/config/ConfigRoot; + public final fun copy (Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;Lorg/pnfolder/pnlibrary/api/config/CommentPolicy;ZLorg/pnfolder/pnlibrary/api/config/ConfigSteps;Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy;Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;Z)Lorg/pnfolder/pnlibrary/api/config/ConfigOptions; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/config/ConfigOptions;Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;Lorg/pnfolder/pnlibrary/api/config/CommentPolicy;ZLorg/pnfolder/pnlibrary/api/config/ConfigSteps;Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy;Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy;Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigOptions; public fun equals (Ljava/lang/Object;)Z public final fun getBackups ()Z public final fun getComments ()Lorg/pnfolder/pnlibrary/api/config/CommentPolicy; @@ -128,6 +334,9 @@ public final class org/pnfolder/pnlibrary/api/config/ConfigOptions { public final fun getMissingFile ()Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy; public final fun getMissingValues ()Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy; public final fun getNaming ()Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy; + public final fun getReadOnly ()Z + public final fun getRoot ()Lorg/pnfolder/pnlibrary/api/config/ConfigRoot; + public final fun getUnknownTypes ()Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy; public final fun getUnknownValues ()Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy; public fun hashCode ()I public fun toString ()Ljava/lang/String; @@ -141,6 +350,10 @@ public final class org/pnfolder/pnlibrary/api/config/ConfigOptions$Builder { public final fun missingFile (Lorg/pnfolder/pnlibrary/api/config/MissingFilePolicy;)Lorg/pnfolder/pnlibrary/api/config/ConfigOptions$Builder; public final fun missingValues (Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy;)Lorg/pnfolder/pnlibrary/api/config/ConfigOptions$Builder; public final fun naming (Lorg/pnfolder/pnlibrary/api/config/ConfigNamingStrategy;)Lorg/pnfolder/pnlibrary/api/config/ConfigOptions$Builder; + public final fun readOnly (Z)Lorg/pnfolder/pnlibrary/api/config/ConfigOptions$Builder; + public static synthetic fun readOnly$default (Lorg/pnfolder/pnlibrary/api/config/ConfigOptions$Builder;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigOptions$Builder; + public final fun root (Lorg/pnfolder/pnlibrary/api/config/ConfigRoot;)Lorg/pnfolder/pnlibrary/api/config/ConfigOptions$Builder; + public final fun unknownTypes (Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy;)Lorg/pnfolder/pnlibrary/api/config/ConfigOptions$Builder; public final fun unknownValues (Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy;)Lorg/pnfolder/pnlibrary/api/config/ConfigOptions$Builder; public final fun withoutVersion ()Lorg/pnfolder/pnlibrary/api/config/ConfigOptions$Builder; } @@ -182,18 +395,40 @@ public abstract interface annotation class org/pnfolder/pnlibrary/api/config/Con public abstract interface annotation class org/pnfolder/pnlibrary/api/config/ConfigRequired : java/lang/annotation/Annotation { } +public final class org/pnfolder/pnlibrary/api/config/ConfigRoot : java/lang/Enum { + public static final field EXTERNAL Lorg/pnfolder/pnlibrary/api/config/ConfigRoot; + public static final field PLUGIN Lorg/pnfolder/pnlibrary/api/config/ConfigRoot; + public static final field PLUGINS Lorg/pnfolder/pnlibrary/api/config/ConfigRoot; + public static final field SERVER Lorg/pnfolder/pnlibrary/api/config/ConfigRoot; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public final fun getPrefix ()Ljava/lang/String; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigRoot; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/config/ConfigRoot; +} + public abstract interface class org/pnfolder/pnlibrary/api/config/ConfigScope : java/lang/AutoCloseable { public abstract fun close ()V + public abstract fun extensions (Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess;)Lorg/pnfolder/pnlibrary/api/config/ConfigScope; + public abstract fun get (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ManagedConfig; + public abstract fun getModule ()Lorg/pnfolder/pnlibrary/api/plugin/ModuleId; + public abstract fun getPlugin ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; public abstract fun getSize ()I + public abstract fun list ()Ljava/util/List; public abstract fun loadAll ()V - public abstract fun publishType (Ljava/lang/Class;Ljava/lang/Class;Ljava/lang/String;Ljava/util/Set;ILorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeRegistration; + public abstract fun publishSerializer (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializer;ILorg/pnfolder/pnlibrary/api/config/ConfigAddress;)Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerRegistration; + public abstract fun publishType (Ljava/lang/Class;Ljava/lang/Class;Ljava/lang/String;Ljava/util/Set;ILorg/pnfolder/pnlibrary/api/config/ConfigAddress;Lorg/pnfolder/pnlibrary/api/config/ConfigTypeConflict;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeRegistration; + public static synthetic fun publishType$default (Lorg/pnfolder/pnlibrary/api/config/ConfigScope;Ljava/lang/Class;Ljava/lang/Class;Ljava/lang/String;Ljava/util/Set;ILorg/pnfolder/pnlibrary/api/config/ConfigAddress;Lorg/pnfolder/pnlibrary/api/config/ConfigTypeConflict;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeRegistration; public abstract fun reloadAll ()V + public fun require (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ManagedConfig; public abstract fun saveAll ()V public abstract fun serializer (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializer;)Lorg/pnfolder/pnlibrary/api/config/ConfigScope; + public fun serializerFor (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializer;)Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerBuilder; public fun type (Ljava/lang/Class;Ljava/lang/Class;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; public abstract fun yaml (Ljava/lang/String;Ljava/lang/Class;Ljava/util/function/Supplier;)Lorg/pnfolder/pnlibrary/api/config/ManagedConfig; public fun yaml (Ljava/lang/String;Ljava/lang/Class;Ljava/util/function/Supplier;Lorg/pnfolder/pnlibrary/api/config/ConfigOptions;)Lorg/pnfolder/pnlibrary/api/config/ManagedConfig; public abstract fun yaml (Ljava/lang/String;Ljava/lang/Class;Ljava/util/function/Supplier;Lorg/pnfolder/pnlibrary/api/config/ConfigOptions;Lorg/pnfolder/pnlibrary/api/config/ConfigValueValidator;)Lorg/pnfolder/pnlibrary/api/config/ManagedConfig; + public fun yamlAt (Ljava/nio/file/Path;Ljava/lang/Class;Ljava/util/function/Supplier;Lorg/pnfolder/pnlibrary/api/config/ConfigOptions;)Lorg/pnfolder/pnlibrary/api/config/ManagedConfig; + public static synthetic fun yamlAt$default (Lorg/pnfolder/pnlibrary/api/config/ConfigScope;Ljava/nio/file/Path;Ljava/lang/Class;Ljava/util/function/Supplier;Lorg/pnfolder/pnlibrary/api/config/ConfigOptions;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ManagedConfig; } public abstract interface annotation class org/pnfolder/pnlibrary/api/config/ConfigSecret : java/lang/annotation/Annotation { @@ -235,6 +470,98 @@ public abstract interface class org/pnfolder/pnlibrary/api/config/ConfigSerializ public abstract fun serialize (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/config/ConfigSerializationContext;)Ljava/lang/Object; } +public final class org/pnfolder/pnlibrary/api/config/ConfigSerializerBuilder { + public final fun everywhere ()Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerBuilder; + public final fun into (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerBuilder; + public final fun into (Lorg/pnfolder/pnlibrary/api/config/ConfigAddress;)Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerBuilder; + public final fun into (Lorg/pnfolder/pnlibrary/api/config/ConfigInfo;)Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerBuilder; + public final fun into (Lorg/pnfolder/pnlibrary/api/config/ConfigScope;)Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerBuilder; + public final fun into (Lorg/pnfolder/pnlibrary/api/config/ManagedConfig;)Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerBuilder; + public final fun into (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerBuilder; + public final fun priority (I)Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerBuilder; + public final fun register ()Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerRegistration; +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigSerializerInfo { + public fun (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;ILorg/pnfolder/pnlibrary/api/config/ConfigAddress;)V + public final fun component1 ()Ljava/lang/Class; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun component3 ()I + public final fun component4 ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun copy (Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;ILorg/pnfolder/pnlibrary/api/config/ConfigAddress;)Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerInfo; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerInfo;Ljava/lang/Class;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;ILorg/pnfolder/pnlibrary/api/config/ConfigAddress;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigSerializerInfo; + public fun equals (Ljava/lang/Object;)Z + public final fun getOwner ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun getPriority ()I + public final fun getTarget ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun getType ()Ljava/lang/Class; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public abstract interface class org/pnfolder/pnlibrary/api/config/ConfigSerializerRegistration : java/lang/AutoCloseable { + public abstract fun close ()V + public abstract fun getOwner ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public abstract fun getPriority ()I + public abstract fun getTarget ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public abstract fun getType ()Ljava/lang/Class; + public abstract fun isActive ()Z +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigSetting { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind;Ljava/lang/String;Ljava/util/List;Ljava/lang/Double;Ljava/lang/Double;Lorg/pnfolder/pnlibrary/api/config/ConfigApply;Ljava/lang/String;DLjava/util/concurrent/TimeUnit;Ljava/lang/String;Ljava/util/List;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind;Ljava/lang/String;Ljava/util/List;Ljava/lang/Double;Ljava/lang/Double;Lorg/pnfolder/pnlibrary/api/config/ConfigApply;Ljava/lang/String;DLjava/util/concurrent/TimeUnit;Ljava/lang/String;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component10 ()Ljava/lang/String; + public final fun component11 ()D + public final fun component12 ()Ljava/util/concurrent/TimeUnit; + public final fun component13 ()Ljava/lang/String; + public final fun component14 ()Ljava/util/List; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind; + public final fun component5 ()Ljava/lang/String; + public final fun component6 ()Ljava/util/List; + public final fun component7 ()Ljava/lang/Double; + public final fun component8 ()Ljava/lang/Double; + public final fun component9 ()Lorg/pnfolder/pnlibrary/api/config/ConfigApply; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind;Ljava/lang/String;Ljava/util/List;Ljava/lang/Double;Ljava/lang/Double;Lorg/pnfolder/pnlibrary/api/config/ConfigApply;Ljava/lang/String;DLjava/util/concurrent/TimeUnit;Ljava/lang/String;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/config/ConfigSetting; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/config/ConfigSetting;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind;Ljava/lang/String;Ljava/util/List;Ljava/lang/Double;Ljava/lang/Double;Lorg/pnfolder/pnlibrary/api/config/ConfigApply;Ljava/lang/String;DLjava/util/concurrent/TimeUnit;Ljava/lang/String;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigSetting; + public fun equals (Ljava/lang/Object;)Z + public final fun getApply ()Lorg/pnfolder/pnlibrary/api/config/ConfigApply; + public final fun getChoices ()Ljava/util/List; + public final fun getDescription ()Ljava/lang/String; + public final fun getDuration ()Ljava/util/concurrent/TimeUnit; + public final fun getExamples ()Ljava/util/List; + public final fun getFormat ()Ljava/lang/String; + public final fun getKind ()Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind; + public final fun getMax ()Ljava/lang/Double; + public final fun getMin ()Ljava/lang/Double; + public final fun getPath ()Ljava/lang/String; + public final fun getStep ()D + public final fun getTitle ()Ljava/lang/String; + public final fun getUnit ()Ljava/lang/String; + public final fun getValue ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigSettingKind : java/lang/Enum { + public static final field BOOLEAN Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind; + public static final field CHOICE Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind; + public static final field DECIMAL Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind; + public static final field INTEGER Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind; + public static final field TEXT Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/config/ConfigSettingKind; +} + +public abstract interface annotation class org/pnfolder/pnlibrary/api/config/ConfigStep : java/lang/annotation/Annotation { + public abstract fun step ()D + public abstract fun unit ()Ljava/lang/String; +} + public class org/pnfolder/pnlibrary/api/config/ConfigSteps { public static final field BASE_VERSION I public static final field Companion Lorg/pnfolder/pnlibrary/api/config/ConfigSteps$Companion; @@ -264,42 +591,52 @@ public abstract interface annotation class org/pnfolder/pnlibrary/api/config/Con public abstract fun type ()Ljava/lang/Class; } -public final class org/pnfolder/pnlibrary/api/config/ConfigTypeAccess { - public static final field Companion Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess$Companion; - public synthetic fun (ZLjava/util/Set;Ljava/util/Set;Ljava/util/Set;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun allows (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Z - public static final fun builder ()Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess$Builder; - public static final fun everyone ()Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess; - public final fun getAllLibraryPlugins ()Z - public final fun getAllowedPatterns ()Ljava/util/Set; - public final fun getAllowedPlugins ()Ljava/util/Set; - public final fun getDeniedPlugins ()Ljava/util/Set; - public static final fun ownerOnly ()Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess; - public static final fun plugins ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess; -} - -public final class org/pnfolder/pnlibrary/api/config/ConfigTypeAccess$Builder { - public final fun allow ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess$Builder; - public final fun allowAll ()Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess$Builder; - public final fun allowMatching ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess$Builder; - public final fun build ()Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess; - public final fun deny ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess$Builder; -} - -public final class org/pnfolder/pnlibrary/api/config/ConfigTypeAccess$Companion { - public final fun builder ()Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess$Builder; - public final fun everyone ()Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess; - public final fun ownerOnly ()Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess; - public final fun plugins ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess; -} - public final class org/pnfolder/pnlibrary/api/config/ConfigTypeBuilder { - public final fun access (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; - public final fun access (Lorg/pnfolder/pnlibrary/api/config/ConfigTypeAccess;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; public final fun alias ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; + public final fun everywhere ()Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; + public final fun into (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; + public final fun into (Lorg/pnfolder/pnlibrary/api/config/ConfigAddress;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; + public final fun into (Lorg/pnfolder/pnlibrary/api/config/ConfigInfo;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; + public final fun into (Lorg/pnfolder/pnlibrary/api/config/ConfigScope;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; + public final fun into (Lorg/pnfolder/pnlibrary/api/config/ManagedConfig;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; + public final fun into (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; public final fun name (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; + public final fun onConflict (Lorg/pnfolder/pnlibrary/api/config/ConfigTypeConflict;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; public final fun priority (I)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeBuilder; public final fun register ()Lorg/pnfolder/pnlibrary/api/config/ConfigTypeRegistration; + public final fun registerEach (Ljava/util/Collection;)Ljava/util/List; +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigTypeConflict : java/lang/Enum { + public static final field FAIL Lorg/pnfolder/pnlibrary/api/config/ConfigTypeConflict; + public static final field KEEP Lorg/pnfolder/pnlibrary/api/config/ConfigTypeConflict; + public static final field REPLACE Lorg/pnfolder/pnlibrary/api/config/ConfigTypeConflict; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeConflict; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/config/ConfigTypeConflict; +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigTypeInfo { + public fun (Ljava/lang/Class;Ljava/lang/Class;Ljava/lang/String;Ljava/util/Set;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;ILorg/pnfolder/pnlibrary/api/config/ConfigAddress;)V + public final fun component1 ()Ljava/lang/Class; + public final fun component2 ()Ljava/lang/Class; + public final fun component3 ()Ljava/lang/String; + public final fun component4 ()Ljava/util/Set; + public final fun component5 ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun component6 ()I + public final fun component7 ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public final fun copy (Ljava/lang/Class;Ljava/lang/Class;Ljava/lang/String;Ljava/util/Set;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;ILorg/pnfolder/pnlibrary/api/config/ConfigAddress;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeInfo; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/config/ConfigTypeInfo;Ljava/lang/Class;Ljava/lang/Class;Ljava/lang/String;Ljava/util/Set;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;ILorg/pnfolder/pnlibrary/api/config/ConfigAddress;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigTypeInfo; + public fun equals (Ljava/lang/Object;)Z + public final fun getAliases ()Ljava/util/Set; + public final fun getBaseType ()Ljava/lang/Class; + public final fun getImplementation ()Ljava/lang/Class; + public final fun getName ()Ljava/lang/String; + public final fun getOwner ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public final fun getPriority ()I + public final fun getTarget ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; } public abstract interface class org/pnfolder/pnlibrary/api/config/ConfigTypeRegistration : java/lang/AutoCloseable { @@ -308,6 +645,7 @@ public abstract interface class org/pnfolder/pnlibrary/api/config/ConfigTypeRegi public abstract fun getImplementation ()Ljava/lang/Class; public abstract fun getName ()Ljava/lang/String; public abstract fun getOwner ()Lorg/pnfolder/pnlibrary/api/plugin/PluginId; + public abstract fun getTarget ()Lorg/pnfolder/pnlibrary/api/config/ConfigAddress; public abstract fun isActive ()Z } @@ -339,16 +677,62 @@ public abstract interface class org/pnfolder/pnlibrary/api/config/ConfigValueVal } public abstract interface class org/pnfolder/pnlibrary/api/config/ConfigurationService { + public abstract fun all ()Ljava/util/List; + public fun byModel (Ljava/lang/Class;)Ljava/util/List; + public fun find (Ljava/lang/String;)Ljava/util/List; + public abstract fun find (Lorg/pnfolder/pnlibrary/api/config/ConfigAddress;)Ljava/util/List; + public fun get (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ManagedConfig; + public abstract fun get (Lorg/pnfolder/pnlibrary/api/config/ConfigId;)Lorg/pnfolder/pnlibrary/api/config/ManagedConfig; + public fun require (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ManagedConfig; + public fun require (Lorg/pnfolder/pnlibrary/api/config/ConfigId;)Lorg/pnfolder/pnlibrary/api/config/ManagedConfig; public abstract fun scope (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ConfigScope; + public abstract fun serializers ()Ljava/util/List; + public abstract fun types (Ljava/lang/Class;)Ljava/util/List; +} + +public final class org/pnfolder/pnlibrary/api/config/ConfigurationServiceKt { + public static final fun extensions (Lorg/pnfolder/pnlibrary/api/config/ConfigScope;Lkotlin/jvm/functions/Function1;)Lorg/pnfolder/pnlibrary/api/config/ConfigScope; +} + +public abstract interface annotation class org/pnfolder/pnlibrary/api/config/DatabaseField : java/lang/annotation/Annotation { + public abstract fun database ()Ljava/lang/String; + public abstract fun role ()Lorg/pnfolder/pnlibrary/api/config/DatabaseRole; +} + +public final class org/pnfolder/pnlibrary/api/config/DatabaseKind : java/lang/Enum { + public static final field MONGODB Lorg/pnfolder/pnlibrary/api/config/DatabaseKind; + public static final field MYSQL Lorg/pnfolder/pnlibrary/api/config/DatabaseKind; + public static final field POSTGRESQL Lorg/pnfolder/pnlibrary/api/config/DatabaseKind; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/DatabaseKind; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/config/DatabaseKind; +} + +public final class org/pnfolder/pnlibrary/api/config/DatabaseRole : java/lang/Enum { + public static final field DATABASE Lorg/pnfolder/pnlibrary/api/config/DatabaseRole; + public static final field HOST Lorg/pnfolder/pnlibrary/api/config/DatabaseRole; + public static final field PASSWORD Lorg/pnfolder/pnlibrary/api/config/DatabaseRole; + public static final field PORT Lorg/pnfolder/pnlibrary/api/config/DatabaseRole; + public static final field URI Lorg/pnfolder/pnlibrary/api/config/DatabaseRole; + public static final field USER Lorg/pnfolder/pnlibrary/api/config/DatabaseRole; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/DatabaseRole; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/config/DatabaseRole; } public abstract interface class org/pnfolder/pnlibrary/api/config/ManagedConfig : java/lang/AutoCloseable { public fun close ()V + public fun edit (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/ConfigEditResult; public abstract fun get ()Ljava/lang/Object; + public fun getId ()Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public fun getInfo ()Lorg/pnfolder/pnlibrary/api/config/ConfigInfo; + public fun getSettings ()Ljava/util/List; public fun getValue ()Ljava/lang/Object; public abstract fun isLoaded ()Z public abstract fun load ()Lorg/pnfolder/pnlibrary/api/config/ConfigLoadResult; public fun loadValue ()Ljava/lang/Object; + public fun onChanged ([Ljava/util/function/Consumer;)Ljava/lang/AutoCloseable; + public fun onReloadRequired ([Ljava/util/function/Consumer;)Ljava/lang/AutoCloseable; public abstract fun reload ()Lorg/pnfolder/pnlibrary/api/config/ConfigLoadResult; public fun reloadValue ()Ljava/lang/Object; public abstract fun resetToDefaults ()Ljava/lang/Object; @@ -376,6 +760,29 @@ public final class org/pnfolder/pnlibrary/api/config/MissingValuePolicy : java/l public static fun values ()[Lorg/pnfolder/pnlibrary/api/config/MissingValuePolicy; } +public final class org/pnfolder/pnlibrary/api/config/ReloadRequest { + public fun (Lorg/pnfolder/pnlibrary/api/config/ConfigId;Lorg/pnfolder/pnlibrary/api/config/ConfigApply;Ljava/util/List;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public final fun component2 ()Lorg/pnfolder/pnlibrary/api/config/ConfigApply; + public final fun component3 ()Ljava/util/List; + public final fun copy (Lorg/pnfolder/pnlibrary/api/config/ConfigId;Lorg/pnfolder/pnlibrary/api/config/ConfigApply;Ljava/util/List;)Lorg/pnfolder/pnlibrary/api/config/ReloadRequest; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/config/ReloadRequest;Lorg/pnfolder/pnlibrary/api/config/ConfigId;Lorg/pnfolder/pnlibrary/api/config/ConfigApply;Ljava/util/List;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/config/ReloadRequest; + public fun equals (Ljava/lang/Object;)Z + public final fun getApply ()Lorg/pnfolder/pnlibrary/api/config/ConfigApply; + public final fun getId ()Lorg/pnfolder/pnlibrary/api/config/ConfigId; + public final fun getSettings ()Ljava/util/List; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/config/UnknownTypePolicy : java/lang/Enum { + public static final field FAIL Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy; + public static final field SKIP Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy; + public static fun values ()[Lorg/pnfolder/pnlibrary/api/config/UnknownTypePolicy; +} + public final class org/pnfolder/pnlibrary/api/config/UnknownValuePolicy : java/lang/Enum { public static final field FAIL Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy; public static final field PRESERVE Lorg/pnfolder/pnlibrary/api/config/UnknownValuePolicy; diff --git a/modules/features/config-api/build.gradle.kts b/modules/features/config-api/build.gradle.kts index 343569b2b..7681ddf9a 100644 --- a/modules/features/config-api/build.gradle.kts +++ b/modules/features/config-api/build.gradle.kts @@ -15,7 +15,8 @@ dependencies { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-config-api", project.version.toString()) pom { name.set("pnLibrary Config API") diff --git a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigAnnotations.kt b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigAnnotations.kt index 85b72a37d..98d1ff834 100644 --- a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigAnnotations.kt +++ b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigAnnotations.kt @@ -44,7 +44,7 @@ annotation class ConfigIgnore * Marks a field whose value must never appear in a diagnostic report, such as a password, a token or a webhook. * * It applies to the file this class is registered for, and to a nested section when put on the field holding it. - * The value is hidden in every report with no entry in `plugins/pnLibrary/config.yml`: + * The value is hidden in every report with no extra setting in the library: * ```kotlin * @field:ConfigSecret * var password: String = "" @@ -191,3 +191,97 @@ annotation class ConfigType( val aliases: Array = [], val priority: Int = 0, ) + +/** A kind of database pnLibrary can copy before an update and put back on a rollback. */ +enum class DatabaseKind { + /** MySQL and MariaDB. */ + MYSQL, + + /** MongoDB; documents are copied with their indexes, without a snapshot in time. */ + MONGODB, + + /** PostgreSQL; tables of the current schema are copied with indexes, constraints and sequences. */ + POSTGRESQL, +} + +/** + * Declares a database that pnLibrary copies before an update of this plugin and can restore when the update is + * rolled back. Repeatable, so one class can describe several databases; their names must differ within a plugin. + * + * Three placements are supported: + * - On a field holding a connection section (a nested class): that section's fields describe the connection. + * - On a scalar `String` field: the field is the database name, and the other connection fields of the same class + * are tied to it by [DatabaseField] with the same [name]. + * - On the configuration class itself, when the connection fields sit at the top of the file. + * + * Connection fields are found by their usual names (`host`, `port`, `database`, `user` or `username`, `password`); + * mark them with [DatabaseField] to use any name. Mark the password with [ConfigSecret] so reports hide it. + * ```kotlin + * @field:BackupDatabase(DatabaseKind.POSTGRESQL, "Clans", tables = ["clans", "clan_members"]) + * var clansDb = "clans" + * @field:DatabaseField(DatabaseRole.HOST, database = "Clans") + * var clansHost = "pg.local" + * ``` + * Only tables (collections in MongoDB) are copied; triggers, procedures and views are not. + * + * @property kind the database server type + * @property name short name shown by the menu and commands; also the key that ties [DatabaseField] and [BackupTable] to it + * @property tables tables or collections to copy; `*` in a name matches any text (`"log_*"`); empty means all of them + */ +@Target(AnnotationTarget.FIELD, AnnotationTarget.CLASS) +@Retention(AnnotationRetention.RUNTIME) +@Repeatable +annotation class BackupDatabase(val kind: DatabaseKind, val name: String, val tables: Array = []) + +/** What a field of a database connection section holds. */ +enum class DatabaseRole { + /** Server host name or address. */ + HOST, + + /** Server port. */ + PORT, + + /** Database (schema) name. */ + DATABASE, + + /** Login of the account. */ + USER, + + /** Password of the account; also mark the field with [ConfigSecret]. */ + PASSWORD, + + /** A full connection string such as `mongodb://user:pass@host/db`; when present it replaces host, port, user and password. */ + URI, +} + +/** + * Says which part of a connection a field holds, so the field can have any name. Use it next to [BackupDatabase]; + * fields without it are found by their usual names. + * + * With several databases in one class, [database] names the [BackupDatabase.name] the field belongs to. A field + * without [database] is shared by all of them, and a field with it wins over a shared one. + * ```kotlin + * @field:DatabaseField(DatabaseRole.HOST) + * var address = "localhost" + * ``` + * + * @property role which part of the connection the field holds + * @property database [BackupDatabase.name] this field belongs to; empty means every database of the class + */ +@Target(AnnotationTarget.FIELD) +@Retention(AnnotationRetention.RUNTIME) +annotation class DatabaseField(val role: DatabaseRole, val database: String = "") + +/** + * Marks a text field that holds the name of a table (or collection) to copy, for plugins whose table names are set + * in the configuration. Several fields may carry it; together with [BackupDatabase.tables] both lists are joined. + * ```kotlin + * @field:BackupTable + * var table = "clans" + * ``` + * + * @property database [BackupDatabase.name] this table belongs to; empty means every database of the class + */ +@Target(AnnotationTarget.FIELD) +@Retention(AnnotationRetention.RUNTIME) +annotation class BackupTable(val database: String = "") diff --git a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigIdentity.kt b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigIdentity.kt new file mode 100644 index 000000000..d6fe1a041 --- /dev/null +++ b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigIdentity.kt @@ -0,0 +1,287 @@ +package org.pnfolder.pnlibrary.api.config + +import org.pnfolder.pnlibrary.api.plugin.ModuleId +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.nio.file.Path +import java.time.Instant + +/** + * The folder a configuration path is counted from. + * + * A path never leaves its root. Files in [PLUGINS] and [SERVER] belong to somebody else, so they get strict defaults: + * a missing file is never created, a backup is always made before a rewrite and unknown keys are kept. + * [EXTERNAL] is the plugin's own choice of an absolute path and has no such limits. + * + * @property prefix text put in front of the path in a [ConfigId], empty for [PLUGIN] + */ +enum class ConfigRoot(val prefix: String) { + /** The data folder of the plugin: `plugins/Name/`. This is the default. */ + PLUGIN(""), + + /** The `plugins/` folder, for example a file of another plugin. */ + PLUGINS("@plugins/"), + + /** The server root, next to `server.properties`. */ + SERVER("@server/"), + + /** + * Any place on the machine, given by an absolute path: another disk, a mounted or network share, a folder the + * plugin learned from its own settings. The plugin opens it itself, so it is treated like its own file + * (it may be created and rewritten). The path in the [ConfigId] is the absolute path with `/` separators. + */ + EXTERNAL("@external/"), +} + +/** + * Address of one configuration file: plugin, module, root and path. + * + * Text form: `plugin/module:path`. A path outside the plugin folder starts with its root: + * `quests/main:@plugins/Essentials/config.yml`. + */ +data class ConfigId( + val plugin: PluginId, + val module: ModuleId, + val root: ConfigRoot, + val path: String, +) { + init { + require(path.isNotBlank()) { "Configuration path must not be blank" } + require(!path.startsWith("@")) { "Configuration path must not start with '@'; use the root parameter" } + } + + /** File name without folders: `daily.yml` for `rewards/daily.yml`. */ + val fileName: String get() = path.substringAfterLast('/') + + /** Folders in front of the file name, empty when the file lies in the root. */ + val directory: String get() = path.substringBeforeLast('/', "") + + /** The address of the module that owns this file. */ + val moduleAddress: ConfigAddress get() = ConfigAddress.module(plugin, module) + + /** The address of this exact file. */ + val address: ConfigAddress get() = ConfigAddress.file(this) + + /** Text form `plugin/module:path`. */ + override fun toString(): String = "${plugin.value}/${module.value}:${root.prefix}$path" + + /** Parsing and building. */ + companion object { + /** Builds an identifier from plain strings, with the plugin folder as root. */ + @JvmStatic + @JvmOverloads + fun of(plugin: String, module: String, path: String, root: ConfigRoot = ConfigRoot.PLUGIN): ConfigId = + ConfigId(PluginId.of(plugin), ModuleId.of(module), root, path.replace('\\', '/')) + + /** Reads `plugin/module:path`, with an optional `@plugins/` or `@server/` in front of the path. */ + @JvmStatic + fun parse(text: String): ConfigId { + val address = ConfigAddress.parse(text) + require(address.level == ConfigAddress.Level.FILE) { "'$text' is not a file address: expected plugin/module:path" } + return ConfigId(address.plugin, requireNotNull(address.module), requireNotNull(address.root), requireNotNull(address.path)) + } + } +} + +/** + * Address of a plugin, a module or a file. The shorter the text, the more files it covers: + * `quests` covers the whole plugin, `quests/main` one module, `quests/main:quests.yml` one file. + */ +class ConfigAddress private constructor( + private val owner: PluginId?, + /** Module, or `null` when the address covers the whole plugin. */ + val module: ModuleId?, + /** Root of the path, `null` unless the address names a file. */ + val root: ConfigRoot?, + /** Path inside the root, `null` unless the address names a file. */ + val path: String?, +) { + /** Plugin of the address. The address of everything ([isAll]) has none and fails here. */ + val plugin: PluginId get() = owner ?: throw IllegalStateException("The address of every file has no plugin") + + /** `true` for [everywhere]: every file of every plugin. */ + val isAll: Boolean get() = owner == null + + /** How much an address covers. */ + enum class Level { ALL, PLUGIN, MODULE, FILE } + + /** Everything, a plugin, a module or a file. */ + val level: Level + get() = when { + isAll -> Level.ALL + module == null -> Level.PLUGIN + path == null -> Level.MODULE + else -> Level.FILE + } + + /** Whether the file [id] lies inside this address. */ + fun matches(id: ConfigId): Boolean = + isAll || (owner == id.plugin && (module == null || module == id.module) && + (path == null || (root == id.root && path == id.path))) + + /** Whether some file can lie inside both this address and [other]. */ + fun overlaps(other: ConfigAddress): Boolean { + if (isAll || other.isAll) return true + if (owner != other.owner) return false + if (module != null && other.module != null && module != other.module) return false + if (path != null && other.path != null && (root != other.root || path != other.path)) return false + return true + } + + /** + * This plugin's address narrowed to one module: `ConfigAddress.plugin("shop").inModule("main")`. + * Only an address of a whole plugin can be narrowed. + */ + fun inModule(module: ModuleId): ConfigAddress { + require(level == Level.PLUGIN) { "Only the address of a whole plugin can be narrowed to a module, but this one is $this" } + return ConfigAddress(plugin, module, null, null) + } + + /** Same as [inModule] with the module written as text. */ + fun inModule(module: String): ConfigAddress = inModule(ModuleId.of(module)) + + /** + * This module's address narrowed to one file: `ConfigAddress.plugin("shop").inModule("main").inFile("rewards.yml")`. + * [root] says where [path] is counted from, the plugin folder by default. + */ + @JvmOverloads + fun inFile(path: String, root: ConfigRoot = ConfigRoot.PLUGIN): ConfigAddress { + require(level == Level.MODULE) { "Only the address of a module can be narrowed to a file, but this one is $this" } + val clean = path.replace('\\', '/').removePrefix(root.prefix) + require(clean.isNotBlank()) { "The path of a file must not be blank" } + return ConfigAddress(plugin, module, root, clean) + } + + override fun equals(other: Any?): Boolean = other is ConfigAddress && toString() == other.toString() + + override fun hashCode(): Int = toString().hashCode() + + /** Text form: `*`, `plugin`, `plugin/module` or `plugin/module:path`. */ + override fun toString(): String = if (isAll) "*" else buildString { + append(plugin.value) + if (module != null) append('/').append(module.value) + if (path != null) append(':').append(root?.prefix.orEmpty()).append(path) + } + + /** Parsing and building. */ + companion object { + /** Address of every file of every plugin, written `*`. */ + @JvmStatic + fun everywhere(): ConfigAddress = ConfigAddress(null, null, null, null) + + /** Address of a whole plugin. */ + @JvmStatic + fun plugin(plugin: PluginId): ConfigAddress = ConfigAddress(plugin, null, null, null) + + /** Address of a whole plugin written as its name. */ + @JvmStatic + fun plugin(plugin: String): ConfigAddress = plugin(PluginId.of(plugin)) + + /** Address of one module written as plugin and module names. */ + @JvmStatic + fun module(plugin: String, module: String): ConfigAddress = module(PluginId.of(plugin), ModuleId.of(module)) + + /** Address of one module. */ + @JvmStatic + fun module(plugin: PluginId, module: ModuleId): ConfigAddress = ConfigAddress(plugin, module, null, null) + + /** Address of one file. */ + @JvmStatic + fun file(id: ConfigId): ConfigAddress = ConfigAddress(id.plugin, id.module, id.root, id.path) + + /** Reads `*`, `plugin`, `plugin/module` or `plugin/module:path`. */ + @JvmStatic + fun parse(text: String): ConfigAddress { + val value = text.trim() + require(value.isNotEmpty()) { "Configuration address must not be blank" } + if (value == "*") return everywhere() + val colon = value.indexOf(':') + val head = if (colon < 0) value else value.substring(0, colon) + val parts = head.split('/') + require(parts.size <= 2 && parts.all { it.isNotBlank() }) { + "Invalid configuration address '$text': expected plugin, plugin/module or plugin/module:path" + } + val pluginId = PluginId.of(parts[0]) + if (parts.size == 1) { + require(colon < 0) { "Invalid configuration address '$text': a path needs a module (plugin/module:path)" } + return ConfigAddress(pluginId, null, null, null) + } + val moduleId = ModuleId.of(parts[1]) + if (colon < 0) return ConfigAddress(pluginId, moduleId, null, null) + var path = value.substring(colon + 1).replace('\\', '/') + var root = ConfigRoot.PLUGIN + ConfigRoot.entries.filter { it != ConfigRoot.PLUGIN }.firstOrNull { path.startsWith(it.prefix) }?.let { + root = it + path = path.removePrefix(it.prefix) + } + require(path.isNotBlank()) { "Invalid configuration address '$text': the path is empty" } + return ConfigAddress(pluginId, moduleId, root, path) + } + } +} + +/** + * Read-only description of one registered configuration file. It never carries values from the file, + * so `@ConfigSecret` fields cannot leak through it. + * + * @property id identifier of the file + * @property modelType class the file is read into + * @property file full path on disk + * @property exists whether the file exists now + * @property isLoaded whether a value is currently held in memory + * @property loadedAt time of the last successful load or reload + * @property readOnly whether the library only reads the file and never writes it + * @property skippedUnknownTypes list elements skipped at the last load because their `type` is not known + * @property problems validation problems of the loaded value, empty when not loaded + * @property pendingApply the strongest requirement of settings changed since the last read that do not work yet, or `null` + */ +data class ConfigInfo( + val id: ConfigId, + val modelType: Class<*>, + val file: Path, + val exists: Boolean, + val isLoaded: Boolean, + val loadedAt: Instant?, + val readOnly: Boolean, + val skippedUnknownTypes: List, + val problems: List, + val pendingApply: ConfigApply? = null, +) { + /** The address of this exact file, ready to be passed to `into(...)`. */ + val address: ConfigAddress get() = id.address + + /** The address of the module that owns this file. */ + val moduleAddress: ConfigAddress get() = id.moduleAddress + + /** Plugin of the file. */ + val plugin: PluginId get() = id.plugin + + /** Module of the file. */ + val module: ModuleId get() = id.module + + /** Path inside the root. */ + val path: String get() = id.path + + /** Root of the path. */ + val root: ConfigRoot get() = id.root +} + +/** + * One word that a polymorphic configuration type understands in its `type` field. + * + * @property baseType the polymorphic contract + * @property implementation class created for the word + * @property name main word + * @property aliases other accepted words + * @property owner plugin that added the word, or `null` when the base type declares it itself + * @property priority wins over a lower priority when two additions use the same word + * @property target where the word works, or `null` for a word declared by the base type + */ +data class ConfigTypeInfo( + val baseType: Class<*>, + val implementation: Class<*>, + val name: String, + val aliases: Set, + val owner: PluginId?, + val priority: Int, + val target: ConfigAddress?, +) diff --git a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigOptions.kt b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigOptions.kt index eab1808a2..69848ebc9 100644 --- a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigOptions.kt +++ b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigOptions.kt @@ -33,6 +33,19 @@ enum class UnknownValuePolicy { FAIL, } +/** What to do with a list element whose `type` is not known to a polymorphic type. */ +enum class UnknownTypePolicy { + /** Reject the whole file with an error that names the element. */ + FAIL, + + /** + * Skip the element, warn, and keep it in the file untouched. While an element is skipped the library does not + * rewrite the file from memory (`save`, `update`, `resetToDefaults` fail), so nothing is lost. When the type + * appears later, the file is read again and the element comes back. Applies to list elements. + */ + SKIP, +} + /** What to do when an existing field has no code-defined comment. */ enum class CommentPolicy { /** Leave the file's existing comments unchanged. */ @@ -64,6 +77,16 @@ data class ConfigOptions @JvmOverloads constructor( val migrations: ConfigSteps<*>? = ConfigSteps.NONE, /** Default conversion from source field names to YAML keys. */ val naming: ConfigNamingStrategy = ConfigNamingStrategy.AS_DECLARED, + /** Policy applied to list elements whose `type` no registered implementation accepts. */ + val unknownTypes: UnknownTypePolicy = UnknownTypePolicy.FAIL, + /** + * Folder the path is counted from. In [ConfigRoot.PLUGINS] and [ConfigRoot.SERVER] the file is somebody else's: it is + * never created, a backup is always made before a rewrite and unknown keys are kept, whatever the other options say. + * [ConfigRoot.EXTERNAL] (see `ConfigScope.yamlAt`) is an absolute path of the plugin's own choice, without those limits. + */ + val root: ConfigRoot = ConfigRoot.PLUGIN, + /** Only read the file: nothing is created, synchronized or written, and `save` fails. Several plugins may read one file. */ + val readOnly: Boolean = false, ) { /** Default options and the Java-friendly fluent construction entry point. */ companion object { @@ -85,6 +108,9 @@ data class ConfigOptions @JvmOverloads constructor( private var backups = true private var migrations: ConfigSteps<*>? = ConfigSteps.NONE private var naming = ConfigNamingStrategy.AS_DECLARED + private var unknownTypes = UnknownTypePolicy.FAIL + private var root = ConfigRoot.PLUGIN + private var readOnly = false /** Sets the missing-file policy. */ fun missingFile(value: MissingFilePolicy): Builder = apply { missingFile = value } @@ -109,7 +135,17 @@ data class ConfigOptions @JvmOverloads constructor( /** Sets the default field naming strategy. */ fun naming(value: ConfigNamingStrategy): Builder = apply { naming = value } + /** Sets what happens to list elements with an unknown `type`. */ + fun unknownTypes(value: UnknownTypePolicy): Builder = apply { unknownTypes = value } + + /** Sets the folder the path is counted from. */ + fun root(value: ConfigRoot): Builder = apply { root = value } + + /** Makes the file read-only for the library. */ + fun readOnly(value: Boolean = true): Builder = apply { readOnly = value } + /** Creates the immutable option set. */ - fun build(): ConfigOptions = ConfigOptions(missingFile, missingValues, unknownValues, comments, backups, migrations, naming) + fun build(): ConfigOptions = + ConfigOptions(missingFile, missingValues, unknownValues, comments, backups, migrations, naming, unknownTypes, root, readOnly) } } diff --git a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigSerializerRegistration.kt b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigSerializerRegistration.kt new file mode 100644 index 000000000..1b82ea110 --- /dev/null +++ b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigSerializerRegistration.kt @@ -0,0 +1,83 @@ +package org.pnfolder.pnlibrary.api.config + +import org.pnfolder.pnlibrary.api.plugin.PluginId + +/** Handle for one serializer that a plugin published for the files at some address. */ +interface ConfigSerializerRegistration : AutoCloseable { + /** Plugin that published the serializer. */ + val owner: PluginId + + /** The value type the serializer converts. */ + val type: Class<*> + + /** Where the serializer works: everything, a plugin, a module or one file. */ + val target: ConfigAddress + + /** The higher value wins when several additions handle one type. */ + val priority: Int + + /** Whether the serializer is still used by configuration codecs. */ + val isActive: Boolean + + /** Stops using the serializer. Closing is idempotent. */ + override fun close() +} + +/** + * Fluent publication of one serializer, created by [ConfigScope.serializerFor]. + * + * Without [into] the serializer works in the files of the module that publishes it. With [into] it works where the + * address points, for example in another plugin's files, and it lives and dies with the publishing module. + * Nothing is published until [register] is called. + */ +class ConfigSerializerBuilder internal constructor( + private val scope: ConfigScope, + private val type: Class, + private val serializer: ConfigSerializer, +) { + private var priority = 0 + private var target: ConfigAddress? = null + + /** Sets the priority; the higher value wins when several additions handle one type. */ + fun priority(value: Int): ConfigSerializerBuilder = apply { priority = value } + + /** Makes the serializer work at [address]: everything, a plugin, a module or one file. */ + fun into(address: ConfigAddress): ConfigSerializerBuilder = apply { target = address } + + /** Short form for the address written as text: `*`, `quests`, `quests/main` or `quests/main:quests.yml`. */ + fun into(address: String): ConfigSerializerBuilder = into(ConfigAddress.parse(address)) + + /** Makes the serializer work in one registered file. */ + fun into(config: ManagedConfig<*>): ConfigSerializerBuilder = + into(requireNotNull(config.id) { "This configuration has no identifier" }.address) + + /** Makes the serializer work in every file of the plugin [plugin]. */ + fun into(plugin: PluginId): ConfigSerializerBuilder = into(ConfigAddress.plugin(plugin)) + + /** Makes the serializer work in every file of the module that owns [other], for example another plugin's scope. */ + fun into(other: ConfigScope): ConfigSerializerBuilder = into(ConfigAddress.module(other.plugin, other.module)) + + /** Makes the serializer work in the file that [info] describes, for example one found in the catalog. */ + fun into(info: ConfigInfo): ConfigSerializerBuilder = into(info.address) + + /** Makes the serializer work in every file of every plugin. */ + fun everywhere(): ConfigSerializerBuilder = into(ConfigAddress.everywhere()) + + /** Publishes the serializer and returns its handle. */ + fun register(): ConfigSerializerRegistration = scope.publishSerializer(type, serializer, priority, target) +} + +/** + * One serializer that plugins added, as the catalog lists it. + * + * @property type value type the serializer converts + * @property owner plugin that published it + * @property priority wins over a lower priority when two additions handle one type + * @property target where it works + */ +data class ConfigSerializerInfo( + val type: Class<*>, + val owner: PluginId, + val priority: Int, + val target: ConfigAddress, +) diff --git a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigSettings.kt b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigSettings.kt new file mode 100644 index 000000000..6f00321a1 --- /dev/null +++ b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigSettings.kt @@ -0,0 +1,140 @@ +package org.pnfolder.pnlibrary.api.config + +/** When an edited setting starts to work. */ +enum class ConfigApply { + /** At once: the plugin reads the value every time it needs it. */ + LIVE, + + /** After the file is read again: the plugin takes the value when it handles [ManagedConfig.onReloadRequired]. */ + RELOAD, + + /** After the server restarts. */ + RESTART, +} + +/** + * Shows a field in the in-game settings menu (`/pn gui`) and lets `/pn configs edit` change it. + * + * Only marked fields are shown; secrets ([ConfigSecret]) never are. Supported types: boolean, whole and decimal + * numbers, text and enums. A [ConfigRange] on the field limits a number, [ConfigStep] sets the click step, + * [ConfigDuration] marks a length of time and [ConfigHint] describes a text. + * + * ```kotlin + * @field:ConfigEditable("Приветствие", "Текст, который видит игрок при входе.") + * var greeting: String = "Добро пожаловать!" + * + * @field:ConfigEditable("Размер пула", "Сколько соединений держать открытыми.", apply = ConfigApply.RESTART) + * @field:ConfigRange(min = 1.0, max = 64.0) + * var poolSize: Int = 10 + * ``` + * + * @property title short name for a player; the YAML key when empty + * @property description what the setting does, shown next to it + * @property apply when a change starts to work + */ +@Target(AnnotationTarget.FIELD) +@Retention(AnnotationRetention.RUNTIME) +annotation class ConfigEditable(val title: String = "", val description: String = "", val apply: ConfigApply = ConfigApply.LIVE) + +/** + * How far one click changes a number in the settings menu, and the unit shown next to it. + * + * The menu also offers ten, a hundred and a thousand steps and lets the viewer type the number. + * + * @property step the smallest change of one click + * @property unit what the number counts, such as `блоков` or `%` + */ +@Target(AnnotationTarget.FIELD) +@Retention(AnnotationRetention.RUNTIME) +annotation class ConfigStep(val step: Double = 1.0, val unit: String = "") + +/** + * Marks a whole number as a length of time kept in [unit]. The menu shows it as `1 ч 30 мин`, steps by seconds, + * minutes or hours, and accepts typed values such as `90m`, `1h30m` or `45с`. + */ +@Target(AnnotationTarget.FIELD) +@Retention(AnnotationRetention.RUNTIME) +annotation class ConfigDuration(val unit: java.util.concurrent.TimeUnit) + +/** + * Tells the person who edits a text what it may hold. + * + * @property format how the text is written, such as `мир;x;y;z` + * @property examples sample values shown in the menu + * @property values the known values; with [strict] only they are accepted and the menu offers them as a list + * @property strict whether anything outside [values] is refused + */ +@Target(AnnotationTarget.FIELD) +@Retention(AnnotationRetention.RUNTIME) +annotation class ConfigHint( + val format: String = "", + val examples: Array = [], + val values: Array = [], + val strict: Boolean = false, +) + +/** What kind of value a setting holds, which decides the control that edits it. */ +enum class ConfigSettingKind { BOOLEAN, INTEGER, DECIMAL, TEXT, CHOICE } + +/** + * One editable setting of a configuration file. + * + * @property path dotted YAML path, such as `shop.greeting` + * @property title short name for a player + * @property description what it does + * @property kind the kind of value + * @property value current value as text, or `null` while the file is not loaded + * @property choices the allowed values of a [ConfigSettingKind.CHOICE], empty otherwise + * @property min lower bound of a number, or `null` + * @property max upper bound of a number, or `null` + * @property apply when a change starts to work + * @property unit what a number counts, empty when it counts nothing in particular + * @property step the smallest change of one click on a number + * @property duration the unit of a number that holds a length of time, or `null` + * @property format how a text is written, empty when free + * @property examples sample values of a text + */ +data class ConfigSetting( + val path: String, + val title: String, + val description: String, + val kind: ConfigSettingKind, + val value: String?, + val choices: List = emptyList(), + val min: Double? = null, + val max: Double? = null, + val apply: ConfigApply = ConfigApply.LIVE, + val unit: String = "", + val step: Double = 1.0, + val duration: java.util.concurrent.TimeUnit? = null, + val format: String = "", + val examples: List = emptyList(), +) + +/** The result of changing one setting: [setting] holds the new value, [previous] the old one. */ +data class ConfigEditResult(val setting: ConfigSetting, val previous: String?) + +/** A setting could not be changed; the message says why and is meant to be shown to the person who typed the value. */ +class ConfigEditException(message: String, cause: Throwable? = null) : IllegalArgumentException(message, cause) + +/** What happened to a file. */ +enum class ConfigChangeCause { LOADED, RELOADED, SAVED, EDITED, RESET } + +/** + * A file changed: it was read, written, or one of its settings was edited. + * + * @property id the file + * @property cause what happened + * @property paths YAML paths that changed, empty when the whole file is meant + */ +data class ConfigChange(val id: ConfigId?, val cause: ConfigChangeCause, val paths: List) + +/** + * A setting that does not work yet was changed: the plugin has to take it over ([ConfigApply.RELOAD]) or the server has + * to restart ([ConfigApply.RESTART]). + * + * @property id the file + * @property apply the strongest requirement among the [settings] + * @property settings the settings that were changed, with their new values + */ +data class ReloadRequest(val id: ConfigId?, val apply: ConfigApply, val settings: List) diff --git a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigTypeRegistration.kt b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigTypeRegistration.kt index 9d0185022..b665b68a6 100644 --- a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigTypeRegistration.kt +++ b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigTypeRegistration.kt @@ -1,88 +1,8 @@ package org.pnfolder.pnlibrary.api.config import org.pnfolder.pnlibrary.api.plugin.PluginId -import org.pnfolder.pnlibrary.common.text.Wildcards -import java.util.Collections import java.util.LinkedHashSet -/** - * Controls which plugin configurations may use a dynamically published polymorphic type. - * - * Denials are evaluated first and override every allow rule, including owner access. Otherwise the - * owner is allowed automatically. Pattern matching is case-insensitive and `*` matches any number - * of characters; all other pattern characters are treated literally. - */ -class ConfigTypeAccess private constructor( - /** Whether every pnLibrary plugin is allowed unless explicitly denied. */ - val allLibraryPlugins: Boolean, - /** Explicitly allowed plugin identifiers. */ - val allowedPlugins: Set, - /** Case-insensitive glob patterns matched against plugin identifiers. */ - val allowedPatterns: Set, - /** Explicit denials that override owner and allow rules. */ - val deniedPlugins: Set, -) { - init { - require(allowedPatterns.none(String::isBlank)) { "Config type access patterns must not be blank" } - } - - /** Returns whether [consumer] may use a type published by [owner]. */ - fun allows(owner: PluginId, consumer: PluginId): Boolean { - if (consumer in deniedPlugins) return false - if (owner == consumer) return true - return allLibraryPlugins || consumer in allowedPlugins || allowedPatterns.any { - Wildcards.matches(it, consumer.value) - } - } - - /** Ready-made visibility policies and the custom-policy builder entry point. */ - companion object { - /** Creates an access policy that allows only the publishing plugin. */ - @JvmStatic - fun ownerOnly(): ConfigTypeAccess = Builder().build() - - /** Creates an access policy that allows every pnLibrary plugin. */ - @JvmStatic - fun everyone(): ConfigTypeAccess = Builder().allowAll().build() - - /** Creates an owner-plus-explicit-plugins access policy. */ - @JvmStatic - fun plugins(vararg pluginIds: String): ConfigTypeAccess = - Builder().allow(*pluginIds).build() - - /** Creates a mutable access-policy builder. */ - @JvmStatic - fun builder(): Builder = Builder() - } - - /** Fluent builder for [ConfigTypeAccess]. */ - class Builder internal constructor() { - private var all = false - private val allowed = linkedSetOf() - private val patterns = linkedSetOf() - private val denied = linkedSetOf() - - /** Allows every pnLibrary plugin unless denied explicitly. */ - fun allowAll(): Builder = apply { all = true } - /** Allows the supplied normalized plugin identifiers. */ - fun allow(vararg pluginIds: String): Builder = apply { pluginIds.map(PluginId::of).forEach(allowed::add) } - /** Allows plugin identifiers matching any supplied case-insensitive glob. */ - fun allowMatching(vararg patterns: String): Builder = apply { - require(patterns.none(String::isBlank)) { "Config type access patterns must not be blank" } - patterns.map(String::trim).forEach(this.patterns::add) - } - /** Denies the supplied plugins, overriding all allow rules. */ - fun deny(vararg pluginIds: String): Builder = apply { pluginIds.map(PluginId::of).forEach(denied::add) } - /** Creates an immutable access policy. */ - fun build(): ConfigTypeAccess = ConfigTypeAccess( - all, - Collections.unmodifiableSet(LinkedHashSet(allowed)), - Collections.unmodifiableSet(LinkedHashSet(patterns)), - Collections.unmodifiableSet(LinkedHashSet(denied)), - ) - } -} - /** Handle for one plugin-owned polymorphic configuration type. */ interface ConfigTypeRegistration : AutoCloseable { /** Plugin that published this type. */ @@ -93,6 +13,8 @@ interface ConfigTypeRegistration : AutoCloseable { val implementation: Class<*> /** Normalized primary discriminator value. */ val name: String + /** Where the word works: a plugin, a module or one file. */ + val target: ConfigAddress /** Whether this registration is still visible to configuration codecs. */ val isActive: Boolean /** Deactivates and removes this registration. Closing is idempotent. */ @@ -102,8 +24,9 @@ interface ConfigTypeRegistration : AutoCloseable { /** * Fluent publication of one polymorphic configuration type, created by [ConfigScope.type]. * - * Only [name] is required. Without further calls the type is private to its owner, has priority - * zero and no aliases. Nothing is published until [register] is called. + * Only [name] is required. Without [into] the word works in the configurations of the module that registers it. + * With [into] it works where the address points, for example in another plugin's file, and it lives and dies + * with the registering module. Nothing is published until [register] is called. */ class ConfigTypeBuilder internal constructor( private val scope: ConfigScope, @@ -113,7 +36,8 @@ class ConfigTypeBuilder internal constructor( private var name: String? = null private val aliases = linkedSetOf() private var priority = 0 - private var access = ConfigTypeAccess.ownerOnly() + private var target: ConfigAddress? = null + private var conflict = ConfigTypeConflict.FAIL /** Sets the primary discriminator value. */ fun name(value: String): ConfigTypeBuilder = apply { name = value } @@ -124,16 +48,67 @@ class ConfigTypeBuilder internal constructor( /** Sets the priority; the higher value wins when several registrations accept one identifier. */ fun priority(value: Int): ConfigTypeBuilder = apply { priority = value } - /** Sets which plugins may use the type. */ - fun access(value: ConfigTypeAccess): ConfigTypeBuilder = apply { access = value } + /** Makes the word work at [address]: a plugin, a module or one file. */ + fun into(address: ConfigAddress): ConfigTypeBuilder = apply { target = address } + + /** Short form for the address written as text: `*`, `quests`, `quests/main` or `quests/main:quests.yml`. */ + fun into(address: String): ConfigTypeBuilder = into(ConfigAddress.parse(address)) + + /** Makes the word work in one registered file. */ + fun into(config: ManagedConfig<*>): ConfigTypeBuilder = + into(requireNotNull(config.id) { "This configuration has no identifier" }.address) + + /** Makes the word work in every file of the plugin [plugin]. */ + fun into(plugin: PluginId): ConfigTypeBuilder = into(ConfigAddress.plugin(plugin)) + + /** Makes the word work in every file of the module that owns [other], for example another plugin's scope. */ + fun into(other: ConfigScope): ConfigTypeBuilder = into(ConfigAddress.module(other.plugin, other.module)) + + /** Makes the word work in the file that [info] describes, for example one found in the catalog. */ + fun into(info: ConfigInfo): ConfigTypeBuilder = into(info.address) + + /** Makes the word work in every file of every plugin that accepts it. */ + fun everywhere(): ConfigTypeBuilder = into(ConfigAddress.everywhere()) - /** Sets the access policy through a Java-friendly callback. */ - fun access(configure: java.util.function.Consumer): ConfigTypeBuilder = - access(ConfigTypeAccess.builder().also(configure::accept).build()) + /** Chooses what happens when the word is already taken at the same place; see [ConfigTypeConflict]. */ + fun onConflict(policy: ConfigTypeConflict): ConfigTypeBuilder = apply { conflict = policy } + + /** Publishes the type at each of [addresses] and returns one handle per place; a refused place fails the whole call. */ + fun registerEach(addresses: Collection): List { + val done = ArrayList() + try { + addresses.forEach { done += into(it).register() } + } catch (error: RuntimeException) { + done.forEach(ConfigTypeRegistration::close) + throw error + } + return done + } /** Publishes the type and returns its handle. */ fun register(): ConfigTypeRegistration { val primary = requireNotNull(name) { "Config type name is required: call name(...) before register()" } - return scope.publishType(baseType, implementation, primary, LinkedHashSet(aliases), priority, access) + return scope.publishType(baseType, implementation, primary, LinkedHashSet(aliases), priority, target, conflict) } } + +/** + * What to do when a configuration word is already taken at the same place by another registration. + * + * ```kotlin + * scope.type().name("message-fancy").onConflict(ConfigTypeConflict.KEEP).register() + * ``` + */ +enum class ConfigTypeConflict { + /** Refuse with an error; the default, so that a clash is never silent. */ + FAIL, + + /** Keep the existing registration and publish nothing; the returned handle is inactive. */ + KEEP, + + /** + * Take the word over: registrations of the same plugin and ones with a lower priority are closed. + * A registration of another plugin with the same or a higher priority is never replaced, and the call fails. + */ + REPLACE, +} diff --git a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigurationService.kt b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigurationService.kt index 9b4b77e6a..f65895573 100644 --- a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigurationService.kt +++ b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ConfigurationService.kt @@ -1,16 +1,52 @@ package org.pnfolder.pnlibrary.api.config +import org.pnfolder.pnlibrary.api.plugin.ModuleId +import org.pnfolder.pnlibrary.api.plugin.PluginAccess +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.nio.file.Path import java.util.function.Supplier /** - * Creates lifecycle-bound typed configuration scopes. + * Creates lifecycle-bound typed configuration scopes and lets you look up every registered file. * * The same owner object resolves to the same scope. Owner identity is used rather than equality. - * Files are rooted in the owner's platform data directory and cannot escape it. + * A file is counted from the owner's data folder by default and cannot escape its [ConfigRoot]. + * Every registered file has an identifier `plugin/module:path`, for example `quests/main:quests.yml`. */ interface ConfigurationService { /** Returns the existing scope for [owner], or creates one atomically. */ fun scope(owner: Any): ConfigScope + + /** Every registered file of every plugin, in registration order. */ + fun all(): List + + /** The files inside [address]: a whole plugin, one module or one file. */ + fun find(address: ConfigAddress): List + + /** The files inside the address written as text: `quests`, `quests/main` or `quests/main:quests.yml`. */ + fun find(address: String): List = find(ConfigAddress.parse(address)) + + /** The file with identifier [id], or `null` when it is not registered. */ + fun get(id: ConfigId): ManagedConfig<*>? + + /** The file with the identifier written as text, or `null` when it is not registered. */ + fun get(id: String): ManagedConfig<*>? = get(ConfigId.parse(id)) + + /** The file with identifier [id], or an error naming the registered files. */ + fun require(id: ConfigId): ManagedConfig<*> = + get(id) ?: error("Configuration $id is not registered; registered: ${all().joinToString { it.id.toString() }}") + + /** The file with the identifier written as text, or an error naming the registered files. */ + fun require(id: String): ManagedConfig<*> = require(ConfigId.parse(id)) + + /** The registered files that read into [model]. */ + fun byModel(model: Class<*>): List = all().filter { it.modelType == model } + + /** Every word [baseType] understands: the ones its annotations declare and the ones plugins added. */ + fun types(baseType: Class<*>): List + + /** The serializers that plugins added, with where each one works. Built-in ones are not listed. */ + fun serializers(): List } /** @@ -40,6 +76,14 @@ interface ConfigScope : AutoCloseable { fun yaml(path: String, type: Class, defaults: Supplier, options: ConfigOptions): ManagedConfig = yaml(path, type, defaults, options, ConfigValueValidator { emptyList() }) + /** + * Registers a file at any place on the machine, for example a path the plugin read from its own settings. + * The file is the plugin's own: it is created when missing and rewritten like one in the data folder. + * Its identifier is `plugin/module:@external/`. + */ + fun yamlAt(file: Path, type: Class, defaults: Supplier, options: ConfigOptions = ConfigOptions.DEFAULT): ManagedConfig = + yaml(file.toAbsolutePath().normalize().toString(), type, defaults, options.copy(root = ConfigRoot.EXTERNAL)) + /** * Registers a typed YAML file with an additional programmatic [validator]. * @@ -57,18 +101,51 @@ interface ConfigScope : AutoCloseable { /** * Registers or replaces the scope-local serializer for [type]. * - * Register serializers before creating affected YAML handles because each handle snapshots - * the available serializers at creation time. + * It works in the files of this module only; use [serializerFor] to work in other files. + * A file is read with the serializers it has at the time of the read. */ fun serializer(type: Class, serializer: ConfigSerializer): ConfigScope + /** + * Starts publishing [serializer] for [type], to work in this module or, with `into`, in other files. + * + * ```kotlin + * // Every file of the plugin `shop` writes a Point as one line + * scope.serializerFor(Point::class.java, PointSerializer()).into("shop").register() + * + * // Every file of every plugin + * scope.serializerFor(Point::class.java, PointSerializer()).everywhere().register() + * ``` + * + * The file's own module keeps its serializers: an addition only fills what the module has none for. + * A module can refuse additions with [extensions]. Files that are already read keep their value until read again. + * Nothing is published until [ConfigSerializerBuilder.register] is called. + */ + fun serializerFor(type: Class, serializer: ConfigSerializer): ConfigSerializerBuilder = + ConfigSerializerBuilder(this, type, serializer) + + /** + * Low-level publication behind [serializerFor]; prefer the builder. + * + * [target] `null` means the files of this scope's module. For files of other modules the type must not be a + * primitive or come from `java.`, `javax.`, `kotlin.` or `jdk.`, so that nobody rewrites how ordinary values are read. + */ + fun publishSerializer( + type: Class, + serializer: ConfigSerializer, + priority: Int, + target: ConfigAddress?, + ): ConfigSerializerRegistration + /** * Starts publishing one implementation of a polymorphic configuration [baseType]. * * ```kotlin - * scope.type(Action::class.java, MessageAction::class.java) - * .name("message").alias("msg").priority(10).access(ConfigTypeAccess.everyone()) - * .register() + * // Only my own files understand `type: message` + * scope.type(Action::class.java, MessageAction::class.java).name("message").alias("msg").register() + * + * // Teach another plugin's file the word: `type: message` works in quests/main:quests.yml + * scope.type(Action::class.java, MessageAction::class.java).name("message").into("quests/main:quests.yml").register() * ``` * * Nothing is published until [ConfigTypeBuilder.register] is called. @@ -80,8 +157,10 @@ interface ConfigScope : AutoCloseable { * Low-level publication behind [type]; prefer the builder. * * [name] and [aliases] are case-insensitive identifiers used in the discriminator field. - * Higher [priority] wins when multiple visible registrations accept the same identifier, and - * [access] controls which plugins may consume the type. + * Higher [priority] wins when multiple visible registrations accept the same identifier. + * [target] says where the word works; `null` means the files of this scope's module. The word cannot + * take a name that the base type declares itself or that the target plugin has published. + * A module can refuse additions with [extensions]. */ fun publishType( baseType: Class, @@ -89,9 +168,32 @@ interface ConfigScope : AutoCloseable { name: String, aliases: Set, priority: Int, - access: ConfigTypeAccess, + target: ConfigAddress?, + conflict: ConfigTypeConflict = ConfigTypeConflict.FAIL, ): ConfigTypeRegistration + /** Plugin that owns this scope. */ + val plugin: PluginId + + /** Module that owns this scope. */ + val module: ModuleId + + /** The files registered in this scope, in registration order. */ + fun list(): List + + /** The file registered under [path] (relative to the plugin folder, or starting with `@plugins/` or `@server/`), or `null`. */ + fun get(path: String): ManagedConfig<*>? + + /** The file registered under [path], or an error naming the registered files. */ + fun require(path: String): ManagedConfig<*> = + get(path) ?: error("Configuration $path is not registered in $plugin/$module; registered: ${list().joinToString { it.id.path }}") + + /** + * Sets which plugins may add polymorphic types to the files of this module. Everybody may by default. + * The module's own plugin is always allowed. + */ + fun extensions(policy: PluginAccess): ConfigScope + /** Loads every registered file in registration order. */ fun loadAll() @@ -150,6 +252,16 @@ inline fun ConfigScope.yaml( noinline defaults: () -> T, ): ManagedConfig = yaml(path, T::class.java, Supplier(defaults), options, validator) +/** + * Sets which plugins may add polymorphic types to the files of this module. + * + * ```kotlin + * module.configs.extensions { allow("questitems"); deny("pnspy") } + * ``` + */ +fun ConfigScope.extensions(block: PluginAccess.Builder.() -> Unit): ConfigScope = + extensions(PluginAccess.builder().owner().apply(block).build()) + /** * Starts publishing implementation [I] of polymorphic base type [B] while inferring both classes. * @@ -169,3 +281,20 @@ inline fun ConfigScope.type(): ConfigTypeBuilde */ inline fun ConfigScope.serializer(serializer: ConfigSerializer): ConfigScope = serializer(T::class.java, serializer) + +/** + * Starts publishing [serializer] for its inferred value type. + * + * ```kotlin + * scope.serializerFor(PointSerializer()).into("shop/main").register() + * ``` + */ +inline fun ConfigScope.serializerFor(serializer: ConfigSerializer): ConfigSerializerBuilder = + serializerFor(T::class.java, serializer) + +/** Kotlin form of [ConfigScope.yamlAt]: `scope.yamlAt(path) { Settings() }`. */ +inline fun ConfigScope.yamlAt( + file: Path, + options: ConfigOptions = ConfigOptions.DEFAULT, + noinline defaults: () -> T, +): ManagedConfig = yamlAt(file, T::class.java, Supplier(defaults), options) diff --git a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ManagedConfig.kt b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ManagedConfig.kt index a4e44064c..3cb9b887e 100644 --- a/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ManagedConfig.kt +++ b/modules/features/config-api/src/main/kotlin/org/pnfolder/pnlibrary/api/config/ManagedConfig.kt @@ -1,5 +1,6 @@ package org.pnfolder.pnlibrary.api.config +import java.util.function.Consumer import java.util.function.UnaryOperator /** Converts between a typed code-first model [T] and YAML text. */ @@ -53,6 +54,40 @@ class ConfigValidationException( * [unload] only clears memory and never deletes or rewrites the YAML file. */ interface ManagedConfig : AutoCloseable { + /** Identifier `plugin/module:path`, or `null` for a library-internal file that no plugin registered. */ + val id: ConfigId? get() = null + + /** Read-only description of this file without any values from it, or `null` when [id] is `null`. */ + val info: ConfigInfo? get() = null + + /** + * The settings of this file that an administrator may change in game (fields marked [ConfigEditable]), + * with their current values. Empty for a file registered outside a configuration scope. + */ + val settings: List get() = emptyList() + + /** + * Changes one setting by its dotted [path] from the typed [text], validates the whole file and writes it. + * When the new value is refused, the file and the value in memory stay as they were. + * + * @throws ConfigEditException when the path is unknown, the text does not fit, or validation fails + */ + fun edit(path: String, text: String): ConfigEditResult = + throw UnsupportedOperationException("Settings of this configuration cannot be edited") + + /** + * Calls [listeners] after the file is read or written, or one of its settings is edited. A failing listener is + * logged and does not stop the others. Closing the result removes them. + */ + fun onChanged(vararg listeners: Consumer): AutoCloseable = AutoCloseable { } + + /** + * Calls [listeners] when a setting that does not work at once ([ConfigApply.RELOAD], [ConfigApply.RESTART]) was + * changed, so the plugin can apply it (usually by re-reading what it caches) or tell the administrator to restart. + * Closing the result removes them. + */ + fun onReloadRequired(vararg listeners: Consumer): AutoCloseable = AutoCloseable { } + /** Whether a configuration value is currently loaded in memory. */ val isLoaded: Boolean diff --git a/modules/features/config-api/src/test/kotlin/org/pnfolder/pnlibrary/api/config/ConfigApiConsistencyTest.kt b/modules/features/config-api/src/test/kotlin/org/pnfolder/pnlibrary/api/config/ConfigApiConsistencyTest.kt index 0ee5a4adc..23ec12bc8 100644 --- a/modules/features/config-api/src/test/kotlin/org/pnfolder/pnlibrary/api/config/ConfigApiConsistencyTest.kt +++ b/modules/features/config-api/src/test/kotlin/org/pnfolder/pnlibrary/api/config/ConfigApiConsistencyTest.kt @@ -1,8 +1,10 @@ package org.pnfolder.pnlibrary.api.config +import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId class ConfigApiConsistencyTest { @@ -27,16 +29,79 @@ class ConfigApiConsistencyTest { } @Test - fun `access policy exposes immutable snapshots and rejects blank patterns`() { - val access = ConfigTypeAccess.builder().allow("shop").allowMatching("clan-*").build() + fun `extension policy exposes immutable snapshots and denials beat allows`() { + val policy = PluginAccess.builder().owner().allow("shop", "clans").deny("clans").build() - assertTrue(access.allows(PluginId.of("owner"), PluginId.of("shop"))) + assertTrue(policy.allows(PluginId.of("owner"), PluginId.of("shop"))) + assertTrue(!policy.allows(PluginId.of("owner"), PluginId.of("clans"))) + assertTrue(policy.allows(PluginId.of("owner"), PluginId.of("owner")), "the host is always allowed") + assertTrue(!policy.allows(PluginId.of("owner"), PluginId.of("stranger"))) assertThrows(UnsupportedOperationException::class.java) { @Suppress("UNCHECKED_CAST") - (access.allowedPlugins as MutableSet).add(PluginId.of("other")) - } - assertThrows(IllegalArgumentException::class.java) { - ConfigTypeAccess.builder().allowMatching(" ") + (policy.allowedPlugins as MutableSet).add(PluginId.of("other")) } } + + @Test + fun `ready-made policies behave as named`() { + val host = PluginId.of("host") + val guest = PluginId.of("guest") + assertTrue(PluginAccess.shared().allows(host, guest)) + assertTrue(!PluginAccess.ownerOnly().allows(host, guest)) + assertTrue(PluginAccess.ownerOnly().allows(host, host)) + assertTrue(PluginAccess.only("guest").allows(host, guest)) + } + + @Test + fun `identifier parts can be read and written back`() { + val id = ConfigId.parse("Quests/Main:rewards/daily.yml") + + assertEquals("quests", id.plugin.value) + assertEquals("main", id.module.value) + assertEquals(ConfigRoot.PLUGIN, id.root) + assertEquals("rewards/daily.yml", id.path) + assertEquals("daily.yml", id.fileName) + assertEquals("rewards", id.directory) + assertEquals("quests/main", id.moduleAddress.toString()) + assertEquals("quests/main:rewards/daily.yml", id.toString()) + assertEquals(id, ConfigId.of("quests", "main", "rewards\\daily.yml")) + } + + @Test + fun `identifier keeps a foreign root in the text`() { + val id = ConfigId.parse("quests/main:@plugins/Essentials/config.yml") + + assertEquals(ConfigRoot.PLUGINS, id.root) + assertEquals("Essentials/config.yml", id.path) + assertEquals("quests/main:@plugins/Essentials/config.yml", id.toString()) + assertEquals(ConfigRoot.SERVER, ConfigId.parse("quests/main:@server/bukkit.yml").root) + } + + @Test + fun `address levels cover more or fewer files`() { + val file = ConfigId.parse("quests/main:quests.yml") + val other = ConfigId.parse("quests/extra:other.yml") + + val plugin = ConfigAddress.parse("quests") + val module = ConfigAddress.parse("quests/main") + val single = ConfigAddress.parse("quests/main:quests.yml") + assertEquals(ConfigAddress.Level.PLUGIN, plugin.level) + assertEquals(ConfigAddress.Level.MODULE, module.level) + assertEquals(ConfigAddress.Level.FILE, single.level) + assertTrue(plugin.matches(file) && plugin.matches(other)) + assertTrue(module.matches(file) && !module.matches(other)) + assertTrue(single.matches(file) && !single.matches(other)) + assertTrue(plugin.overlaps(single) && single.overlaps(plugin)) + assertTrue(!module.overlaps(ConfigAddress.parse("quests/extra"))) + assertTrue(!ConfigAddress.parse("other").overlaps(plugin)) + } + + @Test + fun `malformed identifiers are rejected with a clear message`() { + assertThrows(IllegalArgumentException::class.java) { ConfigId.parse("quests") } + assertThrows(IllegalArgumentException::class.java) { ConfigId.parse("quests/main") } + assertThrows(IllegalArgumentException::class.java) { ConfigAddress.parse("quests:file.yml") } + assertThrows(IllegalArgumentException::class.java) { ConfigAddress.parse("a/b/c") } + assertThrows(IllegalArgumentException::class.java) { ConfigAddress.parse(" ") } + } } diff --git a/modules/features/config-runtime/build.gradle.kts b/modules/features/config-runtime/build.gradle.kts index 8f0e1e173..f9d9c88e7 100644 --- a/modules/features/config-runtime/build.gradle.kts +++ b/modules/features/config-runtime/build.gradle.kts @@ -8,7 +8,7 @@ base { archivesName = "${rootProject.property("pnlibrary.name")}-config" } dependencies { api(project(":modules:features:config-api")) - api(project(":modules:runtime-spi")) + api(project(":modules:spi")) implementation(project(":modules:common")) implementation(libs.kotlin.stdlib) implementation(libs.snakeyaml) @@ -19,7 +19,8 @@ dependencies { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-config", project.version.toString()) pom { name.set("pnLibrary Config") diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigPaths.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigPaths.kt new file mode 100644 index 000000000..c269aa211 --- /dev/null +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigPaths.kt @@ -0,0 +1,66 @@ +package org.pnfolder.pnlibrary.config + +import org.pnfolder.pnlibrary.api.config.ConfigOptions +import org.pnfolder.pnlibrary.api.config.ConfigRoot +import org.pnfolder.pnlibrary.api.config.MissingFilePolicy +import org.pnfolder.pnlibrary.api.config.UnknownValuePolicy +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.nio.file.Files +import java.nio.file.Path + +/** + * Where the configuration files of one plugin may live, and what a path may be. + * + * Every path a plugin gives is checked here: it must stay inside its root folder, must not leave it through a link, and + * must name a YAML file. Kept apart from the service so the rules that keep a plugin out of other folders can be read + * and tested on their own. + * + * @property directory the data folder of the plugin + * @property plugin the plugin the files belong to, for messages + */ +internal class ConfigPaths(private val directory: Path, private val plugin: PluginId) { + /** The folder paths of [root] are counted from. */ + fun rootDirectory(root: ConfigRoot): Path = when (root) { + ConfigRoot.PLUGIN -> directory + ConfigRoot.PLUGINS -> directory.parent + ConfigRoot.SERVER -> directory.parent?.parent + ConfigRoot.EXTERNAL -> error("An external path is absolute and has no root folder") + } ?: error("The ${root.name.lowercase()} folder is not known for $plugin") + + /** Someone else's files get strict handling whatever the options ask: never created, always backed up, unknown keys kept. */ + fun effective(options: ConfigOptions): ConfigOptions = + if (options.root == ConfigRoot.PLUGIN || options.root == ConfigRoot.EXTERNAL) options else options.copy( + missingFile = MissingFilePolicy.FAIL, + backups = true, + unknownValues = if (options.unknownValues == UnknownValuePolicy.REMOVE) UnknownValuePolicy.PRESERVE else options.unknownValues, + ) + + /** An absolute path chosen by the plugin itself; only the file extension is checked. */ + fun external(path: String, relative: Path): Path { + require(relative.isAbsolute) { "An external configuration path must be absolute: $path" } + requireYaml(path) + return relative + } + + /** The absolute file for [path] under the folder of [root]; rejects paths outside it, links out of it and other file extensions. */ + fun checked(path: String, relative: Path, root: ConfigRoot): Path { + val base = rootDirectory(root) + val label = if (root == ConfigRoot.PLUGIN) "plugin directory" else "${root.name.lowercase()} folder" + require(!relative.isAbsolute && !relative.startsWith("..")) { + "Configuration path must stay inside the $label" + } + requireYaml(path) + val target = base.resolve(relative).normalize() + require(target.startsWith(base)) { "Configuration path escapes the $label" } + if (Files.exists(target) && Files.exists(base)) { + require(target.toRealPath().startsWith(base.toRealPath())) { "Configuration path leaves the $label through a link" } + } + return target + } + + private fun requireYaml(path: String) { + require(path.endsWith(".yml", true) || path.endsWith(".yaml", true)) { + "Configuration file must use .yml or .yaml" + } + } +} diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigRunAll.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigRunAll.kt new file mode 100644 index 000000000..988c27073 --- /dev/null +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigRunAll.kt @@ -0,0 +1,20 @@ +package org.pnfolder.pnlibrary.config + +import org.pnfolder.pnlibrary.common.lang.Failures + +internal fun runAll(vararg steps: () -> Unit) = runAll(steps.toList()) + +/** Runs every step even when earlier ones fail; the first failure is rethrown with later ones suppressed into it. */ +internal fun runAll(steps: List<() -> Unit>) { + var failure: Throwable? = null + steps.forEach { step -> + try { + step() + } catch (error: Throwable) { + Failures.rethrowIfFatal(error) + val first = failure + if (first == null) failure = error else if (error !== first) first.addSuppressed(error) + } + } + failure?.let { throw it } +} diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigurationRuntime.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigurationRuntime.kt index f83e23b41..04482c73c 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigurationRuntime.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigurationRuntime.kt @@ -2,11 +2,20 @@ package org.pnfolder.pnlibrary.config import org.pnfolder.pnlibrary.api.config.ConfigScope import org.pnfolder.pnlibrary.api.config.ConfigurationService +import org.pnfolder.pnlibrary.api.plugin.ModuleId import org.pnfolder.pnlibrary.api.plugin.PluginId /** Runtime integration contract for creating and releasing module-owned configuration scopes. */ interface ConfigurationRuntime : ConfigurationService, AutoCloseable { + /** Returns the scope of [owner] registered under [pluginId] as module `main`, creating it on first use. */ fun scope(owner: Any, pluginId: PluginId): ConfigScope + /** + * Returns the scope of [owner] kept under [key] for [module] of [plugin], creating it on first use. + * The scope's files are listed as `plugin/module:path`. + */ + fun scope(owner: Any, key: PluginId, plugin: PluginId, module: ModuleId): ConfigScope + + /** Closes every scope created for [owner]; call it when the owner is disabled. */ fun close(owner: Any) } diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigurationServiceImpl.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigurationServiceImpl.kt index 3f25ad73f..ad1492dc4 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigurationServiceImpl.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ConfigurationServiceImpl.kt @@ -1,17 +1,28 @@ package org.pnfolder.pnlibrary.config +import org.pnfolder.pnlibrary.api.config.ConfigAddress +import org.pnfolder.pnlibrary.api.config.ConfigId +import org.pnfolder.pnlibrary.api.config.ConfigInfo import org.pnfolder.pnlibrary.api.config.ConfigOptions +import org.pnfolder.pnlibrary.api.config.ConfigRoot import org.pnfolder.pnlibrary.api.config.ConfigScope import org.pnfolder.pnlibrary.api.config.ConfigSerializer -import org.pnfolder.pnlibrary.api.config.ConfigTypeAccess +import org.pnfolder.pnlibrary.api.config.ConfigSerializerInfo +import org.pnfolder.pnlibrary.api.config.ConfigSerializerRegistration +import org.pnfolder.pnlibrary.api.config.ConfigTypeConflict +import org.pnfolder.pnlibrary.api.config.ConfigTypeInfo import org.pnfolder.pnlibrary.api.config.ConfigTypeRegistration +import org.pnfolder.pnlibrary.api.config.ConfigTypes import org.pnfolder.pnlibrary.api.config.ConfigValueValidator import org.pnfolder.pnlibrary.api.config.ManagedConfig import org.pnfolder.pnlibrary.api.logging.PnLogger +import org.pnfolder.pnlibrary.api.plugin.ModuleId +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId -import org.pnfolder.pnlibrary.common.lang.Failures import org.pnfolder.pnlibrary.config.yaml.AnnotatedYamlCodec import org.pnfolder.pnlibrary.config.yaml.CodeFirstYaml +import org.pnfolder.pnlibrary.config.yaml.ConfigObjectIntrospector +import org.pnfolder.pnlibrary.config.yaml.ConfigSettingsEditor import org.pnfolder.pnlibrary.config.yaml.RuntimeConfigType import org.pnfolder.pnlibrary.spi.platform.PlatformLogging import org.pnfolder.pnlibrary.spi.platform.PlatformOwnership @@ -23,13 +34,20 @@ import java.util.Locale import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Supplier -/** Hands out one configuration scope per plugin, rooted at its data folder, and closes them with their owner. */ +/** + * Hands out one configuration scope per module, rooted at the plugin's data folder, and closes them with their owner. + * + * Every registered file is listed under its [ConfigId], so files can be found by plugin, module or identifier. + * A polymorphic type published with an address works in the files that address covers. + */ class ConfigurationServiceImpl( private val platform: PlatformOwnership, private val logging: PlatformLogging = object : PlatformLogging {}, ) : ConfigurationRuntime { private val scopes = IdentityHashMap>() private val runtimeTypes = linkedSetOf() + private val runtimeSerializers = linkedSetOf() + private val files = linkedMapOf>() private val closed = AtomicBoolean(false) /** @@ -45,19 +63,28 @@ class ConfigurationServiceImpl( return scope(owner, pluginId) } - /** Returns the scope of [owner] and [pluginId], creating it on first use. Fails after [close]. */ - override fun scope(owner: Any, pluginId: PluginId): ConfigScope = synchronized(scopes) { + /** Returns the scope of [owner] and [pluginId] as module `main`, creating it on first use. Fails after [close]. */ + override fun scope(owner: Any, pluginId: PluginId): ConfigScope = scope(owner, pluginId, pluginId, MAIN_MODULE) + + /** + * Returns the scope of [owner] kept under [key] for module [module] of plugin [plugin], creating it on first use. + * Fails after [close]. + */ + override fun scope(owner: Any, key: PluginId, plugin: PluginId, module: ModuleId): ConfigScope = synchronized(scopes) { check(!closed.get()) { "Configuration service is closed" } - scopes.getOrPut(owner) { linkedMapOf() }.getOrPut(pluginId) { + scopes.getOrPut(owner) { linkedMapOf() }.getOrPut(key) { Scope( owner = owner, - pluginId = pluginId, + key = key, + plugin = plugin, + module = module, directory = ownerDirectory(owner).toAbsolutePath().normalize(), - logger = PlatformPnLogger(logging, owner, pluginId.value), + logger = PlatformPnLogger(logging, owner, key.value), ) } } + /** Closes the scopes created for [owner] and forgets them. */ override fun close(owner: Any) { synchronized(scopes) { scopes.remove(owner)?.values?.toList().orEmpty() }.forEach { it.close() } } @@ -70,20 +97,86 @@ class ConfigurationServiceImpl( }.forEach { it.close() } } + // ── Catalog ─────────────────────────────────────────────────────────────────────────────── + + override fun all(): List = registered().map { it.info } + + override fun find(address: ConfigAddress): List = + registered().filter { address.matches(it.id) }.map { it.info } + + override fun get(id: ConfigId): ManagedConfig<*>? = synchronized(files) { files[id] } + + override fun types(baseType: Class<*>): List { + val declared = baseType.getAnnotation(ConfigTypes::class.java)?.value.orEmpty().map { type -> + ConfigTypeInfo(baseType, type.type.java, type.name, type.aliases.toSet(), null, type.priority, null) + } + val added = synchronized(runtimeTypes) { + runtimeTypes.filter { it.isActive && it.baseType == baseType }.map { + ConfigTypeInfo(baseType, it.implementation, it.name, it.aliases, it.owner, it.priority, it.target) + } + } + return declared + added + } + + override fun serializers(): List = synchronized(runtimeSerializers) { + runtimeSerializers.filter { it.isActive }.map { ConfigSerializerInfo(it.type, it.owner, it.priority, it.target) } + } + + /** The additions that file [consumer] uses: those whose address covers it, its module accepts, and that win by priority. */ + private fun visibleSerializers(consumer: ConfigId, policy: PluginAccess): List = + synchronized(runtimeSerializers) { + runtimeSerializers.filter { + it.isActive && it.target.matches(consumer) && policy.allows(consumer.plugin, it.owner) + }.sortedByDescending { it.priority } + } + + private fun registered(): List> = synchronized(files) { files.values.toList() } + // Platforms without per-plugin folders (Velocity) get the conventional plugins/ directory. private fun ownerDirectory(owner: Any): Path = platform.ownerDataFolder(owner) ?: Paths.get("plugins", platform.ownerDetails(owner)["id"] ?: owner.javaClass.simpleName) + /** The words visible in file [consumer]: those whose address covers it and whose plugin its module accepts. */ + private fun visibleTypes(consumer: ConfigId, policy: PluginAccess): List = + synchronized(runtimeTypes) { + val covering = runtimeTypes.filter { + it.isActive && it.target.matches(consumer) && policy.allows(consumer.plugin, it.owner) + } + // The plugin that owns the file keeps its own words: an addition made for everybody cannot shadow them. + covering.filter { added -> + added.owner == consumer.plugin || covering.none { own -> + own.owner == consumer.plugin && own.baseType == added.baseType && own.words().any { it in added.words() } + } + }.map { + RuntimeConfigType(it.owner.value, it.baseType, it.implementation, it.name, it.aliases, it.priority) + } + } + + /** A new word may unblock files that failed or skipped elements for want of it: read those again. */ + private fun reloadWaiting(where: ConfigAddress) { + val waiting = synchronized(files) { files.values.filter { it.waitingForTypes && where.matches(it.id) } } + // CodeFirstYaml has already logged why a read failed; a file that still fails keeps waiting. + waiting.forEach { handle -> runCatching { handle.reload() } } + } + + /** One module's view of the service: its files, serializers and published types, all released on [close]. */ private inner class Scope( private val owner: Any, - private val pluginId: PluginId, + private val key: PluginId, + override val plugin: PluginId, + override val module: ModuleId, private val directory: Path, private val logger: PnLogger, ) : ConfigScope { - private val handles = linkedSetOf>() + private val paths = ConfigPaths(directory, plugin) + private val handles = linkedSetOf>() private val announcements = mutableListOf() private val serializers = BuiltInConfigSerializers.create() private val scopeClosed = AtomicBoolean(false) + + @Volatile + var extensionPolicy: PluginAccess = PluginAccess.shared() + private set override val size: Int get() = synchronized(handles) { handles.size } override fun yaml(path: String, type: Class, defaults: Supplier): ManagedConfig = @@ -98,22 +191,18 @@ class ConfigurationServiceImpl( ): ManagedConfig { check(!scopeClosed.get()) { "Configuration scope is closed" } val relative = Paths.get(path).normalize() - require(!relative.isAbsolute && !relative.startsWith("..")) { - "Configuration path must stay inside the plugin directory" - } - require(path.endsWith(".yml", true) || path.endsWith(".yaml", true)) { - "Configuration file must use .yml or .yaml" - } - val target = directory.resolve(relative).normalize() - require(target.startsWith(directory)) { "Configuration path escapes the plugin directory" } + val external = options.root == ConfigRoot.EXTERNAL + val target = if (external) paths.external(path, relative) else paths.checked(path, relative, options.root) + val effective = paths.effective(options) + val id = ConfigId(plugin, module, options.root, relative.toString().replace('\\', '/')) val defaultValue = defaults.get() ?: error("Configuration defaults cannot be null") val codec = AnnotatedYamlCodec( type = type, defaults = defaults, - serializers = synchronized(serializers) { serializers.toMap() }, - runtimeTypes = { visibleTypes(pluginId) }, - consumer = pluginId.value, - options = options, + serializers = { serializersFor(id) }, + runtimeTypes = { visibleTypes(id, extensionPolicy) }, + consumer = plugin.value, + options = effective, warning = { message -> logger.warning(message) }, ) val handle = CodeFirstYaml( @@ -122,20 +211,43 @@ class ConfigurationServiceImpl( codec = codec, logger = logger, validator = ConfigValueValidator { value -> codec.validate(value) + validator.validate(value) }, - options = options, + options = effective, ) - val owned = OwnedConfig(target, handle) - synchronized(handles) { - check(!scopeClosed.get()) { "Configuration scope is closed" } - check(handles.none { (it as? OwnedConfig<*>)?.file == target }) { - "Configuration $path is already registered" - } - handles += owned + val editor = ConfigSettingsEditor(ConfigObjectIntrospector(effective.naming), type) + val owned = OwnedConfig(id, target, type, effective.readOnly, handle, editor, logger) + register(owned) + // Files of other plugins can hold secrets that the diagnostic report must not see, so only the plugin's own are announced. + if (options.root == ConfigRoot.PLUGIN) { + announce(ManagedConfigFile(key, directory, id.path, codec.secretPaths, codec.databases)) + } else if (external) { + // The plugin's own file at a place of its choice: it is still the plugin's secrets, so they are hidden in reports too. + announce(ManagedConfigFile(key, target.parent, target.fileName.toString(), codec.secretPaths, codec.databases)) } - announce(ManagedConfigFile(pluginId, directory, relative.toString().replace('\\', '/'), codec.secretPaths)) return owned } + /** Adds [owned] to the library-wide list and to this scope; a second writer of one file is refused. */ + private fun register(owned: OwnedConfig<*>) { + synchronized(files) { + check(owned.id !in files) { "Configuration ${owned.id} is already registered" } + if (!owned.readOnly) { + files.values.firstOrNull { !it.readOnly && it.file == owned.file }?.let { + error("File ${owned.file} is already managed by ${it.id}; register it read-only to only read it") + } + } + files[owned.id] = owned + } + try { + synchronized(handles) { + check(!scopeClosed.get()) { "Configuration scope is closed" } + handles += owned + } + } catch (error: Throwable) { + synchronized(files) { files.remove(owned.id) } + throw error + } + } + // Announcing feeds diagnostics only, so a failing listener is logged and the file still works. private fun announce(file: ManagedConfigFile) { val announced = try { @@ -153,32 +265,117 @@ class ConfigurationServiceImpl( synchronized(serializers) { serializers[type] = serializer } } + /** What file [id] reads with: the module's own serializers first, then the additions that cover it. */ + private fun serializersFor(id: ConfigId): Map, ConfigSerializer<*>> { + val merged = synchronized(serializers) { LinkedHashMap(serializers) } + visibleSerializers(id, extensionPolicy).forEach { merged.putIfAbsent(it.type, it.serializer) } + return merged + } + + override fun publishSerializer( + type: Class, serializer: ConfigSerializer, priority: Int, target: ConfigAddress?, + ): ConfigSerializerRegistration { + check(!scopeClosed.get()) { "Configuration scope is closed" } + val where = target ?: ConfigAddress.module(plugin, module) + val foreign = where.isAll || where.plugin != plugin + require(!foreign || (!type.isPrimitive && FORBIDDEN_PACKAGES.none { type.name.startsWith(it) })) { + "A serializer for ${type.name} cannot be added to other plugins' files: it would change how ordinary values are read" + } + if (!where.isAll) checkAccepted(where) + val registration = SerializerRegistration(key, plugin, type, serializer, priority, where) + synchronized(runtimeSerializers) { + check(!scopeClosed.get()) { "Configuration scope is closed" } + runtimeSerializers.firstOrNull { + it.isActive && it.owner == plugin && it.type == type && it.target.overlaps(where) + }?.let { + error("Plugin $plugin already published a serializer for ${type.name} that works at ${it.target}") + } + runtimeSerializers += registration + } + return registration + } + + override fun extensions(policy: PluginAccess): ConfigScope = apply { + check(!scopeClosed.get()) { "Configuration scope is closed" } + extensionPolicy = policy + } + + override fun list(): List = snapshot().map { it.info } + + override fun get(path: String): ManagedConfig<*>? { + val root = ConfigRoot.entries.filter { it != ConfigRoot.PLUGIN }.firstOrNull { path.startsWith(it.prefix) } ?: ConfigRoot.PLUGIN + val relative = path.removePrefix(root.prefix).replace('\\', '/') + return runCatching { Paths.get(relative).normalize().toString().replace('\\', '/') }.getOrNull() + ?.let { synchronized(files) { files[ConfigId(plugin, module, root, it)] } } + } + override fun publishType( baseType: Class, implementation: Class, name: String, - aliases: Set, priority: Int, access: ConfigTypeAccess, + aliases: Set, priority: Int, target: ConfigAddress?, + conflict: ConfigTypeConflict, ): ConfigTypeRegistration { check(!scopeClosed.get()) { "Configuration scope is closed" } + val where = target ?: ConfigAddress.module(plugin, module) val normalizedName = normalizeTypeName(name) val normalizedAliases = aliases.map(::normalizeTypeName).toSet() require(normalizedName !in normalizedAliases) { "Configuration type aliases must not repeat '$normalizedName'" } require(baseType.isAssignableFrom(implementation)) { "${implementation.name} does not implement ${baseType.name}" } + val words = normalizedAliases + normalizedName + // The base type's own words are not for sale: an addition must not change what an existing file means. + baseType.getAnnotation(ConfigTypes::class.java)?.value?.forEach { declared -> + val taken = (declared.aliases.toList() + declared.name).map { it.lowercase(Locale.ROOT) } + require(taken.none { it in words }) { + "Configuration type word '${taken.first { it in words }}' is declared by ${baseType.simpleName} itself and cannot be taken" + } + } + if (!where.isAll) checkAccepted(where) val registration = TypeRegistration( - pluginId, baseType, implementation, normalizedName, - normalizedAliases, priority, access, + key, plugin, baseType, implementation, normalizedName, + normalizedAliases, priority, where, ) synchronized(runtimeTypes) { check(!scopeClosed.get()) { "Configuration scope is closed" } - require(runtimeTypes.none { - it.isActive && it.owner == pluginId && it.baseType == baseType && - (it.name == normalizedName || normalizedName in it.aliases || it.name in normalizedAliases) - }) { "Plugin $pluginId already published configuration type '$normalizedName' for ${baseType.name}" } + val clashing = runtimeTypes.filter { + it.isActive && it.baseType == baseType && it.target.overlaps(where) && it.words().any { word -> word in words } + } + if (clashing.isNotEmpty() && conflict == ConfigTypeConflict.KEEP) { + registration.deactivate() + return registration + } + clashing.forEach { other -> + val replaceable = conflict == ConfigTypeConflict.REPLACE && (other.owner == plugin || other.priority < priority) + require(replaceable || other.owner != plugin) { + "Plugin $plugin already published configuration type '$normalizedName' for ${baseType.name}" + } + // The plugin that owns the file keeps its own words; an addition can only add new ones. + require(where.isAll || other.owner != where.plugin || replaceable) { + "Configuration type word '${other.words().first { word -> word in words }}' of ${baseType.simpleName} belongs to plugin ${where.plugin}" + } + } + // Another plugin's word with the same or a higher priority stays; priority decides which one wins. + if (conflict == ConfigTypeConflict.REPLACE) { + clashing.filter { it.owner == plugin || it.priority < priority }.forEach { it.close() } + } runtimeTypes += registration } + reloadWaiting(where) return registration } + /** Refuses the addition when a module it would reach has closed itself to the registering plugin. */ + private fun checkAccepted(where: ConfigAddress) { + val reached = synchronized(scopes) { scopes.values.flatMap { it.values } }.filter { + it.plugin == where.plugin && (where.module == null || where.module == it.module) + } + reached.forEach { + check(it.extensionPolicy.allows(it.plugin, plugin)) { + "Module ${it.plugin}/${it.module} does not accept configuration types from plugin $plugin" + } + } + } + private fun normalizeTypeName(value: String): String = value.trim().lowercase(Locale.ROOT).also { require(it.matches(Regex("[a-z0-9][a-z0-9_.-]{0,63}"))) { "Configuration type name '$value' must contain only letters, digits, dots, underscores, or hyphens" @@ -187,25 +384,33 @@ class ConfigurationServiceImpl( override fun loadAll() = forEach(snapshot()) { it.load() } override fun reloadAll() = forEach(snapshot()) { it.reload() } - override fun saveAll() = forEach(snapshot().filter { it.isLoaded }) { it.save() } + override fun saveAll() = forEach(snapshot().filter { it.isLoaded && !it.readOnly }) { it.save() } override fun close() { if (!scopeClosed.compareAndSet(false, true)) return val owned = synchronized(handles) { handles.toList().also { handles.clear() } } runAll( { runAll(owned.map { handle -> { handle.close() } }) }, + { synchronized(files) { owned.forEach { files.remove(it.id, it) } } }, { runAll(synchronized(handles) { announcements.toList().also { announcements.clear() } }.map { it -> { it.close() } }) }, { synchronized(runtimeTypes) { - val published = runtimeTypes.filter { it.owner == pluginId } + val published = runtimeTypes.filter { it.scopeKey == key } published.forEach { it.deactivate() } runtimeTypes.removeAll(published.toSet()) } }, + { + synchronized(runtimeSerializers) { + val published = runtimeSerializers.filter { it.scopeKey == key } + published.forEach { it.deactivate() } + runtimeSerializers.removeAll(published.toSet()) + } + }, { synchronized(scopes) { scopes[owner]?.let { byPlugin -> - byPlugin.remove(pluginId, this) + byPlugin.remove(key, this) if (byPlugin.isEmpty()) scopes.remove(owner) } } @@ -219,24 +424,21 @@ class ConfigurationServiceImpl( private fun snapshot() = synchronized(handles) { handles.toList() } } - private fun visibleTypes(consumer: PluginId): List = synchronized(runtimeTypes) { - runtimeTypes.filter { it.isActive && it.access.allows(it.owner, consumer) }.map { - RuntimeConfigType(it.owner.value, it.baseType, it.implementation, it.name, it.aliases, it.priority) - } - } - + /** A dynamically published polymorphic type; stays visible to codecs until [close] or its scope closes. */ private inner class TypeRegistration( + val scopeKey: PluginId, override val owner: PluginId, override val baseType: Class<*>, override val implementation: Class<*>, override val name: String, val aliases: Set, val priority: Int, - val access: ConfigTypeAccess, + override val target: ConfigAddress, ) : ConfigTypeRegistration { @Volatile private var active = true override val isActive: Boolean get() = active + fun words(): Set = aliases + name override fun close() { deactivate() synchronized(runtimeTypes) { runtimeTypes.remove(this) } @@ -244,35 +446,27 @@ class ConfigurationServiceImpl( fun deactivate() { active = false } } - private class OwnedConfig(val file: Path, private val delegate: ManagedConfig) : ManagedConfig by delegate -} - -private fun runAll(vararg steps: () -> Unit) = runAll(steps.toList()) - -/** Runs every step even when earlier ones fail; the first failure is rethrown with later ones suppressed into it. */ -private fun runAll(steps: List<() -> Unit>) { - var failure: Throwable? = null - steps.forEach { step -> - try { - step() - } catch (error: Throwable) { - Failures.rethrowIfFatal(error) - val first = failure - if (first == null) failure = error else if (error !== first) first.addSuppressed(error) + /** A published serializer; used by codecs until [close] or its scope closes. */ + private inner class SerializerRegistration( + val scopeKey: PluginId, + override val owner: PluginId, + override val type: Class<*>, + val serializer: ConfigSerializer<*>, + override val priority: Int, + override val target: ConfigAddress, + ) : ConfigSerializerRegistration { + @Volatile + private var active = true + override val isActive: Boolean get() = active + override fun close() { + deactivate() + synchronized(runtimeSerializers) { runtimeSerializers.remove(this) } } + fun deactivate() { active = false } } - failure?.let { throw it } -} -/** - * A file registered through a configuration scope. - * - * @property path path relative to [directory], with `/` separators - * @property secretPaths dotted paths of the `@ConfigSecret` fields - */ -class ManagedConfigFile( - val pluginId: PluginId, - val directory: Path, - val path: String, - val secretPaths: List, -) + private companion object { + val MAIN_MODULE: ModuleId = ModuleId.of("main") + val FORBIDDEN_PACKAGES = listOf("java.", "javax.", "kotlin.", "jdk.") + } +} diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/LibraryConfigFiles.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/LibraryConfigFiles.kt deleted file mode 100644 index daca2695a..000000000 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/LibraryConfigFiles.kt +++ /dev/null @@ -1,57 +0,0 @@ -package org.pnfolder.pnlibrary.config - -import org.pnfolder.pnlibrary.api.config.ConfigNamingStrategy -import org.pnfolder.pnlibrary.api.config.ConfigOptions -import org.pnfolder.pnlibrary.api.config.ConfigValueValidator -import org.pnfolder.pnlibrary.api.config.UnknownValuePolicy -import org.pnfolder.pnlibrary.api.logging.LogLevel -import org.pnfolder.pnlibrary.api.logging.PnLogger -import java.nio.file.Files -import java.nio.file.Path -import java.util.function.Supplier - -/** - * Loads the library's own YAML files (`config.yml`, `updates.yml`, `downloads.yml`) through the same - * code-first configuration system that plugins use: defaults, comments and validation come from the model. - * - * Keys that no longer exist in the model are removed after a backup, so a file never keeps stale options. - */ -object LibraryConfigFiles { - private const val MAX_BYTES = 256L * 1024L - - private val OPTIONS = ConfigOptions( - unknownValues = UnknownValuePolicy.REMOVE, - naming = ConfigNamingStrategy.KEBAB_CASE, - ) - - /** - * Creates the file with defaults when it is missing, synchronizes it with [type], and returns the value. - * - * @param warning receiver for recoverable problems such as removed keys - * @throws IllegalArgumentException when the file is a symbolic link, too large or invalid - */ - fun load( - file: Path, - type: Class, - defaults: Supplier, - validator: ConfigValueValidator = ConfigValueValidator { emptyList() }, - warning: (String) -> Unit = {}, - ): T { - require(!Files.isSymbolicLink(file)) { "${file.fileName} must not be a symbolic link" } - require(!Files.exists(file) || Files.size(file) <= MAX_BYTES) { "${file.fileName} exceeds 256 KiB" } - - val result = StandaloneConfigs.yaml(file, type, defaults, OPTIONS, validator, WarningLogger(warning)).load() - if (result.removedPaths.isNotEmpty()) { - val backup = result.backup?.name?.let { "; копия прежнего файла: $it" }.orEmpty() - warning("${file.fileName}: удалены неизвестные параметры (${result.removedPaths.joinToString()})$backup") - } - return result.value - } - - /** Hands warnings and errors to [warning]; the files are read before any logger exists. */ - private class WarningLogger(private val onWarning: (String) -> Unit) : PnLogger { - override fun log(level: LogLevel, message: String, error: Throwable?, record: Boolean) { - if (level >= LogLevel.WARNING) onWarning(message) - } - } -} diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ManagedConfigFile.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ManagedConfigFile.kt new file mode 100644 index 000000000..e06ee2549 --- /dev/null +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/ManagedConfigFile.kt @@ -0,0 +1,22 @@ +package org.pnfolder.pnlibrary.config + +import org.pnfolder.pnlibrary.api.plugin.PluginId +import org.pnfolder.pnlibrary.config.yaml.DatabasePath +import java.nio.file.Path + +/** + * A file registered through a configuration scope. + * + * @property pluginId plugin that registered the file + * @property directory data folder of the plugin + * @property path path relative to [directory], with `/` separators + * @property secretPaths dotted paths of the `@ConfigSecret` fields + * @property databases sections marked `@BackupDatabase` + */ +class ManagedConfigFile( + val pluginId: PluginId, + val directory: Path, + val path: String, + val secretPaths: List, + val databases: List = emptyList(), +) diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/OwnedConfig.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/OwnedConfig.kt new file mode 100644 index 000000000..1a89628b6 --- /dev/null +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/OwnedConfig.kt @@ -0,0 +1,160 @@ +package org.pnfolder.pnlibrary.config + +import org.pnfolder.pnlibrary.api.config.ConfigApply +import org.pnfolder.pnlibrary.api.config.ConfigChange +import org.pnfolder.pnlibrary.api.config.ConfigChangeCause +import org.pnfolder.pnlibrary.api.config.ConfigEditException +import org.pnfolder.pnlibrary.api.config.ConfigEditResult +import org.pnfolder.pnlibrary.api.config.ConfigId +import org.pnfolder.pnlibrary.api.config.ConfigInfo +import org.pnfolder.pnlibrary.api.config.ConfigLoadResult +import org.pnfolder.pnlibrary.api.config.ConfigProblem +import org.pnfolder.pnlibrary.api.config.ConfigSetting +import org.pnfolder.pnlibrary.api.config.ConfigValidationException +import org.pnfolder.pnlibrary.api.config.ManagedConfig +import org.pnfolder.pnlibrary.api.config.ReloadRequest +import org.pnfolder.pnlibrary.api.logging.PnLogger +import org.pnfolder.pnlibrary.config.yaml.CodeFirstYaml +import org.pnfolder.pnlibrary.config.yaml.ConfigSettingsEditor +import org.pnfolder.pnlibrary.config.yaml.UnknownConfigTypeException +import java.nio.file.Files +import java.nio.file.Path +import java.time.Instant +import java.util.concurrent.CopyOnWriteArrayList +import java.util.function.Consumer +import java.util.function.UnaryOperator + +/** + * A managed file that remembers its identifier and path. It tells when it was loaded and whether it is waiting for a type, + * which is the case when its last read failed or skipped list elements because a `type` word was unknown. + */ +internal class OwnedConfig( + override val id: ConfigId, + val file: Path, + private val modelType: Class<*>, + val readOnly: Boolean, + private val delegate: CodeFirstYaml, + private val editor: ConfigSettingsEditor, + private val logger: PnLogger, +) : ManagedConfig by delegate { + @Volatile + private var loadedAt: Instant? = null + + /** Whether reading again could bring back what the last read left out. */ + @Volatile + var waitingForTypes = false + private set + + /** The strongest requirement of edits that do not work yet; a read clears [ConfigApply.RELOAD], a restart clears the rest. */ + @Volatile + private var pending: ConfigApply? = null + + private val changeListeners = CopyOnWriteArrayList>() + private val reloadListeners = CopyOnWriteArrayList>() + + override val info: ConfigInfo + get() = ConfigInfo( + id = id, + modelType = modelType, + file = file, + exists = Files.exists(file), + isLoaded = isLoaded, + loadedAt = loadedAt, + readOnly = readOnly, + skippedUnknownTypes = delegate.skippedUnknownTypes, + problems = if (isLoaded) runCatching { delegate.validate() }.getOrDefault(emptyList()) else emptyList(), + pendingApply = pending, + ) + + override val settings: List + get() = editor.describe(if (isLoaded) delegate.get() else null) + + override fun edit(path: String, text: String): ConfigEditResult { + check(!readOnly) { "Файл $id открыт только для чтения" } + val applied = synchronized(delegate) { + check(isLoaded) { "Файл $id не загружен" } + val applied = editor.set(delegate.get() as Any, path, text) + try { + delegate.save() + } catch (error: ConfigValidationException) { + applied.restore() + throw ConfigEditException(error.problems.joinToString("; ") { "${it.path}: ${it.message}" }, error) + } catch (error: Exception) { + applied.restore() + throw ConfigEditException(error.message ?: "Не удалось записать файл", error) + } + applied + } + val result = ConfigEditResult(applied.setting, applied.previous) + if (applied.setting.apply != ConfigApply.LIVE) { + pending = strongest(pending, applied.setting.apply) + fire(reloadListeners, ReloadRequest(id, applied.setting.apply, listOf(applied.setting))) + } + fire(changeListeners, ConfigChange(id, ConfigChangeCause.EDITED, listOf(path))) + return result + } + + override fun onChanged(vararg listeners: Consumer): AutoCloseable = subscribe(changeListeners, listeners.toList()) + + override fun onReloadRequired(vararg listeners: Consumer): AutoCloseable = subscribe(reloadListeners, listeners.toList()) + + override fun load(): ConfigLoadResult = track(ConfigChangeCause.LOADED) { delegate.load() } + override fun reload(): ConfigLoadResult = track(ConfigChangeCause.RELOADED) { delegate.reload() } + override fun loadValue(): T = load().value + override fun reloadValue(): T = reload().value + + override fun save() { + delegate.save() + fire(changeListeners, ConfigChange(id, ConfigChangeCause.SAVED, emptyList())) + } + + override fun save(value: T) { + delegate.save(value) + fire(changeListeners, ConfigChange(id, ConfigChangeCause.SAVED, emptyList())) + } + + override fun update(updater: UnaryOperator): T = delegate.update(updater).also { + fire(changeListeners, ConfigChange(id, ConfigChangeCause.SAVED, emptyList())) + } + + override fun resetToDefaults(): T = delegate.resetToDefaults().also { + fire(changeListeners, ConfigChange(id, ConfigChangeCause.RESET, emptyList())) + } + + override fun unload() { + delegate.unload() + loadedAt = null + } + + override fun close() = unload() + + private fun track(cause: ConfigChangeCause, action: () -> ConfigLoadResult): ConfigLoadResult = try { + action().also { + loadedAt = Instant.now() + waitingForTypes = delegate.skippedUnknownTypes.isNotEmpty() + if (pending == ConfigApply.RELOAD) pending = null + fire(changeListeners, ConfigChange(id, cause, emptyList())) + } + } catch (error: Exception) { + waitingForTypes = generateSequence(error) { it.cause }.any { it is UnknownConfigTypeException } + throw error + } + + private fun strongest(a: ConfigApply?, b: ConfigApply): ConfigApply = if (a == null || b.ordinal > a.ordinal) b else a + + private fun subscribe(target: CopyOnWriteArrayList>, listeners: List>): AutoCloseable { + target.addAll(listeners) + return AutoCloseable { target.removeAll(listeners.toSet()) } + } + + /** A failing listener is logged and never stops the others or the change itself. */ + private fun fire(listeners: List>, event: E) { + listeners.forEach { listener -> + try { + listener.accept(event) + } catch (error: Exception) { + logger.warning("Обработчик изменения $id завершился ошибкой: ${error.message}", error) + } + } + } +} diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/StandaloneConfigs.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/StandaloneConfigs.kt deleted file mode 100644 index 3586de3d3..000000000 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/StandaloneConfigs.kt +++ /dev/null @@ -1,56 +0,0 @@ -package org.pnfolder.pnlibrary.config - -import org.pnfolder.pnlibrary.api.config.ConfigOptions -import org.pnfolder.pnlibrary.api.config.ConfigValueValidator -import org.pnfolder.pnlibrary.api.config.ManagedConfig -import org.pnfolder.pnlibrary.api.logging.PnLogger -import org.pnfolder.pnlibrary.config.yaml.AnnotatedYamlCodec -import org.pnfolder.pnlibrary.config.yaml.CodeFirstYaml -import java.nio.file.Path -import java.util.function.Supplier - -/** - * Opens typed YAML files that belong to the library itself rather than to a plugin. - * - * The files use the same code-first rules as plugin configurations (defaults, comments, validation, - * version marker), but need no plugin owner, so they are available before the runtime starts. - */ -object StandaloneConfigs { - /** - * Registers the typed YAML file at [file] without loading it. - * - * @param file absolute path of the `.yml` file; its folder is created on load - * @param type annotated mutable model class - * @param defaults supplier of a fresh default instance - * @param options synchronization policy of the file - * @param validator extra semantic validation that runs on every load and save - * @param logger receiver of synchronization and recovery warnings - */ - @JvmStatic - fun yaml( - file: Path, - type: Class, - defaults: Supplier, - options: ConfigOptions, - validator: ConfigValueValidator, - logger: PnLogger, - ): ManagedConfig { - val codec = AnnotatedYamlCodec( - type = type, - defaults = defaults, - serializers = BuiltInConfigSerializers.create(), - runtimeTypes = { emptyList() }, - consumer = "pnlibrary", - options = options, - warning = { message -> logger.warning(message) }, - ) - return CodeFirstYaml( - file = file.toFile(), - defaults = defaults.get(), - codec = codec, - logger = logger, - validator = ConfigValueValidator { value -> codec.validate(value) + validator.validate(value) }, - options = options, - ) - } -} diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/AnnotatedYamlCodec.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/AnnotatedYamlCodec.kt index e7c1f2af2..119cbd21c 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/AnnotatedYamlCodec.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/AnnotatedYamlCodec.kt @@ -10,11 +10,13 @@ import org.pnfolder.pnlibrary.api.config.ConfigProblem import org.pnfolder.pnlibrary.api.config.ConfigSerializationContext import org.pnfolder.pnlibrary.api.config.ConfigSerializer import org.pnfolder.pnlibrary.api.config.ConfigTextForm +import org.pnfolder.pnlibrary.api.config.UnknownTypePolicy import org.yaml.snakeyaml.DumperOptions import org.yaml.snakeyaml.LoaderOptions import org.yaml.snakeyaml.Yaml import org.yaml.snakeyaml.constructor.SafeConstructor import org.yaml.snakeyaml.representer.Representer +import java.lang.reflect.Field import java.lang.reflect.Modifier import java.lang.reflect.ParameterizedType import java.lang.reflect.Type @@ -35,7 +37,7 @@ import java.lang.reflect.Array as ReflectArray * * @param type root configuration class * @param defaults factory for a pristine root object on every decode - * @param serializers serializers keyed by supported Java type + * @param serializers the serializers keyed by supported Java type, asked again on every use so that additions count * @param runtimeTypes current external polymorphic type registrations * @param consumer plugin namespace resolving unqualified external types * @param options naming and document-generation policy @@ -44,7 +46,7 @@ import java.lang.reflect.Array as ReflectArray internal class AnnotatedYamlCodec( private val type: Class, private val defaults: Supplier, - private val serializers: Map, ConfigSerializer<*>>, + private val serializers: () -> Map, ConfigSerializer<*>>, private val runtimeTypes: () -> List, private val consumer: String, private val options: ConfigOptions, @@ -58,6 +60,9 @@ internal class AnnotatedYamlCodec( /** Dotted paths of the `@ConfigSecret` fields, which diagnostic reports never show. */ val secretPaths: List = introspector.secretPaths(type) + + /** The sections marked `@BackupDatabase`; the update system copies those databases. */ + val databases: List = introspector.databasePaths(type) private val yaml = DumperOptions().apply { defaultFlowStyle = DumperOptions.FlowStyle.BLOCK isPrettyFlow = false @@ -66,6 +71,7 @@ internal class AnnotatedYamlCodec( width = 120 }.let { options -> Yaml(SafeConstructor(LoaderOptions()), Representer(options), options) } + /** Writes [value] as YAML with the comments, blank lines and file header declared by annotations. */ override fun encode(value: T): String { val raw = yaml.dump(toYamlValue(value, type, "", emptyList(), value)) val body = YamlSchemaDecorator.decorate(raw, schemaInspector.metadata(type, value)) @@ -80,19 +86,32 @@ internal class AnnotatedYamlCodec( * polymorphic types, and classes that cannot be instantiated */ override fun decode(yaml: String): T { - val loaded = this.yaml.load(yaml) ?: linkedMapOf() - serializerResolver.forType(type)?.let { - @Suppress("UNCHECKED_CAST") - return it.deserialize(loaded, context(type, "", emptyList(), defaults.get())) as T + skippedNow.clear() + try { + val loaded = this.yaml.load(yaml) ?: linkedMapOf() + serializerResolver.forType(type)?.let { + @Suppress("UNCHECKED_CAST") + return it.deserialize(loaded, context(type, "", emptyList(), defaults.get())) as T + } + require(loaded is Map<*, *>) { "Root value of ${type.name} must be a YAML object" } + return defaults.get().also { populate(it, type, loaded, "") } + } finally { + skippedUnknownTypes = skippedNow.toList() } - require(loaded is Map<*, *>) { "Root value of ${type.name} must be a YAML object" } - return defaults.get().also { populate(it, type, loaded, "") } } + private val skippedNow = mutableListOf() + + /** + * List elements the last [decode] skipped because their `type` is unknown (only with + * [UnknownTypePolicy.SKIP]). Each entry names the element and the word. + */ + @Volatile + var skippedUnknownTypes: List = emptyList() + private set + /** Evaluates declarative validation annotations without mutating [value]. */ - fun validate(value: T): List { - return schemaInspector.validate(value, type) - } + fun validate(value: T): List = schemaInspector.validate(value, type) private fun toYamlValue( value: Any?, declaredType: Type = value?.javaClass ?: Any::class.java, path: String = "", @@ -111,17 +130,17 @@ internal class AnnotatedYamlCodec( } } return when (value) { - null, is String, is Number, is Boolean -> value - is Enum<*> -> value.name - is Iterable<*> -> { - val elementType = (declaredType as? ParameterizedType)?.actualTypeArguments?.getOrNull(0) ?: Any::class.java - value.mapIndexed { index, item -> toYamlValue(item, elementType, "$path[$index]", annotations) } - } - is Array<*> -> value.mapIndexed { index, item -> toYamlValue(item, path = "$path[$index]") } - is Map<*, *> -> linkedMapOf().also { out -> value.forEach { (k, v) -> - out[toYamlValue(k)] = toYamlValue(v, path = "$path.$k") - } } - else -> objectYaml(value, path) + null, is String, is Number, is Boolean -> value + is Enum<*> -> value.name + is Iterable<*> -> { + val elementType = (declaredType as? ParameterizedType)?.actualTypeArguments?.getOrNull(0) ?: Any::class.java + value.mapIndexed { index, item -> toYamlValue(item, elementType, "$path[$index]", annotations) } + } + is Array<*> -> value.mapIndexed { index, item -> toYamlValue(item, path = "$path[$index]") } + is Map<*, *> -> linkedMapOf().also { out -> + value.forEach { (k, v) -> out[toYamlValue(k)] = toYamlValue(v, path = "$path.$k") } + } + else -> objectYaml(value, path) } } @@ -154,25 +173,26 @@ internal class AnnotatedYamlCodec( ) ?: convert(resolved, field.genericType, current, path, field.annotations.toList()) } catch (error: Exception) { - if (field.isAnnotationPresent(ConfigDefaultOnInvalid::class.java)) { - warning("Invalid value at $path (${raw ?: "null"}); using default ${current ?: "null"}") - current - } else { - val detail = if (field.type.isEnum) { - val allowed = schemaInspector.enumDescription(field.type) - " Allowed values: $allowed. Default: ${current ?: "null"}." - } else "" - if (error is LocatedConfigException || error.message.orEmpty().startsWith(INVALID_VALUE)) throw error - throw IllegalArgumentException( - "$INVALID_VALUE $path: ${shown(raw)}.$detail${reasonSuffix(error)}", - error, - ) - } + invalidValue(field, raw, current, path, error) } field.set(target, converted) } } + /** Returns [current] for a `@ConfigDefaultOnInvalid` field; otherwise throws an error that names [path] and the value. */ + private fun invalidValue(field: Field, raw: Any?, current: Any?, path: String, error: Exception): Any? { + if (field.isAnnotationPresent(ConfigDefaultOnInvalid::class.java)) { + warning("Invalid value at $path (${raw ?: "null"}); using default ${current ?: "null"}") + return current + } + val detail = if (field.type.isEnum) { + val allowed = schemaInspector.enumDescription(field.type) + " Allowed values: $allowed. Default: ${current ?: "null"}." + } else "" + if (error is LocatedConfigException || error.message.orEmpty().startsWith(INVALID_VALUE)) throw error + throw IllegalArgumentException("$INVALID_VALUE $path: ${shown(raw)}.$detail${reasonSuffix(error)}", error) + } + private fun convert( value: Any?, targetType: Type, current: Any? = null, path: String = "", annotations: List = emptyList(), @@ -195,39 +215,60 @@ internal class AnnotatedYamlCodec( if (rawType == java.lang.Double.TYPE || rawType == java.lang.Double::class.java) return (value as Number).toDouble() if (rawType.isEnum) return rawType.enumConstants.firstOrNull { (it as Enum<*>).name.equals(value.toString(), true) } ?: throw IllegalArgumentException("Unknown ${rawType.simpleName} value: $value") - if (rawType.isArray && value is List<*>) { - val component = rawType.componentType - return ReflectArray.newInstance(component, value.size).also { array -> - value.forEachIndexed { index, item -> ReflectArray.set(array, index, convert(item, component, path = "$path[$index]")) } - } - } + if (rawType.isArray && value is List<*>) return convertArray(rawType, value, path) if (Collection::class.java.isAssignableFrom(rawType) && value is List<*>) { - val elementType = (targetType as? ParameterizedType)?.actualTypeArguments?.getOrNull(0) ?: Any::class.java - val converted = value.mapIndexed { index, item -> - located("$path[$index]") { convert(item, elementType, path = "$path[$index]", annotations = annotations) } - } - return introspector.collection(rawType, converted, path) + return convertCollection(targetType, rawType, value, path, annotations) + } + if (Map::class.java.isAssignableFrom(rawType) && value is Map<*, *>) return convertMap(targetType, rawType, value, path) + if (value is Map<*, *>) return convertSection(rawType, value, current, path) + return value + } + + private fun convertArray(rawType: Class<*>, value: List<*>, path: String): Any { + val component = rawType.componentType + return ReflectArray.newInstance(component, value.size).also { array -> + value.forEachIndexed { index, item -> ReflectArray.set(array, index, convert(item, component, path = "$path[$index]")) } } - if (Map::class.java.isAssignableFrom(rawType) && value is Map<*, *>) { - val arguments = (targetType as? ParameterizedType)?.actualTypeArguments - val keyType = arguments?.getOrNull(0) ?: String::class.java - val valueType = arguments?.getOrNull(1) ?: Any::class.java - val converted = linkedMapOf().also { out -> - value.forEach { (key, item) -> - out[convert(key, keyType)] = located("$path.$key") { convert(item, valueType, path = "$path.$key") } - } + } + + private fun convertCollection( + targetType: Type, rawType: Class<*>, value: List<*>, path: String, annotations: List, + ): Any { + val elementType = (targetType as? ParameterizedType)?.actualTypeArguments?.getOrNull(0) ?: Any::class.java + val skipUnknown = options.unknownTypes == UnknownTypePolicy.SKIP + val converted = value.mapIndexedNotNull { index, item -> + try { + located("$path[$index]") { convert(item, elementType, path = "$path[$index]", annotations = annotations) } + } catch (error: IllegalArgumentException) { + val unknown = generateSequence(error) { it.cause }.filterIsInstance().firstOrNull() + if (!skipUnknown || unknown == null) throw error + // The element stays in the file; only the copy in memory goes without it. + val note = "$path[$index]: ${unknown.message}" + skippedNow += note + warning("Skipped $note. The element stays in the file and is read again when the type appears.") + null } - return introspector.map(rawType, converted, path) } - if (value is Map<*, *>) { - require(!rawType.isInterface && !Modifier.isAbstract(rawType.modifiers)) { - "Type ${rawType.name} at $path is abstract; register a ConfigSerializer" + return introspector.collection(rawType, converted, path) + } + + private fun convertMap(targetType: Type, rawType: Class<*>, value: Map<*, *>, path: String): Any { + val arguments = (targetType as? ParameterizedType)?.actualTypeArguments + val keyType = arguments?.getOrNull(0) ?: String::class.java + val valueType = arguments?.getOrNull(1) ?: Any::class.java + val converted = linkedMapOf().also { out -> + value.forEach { (key, item) -> + out[convert(key, keyType)] = located("$path.$key") { convert(item, valueType, path = "$path.$key") } } - val nested = current ?: introspector.instantiate(rawType, path) - populate(nested, rawType, value, path) - return nested } - return value + return introspector.map(rawType, converted, path) + } + + private fun convertSection(rawType: Class<*>, value: Map<*, *>, current: Any?, path: String): Any { + require(!rawType.isInterface && !Modifier.isAbstract(rawType.modifiers)) { "Type ${rawType.name} at $path is abstract; register a ConfigSerializer" } + val nested = current ?: introspector.instantiate(rawType, path) + populate(nested, rawType, value, path) + return nested } private fun polymorphic(value: Any, baseType: Class<*>, path: String, annotations: List): Any { @@ -245,9 +286,7 @@ internal class AnnotatedYamlCodec( ?: error("Missing '$discriminator' for ${baseType.simpleName} at $path") val name = entry.value?.toString()?.trim().orEmpty() val implementation = polymorphicResolver.decodingType(baseType, annotations, name, path) - val body = linkedMapOf().also { result -> - node.forEach { (key, item) -> if (key != entry.key) result[key] = item } - } + val body = node.filterKeys { it != entry.key } return introspector.instantiate(implementation, path).also { populate(it, implementation, body, path) } } diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/CodeFirstYaml.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/CodeFirstYaml.kt index 05e1e2c44..156daad9f 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/CodeFirstYaml.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/CodeFirstYaml.kt @@ -18,9 +18,9 @@ import java.util.function.UnaryOperator * Loads typed YAML and synchronizes it with code-defined defaults. * * Missing keys and their comments are added recursively. Existing values, - * ordering, comments, and extension keys are preserved. A `.bak` file is - * created before synchronization, and the target is replaced atomically only - * after successful decoding. + * ordering, comments, and extension keys are preserved. A `.before-sync-*.bak` + * copy is made before a rewrite when [ConfigOptions.backups] is on, and the target + * is replaced atomically only after successful decoding. * * ```kotlin * val config = CodeFirstYaml(file, Settings(), codec, logger).load().value @@ -42,6 +42,7 @@ class CodeFirstYaml @JvmOverloads constructor( /** `true` after a successful [load] or [reload] and before [unload]. */ override val isLoaded: Boolean get() = loadedValue != null + /** Returns the loaded value or fails when the file is not loaded. */ override fun get(): T = loadedValue ?: error("Configuration ${file.name} is not loaded") /** @@ -50,12 +51,13 @@ class CodeFirstYaml @JvmOverloads constructor( */ @Synchronized override fun load(): ConfigLoadResult { + if (options.readOnly) return loadWithoutWriting() + // Nothing may be created for a file that must already exist, not even its folder. + check(file.exists() || options.missingFile == MissingFilePolicy.CREATE) { "Configuration ${file.name} does not exist" } val parent = file.absoluteFile.parentFile require(parent.isDirectory || parent.mkdirs()) { "Cannot create configuration directory $parent" } val rawDefaultsYaml = fileStore.normalize(codec.encode(defaults)) - val defaultsYaml = SupportHeader.apply( - options.migrations?.let { fileStore.normalize(migrationEngine.stampDefaults(rawDefaultsYaml, it)) } ?: rawDefaultsYaml, - ) + val defaultsYaml = options.migrations?.let { fileStore.normalize(migrationEngine.stampDefaults(rawDefaultsYaml, it)) } ?: rawDefaultsYaml if (!file.exists()) return createFromDefaults(defaultsYaml) val original = fileStore.normalize(file.readText()) @@ -65,7 +67,7 @@ class CodeFirstYaml @JvmOverloads constructor( val working = migration?.takeIf { it.applied.isNotEmpty() }?.content?.let(fileStore::normalize) ?: original val differences = differences(defaultsYaml, working) val syncResult = synchronize(working, defaultsYaml) - val synchronized = SupportHeader.apply(syncResult.content) + val synchronized = LegacySupportNote.removeFrom(syncResult.content) val value = decodeAndValidate(synchronized) if (synchronized == original) { loadedValue = value @@ -74,10 +76,18 @@ class CodeFirstYaml @JvmOverloads constructor( return writeChanges(original, synchronized, value, differences, migration?.applied.orEmpty(), syncResult) } + /** A read-only file is read as it is: nothing is created, migrated, synchronized or backed up. */ + private fun loadWithoutWriting(): ConfigLoadResult { + check(file.exists()) { "Configuration ${file.name} does not exist" } + val value = decodeAndValidate(fileStore.normalize(file.readText())) + loadedValue = value + return ConfigLoadResult(value, emptyList(), null) + } + private fun createFromDefaults(defaultsYaml: String): ConfigLoadResult { check(options.missingFile == MissingFilePolicy.CREATE) { "Configuration ${file.name} does not exist" } - fileStore.write(defaultsYaml) val value = decodeAndValidate(defaultsYaml) + fileStore.writeDecoded(defaultsYaml) loadedValue = value return ConfigLoadResult(value, YamlDefaultsMerger.paths(defaultsYaml), null) } @@ -90,6 +100,7 @@ class CodeFirstYaml @JvmOverloads constructor( return ConfigLoadResult(value, emptyList(), null) } + /** Paths missing from the file and paths unknown to the code. */ private class Differences(val missing: List, val unknown: List) /** The paths the file lacks and the paths the code does not know; fails when the policy forbids either. */ @@ -129,7 +140,7 @@ class CodeFirstYaml @JvmOverloads constructor( syncResult: YamlDefaultsMerger.Result, ): ConfigLoadResult { val backup = if (options.backups) fileStore.backup(original) else null - fileStore.write(synchronized) + fileStore.writeDecoded(synchronized) val removeUnknown = options.unknownValues == UnknownValuePolicy.REMOVE if (differences.missing.isNotEmpty()) logger.info("Добавлены новые параметры в ${file.name}: ${differences.missing.joinToString()}") if (differences.unknown.isNotEmpty() && removeUnknown) { @@ -151,21 +162,26 @@ class CodeFirstYaml @JvmOverloads constructor( @Synchronized override fun reload(): ConfigLoadResult = load() + /** Saves the value that is currently loaded. */ @Synchronized override fun save() = save(get()) /** Atomically saves [value] after decoding and semantic validation. */ @Synchronized override fun save(value: T) { + check(!options.readOnly) { "Configuration ${file.name} is read-only" } + check(skippedUnknownTypes.isEmpty()) { + "Configuration ${file.name} has elements of an unknown type that are not in memory: " + + "${skippedUnknownTypes.joinToString("; ")}. Saving would delete them from the file" + } val raw = fileStore.normalize(codec.encode(value)) - val encoded = SupportHeader.apply( - options.migrations?.let { fileStore.normalize(migrationEngine.stampDefaults(raw, it)) } ?: raw, - ) + val encoded = options.migrations?.let { fileStore.normalize(migrationEngine.stampDefaults(raw, it)) } ?: raw decodeAndValidate(encoded) - fileStore.write(encoded) + fileStore.writeDecoded(encoded) loadedValue = value } + /** Applies [updater] to the loaded value and saves the result. */ @Synchronized override fun update(updater: UnaryOperator): T { val updated = updater.apply(get()) @@ -173,8 +189,10 @@ class CodeFirstYaml @JvmOverloads constructor( return updated } + /** Runs the validator on the loaded value without writing anything. */ override fun validate(): List = validator.validate(get()) + /** Writes the code defaults to the file and makes them the loaded value. */ @Synchronized override fun resetToDefaults(): T { save(defaults) @@ -185,6 +203,14 @@ class CodeFirstYaml @JvmOverloads constructor( @Synchronized override fun unload() { loadedValue = null } + /** + * List elements skipped at the last read because their `type` is unknown, empty when nothing was skipped. + * While it is not empty, saving is refused: the elements exist only in the file. + */ + @Volatile + var skippedUnknownTypes: List = emptyList() + private set + private fun decodeAndValidate(content: String): T { val value = try { codec.decode(content) @@ -192,6 +218,7 @@ class CodeFirstYaml @JvmOverloads constructor( logger.error("Не удалось прочитать ${file.name}: ${error.message}", error) throw error } + skippedUnknownTypes = (codec as? AnnotatedYamlCodec<*>)?.skippedUnknownTypes.orEmpty() val problems = validator.validate(value) if (problems.isNotEmpty()) throw ConfigValidationException(problems) return value diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigObjectIntrospector.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigObjectIntrospector.kt index cd62eecbc..172788d3e 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigObjectIntrospector.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigObjectIntrospector.kt @@ -1,10 +1,15 @@ package org.pnfolder.pnlibrary.config.yaml +import org.pnfolder.pnlibrary.api.config.BackupDatabase +import org.pnfolder.pnlibrary.api.config.BackupTable import org.pnfolder.pnlibrary.api.config.ConfigIgnore import org.pnfolder.pnlibrary.api.config.ConfigKey import org.pnfolder.pnlibrary.api.config.ConfigNamingStrategy import org.pnfolder.pnlibrary.api.config.ConfigOrder import org.pnfolder.pnlibrary.api.config.ConfigSecret +import org.pnfolder.pnlibrary.api.config.DatabaseField +import org.pnfolder.pnlibrary.api.config.DatabaseKind +import org.pnfolder.pnlibrary.api.config.DatabaseRole import java.lang.reflect.Field import java.lang.reflect.Modifier import java.lang.reflect.ParameterizedType @@ -29,22 +34,10 @@ import java.util.TreeSet internal class ConfigObjectIntrospector( private val defaultNaming: ConfigNamingStrategy, ) { - /** Returns serializable fields in superclass-first, configured order. */ - fun fields(type: Class<*>): List { - val hierarchy = generateSequence(type) { it.superclass } - .takeWhile { it != Any::class.java } - .toList() - .asReversed() - return hierarchy.flatMap { it.declaredFields.asList() } - .filterNot { field -> - field.isSynthetic || Modifier.isStatic(field.modifiers) || - Modifier.isTransient(field.modifiers) || - field.isAnnotationPresent(ConfigIgnore::class.java) - } - .sortedWith(compareBy { it.getAnnotation(ConfigOrder::class.java)?.value ?: 0 }) - .onEach { it.isAccessible = true } - } + /** Returns serializable fields in superclass-first, configured order; read once per class, not per call. */ + fun fields(type: Class<*>): List = FIELDS.get(type) + /** The YAML key of [field]: `@ConfigKey` if present, otherwise the field name in the configured naming style. */ fun key(field: Field): String = field.getAnnotation(ConfigKey::class.java) ?.value ?.takeIf(String::isNotBlank) @@ -61,14 +54,62 @@ internal class ConfigObjectIntrospector( out += path return@forEach } - val raw = rawClass(field.genericType) - val nested = !raw.isPrimitive && !raw.isEnum && !raw.isArray && !isScalar(raw) && - !Collection::class.java.isAssignableFrom(raw) && !Map::class.java.isAssignableFrom(raw) && - !raw.name.startsWith("java.") && !raw.name.startsWith("kotlin.") - if (nested) collectSecrets(raw, "$path.", depth + 1, out) + collectNestedSecrets(field.genericType, path, depth, out) + } + } + + /** Lists add no segment to a report path; a map value adds its key, written `*` because it is only known at run time. */ + private fun collectNestedSecrets(type: Type, path: String, depth: Int, out: MutableList) { + val raw = rawClass(type) + val arguments = (type as? ParameterizedType)?.actualTypeArguments.orEmpty() + when { + Collection::class.java.isAssignableFrom(raw) -> + arguments.firstOrNull()?.let { collectNestedSecrets(it, path, depth + 1, out) } + Map::class.java.isAssignableFrom(raw) -> + arguments.getOrNull(1)?.let { collectNestedSecrets(it, "$path.*", depth + 1, out) } + isSection(raw) -> if (depth < 8) collectSecrets(raw, "$path.", depth + 1, out) + } + } + + fun isSection(raw: Class<*>): Boolean = !raw.isPrimitive && !raw.isEnum && !raw.isArray && !isScalar(raw) && + !raw.name.startsWith("java.") && !raw.name.startsWith("kotlin.") + + /** The databases marked `@BackupDatabase` in [type] (the class may carry several), with the dotted YAML path of each. */ + fun databasePaths(type: Class<*>): List { + val root = type.getAnnotationsByType(BackupDatabase::class.java).map { + DatabasePath("", it.kind, it.name, roleKeys(type, it.name), it.tables.toList(), tableKeys(type, it.name)) + } + val sections = fields(type).flatMap { field -> + field.getAnnotationsByType(BackupDatabase::class.java).map { + val section = rawClass(field.genericType) + if (isScalar(section)) { + // On the field that holds the database name: the other fields of the class carry the same name. + val keys = roleKeys(type, it.name) + (DatabaseRole.DATABASE to key(field)) + DatabasePath("", it.kind, it.name, keys, it.tables.toList(), tableKeys(type, it.name)) + } else { + DatabasePath(key(field), it.kind, it.name, roleKeys(section, it.name), it.tables.toList(), tableKeys(section, it.name)) + } + } } + return root + sections } + /** + * The YAML key of each field that says which part of a connection it holds, whatever the field is called. A field + * with a `database` belongs to that database only and wins over a shared field without one. + */ + private fun roleKeys(section: Class<*>, database: String): Map = fields(section) + .mapNotNull { field -> + field.getAnnotation(DatabaseField::class.java)?.takeIf { it.database.isEmpty() || it.database == database }?.let { it to key(field) } + } + .sortedBy { it.first.database.isNotEmpty() }.associate { it.first.role to it.second } + + /** The YAML keys of the fields marked `@BackupTable` in [section] for [database]. */ + private fun tableKeys(section: Class<*>, database: String): List = fields(section) + .filter { field -> field.getAnnotation(BackupTable::class.java)?.let { it.database.isEmpty() || it.database == database } == true } + .map(::key) + + /** Reads the current value of [field] from [owner]. */ fun read(field: Field, owner: Any): Any? = field.get(owner) /** Resolves the concrete raw class represented by [type], or [Any] if unknown. */ @@ -99,6 +140,7 @@ internal class ConfigObjectIntrospector( ) } + /** Builds the collection of declared [type] holding [values]; an interface or abstract type gets a standard one. */ @Suppress("UNCHECKED_CAST") fun collection(type: Class<*>, values: Collection, path: String): Collection { if (type.isInterface || Modifier.isAbstract(type.modifiers)) return when { @@ -113,6 +155,7 @@ internal class ConfigObjectIntrospector( return collection } + /** Builds the map of declared [type] holding [values]; an interface or abstract type gets a standard one. */ @Suppress("UNCHECKED_CAST") fun map(type: Class<*>, values: Map, path: String): Map { if (type.isInterface || Modifier.isAbstract(type.modifiers)) { @@ -146,9 +189,51 @@ internal class ConfigObjectIntrospector( } } - private companion object { + internal companion object { + /** How many classes had their declared fields read since start; tests use it to prove the cache works. */ + val declaredFieldReads = java.util.concurrent.atomic.AtomicInteger() + + private val FIELDS = object : ClassValue>() { + override fun computeValue(type: Class<*>): List = discover(type) + } + + private fun discover(type: Class<*>): List { + val hierarchy = generateSequence(type) { it.superclass } + .takeWhile { it != Any::class.java } + .toList() + .asReversed() + return hierarchy.flatMap { declaredFieldReads.incrementAndGet(); it.declaredFields.asList() } + .filterNot { field -> + field.isSynthetic || Modifier.isStatic(field.modifiers) || + Modifier.isTransient(field.modifiers) || + field.isAnnotationPresent(ConfigIgnore::class.java) + } + .sortedWith(compareBy { it.getAnnotation(ConfigOrder::class.java)?.value ?: 0 }) + .onEach { it.isAccessible = true } + .let { java.util.Collections.unmodifiableList(it) } + } + val LOWER_TO_UPPER_BOUNDARY = Regex("([a-z0-9])([A-Z])") val ACRONYM_BOUNDARY = Regex("([A-Z]+)([A-Z][a-z])") val WORD_SEPARATOR = Regex("[_\\-\\s]+") } } + +/** + * A section holding database connection details: where it is in the file, what kind it is and what it is called. + * + * @property path dotted path of the section; empty when the connection fields sit at the top of the file + * @property kind database server type + * @property name short name from `@BackupDatabase` + * @property keys YAML key of the field that holds each part of the connection + * @property tables table or collection names written in the annotation + * @property tableKeys YAML keys of the fields that hold table names + */ +class DatabasePath( + val path: String, + val kind: DatabaseKind, + val name: String, + val keys: Map = emptyMap(), + val tables: List = emptyList(), + val tableKeys: List = emptyList(), +) diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigPolymorphicResolver.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigPolymorphicResolver.kt index 3621dd38a..b6a4fc8c1 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigPolymorphicResolver.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigPolymorphicResolver.kt @@ -4,7 +4,15 @@ import org.pnfolder.pnlibrary.api.config.ConfigPolymorphic import org.pnfolder.pnlibrary.api.config.ConfigTypes import java.lang.reflect.Type -/** Selected implementation and its serialized discriminator identity. */ +/** + * Selected implementation and its serialized discriminator identity. + * + * @property owner plugin that published the type, or `null` for a type declared by annotation + * @property implementation concrete class created for this declaration + * @property name canonical discriminator value + * @property aliases additional accepted discriminator values + * @property priority tie-breaker when several declarations match + */ internal data class ResolvedConfigType( val owner: String?, val implementation: Class<*>, @@ -12,11 +20,15 @@ internal data class ResolvedConfigType( val aliases: Set, val priority: Int, ) { - /** Canonical discriminator emitted for [consumer]. */ - fun serializedName(consumer: String): String = - if (owner == null || owner == consumer) name else "$owner::$name" + /** + * Discriminator written to the file. A word that reaches a file is already visible there, so it is written plainly; + * the `owner::name` form is still accepted when reading, to tell two additions with one word apart. + */ + @Suppress("UNUSED_PARAMETER") + fun serializedName(consumer: String): String = name - /** Whether [value] may resolve this declaration for [consumer]. */ + /** Whether [value] resolves this declaration: either the plain word or `owner::word` of its owner. */ + @Suppress("UNUSED_PARAMETER") fun matches(value: String, consumer: String): Boolean { val separator = value.indexOf(NAMESPACE_SEPARATOR) if (separator >= 0) { @@ -25,7 +37,6 @@ internal data class ResolvedConfigType( } return matchesName(value.substring(separator + NAMESPACE_SEPARATOR.length)) } - if (owner != null && !owner.equals(consumer, ignoreCase = true)) return false return matchesName(value) } @@ -37,12 +48,15 @@ internal data class ResolvedConfigType( } } +/** A `type` word that no visible declaration accepts. A list can skip such an element instead of failing. */ +internal class UnknownConfigTypeException(message: String) : IllegalArgumentException(message) + /** * Resolves annotated and runtime polymorphic configuration implementations. * - * Unqualified names can select built-in declarations or declarations owned by - * the consuming plugin. Types owned by other plugins are serialized and resolved - * with an explicit `owner::name` namespace. Priority resolves overlapping matches; + * The runtime types passed in are already limited to those that work in this file, so every one of them can be + * written with its plain word; `owner::name` also works and tells two additions with one word apart. + * The consumer's own and built-in declarations win first, then priority; * an equal-priority tie is rejected as ambiguous. */ internal class ConfigPolymorphicResolver( @@ -58,6 +72,7 @@ internal class ConfigPolymorphicResolver( (rawType.isAnnotationPresent(ConfigTypes::class.java) || annotations.any { it is ConfigTypes }) } + /** The declaration used to write an [implementation] of [baseType]. */ fun encodingType( baseType: Class<*>, annotations: List, @@ -69,6 +84,7 @@ internal class ConfigPolymorphicResolver( "Configuration implementation ${implementation.name} is not declared by ${baseType.name}", ) + /** The implementation class selected by discriminator [value] found at [path]; fails when unknown or ambiguous. */ fun decodingType( baseType: Class<*>, annotations: List, @@ -78,7 +94,7 @@ internal class ConfigPolymorphicResolver( val available = declarations(baseType, annotations) val matches = available.filter { it.matches(value, consumer) } val selected = matches.maxWithOrNull(preference()) - ?: throw IllegalArgumentException( + ?: throw UnknownConfigTypeException( "Unknown ${baseType.simpleName} type '$value' at $path; allowed: " + available.joinToString { it.name }, ) diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSchema.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSchema.kt index 7dae7e5b4..cb2ed9d9d 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSchema.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSchema.kt @@ -2,5 +2,6 @@ package org.pnfolder.pnlibrary.config.yaml /** Optional schema metadata understood by the managed YAML lifecycle. */ internal interface ConfigSchema { + /** Dotted paths of the fields marked `@ConfigRequired`; they must be present in an existing file. */ val requiredPaths: Set } diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSchemaInspector.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSchemaInspector.kt index 29238123f..988fc22a7 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSchemaInspector.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSchemaInspector.kt @@ -20,6 +20,7 @@ internal class ConfigSchemaInspector( private val introspector: ConfigObjectIntrospector, private val serializers: ConfigSerializerResolver, ) { + /** Dotted paths of every `@ConfigRequired` field of [rootType], including nested sections. */ fun requiredPaths(rootType: Class<*>): Set = requiredPaths(rootType, "") /** Builds comment and layout metadata used when rendering generated YAML. */ @@ -41,6 +42,7 @@ internal class ConfigSchemaInspector( ) } + /** Checks the range, not-blank and pattern annotations of [value] and its nested sections. */ fun validate(value: Any?, type: Class<*>): List = buildList { validateObject(value, type, "", this) } diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSerializerResolver.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSerializerResolver.kt index 9229b9b2d..dd02b83f1 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSerializerResolver.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSerializerResolver.kt @@ -14,16 +14,20 @@ import java.lang.reflect.Field * A serializer instance declared by an annotation is created once and then reused. */ internal class ConfigSerializerResolver( - private val registered: Map, ConfigSerializer<*>>, + private val registeredNow: () -> Map, ConfigSerializer<*>>, ) { + constructor(registered: Map, ConfigSerializer<*>>) : this({ registered }) + private val annotationInstances = mutableMapOf>, ConfigSerializer<*>>() + /** The serializer for [type]: an annotation on the class, then an exact registration, then a supertype one. */ @Suppress("UNCHECKED_CAST") fun forType(type: Class<*>): ConfigSerializer? { val annotated = type.getAnnotation(ConfigSerializeWith::class.java) ?.value ?.java ?.let(::annotationInstance) + val registered = registeredNow() val exact = registered[type] val assignable = registered.entries .firstOrNull { (supportedType, _) -> supportedType.isAssignableFrom(type) } @@ -31,6 +35,7 @@ internal class ConfigSerializerResolver( return (annotated ?: exact ?: assignable) as? ConfigSerializer } + /** The serializer named by `@ConfigSerializeWith` on [field], or `null`. */ @Suppress("UNCHECKED_CAST") fun forField(field: Field): ConfigSerializer? = field.getAnnotation(ConfigSerializeWith::class.java) @@ -38,24 +43,23 @@ internal class ConfigSerializerResolver( ?.java ?.let(::annotationInstance) as? ConfigSerializer + /** The shared instance of the `@ConfigTextForm` parser [type]. */ @Suppress("UNCHECKED_CAST") - fun textParser(type: Class>): - ConfigTextParser = synchronized(textParsers) { - textParsers.getOrPut(type) { - runCatchingNonFatal { type.getField("INSTANCE").get(null) }.getOrNull() - ?: type.getDeclaredConstructor().also { it.isAccessible = true }.newInstance() - } as ConfigTextParser - } + fun textParser(type: Class>): ConfigTextParser = helper(type) as ConfigTextParser + + /** The shared instance of the `@ConfigNodeForm` rewriter [type]. */ + fun nodeRewriter(type: Class): ConfigNodeRewriter = helper(type) as ConfigNodeRewriter - fun nodeRewriter(type: Class): ConfigNodeRewriter = synchronized(textParsers) { + private val textParsers = mutableMapOf, Any>() + + // A Kotlin `object` is used as it is; any other class needs a no-argument constructor. + private fun helper(type: Class<*>): Any = synchronized(textParsers) { textParsers.getOrPut(type) { runCatchingNonFatal { type.getField("INSTANCE").get(null) }.getOrNull() ?: type.getDeclaredConstructor().also { it.isAccessible = true }.newInstance() - } as ConfigNodeRewriter + } } - private val textParsers = mutableMapOf, Any>() - private fun annotationInstance(type: Class>): ConfigSerializer<*> = synchronized(annotationInstances) { annotationInstances.getOrPut(type) { diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSettingsEditor.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSettingsEditor.kt new file mode 100644 index 000000000..3d3b8be98 --- /dev/null +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSettingsEditor.kt @@ -0,0 +1,184 @@ +package org.pnfolder.pnlibrary.config.yaml + +import org.pnfolder.pnlibrary.api.config.ConfigDuration +import org.pnfolder.pnlibrary.api.config.ConfigEditException +import org.pnfolder.pnlibrary.api.config.ConfigEditable +import org.pnfolder.pnlibrary.api.config.ConfigHint +import org.pnfolder.pnlibrary.api.config.ConfigRange +import org.pnfolder.pnlibrary.api.config.ConfigSecret +import org.pnfolder.pnlibrary.api.config.ConfigSetting +import org.pnfolder.pnlibrary.api.config.ConfigSettingKind +import org.pnfolder.pnlibrary.api.config.ConfigStep +import java.lang.reflect.Field +import java.lang.reflect.Modifier +import java.util.Locale + +/** + * Finds the fields marked `@ConfigEditable` in a configuration class and changes them from typed text. + * + * Fields are found by looking through nested sections; a `@ConfigSecret` field and everything under it is never offered. + * Changing a value sets the field of the loaded object; the caller validates and writes the file and calls + * [Applied.restore] when that fails. + */ +internal class ConfigSettingsEditor( + private val introspector: ConfigObjectIntrospector, + rootType: Class<*>, +) { + private class Entry(val path: String, val chain: List, val annotation: ConfigEditable, val kind: ConfigSettingKind) { + val field: Field get() = chain.last() + } + + /** What [set] did: the setting with its new value, the old text, and a way to put the old value back. */ + class Applied(val setting: ConfigSetting, val previous: String?, val restore: () -> Unit) + + private val entries: Map = buildList { collect(rootType, "", emptyList(), 0, this) }.associateBy { it.path } + + /** Whether the class has no editable field. */ + val isEmpty: Boolean get() = entries.isEmpty() + + /** The settings with their current values taken from [root], or without values when it is `null`. */ + fun describe(root: Any?): List = entries.values.map { setting(it, root) } + + /** Sets the field behind [path] from [text]; nothing is written to disk here. */ + fun set(root: Any, path: String, text: String): Applied { + val entry = entries[path] ?: throw ConfigEditException( + "Такой настройки нет: $path." + if (entries.isEmpty()) "" else " Доступны: ${entries.keys.joinToString()}", + ) + val target = resolve(root, entry) + val old = entry.field.get(target) + val parsed = parse(entry, text) + entry.field.set(target, parsed) + val updated = setting(entry, root) + return Applied(updated, display(old)) { entry.field.set(target, old) } + } + + private fun resolve(root: Any, entry: Entry): Any { + var current = root + for (field in entry.chain.dropLast(1)) { + current = field.get(current) ?: throw ConfigEditException("Раздел ${field.name} пуст, значение не изменить") + } + return current + } + + private fun setting(entry: Entry, root: Any?): ConfigSetting { + val type = entry.field.type + val range = entry.field.getAnnotation(ConfigRange::class.java) + val value = root?.let { runCatching { display(entry.field.get(resolve(it, entry))) }.getOrNull() } + return ConfigSetting( + path = entry.path, + title = entry.annotation.title.ifBlank { introspector.key(entry.field) }, + description = entry.annotation.description, + kind = entry.kind, + value = value, + choices = choicesOf(entry), + min = range?.min?.takeIf { it != -Double.MAX_VALUE }, + max = range?.max?.takeIf { it != Double.MAX_VALUE }, + apply = entry.annotation.apply, + unit = entry.field.getAnnotation(ConfigStep::class.java)?.unit.orEmpty(), + step = entry.field.getAnnotation(ConfigStep::class.java)?.step ?: 1.0, + duration = entry.field.getAnnotation(ConfigDuration::class.java)?.unit, + format = hint(entry)?.format.orEmpty(), + examples = hint(entry)?.examples?.toList().orEmpty(), + ) + } + + private fun hint(entry: Entry): ConfigHint? = entry.field.getAnnotation(ConfigHint::class.java) + + private fun choicesOf(entry: Entry): List { + val type = entry.field.type + return if (type.isEnum) type.enumConstants.map { (it as Enum<*>).name } else hint(entry)?.values?.toList().orEmpty() + } + + private fun display(value: Any?): String? = when (value) { + null -> null + is Enum<*> -> value.name + else -> value.toString() + } + + private fun parse(entry: Entry, text: String): Any { + val type = entry.field.type + val raw = text.trim() + try { + return when (entry.kind) { + ConfigSettingKind.BOOLEAN -> when (raw.lowercase(Locale.ROOT)) { + "true", "on", "yes", "1", "вкл", "да" -> true + "false", "off", "no", "0", "выкл", "нет" -> false + else -> throw ConfigEditException("«$raw» не подходит: нужно true или false") + } + ConfigSettingKind.INTEGER -> { + val number = DurationText.parse(raw, entry.field.getAnnotation(ConfigDuration::class.java)?.unit) ?: raw.toLong() + when (type) { + Int::class.javaPrimitiveType, Int::class.javaObjectType -> Math.toIntExact(number) + Short::class.javaPrimitiveType, Short::class.javaObjectType -> number.also { require(it in Short.MIN_VALUE..Short.MAX_VALUE) }.toShort() + Byte::class.javaPrimitiveType, Byte::class.javaObjectType -> number.also { require(it in Byte.MIN_VALUE..Byte.MAX_VALUE) }.toByte() + else -> number + } + } + ConfigSettingKind.DECIMAL -> { + val number = raw.replace(',', '.').toDouble() + require(number.isFinite()) + if (type == Float::class.javaPrimitiveType || type == Float::class.javaObjectType) number.toFloat() else number + } + ConfigSettingKind.TEXT -> text + ConfigSettingKind.CHOICE -> if (type.isEnum) { + type.enumConstants.firstOrNull { (it as Enum<*>).name.equals(raw, ignoreCase = true) } + ?: throw ConfigEditException("«$raw» не подходит: нужно одно из ${choicesOf(entry).joinToString()}") + } else { + choicesOf(entry).firstOrNull { it.equals(raw, ignoreCase = true) } + ?: throw ConfigEditException("«$raw» не подходит: нужно одно из ${choicesOf(entry).joinToString()}") + } + } + } catch (error: ConfigEditException) { + throw error + } catch (error: RuntimeException) { + throw ConfigEditException("«$raw» не подходит для настройки ${entry.path}: ${hint(entry.kind)}", error) + } + } + + private fun hint(kind: ConfigSettingKind) = when (kind) { + ConfigSettingKind.INTEGER -> "нужно целое число" + ConfigSettingKind.DECIMAL -> "нужно число" + else -> "неверное значение" + } + + private fun collect(type: Class<*>, prefix: String, chain: List, depth: Int, out: MutableList) { + if (depth >= MAX_DEPTH) return + introspector.fields(type).forEach { field -> + if (field.isAnnotationPresent(ConfigSecret::class.java)) return@forEach + val path = prefix + introspector.key(field) + val annotation = field.getAnnotation(ConfigEditable::class.java) + val kind = kindOf(field) + if (annotation != null && kind != null && !Modifier.isFinal(field.modifiers)) { + out += Entry(path, chain + field, annotation, kind) + } else if (introspector.isSection(field.type)) { + collect(field.type, "$path.", chain + field, depth + 1, out) + } + } + } + + private fun kindOf(field: Field): ConfigSettingKind? { + val hint = field.getAnnotation(ConfigHint::class.java) + if (field.type == String::class.java && hint != null && hint.strict && hint.values.isNotEmpty()) return ConfigSettingKind.CHOICE + return kindOf(field.type) + } + + private fun kindOf(type: Class<*>): ConfigSettingKind? = when { + type == Boolean::class.javaPrimitiveType || type == Boolean::class.javaObjectType -> ConfigSettingKind.BOOLEAN + type in WHOLE -> ConfigSettingKind.INTEGER + type in DECIMAL -> ConfigSettingKind.DECIMAL + type == String::class.java -> ConfigSettingKind.TEXT + type.isEnum -> ConfigSettingKind.CHOICE + else -> null + } + + private companion object { + const val MAX_DEPTH = 8 + val WHOLE = setOf>( + Int::class.javaPrimitiveType!!, Int::class.javaObjectType, Long::class.javaPrimitiveType!!, Long::class.javaObjectType, + Short::class.javaPrimitiveType!!, Short::class.javaObjectType, Byte::class.javaPrimitiveType!!, Byte::class.javaObjectType, + ) + val DECIMAL = setOf>( + Double::class.javaPrimitiveType!!, Double::class.javaObjectType, Float::class.javaPrimitiveType!!, Float::class.javaObjectType, + ) + } +} diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigValueText.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigValueText.kt index d32d45fb8..bfba9d42b 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigValueText.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigValueText.kt @@ -10,9 +10,11 @@ internal fun shown(raw: Any?): String { return if (text.length > MAX_SHOWN) text.take(MAX_SHOWN) + "..." else text } +/** The " Reason: ..." tail of an error message, or an empty text when [error] has no useful reason. */ internal fun reasonSuffix(error: Exception): String = if (error is IllegalArgumentException && !error.message.isNullOrBlank()) " Reason: ${error.message}" else "" +/** Replaces a legacy `@ConfigAlias` spelling in [value] with the enum constant name; other values pass unchanged. */ internal fun enumAlias(type: Class<*>, value: Any?, path: String): Any? { if (!type.isEnum || value !is String) return value val matches = type.enumConstants.map { it as Enum<*> }.filter { constant -> diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigurationFileStore.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigurationFileStore.kt index f987c92ff..50762f1a1 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigurationFileStore.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigurationFileStore.kt @@ -14,14 +14,21 @@ internal class ConfigurationFileStore( private val file: File, private val validator: (String) -> Unit, ) { + /** Converts line endings to a single newline and ends the text with exactly one newline. */ fun normalize(content: String): String = content.replace("\r\n", "\n").trimEnd() + "\n" - fun write(content: String) { + /** Replaces the file with [content] atomically, after the validator accepted it as a temporary file. */ + fun write(content: String) = replace(content, validator) + + /** Like [write] for a document the caller has just decoded and validated, so it is not decoded a second time. */ + fun writeDecoded(content: String) = replace(content) {} + + private fun replace(content: String, check: (String) -> Unit) { val normalized = normalize(content) val temporary = Files.createTempFile(file.absoluteFile.parentFile.toPath(), "${file.name}.", ".tmp") try { Files.write(temporary, normalized.toByteArray(Charsets.UTF_8)) - validator(normalized) + check(normalized) AtomicFiles.move(temporary, file.toPath()) } finally { Files.deleteIfExists(temporary) diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/DurationText.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/DurationText.kt new file mode 100644 index 000000000..60fce82bc --- /dev/null +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/DurationText.kt @@ -0,0 +1,29 @@ +package org.pnfolder.pnlibrary.config.yaml + +import java.util.concurrent.TimeUnit + +/** Reads a length of time typed as `1h30m`, `90 мин` or `45s` into the unit a setting keeps. */ +internal object DurationText { + private val PART = Regex("""(\d+(?:[.,]\d+)?)\s*(ms|мс|сек|с|s|мин|м|m|ч|h|д|d)""") + + /** The time in [unit], or `null` when [text] has no unit letters (a plain number) or [unit] is `null`. */ + fun parse(text: String, unit: TimeUnit?): Long? { + if (unit == null) return null + val cleaned = text.trim().lowercase() + val parts = PART.findAll(cleaned).toList() + if (parts.isEmpty() || parts.joinToString("") { it.value }.replace(" ", "") != cleaned.replace(" ", "")) return null + val millis = parts.sumOf { part -> + val amount = part.groupValues[1].replace(',', '.').toDouble() + (amount * millisOf(part.groupValues[2])).toLong() + } + return unit.convert(millis, TimeUnit.MILLISECONDS) + } + + private fun millisOf(letters: String): Long = when (letters) { + "ms", "мс" -> 1L + "с", "s", "сек" -> 1_000L + "м", "m", "мин" -> 60_000L + "ч", "h" -> 3_600_000L + else -> 86_400_000L + } +} diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/LegacySupportNote.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/LegacySupportNote.kt new file mode 100644 index 000000000..e6b4ea4c8 --- /dev/null +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/LegacySupportNote.kt @@ -0,0 +1,28 @@ +package org.pnfolder.pnlibrary.config.yaml + +/** + * Cleans up the support note that older versions of pnLibrary wrote into every configuration file. + * + * The note (a Russian line, an English line and one or more link lines) is no longer written: help links live in the + * generated files of the library's own folder. A file that still carries the note loses it the next time it is written. + * Nothing but the note lines is touched. + */ +internal object LegacySupportNote { + private val OLD_PREFIXES = listOf( + "# Если у вас возникли проблемы с плагином", + "# If you have any problem with a plugin", + ) + private val LINK_LINE = Regex("^# (\\S+: )?https?://\\S+$") + + /** Returns [content] without any old support note; content without a note is returned unchanged. */ + fun removeFrom(content: String): String { + val kept = ArrayList() + var inNote = false + for (line in content.split('\n')) { + val isNote = OLD_PREFIXES.any(line::startsWith) || (inNote && LINK_LINE.matches(line)) + inNote = isNote + if (!isNote) kept.add(line) + } + return kept.joinToString("\n") + } +} diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/SupportHeader.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/SupportHeader.kt deleted file mode 100644 index a54d05b8c..000000000 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/SupportHeader.kt +++ /dev/null @@ -1,48 +0,0 @@ -package org.pnfolder.pnlibrary.config.yaml - -import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity - -/** - * The Russian and English support note every configuration file written through pnLibrary carries. - * - * It goes right after the `_config-version` marker, or at the top when the file has none. The note is rebuilt from - * [CHANNELS] every time, so a file with an older note (one channel fewer, an old link) gets the current one instead - * of a second copy. To add a support platform, add one line to [CHANNELS]; every configuration gets it on the next load. - */ -internal object SupportHeader { - /** One place where administrators get help. */ - class Channel(val name: String, val url: String) - - /** The support platforms listed in every configuration, in this order. */ - val CHANNELS: List = listOf( - Channel("Discord", PnLibraryIdentity.SUPPORT_URL), - ) - - private const val RUSSIAN = "# Если у вас возникли проблемы с плагином, пишите нам: мы всегда рады помочь." - private const val ENGLISH = "# If you have any problem with a plugin, write to us: we are always happy to help." - private val OLD_PREFIXES = listOf( - "# Если у вас возникли проблемы с плагином", - "# If you have any problem with a plugin", - ) - private val LINK_LINE = Regex("^# (\\S+: )?https?://\\S+$") - - private val note: List = listOf(RUSSIAN, ENGLISH) + CHANNELS.map { "# ${it.name}: ${it.url}" } - - /** Returns [content] with exactly one current support note. */ - fun apply(content: String): String { - val lines = withoutNote(content.split('\n')) - val at = lines.indexOfFirst { it.startsWith("_config-version:") } + 1 - return (lines.take(at) + note + lines.drop(at)).joinToString("\n") - } - - private fun withoutNote(lines: List): List { - val kept = ArrayList(lines.size) - var inNote = false - for (line in lines) { - val isNote = OLD_PREFIXES.any(line::startsWith) || (inNote && LINK_LINE.matches(line)) - inNote = isNote - if (!isNote) kept.add(line) - } - return kept - } -} diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/YamlDefaultsMerger.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/YamlDefaultsMerger.kt index 564f1cc21..d4f56bd8e 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/YamlDefaultsMerger.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/YamlDefaultsMerger.kt @@ -11,10 +11,18 @@ import org.pnfolder.pnlibrary.api.config.MissingValuePolicy * section with four spaces must not get a second copy of every key in it. */ internal object YamlDefaultsMerger { + /** + * Outcome of [merge]. + * + * @property content the merged YAML text + * @property addedPaths dotted paths of the keys inserted from the defaults + * @property addedComments dotted paths of the keys that received a default comment + */ data class Result(val content: String, val addedPaths: List, val addedComments: List) { val changed: Boolean get() = addedPaths.isNotEmpty() || addedComments.isNotEmpty() } + /** Adds to [existing] the keys of [defaults] allowed by [values] and the comments allowed by [comments]. */ fun merge( existing: String, defaults: String, @@ -33,6 +41,7 @@ internal object YamlDefaultsMerger { return Result(target.joinToString("\n").trimEnd() + "\n", added, commented) } + /** Dotted paths of every key in [yaml], parents before their children. */ fun paths(yaml: String): List { val lines = yaml.lines() return collect(lines, 0, lines.size, 0, emptyList()).map { it.dotted } diff --git a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/YamlSchemaDecorator.kt b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/YamlSchemaDecorator.kt index ee87a666b..3047b1524 100644 --- a/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/YamlSchemaDecorator.kt +++ b/modules/features/config-runtime/src/main/kotlin/org/pnfolder/pnlibrary/config/yaml/YamlSchemaDecorator.kt @@ -1,6 +1,12 @@ package org.pnfolder.pnlibrary.config.yaml -/** Metadata used to place documentation around one generated YAML field. */ +/** + * Metadata used to place documentation around one generated YAML field. + * + * @property comments comment lines written above the field + * @property separateWithBlankLine whether an empty line precedes the comments + * @property children metadata of the nested fields, by YAML key + */ internal data class YamlFieldMetadata( val comments: List, val separateWithBlankLine: Boolean, diff --git a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigAdditionsTest.kt b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigAdditionsTest.kt new file mode 100644 index 000000000..faf96e816 --- /dev/null +++ b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigAdditionsTest.kt @@ -0,0 +1,333 @@ +package org.pnfolder.pnlibrary.config + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.config.ConfigAddress +import org.pnfolder.pnlibrary.api.config.ConfigId +import org.pnfolder.pnlibrary.api.config.ConfigScope +import org.pnfolder.pnlibrary.api.config.ConfigSerializationContext +import org.pnfolder.pnlibrary.api.config.ConfigSerializer +import org.pnfolder.pnlibrary.api.config.ConfigTypeConflict +import org.pnfolder.pnlibrary.api.config.extensions +import org.pnfolder.pnlibrary.api.config.serializer +import org.pnfolder.pnlibrary.api.config.serializerFor +import org.pnfolder.pnlibrary.api.config.type +import org.pnfolder.pnlibrary.api.config.yaml +import org.pnfolder.pnlibrary.api.plugin.ModuleId +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.nio.file.Files +import java.nio.file.Path + +data class Place(val world: String = "none", val x: Int = 0) + +/** Writes a place as `world,x`. */ +class PlaceSerializer(private val tag: String = "") : ConfigSerializer { + override fun serialize(value: Place, context: ConfigSerializationContext): Any = "$tag${value.world},${value.x}" + override fun deserialize(value: Any?, context: ConfigSerializationContext): Place { + val parts = value.toString().removePrefix(tag).split(',') + return Place(parts[0], parts[1].toInt()) + } +} + +class PlaceFile { + var spawn: Place = Place("lobby", 1) +} + +/** Serializers and words that one plugin adds to other plugins' files: to all of them, one plugin, one module or one file. */ +class ConfigAdditionsTest { + @TempDir lateinit var server: Path + + private val plugins: Path get() = server.resolve("plugins") + + private fun scope(service: ConfigurationServiceImpl, plugin: String, module: String = "main"): ConfigScope { + val folder = plugins.resolve(plugin).also { Files.createDirectories(it) } + return service.scope(FakeConfigOwner(folder.toFile()), PluginId.of("$plugin-$module"), PluginId.of(plugin), ModuleId.of(module)) + } + + private fun write(plugin: String, name: String, text: String) { + val file = plugins.resolve(plugin).resolve(name) + Files.createDirectories(file.parent) + Files.writeString(file, text) + } + + private fun spawnOf(scope: ConfigScope, file: String = "places.yml"): Place = + scope.yaml(file) { PlaceFile() }.load().value.spawn + + private fun spawnOrNull(scope: ConfigScope, file: String = "places.yml"): Place? = runCatching { spawnOf(scope, file) }.getOrNull() + + @Test + fun `the address star covers every file`() { + val all = ConfigAddress.parse("*") + + assertEquals(ConfigAddress.Level.ALL, all.level) + assertTrue(all.isAll) + assertEquals("*", all.toString()) + assertTrue(all.matches(ConfigId.parse("quests/main:a.yml"))) + assertTrue(all.matches(ConfigId.parse("shop/extra:b.yml"))) + assertTrue(all.overlaps(ConfigAddress.parse("shop"))) + assertFalse(ConfigAddress.parse("shop") == all) + assertEquals(ConfigAddress.everywhere(), all) + // A plugin named "all" is an ordinary plugin and is not mixed up with everything + assertFalse(ConfigAddress.plugin("all") == all) + assertFalse(ConfigAddress.plugin("all").isAll) + assertThrows(IllegalStateException::class.java) { all.plugin } + assertThrows(IllegalArgumentException::class.java) { ConfigId.parse("*") } + } + + @Test + fun `a written file shows whether the serializer reaches it and a registration can be switched`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val scope = scope(service, "shop") + val first = scope.yaml("a.yml") { PlaceFile() }.also { it.load() } + val second = scope.yaml("b.yml") { PlaceFile() }.also { it.load() } + fun text(name: String) = Files.readString(plugins.resolve("shop/$name")) + + scope.serializerFor(PlaceSerializer()).into(first).register().use { + first.resetToDefaults() + second.resetToDefaults() + assertTrue(text("a.yml").contains("spawn: lobby,1"), text("a.yml")) + assertFalse(text("b.yml").contains("spawn: lobby,1"), text("b.yml")) + } + + // Closed: the file is written the old way again + first.resetToDefaults() + assertFalse(text("a.yml").contains("spawn: lobby,1"), text("a.yml")) + + scope.serializerFor(PlaceSerializer()).into(scope).register() + second.resetToDefaults() + assertTrue(text("b.yml").contains("spawn: lobby,1"), text("b.yml")) + } + } + + @Test + fun `an address is built from plugin, module and file without writing a string`() { + val module = ConfigAddress.plugin("shop").inModule("main") + val file = module.inFile("rewards.yml") + + assertEquals("shop/main:rewards.yml", file.toString()) + assertEquals(ConfigAddress.parse("shop/main"), module) + assertEquals(ConfigAddress.parse("shop/main:@server/bukkit.yml"), module.inFile("bukkit.yml", org.pnfolder.pnlibrary.api.config.ConfigRoot.SERVER)) + assertEquals(ConfigAddress.Level.FILE, file.level) + assertThrows(IllegalArgumentException::class.java) { ConfigAddress.plugin("shop").inFile("a.yml") } + assertThrows(IllegalArgumentException::class.java) { file.inModule("other") } + } + + @Test + fun `into takes a plugin, a scope or a catalog entry as they are`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + write("shop", "places.yml", "spawn: arena,7\n") + write("other", "places.yml", "spawn: hub,3\n") + write("third", "places.yml", "spawn: end,9\n") + val shop = scope(service, "shop") + val other = scope(service, "other") + val third = scope(service, "third") + val thirdFile = third.yaml("places.yml") { PlaceFile() } + val publisher = scope(service, "quests") + + publisher.serializerFor(PlaceSerializer()).into(PluginId.of("shop")).register() + publisher.serializerFor(PlaceSerializer()).into(other).register() + publisher.serializerFor(PlaceSerializer()).into(service.all().single { it.plugin.value == "third" }).register() + + assertEquals(Place("arena", 7), spawnOf(shop)) + assertEquals(Place("hub", 3), spawnOf(other)) + assertEquals(Place("end", 9), thirdFile.reload().value.spawn) + } + } + + @Test + fun `without an address a serializer works only in its own module`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + write("shop", "places.yml", "spawn: arena,7\n") + scope(service, "quests").serializerFor(PlaceSerializer()).register() + + // Nobody told shop how to read a place, so it is read as a section and the line does not fit + assertFalse(spawnOrNull(scope(service, "shop")) == Place("arena", 7)) + } + } + + @Test + fun `a serializer added to a plugin works in its files`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + write("shop", "places.yml", "spawn: arena,7\n") + val shop = scope(service, "shop") + val other = scope(service, "other") + scope(service, "quests").serializerFor(PlaceSerializer()).into("shop").register() + write("other", "places.yml", "spawn: arena,7\n") + + assertEquals(Place("arena", 7), spawnOf(shop)) + assertFalse(spawnOrNull(other) == Place("arena", 7), "another plugin is not covered") + } + } + + @Test + fun `a serializer added to everything works in every plugin`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + write("shop", "places.yml", "spawn: arena,7\n") + write("other", "places.yml", "spawn: hub,3\n") + scope(service, "quests").serializerFor(PlaceSerializer()).everywhere().register() + + assertEquals(Place("arena", 7), spawnOf(scope(service, "shop"))) + assertEquals(Place("hub", 3), spawnOf(scope(service, "other"))) + assertEquals(listOf("quests"), service.serializers().map { it.owner.value }) + } + } + + @Test + fun `a serializer can be limited to a module or one file`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + write("shop", "one.yml", "spawn: a,1\n") + write("shop", "two.yml", "spawn: b,2\n") + write("shop", "three.yml", "spawn: c,3\n") + val main = scope(service, "shop") + val extra = scope(service, "shop", "extra") + val publisher = scope(service, "quests") + publisher.serializerFor(PlaceSerializer()).into("shop/main:one.yml").register() + + assertEquals(Place("a", 1), spawnOf(main, "one.yml")) + assertFalse(spawnOrNull(main, "two.yml") == Place("b", 2), "another file of the module is not covered") + + publisher.serializerFor(PlaceSerializer("x:")).into("shop/extra").register() + Files.writeString(plugins.resolve("shop/three.yml"), "spawn: x:c,3\n") + assertEquals(Place("c", 3), spawnOf(extra, "three.yml")) + } + } + + @Test + fun `the module's own serializer is not replaced and the higher priority wins among additions`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + write("shop", "places.yml", "spawn: own:arena,7\n") + val shop = scope(service, "shop").serializer(PlaceSerializer("own:")) + scope(service, "quests").serializerFor(PlaceSerializer("low:")).priority(1).everywhere().register() + + assertEquals(Place("arena", 7), spawnOf(shop)) + + write("other", "places.yml", "spawn: high:hub,3\n") + scope(service, "pnmaps").serializerFor(PlaceSerializer("high:")).priority(9).everywhere().register() + assertEquals(Place("hub", 3), spawnOf(scope(service, "other"))) + } + } + + @Test + fun `a module that refuses additions keeps its files as they were`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + write("shop", "places.yml", "spawn: arena,7\n") + write("other", "places.yml", "spawn: arena,7\n") + val shop = scope(service, "shop") + shop.extensions { denyAll() } + val publisher = scope(service, "quests") + + assertThrows(IllegalStateException::class.java) { publisher.serializerFor(PlaceSerializer()).into("shop").register() } + publisher.serializerFor(PlaceSerializer()).everywhere().register() + + assertFalse(spawnOrNull(shop) == Place("arena", 7), "the refusing module is skipped by an addition for everybody") + assertEquals(Place("arena", 7), spawnOf(scope(service, "other"))) + } + } + + @Test + fun `ordinary types cannot be taken over for other plugins`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val publisher = scope(service, "quests") + val text = object : ConfigSerializer { + override fun serialize(value: String, context: ConfigSerializationContext): Any = value.reversed() + override fun deserialize(value: Any?, context: ConfigSerializationContext): String = value.toString().reversed() + } + + assertThrows(IllegalArgumentException::class.java) { publisher.serializerFor(String::class.java, text).everywhere().register() } + assertThrows(IllegalArgumentException::class.java) { publisher.serializerFor(String::class.java, text).into("shop").register() } + // Its own module may do what it likes + publisher.serializerFor(String::class.java, text).register() + } + } + + @Test + fun `closing the registration or the publisher takes the serializer back`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + write("shop", "places.yml", "spawn: arena,7\n") + val publisher = scope(service, "quests") + val registration = publisher.serializerFor(PlaceSerializer()).into("shop").register() + + assertEquals(1, service.serializers().size) + assertThrows(IllegalStateException::class.java) { publisher.serializerFor(PlaceSerializer()).into("shop/main").register() } + registration.close() + assertTrue(service.serializers().isEmpty()) + assertFalse(registration.isActive) + + publisher.serializerFor(PlaceSerializer()).into("shop").register() + publisher.close() + assertTrue(service.serializers().isEmpty()) + } + } + + @Test + fun `a word added for everything works in every plugin but never replaces a word of the file's plugin`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + write("quests", "awards.yml", "awards:\n - type: item\n material: GOLD\n") + write("shop", "awards.yml", "awards:\n - type: item\n material: GOLD\n") + val quests = scope(service, "quests") + val shop = scope(service, "shop") + // quests has its own meaning of the word item + quests.type().name("item").register() + scope(service, "questitems").type().name("item").everywhere().register() + + val own = quests.yaml("awards.yml") { AwardsFile() }.load().value.awards.single() + val added = shop.yaml("awards.yml") { AwardsFile() }.load().value.awards.single() + + assertTrue(own is GoldAward, "the owner's word wins in its own file: $own") + assertEquals(ItemAward("GOLD", 1), added) + } + } + + private fun first(scope: ConfigScope): Award { + val file = scope.get("awards.yml") ?: scope.yaml("awards.yml") { AwardsFile() } + @Suppress("UNCHECKED_CAST") + return (file as org.pnfolder.pnlibrary.api.config.ManagedConfig).reload().value.awards.first() + } + + private fun item() = "awards:\n - type: pick\n material: GOLD\n" + + @Test + fun `a taken word fails by default, is kept on request and is replaced on request`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + write("quests", "awards.yml", item()) + val quests = scope(service, "quests") + val library = scope(service, "lib") + library.type().name("pick").everywhere().register() + + assertThrows(IllegalArgumentException::class.java) { + library.type().name("pick").everywhere().register() + } + val kept = library.type().name("pick").everywhere().onConflict(ConfigTypeConflict.KEEP).register() + assertFalse(kept.isActive) + assertTrue(first(quests) is ItemAward) + + val replaced = library.type().name("pick").everywhere().onConflict(ConfigTypeConflict.REPLACE).register() + assertTrue(replaced.isActive) + assertTrue(first(quests) is GoldAward) + } + } + + @Test + fun `one word can be published for several places and withdrawn together`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + write("quests", "awards.yml", item()) + write("shop", "awards.yml", item()) + write("farm", "awards.yml", item()) + val publisher = scope(service, "lib") + + val handles = publisher.type().name("pick") + .registerEach(listOf(ConfigAddress.plugin("quests"), ConfigAddress.plugin("shop"))) + + assertEquals(2, handles.size) + assertTrue(first(scope(service, "quests")) is ItemAward) + assertTrue(first(scope(service, "shop")) is ItemAward) + assertTrue(runCatching { first(scope(service, "farm")) }.getOrNull() !is ItemAward) + handles.forEach { it.close() } + assertTrue(runCatching { first(scope(service, "quests")) }.getOrNull() !is ItemAward) + } + } +} diff --git a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigCatalogTest.kt b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigCatalogTest.kt new file mode 100644 index 000000000..82ce4d51f --- /dev/null +++ b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigCatalogTest.kt @@ -0,0 +1,516 @@ +package org.pnfolder.pnlibrary.config + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.config.ConfigId +import org.pnfolder.pnlibrary.api.config.ConfigOptions +import org.pnfolder.pnlibrary.api.config.ConfigPolymorphic +import org.pnfolder.pnlibrary.api.config.ConfigRoot +import org.pnfolder.pnlibrary.api.config.ConfigScope +import org.pnfolder.pnlibrary.api.config.ConfigType +import org.pnfolder.pnlibrary.api.config.ConfigTypes +import org.pnfolder.pnlibrary.api.config.UnknownTypePolicy +import org.pnfolder.pnlibrary.api.config.extensions +import org.pnfolder.pnlibrary.api.config.type +import org.pnfolder.pnlibrary.api.config.yaml +import org.pnfolder.pnlibrary.api.config.yamlAt +import org.pnfolder.pnlibrary.api.plugin.ModuleId +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.nio.file.Files +import java.nio.file.Path + +@ConfigPolymorphic(discriminator = "type") +@ConfigTypes(ConfigType(MoneyAward::class, "money")) +interface Award + +data class MoneyAward(var amount: Int = 0) : Award +data class ItemAward(var material: String = "STONE", var count: Int = 1) : Award +data class GoldAward(var grams: Int = 1) : Award + +data class AwardsFile(var awards: List = listOf(MoneyAward(5))) + +/** Several plugins in one server folder: `plugins//` for each, so `PLUGINS` and `SERVER` roots exist. */ +class ConfigCatalogTest { + @TempDir lateinit var server: Path + + private val plugins: Path get() = server.resolve("plugins") + + private fun scope( + service: ConfigurationServiceImpl, plugin: String, module: String = "main", + ): ConfigScope { + val folder = plugins.resolve(plugin).also { Files.createDirectories(it) } + return service.scope(FakeConfigOwner(folder.toFile()), PluginId.of("$plugin-$module"), PluginId.of(plugin), ModuleId.of(module)) + } + + private fun write(plugin: String, name: String, text: String) { + val file = plugins.resolve(plugin).resolve(name) + Files.createDirectories(file.parent) + Files.writeString(file, text) + } + + private val skipping = ConfigOptions.builder().unknownTypes(UnknownTypePolicy.SKIP).build() + + // ── Identifiers and lookup ──────────────────────────────────────────────────────────────── + + @Test + fun `registered files are listed under plugin, module and path`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val main = scope(service, "quests") + val extra = scope(service, "quests", "extra") + scope(service, "shop").yaml("prices.yml") { AwardsFile() } + val awards = main.yaml("awards.yml") { AwardsFile() } + extra.yaml("rewards/daily.yml") { AwardsFile() } + + assertEquals( + listOf("shop/main:prices.yml", "quests/main:awards.yml", "quests/extra:rewards/daily.yml"), + service.all().map { it.id.toString() }, + ) + assertEquals(2, service.find("quests").size) + assertEquals(listOf("quests/main:awards.yml"), service.find("quests/main").map { it.id.toString() }) + assertEquals(1, service.find("quests/extra:rewards/daily.yml").size) + assertTrue(service.find("nobody").isEmpty()) + assertEquals(awards.id, ConfigId.of("quests", "main", "awards.yml")) + assertSame(awards, service.get("quests/main:awards.yml")) + assertSame(awards, main.get("awards.yml")) + assertNull(service.get("quests/main:missing.yml")) + assertEquals(AwardsFile::class.java, service.require("quests/main:awards.yml").info?.modelType) + assertEquals(3, service.byModel(AwardsFile::class.java).size) + assertTrue(service.byModel(String::class.java).isEmpty()) + } + } + + @Test + fun `a scope lists only its own files and require names the registered ones`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val main = scope(service, "quests") + scope(service, "quests", "extra").yaml("other.yml") { AwardsFile() } + main.yaml("awards.yml") { AwardsFile() } + + assertEquals(listOf("awards.yml"), main.list().map { it.path }) + assertEquals("quests", main.plugin.value) + assertEquals("main", main.module.value) + val error = assertThrows(IllegalStateException::class.java) { main.require("nope.yml") } + assertTrue(error.message.orEmpty().contains("awards.yml"), error.message) + assertThrows(IllegalStateException::class.java) { service.require("quests/main:nope.yml") } + } + } + + @Test + fun `info describes a file without values and follows its life`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val config = scope(service, "quests").yaml("awards.yml") { AwardsFile() } + + val before = requireNotNull(config.info) + assertFalse(before.exists) + assertFalse(before.isLoaded) + assertNull(before.loadedAt) + config.load() + val after = requireNotNull(config.info) + assertTrue(after.exists) + assertTrue(after.isLoaded) + assertNotNull(after.loadedAt) + assertEquals(plugins.resolve("quests").resolve("awards.yml"), after.file) + config.unload() + assertFalse(requireNotNull(config.info).isLoaded) + } + } + + @Test + fun `closing a scope removes its files from the catalog`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val scope = scope(service, "quests") + scope.yaml("awards.yml") { AwardsFile() } + assertEquals(1, service.all().size) + scope.close() + assertTrue(service.all().isEmpty()) + } + } + + // ── Types added to another plugin's files ───────────────────────────────────────────────── + + @Test + fun `a plugin teaches another plugin's file a new word, and the file reads it`() { + write("quests", "awards.yml", "awards:\n - type: money\n amount: 7\n - type: item\n material: DIAMOND\n count: 3\n") + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val awards = scope(service, "quests").yaml("awards.yml") { AwardsFile() } + scope(service, "questitems").type().name("item").into("quests/main:awards.yml").register() + + assertEquals(listOf(MoneyAward(7), ItemAward("DIAMOND", 3)), awards.load().value.awards) + } + } + + @Test + fun `without the word the file fails by default and names the element`() { + write("quests", "awards.yml", "awards:\n - type: item\n material: DIAMOND\n") + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val awards = scope(service, "quests").yaml("awards.yml") { AwardsFile() } + + val error = assertThrows(IllegalArgumentException::class.java) { awards.load() } + assertTrue(error.message.orEmpty().contains("item"), error.message) + } + } + + @Test + fun `skipping keeps the element in the file and reads it again when the word appears`() { + val text = "awards:\n - type: money\n amount: 7\n - type: item\n material: DIAMOND\n count: 3\n" + write("quests", "awards.yml", text) + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val awards = scope(service, "quests").yaml("awards.yml", skipping) { AwardsFile() } + + assertEquals(listOf(MoneyAward(7)), awards.load().value.awards) + assertEquals(1, requireNotNull(awards.info).skippedUnknownTypes.size) + assertTrue(Files.readString(plugins.resolve("quests").resolve("awards.yml")).contains("DIAMOND"), "the element stays in the file") + // Saving would drop the skipped element from the file, so it is refused. + assertThrows(IllegalStateException::class.java) { awards.save() } + assertThrows(IllegalStateException::class.java) { awards.update { it } } + + scope(service, "questitems").type().name("item").into("quests/main:awards.yml").register() + + // Registering the word read the file again by itself. + assertEquals(listOf(MoneyAward(7), ItemAward("DIAMOND", 3)), awards.get().awards) + assertTrue(requireNotNull(awards.info).skippedUnknownTypes.isEmpty()) + awards.save() + assertTrue(Files.readString(plugins.resolve("quests").resolve("awards.yml")).contains("DIAMOND")) + } + } + + @Test + fun `a word added to a module covers its files and no other module`() { + val text = "awards:\n - type: item\n" + write("quests", "a.yml", text) + write("quests", "b.yml", text) + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val main = scope(service, "quests") + val extra = scope(service, "quests", "extra") + val inMain = main.yaml("a.yml", skipping) { AwardsFile() } + val inExtra = extra.yaml("b.yml", skipping) { AwardsFile() } + scope(service, "questitems").type().name("item").into("quests/main").register() + + assertEquals(1, inMain.loadValue().awards.size) + assertTrue(inExtra.loadValue().awards.isEmpty(), "quests/extra is not covered") + } + } + + @Test + fun `a word added to a plugin covers every module of it`() { + val text = "awards:\n - type: item\n" + write("quests", "a.yml", text) + write("quests", "b.yml", text) + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + scope(service, "questitems").type().name("item").into("quests").register() + val inMain = scope(service, "quests").yaml("a.yml") { AwardsFile() } + val inExtra = scope(service, "quests", "extra").yaml("b.yml") { AwardsFile() } + + assertEquals(1, inMain.loadValue().awards.size) + assertEquals(1, inExtra.loadValue().awards.size) + } + } + + @Test + fun `a word can be aimed at a registered file object`() { + write("quests", "awards.yml", "awards:\n - type: stack\n") + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val awards = scope(service, "quests").yaml("awards.yml") { AwardsFile() } + scope(service, "questitems").type().name("item").alias("stack").into(awards).register() + + assertEquals(1, awards.loadValue().awards.size) + } + } + + @Test + fun `a word stops working after the plugin that added it is closed`() { + write("quests", "awards.yml", "awards:\n - type: item\n") + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val awards = scope(service, "quests").yaml("awards.yml", skipping) { AwardsFile() } + val items = scope(service, "questitems") + items.type().name("item").into("quests/main:awards.yml").register() + assertEquals(1, awards.loadValue().awards.size) + + items.close() + + assertTrue(awards.reloadValue().awards.isEmpty()) + } + } + + @Test + fun `a file only sees words that cover it`() { + write("quests", "awards.yml", "awards:\n - type: item\n") + write("shop", "awards.yml", "awards:\n - type: item\n") + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + scope(service, "questitems").type().name("item").into("quests").register() + val shop = scope(service, "shop").yaml("awards.yml", skipping) { AwardsFile() } + + assertTrue(shop.loadValue().awards.isEmpty()) + } + } + + @Test + fun `without into a word works in the module that registers it`() { + write("quests", "awards.yml", "awards:\n - type: item\n") + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val main = scope(service, "quests") + main.type().name("item").register() + + assertEquals(1, main.yaml("awards.yml") { AwardsFile() }.loadValue().awards.size) + } + } + + @Test + fun `types lists the words of a base type and who added them`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + scope(service, "questitems").type().name("item").alias("stack").priority(4).into("quests").register() + + val words = service.types(Award::class.java) + assertEquals(listOf("money", "item"), words.map { it.name }) + assertNull(words[0].owner) + assertEquals("questitems", words[1].owner?.value) + assertEquals(setOf("stack"), words[1].aliases) + assertEquals(4, words[1].priority) + assertEquals("quests", words[1].target.toString()) + } + } + + // ── Protection ──────────────────────────────────────────────────────────────────────────── + + @Test + fun `a word that the base type declares cannot be taken`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val error = assertThrows(IllegalArgumentException::class.java) { + scope(service, "evil").type().name("money").into("quests").register() + } + assertTrue(error.message.orEmpty().contains("money"), error.message) + assertThrows(IllegalArgumentException::class.java) { + scope(service, "evil").type().name("fine").alias("MONEY").into("quests").register() + } + } + } + + @Test + fun `a word that the file's own plugin published cannot be taken by another plugin`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + scope(service, "quests").type().name("gold").register() + + assertThrows(IllegalArgumentException::class.java) { + scope(service, "questitems").type().name("gold").into("quests").register() + } + // A different word is fine. + scope(service, "questitems").type().name("item").into("quests").register() + } + } + + @Test + fun `one plugin cannot publish the same word twice for overlapping files`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val items = scope(service, "questitems") + items.type().name("item").into("quests").register() + + assertThrows(IllegalArgumentException::class.java) { + items.type().name("item").into("quests/main:awards.yml").register() + } + // Files that no earlier registration covers are fine. + items.type().name("item").into("shop").register() + } + } + + @Test + fun `two plugins may add one word and a priority decides`() { + write("quests", "awards.yml", "awards:\n - type: thing\n") + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val awards = scope(service, "quests").yaml("awards.yml") { AwardsFile() } + scope(service, "one").type().name("thing").priority(1).into("quests").register() + scope(service, "two").type().name("thing").priority(9).into("quests").register() + + assertTrue(awards.loadValue().awards.single() is GoldAward) + } + } + + @Test + fun `a module can refuse additions from plugins and allow only some`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val quests = scope(service, "quests") + quests.extensions { allow("questitems") } + + scope(service, "questitems").type().name("item").into("quests").register() + val error = assertThrows(IllegalStateException::class.java) { + scope(service, "stranger").type().name("gold").into("quests/main").register() + } + assertTrue(error.message.orEmpty().contains("stranger"), error.message) + } + } + + @Test + fun `a module that closes itself later hides words that were added before`() { + write("quests", "awards.yml", "awards:\n - type: item\n") + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val quests = scope(service, "quests") + val awards = quests.yaml("awards.yml", skipping) { AwardsFile() } + scope(service, "questitems").type().name("item").into("quests").register() + assertEquals(1, awards.loadValue().awards.size) + + quests.extensions { denyAll() } + + assertTrue(awards.reloadValue().awards.isEmpty()) + } + } + + // ── Roots and read-only files ───────────────────────────────────────────────────────────── + + @Test + fun `read-only reads a file as it is and never writes it`() { + val text = "awards:\n - type: money\n amount: 9\n# keep me\n" + write("quests", "awards.yml", text) + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val options = ConfigOptions.builder().readOnly().build() + val awards = scope(service, "quests").yaml("awards.yml", options) { AwardsFile() } + + assertEquals(MoneyAward(9), awards.loadValue().awards.single()) + assertEquals(text, Files.readString(plugins.resolve("quests").resolve("awards.yml"))) + assertThrows(IllegalStateException::class.java) { awards.save() } + assertTrue(requireNotNull(awards.info).readOnly) + } + } + + @Test + fun `read-only does not create a missing file`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val awards = scope(service, "quests").yaml("awards.yml", ConfigOptions.builder().readOnly().build()) { AwardsFile() } + + assertThrows(IllegalStateException::class.java) { awards.load() } + assertFalse(Files.exists(plugins.resolve("quests").resolve("awards.yml"))) + } + } + + @Test + fun `two plugins may read one file but only one may write it`() { + write("shop", "prices.yml", "awards: []\n") + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val readOnly = ConfigOptions.builder().readOnly().root(ConfigRoot.PLUGINS).build() + val writing = ConfigOptions.builder().root(ConfigRoot.PLUGINS).build() + scope(service, "quests").yaml("shop/prices.yml", readOnly) { AwardsFile() } + scope(service, "quests", "extra").yaml("shop/prices.yml", readOnly) { AwardsFile() } + scope(service, "other").yaml("shop/prices.yml", writing) { AwardsFile() } + + val error = assertThrows(IllegalStateException::class.java) { + scope(service, "third").yaml("shop/prices.yml", writing) { AwardsFile() } + } + assertTrue(error.message.orEmpty().contains("already managed"), error.message) + } + } + + @Test + fun `the same file cannot be registered twice by one module`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val quests = scope(service, "quests") + quests.yaml("awards.yml") { AwardsFile() } + + assertThrows(IllegalStateException::class.java) { quests.yaml("awards.yml") { AwardsFile() } } + } + } + + @Test + fun `a file in the plugins folder gets the root in its identifier and is never created`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val config = scope(service, "quests").yaml( + "essentials/config.yml", ConfigOptions.builder().root(ConfigRoot.PLUGINS).build(), + ) { AwardsFile() } + + assertEquals("quests/main:@plugins/essentials/config.yml", config.id.toString()) + assertSame(config, service.get("quests/main:@plugins/essentials/config.yml")) + assertSame(config, scope(service, "quests").get("@plugins/essentials/config.yml")) + assertThrows(IllegalStateException::class.java) { config.load() } + assertFalse(Files.exists(plugins.resolve("essentials")), "somebody else's folder stays untouched") + } + } + + @Test + fun `a file in the plugins folder is read and backed up before a rewrite`() { + write("essentials", "config.yml", "awards:\n - type: money\n amount: 3\n") + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val config = scope(service, "quests").yaml( + "essentials/config.yml", ConfigOptions.builder().root(ConfigRoot.PLUGINS).backups(false).build(), + ) { AwardsFile() } + + assertEquals(MoneyAward(3), config.loadValue().awards.single()) + val backups = Files.list(plugins.resolve("essentials")).use { files -> files.map { it.fileName.toString() }.toList() } + assertTrue(backups.any { it.contains(".bak") }, "a backup was made although the options turned backups off: $backups") + } + } + + @Test + fun `a file in the server root is found next to the plugins folder`() { + Files.writeString(server.resolve("bukkit.yml"), "awards: []\n") + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val config = scope(service, "quests").yaml( + "bukkit.yml", ConfigOptions.builder().root(ConfigRoot.SERVER).readOnly().build(), + ) { AwardsFile() } + + assertTrue(config.loadValue().awards.isEmpty()) + assertEquals("quests/main:@server/bukkit.yml", config.id.toString()) + } + } + + @Test + fun `a path cannot leave its root`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val quests = scope(service, "quests") + assertThrows(IllegalArgumentException::class.java) { quests.yaml("../shop/prices.yml") { AwardsFile() } } + assertThrows(IllegalArgumentException::class.java) { quests.yaml("/etc/x.yml") { AwardsFile() } } + assertThrows(IllegalArgumentException::class.java) { + quests.yaml("../../outside.yml", ConfigOptions.builder().root(ConfigRoot.PLUGINS).build()) { AwardsFile() } + } + assertThrows(IllegalArgumentException::class.java) { quests.yaml("notes.txt") { AwardsFile() } } + } + } + + @Test + fun `files of other plugins are not announced to diagnostics`() { + write("essentials", "config.yml", "awards: []\n") + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val announced = mutableListOf() + service.fileListener = { file -> announced += file.path; null } + val quests = scope(service, "quests") + quests.yaml("own.yml") { AwardsFile() } + quests.yaml("essentials/config.yml", ConfigOptions.builder().root(ConfigRoot.PLUGINS).readOnly().build()) { AwardsFile() } + + assertEquals(listOf("own.yml"), announced) + } + } + + private fun assertSame(expected: Any?, actual: Any?) = + assertTrue(expected === actual, "expected the same object: $expected vs $actual") + + @Test + fun `a plugin opens a file at any absolute path and the file is created and listed`(@TempDir elsewhere: Path) { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val file = elsewhere.resolve("deep/folder/awards.yml") + val config = scope(service, "quests").yamlAt(file) { AwardsFile() } + + config.load() + + assertTrue(Files.exists(file), "created where the plugin asked") + val id = config.id!! + assertEquals(ConfigRoot.EXTERNAL, id.root) + assertEquals(id, ConfigId.parse(id.toString()), id.toString()) + assertEquals(file.toAbsolutePath().normalize(), service.get(id)!!.info!!.file) + } + } + + @Test + fun `an external path must be absolute and a second writer of the same file is refused`(@TempDir elsewhere: Path) { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val quests = scope(service, "quests") + assertThrows(IllegalArgumentException::class.java) { + quests.yaml("relative.yml", ConfigOptions.builder().root(ConfigRoot.EXTERNAL).build()) { AwardsFile() } + } + val file = elsewhere.resolve("shared.yml") + quests.yamlAt(file) { AwardsFile() } + assertThrows(IllegalStateException::class.java) { scope(service, "other").yamlAt(file) { AwardsFile() } } + } + } +} diff --git a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigEditingKindsTest.kt b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigEditingKindsTest.kt new file mode 100644 index 000000000..02777d863 --- /dev/null +++ b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigEditingKindsTest.kt @@ -0,0 +1,92 @@ +package org.pnfolder.pnlibrary.config + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.config.ConfigDuration +import org.pnfolder.pnlibrary.api.config.ConfigEditException +import org.pnfolder.pnlibrary.api.config.ConfigEditable +import org.pnfolder.pnlibrary.api.config.ConfigHint +import org.pnfolder.pnlibrary.api.config.ConfigScope +import org.pnfolder.pnlibrary.api.config.ConfigSettingKind +import org.pnfolder.pnlibrary.api.config.ConfigStep +import org.pnfolder.pnlibrary.api.config.ManagedConfig +import org.pnfolder.pnlibrary.api.config.yaml +import org.pnfolder.pnlibrary.api.plugin.ModuleId +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.nio.file.Files +import java.nio.file.Path +import java.util.concurrent.TimeUnit + +class RichFile { + @field:ConfigEditable("Задержка", "Через сколько срабатывает.") + @field:ConfigDuration(TimeUnit.SECONDS) + var delay: Int = 30 + + @field:ConfigEditable("Радиус") + @field:ConfigStep(5.0, "блоков") + var radius: Int = 10 + + @field:ConfigEditable("Режим") + @field:ConfigHint(values = ["alpha", "beta", "gamma"], strict = true) + var mode: String = "alpha" + + @field:ConfigEditable("Место") + @field:ConfigHint(format = "мир;x;y;z", examples = ["world;0;64;0"]) + var place: String = "world;0;64;0" +} + +class ConfigEditingKindsTest { + @TempDir lateinit var server: Path + + private fun open(service: ConfigurationServiceImpl): ManagedConfig { + val folder = server.resolve("plugins/quests").also { Files.createDirectories(it) } + val scope: ConfigScope = service.scope(FakeConfigOwner(folder.toFile()), PluginId.of("quests-main"), PluginId.of("quests"), ModuleId.of("main")) + return scope.yaml("rich.yml") { RichFile() }.also { it.load() } + } + + @Test + fun `a time is typed with units and kept in the unit of the field`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val config = open(service) + + config.edit("delay", "1h30m") + assertEquals(5400, config.get().delay) + + config.edit("delay", "2 мин") + assertEquals(120, config.get().delay) + + config.edit("delay", "45") + assertEquals(45, config.get().delay) + } + } + + @Test + fun `the step, the unit and the hints reach the menu`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val settings = open(service).settings.associateBy { it.path } + + assertEquals(TimeUnit.SECONDS, settings.getValue("delay").duration) + assertEquals(5.0, settings.getValue("radius").step) + assertEquals("блоков", settings.getValue("radius").unit) + assertEquals("мир;x;y;z", settings.getValue("place").format) + assertEquals(listOf("world;0;64;0"), settings.getValue("place").examples) + } + } + + @Test + fun `a strict list of values makes a text a choice that refuses anything else`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val config = open(service) + val mode = config.settings.single { it.path == "mode" } + + assertEquals(ConfigSettingKind.CHOICE, mode.kind) + assertEquals(listOf("alpha", "beta", "gamma"), mode.choices) + + config.edit("mode", "BETA") + assertEquals("beta", config.get().mode) + assertThrows(ConfigEditException::class.java) { config.edit("mode", "delta") } + } + } +} diff --git a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigEditingTest.kt b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigEditingTest.kt new file mode 100644 index 000000000..2f9fc7912 --- /dev/null +++ b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigEditingTest.kt @@ -0,0 +1,173 @@ +package org.pnfolder.pnlibrary.config + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.config.ConfigApply +import org.pnfolder.pnlibrary.api.config.ConfigChange +import org.pnfolder.pnlibrary.api.config.ConfigChangeCause +import org.pnfolder.pnlibrary.api.config.ConfigEditException +import org.pnfolder.pnlibrary.api.config.ConfigEditable +import org.pnfolder.pnlibrary.api.config.ConfigRange +import org.pnfolder.pnlibrary.api.config.ConfigScope +import org.pnfolder.pnlibrary.api.config.ConfigSecret +import org.pnfolder.pnlibrary.api.config.ConfigSettingKind +import org.pnfolder.pnlibrary.api.config.ManagedConfig +import org.pnfolder.pnlibrary.api.config.ReloadRequest +import org.pnfolder.pnlibrary.api.config.yaml +import org.pnfolder.pnlibrary.api.plugin.ModuleId +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.nio.file.Files +import java.nio.file.Path +import java.util.function.Consumer + +enum class Difficulty { EASY, HARD } + +class ShopSection { + @field:ConfigEditable("Включён", "Работает ли магазин.") + var enabled: Boolean = true + + @field:ConfigEditable("Налог", "Доля от цены.") + @field:ConfigRange(min = 0.0, max = 1.0) + var tax: Double = 0.1 +} + +class EditableFile { + @field:ConfigEditable("Приветствие", "Текст при входе.") + var greeting: String = "Привет" + + @field:ConfigEditable("Пул", "Сколько соединений.", apply = ConfigApply.RESTART) + @field:ConfigRange(min = 1.0, max = 64.0) + var poolSize: Int = 10 + + @field:ConfigEditable("Сложность", apply = ConfigApply.RELOAD) + var difficulty: Difficulty = Difficulty.EASY + + @field:ConfigEditable("Секрет", "Не должен показываться.") + @field:ConfigSecret + var token: String = "s3cret" + + var hidden: String = "not marked" + + var shop: ShopSection = ShopSection() +} + +class ConfigEditingTest { + @TempDir lateinit var server: Path + + private fun open(service: ConfigurationServiceImpl): ManagedConfig { + val folder = server.resolve("plugins/quests").also { Files.createDirectories(it) } + val scope: ConfigScope = service.scope(FakeConfigOwner(folder.toFile()), PluginId.of("quests-main"), PluginId.of("quests"), ModuleId.of("main")) + return scope.yaml("settings.yml") { EditableFile() }.also { it.load() } + } + + @Test + fun `only marked fields are offered and secrets never`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val config = open(service) + + val paths = config.settings.map { it.path }.toSet() + + assertEquals(setOf("greeting", "poolSize", "difficulty", "shop.enabled", "shop.tax"), paths) + assertFalse("token" in paths) + assertFalse("hidden" in paths) + val pool = config.settings.single { it.path == "poolSize" } + assertEquals(ConfigSettingKind.INTEGER, pool.kind) + assertEquals(1.0, pool.min) + assertEquals(64.0, pool.max) + assertEquals("10", pool.value) + assertEquals(listOf("EASY", "HARD"), config.settings.single { it.path == "difficulty" }.choices) + } + } + + @Test + fun `an edit changes the value in memory and in the file`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val config = open(service) + + val result = config.edit("greeting", "Здравствуй") + config.edit("shop.enabled", "off") + config.edit("difficulty", "hard") + + assertEquals("Привет", result.previous) + assertEquals("Здравствуй", result.setting.value) + assertEquals("Здравствуй", config.get().greeting) + assertFalse(config.get().shop.enabled) + assertEquals(Difficulty.HARD, config.get().difficulty) + val text = Files.readString(server.resolve("plugins/quests/settings.yml")) + assertTrue(text.contains("Здравствуй"), text) + assertTrue(text.contains("HARD"), text) + } + } + + @Test + fun `a wrong value is refused and nothing changes`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val config = open(service) + val before = Files.readString(server.resolve("plugins/quests/settings.yml")) + + assertThrows(ConfigEditException::class.java) { config.edit("poolSize", "many") } + assertThrows(ConfigEditException::class.java) { config.edit("poolSize", "1000") } + assertThrows(ConfigEditException::class.java) { config.edit("shop.tax", "5") } + assertThrows(ConfigEditException::class.java) { config.edit("difficulty", "medium") } + assertThrows(ConfigEditException::class.java) { config.edit("token", "x") } + assertThrows(ConfigEditException::class.java) { config.edit("hidden", "x") } + + assertEquals(10, config.get().poolSize) + assertEquals(0.1, config.get().shop.tax) + assertEquals("s3cret", config.get().token) + assertEquals(before, Files.readString(server.resolve("plugins/quests/settings.yml"))) + } + } + + @Test + fun `listeners hear about reads, edits and settings that need a reload`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val config = open(service) + val changes = mutableListOf() + val requests = mutableListOf() + val second = mutableListOf() + config.onChanged(Consumer { changes += it }) + config.onReloadRequired(Consumer { requests += it }, Consumer { second += it }) + + config.edit("greeting", "Hi") + assertTrue(requests.isEmpty(), "a live setting asks for nothing") + config.edit("poolSize", "20") + config.edit("difficulty", "HARD") + + assertEquals(listOf(ConfigApply.RESTART, ConfigApply.RELOAD), requests.map { it.apply }) + assertEquals(2, second.size, "every listener is called") + assertEquals(ConfigApply.RESTART, service.get(config.id!!)!!.info!!.pendingApply) + assertEquals(listOf("greeting", "poolSize", "difficulty"), changes.map { it.paths.single() }) + assertTrue(changes.all { it.cause == ConfigChangeCause.EDITED }) + + config.reload() + assertEquals(ConfigChangeCause.RELOADED, changes.last().cause) + assertEquals(ConfigApply.RESTART, config.info!!.pendingApply, "a reload does not make a restart") + } + } + + @Test + fun `a pending reload is cleared by reading the file again and a failing listener does not stop others`() { + ConfigurationServiceImpl(FakeOwnerPlatform).use { service -> + val config = open(service) + val heard = mutableListOf() + val subscription = config.onReloadRequired(Consumer { error("broken listener") }, Consumer { heard += it }) + + config.edit("difficulty", "HARD") + assertEquals(1, heard.size) + assertEquals(ConfigApply.RELOAD, config.info!!.pendingApply) + + config.reload() + assertNull(config.info!!.pendingApply) + + subscription.close() + config.edit("difficulty", "EASY") + assertEquals(1, heard.size, "a closed subscription hears nothing") + } + } +} diff --git a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigPathsTest.kt b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigPathsTest.kt new file mode 100644 index 000000000..00cfdb003 --- /dev/null +++ b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigPathsTest.kt @@ -0,0 +1,47 @@ +package org.pnfolder.pnlibrary.config + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.config.ConfigRoot +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.nio.file.Path +import java.nio.file.Paths + +class ConfigPathsTest { + @TempDir + lateinit var root: Path + + private fun paths(): ConfigPaths { + val folder = root.resolve("plugins").resolve("shop") + java.nio.file.Files.createDirectories(folder) + return ConfigPaths(folder, PluginId.of("shop")) + } + + @Test + fun `a path inside the plugin folder is accepted`() { + val target = paths().checked("data/prices.yml", Paths.get("data/prices.yml"), ConfigRoot.PLUGIN) + + assertEquals(root.resolve("plugins").resolve("shop").resolve("data").resolve("prices.yml"), target) + } + + @Test + fun `a path that climbs out of the folder is refused`() { + assertThrows(IllegalArgumentException::class.java) { + paths().checked("../other/x.yml", Paths.get("../other/x.yml"), ConfigRoot.PLUGIN) + } + } + + @Test + fun `only yaml files are accepted`() { + assertThrows(IllegalArgumentException::class.java) { + paths().checked("prices.txt", Paths.get("prices.txt"), ConfigRoot.PLUGIN) + } + } + + @Test + fun `the plugins folder is the parent of the plugin folder`() { + assertEquals(root.resolve("plugins"), paths().rootDirectory(ConfigRoot.PLUGINS)) + } +} diff --git a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigurationServiceImplTest.kt b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigurationServiceImplTest.kt index 2277707c9..a9ec680b8 100644 --- a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigurationServiceImplTest.kt +++ b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/ConfigurationServiceImplTest.kt @@ -108,36 +108,38 @@ class ConfigurationServiceImplTest { } @Test - fun `every file carries the support note once, new or already existing`() { - Files.writeString(directory.resolve("old.yml"), "retries: 4"+"\n"+"name: custom"+"\n") + fun `new and rewritten files never carry a support note`() { + Files.writeString(directory.resolve("old.yml"), "retries: 4\nname: custom\n") service().use { service -> val scope = scope(service) - scope.yaml("settings.yml") { ServiceSettings() }.load() + val fresh = scope.yaml("settings.yml") { ServiceSettings() } + fresh.load() + fresh.save() val old = scope.yaml("old.yml") { ServiceSettings() } old.load() old.reload() listOf("settings.yml", "old.yml").forEach { name -> val text = Files.readString(directory.resolve(name)) - assertEquals(1, text.split("discord.gg").size - 1, "$name: $text") - assertTrue(text.contains("write to us"), text) - assertTrue(text.contains("пишите нам"), text) - assertTrue(text.contains("# Discord: https://discord.gg/"), text) + assertFalse(text.contains("discord.gg"), "$name: $text") + assertFalse(text.contains("write to us"), text) + assertFalse(text.contains("пишите нам"), text) } } } @Test - fun `an older support note is replaced by the current one instead of being repeated`() { - val older = "# Если у вас возникли проблемы с плагином, пишите в наш Discord: мы всегда рады помочь.\n" + - "# If you have any problem with a plugin, write to our Discord: we are always happy to help.\n" + - "# https://discord.gg/old\n" - Files.writeString(directory.resolve("old.yml"), "_config-version: 1\n" + older + "retries: 4\n") + fun `an old support note is removed from an existing file and nothing else changes`() { + val note = "# Если у вас возникли проблемы с плагином, пишите нам: мы всегда рады помочь.\n" + + "# If you have any problem with a plugin, write to us: we are always happy to help.\n" + + "# Discord: https://discord.gg/old\n" + Files.writeString(directory.resolve("old.yml"), "_config-version: 1\n" + note + "# my note\nretries: 4\nname: custom\n") service().use { service -> scope(service).yaml("old.yml") { ServiceSettings() }.load() val text = Files.readString(directory.resolve("old.yml")) - assertEquals(1, text.split("If you have any problem").size - 1, text) - assertFalse(text.contains("discord.gg/old"), text) - assertTrue(text.contains("retries: 4"), text) + assertFalse(text.contains("discord.gg"), text) + assertFalse(text.contains("If you have any problem"), text) + assertTrue(text.contains("# my note\nretries: 4"), text) + assertTrue(text.contains("name: custom"), text) } } diff --git a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigObjectIntrospectorTest.kt b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigObjectIntrospectorTest.kt index 53a2782cf..a3a301cd5 100644 --- a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigObjectIntrospectorTest.kt +++ b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigObjectIntrospectorTest.kt @@ -2,10 +2,15 @@ package org.pnfolder.pnlibrary.config.yaml import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.config.BackupDatabase +import org.pnfolder.pnlibrary.api.config.BackupTable import org.pnfolder.pnlibrary.api.config.ConfigIgnore import org.pnfolder.pnlibrary.api.config.ConfigKey import org.pnfolder.pnlibrary.api.config.ConfigNamingStrategy import org.pnfolder.pnlibrary.api.config.ConfigOrder +import org.pnfolder.pnlibrary.api.config.DatabaseField +import org.pnfolder.pnlibrary.api.config.DatabaseKind +import org.pnfolder.pnlibrary.api.config.DatabaseRole class ConfigObjectIntrospectorTest { @Test @@ -52,4 +57,56 @@ class ConfigObjectIntrospectorTest { val staticValue: Int = 0 } } + + @BackupDatabase(DatabaseKind.MYSQL, "Игроки", tables = ["players"]) + @BackupDatabase(DatabaseKind.MYSQL, "Экономика") + class ThreeInOne { + @DatabaseField(DatabaseRole.USER) + var user = "" + + @DatabaseField(DatabaseRole.DATABASE, database = "Игроки") + var playersSchema = "" + + @DatabaseField(DatabaseRole.DATABASE, database = "Экономика") + var economySchema = "" + + @BackupTable(database = "Экономика") + var accounts = "" + } + + @Test + fun `one class can describe several databases and each field joins its own`() { + val paths = ConfigObjectIntrospector(ConfigNamingStrategy.AS_DECLARED).databasePaths(ThreeInOne::class.java) + + assertEquals(listOf("Игроки", "Экономика"), paths.map { it.name }) + assertEquals(mapOf(DatabaseRole.USER to "user", DatabaseRole.DATABASE to "playersSchema"), paths[0].keys) + assertEquals(mapOf(DatabaseRole.USER to "user", DatabaseRole.DATABASE to "economySchema"), paths[1].keys) + assertEquals(emptyList(), paths[0].tableKeys) + assertEquals(listOf("accounts"), paths[1].tableKeys) + } + + class OnTheFields { + @BackupDatabase(DatabaseKind.MYSQL, "Игроки") + var playersDb = "" + + @DatabaseField(DatabaseRole.HOST, database = "Игроки") + var playersHost = "" + + @BackupDatabase(DatabaseKind.POSTGRESQL, "Кланы", tables = ["clans"]) + var clansDb = "" + + @DatabaseField(DatabaseRole.HOST, database = "Кланы") + var clansHost = "" + } + + @Test + fun `a database can be described on its fields alone with no annotation on the class`() { + val paths = ConfigObjectIntrospector(ConfigNamingStrategy.AS_DECLARED).databasePaths(OnTheFields::class.java) + + assertEquals(listOf("Игроки", "Кланы"), paths.map { it.name }) + assertEquals(listOf(DatabaseKind.MYSQL, DatabaseKind.POSTGRESQL), paths.map { it.kind }) + assertEquals(mapOf(DatabaseRole.HOST to "playersHost", DatabaseRole.DATABASE to "playersDb"), paths[0].keys) + assertEquals(mapOf(DatabaseRole.HOST to "clansHost", DatabaseRole.DATABASE to "clansDb"), paths[1].keys) + assertEquals("", paths[0].path) + } } diff --git a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigPolymorphicResolverTest.kt b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigPolymorphicResolverTest.kt index ca7435123..d4c4d5036 100644 --- a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigPolymorphicResolverTest.kt +++ b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigPolymorphicResolverTest.kt @@ -24,7 +24,7 @@ class ConfigPolymorphicResolverTest { } @Test - fun `external runtime type requires owner namespace`() { + fun `visible external type works with its plain word and with owner namespace`() { val external = RuntimeConfigType( owner = "economy", baseType = Payment::class.java, @@ -35,20 +35,49 @@ class ConfigPolymorphicResolverTest { ) val resolver = resolver(listOf(external), consumer = "shop") - assertThrows(IllegalArgumentException::class.java) { - resolver.decodingType(Payment::class.java, emptyList(), "token", "payment") - } + assertEquals( + TokenPayment::class.java, + resolver.decodingType(Payment::class.java, emptyList(), "token", "payment"), + ) assertEquals( TokenPayment::class.java, resolver.decodingType(Payment::class.java, emptyList(), "economy::token", "payment"), ) assertEquals( - "economy::token", + "token", resolver.encodingType(Payment::class.java, emptyList(), TokenPayment::class.java) .serializedName("shop"), ) } + @Test + fun `an unknown word fails with a dedicated exception that a list can skip`() { + val resolver = resolver(emptyList(), consumer = "shop") + + assertThrows(UnknownConfigTypeException::class.java) { + resolver.decodingType(Payment::class.java, emptyList(), "nope", "payment") + } + } + + @Test + fun `two additions with one word and one priority are ambiguous until namespaced`() { + fun addition(owner: String, implementation: Class<*>) = RuntimeConfigType( + owner, Payment::class.java, implementation, "token", emptySet(), 0, + ) + val resolver = resolver( + listOf(addition("economy", TokenPayment::class.java), addition("bank", CardPayment::class.java)), + consumer = "shop", + ) + + assertThrows(IllegalArgumentException::class.java) { + resolver.decodingType(Payment::class.java, emptyList(), "token", "payment") + } + assertEquals( + CardPayment::class.java, + resolver.decodingType(Payment::class.java, emptyList(), "bank::token", "payment"), + ) + } + @Test fun `consumer-owned runtime type can use an unqualified name`() { val owned = RuntimeConfigType( diff --git a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigReflectionCostTest.kt b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigReflectionCostTest.kt new file mode 100644 index 000000000..c18d985df --- /dev/null +++ b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigReflectionCostTest.kt @@ -0,0 +1,129 @@ +package org.pnfolder.pnlibrary.config.yaml + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.config.ConfigCodec +import org.pnfolder.pnlibrary.api.config.ConfigIgnore +import org.pnfolder.pnlibrary.api.config.ConfigNamingStrategy +import org.pnfolder.pnlibrary.api.config.ConfigOrder +import org.pnfolder.pnlibrary.spi.platform.PlatformLogging +import org.pnfolder.pnlibrary.spi.platform.PlatformPnLogger +import java.lang.reflect.Field +import java.lang.reflect.Modifier +import java.nio.file.Files +import java.nio.file.Path +import java.util.concurrent.atomic.AtomicInteger + +class ConfigReflectionCostTest { + open class Base { + var baseName = "x" + + @ConfigOrder(5) var late = 1 + @Transient var skipped = 2 + } + + class Child : Base() { + @ConfigIgnore var ignored = 3 + + @ConfigOrder(-1) var first = 4 + var port = 5 + val list = listOf(1) + + companion object { + @JvmField var shared = 6 + } + } + + /** The discovery as it was before the cache: every call reads the declared fields of the whole hierarchy. */ + private fun discoveredAgain(type: Class<*>): List = generateSequence(type) { it.superclass } + .takeWhile { it != Any::class.java }.toList().asReversed() + .flatMap { it.declaredFields.asList() } + .filterNot { field -> + field.isSynthetic || Modifier.isStatic(field.modifiers) || Modifier.isTransient(field.modifiers) || + field.isAnnotationPresent(ConfigIgnore::class.java) + } + .sortedWith(compareBy { it.getAnnotation(ConfigOrder::class.java)?.value ?: 0 }) + + @Test + fun `cached fields equal a fresh discovery`() { + val introspector = ConfigObjectIntrospector(ConfigNamingStrategy.KEBAB_CASE) + listOf(Base::class.java, Child::class.java, Any::class.java).forEach { type -> + assertEquals(discoveredAgain(type), introspector.fields(type), type.name) + } + assertEquals(listOf("first", "baseName", "port", "list", "late"), introspector.fields(Child::class.java).map { it.name }) + } + + @Test + fun `declared fields are read once per class however often they are asked`() { + class Fresh : Base() + val introspector = ConfigObjectIntrospector(ConfigNamingStrategy.KEBAB_CASE) + val before = ConfigObjectIntrospector.declaredFieldReads.get() + + repeat(5_000) { introspector.fields(Fresh::class.java) } + repeat(100) { ConfigObjectIntrospector(ConfigNamingStrategy.SNAKE_CASE).fields(Fresh::class.java) } + + assertEquals(2, ConfigObjectIntrospector.declaredFieldReads.get() - before) // Fresh and Base + } + + private class CountingCodec : ConfigCodec { + val decodes = AtomicInteger() + override fun encode(value: Int) = "port: $value\n" + override fun decode(yaml: String): Int { + decodes.incrementAndGet() + return Regex("port: ([0-9]+)").find(yaml)?.groupValues?.get(1)?.toInt() ?: error("port is missing") + } + } + + private fun yaml(file: Path, codec: CountingCodec) = + CodeFirstYaml(file.toFile(), 3306, codec, PlatformPnLogger(object : PlatformLogging {}, "test", "test")) + + @Test + fun `saving decodes the document once and writes the same file`(@TempDir directory: Path) { + val codec = CountingCodec() + val file = directory.resolve("config.yml") + val managed = yaml(file, codec) + managed.load() + codec.decodes.set(0) + + managed.save(5432) + + assertEquals(1, codec.decodes.get()) + assertTrue(Files.readString(file).endsWith("port: 5432\n")) + assertEquals(5432, managed.get()) + } + + @Test + fun `creating the file from defaults decodes once`(@TempDir directory: Path) { + val codec = CountingCodec() + val file = directory.resolve("config.yml") + + yaml(file, codec).load() + + assertEquals(1, codec.decodes.get()) + assertTrue(Files.readString(file).endsWith("port: 3306\n")) + } + + @Test + fun `rewriting a changed file decodes once and an invalid document is not written`(@TempDir directory: Path) { + val codec = CountingCodec() + val file = directory.resolve("config.yml") + Files.writeString(file, "port: 1\n# note\n") + codec.decodes.set(0) + + yaml(file, codec).load() + + assertTrue(codec.decodes.get() <= 1, "decoded ${codec.decodes.get()} times") + val broken = directory.resolve("broken.yml") + val managed = yaml(broken, codec) + managed.load() + val before = Files.readString(broken) + val failing = object : ConfigCodec { + override fun encode(value: Int) = "nonsense\n" + override fun decode(yaml: String): Int = error("cannot read") + } + runCatching { CodeFirstYaml(broken.toFile(), 1, failing, PlatformPnLogger(object : PlatformLogging {}, "t", "t")).save(7) } + assertEquals(before, Files.readString(broken)) + } +} diff --git a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSecretTest.kt b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSecretTest.kt index 3333099dd..9b7c7ad86 100644 --- a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSecretTest.kt +++ b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/ConfigSecretTest.kt @@ -22,6 +22,25 @@ class ConfigSecretTest { var welcome: String = "Hi" } + class Account { + var name: String = "" + + @field:ConfigSecret + var pin: String = "" + } + + class Holders { + var users: List = emptyList() + var byName: Map = emptyMap() + } + + @Test + fun `secrets inside list items and map values are found`() { + val paths = ConfigObjectIntrospector(ConfigNamingStrategy.KEBAB_CASE).secretPaths(Holders::class.java) + + assertEquals(listOf("users.pin", "by-name.*.pin"), paths) + } + @Test fun `secret fields are found at any depth under their file keys`() { val paths = ConfigObjectIntrospector(ConfigNamingStrategy.KEBAB_CASE).secretPaths(Settings::class.java) diff --git a/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/LegacySupportNoteTest.kt b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/LegacySupportNoteTest.kt new file mode 100644 index 000000000..af9a48f00 --- /dev/null +++ b/modules/features/config-runtime/src/test/kotlin/org/pnfolder/pnlibrary/config/yaml/LegacySupportNoteTest.kt @@ -0,0 +1,25 @@ +package org.pnfolder.pnlibrary.config.yaml + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class LegacySupportNoteTest { + private val note = listOf( + "# Если у вас возникли проблемы с плагином, пишите нам: мы всегда рады помочь.", + "# If you have any problem with a plugin, write to us: we are always happy to help.", + "# Discord: https://discord.gg/old", + "# https://example.org/second-link", + ) + + @Test + fun `the note is removed together with all its link lines and nothing else`() { + val content = (listOf("_config-version: 1") + note + listOf("retries: 4", "")).joinToString("\n") + assertEquals("_config-version: 1\nretries: 4\n", LegacySupportNote.removeFrom(content)) + } + + @Test + fun `content without a note is returned unchanged`() { + val content = "# my note\n# https://example.org/docs\nretries: 4\n" + assertEquals(content, LegacySupportNote.removeFrom(content)) + } +} diff --git a/modules/features/currency-api/api/currency-api.api b/modules/features/currency-api/api/currency-api.api index 024f2afb7..9dbf1f49a 100644 --- a/modules/features/currency-api/api/currency-api.api +++ b/modules/features/currency-api/api/currency-api.api @@ -1,3 +1,37 @@ +public final class org/pnfolder/pnlibrary/api/currency/BalanceRequirement : org/pnfolder/pnlibrary/api/scenario/requirements/Requirement { + public fun ()V + public fun (Ljava/lang/String;Ljava/lang/String;)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun copy (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/currency/BalanceRequirement; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/currency/BalanceRequirement;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/currency/BalanceRequirement; + public fun equals (Ljava/lang/Object;)Z + public final fun getAtLeast ()Ljava/lang/String; + public final fun getCurrency ()Ljava/lang/String; + public fun hashCode ()I + public fun test (Lorg/pnfolder/pnlibrary/api/scenario/requirements/RequirementContext;)Lorg/pnfolder/pnlibrary/api/scenario/requirements/Verdict; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/api/currency/ChargeAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/lang/String;Ljava/lang/String;Z)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Z + public final fun copy (Ljava/lang/String;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/currency/ChargeAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/currency/ChargeAction;Ljava/lang/String;Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/currency/ChargeAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getAmount ()Ljava/lang/String; + public final fun getCurrency ()Ljava/lang/String; + public final fun getUndo ()Z + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; +} + public abstract interface class org/pnfolder/pnlibrary/api/currency/Currency { public abstract fun balance (Ljava/util/UUID;)Ljava/util/concurrent/CompletionStage; public fun deposit (Ljava/util/UUID;J)Ljava/util/concurrent/CompletionStage; @@ -18,30 +52,6 @@ public abstract interface class org/pnfolder/pnlibrary/api/currency/Currency { public abstract fun withdraw (Ljava/util/UUID;Ljava/math/BigDecimal;)Ljava/util/concurrent/CompletionStage; } -public final class org/pnfolder/pnlibrary/api/currency/CurrencyAccess { - public static final field Companion Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess$Companion; - public synthetic fun (ZZLjava/util/Set;Ljava/util/Set;Ljava/util/Set;Lkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun allows (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Lorg/pnfolder/pnlibrary/api/plugin/PluginId;)Z - public static final fun builder ()Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess$Builder; - public static final fun ownerOnly ()Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess; - public static final fun shared ()Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess; -} - -public final class org/pnfolder/pnlibrary/api/currency/CurrencyAccess$Builder { - public final fun allow ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess$Builder; - public final fun allowAll ()Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess$Builder; - public final fun allowMatching ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess$Builder; - public final fun build ()Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess; - public final fun deny ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess$Builder; - public final fun owner ()Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess$Builder; -} - -public final class org/pnfolder/pnlibrary/api/currency/CurrencyAccess$Companion { - public final fun builder ()Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess$Builder; - public final fun ownerOnly ()Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess; - public final fun shared ()Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess; -} - public final class org/pnfolder/pnlibrary/api/currency/CurrencyAccount { public fun (Ljava/util/UUID;)V public final fun component1 ()Ljava/util/UUID; @@ -349,7 +359,7 @@ public abstract interface class org/pnfolder/pnlibrary/api/currency/CurrencyOper } public abstract interface class org/pnfolder/pnlibrary/api/currency/CurrencyPlaceholderOptions { - public abstract fun access (Lorg/pnfolder/pnlibrary/api/placeholders/PlaceholderAccess;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyPlaceholderOptions; + public abstract fun access (Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyPlaceholderOptions; public abstract fun enabled (Z)Lorg/pnfolder/pnlibrary/api/currency/CurrencyPlaceholderOptions; public abstract fun placeholderApi (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyPlaceholderOptions; public abstract fun placeholderApi (Z)Lorg/pnfolder/pnlibrary/api/currency/CurrencyPlaceholderOptions; @@ -365,7 +375,7 @@ public abstract interface class org/pnfolder/pnlibrary/api/currency/CurrencyProv public abstract fun all ()Ljava/util/List; public abstract fun get (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/currency/Currency; public fun register (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/currency/CurrencyProvider;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyRegistration; - public abstract fun register (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/currency/CurrencyProvider;Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyRegistration; + public abstract fun register (Lorg/pnfolder/pnlibrary/api/plugin/PluginId;Ljava/lang/String;Lorg/pnfolder/pnlibrary/api/currency/CurrencyProvider;Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyRegistration; public fun require (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/currency/Currency; } @@ -377,7 +387,7 @@ public abstract interface class org/pnfolder/pnlibrary/api/currency/CurrencyRegi public abstract interface class org/pnfolder/pnlibrary/api/currency/CurrencyRegistrationOptions { public abstract fun access (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyRegistrationOptions; - public abstract fun access (Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccess;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyRegistrationOptions; + public abstract fun access (Lorg/pnfolder/pnlibrary/api/plugin/PluginAccess;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyRegistrationOptions; public abstract fun aliases ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/currency/CurrencyRegistrationOptions; } @@ -615,6 +625,24 @@ public abstract interface class org/pnfolder/pnlibrary/api/currency/CurrencyWith public abstract fun withdraw (Lorg/pnfolder/pnlibrary/api/currency/CurrencyAccount;Ljava/math/BigDecimal;)Ljava/util/concurrent/CompletionStage; } +public final class org/pnfolder/pnlibrary/api/currency/GiveAction : org/pnfolder/pnlibrary/api/scenario/actions/Action { + public fun ()V + public fun (Ljava/lang/String;Ljava/lang/String;Z)V + public synthetic fun (Ljava/lang/String;Ljava/lang/String;ZILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Z + public final fun copy (Ljava/lang/String;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/api/currency/GiveAction; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/api/currency/GiveAction;Ljava/lang/String;Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/api/currency/GiveAction; + public fun equals (Ljava/lang/Object;)Z + public final fun getAmount ()Ljava/lang/String; + public final fun getCurrency ()Ljava/lang/String; + public final fun getUndo ()Z + public fun hashCode ()I + public fun run (Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionContext;)Lorg/pnfolder/pnlibrary/api/scenario/actions/ActionResult; + public fun toString ()Ljava/lang/String; +} + public abstract interface class org/pnfolder/pnlibrary/api/currency/ManagedCurrencyBuilder : org/pnfolder/pnlibrary/api/currency/CurrencyRegistrationOptions { public abstract fun commands (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/currency/ManagedCurrencyBuilder; public abstract fun descriptor (Ljava/util/function/Consumer;)Lorg/pnfolder/pnlibrary/api/currency/ManagedCurrencyBuilder; diff --git a/modules/features/currency-api/build.gradle.kts b/modules/features/currency-api/build.gradle.kts index 5b98eba69..5addc0164 100644 --- a/modules/features/currency-api/build.gradle.kts +++ b/modules/features/currency-api/build.gradle.kts @@ -15,7 +15,8 @@ dependencies { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-currency-api", project.version.toString()) pom { name.set("pnLibrary Currency API") diff --git a/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyAccess.kt b/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyAccess.kt deleted file mode 100644 index 054e7df1c..000000000 --- a/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyAccess.kt +++ /dev/null @@ -1,72 +0,0 @@ -package org.pnfolder.pnlibrary.api.currency - -import org.pnfolder.pnlibrary.api.plugin.PluginId -import org.pnfolder.pnlibrary.common.text.Wildcards -import java.util.Collections - -/** - * Immutable policy controlling which registered plugins may resolve a currency. - * - * Explicit denials take precedence over every allow rule. The owner rule is checked - * next, followed by global access, exact plugin IDs, and case-insensitive patterns in - * which `*` matches any character sequence. - */ -class CurrencyAccess private constructor( - private val ownerAllowed: Boolean, - private val allPlugins: Boolean, - private val allowed: Set, - private val patterns: Set, - private val denied: Set, -) { - /** Returns whether [consumer] may access a currency owned by [owner]. */ - fun allows(owner: PluginId, consumer: PluginId): Boolean { - if (consumer in denied) return false - if (ownerAllowed && owner == consumer) return true - if (allPlugins || consumer in allowed) return true - return patterns.any { Wildcards.matches(it, consumer.value) } - } - - /** Common visibility policies and the custom-policy builder entry point. */ - companion object { - /** Creates a policy visible only to the owning plugin. */ - @JvmStatic - fun ownerOnly(): CurrencyAccess = Builder().owner().build() - /** Creates a policy visible to the owner and every pnLibrary plugin. */ - @JvmStatic - fun shared(): CurrencyAccess = Builder().owner().allowAll().build() - /** Creates an initially empty policy builder. */ - @JvmStatic - fun builder(): Builder = Builder() - } - - /** Mutable Java-friendly builder for [CurrencyAccess]. */ - class Builder internal constructor() { - private var owner = false - private var all = false - private val allowed = linkedSetOf() - private val patterns = linkedSetOf() - private val denied = linkedSetOf() - - /** Allows the currency owner. */ - fun owner(): Builder = apply { owner = true } - /** Allows every plugin registered with pnLibrary. */ - fun allowAll(): Builder = apply { all = true } - /** Adds exact validated plugin IDs to the allow set. */ - fun allow(vararg pluginIds: String): Builder = apply { pluginIds.map(PluginId::of).forEach(allowed::add) } - /** Adds case-insensitive plugin-ID patterns using `*` as a wildcard. */ - fun allowMatching(vararg patterns: String): Builder = apply { - require(patterns.none(String::isBlank)) { "Currency access patterns must not be blank" } - patterns.map(String::trim).forEach(this.patterns::add) - } - /** Adds exact plugin IDs to the deny set, which has highest priority. */ - fun deny(vararg pluginIds: String): Builder = apply { pluginIds.map(PluginId::of).forEach(denied::add) } - /** Creates an immutable policy from the current rules. */ - fun build(): CurrencyAccess = CurrencyAccess( - owner, - all, - Collections.unmodifiableSet(LinkedHashSet(allowed)), - Collections.unmodifiableSet(LinkedHashSet(patterns)), - Collections.unmodifiableSet(LinkedHashSet(denied)), - ) - } -} diff --git a/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyProviderRegistry.kt b/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyProviderRegistry.kt index 4b3d3ce66..132e2cdbf 100644 --- a/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyProviderRegistry.kt +++ b/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyProviderRegistry.kt @@ -1,13 +1,14 @@ package org.pnfolder.pnlibrary.api.currency +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId /** Restricted registry for platform integrations; consumer plugins use their owned [CurrencyService]. */ interface CurrencyProviderRegistry { /** Registers a provider shared with every pnLibrary plugin. */ - fun register(owner: PluginId, name: String, provider: CurrencyProvider): CurrencyRegistration = register(owner, name, provider, CurrencyAccess.shared()) + fun register(owner: PluginId, name: String, provider: CurrencyProvider): CurrencyRegistration = register(owner, name, provider, PluginAccess.shared()) /** Registers a provider with explicit cross-plugin [access]. */ - fun register(owner: PluginId, name: String, provider: CurrencyProvider, access: CurrencyAccess): CurrencyRegistration + fun register(owner: PluginId, name: String, provider: CurrencyProvider, access: PluginAccess): CurrencyRegistration /** Resolves an active canonical `owner:name` reference without consumer filtering. */ fun get(reference: String): Currency? /** Resolves [reference] or fails when no active provider is registered. */ diff --git a/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyRegistry.kt b/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyRegistry.kt index 58ad0d8e1..4836ff6cd 100644 --- a/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyRegistry.kt +++ b/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyRegistry.kt @@ -1,6 +1,6 @@ package org.pnfolder.pnlibrary.api.currency -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAccess +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId import java.math.BigDecimal import java.util.function.Consumer @@ -37,9 +37,9 @@ interface CurrencyRegistration : Currency, AutoCloseable { /** Options shared by lightweight, managed, and direct provider registrations. */ interface CurrencyRegistrationOptions { /** Replaces the complete consumer access policy. */ - fun access(access: CurrencyAccess): CurrencyRegistrationOptions + fun access(access: PluginAccess): CurrencyRegistrationOptions /** Builds and replaces the access policy through a Java-friendly callback. */ - fun access(configure: Consumer): CurrencyRegistrationOptions + fun access(configure: Consumer): CurrencyRegistrationOptions /** Adds local aliases owned by the same plugin; conflicts fail during registration. */ fun aliases(vararg aliases: String): CurrencyRegistrationOptions } @@ -63,7 +63,7 @@ interface CurrencyPlaceholderOptions { /** Enables or disables generation of library placeholders. */ fun enabled(value: Boolean): CurrencyPlaceholderOptions /** Sets which plugins may consume generated placeholders. */ - fun access(access: PlaceholderAccess): CurrencyPlaceholderOptions + fun access(access: PluginAccess): CurrencyPlaceholderOptions /** Enables or disables publication through the PlaceholderAPI adapter. */ fun placeholderApi(enabled: Boolean): CurrencyPlaceholderOptions /** Enables PlaceholderAPI publication with explicit [namespace]. */ diff --git a/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyScenario.kt b/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyScenario.kt new file mode 100644 index 000000000..a25d15aae --- /dev/null +++ b/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyScenario.kt @@ -0,0 +1,106 @@ +package org.pnfolder.pnlibrary.api.currency + +import org.pnfolder.pnlibrary.api.scenario.actions.Action +import org.pnfolder.pnlibrary.api.scenario.actions.ActionContext +import org.pnfolder.pnlibrary.api.scenario.actions.ActionResult +import org.pnfolder.pnlibrary.api.scenario.requirements.Requirement +import org.pnfolder.pnlibrary.api.scenario.requirements.RequirementContext +import org.pnfolder.pnlibrary.api.scenario.requirements.Verdict +import java.math.BigDecimal + +private fun RequirementContext.currencyOrNull(reference: String): Currency? = + service(CurrencyService::class.java)?.get(reference.trim()) + +private fun ActionContext.amountOf(expression: String): BigDecimal? = + text(expression).trim().toBigDecimalOrNull()?.takeIf { it.signum() > 0 } + +private fun CurrencyResult.failure(currency: Currency, amount: BigDecimal): ActionResult.Failed = when (status) { + CurrencyResultStatus.REJECTED -> when (reason) { + CurrencyRejectReason.INSUFFICIENT_FUNDS -> ActionResult.Failed( + "currency.insufficient-funds", + "Not enough money: ${currency.format(amount)} is needed", + ) + else -> ActionResult.Failed("currency.rejected", message ?: "The currency refused the operation (${reason ?: "unknown"})") + } + CurrencyResultStatus.UNSUPPORTED -> ActionResult.Failed("currency.unsupported", message ?: "The currency does not support this operation") + CurrencyResultStatus.UNAVAILABLE -> ActionResult.Failed("currency.unavailable", message ?: "The currency is temporarily unavailable") + else -> ActionResult.Failed("currency.failed", message ?: "The currency operation failed", error) +} + +/** + * Takes [amount] of [currency] from the player, and gives it back if a later step of the scenario fails. + * + * It fails with `currency.insufficient-funds` when the player cannot pay, so wrap it in `attempt` to show a + * message. After a successful charge the values `[paid]` and `[balance]` are available to later texts. + * + * Money is taken through the currency service, so it blocks the calling thread until the provider answers. + * + * ```yaml + * - type: attempt + * do: + * - { type: charge, currency: money, amount: 100 } + * - { type: command, command: 'give [player] diamond 1' } + * fail: + * - { type: message, messages: ['&cCould not buy: [error]'] } + * ``` + * + * The words `charge`, `give` and `balance` are registered by the library for every plugin. + * + * @property currency currency reference, as in [CurrencyService.get] + * @property amount positive amount; may be a placeholder such as `{shop:price}` + * @property undo whether a later failure gives the money back; `false` keeps it + */ +data class ChargeAction(val currency: String = "", val amount: String = "", val undo: Boolean = true) : Action { + override fun run(context: ActionContext): ActionResult { + val money = context.currencyOrNull(currency) + ?: return ActionResult.Failed("currency.unavailable", "Currency '$currency' is not available") + val sum = context.amountOf(amount) + ?: return ActionResult.Failed("currency.invalid-amount", "'$amount' is not a positive amount") + val result = money.withdraw(context.player.uniqueId, sum).toCompletableFuture().join() + if (!result.isSuccess) return result.failure(money, sum) + if (undo) context.onUndo("give back ${money.format(sum)}") { money.deposit(context.player.uniqueId, sum).toCompletableFuture().join() } + context.setValue("paid", money.format(sum)) + result.currentBalance?.let { context.setValue("balance", money.format(it)) } + return ActionResult.Done + } +} + +/** + * Pays [amount] of [currency] to the player, and takes it back if a later step of the scenario fails. + * + * After a successful payment the values `[paid]` and `[balance]` are available to later texts. + * + * @property currency currency reference, as in [CurrencyService.get] + * @property amount positive amount; may be a placeholder + * @property undo whether a later failure gives the money back; `false` keeps it + */ +data class GiveAction(val currency: String = "", val amount: String = "", val undo: Boolean = true) : Action { + override fun run(context: ActionContext): ActionResult { + val money = context.currencyOrNull(currency) + ?: return ActionResult.Failed("currency.unavailable", "Currency '$currency' is not available") + val sum = context.amountOf(amount) + ?: return ActionResult.Failed("currency.invalid-amount", "'$amount' is not a positive amount") + val result = money.deposit(context.player.uniqueId, sum).toCompletableFuture().join() + if (!result.isSuccess) return result.failure(money, sum) + if (undo) context.onUndo("take back ${money.format(sum)}") { money.withdraw(context.player.uniqueId, sum).toCompletableFuture().join() } + context.setValue("paid", money.format(sum)) + result.currentBalance?.let { context.setValue("balance", money.format(it)) } + return ActionResult.Done + } +} + +/** + * Met when the player has at least [atLeast] of [currency]. It only looks: to take the money use `charge`, + * which cannot disagree with this check. + * + * @property currency currency reference, as in [CurrencyService.get] + * @property atLeast the least balance; may be a placeholder + */ +data class BalanceRequirement(val currency: String = "", val atLeast: String = "") : Requirement { + override fun test(context: RequirementContext): Verdict { + val money = context.currencyOrNull(currency) ?: return Verdict.Unmet("currency '$currency' is not available") + val need = context.text(atLeast).trim().toBigDecimalOrNull() ?: return Verdict.Unmet("'$atLeast' is not an amount") + val has = money.has(context.player.uniqueId, need).toCompletableFuture().join() + return Verdict.of(has, "need ${money.format(need)}") + } +} diff --git a/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyService.kt b/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyService.kt index bd27867f1..b30850e06 100644 --- a/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyService.kt +++ b/modules/features/currency-api/src/main/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyService.kt @@ -1,12 +1,13 @@ package org.pnfolder.pnlibrary.api.currency +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import java.util.function.Consumer /** * Plugin-owned facade for registering and discovering currencies. * * Unqualified references resolve inside the owning plugin. Cross-plugin references use - * canonical `owner:name` form and are filtered through [CurrencyAccess]. Closing the + * canonical `owner:name` form and are filtered through [PluginAccess]. Closing the * service closes every registration created through it. */ interface CurrencyService : AutoCloseable { diff --git a/modules/features/currency-api/src/test/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyAccessTest.kt b/modules/features/currency-api/src/test/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyAccessTest.kt index ff16abec3..cc8e150bf 100644 --- a/modules/features/currency-api/src/test/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyAccessTest.kt +++ b/modules/features/currency-api/src/test/kotlin/org/pnfolder/pnlibrary/api/currency/CurrencyAccessTest.kt @@ -3,16 +3,17 @@ package org.pnfolder.pnlibrary.api.currency import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId class CurrencyAccessTest { @Test fun `patterns are normalized and blank patterns fail while building`() { - val access = CurrencyAccess.builder().allowMatching(" shop-* ").build() + val access = PluginAccess.builder().allowMatching(" shop-* ").build() assertTrue(access.allows(PluginId.of("economy"), PluginId.of("shop-menu"))) assertThrows(IllegalArgumentException::class.java) { - CurrencyAccess.builder().allowMatching(" ").build() + PluginAccess.builder().allowMatching(" ").build() } } } diff --git a/modules/features/currency-runtime/build.gradle.kts b/modules/features/currency-runtime/build.gradle.kts index bc3414ba9..1f0adcbe8 100644 --- a/modules/features/currency-runtime/build.gradle.kts +++ b/modules/features/currency-runtime/build.gradle.kts @@ -18,7 +18,8 @@ dependencies { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-currency", project.version.toString()) pom { name.set("pnLibrary Currency") diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/BuiltInCurrencyStorage.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/BuiltInCurrencyStorage.kt index 34057a879..ccc7e0b84 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/BuiltInCurrencyStorage.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/BuiltInCurrencyStorage.kt @@ -10,7 +10,7 @@ import java.time.Instant import java.util.concurrent.CompletionStage import javax.sql.DataSource -/** Creates built-in storage backends and coordinates portable snapshot migrations. */ +/** Creates built-in storage backends (file keeps 100 000 transactions by default) and migrates currencies between them. */ internal class BuiltInCurrencyStorage : CurrencyStorageFactory { override fun file(path: Path): CurrencyStorage = FileCurrencyStorage(path, 100_000) override fun file(path: Path, maximumTransactions: Int): CurrencyStorage = FileCurrencyStorage(path, maximumTransactions) diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/ConfiguredCurrencyProvider.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/ConfiguredCurrencyProvider.kt index d78b99465..293ce2d57 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/ConfiguredCurrencyProvider.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/ConfiguredCurrencyProvider.kt @@ -91,6 +91,7 @@ internal class CurrencyOperationsBuilder : CurrencyOperations { ) } + /** Wraps a synchronous callback result, or its exception, into an already completed stage. */ private fun completed(operation: () -> T): CompletionStage = try { CompletableFuture.completedFuture(operation()) } catch (error: Throwable) { @@ -135,15 +136,30 @@ private class ConfiguredCurrencyProvider( override fun extension(type: Class): T? = extensions[type]?.let(type::cast) + /** Result returned when the plugin did not configure the requested operation. */ private fun unsupported() = CompletableFuture.completedFuture(CurrencyResult.unsupported("Operation is not configured")) } /** Internal capability declaration used when a provider implements optional interfaces structurally. */ internal interface CurrencyCapabilitySource { + /** Operations the provider really supports, which may be fewer than the interfaces it implements. */ val declaredCapabilities: Set } +/** Stage failed with a generic message that keeps the callback's exception as the cause. */ +/** Capabilities of [provider]: those it declares, else one per optional interface it implements. */ +internal fun capabilitiesOf(provider: CurrencyProvider): Set = + if (provider is CurrencyCapabilitySource) provider.declaredCapabilities else buildSet { + add(CurrencyCapability.BALANCE) + if (provider is CurrencyDeposits) add(CurrencyCapability.DEPOSIT) + if (provider is CurrencyWithdrawals) add(CurrencyCapability.WITHDRAW) + if (provider is CurrencyBalanceMutation) add(CurrencyCapability.SET_BALANCE) + if (provider is CurrencyReset) add(CurrencyCapability.RESET) + if (provider is CurrencyTransfers) add(CurrencyCapability.TRANSFER) + if (provider is CurrencyFormatting) add(CurrencyCapability.FORMATTING) + } + private fun failedFuture(error: Throwable): CompletionStage = CompletableFuture().also { it.completeExceptionally(IllegalStateException("Currency operation failed", error)) } diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyBuilders.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyBuilders.kt index 38d493de6..161e8cb20 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyBuilders.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyBuilders.kt @@ -1,6 +1,5 @@ package org.pnfolder.pnlibrary.currency -import org.pnfolder.pnlibrary.api.currency.CurrencyAccess import org.pnfolder.pnlibrary.api.currency.CurrencyCommandOptions import org.pnfolder.pnlibrary.api.currency.CurrencyCommandSettings import org.pnfolder.pnlibrary.api.currency.CurrencyConfirmationMode @@ -14,10 +13,10 @@ import org.pnfolder.pnlibrary.api.currency.CurrencyRegistration import org.pnfolder.pnlibrary.api.currency.CurrencyRegistrationOptions import org.pnfolder.pnlibrary.api.currency.CurrencyStorage import org.pnfolder.pnlibrary.api.currency.ManagedCurrencyBuilder -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAccess -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderKey -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderPublication import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderKey +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderPublication +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId import java.math.BigDecimal import java.time.Duration @@ -29,12 +28,14 @@ import java.util.function.Consumer /** Common access and alias configuration shared by all currency builders. */ internal open class CurrencyOptions : CurrencyRegistrationOptions { - var access: CurrencyAccess = CurrencyAccess.ownerOnly() + /** Visibility policy; owner-only until the plugin widens it. */ + var access: PluginAccess = PluginAccess.ownerOnly() + /** Extra names under which the same currency can be resolved. */ val aliases = linkedSetOf() - override fun access(access: CurrencyAccess) = apply { this.access = access } - override fun access(configure: Consumer) = apply { - access = CurrencyAccess.builder().also(configure::accept).build() + override fun access(access: PluginAccess) = apply { this.access = access } + override fun access(configure: Consumer) = apply { + access = PluginAccess.builder().also(configure::accept).build() } override fun aliases(vararg aliases: String) = apply { this.aliases += aliases } } @@ -46,6 +47,7 @@ internal class CurrencyDefinition(private val name: String) : CurrencyOptions(), override fun descriptor(configure: Consumer) = apply { configure.accept(descriptor) } override fun operations(configure: Consumer) = apply { configure.accept(operations) } + /** Builds the callback-backed provider; call after the user's configuration has run. */ fun provider(): CurrencyProvider = operations.build(descriptor.build(), name) } @@ -77,6 +79,7 @@ internal class ManagedCurrencyDefinition( override fun placeholders(configure: Consumer) = apply { configure.accept(placeholderOptions) } override fun commands(configure: Consumer) = apply { configure.accept(commandOptions) } + /** Builds the storage-backed provider; fails when no storage was configured. */ fun provider(): CurrencyProvider = ManagedCurrencyProvider( key = CurrencyKey(owner, normalizeCurrencyName(name)), descriptor = descriptor.build(), @@ -86,6 +89,7 @@ internal class ManagedCurrencyDefinition( commandSettings = commandOptions.build(), ) + /** Registers balance, formatted and symbol placeholders for [currency]; the caller closes the returned handles. */ fun installPlaceholders(currency: CurrencyRegistration, placeholders: PlaceholderService): List { if (!placeholderOptions.enabled) return emptyList() val normalizedName = normalizeCurrencyName(name) @@ -115,14 +119,19 @@ internal class ManagedCurrencyDefinition( } } +/** Mutable placeholder switches collected from the plugin's configuration callback. */ private class ManagedPlaceholderOptions(defaultNamespace: String) : CurrencyPlaceholderOptions { + /** Whether placeholders are registered at all. */ var enabled = true - var access: PlaceholderAccess = PlaceholderAccess.ownerOnly() + /** Who may resolve the placeholders. */ + var access: PluginAccess = PluginAccess.ownerOnly() + /** Whether the placeholders are also published to PlaceholderAPI. */ var placeholderApi = false + /** PlaceholderAPI identifier prefix. */ var namespace = defaultNamespace override fun enabled(value: Boolean) = apply { enabled = value } - override fun access(access: PlaceholderAccess) = apply { this.access = access } + override fun access(access: PluginAccess) = apply { this.access = access } override fun placeholderApi(enabled: Boolean) = apply { placeholderApi = enabled } override fun placeholderApi(namespace: String) = apply { require(namespace.isNotBlank()) { "PlaceholderAPI namespace must not be blank" } @@ -131,6 +140,7 @@ private class ManagedPlaceholderOptions(defaultNamespace: String) : CurrencyPlac } } +/** Mutable command settings collected from the plugin's configuration callback, starting from the defaults. */ private class ManagedCommandOptions : CurrencyCommandOptions { private val defaults = CurrencyCommandSettings() private var enabled = defaults.enabled @@ -153,6 +163,7 @@ private class ManagedCommandOptions : CurrencyCommandOptions { override fun confirmation(mode: CurrencyConfirmationMode) = apply { confirmationMode = mode } override fun confirmationTimeout(value: Duration) = apply { confirmationTimeout = value } + /** Creates immutable settings; validates the confirmation timeout. */ fun build() = CurrencyCommandSettings( enabled = enabled, permissionPrefix = permissionPrefix, @@ -166,6 +177,7 @@ private class ManagedCommandOptions : CurrencyCommandOptions { ) } +/** Lowercases and validates a currency name or alias (`a-z`, digits, `_`, `.`, `-`). */ internal fun normalizeCurrencyName(value: String): String = value.trim().lowercase(Locale.ROOT).also { require(it.matches(Regex("[a-z0-9_.-]+"))) { "Invalid currency name: $value" } } diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyFeature.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyFeature.kt index c94656f8f..799577d39 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyFeature.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyFeature.kt @@ -6,9 +6,11 @@ import org.pnfolder.pnlibrary.api.currency.CurrencyStorageFactory import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService import org.pnfolder.pnlibrary.api.plugin.PluginId -/** Narrow integration boundary between the currency feature and pnLibrary core. */ -class CurrencyFeature : CurrencyRuntime { - private val hub = CurrencyHub() +/** Currency feature entry point: owns the registry hub and storage factory and hands plugins their scoped service. */ +class CurrencyFeature( + report: (message: String, error: Throwable) -> Unit = { _, _ -> }, +) : CurrencyRuntime { + private val hub = CurrencyHub(report) override val providers: CurrencyProviderRegistry get() = hub diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyFileWriter.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyFileWriter.kt new file mode 100644 index 000000000..82f5112af --- /dev/null +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyFileWriter.kt @@ -0,0 +1,55 @@ +package org.pnfolder.pnlibrary.currency + +import com.google.gson.GsonBuilder +import com.google.gson.JsonArray +import com.google.gson.JsonObject +import org.pnfolder.pnlibrary.api.currency.CurrencyTransaction +import java.io.Writer +import java.util.Collections +import java.util.IdentityHashMap + +/** + * Writes the currency file. Every transaction is encoded once and its text is kept, so a save only joins ready pieces; + * the bytes are exactly what Gson's pretty printer gives for the whole tree. + */ +internal class CurrencyFileWriter(private val onEncode: () -> Unit = {}) { + private val gson = GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create() + + // Identity, not equality: the ledger keeps the same instances between saves, and a different instance is simply encoded again. + private val fragments = IdentityHashMap() + + fun write(target: Writer, state: CurrencyLedgerState) { + val balances = JsonObject().also { values -> state.balances.forEach { (key, value) -> values.addProperty(key, value.toPlainString()) } } + if (state.transactions.isEmpty()) { + fragments.clear() + val root = JsonObject().also { it.add("balances", balances); it.add("transactions", JsonArray()) } + gson.toJson(root, target) + return + } + target.write("{\n \"balances\": ") + target.write(deeper(gson.toJson(balances), " ")) + target.write(",\n \"transactions\": [") + state.transactions.forEachIndexed { index, transaction -> + target.write(if (index == 0) "\n " else ",\n ") + target.write(fragment(transaction)) + } + target.write("\n ]\n}") + forgetAbsent(state) + } + + private fun fragment(transaction: CurrencyTransaction): String = fragments.getOrPut(transaction) { + onEncode() + deeper(gson.toJson(CurrencyTransactionJson.encode(transaction)), " ") + } + + // String values never hold raw line breaks (Gson escapes them), so every line break is structure. + private fun deeper(text: String, indent: String) = text.replace("\n", "\n$indent") + + /** Drops pieces of transactions that left the ledger: trimmed, replaced or rolled back. */ + private fun forgetAbsent(state: CurrencyLedgerState) { + if (fragments.size <= state.transactions.size) return + val present = Collections.newSetFromMap(IdentityHashMap()) + present.addAll(state.transactions) + fragments.keys.retainAll(present) + } +} diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyHub.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyHub.kt index adf77425b..2cf14c513 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyHub.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyHub.kt @@ -1,7 +1,6 @@ package org.pnfolder.pnlibrary.currency import org.pnfolder.pnlibrary.api.currency.Currency -import org.pnfolder.pnlibrary.api.currency.CurrencyAccess import org.pnfolder.pnlibrary.api.currency.CurrencyAccount import org.pnfolder.pnlibrary.api.currency.CurrencyBalanceMutation import org.pnfolder.pnlibrary.api.currency.CurrencyCapability @@ -22,6 +21,7 @@ import org.pnfolder.pnlibrary.api.currency.CurrencyTransfers import org.pnfolder.pnlibrary.api.currency.CurrencyWithdrawals import org.pnfolder.pnlibrary.api.currency.ManagedCurrencyBuilder import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import java.math.BigDecimal @@ -33,15 +33,21 @@ import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Consumer -/** Registered currencies with their owners, aliases and visibility; [scope] gives one plugin its own view. */ -internal class CurrencyHub : CurrencyProviderRegistry, AutoCloseable { +/** + * Registered currencies with their owners, aliases and visibility; [scope] gives one plugin its own view. + * A provider that throws is turned into a failed result for the caller and also passed to [report], so it is not lost. + */ +internal class CurrencyHub( + private val report: (message: String, error: Throwable) -> Unit = { _, _ -> }, +) : CurrencyProviderRegistry, AutoCloseable { private val entries = ConcurrentHashMap() private val aliases = ConcurrentHashMap, CurrencyKey>() private val closed = AtomicBoolean(false) + /** Creates the per-plugin view of this registry; call once per plugin that registers or resolves currencies. */ fun scope(owner: PluginId, placeholders: PlaceholderService): CurrencyService = Scope(owner, placeholders) - override fun register(owner: PluginId, name: String, provider: CurrencyProvider, access: CurrencyAccess): CurrencyRegistration = + override fun register(owner: PluginId, name: String, provider: CurrencyProvider, access: PluginAccess): CurrencyRegistration = install(owner, name, provider, access, emptySet()) override fun get(reference: String): Currency? { @@ -68,11 +74,12 @@ internal class CurrencyHub : CurrencyProviderRegistry, AutoCloseable { aliases.clear() } + /** Validates names and aliases, then publishes the entry atomically under the registry lock. */ private fun install( owner: PluginId, name: String, provider: CurrencyProvider, - access: CurrencyAccess, + access: PluginAccess, requestedAliases: Set, ): Entry { check(!closed.get()) { "Currency registry is closed" } @@ -92,6 +99,7 @@ internal class CurrencyHub : CurrencyProviderRegistry, AutoCloseable { return entry } + /** Registry view of one plugin: its own registrations plus the currencies whose access policy admits it. */ private inner class Scope(private val owner: PluginId, private val placeholders: PlaceholderService) : CurrencyService { private val owned = ConcurrentHashMap.newKeySet() private val scopeClosed = AtomicBoolean(false) @@ -153,10 +161,11 @@ internal class CurrencyHub : CurrencyProviderRegistry, AutoCloseable { private fun checkOpen() = check(!scopeClosed.get()) { "Currencies for $owner are closed" } } + /** One registered currency: wraps the provider with state, capability checks and amount normalization. */ private inner class Entry( override val key: CurrencyKey, private val provider: CurrencyProvider, - val access: CurrencyAccess, + val access: PluginAccess, private val registeredAliases: Set, ) : CurrencyRegistration { private val attachments = Collections.synchronizedList(mutableListOf()) @@ -168,15 +177,7 @@ internal class CurrencyHub : CurrencyProviderRegistry, AutoCloseable { enabled.get() -> CurrencyRegistrationState.ACTIVE else -> CurrencyRegistrationState.DISABLED } - override val capabilities = if (provider is CurrencyCapabilitySource) provider.declaredCapabilities else buildSet { - add(CurrencyCapability.BALANCE) - if (provider is CurrencyDeposits) add(CurrencyCapability.DEPOSIT) - if (provider is CurrencyWithdrawals) add(CurrencyCapability.WITHDRAW) - if (provider is CurrencyBalanceMutation) add(CurrencyCapability.SET_BALANCE) - if (provider is CurrencyReset) add(CurrencyCapability.RESET) - if (provider is CurrencyTransfers) add(CurrencyCapability.TRANSFER) - if (provider is CurrencyFormatting) add(CurrencyCapability.FORMATTING) - } + override val capabilities = capabilitiesOf(provider) override fun balance(playerId: UUID): CompletionStage = availableValue { provider.balance(CurrencyAccount(playerId)).thenApply(descriptor::normalize) @@ -224,14 +225,18 @@ internal class CurrencyHub : CurrencyProviderRegistry, AutoCloseable { entries.remove(key, this) registeredAliases.forEach { aliases.remove(key.owner to it, key) } } - attachments.toList().forEach { runCatchingNonFatal(it::close) } + attachments.toList().forEach { runCatchingNonFatal(it::close).onFailure(::reportCloseFailure) } attachments.clear() - if (provider is AutoCloseable) runCatchingNonFatal(provider::close) + if (provider is AutoCloseable) runCatchingNonFatal(provider::close).onFailure(::reportCloseFailure) } + private fun reportCloseFailure(error: Throwable) = report("Currency $key did not close cleanly", error) + + /** Ties [registration] (for example a placeholder) to this entry so it is closed together with it. */ fun attach(registration: AutoCloseable) { attachments += registration } + /** Runs an amount-based mutation after state, capability and amount validation. */ private fun amountOperation( capability: CurrencyCapability, amount: BigDecimal, @@ -243,6 +248,7 @@ internal class CurrencyHub : CurrencyProviderRegistry, AutoCloseable { if (!accepts(amount)) return invalidAmount() return safeResult { operation(descriptor.normalize(amount)) } } + /** Runs a mutation without an amount after state and capability validation. */ private fun resultOperation( capability: CurrencyCapability, operation: () -> CompletionStage, @@ -266,18 +272,27 @@ internal class CurrencyHub : CurrencyProviderRegistry, AutoCloseable { private fun availableValue(operation: () -> CompletionStage): CompletionStage { if (state != CurrencyRegistrationState.ACTIVE) return failed("Currency $key is not active") return try { - operation() + operation().whenComplete { _, error -> + if (error != null) report("Currency $key failed", error.cause ?: error) + } } catch (error: Throwable) { + report("Currency $key failed", error) failed("Currency $key failed", error) } } + /** Converts provider exceptions, thrown or asynchronous, into a failed [CurrencyResult]. */ private fun safeResult(operation: () -> CompletionStage): CompletionStage = try { - operation().exceptionally(CurrencyResult::failed) + operation().exceptionally { error -> + report("Currency $key operation failed", error.cause ?: error) + CurrencyResult.failed(error) + } } catch (error: Throwable) { + report("Currency $key operation failed", error) CompletableFuture.completedFuture(CurrencyResult.failed(error)) } } + /** Resolves `owner:name` or a bare name, which belongs to [consumer]. */ private fun parseReference(consumer: PluginId, reference: String): CurrencyKey { val separator = reference.indexOf(':') return if (separator < 0) { diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyLedgerState.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyLedgerState.kt new file mode 100644 index 000000000..f9a8a6054 --- /dev/null +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyLedgerState.kt @@ -0,0 +1,121 @@ +package org.pnfolder.pnlibrary.currency + +import org.pnfolder.pnlibrary.api.currency.CurrencyAccount +import org.pnfolder.pnlibrary.api.currency.CurrencyDescriptor +import org.pnfolder.pnlibrary.api.currency.CurrencyKey +import org.pnfolder.pnlibrary.api.currency.CurrencyTransaction +import org.pnfolder.pnlibrary.api.currency.CurrencyTransactionRequest +import java.math.BigDecimal + +/** Balances, ledger and idempotency index of the file storage; changes made with an undo log can be taken back step by step. */ +internal class CurrencyLedgerState { + val balances = linkedMapOf() + val transactions = ArrayDeque() + private val idempotency = hashMapOf() + + /** The earlier transaction recorded under the request's idempotency key, if any. */ + fun replay(currency: CurrencyKey, request: CurrencyTransactionRequest): CurrencyTransaction? = + request.idempotencyKey?.let { idempotency[idempotencyKey(currency, it)] } + + fun hasIdempotencyKey(currency: CurrencyKey, key: String) = idempotencyKey(currency, key) in idempotency + + /** Evaluates [request] against current balances, stores the new balances when it commits, records and trims the ledger. */ + fun apply( + currency: CurrencyKey, + descriptor: CurrencyDescriptor, + request: CurrencyTransactionRequest, + maximumTransactions: Int, + undo: LedgerUndo, + ): CurrencyTransaction { + val sourceKey = request.source?.let { accountKey(currency, it) } + val targetKey = request.target?.let { accountKey(currency, it) } + val sourceBefore = sourceKey?.let { balances[it] ?: BigDecimal.ZERO }?.let(descriptor::normalize) + val targetBefore = targetKey?.let { balances[it] ?: BigDecimal.ZERO }?.let(descriptor::normalize) + val mutation = CurrencyMutationEngine.evaluate(request, sourceBefore, targetBefore, descriptor) + if (mutation.committed) { + sourceKey?.let { setBalance(it, descriptor.normalize(requireNotNull(mutation.sourceAfter)), undo) } + targetKey?.let { setBalance(it, descriptor.normalize(requireNotNull(mutation.targetAfter)), undo) } + } + return mutation.transaction(currency, descriptor, request).also { transaction -> + record(transaction, undo) + trim(maximumTransactions, undo) + } + } + + /** Appends [transaction] to the ledger and indexes its idempotency key. */ + fun record(transaction: CurrencyTransaction, undo: LedgerUndo? = null) { + transactions.addLast(transaction) + val key = transaction.idempotencyKey?.let { idempotencyKey(transaction.currency, it) } + val previous = key?.let { idempotency.put(it, transaction) } + undo?.add { + transactions.removeLast() + if (key != null) if (previous == null) idempotency.remove(key) else idempotency[key] = previous + } + } + + /** Drops the oldest transactions beyond [maximumTransactions], together with their idempotency keys. */ + fun trim(maximumTransactions: Int, undo: LedgerUndo? = null) { + while (transactions.size > maximumTransactions) { + val old = transactions.removeFirst() + val key = old.idempotencyKey?.let { idempotencyKey(old.currency, it) } + val indexedKey = key?.takeIf { idempotency.remove(it, old) } + undo?.add { + transactions.addFirst(old) + if (indexedKey != null) idempotency[indexedKey] = old + } + } + } + + /** Deletes all balances, transactions and idempotency keys of [currency]. */ + fun removeCurrency(currency: CurrencyKey) { + val prefix = "$currency|" + balances.keys.removeIf { it.startsWith(prefix) } + transactions.removeAll { it.currency == currency } + idempotency.keys.removeIf { it.startsWith(prefix) } + } + + /** Full copy for operations that rewrite much of the state at once. */ + fun copy(): Copy = Copy(LinkedHashMap(balances), transactions.toList(), HashMap(idempotency)) + + fun restore(copy: Copy) { + balances.clear() + balances.putAll(copy.balances) + transactions.clear() + transactions.addAll(copy.transactions) + idempotency.clear() + idempotency.putAll(copy.idempotency) + } + + private fun setBalance(key: String, value: BigDecimal, undo: LedgerUndo) { + val previous = balances.put(key, value) + undo.add { if (previous == null) balances.remove(key) else balances[key] = previous } + } + + class Copy(val balances: Map, val transactions: List, val idempotency: Map) + + companion object { + /** Map key of one account balance: `currency|playerId`. */ + fun accountKey(currency: CurrencyKey, account: CurrencyAccount) = "$currency|${account.playerId}" + + /** Map key of one idempotency key, scoped per currency. */ + fun idempotencyKey(currency: CurrencyKey, key: String) = "$currency|$key" + } +} + +/** Reverse steps of the changes made to a [CurrencyLedgerState]; reverting restores it exactly. */ +internal class LedgerUndo { + private val steps = ArrayList<() -> Unit>() + + fun add(step: () -> Unit) { + steps += step + } + + /** Position to pass to [revertTo] to undo only what is added after this call. */ + fun mark(): Int = steps.size + + fun revertTo(mark: Int) { + while (steps.size > mark) steps.removeAt(steps.size - 1)() + } + + fun revert() = revertTo(0) +} diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyMutationEngine.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyMutationEngine.kt index f3ecc69dc..bdbe2ddd4 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyMutationEngine.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyMutationEngine.kt @@ -16,7 +16,7 @@ internal object CurrencyMutationEngine { const val INSUFFICIENT_FUNDS = "Insufficient funds" /** - * A rejected transition preserves both balances. Storage implementations are + * Computes the new balances for [request] from the current ones. A rejected transition preserves both balances. Storage implementations are * responsible for descriptor normalization before reading and after committing. */ fun evaluate( @@ -58,6 +58,7 @@ internal object CurrencyMutationEngine { ) } + /** Creates a rejection that leaves both balances unchanged. */ private fun rejected(source: BigDecimal?, target: BigDecimal?, failure: String = INSUFFICIENT_FUNDS) = CurrencyMutation( status = CurrencyTransactionStatus.REJECTED, sourceBefore = source, @@ -77,6 +78,7 @@ internal data class CurrencyMutation( val targetAfter: BigDecimal?, val failure: String? = null, ) { + /** True when the balances must be written. */ val committed: Boolean get() = status == CurrencyTransactionStatus.COMMITTED /** The ledger record of this mutation, created when the storage has applied it. */ diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyRequestValidation.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyRequestValidation.kt index 794336495..d1deb010f 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyRequestValidation.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyRequestValidation.kt @@ -6,6 +6,7 @@ import org.pnfolder.pnlibrary.api.currency.CurrencyTransactionType /** Shared validation at both the provider and persistence boundaries. */ internal object CurrencyRequestValidation { + /** Returns the reason [request] is invalid for [descriptor], or null when it may proceed. */ fun failure(descriptor: CurrencyDescriptor, request: CurrencyTransactionRequest): String? { val amountValid = descriptor.accepts(request.amount) && when (request.type) { CurrencyTransactionType.SET_BALANCE -> request.amount.signum() >= 0 diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyTransactionJson.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyTransactionJson.kt index cffcf83fc..02a2cf029 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyTransactionJson.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/CurrencyTransactionJson.kt @@ -14,6 +14,7 @@ import java.util.UUID /** How a transaction is written to and read from the currency file. */ internal object CurrencyTransactionJson { + /** Serializes [value]; absent optional fields are omitted. */ fun encode(value: CurrencyTransaction) = JsonObject().apply { addProperty("id", value.id.toString()) addProperty("currency", value.currency.toString()) @@ -38,6 +39,7 @@ internal object CurrencyTransactionJson { }) } + /** Reads a transaction written by [encode]; optional fields default to null. */ fun decode(value: JsonObject): CurrencyTransaction { val currencyParts = value["currency"].asString.split(':', limit = 2) fun decimal(name: String) = value.get(name)?.takeUnless { it.isJsonNull }?.asString?.toBigDecimal() diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/FileCurrencyStorage.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/FileCurrencyStorage.kt index ba63db196..a0aca2070 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/FileCurrencyStorage.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/FileCurrencyStorage.kt @@ -1,8 +1,5 @@ package org.pnfolder.pnlibrary.currency -import com.google.gson.GsonBuilder -import com.google.gson.JsonArray -import com.google.gson.JsonObject import com.google.gson.JsonParser import org.pnfolder.pnlibrary.api.currency.CurrencyAccount import org.pnfolder.pnlibrary.api.currency.CurrencyDescriptor @@ -23,19 +20,26 @@ import java.nio.file.Files import java.nio.file.Path import java.time.Instant import java.util.UUID +import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage +import java.util.concurrent.ConcurrentLinkedQueue +import java.util.concurrent.atomic.AtomicBoolean -/** Single-writer JSON storage: every change is kept in memory only after the whole file has been saved. */ +/** + * Single-writer JSON storage with group commit: transactions that wait together are applied one after another and saved + * once. Each result is reported only after the file holding it has reached the disk. + */ internal class FileCurrencyStorage( private val file: Path, private val maximumTransactions: Int, + private val encoded: () -> Unit = {}, + private val replaceFile: (Path, (Path) -> Unit) -> Unit = { target, fill -> AtomicFiles.write(target, durable = true, fill) }, ) : CurrencyStorage { - private val lock = Any() private val worker = ManagedWorker("pnLibrary-currency-file") - private val balances = linkedMapOf() - private val transactions = mutableListOf() - private val idempotency = hashMapOf() - private val gson = GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create() + private val state = CurrencyLedgerState() + private val jobs = ConcurrentLinkedQueue() + private val drainScheduled = AtomicBoolean() + private val writer = CurrencyFileWriter(encoded) init { require(maximumTransactions in 100..1_000_000) { "maximumTransactions must be between 100 and 1000000" } @@ -43,29 +47,21 @@ internal class FileCurrencyStorage( } override fun balance(currency: CurrencyKey, account: CurrencyAccount): CompletionStage = async { - synchronized(lock) { balances[accountKey(currency, account)] ?: BigDecimal.ZERO } + state.balances[CurrencyLedgerState.accountKey(currency, account)] ?: BigDecimal.ZERO } override fun transact( currency: CurrencyKey, descriptor: CurrencyDescriptor, request: CurrencyTransactionRequest, - ): CompletionStage = async { - synchronized(lock) { - request.idempotencyKey?.let { idempotency[idempotencyKey(currency, it)] }?.let { return@synchronized it } - atomically { - apply(currency, descriptor, request).also { transaction -> - record(transaction) - trimHistory() - } - } - } + ): CompletionStage { + val job = Job.Transact(currency, descriptor, request) + enqueue(job) + return job.result } override fun history(currency: CurrencyKey, query: CurrencyHistoryQuery): CompletionStage = async { - val filtered = synchronized(lock) { - transactions.asReversed().filter { transaction -> matches(transaction, currency, query) } - } + val filtered = state.transactions.asReversed().filter { transaction -> matches(transaction, currency, query) } CurrencyHistoryPage( items = filtered.drop(query.offset).take(query.limit), offset = query.offset, @@ -74,37 +70,33 @@ internal class FileCurrencyStorage( } override fun export(currency: CurrencyKey): CompletionStage = async { - synchronized(lock) { - val prefix = "$currency|" - val exportedBalances = balances.entries.filter { it.key.startsWith(prefix) }.associate { - UUID.fromString(it.key.removePrefix(prefix)) to it.value - } - CurrencyStorageSnapshot( - currency = currency, - createdAt = Instant.now(), - balances = exportedBalances, - transactions = transactions.filter { it.currency == currency }, - ) + val prefix = "$currency|" + val exportedBalances = state.balances.entries.filter { it.key.startsWith(prefix) }.associate { + UUID.fromString(it.key.removePrefix(prefix)) to it.value } + CurrencyStorageSnapshot( + currency = currency, + createdAt = Instant.now(), + balances = exportedBalances, + transactions = state.transactions.filter { it.currency == currency }, + ) } override fun importSnapshot(snapshot: CurrencyStorageSnapshot, mode: CurrencyImportMode): CompletionStage = async { - synchronized(lock) { - require(snapshot.transactions.all { it.currency == snapshot.currency }) { "Snapshot contains transactions from another currency" } - atomically { - if (mode == CurrencyImportMode.REPLACE) removeCurrency(snapshot.currency) - val accounts = importBalances(snapshot, mode) - val moved = importTransactions(snapshot) - trimHistory() - CurrencyImportResult( - currency = snapshot.currency, - mode = mode, - importedAccounts = accounts.first, - skippedAccounts = accounts.second, - importedTransactions = moved.first, - skippedTransactions = moved.second, - ) - } + require(snapshot.transactions.all { it.currency == snapshot.currency }) { "Snapshot contains transactions from another currency" } + replacingState { + if (mode == CurrencyImportMode.REPLACE) state.removeCurrency(snapshot.currency) + val accounts = importBalances(snapshot, mode) + val moved = importTransactions(snapshot) + state.trim(maximumTransactions) + CurrencyImportResult( + currency = snapshot.currency, + mode = mode, + importedAccounts = accounts.first, + skippedAccounts = accounts.second, + importedTransactions = moved.first, + skippedTransactions = moved.second, + ) } } @@ -113,11 +105,11 @@ internal class FileCurrencyStorage( var imported = 0 var skipped = 0 snapshot.balances.forEach { (accountId, balance) -> - val key = accountKey(snapshot.currency, CurrencyAccount(accountId)) - if (mode == CurrencyImportMode.MERGE_KEEP_TARGET && balances.containsKey(key)) { + val key = CurrencyLedgerState.accountKey(snapshot.currency, CurrencyAccount(accountId)) + if (mode == CurrencyImportMode.MERGE_KEEP_TARGET && state.balances.containsKey(key)) { skipped++ } else { - balances[key] = balance + state.balances[key] = balance imported++ } } @@ -128,13 +120,13 @@ internal class FileCurrencyStorage( private fun importTransactions(snapshot: CurrencyStorageSnapshot): Pair { var imported = 0 var skipped = 0 - val ids = transactions.mapTo(hashSetOf()) { it.id } + val ids = state.transactions.mapTo(hashSetOf()) { it.id } snapshot.transactions.forEach { transaction -> - val duplicateKey = transaction.idempotencyKey?.let { idempotencyKey(snapshot.currency, it) } - if (transaction.id in ids || duplicateKey != null && duplicateKey in idempotency) { + val duplicate = transaction.idempotencyKey?.let { state.hasIdempotencyKey(snapshot.currency, it) } == true + if (transaction.id in ids || duplicate) { skipped++ } else { - record(transaction) + state.record(transaction) ids += transaction.id imported++ } @@ -146,65 +138,100 @@ internal class FileCurrencyStorage( worker.close() } - private fun apply(currency: CurrencyKey, descriptor: CurrencyDescriptor, request: CurrencyTransactionRequest): CurrencyTransaction { - val sourceKey = request.source?.let { accountKey(currency, it) } - val targetKey = request.target?.let { accountKey(currency, it) } - val sourceBefore = sourceKey?.let { balances[it] ?: BigDecimal.ZERO }?.let(descriptor::normalize) - val targetBefore = targetKey?.let { balances[it] ?: BigDecimal.ZERO }?.let(descriptor::normalize) - val mutation = CurrencyMutationEngine.evaluate(request, sourceBefore, targetBefore, descriptor) - if (mutation.committed) { - sourceKey?.let { balances[it] = descriptor.normalize(requireNotNull(mutation.sourceAfter)) } - targetKey?.let { balances[it] = descriptor.normalize(requireNotNull(mutation.targetAfter)) } - } - return mutation.transaction(currency, descriptor, request) - } - + /** Reads balances and ledger from [file]; a missing file means an empty store. */ private fun load() { if (!Files.exists(file)) return require(!Files.isSymbolicLink(file)) { "Currency storage file must not be a symbolic link" } val root = Files.newBufferedReader(file, StandardCharsets.UTF_8).use { JsonParser.parseReader(it).asJsonObject } - root.getAsJsonObject("balances")?.entrySet()?.forEach { balances[it.key] = it.value.asString.toBigDecimal() } + root.getAsJsonObject("balances")?.entrySet()?.forEach { state.balances[it.key] = it.value.asString.toBigDecimal() } root.getAsJsonArray("transactions")?.forEach { element -> - record(CurrencyTransactionJson.decode(element.asJsonObject)) + state.record(CurrencyTransactionJson.decode(element.asJsonObject)) } } /** Applies [change] and saves; on any failure memory goes back to what the file still holds. */ - private fun atomically(change: () -> T): T { - val before = snapshotState() + private fun replacingState(change: () -> T): T { + val before = state.copy() try { return change().also { save() } } catch (error: Throwable) { - restore(before) + state.restore(before) throw error } } - private fun record(transaction: CurrencyTransaction) { - transactions += transaction - transaction.idempotencyKey?.let { idempotency[idempotencyKey(transaction.currency, it)] = transaction } + /** Queues [job] for the worker; one drain run takes everything that waits, so jobs keep their arrival order. */ + private fun enqueue(job: Job) { + jobs.add(job) + if (!drainScheduled.compareAndSet(false, true)) return + try { + worker.submit(::drain).whenComplete { _, error -> if (error != null) failWaiting(error) } + } catch (error: Throwable) { + drainScheduled.set(false) + // A drain that already took the job will still answer it. + if (jobs.remove(job)) throw error + } } - private fun trimHistory() { - val excess = transactions.size - maximumTransactions - if (excess <= 0) return - val evicted = transactions.subList(0, excess) - evicted.forEach { old -> old.idempotencyKey?.let { idempotency.remove(idempotencyKey(old.currency, it), old) } } - evicted.clear() + private fun drain() { + drainScheduled.set(false) + while (true) { + val first = jobs.poll() ?: return + if (first is Job.Other) { + first.run() + continue + } + val batch = arrayListOf(first as Job.Transact) + while (batch.size < MAXIMUM_BATCH && jobs.peek() is Job.Transact) batch += jobs.poll() as Job.Transact + commit(batch) + } + } + + /** Applies [batch] in order and saves once; if that save fails, each transaction gets its own save so only the failing ones fail. */ + private fun commit(batch: List) { + val undo = LedgerUndo() + val waiting = arrayListOf>() + val unsaved = hashSetOf() + batch.forEach { job -> + val replay = state.replay(job.currency, job.request) + if (replay != null && replay.id !in unsaved) return@forEach job.finish(replay) + val mark = undo.mark() + val transaction = try { + replay ?: state.apply(job.currency, job.descriptor, job.request, maximumTransactions, undo) + } catch (error: Throwable) { + undo.revertTo(mark) + return@forEach job.fail(error) + } + unsaved += transaction.id + waiting += job to transaction + } + if (waiting.isEmpty()) return + try { + save() + } catch (error: Throwable) { + undo.revert() + if (waiting.size == 1) waiting.single().first.fail(error) else waiting.forEach { commit(listOf(it.first)) } + return + } + waiting.forEach { (job, transaction) -> job.finish(transaction) } + } + + /** Fails everything still queued when the worker gives up, so no caller waits forever. */ + private fun failWaiting(error: Throwable) { + drainScheduled.set(false) + while (true) (jobs.poll() ?: return).fail(error) } // Balances are money: the file must reach the disk before it replaces the previous one, or a power loss // after the rename can leave an empty file. private fun save() { require(!Files.isSymbolicLink(file)) { "Currency storage file must not be a symbolic link" } - val root = JsonObject() - root.add("balances", JsonObject().also { values -> balances.forEach { (key, value) -> values.addProperty(key, value.toPlainString()) } }) - root.add("transactions", JsonArray().also { values -> transactions.forEach { values.add(CurrencyTransactionJson.encode(it)) } }) - AtomicFiles.write(file, durable = true) { temporary -> - Files.newBufferedWriter(temporary, StandardCharsets.UTF_8).use { gson.toJson(root, it) } + replaceFile(file) { temporary -> + Files.newBufferedWriter(temporary, StandardCharsets.UTF_8).use { writer.write(it, state) } } } + /** Applies every non-null filter of [query] with logical AND. */ private fun matches( transaction: CurrencyTransaction, currency: CurrencyKey, @@ -217,37 +244,49 @@ internal class FileCurrencyStorage( (query.from == null || !transaction.createdAt.isBefore(query.from)) && (query.until == null || transaction.createdAt.isBefore(query.until)) - private fun snapshotState() = StorageState( - balances = LinkedHashMap(balances), - transactions = transactions.toList(), - idempotency = HashMap(idempotency), - ) - - private fun restore(state: StorageState) { - balances.clear() - balances.putAll(state.balances) - transactions.clear() - transactions.addAll(state.transactions) - idempotency.clear() - idempotency.putAll(state.idempotency) + /** Queues [operation] on the single storage worker so file access never blocks the caller. */ + private fun async(operation: () -> T): CompletionStage { + val result = CompletableFuture() + enqueue(Job.Other( + action = { + try { + result.complete(operation()) + } catch (error: Throwable) { + result.completeExceptionally(error) + } + }, + onFail = { error -> result.completeExceptionally(error) }, + )) + return result } - private fun accountKey(currency: CurrencyKey, account: CurrencyAccount) = "$currency|${account.playerId}" + private sealed interface Job { + fun fail(error: Throwable) - private fun idempotencyKey(currency: CurrencyKey, key: String) = "$currency|$key" + class Transact( + val currency: CurrencyKey, + val descriptor: CurrencyDescriptor, + val request: CurrencyTransactionRequest, + ) : Job { + val result = CompletableFuture() - private fun removeCurrency(currency: CurrencyKey) { - val prefix = "$currency|" - balances.keys.removeIf { it.startsWith(prefix) } - transactions.removeIf { it.currency == currency } - idempotency.keys.removeIf { it.startsWith(prefix) } - } + fun finish(transaction: CurrencyTransaction) { + result.complete(transaction) + } + + override fun fail(error: Throwable) { + result.completeExceptionally(error) + } + } - private fun async(operation: () -> T): CompletionStage = worker.submit(operation) + class Other(private val action: () -> Unit, private val onFail: (Throwable) -> Unit) : Job { + fun run() = action() - private data class StorageState( - val balances: Map, - val transactions: List, - val idempotency: Map, - ) + override fun fail(error: Throwable) = onFail(error) + } + } + + private companion object { + const val MAXIMUM_BATCH = 500 + } } diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencyLedger.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencyLedger.kt index d74b9ed30..5b2559d6b 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencyLedger.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencyLedger.kt @@ -17,6 +17,7 @@ internal class JdbcCurrencyLedger( private val accountsTable = schema.accountsTable private val transactionsTable = schema.transactionsTable + /** Returns the balance without locking; absent accounts read as zero. */ fun readBalance(connection: Connection, currency: CurrencyKey, account: CurrencyAccount): BigDecimal = selectBalance(connection, currency, account, "") @@ -26,6 +27,7 @@ internal class JdbcCurrencyLedger( return selectBalance(connection, currency, account, if (sqlite) "" else " FOR UPDATE") } + /** Selects the balance row, appending [suffix] (a lock clause or nothing). */ private fun selectBalance(connection: Connection, currency: CurrencyKey, account: CurrencyAccount, suffix: String): BigDecimal { val sql = "SELECT balance FROM $accountsTable WHERE currency_id = ? AND account_id = ?$suffix" connection.prepareStatement(sql).use { statement -> @@ -64,6 +66,7 @@ internal class JdbcCurrencyLedger( } } + /** Returns whether a balance row exists for [account]. */ fun accountExists(connection: Connection, currency: CurrencyKey, account: CurrencyAccount): Boolean { connection.prepareStatement( "SELECT 1 FROM $accountsTable WHERE currency_id = ? AND account_id = ?", @@ -91,6 +94,7 @@ internal class JdbcCurrencyLedger( } } + /** Inserts one ledger row. */ fun insertTransaction(connection: Connection, value: CurrencyTransaction) { connection.prepareStatement(schema.insertTransactionSql()).use { statement -> val values = listOf( @@ -119,6 +123,7 @@ internal class JdbcCurrencyLedger( } } + /** Returns the transaction already stored under [key], or null when the key is new. */ fun findIdempotent(connection: Connection, currency: CurrencyKey, key: String): CurrencyTransaction? { connection.prepareStatement( "SELECT * FROM $transactionsTable WHERE currency_id = ? AND idempotency_key = ?", @@ -129,6 +134,7 @@ internal class JdbcCurrencyLedger( } } + /** Deletes all balances and ledger rows of [currency]. */ fun deleteCurrency(connection: Connection, currency: CurrencyKey) { listOf(transactionsTable, accountsTable).forEach { table -> connection.prepareStatement("DELETE FROM $table WHERE currency_id = ?").use { statement -> diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencySchema.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencySchema.kt index f99d3b262..11a297ab7 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencySchema.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencySchema.kt @@ -6,9 +6,12 @@ internal class JdbcCurrencySchema(tablePrefix: String) { require(tablePrefix.matches(PREFIX_PATTERN)) { "Invalid currency table prefix" } } + /** Table holding one balance row per currency and account. */ val accountsTable = "${tablePrefix}_accounts" + /** Table holding the append-only ledger. */ val transactionsTable = "${tablePrefix}_transactions" + /** DDL of the balances table. */ fun createAccountsTableSql(): String = """ CREATE TABLE IF NOT EXISTS $accountsTable ( currency_id VARCHAR(190) NOT NULL, @@ -18,6 +21,7 @@ internal class JdbcCurrencySchema(tablePrefix: String) { ) """.trimIndent() + /** DDL of the ledger table; the unique key makes idempotent retries safe. */ fun createTransactionsTableSql(): String = """ CREATE TABLE IF NOT EXISTS $transactionsTable ( transaction_id VARCHAR(36) PRIMARY KEY, @@ -43,6 +47,7 @@ internal class JdbcCurrencySchema(tablePrefix: String) { ) """.trimIndent() + /** Insert statement whose 19 placeholders follow the column order of the ledger table. */ fun insertTransactionSql(): String = """ INSERT INTO $transactionsTable ( transaction_id, currency_id, transaction_type, status, amount, diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencySnapshots.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencySnapshots.kt index cf32c9703..53c68bd2a 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencySnapshots.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencySnapshots.kt @@ -20,6 +20,7 @@ internal class JdbcCurrencySnapshots( private val accountsTable = schema.accountsTable private val transactionsTable = schema.transactionsTable + /** Reads all balances and the full ledger of [currency] in the caller's transaction. */ fun export(connection: Connection, currency: CurrencyKey): CurrencyStorageSnapshot { val balances = linkedMapOf() connection.prepareStatement( diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencyStorage.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencyStorage.kt index 7003d9e40..c86d991dd 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencyStorage.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcCurrencyStorage.kt @@ -59,6 +59,7 @@ internal class JdbcCurrencyStorage( } } + /** Locks the affected accounts, evaluates [request] and writes balances and the ledger row. */ private fun applyMutation( connection: Connection, currency: CurrencyKey, @@ -97,6 +98,7 @@ internal class JdbcCurrencyStorage( } } + /** True for serialization failure, deadlock and constraint violation SQL states. */ private fun isConflict(error: SQLException): Boolean { val state = error.sqlState ?: return false return state == "40001" || state == "40P01" || state.startsWith("23") @@ -128,6 +130,7 @@ internal class JdbcCurrencyStorage( worker.close() } + /** Creates the tables once per storage instance, on first use. */ private fun ensureSchema() { if (initialized) return synchronized(schemaLock) { @@ -142,11 +145,13 @@ internal class JdbcCurrencyStorage( } } + /** Borrows a pooled connection for [operation] and returns it afterwards. */ private fun connection(operation: (Connection) -> T): T { ensureSchema() return dataSource.connection.use(operation) } + /** Runs [operation] in one transaction with [isolation]; rolls back on failure and restores connection settings. */ private fun committed(connection: Connection, isolation: Int, operation: () -> T): T { val previous = ConnectionSettings.capture(connection) connection.autoCommit = false @@ -154,13 +159,14 @@ internal class JdbcCurrencyStorage( return try { operation().also { connection.commit() } } catch (error: Throwable) { - runCatchingNonFatal { connection.rollback() } + runCatchingNonFatal { connection.rollback() }.onFailure(error::addSuppressed) throw error } finally { previous.restore(connection) } } + /** Runs [operation] on the storage worker pool so JDBC never blocks the caller. */ private fun async(operation: () -> T): CompletionStage = worker.submit(operation) private companion object { @@ -170,12 +176,14 @@ internal class JdbcCurrencyStorage( /** Transaction settings of a borrowed connection, put back before it returns to the caller's pool. */ private class ConnectionSettings(private val autoCommit: Boolean, private val isolation: Int) { + /** Reapplies the captured settings; failures are ignored because the connection is being returned. */ fun restore(connection: Connection) { runCatchingNonFatal { connection.autoCommit = autoCommit } runCatchingNonFatal { connection.transactionIsolation = isolation } } companion object { + /** Reads the current settings of [connection]. */ fun capture(connection: Connection) = ConnectionSettings(connection.autoCommit, connection.transactionIsolation) } } diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcHistoryQuery.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcHistoryQuery.kt index b0ccad201..1cef20b62 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcHistoryQuery.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcHistoryQuery.kt @@ -33,6 +33,7 @@ internal class JdbcHistoryQuery( } } + /** Translates the filters of [query] into a parameterized SELECT without limit and offset values. */ private fun statement(currency: CurrencyKey, query: CurrencyHistoryQuery): SqlStatement { val clauses = mutableListOf("currency_id = ?") val parameters = mutableListOf(currency.toString()) @@ -71,6 +72,7 @@ internal class JdbcHistoryQuery( ) } + /** SQL text with its positional parameters. */ private data class SqlStatement( val sql: String, val parameters: List, diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcTransactionDecoder.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcTransactionDecoder.kt index f281a1d1d..aef6f9214 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcTransactionDecoder.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/JdbcTransactionDecoder.kt @@ -15,6 +15,7 @@ import java.util.UUID /** Maps a ledger row of [JdbcCurrencySchema] to a [CurrencyTransaction]. */ internal class JdbcTransactionDecoder(private val gson: Gson) { + /** Reads the current row of [result]; the caller advances the cursor. */ fun decode(result: ResultSet): CurrencyTransaction { val parts = result.getString("currency_id").split(':', limit = 2) fun account(column: String) = result.getString(column)?.let(UUID::fromString)?.let(::CurrencyAccount) diff --git a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/ManagedCurrencyProvider.kt b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/ManagedCurrencyProvider.kt index 4257fb455..512041ff6 100644 --- a/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/ManagedCurrencyProvider.kt +++ b/modules/features/currency-runtime/src/main/kotlin/org/pnfolder/pnlibrary/currency/ManagedCurrencyProvider.kt @@ -93,6 +93,7 @@ internal class ManagedCurrencyProvider( if (ownsStorage) storage.close() } + /** Builds the rejected record returned when validation fails before storage is touched. */ private fun rejectedTransaction(request: CurrencyTransactionRequest, failure: String) = CurrencyTransaction( id = UUID.randomUUID(), currency = key, @@ -110,6 +111,7 @@ internal class ManagedCurrencyProvider( idempotencyKey = request.idempotencyKey, ) + /** Submits a system-initiated transaction for the simple API operations and maps the outcome to a result. */ private fun mutate( type: CurrencyTransactionType, amount: BigDecimal, @@ -128,6 +130,7 @@ internal class ManagedCurrencyProvider( ), ).thenApply(::toResult) + /** Maps a stored transaction to the consumer-facing result. */ private fun toResult(transaction: CurrencyTransaction): CurrencyResult = when (transaction.status) { CurrencyTransactionStatus.COMMITTED -> CurrencyResult.success( transaction.sourceBalanceBefore ?: transaction.targetBalanceBefore, @@ -138,6 +141,7 @@ internal class ManagedCurrencyProvider( CurrencyResult.failed(IllegalStateException(transaction.failure ?: "Currency transaction failed")) } + /** Insufficient funds is reported distinctly; any other rejection is a provider rejection. */ private fun rejectReason(transaction: CurrencyTransaction) = if (transaction.failure == CurrencyMutationEngine.INSUFFICIENT_FUNDS) { CurrencyRejectReason.INSUFFICIENT_FUNDS diff --git a/modules/features/currency-runtime/src/test/kotlin/org/pnfolder/pnlibrary/currency/CurrencyFileBytesTest.kt b/modules/features/currency-runtime/src/test/kotlin/org/pnfolder/pnlibrary/currency/CurrencyFileBytesTest.kt new file mode 100644 index 000000000..f75ca50c6 --- /dev/null +++ b/modules/features/currency-runtime/src/test/kotlin/org/pnfolder/pnlibrary/currency/CurrencyFileBytesTest.kt @@ -0,0 +1,131 @@ +package org.pnfolder.pnlibrary.currency + +import com.google.gson.GsonBuilder +import com.google.gson.JsonArray +import com.google.gson.JsonObject +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.currency.CurrencyAccount +import org.pnfolder.pnlibrary.api.currency.CurrencyActor +import org.pnfolder.pnlibrary.api.currency.CurrencyDescriptor +import org.pnfolder.pnlibrary.api.currency.CurrencyImportMode +import org.pnfolder.pnlibrary.api.currency.CurrencyKey +import org.pnfolder.pnlibrary.api.currency.CurrencyTransactionRequest +import org.pnfolder.pnlibrary.api.currency.CurrencyTransactionType +import org.pnfolder.pnlibrary.api.plugin.PluginId +import org.pnfolder.pnlibrary.common.io.AtomicFiles +import java.math.BigDecimal +import java.math.RoundingMode +import java.nio.file.Files +import java.nio.file.Path +import java.security.MessageDigest +import java.util.Random +import java.util.UUID +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong + +class CurrencyFileBytesTest { + private val currency = CurrencyKey(PluginId.of("test"), "coins") + private val descriptor = CurrencyDescriptor("Coins", "C", 2, RoundingMode.DOWN) + private val accounts = (1..5).map { CurrencyAccount(UUID(0, it.toLong())) } + private val gson = GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create() + private val reasons = listOf(null, "plain", "quote ${34.toChar()} slash ${92.toChar()} tab${9.toChar()} line${10.toChar()}break", + "&' é 日本 😀 ${8232.toChar()}", "") + + private fun requests(count: Int): List { + val random = Random(7) + return (0 until count).map { index -> + val type = CurrencyTransactionType.entries[random.nextInt(CurrencyTransactionType.entries.size)] + val first = accounts[random.nextInt(accounts.size)] + val second = accounts[random.nextInt(accounts.size)] + CurrencyTransactionRequest( + type = type, + amount = if (type == CurrencyTransactionType.RESET) BigDecimal.ZERO else BigDecimal(random.nextInt(900) + 1).movePointLeft(2), + source = if (type == CurrencyTransactionType.DEBIT || type == CurrencyTransactionType.TRANSFER) first else null, + target = if (type == CurrencyTransactionType.TRANSFER) second else if (type == CurrencyTransactionType.DEBIT) null else first, + actor = CurrencyActor.system("test"), service = "bytes-test", + reason = reasons[index % reasons.size], + metadata = if (index % 3 == 0) mapOf("k$index" to "v \"$index\"", "é" to "<&>") else emptyMap(), + idempotencyKey = if (index % 7 == 0) "key-${random.nextInt(20)}" else null, + ) + } + } + + /** What the storage wrote before the pieces were cached: the whole tree through Gson's pretty printer. */ + private fun legacyBytes(storage: FileCurrencyStorage): ByteArray { + val snapshot = storage.export(currency).toCompletableFuture().join() + val root = JsonObject() + root.add("balances", JsonObject().also { values -> + snapshot.balances.forEach { (id, value) -> + values.addProperty(CurrencyLedgerState.accountKey(currency, CurrencyAccount(id)), value.toPlainString()) + } + }) + root.add("transactions", JsonArray().also { values -> snapshot.transactions.forEach { values.add(CurrencyTransactionJson.encode(it)) } }) + return gson.toJson(root).toByteArray(Charsets.UTF_8) + } + + private fun sha(bytes: ByteArray) = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } + + @Test + fun `the file is byte for byte what the whole-tree writer gives, with trimming and failed saves`(@TempDir directory: Path) { + val file = directory.resolve("ledger.json") + val calls = AtomicInteger() + val failing = setOf(5, 6, 90, 91, 200) + var compared = 0 + FileCurrencyStorage(file, 100, replaceFile = { target, fill -> + if (calls.incrementAndGet() in failing) error("disk full") + AtomicFiles.write(target, durable = false, fill) + }).use { storage -> + requests(400).forEachIndexed { index, request -> + runCatching { storage.transact(currency, descriptor, request).toCompletableFuture().join() } + if (index % 5 == 0 && Files.exists(file)) { + assertEquals(sha(legacyBytes(storage)), sha(Files.readAllBytes(file)), "after request $index") + compared++ + } + } + assertEquals(sha(legacyBytes(storage)), sha(Files.readAllBytes(file))) + } + assertTrue(compared > 70) + } + + @Test + fun `an emptied ledger and a reloaded file keep the same bytes`(@TempDir directory: Path) { + val file = directory.resolve("ledger.json") + FileCurrencyStorage(file, 1000).use { storage -> + requests(60).forEach { storage.transact(currency, descriptor, it).toCompletableFuture().join() } + val snapshot = storage.export(currency).toCompletableFuture().join() + storage.importSnapshot(snapshot.copy(balances = emptyMap(), transactions = emptyList()), CurrencyImportMode.REPLACE) + .toCompletableFuture().join() + assertEquals(sha(legacyBytes(storage)), sha(Files.readAllBytes(file))) + assertTrue(String(Files.readAllBytes(file)).contains("\"transactions\": []")) + storage.importSnapshot(snapshot, CurrencyImportMode.REPLACE).toCompletableFuture().join() + assertEquals(sha(legacyBytes(storage)), sha(Files.readAllBytes(file))) + } + val reloaded = Files.readAllBytes(file) + FileCurrencyStorage(file, 1000).use { storage -> + storage.transact(currency, descriptor, requests(1).single()).toCompletableFuture().join() + assertEquals(sha(legacyBytes(storage)), sha(Files.readAllBytes(file))) + } + assertTrue(reloaded.isNotEmpty()) + } + + @Test + fun `a thousand operations encode each transaction once`(@TempDir directory: Path) { + val encodings = AtomicLong() + val ledgerSizes = ArrayList() + val storage = FileCurrencyStorage(directory.resolve("ledger.json"), 5000, { encodings.incrementAndGet() }) { target, fill -> + AtomicFiles.write(target, durable = false, fill) + ledgerSizes += 1 + } + storage.use { + requests(1000).forEach { storage.transact(currency, descriptor, it).toCompletableFuture().join() } + val ledger = storage.export(currency).toCompletableFuture().join().transactions.size + // before: each of the saves encoded the whole ledger so far; now each transaction once + val old = (1..ledgerSizes.size).fold(0L) { total, save -> total + minOf(save, ledger) } + assertEquals(ledger.toLong(), encodings.get()) + assertTrue(old > 100L * encodings.get(), "old=$old new=${encodings.get()}") + } + } +} diff --git a/modules/features/currency-runtime/src/test/kotlin/org/pnfolder/pnlibrary/currency/CurrencyHubTest.kt b/modules/features/currency-runtime/src/test/kotlin/org/pnfolder/pnlibrary/currency/CurrencyHubTest.kt index 745814f84..f8c51b737 100644 --- a/modules/features/currency-runtime/src/test/kotlin/org/pnfolder/pnlibrary/currency/CurrencyHubTest.kt +++ b/modules/features/currency-runtime/src/test/kotlin/org/pnfolder/pnlibrary/currency/CurrencyHubTest.kt @@ -5,12 +5,12 @@ import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.currency.CurrencyAccess import org.pnfolder.pnlibrary.api.currency.CurrencyAccount import org.pnfolder.pnlibrary.api.currency.CurrencyDescriptor import org.pnfolder.pnlibrary.api.currency.CurrencyProvider import org.pnfolder.pnlibrary.api.currency.CurrencyRegistrationState import org.pnfolder.pnlibrary.api.placeholders.PlaceholderService +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId import java.lang.reflect.Proxy import java.math.BigDecimal @@ -37,7 +37,7 @@ class CurrencyHubTest { val owner = hub.scope(PluginId.of("owner"), placeholders()) val consumer = hub.scope(PluginId.of("consumer"), placeholders()) val registration = owner.register("coins", provider(), Consumer { - it.access(CurrencyAccess.shared()) + it.access(PluginAccess.shared()) }) assertSame(registration, consumer.get("owner:coins")) @@ -54,6 +54,25 @@ class CurrencyHubTest { hub.close() } + @Test + fun `a provider that throws is reported to the owner as well as failing the call`() { + val reported = mutableListOf>() + val hub = CurrencyHub { message, error -> reported += message to error } + val owner = hub.scope(PluginId.of("owner"), placeholders()) + val broken = object : CurrencyProvider, AutoCloseable { + override val descriptor = CurrencyDescriptor("Coins", "C", 2, RoundingMode.DOWN) + override fun balance(account: CurrencyAccount): CompletableFuture = error("balance broke") + override fun close() = error("close broke") + } + val registration = owner.register("coins", broken) + + assertThrows(Exception::class.java) { registration.balance(java.util.UUID.randomUUID()).toCompletableFuture().get() } + registration.close() + + assertEquals(listOf("balance broke", "close broke"), reported.map { it.second.message }) + hub.close() + } + private fun provider() = object : CurrencyProvider, AutoCloseable { override val descriptor = CurrencyDescriptor("Coins", "C", 2, RoundingMode.DOWN) override fun balance(account: CurrencyAccount) = CompletableFuture.completedFuture(BigDecimal.ZERO) diff --git a/modules/features/currency-runtime/src/test/kotlin/org/pnfolder/pnlibrary/currency/FileCurrencyStorageBatchTest.kt b/modules/features/currency-runtime/src/test/kotlin/org/pnfolder/pnlibrary/currency/FileCurrencyStorageBatchTest.kt new file mode 100644 index 000000000..744f987b0 --- /dev/null +++ b/modules/features/currency-runtime/src/test/kotlin/org/pnfolder/pnlibrary/currency/FileCurrencyStorageBatchTest.kt @@ -0,0 +1,228 @@ +package org.pnfolder.pnlibrary.currency + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.currency.CurrencyAccount +import org.pnfolder.pnlibrary.api.currency.CurrencyActor +import org.pnfolder.pnlibrary.api.currency.CurrencyDescriptor +import org.pnfolder.pnlibrary.api.currency.CurrencyHistoryQuery +import org.pnfolder.pnlibrary.api.currency.CurrencyKey +import org.pnfolder.pnlibrary.api.currency.CurrencyTransaction +import org.pnfolder.pnlibrary.api.currency.CurrencyTransactionRequest +import org.pnfolder.pnlibrary.api.currency.CurrencyTransactionType +import org.pnfolder.pnlibrary.api.plugin.PluginId +import org.pnfolder.pnlibrary.common.io.AtomicFiles +import java.math.BigDecimal +import java.math.RoundingMode +import java.nio.file.Files +import java.nio.file.Path +import java.security.MessageDigest +import java.util.Random +import java.util.UUID +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CompletionException +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong + +class FileCurrencyStorageBatchTest { + private val currency = CurrencyKey(PluginId.of("test"), "coins") + private val descriptor = CurrencyDescriptor("Coins", "C", 2, RoundingMode.DOWN) + private val accounts = (1..5).map { CurrencyAccount(UUID(0, it.toLong())) } + + private fun corpus(count: Int): List { + val random = Random(42) + return (0 until count).map { index -> + val type = CurrencyTransactionType.entries[random.nextInt(CurrencyTransactionType.entries.size)] + val amount = when { + type == CurrencyTransactionType.RESET -> BigDecimal.ZERO + index % 13 == 0 -> BigDecimal("1.005") + else -> BigDecimal(random.nextInt(900) + 1).movePointLeft(2) + } + val first = accounts[random.nextInt(accounts.size)] + val second = accounts[random.nextInt(accounts.size)] + CurrencyTransactionRequest( + type = type, amount = amount, + source = if (type == CurrencyTransactionType.DEBIT || type == CurrencyTransactionType.TRANSFER) first else null, + target = if (type == CurrencyTransactionType.TRANSFER) second else if (type == CurrencyTransactionType.DEBIT) null else first, + actor = CurrencyActor.system("test"), service = "batch-test", + idempotencyKey = if (index % 7 == 0) "key-${random.nextInt(20)}" else null, + ) + } + } + + private fun describe(transaction: CurrencyTransaction) = listOf( + transaction.type, transaction.status, transaction.amount, transaction.source?.playerId, transaction.target?.playerId, + transaction.sourceBalanceBefore, transaction.sourceBalanceAfter, transaction.targetBalanceBefore, transaction.targetBalanceAfter, + transaction.failure, transaction.idempotencyKey, + ).joinToString("|") + + private fun state(storage: FileCurrencyStorage): String { + val snapshot = storage.export(currency).toCompletableFuture().join() + val balances = snapshot.balances.entries.sortedBy { it.key }.joinToString(",") { "${it.key}=${it.value}" } + return balances + "\n" + snapshot.transactions.joinToString("\n", transform = ::describe) + } + + private fun sha(text: String) = MessageDigest.getInstance("SHA-256").digest(text.toByteArray()).joinToString("") { "%02x".format(it) } + + private fun outcome(future: CompletableFuture) = try { + describe(future.join()) + } catch (error: CompletionException) { + "failed:" + error.cause?.message + } + + private fun run(file: Path, queued: Boolean, writer: ((Path, (Path) -> Unit) -> Unit)? = null): String { + val storage = if (writer == null) FileCurrencyStorage(file, 100) else FileCurrencyStorage(file, 100, replaceFile = writer) + storage.use { + val futures = ArrayList>() + val log = StringBuilder() + corpus(400).forEach { request -> + val future = it.transact(currency, descriptor, request).toCompletableFuture() + if (queued) futures += future else log.append(outcome(future)).append('\n') + } + futures.forEach { log.append(outcome(it)).append('\n') } + log.append(state(it)) + return log.toString() + } + } + + @Test + fun `corpus gives the same ledger when sequential or queued`(@TempDir directory: Path) { + val sequential = run(directory.resolve("a.json"), queued = false) + val queued = run(directory.resolve("b.json"), queued = true) + assertEquals(sequential, queued) + assertEquals(GOLDEN, sha(sequential)) + } + + @Test + fun `corpus with failing writes gives the pinned result`(@TempDir directory: Path) { + val calls = AtomicInteger() + val failing = setOf(3, 7, 8, 100) + val result = run(directory.resolve("c.json"), queued = false) { target, fill -> + if (calls.incrementAndGet() in failing) error("disk full") + AtomicFiles.write(target, durable = true, fill) + } + assertEquals(GOLDEN_FAILING, sha(result)) + } + + @Test + fun `reloading the file gives the same balances and history`(@TempDir directory: Path) { + val file = directory.resolve("d.json") + val before = FileCurrencyStorage(file, 100).use { storage -> + corpus(400).map { storage.transact(currency, descriptor, it) }.forEach { it.toCompletableFuture().join() } + state(storage) + } + assertEquals(before, FileCurrencyStorage(file, 100).use(::state)) + } + + @Test + fun `a thousand parallel transactions are saved in a few batches`(@TempDir directory: Path) { + val file = directory.resolve("e.json") + val saves = AtomicInteger() + val written = AtomicLong() + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val storage = FileCurrencyStorage(file, 100_000) { target, fill -> + if (saves.incrementAndGet() == 1) { + entered.countDown() + assertTrue(release.await(10, TimeUnit.SECONDS)) + } + AtomicFiles.write(target, durable = false, fill) + written.addAndGet(Files.size(target)) + } + storage.use { + val credit = credit("1") + val futures = ArrayList>() + futures += it.transact(currency, descriptor, credit).toCompletableFuture() + assertTrue(entered.await(10, TimeUnit.SECONDS)) + repeat(999) { _ -> futures += it.transact(currency, descriptor, credit).toCompletableFuture() } + release.countDown() + futures.forEach { future -> future.join() } + assertEquals(BigDecimal("1000.00"), it.balance(currency, accounts[0]).toCompletableFuture().join()) + } + val finalSize = Files.size(file) + assertTrue(saves.get() <= 10, "saves=${saves.get()}") + assertTrue(written.get() <= 10 * finalSize, "written=${written.get()} final=$finalSize") + } + + @Test + fun `a failed batch save keeps balances and idempotency and later transactions still work`(@TempDir directory: Path) { + val broken = AtomicBoolean(false) + val blockNext = AtomicBoolean(false) + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val storage = FileCurrencyStorage(directory.resolve("f.json"), 100) { target, fill -> + val failed = broken.get() + if (blockNext.compareAndSet(true, false)) { + entered.countDown() + release.await(10, TimeUnit.SECONDS) + } + if (failed) error("disk full") + AtomicFiles.write(target, durable = false, fill) + } + storage.use { + it.transact(currency, descriptor, credit("5", "ok")).toCompletableFuture().join() + blockNext.set(true) + val blocker = it.transact(currency, descriptor, credit("1")).toCompletableFuture() + assertTrue(entered.await(10, TimeUnit.SECONDS)) + broken.set(true) + val doomed = (1..5).map { n -> it.transact(currency, descriptor, credit("10", "doomed-$n")).toCompletableFuture() } + release.countDown() + blocker.join() + doomed.forEach { future -> assertThrows(CompletionException::class.java) { future.join() } } + assertEquals(0, BigDecimal("6").compareTo(it.balance(currency, accounts[0]).toCompletableFuture().join())) + assertEquals(2, it.history(currency, CurrencyHistoryQuery()).toCompletableFuture().join().items.size) + broken.set(false) + val retried = it.transact(currency, descriptor, credit("10", "doomed-1")).toCompletableFuture().join() + assertEquals(0, BigDecimal("16").compareTo(retried.targetBalanceAfter)) + } + } + + @Test + fun `a failed batch brings back evicted history and its idempotency keys`(@TempDir directory: Path) { + val broken = AtomicBoolean(false) + val blockNext = AtomicBoolean(false) + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val storage = FileCurrencyStorage(directory.resolve("g.json"), 100) { target, fill -> + val failed = broken.get() + if (blockNext.compareAndSet(true, false)) { + entered.countDown() + release.await(10, TimeUnit.SECONDS) + } + if (failed) error("disk full") + AtomicFiles.write(target, durable = false, fill) + } + storage.use { + repeat(99) { n -> it.transact(currency, descriptor, credit("1", "old-$n")).toCompletableFuture().join() } + blockNext.set(true) + val blocker = it.transact(currency, descriptor, credit("0.01")).toCompletableFuture() + assertTrue(entered.await(10, TimeUnit.SECONDS)) + broken.set(true) + val doomed = (1..30).map { n -> it.transact(currency, descriptor, credit("2", "new-$n")).toCompletableFuture() } + release.countDown() + blocker.join() + doomed.forEach { future -> assertThrows(CompletionException::class.java) { future.join() } } + broken.set(false) + val replayed = it.transact(currency, descriptor, credit("5", "old-0")).toCompletableFuture().join() + assertEquals(0, BigDecimal("1").compareTo(replayed.amount)) + assertEquals(100, it.history(currency, CurrencyHistoryQuery(limit = 500)).toCompletableFuture().join().items.size) + assertEquals(0, BigDecimal("99.01").compareTo(it.balance(currency, accounts[0]).toCompletableFuture().join())) + } + } + + private fun credit(amount: String, key: String? = null) = CurrencyTransactionRequest( + type = CurrencyTransactionType.CREDIT, amount = BigDecimal(amount), target = accounts[0], + actor = CurrencyActor.system("test"), service = "batch-test", idempotencyKey = key, + ) + + private companion object { + const val GOLDEN = "b2d6d39db3fda0f3a53ba7c27164e601886a2b5ad36b8f117abdb25c69c59d54" + const val GOLDEN_FAILING = "66c00db1263b8b105cfe6a9a3a73e6f4fd76d3c1f1f355d321a7831f94647e14" + } +} diff --git a/modules/features/minecraft-localization-api/api/minecraft-localization-api.api b/modules/features/localization-api/api/localization-api.api similarity index 100% rename from modules/features/minecraft-localization-api/api/minecraft-localization-api.api rename to modules/features/localization-api/api/localization-api.api diff --git a/modules/features/localization-api/api/minecraft-localization-api.api b/modules/features/localization-api/api/minecraft-localization-api.api new file mode 100644 index 000000000..4634c1c59 --- /dev/null +++ b/modules/features/localization-api/api/minecraft-localization-api.api @@ -0,0 +1,409 @@ +public abstract interface class org/pnfolder/pnlibrary/localization/LocaleTranslations { + public fun getLayouts ()Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayouts; + public abstract fun getLocale ()Ljava/lang/String; + public abstract fun getMetadata ()Lorg/pnfolder/pnlibrary/localization/TranslationMetadata; + public abstract fun keys ()Lorg/pnfolder/pnlibrary/localization/TranslationIndex; + public abstract fun translate (Ljava/lang/String;)Ljava/util/Optional; + public fun translate (Lorg/pnfolder/pnlibrary/localization/TranslatableType;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/localization/Translation; + public fun translateOrKey (Ljava/lang/String;)Ljava/lang/String; + public abstract fun translations ()Ljava/util/Map; +} + +public final class org/pnfolder/pnlibrary/localization/MinecraftLocale : java/lang/Enum { + public static final field AF_ZA Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field AR_SA Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field AST_ES Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field AZ_AZ Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field BAR Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field BA_RU Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field BE_BY Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field BG_BG Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field BRB Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field BR_FR Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field BS_BA Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field CA_ES Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field CS_CZ Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field CY_GB Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field Companion Lorg/pnfolder/pnlibrary/localization/MinecraftLocale$Companion; + public static final field DA_DK Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field DE_AT Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field DE_CH Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field DE_DE Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field EL_GR Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ENP Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ENWS Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field EN_AU Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field EN_CA Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field EN_GB Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field EN_NZ Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field EN_PT Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field EN_UD Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field EN_US Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field EO_UY Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ESAN Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ES_AR Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ES_CL Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ES_EC Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ES_ES Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ES_MX Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ES_UY Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ES_VE Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ET_EE Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field EU_ES Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field FA_IR Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field FIL_PH Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field FI_FI Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field FO_FO Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field FRA_DE Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field FR_CA Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field FR_FR Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field FUR_IT Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field FY_NL Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field GA_IE Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field GD_GB Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field GL_ES Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field HAW_US Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field HE_IL Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field HI_IN Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field HR_HR Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field HU_HU Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field HY_AM Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ID_ID Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field IG_NG Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field IO_EN Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ISV Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field IS_IS Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field IT_IT Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field JA_JP Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field JBO_EN Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field KA_GE Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field KK_KZ Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field KN_IN Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field KO_KR Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field KSH Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field KW_GB Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field LA_LA Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field LB_LU Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field LI_LI Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field LMO Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field LOL_US Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field LT_LT Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field LV_LV Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field LZH Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field MK_MK Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field MN_MN Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field MS_MY Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field MT_MT Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field NAH Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field NDS_DE Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field NL_BE Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field NL_NL Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field NN_NO Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field NO_NO Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field OC_FR Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field OVD Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field PL_PL Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field PT_BR Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field PT_PT Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field QYA_AA Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field RO_RO Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field RPR Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field RU_RU Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field RY_UA Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field SAH_SAH Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field SE_NO Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field SK_SK Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field SL_SI Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field SO_SO Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field SQ_AL Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field SR_SP Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field SV_SE Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field SWG Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field SXU Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field SZL Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field TA_IN Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field TH_TH Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field TLH_AA Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field TL_PH Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field TOK Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field TR_TR Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field TT_RU Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field TZL_TZL Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field UK_UA Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field VAL_ES Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field VEC_IT Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field VI_VN Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field VP_VL Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field YI_DE Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field YO_NG Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ZH_CN Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ZH_HK Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ZH_TW Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static final field ZLM_ARAB Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public final fun getCode ()Ljava/lang/String; + public final fun getEnglishName ()Ljava/lang/String; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public final fun getNativeName ()Ljava/lang/String; + public static final fun parse (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; + public static fun values ()[Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; +} + +public final class org/pnfolder/pnlibrary/localization/MinecraftLocale$Companion { + public final fun parse (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/MinecraftLocale; +} + +public abstract interface class org/pnfolder/pnlibrary/localization/MinecraftLocalization : java/lang/AutoCloseable { + public static final field Companion Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization$Companion; + public abstract fun availableLocales (Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersion;)Ljava/util/concurrent/CompletionStage; + public abstract fun availableVersions ()Ljava/util/concurrent/CompletionStage; + public static fun builder ()Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization$Builder; + public abstract fun close ()V + public abstract fun getLayouts ()Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayouts; + public abstract fun load (Lorg/pnfolder/pnlibrary/localization/TranslationRequest;)Ljava/util/concurrent/CompletionStage; + public fun locale (Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersion;Ljava/lang/String;)Ljava/util/concurrent/CompletionStage; + public fun locale (Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersion;Lorg/pnfolder/pnlibrary/localization/MinecraftLocale;)Ljava/util/concurrent/CompletionStage; + public abstract fun refresh (Lorg/pnfolder/pnlibrary/localization/TranslationRequest;)Ljava/util/concurrent/CompletionStage; +} + +public final class org/pnfolder/pnlibrary/localization/MinecraftLocalization$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization; + public final fun cacheDirectory (Ljava/nio/file/Path;)Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization$Builder; + public final fun connectTimeout (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization$Builder; + public final fun downloadConcurrency (I)Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization$Builder; + public final fun executor (Ljava/util/concurrent/ExecutorService;)Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization$Builder; + public final fun layouts (Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayouts;)Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization$Builder; + public final fun manifestTtl (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization$Builder; + public final fun memoryEntries (I)Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization$Builder; + public final fun readTimeout (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization$Builder; +} + +public final class org/pnfolder/pnlibrary/localization/MinecraftLocalization$Companion { + public final fun builder ()Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization$Builder; +} + +public final class org/pnfolder/pnlibrary/localization/MinecraftLocalizationDslKt { + public static final synthetic fun load (Lorg/pnfolder/pnlibrary/localization/MinecraftLocalization;Lkotlin/jvm/functions/Function1;)Ljava/util/concurrent/CompletionStage; +} + +public abstract interface class org/pnfolder/pnlibrary/localization/TranslatableType { + public abstract fun fallbackName (Ljava/lang/Object;)Ljava/lang/String; + public abstract fun keysOf (Ljava/lang/Object;)Ljava/util/List; +} + +public final class org/pnfolder/pnlibrary/localization/Translation { + public fun (Ljava/lang/String;Ljava/lang/String;Z)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Z + public final fun copy (Ljava/lang/String;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/localization/Translation; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/localization/Translation;Ljava/lang/String;Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/localization/Translation; + public fun equals (Ljava/lang/Object;)Z + public final fun getKey ()Ljava/lang/String; + public final fun getLocalized ()Z + public final fun getText ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public abstract interface class org/pnfolder/pnlibrary/localization/TranslationBundle { + public abstract fun getLocales ()Ljava/util/Set; + public abstract fun getVersion ()Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersion; + public abstract fun locale (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/LocaleTranslations; + public fun locale (Lorg/pnfolder/pnlibrary/localization/MinecraftLocale;)Lorg/pnfolder/pnlibrary/localization/LocaleTranslations; +} + +public final class org/pnfolder/pnlibrary/localization/TranslationCategory : java/lang/Enum { + public static final field BIOME Lorg/pnfolder/pnlibrary/localization/TranslationCategory; + public static final field BLOCK Lorg/pnfolder/pnlibrary/localization/TranslationCategory; + public static final field COLOR Lorg/pnfolder/pnlibrary/localization/TranslationCategory; + public static final field Companion Lorg/pnfolder/pnlibrary/localization/TranslationCategory$Companion; + public static final field EFFECT Lorg/pnfolder/pnlibrary/localization/TranslationCategory; + public static final field ENCHANTMENT Lorg/pnfolder/pnlibrary/localization/TranslationCategory; + public static final field ENTITY Lorg/pnfolder/pnlibrary/localization/TranslationCategory; + public static final field GAME_MODE Lorg/pnfolder/pnlibrary/localization/TranslationCategory; + public static final field ITEM Lorg/pnfolder/pnlibrary/localization/TranslationCategory; + public static final field VANILLA_NAMESPACE Ljava/lang/String; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public final fun getId ()Ljava/lang/String; + public final fun key (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; + public static synthetic fun key$default (Lorg/pnfolder/pnlibrary/localization/TranslationCategory;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Ljava/lang/String; + public final fun prefix (Ljava/lang/String;)Ljava/lang/String; + public static synthetic fun prefix$default (Lorg/pnfolder/pnlibrary/localization/TranslationCategory;Ljava/lang/String;ILjava/lang/Object;)Ljava/lang/String; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/TranslationCategory; + public static fun values ()[Lorg/pnfolder/pnlibrary/localization/TranslationCategory; +} + +public final class org/pnfolder/pnlibrary/localization/TranslationCategory$Companion { +} + +public final class org/pnfolder/pnlibrary/localization/TranslationException : java/lang/RuntimeException { + public fun (Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason;Ljava/lang/String;Ljava/lang/Throwable;)V + public synthetic fun (Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason;Ljava/lang/String;Ljava/lang/Throwable;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun getReason ()Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason; +} + +public final class org/pnfolder/pnlibrary/localization/TranslationException$Reason : java/lang/Enum { + public static final field CLOSED Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason; + public static final field INTEGRITY Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason; + public static final field INVALID_LOCALE Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason; + public static final field MALFORMED_DATA Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason; + public static final field OFFLINE Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason; + public static final field REMOTE Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason; + public static final field UNAVAILABLE_LOCALE Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason; + public static final field UNSUPPORTED_VERSION Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason; + public static fun values ()[Lorg/pnfolder/pnlibrary/localization/TranslationException$Reason; +} + +public abstract interface class org/pnfolder/pnlibrary/localization/TranslationIndex { + public static final field Companion Lorg/pnfolder/pnlibrary/localization/TranslationIndex$Companion; + public fun best (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/TranslationMatch; + public fun best (Ljava/lang/String;D)Lorg/pnfolder/pnlibrary/localization/TranslationMatch; + public abstract fun best (Ljava/lang/String;DLjava/util/Collection;)Lorg/pnfolder/pnlibrary/localization/TranslationMatch; + public abstract fun findExact (Ljava/lang/String;)Ljava/util/List; + public fun fuzzy (Ljava/lang/String;)Ljava/util/List; + public abstract fun fuzzy (Ljava/lang/String;DI)Ljava/util/List; + public fun getLayouts ()Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayouts; + public static fun of (Ljava/util/List;)Lorg/pnfolder/pnlibrary/localization/TranslationIndex; + public static fun of (Ljava/util/List;Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayouts;)Lorg/pnfolder/pnlibrary/localization/TranslationIndex; + public abstract fun search (Ljava/lang/String;)Ljava/util/List; + public fun suggest (Ljava/lang/String;)Ljava/util/List; + public fun suggest (Ljava/lang/String;I)Ljava/util/List; + public abstract fun suggest (Ljava/lang/String;ILjava/util/Collection;)Ljava/util/List; +} + +public final class org/pnfolder/pnlibrary/localization/TranslationIndex$Companion { + public final fun of (Ljava/util/List;)Lorg/pnfolder/pnlibrary/localization/TranslationIndex; + public final fun of (Ljava/util/List;Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayouts;)Lorg/pnfolder/pnlibrary/localization/TranslationIndex; + public static synthetic fun of$default (Lorg/pnfolder/pnlibrary/localization/TranslationIndex$Companion;Ljava/util/List;Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayouts;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/localization/TranslationIndex; +} + +public final class org/pnfolder/pnlibrary/localization/TranslationMatch { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Ljava/lang/Object; + public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/localization/TranslationMatch; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/localization/TranslationMatch;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/localization/TranslationMatch; + public fun equals (Ljava/lang/Object;)Z + public final fun getKey ()Ljava/lang/String; + public final fun getTranslation ()Ljava/lang/String; + public final fun getValue ()Ljava/lang/Object; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/localization/TranslationMetadata { + public fun (Lorg/pnfolder/pnlibrary/localization/TranslationSource;Ljava/lang/String;Z)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/localization/TranslationSource; + public final fun component2 ()Ljava/lang/String; + public final fun component3 ()Z + public final fun copy (Lorg/pnfolder/pnlibrary/localization/TranslationSource;Ljava/lang/String;Z)Lorg/pnfolder/pnlibrary/localization/TranslationMetadata; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/localization/TranslationMetadata;Lorg/pnfolder/pnlibrary/localization/TranslationSource;Ljava/lang/String;ZILjava/lang/Object;)Lorg/pnfolder/pnlibrary/localization/TranslationMetadata; + public fun equals (Ljava/lang/Object;)Z + public final fun getSha1 ()Ljava/lang/String; + public final fun getSource ()Lorg/pnfolder/pnlibrary/localization/TranslationSource; + public final fun getStale ()Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/localization/TranslationRequest { + public static final field Companion Lorg/pnfolder/pnlibrary/localization/TranslationRequest$Companion; + public static final fun builder ()Lorg/pnfolder/pnlibrary/localization/TranslationRequest$Builder; + public final fun getFallbackLocale ()Ljava/lang/String; + public final fun getLocales ()Ljava/util/Set; + public final fun getVersion ()Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersion; +} + +public final class org/pnfolder/pnlibrary/localization/TranslationRequest$Builder { + public final fun build ()Lorg/pnfolder/pnlibrary/localization/TranslationRequest; + public final fun fallback (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/TranslationRequest$Builder; + public final fun fallback (Lorg/pnfolder/pnlibrary/localization/MinecraftLocale;)Lorg/pnfolder/pnlibrary/localization/TranslationRequest$Builder; + public final fun locale (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/TranslationRequest$Builder; + public final fun locale (Lorg/pnfolder/pnlibrary/localization/MinecraftLocale;)Lorg/pnfolder/pnlibrary/localization/TranslationRequest$Builder; + public final fun locales (Ljava/util/Collection;)Lorg/pnfolder/pnlibrary/localization/TranslationRequest$Builder; + public final fun locales ([Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/TranslationRequest$Builder; + public final fun locales ([Lorg/pnfolder/pnlibrary/localization/MinecraftLocale;)Lorg/pnfolder/pnlibrary/localization/TranslationRequest$Builder; + public final fun version (Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersion;)Lorg/pnfolder/pnlibrary/localization/TranslationRequest$Builder; +} + +public final class org/pnfolder/pnlibrary/localization/TranslationRequest$Companion { + public final fun builder ()Lorg/pnfolder/pnlibrary/localization/TranslationRequest$Builder; +} + +public final class org/pnfolder/pnlibrary/localization/TranslationRequestDsl { + public field version Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersion; + public final fun fallback (Ljava/lang/String;)V + public final fun fallback (Lorg/pnfolder/pnlibrary/localization/MinecraftLocale;)V + public final fun getVersion ()Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersion; + public final fun locales ([Ljava/lang/String;)V + public final fun locales ([Lorg/pnfolder/pnlibrary/localization/MinecraftLocale;)V + public final fun setVersion (Lorg/pnfolder/pnlibrary/common/minecraft/MinecraftVersion;)V +} + +public final class org/pnfolder/pnlibrary/localization/TranslationSource : java/lang/Enum { + public static final field DISK Lorg/pnfolder/pnlibrary/localization/TranslationSource; + public static final field MEMORY Lorg/pnfolder/pnlibrary/localization/TranslationSource; + public static final field NETWORK Lorg/pnfolder/pnlibrary/localization/TranslationSource; + public static final field STALE_DISK Lorg/pnfolder/pnlibrary/localization/TranslationSource; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/TranslationSource; + public static fun values ()[Lorg/pnfolder/pnlibrary/localization/TranslationSource; +} + +public final class org/pnfolder/pnlibrary/localization/layout/KeyboardLayout { + public static final field BE Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field CS Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field Companion Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout$Companion; + public static final field DE Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field EN_US Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field ES Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field FR Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field GREEK Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field HE Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field IT Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field PT_BR Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field RU Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field TR_Q Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field UK Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public static final field builtIn Ljava/util/List; + public synthetic fun (Ljava/lang/String;Ljava/lang/String;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public static final fun alternatives (Ljava/lang/String;)Ljava/util/List; + public static final fun alternatives (Ljava/lang/String;Ljava/util/Collection;)Ljava/util/List; + public static final fun convert (Ljava/lang/String;Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout;Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout;)Ljava/lang/String; + public static final fun detect (Ljava/lang/String;)Ljava/util/List; + public static final fun detect (Ljava/lang/String;Ljava/util/Collection;)Ljava/util/List; + public fun equals (Ljava/lang/Object;)Z + public final fun getId ()Ljava/lang/String; + public fun hashCode ()I + public static final fun of (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; + public fun toString ()Ljava/lang/String; +} + +public final class org/pnfolder/pnlibrary/localization/layout/KeyboardLayout$Companion { + public final fun alternatives (Ljava/lang/String;)Ljava/util/List; + public final fun alternatives (Ljava/lang/String;Ljava/util/Collection;)Ljava/util/List; + public static synthetic fun alternatives$default (Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout$Companion;Ljava/lang/String;Ljava/util/Collection;ILjava/lang/Object;)Ljava/util/List; + public final fun convert (Ljava/lang/String;Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout;Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout;)Ljava/lang/String; + public final fun detect (Ljava/lang/String;)Ljava/util/List; + public final fun detect (Ljava/lang/String;Ljava/util/Collection;)Ljava/util/List; + public static synthetic fun detect$default (Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout$Companion;Ljava/lang/String;Ljava/util/Collection;ILjava/lang/Object;)Ljava/util/List; + public final fun of (Ljava/lang/String;Ljava/lang/String;)Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout; +} + +public abstract interface class org/pnfolder/pnlibrary/localization/layout/KeyboardLayouts : java/lang/AutoCloseable { + public static final field Companion Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayouts$Companion; + public static final field builtIn Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayouts; + public abstract fun all ()Ljava/util/List; + public abstract fun close ()V + public static fun create ()Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayouts; + public abstract fun register (Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayout;)Ljava/lang/AutoCloseable; +} + +public final class org/pnfolder/pnlibrary/localization/layout/KeyboardLayouts$Companion { + public final fun create ()Lorg/pnfolder/pnlibrary/localization/layout/KeyboardLayouts; +} + diff --git a/modules/features/minecraft-localization-api/build.gradle.kts b/modules/features/localization-api/build.gradle.kts similarity index 91% rename from modules/features/minecraft-localization-api/build.gradle.kts rename to modules/features/localization-api/build.gradle.kts index 5089b9add..3fbefc59e 100644 --- a/modules/features/minecraft-localization-api/build.gradle.kts +++ b/modules/features/localization-api/build.gradle.kts @@ -20,7 +20,8 @@ java { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-minecraft-localization-api", project.version.toString()) pom { name.set("pnLibrary Minecraft Localization API") diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/LocaleTranslations.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/LocaleTranslations.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/LocaleTranslations.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/LocaleTranslations.kt diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocale.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocale.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocale.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocale.kt diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocalization.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocalization.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocalization.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocalization.kt diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocalizationDsl.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocalizationDsl.kt similarity index 93% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocalizationDsl.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocalizationDsl.kt index 6d229d7f9..90a09ba06 100644 --- a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocalizationDsl.kt +++ b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocalizationDsl.kt @@ -23,6 +23,7 @@ class TranslationRequestDsl internal constructor() { /** Sets the optional fallback to a typed [locale]. */ fun fallback(locale: MinecraftLocale) { fallback = locale.code } + /** Validates the collected settings and creates the request; fails when [version] was not set. */ internal fun build(): TranslationRequest { // lateinit keeps the published field and accessors; this check replaces its generic failure message. require(::version.isInitialized) { "Minecraft version must be set" } diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslatableType.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslatableType.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslatableType.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslatableType.kt diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/Translation.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/Translation.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/Translation.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/Translation.kt diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationBundle.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationBundle.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationBundle.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationBundle.kt diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationCategory.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationCategory.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationCategory.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationCategory.kt diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationException.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationException.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationException.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationException.kt diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationMatch.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationMatch.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationMatch.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationMatch.kt diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationRequest.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationRequest.kt similarity index 94% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationRequest.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationRequest.kt index 698555d5b..aa3bcbde1 100644 --- a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationRequest.kt +++ b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationRequest.kt @@ -54,12 +54,14 @@ class TranslationRequest internal constructor( @JvmStatic fun builder(): Builder = Builder() + /** Lowercases [value], turns `-` into `_` and rejects anything that is not a Minecraft locale id. */ internal fun normalizeLocale(value: String): String { val normalized = value.trim().lowercase(Locale.ROOT).replace('-', '_') require(LOCALE.matches(normalized)) { "Invalid Minecraft locale: $value" } return normalized } + /** Shape of a normalized locale id, such as `en_us`. */ private val LOCALE = Regex("[a-z0-9]+(?:_[a-z0-9]+)*") } } diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationSource.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationSource.kt similarity index 60% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationSource.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationSource.kt index 8646c7d8f..ff43acc83 100644 --- a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationSource.kt +++ b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/TranslationSource.kt @@ -1,7 +1,16 @@ package org.pnfolder.pnlibrary.localization /** Where a parsed translation table was obtained. */ -enum class TranslationSource { MEMORY, DISK, STALE_DISK, NETWORK } +enum class TranslationSource { + /** Served from the in-memory cache. */ + MEMORY, + /** Read from the verified disk cache. */ + DISK, + /** Read from disk after a refresh failed; the data may be outdated. */ + STALE_DISK, + /** Downloaded from Mojang servers in this request. */ + NETWORK, +} /** * Immutable provenance for a loaded locale. diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/DefaultMinecraftLocalization.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/DefaultMinecraftLocalization.kt similarity index 89% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/DefaultMinecraftLocalization.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/DefaultMinecraftLocalization.kt index 78862e9e1..4679caea0 100644 --- a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/DefaultMinecraftLocalization.kt +++ b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/DefaultMinecraftLocalization.kt @@ -68,6 +68,7 @@ internal class DefaultMinecraftLocalization internal constructor( override fun load(request: TranslationRequest): CompletionStage = load(request, refresh = false) override fun refresh(request: TranslationRequest): CompletionStage = load(request, refresh = true) + /** Loads every requested locale plus the fallback in parallel; [refresh] skips the memory and disk caches. */ private fun load(request: TranslationRequest, refresh: Boolean): CompletionStage { ensureOpen() val requested = LinkedHashSet(request.locales) @@ -79,6 +80,7 @@ internal class DefaultMinecraftLocalization internal constructor( } } + /** Returns the locale from memory or a shared in-flight download, starting one when needed. */ private fun loadLocale(version: MinecraftVersion, locale: String, refresh: Boolean): CompletableFuture { requireKnown(version) val normalized = try { TranslationRequest.normalizeLocale(locale) } catch (error: IllegalArgumentException) { @@ -98,6 +100,7 @@ internal class DefaultMinecraftLocalization internal constructor( } } + /** Reads the locale from disk, else downloads it; on a failed refresh falls back to the stale disk copy. */ private fun loadLocaleNow(key: CacheKey, refresh: Boolean): LoadedLocale { val path = store.translation(key.version.text, key.locale) if (!refresh) store.read(path, MAX_LANGUAGE_BYTES)?.let { bytes -> @@ -121,12 +124,14 @@ internal class DefaultMinecraftLocalization internal constructor( } } + /** Parses [bytes] and keeps the result in the memory cache unless the service is closed. */ private fun cache(key: CacheKey, bytes: ByteArray, metadata: TranslationMetadata): LoadedLocale { val loaded = LoadedLocale(key.locale, TranslationJsonCodec.parse(bytes), metadata, layouts) synchronized(memory) { if (!closed.get()) memory[key] = loaded } return loaded } + /** Returns the version manifest, re-downloading it after [manifestTtl]; [allowStale] tolerates a failed refresh. */ @Synchronized private fun manifest(allowStale: Boolean): ByteArray? { val path = store.manifest() @@ -150,11 +155,13 @@ internal class DefaultMinecraftLocalization internal constructor( } } + /** Runs [action] on the executor and returns its future. */ private fun async(action: () -> T): CompletableFuture { ensureOpen() return submit(CompletableFuture(), action = action) } + /** Executes [action] on the executor and completes [promise]; [beforeCompletion] always runs first. */ private fun submit( promise: CompletableFuture, beforeCompletion: () -> Unit = {}, @@ -191,10 +198,12 @@ internal class DefaultMinecraftLocalization internal constructor( return promise } + /** Throws a CLOSED [TranslationException] after [close]. */ private fun ensureOpen() { if (closed.get()) throw closedError() } + /** Rejects the UNKNOWN version, which has no assets. */ private fun requireKnown(version: MinecraftVersion) { if (!version.known) throw TranslationException( TranslationException.Reason.UNSUPPORTED_VERSION, "UNKNOWN Minecraft version is not supported", @@ -212,9 +221,13 @@ internal class DefaultMinecraftLocalization internal constructor( if (ownsExecutor) executor.shutdownNow() } + /** Error given to callers after the service is closed. */ private fun closedError() = TranslationException(TranslationException.Reason.CLOSED, "Minecraft localization service is closed") + /** Error given when a download is needed but no manifest was ever cached. */ private fun offline() = TranslationException(TranslationException.Reason.OFFLINE, "No cached Minecraft manifest is available") + /** Already failed future carrying [error]. */ private fun failed(error: Throwable): CompletableFuture = CompletableFuture().also { it.completeExceptionally(error) } + /** Memory and in-flight cache key: one language file of one version. */ private data class CacheKey(val version: MinecraftVersion, val locale: String) private companion object { @@ -237,14 +250,17 @@ internal class LoadedLocale private constructor( override fun translate(key: String): Optional = Optional.ofNullable(data.values[key]) override fun translations(): Map = data.values override fun keys(): TranslationIndex = data.keys + /** Copy that reports a different origin, for example MEMORY when served from the cache. */ fun withSource(source: TranslationSource) = LoadedLocale(locale, data, metadata.copy(source = source), layouts) + /** Shared immutable values with a lazily built key index, so copies by [withSource] reuse it. */ private class LocaleData(values: Map, layouts: KeyboardLayouts) { val values = Collections.unmodifiableMap(LinkedHashMap(values)) val keys by lazy { TranslationSearchIndex.keys(this.values, layouts) } } } +/** Bundle of the locales loaded for one request; the optional fallback fills keys missing from a locale. */ private class DefaultTranslationBundle( override val version: MinecraftVersion, requested: Set, @@ -260,6 +276,7 @@ private class DefaultTranslationBundle( } } +/** Locale view that asks [fallback] for keys the [primary] locale lacks. */ private class FallbackLocale( private val primary: LoadedLocale, private val fallback: LoadedLocale, diff --git a/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/LocalizationHttpClient.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/LocalizationHttpClient.kt new file mode 100644 index 000000000..510cec55e --- /dev/null +++ b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/LocalizationHttpClient.kt @@ -0,0 +1,89 @@ +package org.pnfolder.pnlibrary.localization.internal + +import org.pnfolder.pnlibrary.localization.TranslationException +import java.io.ByteArrayOutputStream +import java.io.InputStream +import java.io.OutputStream +import java.net.HttpURLConnection +import java.net.URI +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardOpenOption +import java.time.Duration + +/** + * HTTPS-only client for the fixed set of Mojang hosts, with bounded timeouts and no redirects. + * Open so tests can replace the transport. + */ +internal open class LocalizationHttpClient( + private val connectTimeout: Duration, + private val readTimeout: Duration, +) { + /** Downloads [uri] into memory; fails with INTEGRITY when it exceeds [maximumBytes]. */ + open fun get(uri: URI, maximumBytes: Int): ByteArray = request(uri, maximumBytes) { input -> + val output = ByteArrayOutputStream(minOf(maximumBytes, 8192)) + copyBounded(input, output, maximumBytes) + output.toByteArray() + } + + /** Downloads [uri] into the file [destination] and returns the byte count; fails when it exceeds [maximumBytes]. */ + open fun download(uri: URI, maximumBytes: Int, destination: Path): Long = request(uri, maximumBytes) { input -> + Files.newOutputStream(destination, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING).use { output -> + copyBounded(input, output, maximumBytes) + } + } + + /** Opens [uri], checks the status and declared size, runs [read] on the body and always disconnects. */ + private fun request(uri: URI, maximumBytes: Int, read: (InputStream) -> T): T { + val connection = connection(uri) + try { + val status = connection.responseCode + if (status !in 200..299) throw TranslationException( + TranslationException.Reason.REMOTE, "Minecraft resource request failed with HTTP $status", + ) + if (connection.contentLengthLong > maximumBytes) throw tooLarge(maximumBytes) + return connection.inputStream.use(read) + } catch (error: TranslationException) { + throw error + } catch (error: Exception) { + throw TranslationException(TranslationException.Reason.OFFLINE, "Unable to download Minecraft resource", error) + } finally { + connection.disconnect() + } + } + + /** Copies [input] to [output] and returns the byte count; stops with INTEGRITY past [maximumBytes] whatever the headers said. */ + private fun copyBounded(input: InputStream, output: OutputStream, maximumBytes: Int): Long { + val buffer = ByteArray(8192) + var total = 0L + while (true) { + val read = input.read(buffer) + if (read < 0) return total + total += read + if (total > maximumBytes) throw tooLarge(maximumBytes) + output.write(buffer, 0, read) + } + } + + private fun tooLarge(maximumBytes: Int) = + TranslationException(TranslationException.Reason.INTEGRITY, "Minecraft resource exceeds $maximumBytes bytes") + + /** Opens a connection after checking that the host is on the Mojang allow list. */ + private fun connection(uri: URI): HttpURLConnection { + require(uri.scheme == "https" && uri.host in ALLOWED_HOSTS) { "Unsupported localization host: $uri" } + return (uri.toURL().openConnection() as HttpURLConnection).apply { + instanceFollowRedirects = false + connectTimeout = this@LocalizationHttpClient.connectTimeout.toMillis().coerceAtMost(Int.MAX_VALUE.toLong()).toInt() + readTimeout = this@LocalizationHttpClient.readTimeout.toMillis().coerceAtMost(Int.MAX_VALUE.toLong()).toInt() + setRequestProperty("Accept", "application/json, application/octet-stream") + } + } + + companion object { + /** The only hosts that serve Minecraft metadata and assets. */ + private val ALLOWED_HOSTS = setOf( + "piston-meta.mojang.com", "launchermeta.mojang.com", + "resources.download.minecraft.net", "piston-data.mojang.com", + ) + } +} diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/MojangAssetResolver.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/MojangAssetResolver.kt similarity index 76% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/MojangAssetResolver.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/MojangAssetResolver.kt index ea1090b76..54ec71864 100644 --- a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/MojangAssetResolver.kt +++ b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/MojangAssetResolver.kt @@ -34,13 +34,17 @@ internal class MojangAssetResolver( private val http: LocalizationHttpClient, private val store: VerifiedFileStore, ) { + /** Per-version asset metadata cache. */ private val versionAssets = ConcurrentHashMap() + /** Downloads and validates the current Mojang version manifest. */ fun manifestBytes(): ByteArray = http.get(MANIFEST, MANIFEST_LIMIT).also(::validateManifest) + /** Throws [TranslationException] when [bytes] is not a usable version manifest. */ fun validateManifest(bytes: ByteArray) { manifestEntries(bytes) } + /** Lists release versions of the manifest that this library knows, newest first. */ fun versions(manifest: ByteArray): List { return manifestEntries(manifest) .mapNotNull { entry -> @@ -51,12 +55,14 @@ internal class MojangAssetResolver( .sortedWith(compareByDescending { it.major }.thenByDescending { it.minor }.thenByDescending { it.patch }) } + /** Lists locale ids published for [version]; `en_us` is always included because it ships in the client. */ fun locales(version: MinecraftVersion, manifest: ByteArray): List = (versionAssets(version, manifest).objects.keys.asSequence() .filter { it.startsWith("minecraft/lang/") && (it.endsWith(".json") || it.endsWith(".lang")) } .map { it.substringAfterLast('/').substringBeforeLast('.') } + sequenceOf("en_us")) .distinct().sorted().toList() + /** Downloads the language file of [locale], verifying size and SHA-1; falls back to the client jar when not in the index. */ fun language(version: MinecraftVersion, locale: String, manifest: ByteArray): ResolvedLanguage { val assets = versionAssets(version, manifest) val reference = assets.objects["minecraft/lang/$locale.json"] @@ -70,9 +76,11 @@ internal class MojangAssetResolver( return ResolvedLanguage(bytes, reference.hash) } + /** Version assets, resolved once per version and kept in memory. */ private fun versionAssets(version: MinecraftVersion, manifest: ByteArray): VersionAssets = versionAssets.computeIfAbsent(version) { resolveVersionAssets(it, manifest) } + /** Loads version metadata and the asset index, from the disk cache or the network. */ private fun resolveVersionAssets(version: MinecraftVersion, manifest: ByteArray): VersionAssets { val versionEntry = manifestEntries(manifest) .firstOrNull { it.string("id") == version.text } @@ -102,6 +110,7 @@ internal class MojangAssetResolver( return VersionAssets(versionJson, objects) } + /** Returns verified JSON from the disk cache, or downloads and caches it; a corrupt cache file is quarantined. */ private fun cachedJson( path: Path, uri: URI, @@ -111,22 +120,7 @@ internal class MojangAssetResolver( expectedSize: Long? = null, validator: (JsonObject) -> Unit, ): JsonObject { - fun decode(bytes: ByteArray): JsonObject { - if ((expectedSize != null && bytes.size.toLong() != expectedSize) || - (expectedHash != null && store.sha1(bytes) != expectedHash) - ) throw TranslationException( - TranslationException.Reason.INTEGRITY, "Checksum or size mismatch for Minecraft $name", - ) - val parsed = parse(bytes, name) - try { - validator(parsed) - } catch (error: TranslationException) { - throw error - } catch (error: RuntimeException) { - throw TranslationException(TranslationException.Reason.MALFORMED_DATA, "Malformed Minecraft $name", error) - } - return parsed - } + fun decode(bytes: ByteArray) = decodeJson(bytes, name, expectedHash, expectedSize, validator) store.read(path, limit)?.let { bytes -> try { return decode(bytes) @@ -140,11 +134,37 @@ internal class MojangAssetResolver( return parsed } + /** Checks size and SHA-1 when known, parses [bytes] and runs [validator]; failures become [TranslationException]. */ + private fun decodeJson( + bytes: ByteArray, + name: String, + expectedHash: String?, + expectedSize: Long?, + validator: (JsonObject) -> Unit, + ): JsonObject { + if ((expectedSize != null && bytes.size.toLong() != expectedSize) || + (expectedHash != null && store.sha1(bytes) != expectedHash) + ) throw TranslationException( + TranslationException.Reason.INTEGRITY, "Checksum or size mismatch for Minecraft $name", + ) + val parsed = parse(bytes, name) + try { + validator(parsed) + } catch (error: TranslationException) { + throw error + } catch (error: RuntimeException) { + throw TranslationException(TranslationException.Reason.MALFORMED_DATA, "Malformed Minecraft $name", error) + } + return parsed + } + + /** Requires an asset index with a URL. */ private fun validateVersionMetadata(metadata: JsonObject) { val index = metadata.getAsJsonObject("assetIndex") ?: throw malformed("Version metadata has no asset index") if (index.string("url").isNullOrBlank()) throw malformed("Version metadata has no asset index URL") } + /** Requires every asset to have a hash and a non-negative size. */ private fun validateAssetIndex(index: JsonObject) { val objects = index.getAsJsonObject("objects") ?: throw malformed("Asset index has no objects") objects.entrySet().forEach { (key, raw) -> @@ -157,6 +177,7 @@ internal class MojangAssetResolver( } } + /** Fallback for locales absent from the asset index: downloads the client jar and extracts the language file. */ private fun languageFromClient(version: MinecraftVersion, locale: String, metadata: JsonObject): ResolvedLanguage { val client = metadata.getAsJsonObject("downloads")?.getAsJsonObject("client") ?: throw unavailable(version, locale) @@ -173,16 +194,7 @@ internal class MojangAssetResolver( if (downloaded != size.toLong() || store.sha1(temporary) != hash) throw TranslationException( TranslationException.Reason.INTEGRITY, "Checksum or size mismatch for Minecraft $version client artifact", ) - val names = listOf("assets/minecraft/lang/$locale.json", "assets/minecraft/lang/$locale.lang") - ZipFile(temporary.toFile()).use { zip -> - val entry = names.asSequence().mapNotNull(zip::getEntry).firstOrNull() - ?: throw unavailable(version, locale) - if (entry.isDirectory || entry.size > LANGUAGE_LIMIT) throw TranslationException( - TranslationException.Reason.INTEGRITY, "Minecraft language entry exceeds $LANGUAGE_LIMIT bytes", - ) - val bytes = readEntry(zip, entry) - return ResolvedLanguage(bytes, store.sha1(bytes)) - } + return extractLanguage(temporary, version, locale) } catch (error: TranslationException) { throw error } catch (error: Exception) { @@ -200,6 +212,20 @@ internal class MojangAssetResolver( } } + /** Reads the language file of [locale] from the downloaded client archive. */ + private fun extractLanguage(archive: Path, version: MinecraftVersion, locale: String): ResolvedLanguage { + val names = listOf("assets/minecraft/lang/$locale.json", "assets/minecraft/lang/$locale.lang") + ZipFile(archive.toFile()).use { zip -> + val entry = names.asSequence().mapNotNull(zip::getEntry).firstOrNull() + ?: throw unavailable(version, locale) + if (entry.isDirectory || entry.size > LANGUAGE_LIMIT) throw TranslationException( + TranslationException.Reason.INTEGRITY, "Minecraft language entry exceeds $LANGUAGE_LIMIT bytes", + ) + val bytes = readEntry(zip, entry) + return ResolvedLanguage(bytes, store.sha1(bytes)) + } + } + /** Reads a language file, stopping as soon as it grows past [LANGUAGE_LIMIT] whatever the archive claims. */ private fun readEntry(zip: ZipFile, entry: ZipEntry): ByteArray = zip.getInputStream(entry).use { input -> val output = ByteArrayOutputStream(minOf(entry.size.coerceAtLeast(0L).toInt(), 8192)) @@ -215,17 +241,20 @@ internal class MojangAssetResolver( output.toByteArray() } + /** Error for a version that does not publish [locale]. */ private fun unavailable(version: MinecraftVersion, locale: String) = TranslationException( TranslationException.Reason.UNAVAILABLE_LOCALE, "Minecraft ${version.text} does not publish locale $locale", ) + /** Parses a JSON object, mapping any failure to MALFORMED_DATA. */ private fun parse(bytes: ByteArray, name: String): JsonObject = try { JsonParser.parseString(String(bytes, StandardCharsets.UTF_8)).asJsonObject } catch (error: Exception) { throw TranslationException(TranslationException.Reason.MALFORMED_DATA, "Malformed Minecraft $name", error) } + /** Parses and validates the `versions` array of the manifest. */ private fun manifestEntries(bytes: ByteArray): List = try { val entries = parse(bytes, "version manifest").getAsJsonArray("versions") ?: throw malformed("Version manifest has no versions") @@ -242,10 +271,13 @@ internal class MojangAssetResolver( throw TranslationException(TranslationException.Reason.MALFORMED_DATA, "Malformed Minecraft version manifest", error) } + /** MALFORMED_DATA error with [message]. */ private fun malformed(message: String) = TranslationException(TranslationException.Reason.MALFORMED_DATA, message) + /** String value of [name], or null when missing or JSON null. */ private fun JsonObject.string(name: String): String? = get(name)?.takeUnless { it.isJsonNull }?.asString companion object { + /** Official Mojang version manifest. */ val MANIFEST: URI = URI.create("https://piston-meta.mojang.com/mc/game/version_manifest_v2.json") private const val MANIFEST_LIMIT = 4 * 1024 * 1024 private const val VERSION_LIMIT = 4 * 1024 * 1024 diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationJsonCodec.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationJsonCodec.kt similarity index 93% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationJsonCodec.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationJsonCodec.kt index 6a7bac573..50c6957c1 100644 --- a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationJsonCodec.kt +++ b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationJsonCodec.kt @@ -8,6 +8,7 @@ import java.nio.charset.StandardCharsets * Reads a language file into a flat key-to-text map; accepts JSON objects and `key=value` lines. */ internal object TranslationJsonCodec { + /** Parses [bytes]; throws MALFORMED_DATA when the content is invalid or empty. */ fun parse(bytes: ByteArray): Map = try { val text = String(bytes, StandardCharsets.UTF_8) val values = if (text.trimStart().startsWith("{")) { diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationSearchIndex.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationSearchIndex.kt similarity index 51% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationSearchIndex.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationSearchIndex.kt index fd8d2ec24..243c6df42 100644 --- a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationSearchIndex.kt +++ b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationSearchIndex.kt @@ -17,10 +17,19 @@ import kotlin.math.abs internal class TranslationSearchIndex( matches: List>, override val layouts: KeyboardLayouts = KeyboardLayouts.builtIn, + private val distance: (String, String) -> Int = ::editDistance, ) : TranslationIndex { + /** All indexed translations with their normalized text. */ private val entries = matches.map { Indexed(it, normalize(it.translation)) } + /** Normalized text to its matches, for [findExact]. */ private val exact = entries.groupBy({ it.normalized }, { it.match }) .mapValues { (_, matches) -> Collections.unmodifiableList(matches) } + /** Small LRU of ranked results per query, floor and layouts, so a repeated suggestion does no scoring; guarded by its own monitor. */ + private val rankedCache = object : LinkedHashMap>>(64, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry>>?): Boolean = + size > SEARCH_CACHE_CAPACITY + } + /** Small LRU of substring-search results; guarded by its own monitor. */ private val searchCache = object : LinkedHashMap>>(64, 0.75f, true) { override fun removeEldestEntry(eldest: MutableMap.MutableEntry>>?): Boolean = size > SEARCH_CACHE_CAPACITY @@ -80,47 +89,113 @@ internal class TranslationSearchIndex( * first, then those the query matched as typed, then by key. */ private fun ranked(query: String, floor: Double, layouts: Collection): List> { - val queries = (listOf(query) + KeyboardLayout.alternatives(query, layouts).map { normalize(it) }).distinct() + val key = RankedKey(query, floor, layouts.toList()) + synchronized(rankedCache) { rankedCache[key]?.let { return it } } + val result = computeRanked(query, floor, layouts) + if (result.size <= MAX_CACHED_RANKED) synchronized(rankedCache) { rankedCache[key] = result } + return result + } + + private fun computeRanked(query: String, floor: Double, layouts: Collection): List> { + val probes = (listOf(query) + KeyboardLayout.alternatives(query, layouts).map { normalize(it) }).distinct().map(::Probe) return entries.mapNotNull { entry -> - val scores = queries.map { variant -> entry.candidates.maxOf { similarity(variant, it, floor) } } - val score = scores.max() - if (score >= floor) Ranked(entry.match, score, typedAsIs = scores[0] >= score) else null + var typedAsIs = 0.0 + var best = 0.0 + probes.forEachIndexed { index, probe -> + val score = entry.candidates.maxOf { similarity(probe, it, floor) } + if (index == 0) typedAsIs = score + best = maxOf(best, score) + } + if (best >= floor) Ranked(entry.match, best, typedAsIs = typedAsIs >= best) else null }.sortedWith(compareByDescending> { it.score }.thenByDescending { it.typedAsIs }.thenBy { it.match.key }) } + /** + * The better of the edit and letter-triple scores, both between 0.0 and 1.0. A pair that cannot reach [floor] may get any + * value below it; the edit distance is only computed when the triple overlap leaves it a chance to win. + */ + private fun similarity(probe: Probe, candidate: Candidate, floor: Double): Double { + val a = probe.text + val b = candidate.text + val longest = maxOf(a.length, b.length) + val lengthGap = abs(a.length - b.length) + val lengthBound = 1.0 - lengthGap.toDouble() / longest + if (a.length < 3 || b.length < 3) return if (lengthBound < floor) 0.0 else editScore(a, b, longest) + val left = probe.trigrams + val right = candidate.trigrams + val common = left.count { it in right } + val triple = 2.0 * common / (left.size + right.size) + if (lengthBound < floor) return triple + // One edit spoils at most four letter triples and changes at most two letter counts, so what differs bounds the distance from below. + val unmatched = maxOf(left.size, right.size) - common + val lowest = maxOf(lengthGap, (unmatched + 3) / 4, (letterDifference(probe.letters, candidate.letters) + 1) / 2) + val bound = 1.0 - lowest.toDouble() / longest + if (bound <= triple || bound < floor && triple < floor) return triple + return maxOf(editScore(a, b, longest), triple) + } + + /** Sum of the differences between how often each letter occurs in two sorted letter arrays. */ + private fun letterDifference(x: CharArray, y: CharArray): Int { + var i = 0 + var j = 0 + var difference = 0 + while (i < x.size && j < y.size) { + when { + x[i] == y[j] -> { i++; j++ } + x[i] < y[j] -> { i++; difference++ } + else -> { j++; difference++ } + } + } + return difference + (x.size - i) + (y.size - j) + } + + private fun editScore(a: String, b: String, longest: Int) = 1.0 - distance(a, b).toDouble() / longest + + /** A match with its similarity [score]; [typedAsIs] is true when the query matched without layout conversion. */ private class Ranked(val match: TranslationMatch, val score: Double, val typedAsIs: Boolean) + /** A match with its normalized text; [candidates] are the whole text and each word, compared separately. */ private class Indexed(val match: TranslationMatch, val normalized: String) { - val candidates: List = (listOf(normalized) + normalized.split(' ')).distinct() + val candidates: List = (listOf(normalized) + normalized.split(' ')).distinct().map(::Candidate) + } + + /** Text to compare against, with its letter triples computed on first use and then kept. */ + private class Candidate(val text: String) { + val trigrams: Set by lazy(LazyThreadSafetyMode.PUBLICATION) { trigramsOf(text) } + val letters: CharArray by lazy(LazyThreadSafetyMode.PUBLICATION) { text.toCharArray().also { it.sort() } } } + /** A query variant with its letter triples, computed once per search. */ + private class Probe(val text: String) { + val trigrams: Set = trigramsOf(text) + val letters: CharArray = text.toCharArray().also { it.sort() } + } + + private data class RankedKey(val query: String, val floor: Double, val layouts: List) + companion object { + /** Folds case, width and whitespace and treats `ё` as `е`, so lookups ignore those differences. */ fun normalize(value: String): String = Normalizer.normalize(value, Normalizer.Form.NFKC) .trim().lowercase(Locale.ROOT).replace('ё', 'е').replace(WHITESPACE, " ") + /** Builds an index whose results are keyed by the translation key itself. */ fun keys(values: Map, layouts: KeyboardLayouts) = TranslationSearchIndex( values.map { (key, value) -> TranslationMatch(key, value, key) }, layouts, ) + /** Runs of whitespace collapsed by [normalize]. */ private val WHITESPACE = Regex("\\s+") private const val SEARCH_CACHE_CAPACITY = 64 private const val SUGGEST_FLOOR = 0.5 + private const val MAX_CACHED_RANKED = 2000 } } -/** The better of the edit and letter-triple scores, both between 0.0 and 1.0. */ -private fun similarity(a: String, b: String, floor: Double): Double { - val longest = maxOf(a.length, b.length) - val edit = if (1.0 - abs(a.length - b.length).toDouble() / longest < floor) 0.0 else 1.0 - distance(a, b).toDouble() / longest - if (a.length < 3 || b.length < 3) return edit - val left = a.windowed(3).toSet() - val right = b.windowed(3).toSet() - return maxOf(edit, 2.0 * left.count { it in right } / (left.size + right.size)) -} +private fun trigramsOf(text: String): Set = if (text.length < 3) emptySet() else text.windowed(3).toSet() /** Optimal string alignment distance: insertion, deletion, substitution and swapping two neighbours each cost 1. */ -private fun distance(a: String, b: String): Int { +internal fun editDistance(a: String, b: String): Int { var older = IntArray(b.length + 1) var previous = IntArray(b.length + 1) { it } var current = IntArray(b.length + 1) diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/VerifiedFileStore.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/VerifiedFileStore.kt similarity index 78% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/VerifiedFileStore.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/VerifiedFileStore.kt index 5dcfa5181..db2db2ff0 100644 --- a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/VerifiedFileStore.kt +++ b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/VerifiedFileStore.kt @@ -11,16 +11,22 @@ import java.security.MessageDigest * and quarantine for files that fail verification. */ internal class VerifiedFileStore(private val root: Path) { + /** Cache file of one language of one version. */ fun translation(version: String, locale: String): Path = root.resolve("translations").resolve(version).resolve("$locale.json") + /** Cache file of the Mojang version manifest. */ fun manifest(): Path = root.resolve("version-manifest.json") + /** Cache file of the metadata of [version]. */ fun versionMetadata(version: String): Path = root.resolve("versions").resolve("$version.json") + /** Cache file of the asset index of [version]. */ fun assetIndex(version: String): Path = root.resolve("asset-indexes").resolve("$version.json") + /** Creates an empty temporary file in the cache for a large download. */ fun temporary(suffix: String): Path { val directory = root.resolve("temporary") Files.createDirectories(directory) return Files.createTempFile(directory, "download-", suffix) } + /** Returns the file bytes, or null when it is missing or larger than [maximumBytes]. */ fun read(path: Path, maximumBytes: Int = DEFAULT_READ_LIMIT): ByteArray? { if (!Files.isRegularFile(path)) return null if (maximumBytes < 0) throw IllegalArgumentException("Maximum bytes must not be negative") @@ -28,6 +34,7 @@ internal class VerifiedFileStore(private val root: Path) { return Files.readAllBytes(path) } + /** Writes [bytes] through a temporary file and an atomic move, so readers never see a partial file. */ fun write(path: Path, bytes: ByteArray) { Files.createDirectories(path.parent) val temporary = Files.createTempFile(path.parent, path.fileName.toString(), ".tmp") @@ -39,14 +46,17 @@ internal class VerifiedFileStore(private val root: Path) { } } + /** Renames a file that failed verification so it is neither reused nor lost. */ fun quarantine(path: Path) { if (!Files.exists(path)) return Files.move(path, path.resolveSibling("${path.fileName}.corrupt-${System.currentTimeMillis()}"), StandardCopyOption.REPLACE_EXISTING) } + /** Lowercase hex SHA-1 of [bytes]. */ fun sha1(bytes: ByteArray): String = MessageDigest.getInstance("SHA-1") .digest(bytes).joinToString("") { "%02x".format(it) } + /** Lowercase hex SHA-1 of the file, streamed so large archives are not loaded into memory. */ fun sha1(path: Path): String { val digest = MessageDigest.getInstance("SHA-1") Files.newInputStream(path).use { input -> diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayout.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayout.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayout.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayout.kt diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayouts.kt b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayouts.kt similarity index 96% rename from modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayouts.kt rename to modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayouts.kt index 5a3a2af7d..675bc2275 100644 --- a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayouts.kt +++ b/modules/features/localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayouts.kt @@ -48,6 +48,7 @@ interface KeyboardLayouts : AutoCloseable { } } +/** Mutable registry guarded by [lock]; readers use the volatile snapshot of [layouts] without locking. */ private class KeyboardLayoutRegistry : KeyboardLayouts { private val lock = Any() diff --git a/modules/features/minecraft-localization-api/src/test/java/org/pnfolder/pnlibrary/localization/LocalizationApiJavaTest.java b/modules/features/localization-api/src/test/java/org/pnfolder/pnlibrary/localization/LocalizationApiJavaTest.java similarity index 100% rename from modules/features/minecraft-localization-api/src/test/java/org/pnfolder/pnlibrary/localization/LocalizationApiJavaTest.java rename to modules/features/localization-api/src/test/java/org/pnfolder/pnlibrary/localization/LocalizationApiJavaTest.java diff --git a/modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/LocalizationApiTest.kt b/modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/LocalizationApiTest.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/LocalizationApiTest.kt rename to modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/LocalizationApiTest.kt diff --git a/modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocaleTest.kt b/modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocaleTest.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocaleTest.kt rename to modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/MinecraftLocaleTest.kt diff --git a/modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/TranslatableTypeTest.kt b/modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/TranslatableTypeTest.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/TranslatableTypeTest.kt rename to modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/TranslatableTypeTest.kt diff --git a/modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/TranslationIndexFuzzyTest.kt b/modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/TranslationIndexFuzzyTest.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/TranslationIndexFuzzyTest.kt rename to modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/TranslationIndexFuzzyTest.kt diff --git a/modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/internal/LocalizationServiceTest.kt b/modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/internal/LocalizationServiceTest.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/internal/LocalizationServiceTest.kt rename to modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/internal/LocalizationServiceTest.kt diff --git a/modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationSearchIndexRankingTest.kt b/modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationSearchIndexRankingTest.kt new file mode 100644 index 000000000..27aaa8090 --- /dev/null +++ b/modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/internal/TranslationSearchIndexRankingTest.kt @@ -0,0 +1,142 @@ +package org.pnfolder.pnlibrary.localization.internal + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.localization.TranslationMatch +import org.pnfolder.pnlibrary.localization.layout.KeyboardLayout +import org.pnfolder.pnlibrary.localization.layout.KeyboardLayouts +import java.lang.management.ManagementFactory +import java.util.Random +import java.util.concurrent.atomic.AtomicInteger +import kotlin.math.abs + +class TranslationSearchIndexRankingTest { + private val words = listOf( + "алмазный", "меч", "железный", "кирка", "деревянный", "топор", "золотой", "шлем", "блок", "камня", "руда", "дверь", + "стекло", "панель", "ступени", "плита", "заготовка", "зелье", "свиток", "шерсть", "diamond", "sword", "iron", "pickaxe", + ) + private val matches: List> = Random(3).let { random -> + (0 until 1500).map { index -> + val text = (1..(1 + random.nextInt(3))).joinToString(" ") { words[random.nextInt(words.size)] } + TranslationMatch("item.k$index", text, "item.k$index") + } + } + private val layouts = KeyboardLayouts.builtIn.all() + + /** Queries typed exactly, with a typo, cut short, and in the wrong layout. */ + private fun queries(): List { + val random = Random(11) + return (0 until 100).map { n -> + val source = matches[random.nextInt(matches.size)].translation + when (n % 4) { + 0 -> source + 1 -> source.replaceRange(1, 2, "ы") + 2 -> source.take(3 + random.nextInt(5)) + else -> KeyboardLayout.alternatives(source, layouts).firstOrNull() ?: source + } + } + } + + @Test + fun `suggest, fuzzy and best match the previous algorithm on 100 queries`() { + val index = TranslationSearchIndex(matches, KeyboardLayouts.builtIn) + val reference = ReferenceRanking(matches) + queries().forEach { text -> + val query = TranslationSearchIndex.normalize(text) + listOf(emptyList(), layouts).forEach { chosen -> + assertEquals(reference.suggest(index, query, 10, chosen).map { it.key }, index.suggest(text, 10, chosen).map { it.key }, text) + assertEquals(reference.best(query, 0.7, chosen)?.key, index.best(text, 0.7, chosen)?.key, text) + } + assertEquals(reference.ranked(query, 0.6, emptyList()).take(5).map { it.key }, index.fuzzy(text, 0.6, 5).map { it.key }, text) + } + } + + private fun allocated(): Long = + (ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean).getThreadAllocatedBytes(Thread.currentThread().id) + + @Test + fun `scoring computes far fewer distances and allocates less than the previous algorithm`() { + val counted = AtomicInteger() + val index = TranslationSearchIndex(matches, KeyboardLayouts.builtIn) { a, b -> counted.incrementAndGet(); editDistance(a, b) } + val reference = ReferenceRanking(matches) + val queries = queries().map { TranslationSearchIndex.normalize(it) }.distinct() + queries.forEach { index.suggest(it, 10, layouts) } // warm up classes, not the per-query results + val fresh = TranslationSearchIndex(matches, KeyboardLayouts.builtIn) { a, b -> counted.incrementAndGet(); editDistance(a, b) } + counted.set(0) + + val newStart = allocated() + queries.forEach { fresh.suggest(it, 10, layouts) } + val newBytes = allocated() - newStart + val oldStart = allocated() + queries.forEach { reference.suggest(fresh, it, 10, layouts) } + val oldBytes = allocated() - oldStart + + assertTrue(counted.get() * 5 <= reference.distances, "distances new=${counted.get()} old=${reference.distances}") + assertTrue(newBytes * 2 <= oldBytes, "allocated new=$newBytes old=$oldBytes") + } + + @Test + fun `a repeated suggestion is answered from the cache without scoring`() { + val counted = AtomicInteger() + val index = TranslationSearchIndex(matches, KeyboardLayouts.builtIn) { a, b -> counted.incrementAndGet(); editDistance(a, b) } + val first = index.suggest("алмазн", 10, layouts) + val after = counted.get() + assertEquals(first, index.suggest("алмазн", 10, layouts)) + assertEquals(after, counted.get()) + } + + /** Previous algorithm kept verbatim to compare against. */ + internal class ReferenceRanking(matches: List>) { + private val entries = matches.map { it to TranslationSearchIndex.normalize(it.translation) } + + fun suggest(index: TranslationSearchIndex, query: String, limit: Int, layouts: Collection) = + (index.search(query) + ranked(query, 0.5, layouts)).distinctBy { it.key }.take(limit) + + fun best(text: String, floor: Double, layouts: Collection) = + TranslationSearchIndex.normalize(text).let { ranked(it, floor, layouts).firstOrNull() } + + fun ranked(query: String, floor: Double, layouts: Collection): List> { + val queries = (listOf(query) + KeyboardLayout.alternatives(query, layouts).map { TranslationSearchIndex.normalize(it) }).distinct() + return entries.mapNotNull { (match, normalized) -> + val candidates = (listOf(normalized) + normalized.split(' ')).distinct() + val scores = queries.map { variant -> candidates.maxOf { similarity(variant, it, floor) } } + val score = scores.max() + if (score >= floor) Triple(match, score, scores[0] >= score) else null + }.sortedWith(compareByDescending, Double, Boolean>> { it.second } + .thenByDescending { it.third }.thenBy { it.first.key }).map { it.first } + } + + private fun similarity(a: String, b: String, floor: Double): Double { + val longest = maxOf(a.length, b.length) + val edit = if (1.0 - abs(a.length - b.length).toDouble() / longest < floor) 0.0 else 1.0 - distance(a, b).toDouble() / longest + if (a.length < 3 || b.length < 3) return edit + val left = a.windowed(3).toSet() + val right = b.windowed(3).toSet() + return maxOf(edit, 2.0 * left.count { it in right } / (left.size + right.size)) + } + + var distances = 0 + + private fun distance(a: String, b: String): Int { + distances++ + var older = IntArray(b.length + 1) + var previous = IntArray(b.length + 1) { it } + var current = IntArray(b.length + 1) + for (i in 1..a.length) { + current[0] = i + for (j in 1..b.length) { + val cost = if (a[i - 1] == b[j - 1]) 0 else 1 + var best = minOf(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost) + if (i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1]) best = minOf(best, older[j - 2] + 1) + current[j] = best + } + val recycled = older + older = previous + previous = current + current = recycled + } + return previous[b.length] + } + } +} diff --git a/modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayoutTest.kt b/modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayoutTest.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayoutTest.kt rename to modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayoutTest.kt diff --git a/modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayoutsTest.kt b/modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayoutsTest.kt similarity index 100% rename from modules/features/minecraft-localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayoutsTest.kt rename to modules/features/localization-api/src/test/kotlin/org/pnfolder/pnlibrary/localization/layout/KeyboardLayoutsTest.kt diff --git a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/LocalizationHttpClient.kt b/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/LocalizationHttpClient.kt deleted file mode 100644 index 1d2768bf7..000000000 --- a/modules/features/minecraft-localization-api/src/main/kotlin/org/pnfolder/pnlibrary/localization/internal/LocalizationHttpClient.kt +++ /dev/null @@ -1,107 +0,0 @@ -package org.pnfolder.pnlibrary.localization.internal - -import org.pnfolder.pnlibrary.localization.TranslationException -import java.io.ByteArrayOutputStream -import java.net.HttpURLConnection -import java.net.URI -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.StandardOpenOption -import java.time.Duration - -/** - * HTTPS-only client for the fixed set of Mojang hosts, with bounded timeouts and no redirects. - * Open so tests can replace the transport. - */ -internal open class LocalizationHttpClient( - private val connectTimeout: Duration, - private val readTimeout: Duration, -) { - open fun get(uri: URI, maximumBytes: Int): ByteArray { - val connection = connection(uri) - try { - val status = connection.responseCode - if (status !in 200..299) throw TranslationException( - TranslationException.Reason.REMOTE, "Minecraft resource request failed with HTTP $status", - ) - val declared = connection.contentLengthLong - if (declared > maximumBytes) throw TranslationException( - TranslationException.Reason.INTEGRITY, "Minecraft resource exceeds $maximumBytes bytes", - ) - connection.inputStream.use { input -> - val output = ByteArrayOutputStream(minOf(maximumBytes, 8192)) - val buffer = ByteArray(8192) - var total = 0 - while (true) { - val read = input.read(buffer) - if (read < 0) break - total += read - if (total > maximumBytes) throw TranslationException( - TranslationException.Reason.INTEGRITY, "Minecraft resource exceeds $maximumBytes bytes", - ) - output.write(buffer, 0, read) - } - return output.toByteArray() - } - } catch (error: TranslationException) { - throw error - } catch (error: Exception) { - throw TranslationException(TranslationException.Reason.OFFLINE, "Unable to download Minecraft resource", error) - } finally { - connection.disconnect() - } - } - - open fun download(uri: URI, maximumBytes: Int, destination: Path): Long { - val connection = connection(uri) - try { - val status = connection.responseCode - if (status !in 200..299) throw TranslationException( - TranslationException.Reason.REMOTE, "Minecraft resource request failed with HTTP $status", - ) - val declared = connection.contentLengthLong - if (declared > maximumBytes) throw TranslationException( - TranslationException.Reason.INTEGRITY, "Minecraft resource exceeds $maximumBytes bytes", - ) - connection.inputStream.use { input -> - Files.newOutputStream(destination, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING).use { output -> - val buffer = ByteArray(8192) - var total = 0L - while (true) { - val read = input.read(buffer) - if (read < 0) break - total += read - if (total > maximumBytes) throw TranslationException( - TranslationException.Reason.INTEGRITY, "Minecraft resource exceeds $maximumBytes bytes", - ) - output.write(buffer, 0, read) - } - return total - } - } - } catch (error: TranslationException) { - throw error - } catch (error: Exception) { - throw TranslationException(TranslationException.Reason.OFFLINE, "Unable to download Minecraft resource", error) - } finally { - connection.disconnect() - } - } - - private fun connection(uri: URI): HttpURLConnection { - require(uri.scheme == "https" && uri.host in ALLOWED_HOSTS) { "Unsupported localization host: $uri" } - return (uri.toURL().openConnection() as HttpURLConnection).apply { - instanceFollowRedirects = false - connectTimeout = this@LocalizationHttpClient.connectTimeout.toMillis().coerceAtMost(Int.MAX_VALUE.toLong()).toInt() - readTimeout = this@LocalizationHttpClient.readTimeout.toMillis().coerceAtMost(Int.MAX_VALUE.toLong()).toInt() - setRequestProperty("Accept", "application/json, application/octet-stream") - } - } - - companion object { - private val ALLOWED_HOSTS = setOf( - "piston-meta.mojang.com", "launchermeta.mojang.com", - "resources.download.minecraft.net", "piston-data.mojang.com", - ) - } -} diff --git a/modules/journal/build.gradle.kts b/modules/journal/build.gradle.kts deleted file mode 100644 index df0be0ac6..000000000 --- a/modules/journal/build.gradle.kts +++ /dev/null @@ -1,54 +0,0 @@ -plugins { - alias(libs.plugins.kotlin.jvm) - `java-library` - alias(libs.plugins.maven.publish) -} - -base { archivesName = "${rootProject.property("pnlibrary.name")}-journal" } - -dependencies { - api(project(":modules:api")) - implementation(project(":modules:common")) - implementation(libs.adventure.minimessage) - implementation(libs.adventure.legacy) - implementation(libs.adventure.gson) - implementation(libs.adventure.plain) - implementation(libs.kotlin.stdlib) - - testImplementation(libs.junit.jupiter) - testImplementation(libs.mockito.core) - testRuntimeOnly(libs.junit.launcher) -} - -mavenPublishing { - publishToMavenCentral() - signAllPublications() - coordinates("io.github.pnfolder", "pnlibrary-journal", project.version.toString()) - pom { - name.set("pnLibrary journal") - description.set("Event journal and its chat pages for pnLibrary.") - inceptionYear.set("2026") - url.set("https://github.com/${rootProject.property("pnlibrary.repository")}") - licenses { - license { - name.set(providers.gradleProperty("POM_LICENSE_NAME")) - url.set(providers.gradleProperty("POM_LICENSE_URL")) - distribution.set(providers.gradleProperty("POM_LICENSE_DIST").orElse("repo")) - } - } - developers { - rootProject.property("pnlibrary.authors").toString().split(",").map(String::trim).forEach { author -> - developer { - id.set(author) - name.set(author) - url.set("https://github.com/" + rootProject.property("pnlibrary.organization")) - } - } - } - scm { - url.set("https://github.com/${rootProject.property("pnlibrary.repository")}") - connection.set("scm:git:git://github.com/${rootProject.property("pnlibrary.repository")}.git") - developerConnection.set("scm:git:ssh://git@github.com/${rootProject.property("pnlibrary.repository")}.git") - } - } -} diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalCard.kt b/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalCard.kt deleted file mode 100644 index 57e851cef..000000000 --- a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalCard.kt +++ /dev/null @@ -1,131 +0,0 @@ -package org.pnfolder.pnlibrary.core.journal - -import net.kyori.adventure.text.Component -import net.kyori.adventure.text.event.ClickEvent -import org.pnfolder.pnlibrary.api.chat.ChatKit -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.commands.CommandSender -import org.pnfolder.pnlibrary.common.time.DisplayZone - -/** The detail card of one event, or the timeline of its occurrences when [repeats] is set. */ -fun card( - sender: CommandSender, - kit: ChatKit, - journal: JournalStore, - id: String?, - repeats: Boolean, - fullTrace: Boolean = false, - root: String, -) { - val group = journal.read(limit = SCAN_LIMIT).filter { it.fingerprint == id }.sortedByDescending { it.timeMillis } - if (id == null || group.isEmpty()) { - sender.send(kit.text("Такой записи нет: возможно, её уже удалили по сроку хранения.", ChatPalette.DANGER)) - return - } - val record = group.first() - val (tag, color) = levelStyle(record.level) - var traceHidden = false - val lines = mutableListOf( - kit.blank(), - kit.blank(), - kit.header("Событие $id", kit.bracketed(tag, color)), - kit.text(" ${record.source}", ChatPalette.ACCENT).append(kit.dot()).append(kit.text(record.type, ChatPalette.LABEL)), - kit.blank(), - ) - lines += kit.section("Когда") - lines += kit.field( - "Последний раз", - moment(kit, record.timeMillis).append(kit.text(" ${ago(record.timeMillis)}", agoColor(record.timeMillis))), - ) - lines += kit.field("Часовой пояс", kit.text(zoneLabel(), ChatPalette.SOFT)) - if (group.size > 1) { - val gap = (group.first().timeMillis - group.last().timeMillis) / (group.size - 1) - lines += kit.field("Первый раз", moment(kit, group.last().timeMillis).append(kit.text(" ${ago(group.last().timeMillis)}", - agoColor(group.last().timeMillis)))) - lines += kit.field( - "Повторов", - kit.text(group.size.toString(), ChatPalette.ORANGE).append(kit.text(" примерно раз в ${span(gap)}", ChatPalette.SOFT)), - ) - } - lines += kit.blank() - if (repeats) { - val zone = DisplayZone.zone - val today = java.time.LocalDate.now(zone) - val days = group.take(REPEAT_ROWS).groupBy { java.time.Instant.ofEpochMilli(it.timeMillis).atZone(zone).toLocalDate() } - days.forEach { (day, items) -> - val title = when (day) { - today -> "Сегодня" - today.minusDays(1) -> "Вчера" - else -> longDate(day) - } - val dayTip = kit.tooltip( - kit.text(DAY_WITH_YEAR.format(day), ChatPalette.TEXT), - kit.text(WEEKDAY.format(day), ChatPalette.LABEL), - kit.blank(), - kit.hoverField("Событий в этот день", kit.text(items.size.toString(), ChatPalette.ORANGE)), - ) - var heading = kit.section(title) - if (day == today || day == today.minusDays(1)) heading = heading.append(kit.text(" · ${longDate(day)}", ChatPalette.SOFT)) - lines += heading.append(kit.text(" ×${items.size}", ChatPalette.ORANGE)).hoverEvent(dayTip) - items.forEach { item -> - lines += kit.text(" " + CLOCK.withZone(zone).format(java.time.Instant.ofEpochMilli(item.timeMillis)), ChatPalette.TEXT) - .append(kit.text(" ${ago(item.timeMillis)}", agoColor(item.timeMillis))) - .hoverEvent(momentTip(kit, item.timeMillis)) - } - lines += kit.blank() - } - if (group.size > REPEAT_ROWS) { - lines += kit.note("Показаны последние $REPEAT_ROWS из ${group.size}.") - lines += kit.blank() - } - } else { - lines += kit.section("Что случилось") - wrap(record.message, CARD_WIDTH).forEach { lines += kit.text(" $it", ChatPalette.TEXT) } - record.details.filterKeys { it != JournalRecord.STACKTRACE }.forEach { (key, value) -> - lines += kit.text(" $key: ", ChatPalette.LABEL).append(kit.text(value, ChatPalette.SOFT)) - } - val trace = record.details[JournalRecord.STACKTRACE]?.lines().orEmpty() - if (trace.isNotEmpty()) { - lines += kit.blank() - lines += kit.section("Стек вызовов") - val (view, hidden) = traceView(kit, trace, sender.isConsole || fullTrace) - lines += view - traceHidden = hidden - } - lines += kit.blank() - } - val buttons = mutableListOf( - kit.button("назад", "$root", "К списку событий", ChatPalette.ACCENT), - if (repeats) kit.button("карточка", "$root view $id", "Вернуться к карточке", ChatPalette.ACCENT) - else if (group.size > 1) kit.button("повторы", "$root times $id", "Когда это повторялось", ChatPalette.ACCENT) - else null, - if (traceHidden) kit.button("показать всё", "$root full $id", "Стек вызовов целиком, ничего не свёрнуто", ChatPalette.ACCENT) - else if (fullTrace) kit.button("свернуть", "$root view $id", "Снова свернуть служебные вызовы", ChatPalette.ACCENT) - else null, - ) - if (kit.reader.interactive) { - buttons += kit.bracketed("скопировать", ChatPalette.OK) - .clickEvent(ClickEvent.copyToClipboard(report(record, group.size))) - .hoverEvent( - kit.tooltip( - kit.text("Скопировать отчёт для автора плагина", ChatPalette.OK), - kit.blank(), - kit.text("Время, число повторов, сообщение и весь стек вызовов", ChatPalette.LABEL), - ), - ) - } - lines += kit.actions(*buttons.toTypedArray()) ?: kit.blank() - lines.forEach(sender::send) -} - -/** Plain text for the plugin author: what happened, how often, and the whole stack trace. */ -fun report(record: JournalRecord, count: Int): String = buildString { - appendLine("[${record.level}] ${record.source} · ${record.type}") - appendLine("Время: ${stamp(record.timeMillis)} ${zoneLabel()}, повторов: $count") - appendLine(record.message) - record.details.filterKeys { it != JournalRecord.STACKTRACE }.forEach { (key, value) -> appendLine("$key: $value") } - record.details[JournalRecord.STACKTRACE]?.let { - appendLine() - append(it) - } -}.trim() diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalLayout.kt b/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalLayout.kt deleted file mode 100644 index bcdc8c91a..000000000 --- a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalLayout.kt +++ /dev/null @@ -1,21 +0,0 @@ -package org.pnfolder.pnlibrary.core.journal - -/** rows shown on one page of `/pn events`. */ -const val PAGE_SIZE = 5 - -/** Longest message shown in a player's chat so lines do not flood it; the console and the card show all. */ -const val CHAT_CHARS = 46 - -/** Records read to fold repeats and to count how often an event happened. */ -const val SCAN_LIMIT = 5_000 - -/** Width in characters at which hover text is wrapped, and how many message lines a hover shows. */ -const val HOVER_WIDTH = 44 - -const val HOVER_MESSAGE_LINES = 4 - -/** Width at which the message in the card is wrapped. */ -const val CARD_WIDTH = 56 - -/** Occurrence times listed on the repeats page. */ -const val REPEAT_ROWS = 15 diff --git a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalStore.kt b/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalStore.kt deleted file mode 100644 index 79a4b79f7..000000000 --- a/modules/journal/src/main/kotlin/org/pnfolder/pnlibrary/core/journal/JournalStore.kt +++ /dev/null @@ -1,218 +0,0 @@ -package org.pnfolder.pnlibrary.core.journal - -import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import java.nio.channels.FileChannel -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.StandardOpenOption -import java.time.Clock -import java.time.Duration -import java.time.Instant -import java.time.LocalDate -import java.time.ZoneOffset -import java.util.PriorityQueue - -/** - * Durable, local journal of everything the library and its plugins report. - * - * Records are grouped by event date into bounded segments named `-[-segment].pnj`. - * Legacy daily files remain readable. Reads keep only the selected newest records in memory and - * scan at most [maximumReadBytes]; summary exposes an exhausted budget. Retention also caps disk use. - * Every append writes a whole block to the end of today's file. ERROR records are forced to disk - * before [append] returns, so a crash right after an error cannot lose it. - * - * Retention is per level: each level's files are removed once they are older than that level's limit, - * so an error is kept longer than a routine info line. - * - * @param directory journal folder, created on first use - * @param retention maximum age of files per level - * @param clock source of the current date for file names and pruning - */ -class JournalStore( - private val directory: Path, - private val retention: Map, - private val clock: Clock = Clock.systemUTC(), - private val maximumSegmentBytes: Long = 8L * 1024 * 1024, - private val maximumDiskBytes: Long = 256L * 1024 * 1024, - private val maximumReadBytes: Long = 64L * 1024 * 1024, -) { - init { - require(JournalLevel.values().all { it in retention }) { "Every journal level needs a retention period" } - require(maximumSegmentBytes > 0 && maximumDiskBytes >= maximumSegmentBytes && maximumReadBytes > 0) - } - - private var lastPrunedOn: LocalDate? = null - - /** - * Writes [record] as one block to today's file of its level. - * - * Old files are pruned once per day here, so a server that runs for weeks without a restart still - * honours the retention limits. - */ - @Synchronized - fun append(record: JournalRecord) { - Files.createDirectories(directory) - val today = today() - if (lastPrunedOn != today) { - lastPrunedOn = today - runCatchingNonFatal { prune() } - } - val block = JournalBlockCodec.encode(listOf(record)) - require(block.size <= maximumDiskBytes) { "Journal block exceeds disk budget" } - val date = Instant.ofEpochMilli(record.timeMillis).atZone(ZoneOffset.UTC).toLocalDate() - val existing = filesOf(record.level).filter { dateOf(it) == date }.maxByOrNull(::segmentOf) - val target = if (existing != null && Files.size(existing) + block.size <= maximumSegmentBytes) existing else { - val segment = existing?.let { segmentOf(it) + 1 } ?: 0 - directory.resolve("${record.level.fileGroup}-$date${if (segment == 0) "" else "-$segment"}.pnj") - } - FileChannel.open(target, StandardOpenOption.CREATE, StandardOpenOption.WRITE, - StandardOpenOption.APPEND).use { channel -> - val bytes = java.nio.ByteBuffer.wrap(block) - while (bytes.hasRemaining()) channel.write(bytes) - if (record.level == JournalLevel.ERROR) channel.force(true) - } - enforceDiskBudget() - } - - /** - * Returns records that match the filters, newest first, at most [limit] of them. - * - * @param levels levels to include; an empty set means every level - * @param source exact source name, or `null` for every source - * @param sinceMillis earliest time to include, or `null` for no lower bound - * @param type record type to return; with `null` every type except [JournalRecord.STATS_TYPE] - */ - fun read( - levels: Set = emptySet(), - source: String? = null, - sinceMillis: Long? = null, - limit: Int = 100, - type: String? = null, - ): List = readSnapshot(levels, source, sinceMillis, limit, type).records - - /** Newest-first read; [Snapshot.truncated] tells whether the byte budget stopped it before all matches. */ - private fun readSnapshot( - levels: Set, - source: String?, - sinceMillis: Long?, - limit: Int, - type: String? = null, - ): Snapshot { - require(limit in 1..100_000) { "Journal limit must be between 1 and 100000" } - val wanted = if (levels.isEmpty()) JournalLevel.values().toSet() else levels - val sinceDate = sinceMillis?.let { Instant.ofEpochMilli(it).atZone(ZoneOffset.UTC).toLocalDate() } - val files = wanted.flatMap(::filesOf).filter { sinceDate == null || dateOf(it)?.isBefore(sinceDate) != true } - .sortedWith(compareByDescending { dateOf(it) }.thenByDescending(::segmentOf)) - val newest = PriorityQueue(compareBy { it.timeMillis }) - var remaining = maximumReadBytes - var scannedDate: LocalDate? = null - var truncated = false - for (file in files) { - val date = dateOf(file) - if (newest.size >= limit && date != scannedDate) break - scannedDate = date - try { - val size = Files.size(file) - // Files are read whole and newest first: a file that does not fit is skipped, so the - // returned records are always the newest complete set rather than an arbitrary prefix. - if (size > remaining) { truncated = true; break } - Files.newInputStream(file).buffered().use { input -> - JournalBlockCodec.visit(input, size) { record -> - val typeFits = if (type == null) record.type != JournalRecord.STATS_TYPE else record.type == type - if (typeFits && (source == null || record.source == source) && (sinceMillis == null || record.timeMillis >= sinceMillis)) { - if (newest.size < limit) newest.add(record) - else if (record.timeMillis > newest.peek().timeMillis) { newest.poll(); newest.add(record) } - } - } - } - remaining -= size - } catch (_: java.nio.file.NoSuchFileException) { - // Retention can remove a segment after the reader takes its snapshot. - } - } - return Snapshot(newest.sortedByDescending { it.timeMillis }, truncated) - } - - private class Snapshot(val records: List, val truncated: Boolean) - - /** - * Counts and retention per level for diagnostic reports. It holds no message text, so it is safe to share: - * for each level the number of records in the last 24 hours, the time of the newest one, and the retention. - */ - fun summary(): Map { - val since = clock.millis() - Duration.ofHours(24).toMillis() - return JournalLevel.values().associate { level -> - val snapshot = readSnapshot(levels = setOf(level), source = null, sinceMillis = since, limit = SUMMARY_LIMIT) - val recent = snapshot.records - level.fileGroup to linkedMapOf( - "recordsLast24h" to recent.size, - "countCapped" to (recent.size >= SUMMARY_LIMIT || snapshot.truncated), - "readBudgetExhausted" to snapshot.truncated, - "maximumReadBytes" to maximumReadBytes, - "maximumDiskBytes" to maximumDiskBytes, - "newestAtMillis" to recent.firstOrNull()?.timeMillis, - "retentionDays" to retentionDays(level), - ) - } - } - - @Synchronized - fun prune(): Int { - if (!Files.isDirectory(directory)) return 0 - val today = today() - var removed = 0 - JournalLevel.values().forEach { level -> - val keepFrom = today.minusDays(retentionDays(level)) - filesOf(level).forEach { file -> - val date = dateOf(file) ?: return@forEach - if (date.isBefore(keepFrom)) { - Files.deleteIfExists(file) - removed++ - } - } - } - return removed + enforceDiskBudget() - } - - /** Evicts oldest files first, but routine levels before ERROR so the disk budget never drops errors early. */ - private fun enforceDiskBudget(): Int { - val files = JournalLevel.values().flatMap(::filesOf) - .sortedWith(compareBy { it.fileName.toString().startsWith("${JournalLevel.ERROR.fileGroup}-") } - .thenBy { dateOf(it) }.thenBy(::segmentOf)) - var total = files.sumOf { Files.size(it) } - var removed = 0 - for (file in files) { - if (total <= maximumDiskBytes) break - val bytes = Files.size(file) - if (Files.deleteIfExists(file)) { total -= bytes; removed++ } - } - return removed - } - - private companion object { - /** Records counted per level in [summary]; more than this is reported as "at least". */ - const val SUMMARY_LIMIT = 10_000 - } - - private fun retentionDays(level: JournalLevel): Long = - retention.getValue(level).toDays().coerceAtLeast(1) - - private fun today(): LocalDate = LocalDate.now(clock.withZone(ZoneOffset.UTC)) - - private fun segmentOf(file: Path): Int = file.fileName.toString().substringAfter('-').drop(10) - .removePrefix("-").removeSuffix(".pnj").toIntOrNull() ?: 0 - - private fun filesOf(level: JournalLevel): List { - if (!Files.isDirectory(directory)) return emptyList() - val prefix = "${level.fileGroup}-" - return Files.list(directory).use { stream -> - stream.filter { Files.isRegularFile(it) && it.fileName.toString().startsWith(prefix) && it.fileName.toString().endsWith(".pnj") } - .sorted() - .collect(java.util.stream.Collectors.toList()) - } - } - - private fun dateOf(file: Path): LocalDate? = - runCatchingNonFatal { LocalDate.parse(file.fileName.toString().substringAfter('-').take(10)) } - .getOrNull() -} diff --git a/modules/link/build.gradle.kts b/modules/link/build.gradle.kts deleted file mode 100644 index 2bf66f1d0..000000000 --- a/modules/link/build.gradle.kts +++ /dev/null @@ -1,50 +0,0 @@ -plugins { - alias(libs.plugins.kotlin.jvm) - `java-library` - alias(libs.plugins.maven.publish) -} - -base { archivesName = "${rootProject.property("pnlibrary.name")}-link" } - -dependencies { - api(project(":modules:api")) - implementation(project(":modules:common")) - implementation(libs.kotlin.stdlib) - - testImplementation(libs.junit.jupiter) - testImplementation(libs.mockito.core) - testRuntimeOnly(libs.junit.launcher) -} - -mavenPublishing { - publishToMavenCentral() - signAllPublications() - coordinates("io.github.pnfolder", "pnlibrary-link", project.version.toString()) - pom { - name.set("pnLibrary Link") - description.set("Messages between a proxy and its game servers for pnLibrary.") - inceptionYear.set("2026") - url.set("https://github.com/${rootProject.property("pnlibrary.repository")}") - licenses { - license { - name.set(providers.gradleProperty("POM_LICENSE_NAME")) - url.set(providers.gradleProperty("POM_LICENSE_URL")) - distribution.set(providers.gradleProperty("POM_LICENSE_DIST").orElse("repo")) - } - } - developers { - rootProject.property("pnlibrary.authors").toString().split(",").map(String::trim).forEach { author -> - developer { - id.set(author) - name.set(author) - url.set("https://github.com/" + rootProject.property("pnlibrary.organization")) - } - } - } - scm { - url.set("https://github.com/${rootProject.property("pnlibrary.repository")}") - connection.set("scm:git:git://github.com/${rootProject.property("pnlibrary.repository")}.git") - developerConnection.set("scm:git:ssh://git@github.com/${rootProject.property("pnlibrary.repository")}.git") - } - } -} diff --git a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkSecret.kt b/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkSecret.kt deleted file mode 100644 index b934995ca..000000000 --- a/modules/link/src/main/kotlin/org/pnfolder/pnlibrary/core/link/LinkSecret.kt +++ /dev/null @@ -1,44 +0,0 @@ -package org.pnfolder.pnlibrary.core.link - -import java.nio.file.Files -import java.nio.file.Path -import java.security.SecureRandom -import java.util.Base64 - -/** - * The key the proxy and its game servers share, kept in `link.key` in the pnLibrary folder. - * - * The proxy makes the file when it is missing; a game server only reads it, so the link stays off until the - * administrator copies the file from the proxy. - */ -object LinkSecret { - const val FILE = "link.key" - private const val KEY_BYTES = 32 - - /** Reads the key from [folder], or returns null when there is no valid key file. */ - fun read(folder: Path): ByteArray? = runCatching { - val text = String(Files.readAllBytes(folder.resolve(FILE)), Charsets.UTF_8).removePrefix(BOM).trim() - Base64.getDecoder().decode(text).takeIf { it.size >= KEY_BYTES } - }.getOrNull() - - /** - * Reads the key from [folder] and makes a new one only when the file does not exist. - * - * A file that exists but cannot be read is left alone and the link stays off: a new key would silently cut - * this proxy off from every server that already has the old one. - */ - fun readOrCreate(folder: Path, warn: (String) -> Unit = {}): ByteArray? { - val path = folder.resolve(FILE) - if (Files.exists(path)) { - return read(folder) ?: null.also { warn("$FILE exists but holds no valid key; the link stays off until it is fixed or deleted") } - } - val key = ByteArray(KEY_BYTES).also(SecureRandom()::nextBytes) - return runCatching { - Files.createDirectories(folder) - Files.write(path, (Base64.getEncoder().encodeToString(key) + '\n').toByteArray(Charsets.UTF_8)) - key - }.getOrNull() - } - - private const val BOM = "\uFEFF" -} diff --git a/modules/placeholders/build.gradle.kts b/modules/placeholders/build.gradle.kts deleted file mode 100644 index c6cb0bc6c..000000000 --- a/modules/placeholders/build.gradle.kts +++ /dev/null @@ -1,51 +0,0 @@ -plugins { - alias(libs.plugins.kotlin.jvm) - `java-library` - alias(libs.plugins.maven.publish) -} - -base { archivesName = "${rootProject.property("pnlibrary.name")}-placeholders" } - -dependencies { - api(project(":modules:api")) - implementation(project(":modules:common")) - implementation(project(":modules:runtime-spi")) - implementation(libs.kotlin.stdlib) - - testImplementation(libs.junit.jupiter) - testImplementation(libs.mockito.core) - testRuntimeOnly(libs.junit.launcher) -} - -mavenPublishing { - publishToMavenCentral() - signAllPublications() - coordinates("io.github.pnfolder", "pnlibrary-placeholders", project.version.toString()) - pom { - name.set("pnLibrary placeholders") - description.set("Placeholder registry and expansion for pnLibrary.") - inceptionYear.set("2026") - url.set("https://github.com/${rootProject.property("pnlibrary.repository")}") - licenses { - license { - name.set(providers.gradleProperty("POM_LICENSE_NAME")) - url.set(providers.gradleProperty("POM_LICENSE_URL")) - distribution.set(providers.gradleProperty("POM_LICENSE_DIST").orElse("repo")) - } - } - developers { - rootProject.property("pnlibrary.authors").toString().split(",").map(String::trim).forEach { author -> - developer { - id.set(author) - name.set(author) - url.set("https://github.com/" + rootProject.property("pnlibrary.organization")) - } - } - } - scm { - url.set("https://github.com/${rootProject.property("pnlibrary.repository")}") - connection.set("scm:git:git://github.com/${rootProject.property("pnlibrary.repository")}.git") - developerConnection.set("scm:git:ssh://git@github.com/${rootProject.property("pnlibrary.repository")}.git") - } - } -} diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/LocalPlaceholderExpression.kt b/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/LocalPlaceholderExpression.kt deleted file mode 100644 index 4a90061d8..000000000 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/LocalPlaceholderExpression.kt +++ /dev/null @@ -1,25 +0,0 @@ -package org.pnfolder.pnlibrary.core.placeholders - -/** Parsed single-bracket placeholder backed by values local to an action context. */ -data class LocalPlaceholderExpression( - val reference: String, - val formatters: List, -) { - companion object { - /** Parses `[reference|formatter:argument]`, or returns `null` for malformed input. */ - fun parse(token: String): LocalPlaceholderExpression? { - if (token.length < 3 || token.first() != '[' || token.last() != ']') return null - val body = token.substring(1, token.length - 1) - if ('[' in body || ']' in body) return null - - val parts = body.split('|').map(String::trim) - val reference = parts.firstOrNull().orEmpty() - if (reference.isEmpty()) return null - - return LocalPlaceholderExpression( - reference = reference, - formatters = parts.drop(1).filter(String::isNotEmpty), - ) - } - } -} diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderAddressIndex.kt b/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderAddressIndex.kt deleted file mode 100644 index f81ab68ed..000000000 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderAddressIndex.kt +++ /dev/null @@ -1,42 +0,0 @@ -package org.pnfolder.pnlibrary.core.placeholders - -import java.util.concurrent.ConcurrentHashMap - -/** Finds placeholders by their readable `plugin/module:name` address. */ -class PlaceholderAddressIndex { - private val entries = ConcurrentHashMap>() - - /** Adds [entry] under [address]; returns `false` when the address is taken. */ - fun add(address: PlaceholderAddress, entry: PlaceholderEntry<*>): Boolean = entries.putIfAbsent(address, entry) == null - - fun remove(address: PlaceholderAddress, entry: PlaceholderEntry<*>) { - entries.remove(address, entry) - } - - /** Every address with its entry, ordered for display. */ - fun all(): List>> = - entries.entries.map { it.key to it.value }.sortedBy { it.first.toString() } - - /** Finds the exact entry, or the most specific pattern of the same plugin and module. */ - fun find(address: PlaceholderAddress): PlaceholderEntryLookup.Match = - search(address.name) { known -> known.plugin == address.plugin && known.module == address.module } - - /** Finds [name] in any module of [plugin]; the module `main` comes first, the rest by name. */ - fun findInPlugin(plugin: String, name: String): PlaceholderEntryLookup.Match = - search(name) { known -> known.plugin == plugin } - - private fun search(name: String, inScope: (PlaceholderAddress) -> Boolean): PlaceholderEntryLookup.Match { - val candidates = entries.entries.filter { inScope(it.key) }.sortedWith(compareBy({ it.key.module != MAIN }, { it.key.module })) - val lowered = name.lowercase() - candidates.firstOrNull { it.key.name == lowered }?.let { return PlaceholderEntryLookup.Match(it.value, emptyMap()) } - return candidates - .mapNotNull { (known, entry) -> PlaceholderPatternMatcher.match(known.name, name)?.let { Triple(known, entry, it) } } - .maxByOrNull { (known, _, _) -> PlaceholderPatternMatcher.specificity(known.name) } - ?.let { (_, entry, parameters) -> PlaceholderEntryLookup.Match(entry, parameters) } - ?: PlaceholderEntryLookup.Match(null, emptyMap()) - } - - private companion object { - const val MAIN = PlaceholderAddress.DEFAULT_MODULE - } -} diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderEntryLookup.kt b/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderEntryLookup.kt deleted file mode 100644 index 59b85578e..000000000 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderEntryLookup.kt +++ /dev/null @@ -1,45 +0,0 @@ -package org.pnfolder.pnlibrary.core.placeholders - -import org.pnfolder.pnlibrary.api.plugin.PluginId -import java.util.Locale - -/** Resolves exact and patterned placeholder references across plugin namespaces. */ -class PlaceholderEntryLookup( - private val entries: Map>, - private val systemNamespace: PluginId, -) { - data class Match( - val entry: PlaceholderEntry<*>?, - val parameters: Map, - ) - - /** Finds the most specific entry visible under the namespace encoded in [reference]. */ - fun find(consumer: PluginId, reference: String): Match { - val separator = reference.indexOf(':') - val namespace = if (separator > 0) { - PluginId.of(reference.substring(0, separator)) - } else { - consumer - } - val key = if (separator > 0) reference.substring(separator + 1) else reference - - exact(namespace, key)?.let { return Match(it, emptyMap()) } - if (separator < 0) { - exact(systemNamespace, key)?.let { return Match(it, emptyMap()) } - } - - return entries.values - .asSequence() - .filter { entry -> entry.owner == namespace } - .mapNotNull { entry -> - PlaceholderPatternMatcher.match(entry.key.value, key) - ?.let { parameters -> entry to parameters } - } - .maxByOrNull { (entry, _) -> PlaceholderPatternMatcher.specificity(entry.key.value) } - ?.let { (entry, parameters) -> Match(entry, parameters) } - ?: Match(null, emptyMap()) - } - - private fun exact(owner: PluginId, key: String): PlaceholderEntry<*>? = - entries["${owner.value}:${key.lowercase(Locale.ROOT)}"] -} diff --git a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPatternMatcher.kt b/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPatternMatcher.kt deleted file mode 100644 index 8e8c99d7f..000000000 --- a/modules/placeholders/src/main/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderPatternMatcher.kt +++ /dev/null @@ -1,38 +0,0 @@ -package org.pnfolder.pnlibrary.core.placeholders - -/** - * Matches a concrete placeholder key against a parameterized key pattern. - * - * Parameters use braces, for example `player.stat.{name}` matches - * `player.stat.kills` and returns `name=kills`. A parameter consumes exactly - * one dot-delimited segment; literal portions of a pattern are matched - * verbatim. - */ -object PlaceholderPatternMatcher { - private val parameter = Regex("\\{([a-zA-Z0-9_-]+)}") - - /** How many characters of [pattern] are fixed text; a pattern with more of them is the more specific one. */ - fun specificity(pattern: String): Int = parameter.replace(pattern, "").length - - /** Returns captured parameters, or `null` when [value] does not match [pattern]. */ - fun match(pattern: String, value: String): Map? { - val tokens = parameter.findAll(pattern).toList() - if (tokens.isEmpty()) return null - - var cursor = 0 - val expression = buildString { - append('^') - tokens.forEach { token -> - append(Regex.escape(pattern.substring(cursor, token.range.first))) - append("([^.]+)") - cursor = token.range.last + 1 - } - append(Regex.escape(pattern.substring(cursor))) - append('$') - } - val result = Regex(expression).matchEntire(value) ?: return null - return tokens.mapIndexed { index, token -> - token.groupValues[1] to result.groupValues[index + 1] - }.toMap() - } -} diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/LocalPlaceholderExpressionTest.kt b/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/LocalPlaceholderExpressionTest.kt deleted file mode 100644 index c087e91e5..000000000 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/LocalPlaceholderExpressionTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -package org.pnfolder.pnlibrary.core.placeholders - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertNull -import org.junit.jupiter.api.Test - -class LocalPlaceholderExpressionTest { - @Test - fun `parses local reference and formatter pipeline`() { - val expression = requireNotNull( - LocalPlaceholderExpression.parse("[player-level|default:0|upper]"), - ) - - assertEquals("player-level", expression.reference) - assertEquals(listOf("default:0", "upper"), expression.formatters) - } - - @Test - fun `rejects malformed or empty local expressions`() { - listOf("player", "[]", "[ ]", "[|upper]", "[[player]]", "[player").forEach { - assertNull(LocalPlaceholderExpression.parse(it), it) - } - } -} diff --git a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderTemplateRendererTest.kt b/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderTemplateRendererTest.kt deleted file mode 100644 index a11df8f3f..000000000 --- a/modules/placeholders/src/test/kotlin/org/pnfolder/pnlibrary/core/placeholders/PlaceholderTemplateRendererTest.kt +++ /dev/null @@ -1,30 +0,0 @@ -package org.pnfolder.pnlibrary.core.placeholders - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Test -import java.util.concurrent.CompletableFuture - -class PlaceholderTemplateRendererTest { - @Test - fun `renderer handles conditions local expressions and ordinary expressions`() { - val values = mapOf( - "enabled" to true, - "status" to "online", - "name" to "Alex", - ) - val renderer = PlaceholderTemplateRenderer( - resolve = { expression, _, _ -> CompletableFuture.completedFuture(values[expression]) }, - format = { value, pipeline, _, _ -> - if ("upper" in pipeline) value?.toString()?.uppercase() else value - }, - ) - - val rendered = renderer.render( - "{?enabled}Server [status|upper]: {name}{:}offline{/}", - playerId = null, - values = emptyMap(), - ).toCompletableFuture().join() - - assertEquals("Server ONLINE: Alex", rendered) - } -} diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapter.kt b/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapter.kt deleted file mode 100644 index 0323d618f..000000000 --- a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapter.kt +++ /dev/null @@ -1,50 +0,0 @@ -package org.pnfolder.pnlibrary.spi.tasks - -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import java.time.Duration - -/** - * Native scheduling request emitted by the shared task service. - * - * @property executionKind requested platform execution context - * @property target native entity target for entity execution - * @property delay delay before the first invocation - * @property interval repeat interval, or `null` for one-shot execution - * @property callback callback dispatched by the platform scheduler - * @property owner native plugin owning this task; supplied by the shared task scope - */ -data class PlatformTaskRequest( - val executionKind: TaskExecution.Kind, - val target: Any?, - val delay: Duration, - val interval: Duration?, - val callback: Runnable, - val owner: Any? = null, -) { - init { - require(executionKind != TaskExecution.Kind.ENTITY || target != null) { "Entity task target is required" } - require(!delay.isNegative) { "Task delay must not be negative" } - interval?.let { require(!it.isNegative && !it.isZero) { "Task interval must be positive" } } - } -} - -/** Native cancellation handle returned by a platform scheduler. */ -fun interface PlatformTaskHandle { - /** Cancels future execution and reports whether cancellation changed state. */ - fun cancel(): Boolean -} - -/** Native scheduling boundary implemented by each platform runtime. */ -interface PlatformTaskAdapter : AutoCloseable { - /** Schedules [request] and returns its native cancellation handle. */ - fun schedule(request: PlatformTaskRequest): PlatformTaskHandle - /** Releases platform scheduler resources. */ - override fun close() = Unit -} - -/** Adapter used by runtimes that do not provide native task scheduling. */ -object UnsupportedPlatformTaskAdapter : PlatformTaskAdapter { - /** Always fails because scheduling is unavailable. */ - override fun schedule(request: PlatformTaskRequest): PlatformTaskHandle = - throw UnsupportedOperationException("Native task scheduling is not supported by this platform") -} diff --git a/modules/runtime-spi/api/runtime-spi.api b/modules/spi/api/spi.api similarity index 77% rename from modules/runtime-spi/api/runtime-spi.api rename to modules/spi/api/spi.api index 84be790b1..479188cb4 100644 --- a/modules/runtime-spi/api/runtime-spi.api +++ b/modules/spi/api/spi.api @@ -1,7 +1,7 @@ public abstract interface class org/pnfolder/pnlibrary/spi/audiences/PlatformAudienceAdapter { public abstract fun console ()Lorg/pnfolder/pnlibrary/api/audiences/AudienceSender; public abstract fun onlinePlayers ()Ljava/util/List; - public abstract fun player (Ljava/util/UUID;)Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer; + public abstract fun player (Ljava/util/UUID;)Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer; public abstract fun sender (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/audiences/AudienceSender; } @@ -9,7 +9,7 @@ public final class org/pnfolder/pnlibrary/spi/audiences/UnsupportedPlatformAudie public static final field INSTANCE Lorg/pnfolder/pnlibrary/spi/audiences/UnsupportedPlatformAudienceAdapter; public fun console ()Lorg/pnfolder/pnlibrary/api/audiences/AudienceSender; public fun onlinePlayers ()Ljava/util/List; - public fun player (Ljava/util/UUID;)Lorg/pnfolder/pnlibrary/api/audiences/LibraryPlayer; + public fun player (Ljava/util/UUID;)Lorg/pnfolder/pnlibrary/api/audiences/player/LibraryPlayer; public fun sender (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/api/audiences/AudienceSender; } @@ -17,21 +17,21 @@ public abstract class org/pnfolder/pnlibrary/spi/commands/GenericPlatformCommand public fun ()V protected abstract fun context (Ljava/lang/Object;Ljava/lang/String;[Ljava/lang/String;)Lorg/pnfolder/pnlibrary/api/commands/CommandContext; protected abstract fun getRegistrar ()Lorg/pnfolder/pnlibrary/spi/commands/NativeCommandRegistrar; - protected final fun registerNative (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition;Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandDispatcher;)Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration; + protected final fun registerNative (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition;Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandDispatcher;)Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration; } public abstract interface class org/pnfolder/pnlibrary/spi/commands/NativeCommandRegistrar { - public abstract fun register (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition;Lkotlin/jvm/functions/Function3;Lkotlin/jvm/functions/Function3;)Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration; + public abstract fun register (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition;Lkotlin/jvm/functions/Function3;Lkotlin/jvm/functions/Function3;)Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration; } public abstract interface class org/pnfolder/pnlibrary/spi/commands/PlatformCommandAdapter : java/lang/AutoCloseable { public fun close ()V - public abstract fun register (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition;Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandDispatcher;)Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration; + public abstract fun register (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition;Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandDispatcher;)Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration; } public abstract interface class org/pnfolder/pnlibrary/spi/commands/PlatformCommandDispatcher { - public abstract fun execute (Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition;Lorg/pnfolder/pnlibrary/api/commands/CommandContext;)Ljava/util/concurrent/CompletionStage; - public abstract fun suggest (Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition;Lorg/pnfolder/pnlibrary/api/commands/CommandContext;)Ljava/util/concurrent/CompletionStage; + public abstract fun execute (Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition;Lorg/pnfolder/pnlibrary/api/commands/CommandContext;)Ljava/util/concurrent/CompletionStage; + public abstract fun suggest (Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition;Lorg/pnfolder/pnlibrary/api/commands/CommandContext;)Ljava/util/concurrent/CompletionStage; } public abstract interface class org/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration : java/lang/AutoCloseable { @@ -41,13 +41,25 @@ public abstract interface class org/pnfolder/pnlibrary/spi/commands/PlatformComm public abstract class org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapter : org/pnfolder/pnlibrary/spi/commands/PlatformCommandAdapter { public fun ()V public final fun close ()V - public final fun register (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition;Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandDispatcher;)Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration; - protected abstract fun registerNative (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition;Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandDispatcher;)Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration; + public final fun register (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition;Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandDispatcher;)Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration; + protected abstract fun registerNative (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition;Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandDispatcher;)Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration; } public final class org/pnfolder/pnlibrary/spi/commands/UnsupportedPlatformCommandAdapter : org/pnfolder/pnlibrary/spi/commands/PlatformCommandAdapter { public static final field INSTANCE Lorg/pnfolder/pnlibrary/spi/commands/UnsupportedPlatformCommandAdapter; - public fun register (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/commands/CommandDefinition;Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandDispatcher;)Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration; + public fun register (Ljava/lang/Object;Lorg/pnfolder/pnlibrary/api/commands/definition/CommandDefinition;Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandDispatcher;)Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandRegistration; +} + +public final class org/pnfolder/pnlibrary/spi/libraries/ExternalLibraries { + public static final field INSTANCE Lorg/pnfolder/pnlibrary/spi/libraries/ExternalLibraries; + public final fun fileOf (Ljava/lang/ClassLoader;Ljava/lang/String;)Ljava/lang/String; + public final fun load (Ljava/lang/ClassLoader;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZLjava/lang/Object;)Ljava/lang/ClassLoader; + public static synthetic fun load$default (Lorg/pnfolder/pnlibrary/spi/libraries/ExternalLibraries;Ljava/lang/ClassLoader;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/util/List;ZLjava/lang/Object;ILjava/lang/Object;)Ljava/lang/ClassLoader; +} + +public final class org/pnfolder/pnlibrary/spi/libraries/OptionalLibrary { + public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/ClassLoader;)V + public final fun ensure ()Z } public final class org/pnfolder/pnlibrary/spi/metrics/NoopMetricsFactory : org/pnfolder/pnlibrary/spi/metrics/PlatformMetricsFactory { @@ -57,7 +69,7 @@ public final class org/pnfolder/pnlibrary/spi/metrics/NoopMetricsFactory : org/p public abstract interface class org/pnfolder/pnlibrary/spi/metrics/PlatformMetricsFactory { public abstract fun open (Ljava/lang/Object;Ljava/util/Collection;)Lorg/pnfolder/pnlibrary/api/metrics/PluginMetrics; - public fun openErrorReporter (Ljava/lang/Object;Ljava/util/Collection;)Lorg/pnfolder/pnlibrary/api/metrics/ErrorReporter; + public fun openErrorReporter (Ljava/lang/Object;Ljava/util/Collection;)Lorg/pnfolder/pnlibrary/api/metrics/error/ErrorReporter; } public final class org/pnfolder/pnlibrary/spi/platform/DiagnosticDetailsCollector { @@ -113,11 +125,18 @@ public final class org/pnfolder/pnlibrary/spi/platform/JulLogObserver$Companion public final fun matchPlugin (Ljava/lang/String;Ljava/util/Collection;Lkotlin/jvm/functions/Function1;)Ljava/lang/Object; } +public final class org/pnfolder/pnlibrary/spi/platform/OwnLogScope { + public fun ()V + public final fun isActive ()Z + public final fun run (Lkotlin/jvm/functions/Function0;)Ljava/lang/Object; +} + public abstract interface class org/pnfolder/pnlibrary/spi/platform/PlatformAdapter : org/pnfolder/pnlibrary/spi/platform/PlatformBinding, org/pnfolder/pnlibrary/spi/platform/PlatformDiagnostics, org/pnfolder/pnlibrary/spi/platform/PlatformExecution, org/pnfolder/pnlibrary/spi/platform/PlatformIdentity, org/pnfolder/pnlibrary/spi/platform/PlatformLogObservation, org/pnfolder/pnlibrary/spi/platform/PlatformLogging, org/pnfolder/pnlibrary/spi/platform/PlatformOwnership, org/pnfolder/pnlibrary/spi/platform/PlatformReadiness, org/pnfolder/pnlibrary/spi/platform/PlatformShutdown { public fun getAudienceAdapter ()Lorg/pnfolder/pnlibrary/spi/audiences/PlatformAudienceAdapter; public fun getCommandAdapter ()Lorg/pnfolder/pnlibrary/spi/commands/PlatformCommandAdapter; public abstract fun getDataFolder ()Ljava/nio/file/Path; public fun getMetricsFactory ()Lorg/pnfolder/pnlibrary/spi/metrics/PlatformMetricsFactory; + public fun getNetworkProxy ()Lorg/pnfolder/pnlibrary/api/network/NetworkProxy; public fun getTaskAdapter ()Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapter; } @@ -143,6 +162,7 @@ public abstract interface class org/pnfolder/pnlibrary/spi/platform/PlatformIden public fun getDescriptorFileName ()Ljava/lang/String; public fun getId ()Ljava/lang/String; public fun getImplementationName ()Ljava/lang/String; + public fun getMinecraftVersion ()Ljava/lang/String; public abstract fun getType ()Lorg/pnfolder/pnlibrary/api/platform/PlatformType; public fun isProxy ()Z public fun isServer ()Z @@ -206,7 +226,7 @@ public final class org/pnfolder/pnlibrary/spi/platform/PlatformPlugins { public final class org/pnfolder/pnlibrary/spi/platform/PlatformPnLogger : org/pnfolder/pnlibrary/api/logging/PnLogger { public fun (Lorg/pnfolder/pnlibrary/spi/platform/PlatformLogging;Ljava/lang/Object;Ljava/lang/String;)V - public fun log (Lorg/pnfolder/pnlibrary/api/logging/LogLevel;Ljava/lang/String;Ljava/lang/Throwable;Z)V + public fun log (Lorg/pnfolder/pnlibrary/api/logging/LogLevel;Ljava/lang/String;Ljava/lang/Throwable;Ljava/util/Map;)V } public abstract interface class org/pnfolder/pnlibrary/spi/platform/PlatformReadiness { @@ -279,6 +299,19 @@ public final class org/pnfolder/pnlibrary/spi/platform/ProxyBackend { public final fun getPlayers ()I } +public abstract class org/pnfolder/pnlibrary/spi/platform/ProxyPlatformAdapter : org/pnfolder/pnlibrary/spi/platform/PlatformAdapter { + public fun (Ljava/lang/Object;)V + public fun close ()V + public fun executeReply (Ljava/lang/Object;Ljava/lang/Runnable;)V + protected final fun getLifecycle ()Lorg/pnfolder/pnlibrary/spi/platform/PlatformLifecycle; + public abstract fun getNetworkProxy ()Lorg/pnfolder/pnlibrary/api/network/NetworkProxy; + public final fun markReady ()V + public fun observeNativeLogs (Lkotlin/jvm/functions/Function4;)V + protected abstract fun observeProxyLogs (Lkotlin/jvm/functions/Function4;)V + public final fun warn (Ljava/lang/String;)V + public fun whenServerReady (Ljava/lang/Runnable;)V +} + public final class org/pnfolder/pnlibrary/spi/platform/StartupGate { public fun (Lorg/pnfolder/pnlibrary/spi/platform/PlatformLifecycle;Lkotlin/jvm/functions/Function1;)V public final fun discardPending ()V @@ -292,8 +325,21 @@ public final class org/pnfolder/pnlibrary/spi/platform/UncaughtExceptionLogObser } public abstract interface class org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapter : java/lang/AutoCloseable { + public abstract fun buildTask ()Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskBuilder; public fun close ()V - public abstract fun schedule (Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskHandle; +} + +public final class org/pnfolder/pnlibrary/spi/tasks/PlatformTaskBuilder { + public fun (Lkotlin/jvm/functions/Function1;)V + public final fun build ()Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest; + public final fun delay (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskBuilder; + public final fun entity (Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskBuilder; + public final fun every (Ljava/time/Duration;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskBuilder; + public final fun execution (Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskBuilder; + public static synthetic fun execution$default (Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskBuilder;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind;Ljava/lang/Object;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskBuilder; + public final fun from (Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskBuilder; + public final fun schedule ()Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskHandle; + public final fun task (Ljava/lang/Runnable;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskBuilder; } public abstract interface class org/pnfolder/pnlibrary/spi/tasks/PlatformTaskHandle { @@ -301,22 +347,19 @@ public abstract interface class org/pnfolder/pnlibrary/spi/tasks/PlatformTaskHan } public final class org/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest { - public fun (Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind;Ljava/lang/Object;Ljava/time/Duration;Ljava/time/Duration;Ljava/lang/Runnable;Ljava/lang/Object;)V - public synthetic fun (Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind;Ljava/lang/Object;Ljava/time/Duration;Ljava/time/Duration;Ljava/lang/Runnable;Ljava/lang/Object;ILkotlin/jvm/internal/DefaultConstructorMarker;)V - public final fun component1 ()Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind; + public fun (Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind;Ljava/lang/Object;Ljava/time/Duration;Ljava/time/Duration;Ljava/lang/Runnable;)V + public final fun component1 ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind; public final fun component2 ()Ljava/lang/Object; public final fun component3 ()Ljava/time/Duration; public final fun component4 ()Ljava/time/Duration; public final fun component5 ()Ljava/lang/Runnable; - public final fun component6 ()Ljava/lang/Object; - public final fun copy (Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind;Ljava/lang/Object;Ljava/time/Duration;Ljava/time/Duration;Ljava/lang/Runnable;Ljava/lang/Object;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest; - public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest;Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind;Ljava/lang/Object;Ljava/time/Duration;Ljava/time/Duration;Ljava/lang/Runnable;Ljava/lang/Object;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest; + public final fun copy (Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind;Ljava/lang/Object;Ljava/time/Duration;Ljava/time/Duration;Ljava/lang/Runnable;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest; + public static synthetic fun copy$default (Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest;Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind;Ljava/lang/Object;Ljava/time/Duration;Ljava/time/Duration;Ljava/lang/Runnable;ILjava/lang/Object;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest; public fun equals (Ljava/lang/Object;)Z public final fun getCallback ()Ljava/lang/Runnable; public final fun getDelay ()Ljava/time/Duration; - public final fun getExecutionKind ()Lorg/pnfolder/pnlibrary/api/tasks/TaskExecution$Kind; + public final fun getExecutionKind ()Lorg/pnfolder/pnlibrary/api/tasks/spec/TaskExecution$Kind; public final fun getInterval ()Ljava/time/Duration; - public final fun getOwner ()Ljava/lang/Object; public final fun getTarget ()Ljava/lang/Object; public fun hashCode ()I public fun toString ()Ljava/lang/String; @@ -328,13 +371,14 @@ public abstract interface class org/pnfolder/pnlibrary/spi/tasks/RetirableCallba public abstract class org/pnfolder/pnlibrary/spi/tasks/TrackingPlatformTaskAdapter : org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapter { public fun ()V + protected fun beforeSchedule (Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest;)V + public final fun buildTask ()Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskBuilder; public final fun close ()V - public final fun schedule (Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskHandle; protected abstract fun scheduleNative (Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskHandle; } public final class org/pnfolder/pnlibrary/spi/tasks/UnsupportedPlatformTaskAdapter : org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapter { public static final field INSTANCE Lorg/pnfolder/pnlibrary/spi/tasks/UnsupportedPlatformTaskAdapter; - public fun schedule (Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskRequest;)Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskHandle; + public fun buildTask ()Lorg/pnfolder/pnlibrary/spi/tasks/PlatformTaskBuilder; } diff --git a/modules/runtime-spi/build.gradle.kts b/modules/spi/build.gradle.kts similarity index 95% rename from modules/runtime-spi/build.gradle.kts rename to modules/spi/build.gradle.kts index d503acd91..05a24b595 100644 --- a/modules/runtime-spi/build.gradle.kts +++ b/modules/spi/build.gradle.kts @@ -3,7 +3,7 @@ plugins { `java-library` } -base { archivesName = "${rootProject.property("pnlibrary.name")}-runtime-spi" } +base { archivesName = "${rootProject.property("pnlibrary.name")}-spi" } dependencies { api(project(":modules:api")) diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/audiences/PlatformAudienceAdapter.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/audiences/PlatformAudienceAdapter.kt similarity index 96% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/audiences/PlatformAudienceAdapter.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/audiences/PlatformAudienceAdapter.kt index 1ee0fae4a..5a56090f4 100644 --- a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/audiences/PlatformAudienceAdapter.kt +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/audiences/PlatformAudienceAdapter.kt @@ -4,7 +4,7 @@ import net.kyori.adventure.sound.Sound import net.kyori.adventure.text.Component import org.pnfolder.pnlibrary.api.audiences.AudienceSender import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer import java.util.UUID /** Native audience lookup boundary implemented by each platform runtime. */ diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/NativeCommandAdapter.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/GenericPlatformCommandAdapter.kt similarity index 89% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/NativeCommandAdapter.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/GenericPlatformCommandAdapter.kt index a9f28bb21..24975349f 100644 --- a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/NativeCommandAdapter.kt +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/GenericPlatformCommandAdapter.kt @@ -1,7 +1,7 @@ package org.pnfolder.pnlibrary.spi.commands import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition import java.util.concurrent.CompletionStage /** Native source-specific registration boundary shared by every platform runtime. */ @@ -21,8 +21,10 @@ interface NativeCommandRegistrar { /** Connects one native source type to the shared portable command dispatcher. */ abstract class GenericPlatformCommandAdapter : TrackingPlatformCommandAdapter() { + /** Native registration bridge of the platform. */ protected abstract val registrar: NativeCommandRegistrar + /** Builds the portable command context for one native invocation. */ protected abstract fun context( source: S, alias: String, diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/PlatformCommandAdapter.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/PlatformCommandAdapter.kt similarity index 95% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/PlatformCommandAdapter.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/PlatformCommandAdapter.kt index ad648ff7b..be0af6906 100644 --- a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/PlatformCommandAdapter.kt +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/PlatformCommandAdapter.kt @@ -1,7 +1,7 @@ package org.pnfolder.pnlibrary.spi.commands import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition import java.util.concurrent.CompletionStage /** Native command registration boundary implemented by each platform runtime. */ diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapter.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapter.kt similarity index 89% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapter.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapter.kt index b7c0c18a2..8787b0041 100644 --- a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapter.kt +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapter.kt @@ -1,6 +1,6 @@ package org.pnfolder.pnlibrary.spi.commands -import org.pnfolder.pnlibrary.api.commands.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition import java.util.LinkedHashSet import java.util.concurrent.atomic.AtomicBoolean @@ -9,6 +9,7 @@ abstract class TrackingPlatformCommandAdapter : PlatformCommandAdapter { private val closed = AtomicBoolean(false) private val registrations = LinkedHashSet() + /** Registers [command] natively so that native calls reach [dispatcher]. */ protected abstract fun registerNative( owner: Any, command: CommandDefinition, @@ -35,7 +36,7 @@ abstract class TrackingPlatformCommandAdapter : PlatformCommandAdapter { try { registration.close() } catch (error: Throwable) { - if (failure == null) failure = error + failure?.addSuppressed(error) ?: run { failure = error } } } synchronized(registrations) { registrations.clear() } diff --git a/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/libraries/ExternalLibraries.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/libraries/ExternalLibraries.kt new file mode 100644 index 000000000..1d2fe6faa --- /dev/null +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/libraries/ExternalLibraries.kt @@ -0,0 +1,46 @@ +package org.pnfolder.pnlibrary.spi.libraries + +/** + * Loads a library a module asked for through the platform's Libby loader, which this module cannot depend on: the loader + * is plain Java in the same JAR, so it is called by name, like [OptionalLibrary] does. + */ +object ExternalLibraries { + /** + * Downloads and loads one library and returns the class loader that holds it, or `null` when it joined pnLibrary's own + * loader (`isolated` false). + * + * @throws IllegalStateException with the reason when it cannot be loaded + */ + fun load( + classLoader: ClassLoader, + owner: String, + group: String, + artifact: String, + version: String, + classifier: String?, + sha256: String?, + url: String?, + repositories: List, + isolated: Boolean, + plugin: Any? = null, + ): ClassLoader? = try { + Class.forName("org.pnfolder.pnlibrary.loader.LibraryLoader", true, classLoader) + .getMethod( + "loadExternal", String::class.java, String::class.java, String::class.java, String::class.java, String::class.java, + String::class.java, String::class.java, Array::class.java, Boolean::class.javaPrimitiveType, Any::class.java, + ) + .invoke(null, owner, group, artifact, version, classifier, sha256, url, repositories.toTypedArray(), isolated, plugin) as ClassLoader? + } catch (failure: java.lang.reflect.InvocationTargetException) { + throw IllegalStateException(failure.targetException.message ?: "Library cannot be loaded", failure.targetException) + } catch (_: ReflectiveOperationException) { + throw IllegalStateException("The library loader is not available on this server") + } + + /** The jar file of a library this loader has loaded, as a path, or `null` when it is not known (never loaded, or no loader). */ + fun fileOf(classLoader: ClassLoader, coordinates: String): String? = try { + Class.forName("org.pnfolder.pnlibrary.loader.LibraryLoader", true, classLoader) + .getMethod("fileOf", String::class.java).invoke(null, coordinates) as String? + } catch (_: ReflectiveOperationException) { + null + } +} diff --git a/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/libraries/OptionalLibrary.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/libraries/OptionalLibrary.kt new file mode 100644 index 000000000..63ab77807 --- /dev/null +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/libraries/OptionalLibrary.kt @@ -0,0 +1,30 @@ +package org.pnfolder.pnlibrary.spi.libraries + +/** + * A library pnLibrary does not pack and downloads through Libby only when something needs it, such as a database + * driver or the policy compiler. Nothing is loaded for features a server never uses. + * + * @property id group name known to the loader: `mysql`, `mongo` or `compiler` + * @property probe a class of the library, used to tell whether it is already visible + */ +class OptionalLibrary(private val id: String, private val probe: String, private val classLoader: ClassLoader) { + /** Whether the library can be used now, loading it first when it is missing. Never throws; false means it is unavailable. */ + fun ensure(): Boolean = present() || (loadThroughLoader() && present()) + + private fun present(): Boolean = try { + Class.forName(probe, false, classLoader) + true + } catch (_: ClassNotFoundException) { + false + } catch (_: LinkageError) { + false + } + + // The loader is plain Java in the same JAR and runs before Kotlin exists, so this module cannot depend on it. + private fun loadThroughLoader(): Boolean = try { + Class.forName("org.pnfolder.pnlibrary.loader.LibraryLoader", true, classLoader) + .getMethod("loadOptional", String::class.java).invoke(null, id) as Boolean + } catch (_: ReflectiveOperationException) { + false + } +} diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/metrics/PlatformMetricsFactory.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/metrics/PlatformMetricsFactory.kt similarity index 91% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/metrics/PlatformMetricsFactory.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/metrics/PlatformMetricsFactory.kt index 26079a9f9..51ac0b6de 100644 --- a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/metrics/PlatformMetricsFactory.kt +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/metrics/PlatformMetricsFactory.kt @@ -1,9 +1,9 @@ package org.pnfolder.pnlibrary.spi.metrics -import org.pnfolder.pnlibrary.api.metrics.ErrorReporter -import org.pnfolder.pnlibrary.api.metrics.MetricsProvider -import org.pnfolder.pnlibrary.api.metrics.MetricsProviderConfiguration import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.api.metrics.error.ErrorReporter +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProvider +import org.pnfolder.pnlibrary.api.metrics.provider.MetricsProviderConfiguration import java.util.function.Supplier /** diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticDetailsCollector.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticDetailsCollector.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticDetailsCollector.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticDetailsCollector.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticSections.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticSections.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticSections.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticSections.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/JulLogObserver.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/JulLogObserver.kt similarity index 84% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/JulLogObserver.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/JulLogObserver.kt index 264e19aa2..63770f26a 100644 --- a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/JulLogObserver.kt +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/JulLogObserver.kt @@ -19,7 +19,7 @@ class JulLogObserver( private val fallbackOwner: Any, private val resolveOwner: (loggerName: String?) -> Any?, ) { - private val ownLogCall = ThreadLocal.withInitial { false } + private val ownLogs = OwnLogScope() @Volatile private var observer: ((Any, LogLevel, String, Throwable?) -> Unit)? = null @@ -27,7 +27,7 @@ class JulLogObserver( private val handler = object : Handler() { override fun publish(record: LogRecord?) { - if (record == null || ownLogCall.get()) return + if (record == null || ownLogs.isActive) return if (record.level.intValue() < Level.WARNING.intValue()) return val level = if (record.level.intValue() >= Level.SEVERE.intValue()) LogLevel.ERROR else LogLevel.WARNING val owner = resolveOwner(record.loggerName) ?: fallbackOwner @@ -51,24 +51,11 @@ class JulLogObserver( } /** Runs [block] while records produced by this thread are treated as the library's own. */ - fun runOwn(block: () -> T): T { - val previous = ownLogCall.get() - ownLogCall.set(true) - try { - return block() - } finally { - ownLogCall.set(previous) - } - } + fun runOwn(block: () -> T): T = ownLogs.run(block) - /** - * Platform log handler that writes each record to the logger [loggerFor] picks for its owner, at the - * matching [julLevel], without the record coming back as an observation. - */ + /** Platform log handler that writes each record to the logger [loggerFor] picks for its owner at the matching [julLevel]. */ fun logHandler(loggerFor: (owner: Any) -> Logger): (Any, LogLevel, String, Throwable?) -> Unit = - { owner, level, message, error -> - runOwn { loggerFor(owner).log(julLevel(level), message, error) } - } + { owner, level, message, error -> loggerFor(owner).log(julLevel(level), message, error) } /** Level mapping for `java.util.logging`. */ companion object { diff --git a/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/OwnLogScope.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/OwnLogScope.kt new file mode 100644 index 000000000..8650a896b --- /dev/null +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/OwnLogScope.kt @@ -0,0 +1,24 @@ +package org.pnfolder.pnlibrary.spi.platform + +/** + * Marks the log records the library writes itself, so a log observer does not report them back. + * + * The mark belongs to the calling thread and nests: a record is own while any [run] on its thread is active. + */ +class OwnLogScope { + private val active = ThreadLocal.withInitial { false } + + /** Whether the current thread is inside [run]. */ + val isActive: Boolean get() = active.get() + + /** Runs [block] while records produced by this thread are treated as the library's own. */ + fun run(block: () -> T): T { + val previous = active.get() + active.set(true) + try { + return block() + } finally { + active.set(previous) + } + } +} diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformAdapter.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformAdapter.kt similarity index 92% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformAdapter.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformAdapter.kt index ede3e2d64..d65800114 100644 --- a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformAdapter.kt +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformAdapter.kt @@ -1,5 +1,6 @@ package org.pnfolder.pnlibrary.spi.platform +import org.pnfolder.pnlibrary.api.network.NetworkProxy import org.pnfolder.pnlibrary.spi.audiences.PlatformAudienceAdapter import org.pnfolder.pnlibrary.spi.audiences.UnsupportedPlatformAudienceAdapter import org.pnfolder.pnlibrary.spi.commands.PlatformCommandAdapter @@ -32,4 +33,6 @@ interface PlatformAdapter : PlatformShutdown, PlatformIdentity, PlatformExecutio val audienceAdapter: PlatformAudienceAdapter get() = UnsupportedPlatformAudienceAdapter /** Native task scheduling; unsupported by default. */ val taskAdapter: PlatformTaskAdapter get() = UnsupportedPlatformTaskAdapter + /** Proxy layer; null on game-server platforms. */ + val networkProxy: NetworkProxy? get() = null } diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformBinding.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformBinding.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformBinding.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformBinding.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformDiagnosticReport.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformDiagnosticReport.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformDiagnosticReport.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformDiagnosticReport.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformDiagnostics.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformDiagnostics.kt similarity index 74% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformDiagnostics.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformDiagnostics.kt index d9785220b..b66987444 100644 --- a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformDiagnostics.kt +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformDiagnostics.kt @@ -1,6 +1,6 @@ package org.pnfolder.pnlibrary.spi.platform -/** Diagnostic snapshots and native log observation supplied by a platform. */ +/** Diagnostic snapshots supplied by a platform. */ interface PlatformDiagnostics : PlatformSnapshotProvider, PlatformDiagnosticReport { override fun diagnosticDetails(includeSensitive: Boolean): Map = snapshot().asMap() } diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformExecution.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformExecution.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformExecution.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformExecution.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformIdentity.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformIdentity.kt similarity index 90% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformIdentity.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformIdentity.kt index d042fada6..df0c024c1 100644 --- a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformIdentity.kt +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformIdentity.kt @@ -13,6 +13,8 @@ interface PlatformIdentity { val isProxy: Boolean get() = type.isProxy /** Whether the platform is a game server such as Bukkit. */ val isServer: Boolean get() = type.isServer + /** Minecraft version of the game server such as `1.21.4`; null on a proxy or when it cannot be read. */ + val minecraftVersion: String? get() = null /** Stable suffix used by the installed distribution artifact. */ val artifactId: String get() = when (type) { diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLifecycle.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLifecycle.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLifecycle.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLifecycle.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLogObservation.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLogObservation.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLogObservation.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLogObservation.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLogging.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLogging.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLogging.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLogging.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformOwnerControl.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformOwnerControl.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformOwnerControl.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformOwnerControl.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformOwnerMetadata.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformOwnerMetadata.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformOwnerMetadata.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformOwnerMetadata.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformOwnership.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformOwnership.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformOwnership.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformOwnership.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPluginInventory.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPluginInventory.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPluginInventory.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPluginInventory.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPlugins.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPlugins.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPlugins.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPlugins.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPnLogger.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPnLogger.kt similarity index 75% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPnLogger.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPnLogger.kt index 48aa74645..4b6c670c1 100644 --- a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPnLogger.kt +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPnLogger.kt @@ -6,14 +6,13 @@ import org.pnfolder.pnlibrary.api.logging.PnLogger /** * A [PnLogger] for runtime parts that hold a [PlatformLogging] instead of a plugin logger. Lines carry the [name] * and go where [logging] sends them; when it is the library's recording sink, that is the black box too. + * Context keys are not forwarded since [PlatformLogging] does not carry structured fields. */ class PlatformPnLogger( private val logging: PlatformLogging, private val owner: Any, private val name: String, ) : PnLogger { - override fun log(level: LogLevel, message: String, error: Throwable?, record: Boolean) { - val line = "[$name] $message" - if (record) logging.log(owner, level, line, error) else logging.console(owner, line) - } + override fun log(level: LogLevel, message: String, error: Throwable?, context: Map) = + logging.log(owner, level, "[$name] $message", error) } diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformReadiness.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformReadiness.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformReadiness.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformReadiness.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformShutdown.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformShutdown.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformShutdown.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformShutdown.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformSnapshot.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformSnapshot.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformSnapshot.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformSnapshot.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformSnapshotProvider.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformSnapshotProvider.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformSnapshotProvider.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformSnapshotProvider.kt diff --git a/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/ProxyPlatformAdapter.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/ProxyPlatformAdapter.kt new file mode 100644 index 000000000..790af2e5f --- /dev/null +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/ProxyPlatformAdapter.kt @@ -0,0 +1,55 @@ +package org.pnfolder.pnlibrary.spi.platform + +import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.api.network.NetworkProxy + +/** + * Shared lifecycle of the proxy adapters: startup gate, native log observation, replies and shutdown. + * + * Startup-dependent callbacks wait for [markReady], called by the plugin entry point after runtime creation and + * native API registration. Proxies have no per-player scheduler, so replies run as global work. + * + * @param owner identifies the uncaught-exception observer + */ +abstract class ProxyPlatformAdapter(owner: Any) : PlatformAdapter { + + abstract override val networkProxy: NetworkProxy + + /** Logs a warning through this adapter's log handler. */ + fun warn(message: String) = logHandler(this, LogLevel.WARNING, message, null) + + /** Registrations and shutdown state of this adapter. */ + protected val lifecycle = PlatformLifecycle() + private val startup = StartupGate(lifecycle, ::executeGlobal) + private val uncaughtExceptionObserver = UncaughtExceptionLogObserver(owner) + + /** Starts or stops forwarding the proxy's own and its plugins' log records to [observer]. */ + protected abstract fun observeProxyLogs(observer: ((Any, LogLevel, String, Throwable?) -> Unit)?) + + /** Forwards proxy and plugin warnings/errors and uncaught JVM exceptions, preserving the previous handler. */ + @Synchronized + override fun observeNativeLogs(observer: ((Any, LogLevel, String, Throwable?) -> Unit)?) { + if (observer != null) lifecycle.checkOpen() + observeProxyLogs(observer) + uncaughtExceptionObserver.observe(observer) + } + + /** Defers startup-dependent work until the entry point has published the runtime and native platform API. */ + override fun whenServerReady(task: Runnable) { + startup.whenReady(task) + } + + /** Releases startup callbacks once; other managed plugins may still use the startup grace. */ + fun markReady() { + startup.markReady() + } + + override fun executeReply(recipient: Any, task: Runnable) { + executeGlobal(task) + } + + /** Discards pending startup work, cancels native tasks and stops native log observation once. */ + override fun close() { + lifecycle.closeAdapter(startup, taskAdapter) { observeNativeLogs(null) } + } +} diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/StartupGate.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/StartupGate.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/StartupGate.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/StartupGate.kt diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/UncaughtExceptionLogObserver.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/UncaughtExceptionLogObserver.kt similarity index 100% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/UncaughtExceptionLogObserver.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/platform/UncaughtExceptionLogObserver.kt diff --git a/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapter.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapter.kt new file mode 100644 index 000000000..11a575e3c --- /dev/null +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapter.kt @@ -0,0 +1,107 @@ +package org.pnfolder.pnlibrary.spi.tasks + +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import java.time.Duration + +/** Native cancellation handle returned by a platform scheduler. */ +fun interface PlatformTaskHandle { + /** Cancels future execution and reports whether cancellation changed state. */ + fun cancel(): Boolean +} + +/** + * Native scheduling request produced by [PlatformTaskBuilder]. + * + * @property executionKind requested platform execution context + * @property target native entity target for entity execution + * @property delay delay before the first invocation + * @property interval repeat interval, or `null` for one-shot execution + * @property callback callback dispatched by the platform scheduler + */ +data class PlatformTaskRequest( + val executionKind: TaskExecution.Kind, + val target: Any?, + val delay: Duration, + val interval: Duration?, + val callback: Runnable, +) { + init { + require(executionKind != TaskExecution.Kind.ENTITY || target != null) { "Entity task target is required" } + require(!delay.isNegative) { "Task delay must not be negative" } + interval?.let { require(!it.isNegative && !it.isZero) { "Task interval must be positive" } } + } +} + +/** + * Fluent description of a task, started with [PlatformTaskAdapter.buildTask]. + * + * Unless changed the task is global, starts immediately and runs once: + * ``` + * adapter.buildTask() + * .task(callback) + * .delay(Duration.ofSeconds(5)) + * .every(Duration.ofSeconds(30)) + * .schedule() + * ``` + * + * @param dispatch hands the finished request to the platform scheduler + */ +class PlatformTaskBuilder(private val dispatch: (PlatformTaskRequest) -> PlatformTaskHandle) { + private var callback: Runnable? = null + private var kind = TaskExecution.Kind.GLOBAL + private var target: Any? = null + private var delay = Duration.ZERO + private var interval: Duration? = null + + /** Sets the [callback] the task runs; required. */ + fun task(callback: Runnable) = apply { this.callback = callback } + + /** Runs the task in the execution context of the entity [target]. */ + fun entity(target: Any) = execution(TaskExecution.Kind.ENTITY, target) + + /** Runs the task in the given execution [kind], bound to [target] when the kind needs one. */ + fun execution(kind: TaskExecution.Kind, target: Any? = null) = apply { + this.kind = kind + this.target = target + } + + /** Waits [delay] before the first run. */ + fun delay(delay: Duration) = apply { this.delay = delay } + + /** Repeats the task every [interval]. */ + fun every(interval: Duration) = apply { this.interval = interval } + + /** Copies every setting from an already built [request]. */ + fun from(request: PlatformTaskRequest) = apply { + callback = request.callback + kind = request.executionKind + target = request.target + delay = request.delay + interval = request.interval + } + + /** Builds the request without scheduling it. */ + fun build() = PlatformTaskRequest( + kind, target, delay, interval, checkNotNull(callback) { "Task callback is not set" }, + ) + + /** Schedules the task and returns its native cancellation handle. */ + fun schedule(): PlatformTaskHandle = dispatch(build()) +} + +/** Native scheduling boundary implemented by each platform runtime. */ +interface PlatformTaskAdapter : AutoCloseable { + /** Starts describing a task; finish with [PlatformTaskBuilder.schedule]. */ + fun buildTask(): PlatformTaskBuilder + + /** Releases platform scheduler resources. */ + override fun close() = Unit +} + +/** Adapter used by runtimes that do not provide native task scheduling. */ +object UnsupportedPlatformTaskAdapter : PlatformTaskAdapter { + /** Returns a builder whose [PlatformTaskBuilder.schedule] always fails. */ + override fun buildTask() = PlatformTaskBuilder { + throw UnsupportedOperationException("Native task scheduling is not supported by this platform") + } +} diff --git a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/tasks/TrackingPlatformTaskAdapter.kt b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/tasks/TrackingPlatformTaskAdapter.kt similarity index 84% rename from modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/tasks/TrackingPlatformTaskAdapter.kt rename to modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/tasks/TrackingPlatformTaskAdapter.kt index ef2403bfd..691914b8d 100644 --- a/modules/runtime-spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/tasks/TrackingPlatformTaskAdapter.kt +++ b/modules/spi/src/main/kotlin/org/pnfolder/pnlibrary/spi/tasks/TrackingPlatformTaskAdapter.kt @@ -14,10 +14,17 @@ abstract class TrackingPlatformTaskAdapter : PlatformTaskAdapter { private val closed = AtomicBoolean(false) private val handles = ConcurrentHashMap.newKeySet() + /** Hands [request] to the native scheduler and returns its handle. */ protected abstract fun scheduleNative(request: PlatformTaskRequest): PlatformTaskHandle - final override fun schedule(request: PlatformTaskRequest): PlatformTaskHandle { + /** Called for every request after the closed check and before it is scheduled; the default does nothing. */ + protected open fun beforeSchedule(request: PlatformTaskRequest) = Unit + + final override fun buildTask() = PlatformTaskBuilder(::track) + + private fun track(request: PlatformTaskRequest): PlatformTaskHandle { check(!closed.get()) { "Platform task adapter is closed" } + beforeSchedule(request) val reference = AtomicReference() val completed = AtomicBoolean(false) val forwarded = request.copy(callback = object : Runnable, RetirableCallback { @@ -51,7 +58,7 @@ abstract class TrackingPlatformTaskAdapter : PlatformTaskAdapter { try { handle.cancel() } catch (error: Throwable) { - if (failure == null) failure = error + failure?.addSuppressed(error) ?: run { failure = error } } } handles.clear() diff --git a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapterTest.kt b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapterTest.kt similarity index 62% rename from modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapterTest.kt rename to modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapterTest.kt index 6b5035c84..8f9060270 100644 --- a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapterTest.kt +++ b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/commands/TrackingPlatformCommandAdapterTest.kt @@ -3,7 +3,9 @@ package org.pnfolder.pnlibrary.spi.commands import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.completedExecution +import org.pnfolder.pnlibrary.api.commands.definition.completedSuggestions import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.TimeUnit @@ -46,15 +48,32 @@ class TrackingPlatformCommandAdapterTest { } } + @Test + fun `close throws the first failure and keeps the others as suppressed`() { + val adapter = object : TrackingPlatformCommandAdapter() { + override fun registerNative( + owner: Any, + command: CommandDefinition, + dispatcher: PlatformCommandDispatcher, + ) = PlatformCommandRegistration { error("close failed for ${command.name}") } + } + adapter.register(Any(), CommandDefinition.builder("first").build(), dispatcher()) + adapter.register(Any(), CommandDefinition.builder("second").build(), dispatcher()) + + val thrown = org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException::class.java) { adapter.close() } + + assertEquals(1, thrown.suppressed.size) + } + private fun dispatcher() = object : PlatformCommandDispatcher { override fun execute( command: CommandDefinition, context: CommandContext, - ) = org.pnfolder.pnlibrary.api.commands.completedExecution() + ) = org.pnfolder.pnlibrary.api.commands.definition.completedExecution() override fun suggest( command: CommandDefinition, context: CommandContext, - ) = org.pnfolder.pnlibrary.api.commands.completedSuggestions(emptyList()) + ) = org.pnfolder.pnlibrary.api.commands.definition.completedSuggestions(emptyList()) } } diff --git a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticDetailsCollectorTest.kt b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticDetailsCollectorTest.kt similarity index 100% rename from modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticDetailsCollectorTest.kt rename to modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticDetailsCollectorTest.kt diff --git a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticSectionsTest.kt b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticSectionsTest.kt similarity index 100% rename from modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticSectionsTest.kt rename to modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/DiagnosticSectionsTest.kt diff --git a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/JulLogObserverTest.kt b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/JulLogObserverTest.kt similarity index 97% rename from modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/JulLogObserverTest.kt rename to modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/JulLogObserverTest.kt index 55e417630..402b7d4f6 100644 --- a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/JulLogObserverTest.kt +++ b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/JulLogObserverTest.kt @@ -2,7 +2,6 @@ package org.pnfolder.pnlibrary.spi.platform import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull -import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.logging.LogLevel import java.util.UUID @@ -76,7 +75,7 @@ class JulLogObserverTest { } @Test - fun `log handler writes to the owner logger at the mapped level without observing it back`() { + fun `log handler writes to the owner logger at the mapped level and forwards to the observer`() { start() val records = mutableListOf() val ownerLogger = Logger.getLogger(platform.name + ".owner").apply { @@ -96,6 +95,6 @@ class JulLogObserverTest { assertEquals(listOf(Level.SEVERE, Level.WARNING, Level.INFO), records.map { it.level }) assertEquals(failure, records[0].thrown) - assertTrue(seen.isEmpty()) + assertEquals(listOf("failed", "careful"), seen.map { it.message }) } } diff --git a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformAdapterLoggingTest.kt b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformAdapterLoggingTest.kt similarity index 100% rename from modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformAdapterLoggingTest.kt rename to modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformAdapterLoggingTest.kt diff --git a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLifecycleTest.kt b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLifecycleTest.kt similarity index 94% rename from modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLifecycleTest.kt rename to modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLifecycleTest.kt index ca61511a5..e274347c9 100644 --- a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLifecycleTest.kt +++ b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformLifecycleTest.kt @@ -6,6 +6,7 @@ import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskAdapter +import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskBuilder import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskHandle import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest import java.util.concurrent.CopyOnWriteArrayList @@ -163,7 +164,8 @@ class PlatformLifecycleTest { val steps = CopyOnWriteArrayList() val startup = StartupGate(lifecycle) { steps += "startup task ran" } val tasks = object : PlatformTaskAdapter { - override fun schedule(request: PlatformTaskRequest) = PlatformTaskHandle { true } + override fun buildTask() = PlatformTaskBuilder(::dispatch) + private fun dispatch(request: PlatformTaskRequest) = PlatformTaskHandle { true } override fun close() { steps += "tasks" } } lifecycle.track(AutoCloseable { steps += "registration" }) @@ -182,7 +184,8 @@ class PlatformLifecycleTest { var observing = true val failure = IllegalStateException("cancel failed") val tasks = object : PlatformTaskAdapter { - override fun schedule(request: PlatformTaskRequest) = PlatformTaskHandle { true } + override fun buildTask() = PlatformTaskBuilder(::dispatch) + private fun dispatch(request: PlatformTaskRequest) = PlatformTaskHandle { true } override fun close() = throw failure } diff --git a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPluginsTest.kt b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPluginsTest.kt similarity index 100% rename from modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPluginsTest.kt rename to modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/PlatformPluginsTest.kt diff --git a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/StartupGateTest.kt b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/StartupGateTest.kt similarity index 100% rename from modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/StartupGateTest.kt rename to modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/StartupGateTest.kt diff --git a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/UncaughtExceptionLogObserverTest.kt b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/UncaughtExceptionLogObserverTest.kt similarity index 100% rename from modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/UncaughtExceptionLogObserverTest.kt rename to modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/platform/UncaughtExceptionLogObserverTest.kt diff --git a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapterTest.kt b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapterTest.kt similarity index 86% rename from modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapterTest.kt rename to modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapterTest.kt index e97dc83c5..f38715b99 100644 --- a/modules/runtime-spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapterTest.kt +++ b/modules/spi/src/test/kotlin/org/pnfolder/pnlibrary/spi/tasks/PlatformTaskAdapterTest.kt @@ -3,7 +3,7 @@ package org.pnfolder.pnlibrary.spi.tasks import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.tasks.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import java.time.Duration import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors @@ -20,9 +20,9 @@ class PlatformTaskAdapterTest { @Test fun `unsupported adapter rejects registration`() { assertThrows(UnsupportedOperationException::class.java) { - UnsupportedPlatformTaskAdapter.schedule( + UnsupportedPlatformTaskAdapter.buildTask().from( PlatformTaskRequest(TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, Runnable {}), - ) + ).schedule() } } @@ -42,7 +42,7 @@ class PlatformTaskAdapterTest { try { val future = executor.submit { - adapter.schedule(PlatformTaskRequest(TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, Runnable {})) + adapter.buildTask().from(PlatformTaskRequest(TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, Runnable {})).schedule() } check(entered.await(2, TimeUnit.SECONDS)) adapter.close() diff --git a/modules/updates/build.gradle.kts b/modules/updates/build.gradle.kts index 933b98c4f..1aafe379d 100644 --- a/modules/updates/build.gradle.kts +++ b/modules/updates/build.gradle.kts @@ -74,18 +74,21 @@ tasks.register("verifyUpdaterProcess") { dependencies { implementation(project(":modules:api")) - implementation(project(":modules:runtime-spi")) + implementation(project(":modules:spi")) implementation(project(":modules:features:config-runtime")) implementation(project(":modules:common")) implementation(libs.kotlin.stdlib) implementation(libs.gson) implementation(libs.snakeyaml) + // Loaded through Libby the first time a MongoDB backup needs it; never packed. + compileOnly(libs.mongodb.driver.sync) implementation(libs.adventure.minimessage) implementation(libs.adventure.legacy) implementation(libs.adventure.gson) implementation(libs.adventure.plain) implementation(project(":modules:console")) + testImplementation(libs.mongodb.driver.sync) testImplementation(libs.junit.jupiter) testImplementation(libs.mockito.core) testRuntimeOnly(libs.junit.launcher) @@ -93,7 +96,8 @@ dependencies { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates( groupId = "io.github.pnfolder", diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateChannelLabels.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateChannelLabels.kt deleted file mode 100644 index 4d6448576..000000000 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateChannelLabels.kt +++ /dev/null @@ -1,43 +0,0 @@ -package org.pnfolder.pnlibrary.core.updates.catalog - -import net.kyori.adventure.text.format.TextColor -import org.pnfolder.pnlibrary.api.chat.ChatPalette -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import java.util.Locale - -/** The words and colors of update channels, shared by the chat catalog and every console card. */ -object UpdateChannelLabels { - /** The channel as it is typed in commands and shown in tags: `stable`, `rc`, `beta`. */ - @JvmStatic - fun channelName(channel: UpdateChannel): String = channel.name.lowercase(Locale.ROOT) - - /** Channels are colored by risk, from green for stable to red for development builds. */ - @JvmStatic - fun channelColor(channel: UpdateChannel): TextColor = when (channel) { - UpdateChannel.STABLE -> ChatPalette.OK - UpdateChannel.RC -> ChatPalette.INFO - UpdateChannel.BETA -> ChatPalette.WARN - UpdateChannel.ALPHA -> ChatPalette.ORANGE - UpdateChannel.DEV -> ChatPalette.DANGER - } - - /** What a server on this channel receives. */ - @JvmStatic - fun channelHint(channel: UpdateChannel): String = when (channel) { - UpdateChannel.STABLE -> "Только стабильные релизы" - UpdateChannel.RC -> "Кандидаты в релиз и стабильные" - UpdateChannel.BETA -> "Бета-версии и стабильные" - UpdateChannel.ALPHA -> "Экспериментальные alpha-версии: возможны ошибки" - UpdateChannel.DEV -> "Все сборки, включая разрабатываемые: только для тестового сервера" - } - - /** The channel in a sentence, such as `тестовый канал Beta`. */ - @JvmStatic - fun channelTitle(channel: UpdateChannel): String = when (channel) { - UpdateChannel.STABLE -> "стабильный канал" - UpdateChannel.RC -> "канал RC" - UpdateChannel.BETA -> "тестовый канал Beta" - UpdateChannel.ALPHA -> "экспериментальный канал Alpha" - UpdateChannel.DEV -> "разрабатываемый канал Dev" - } -} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalogSelector.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalogSelector.kt deleted file mode 100644 index 5666976a6..000000000 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalogSelector.kt +++ /dev/null @@ -1,29 +0,0 @@ -package org.pnfolder.pnlibrary.core.updates.engine - -import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.api.updates.UpdateChannel - -/** Deterministically selects the newest catalog release compatible with a runtime. */ -internal object ReleaseCatalogSelector { - /** Selects the newest channel, platform, Java, and API-compatible release. */ - fun select( - catalog: ReleaseCatalog, - acceptedChannel: UpdateChannel, - platform: PlatformType, - javaFeature: Int, - apiVersion: Int, - ): CatalogRelease? = catalog.releases - .asSequence() - .filter { acceptedChannel.accepts(it.channel) } - .filter { it.api.supports(apiVersion) } - .filter { it.artifacts.any { artifact -> artifact.matchesPlatform(platform) && artifact.supports(javaFeature) } } - .sortedByDescending { it.version } - .firstOrNull() - - private fun CatalogArtifact.supports(javaFeature: Int): Boolean = - javaFeature >= javaMinimum && (javaMaximum == null || javaFeature <= javaMaximum) -} - -/** Whether this artifact runs on [target]: an exact platform match, or one built for every platform. */ -internal fun CatalogArtifact.matchesPlatform(target: PlatformType): Boolean = - platform == target || platform == PlatformType.UNIVERSAL diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdateInstaller.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdateInstaller.kt deleted file mode 100644 index 62ee26e53..000000000 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdateInstaller.kt +++ /dev/null @@ -1,178 +0,0 @@ -package org.pnfolder.pnlibrary.core.updates.install - -import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState -import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup -import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackupComponent -import org.pnfolder.pnlibrary.api.updates.backup.UpdateConfigurationBackup -import org.pnfolder.pnlibrary.api.updates.release.ProductChange -import org.pnfolder.pnlibrary.api.updates.release.UpdatePlan -import org.pnfolder.pnlibrary.api.version.SemanticVersion -import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.updates.engine.ArtifactVerifier -import org.pnfolder.pnlibrary.core.updates.engine.TransactionJournal -import org.pnfolder.pnlibrary.core.updates.engine.TrustedHttpClient -import org.pnfolder.pnlibrary.core.updates.engine.UpdateProcessSession -import org.pnfolder.pnlibrary.core.updates.engine.UpdateTransaction -import org.pnfolder.pnlibrary.core.updates.history.ConfigurationSnapshots -import org.pnfolder.pnlibrary.core.updates.policy.UpdateConfiguration -import org.pnfolder.pnlibrary.core.updates.service.RegisteredUpdate -import org.pnfolder.pnlibrary.core.updates.service.UpdateHealthReport -import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity -import java.nio.file.Path -import java.time.Instant -import java.util.UUID - -/** Stages update files and verifies a staged transaction after the next server start. */ -internal class UpdateInstaller( - platform: PlatformIdentity, - dataFolder: Path, - private val configuration: UpdateConfiguration, - http: TrustedHttpClient, -) { - private val configurations = ConfigurationSnapshots(dataFolder.resolve("updates/configurations"), dataFolder.parent) - private val libraryConfiguration = UpdateConfigurationBackup(dataFolder, listOf("updates.yml")) - private val transaction = UpdateTransaction( - dataFolder.resolve("updates/transactions"), - ArtifactVerifier(configuration.downloads.maxArtifactBytes), - dataFolder.parent, - ) - private val stager = UpdatePlanStager( - platform = platform.type, - dataFolder = dataFolder, - http = http, - transaction = transaction, - maximumArtifactBytes = configuration.downloads.maxArtifactBytes, - requireSha256 = configuration.installation.requireSha256, - ) - - fun recoverInterruptedTransactions() { - transaction.recoverAll() - } - - fun stage(snapshot: UpdatePlanSnapshot, registrations: List) { - require(transaction.awaitingHealth().isEmpty() && - transaction.awaitingRollbackHealth().isEmpty()) { "A prepared change is still awaiting restart verification" } - require(transaction.pendingInstallations().isEmpty()) { "A prepared rollback must be applied before preparing another update" } - val plan = requireNotNull(snapshot.plan) { "Update plan has no installable target" } - verifyPluginDownloadsAllowed(plan) - - val targets = registrations.associate { registration -> - registration.descriptor.id to InstalledUpdateTarget( - currentJar = registration.jar, - updateDirectory = registration.updateDirectory, - supportedApi = registration.descriptor.supportedApi, - ) - } - val changed = plan.changes.map { it.product }.toSet() - val selections = registrations.filter { it.descriptor.id in changed }.mapNotNull { registration -> - val selection = registration.request.configurationBackup - ?: libraryConfiguration.takeIf { registration.product == PnLibraryIdentity.PRODUCT_ID } - selection?.let { registration.descriptor.id to it } - }.toMap() - val configurationSnapshot = configurations.capture(snapshot.id, selections) - stager.stage(snapshot.id, plan, targets, configurationSnapshot) - } - - fun backups(): List = transaction.rollbackCandidates().map { path -> - val journal = TransactionJournal.load(path) - UpdateBackup(UUID.fromString(journal.id), journal.createdAt?.let(Instant::parse), journal.planId?.let(UUID::fromString), - journal.artifacts.map { UpdateBackupComponent(ProductId.of(it.component), it.expectedVersion, it.previousVersion) }, - journal.configurationSnapshot?.let { id -> runCatchingNonFatal { configurations.read(UUID.fromString(id)).files.size }.getOrDefault(0) } ?: 0) - } - - fun rollbackLatest(): UpdatePlanSnapshot { - val candidate = transaction.latestRollbackCandidate() - ?: error("Нет сохранённого набора JAR для отката") - return rollback(UUID.fromString(TransactionJournal.load(candidate).id)) - } - - fun rollback(id: UUID, restoreConfigurations: Boolean = false): UpdatePlanSnapshot { - require(transaction.awaitingHealth().isEmpty() && - transaction.awaitingRollbackHealth().isEmpty()) { "A prepared change is still awaiting restart verification" } - require(transaction.pendingInstallations().isEmpty()) { "Another rollback is already prepared for restart" } - val candidate = transaction.rollbackCandidate(id) - val journal = TransactionJournal.load(candidate) - if (restoreConfigurations) { - val saved = requireNotNull(journal.configurationSnapshot) { "У этого набора нет снимка конфигураций" } - require(configurations.read(UUID.fromString(saved)).planId == journal.planId) { "Configuration snapshot belongs to another plan" } - } - // Legacy backups may lack version information. Never invent a version from the current plan. - val changes = journal.artifacts.mapNotNull { artifact -> - val updated = artifact.expectedVersion?.let(SemanticVersion::tryParse) - val previous = artifact.previousVersion?.let(SemanticVersion::tryParse) - if (previous == null || updated == null) null else ProductChange(ProductId.of(artifact.component), previous, updated) - } - val snapshot = UpdatePlanSnapshot(journal.planId?.let(UUID::fromString) ?: id, 0, UpdateState.ROLLED_BACK, - journal.targetApi?.let { UpdatePlan(it, changes, emptyList()) }, emptyList(), - "Резервный набор $id подготовлен к следующему перезапуску" + - "${if (restoreConfigurations) " с восстановлением конфигураций" else " без изменения конфигураций"}.") - transaction.rollback(candidate, restoreConfigurations) - return snapshot - } - - fun reconcilePending( - registrations: List, - reportHealth: (UpdateHealthReport) -> Unit, - ) = reconcileVersions(registrations.associate { it.product to it.version }, reportHealth) - - internal fun reconcileVersions(installedVersions: Map, reportHealth: (UpdateHealthReport) -> Unit, recoveredFailuresOnly: Boolean = false) { - val recovered = transaction.failedHealthChecks().filter { pending -> - pending.unknownProducts.isEmpty() && pending.expectedVersions.all { (product, expected) -> installedVersions[product] == expected } - } - val pendingChecks = ((if (recoveredFailuresOnly) emptyList() else transaction.awaitingHealth() + transaction.awaitingRollbackHealth()) + recovered) - .filter { it.preparedSession != UpdateProcessSession.id } - .map { it to transaction.readJournal(it.journal) } - .sortedBy { it.second.createdAt?.let(Instant::parse) ?: Instant.MIN } - pendingChecks.forEach { (pending, source) -> - val mismatches = pending.expectedVersions.filter { (product, expected) -> - installedVersions[product] != expected - } - val healthy = mismatches.isEmpty() && pending.unknownProducts.isEmpty() - val details = mismatches.entries.map { (product, expected) -> - "$product: ожидалась $expected, загружена ${installedVersions[product] ?: "не загружена"}" - } + pending.unknownProducts.map { "$it: ожидаемая версия не записана в старом журнале" } - val changes = source.artifacts.mapNotNull { artifact -> - val previous = artifact.previousVersion?.let(SemanticVersion::tryParse) - val updated = artifact.expectedVersion?.let(SemanticVersion::tryParse) - when { - pending.rollback && previous != null && updated != null -> ProductChange(ProductId.of(artifact.component), updated, previous) - !pending.rollback && updated != null && (previous != null || !artifact.targetExisted) -> ProductChange(ProductId.of(artifact.component), - previous, updated) - else -> null - } - } - val outcome = if (healthy) "Подтверждены загруженные версии: ${pending.expectedVersions.entries.joinToString { "${it.key}=${it.value}" }}" - else "Версии после перезапуска не подтвердились: ${details.joinToString()}" - val id = UUID.fromString(source.id) - reportHealth(UpdateHealthReport(id, source.planId?.let(UUID::fromString) ?: id, changes, healthy, pending.rollback, "Набор $id. $outcome")) - if (pending.rollback) transaction.completeRollbackHealth(pending.journal, healthy) - else transaction.completeHealth(pending.journal, healthy) - } - } - - fun reconcileRecoveredFailures(registrations: List, reportHealth: (UpdateHealthReport) -> Unit) = - reconcileVersions(registrations.associate { it.product to it.version }, reportHealth, recoveredFailuresOnly = true) - - fun automaticUpdatesHealthy(products: Set): Boolean = transaction.awaitingHealth().isEmpty() && - transaction.awaitingRollbackHealth().isEmpty() && transaction.automaticUpdatesHealthy(products.map { it.value }.toSet()) - - fun awaitingRegistrations(registrations: List): Boolean { - val installed = registrations.map { it.product }.toSet() - return (transaction.awaitingHealth() + transaction.awaitingRollbackHealth()) - .filter { it.preparedSession != UpdateProcessSession.id } - .any { pending -> (pending.expectedVersions.keys + pending.unknownProducts).any { it !in installed } } - } - - private fun verifyPluginDownloadsAllowed(plan: UpdatePlan) { - plan.changes - .filterNot { change -> change.product.value == PnLibraryIdentity.PRODUCT_ID } - .forEach { change -> - require(change.product.value !in configuration.ignoredPlugins) { - "Загрузка плагина ${change.product} отключена политикой обновлений" - } - } - } -} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateConfiguration.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateConfiguration.kt deleted file mode 100644 index bb56f47d4..000000000 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateConfiguration.kt +++ /dev/null @@ -1,72 +0,0 @@ -package org.pnfolder.pnlibrary.core.updates.policy - -import org.pnfolder.pnlibrary.api.config.ConfigProblem -import org.pnfolder.pnlibrary.api.config.ConfigValueValidator -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.config.LibraryConfigFiles -import java.nio.file.Path -import java.time.Duration -import java.util.Locale -import java.util.function.Supplier - -/** - * Update policy: the few choices in `updates.yml` plus the fixed rules of [UpdateDefaults]. - * - * Per-plugin channel, automatic download and temporary pause are chosen with commands and kept in - * `updates/`; the file lists automatic downloads, new plugins and plugins that must never be updated ([ignoredPlugins]). - */ -internal data class UpdateConfiguration( - val checks: Checks = Checks(), - val notifications: Notifications = Notifications(), - val downloads: Downloads = Downloads(), - val installation: Installation = Installation(), - val library: LibraryPolicy = LibraryPolicy(), - val pluginAutomaticDownload: Boolean = false, - val ignoredPlugins: Set = emptySet(), -) { - data class LibraryPolicy( - val channel: UpdateChannel = UpdateChannel.DEV, - val automaticDownload: Boolean = false, - ) - data class Checks(val interval: Duration = UpdateDefaults.CHECK_INTERVAL) - data class Notifications(val repeatInterval: Duration = UpdateDefaults.NOTIFICATION_REPEAT) - data class Downloads( - val allowManagedPlugins: Boolean = UpdateDefaults.ALLOW_MANAGED_PLUGINS, - val connectTimeout: Duration = UpdateDefaults.CONNECT_TIMEOUT, - val readTimeout: Duration = UpdateDefaults.READ_TIMEOUT, - val maxArtifactBytes: Long = UpdateDefaults.MAX_ARTIFACT_BYTES, - ) - data class Installation( - val allowNewPlugins: Boolean = false, - val requireSha256: Boolean = UpdateDefaults.REQUIRE_SHA256, - ) - - /** Whether any component may be downloaded without a command. */ - val effectiveAutomaticDownloads get() = library.automaticDownload || pluginAutomaticDownload - - companion object { - private val VALIDATOR = ConfigValueValidator { settings -> - settings.plugins.ignored - .filterNot { UpdateSettings.PLUGIN_ID.matches(it.trim().lowercase(Locale.ROOT)) } - .map { ConfigProblem("plugins.ignored", "недопустимый идентификатор плагина: $it") } - } - - /** - * Reads the policy from [file], creating the file with defaults when it is missing. - * - * An unreadable file never grants more rights: conservative defaults are used and [warning] says why. - */ - fun load(file: Path, warning: (String) -> Unit = {}): UpdateConfiguration = try { - LibraryConfigFiles.load( - file = file, - type = UpdateSettings::class.java, - defaults = Supplier { UpdateSettings() }, - validator = VALIDATOR, - warning = warning, - ).toConfiguration() - } catch (error: Exception) { - warning("updates.yml не прочитан, используются безопасные значения по умолчанию: ${error.message}") - UpdateConfiguration() - } - } -} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateDefaults.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateDefaults.kt deleted file mode 100644 index ca6daa465..000000000 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateDefaults.kt +++ /dev/null @@ -1,32 +0,0 @@ -package org.pnfolder.pnlibrary.core.updates.policy - -import java.time.Duration - -/** - * Fixed update rules that administrators cannot change in `updates.yml`. - * - * Checks and warnings are never switched off by a file: an administrator pauses one plugin with a command - * (`hold`), which always expires. Every number the update system relies on lives here, so it is found in one place. - */ -object UpdateDefaults { - /** How often the release catalogs are asked for new versions; the first check runs at startup. */ - val CHECK_INTERVAL: Duration = Duration.ofHours(6) - - /** How long the same console message about an update is not repeated. */ - val NOTIFICATION_REPEAT: Duration = Duration.ofHours(6) - - /** How long to wait for a connection while downloading an update file. */ - val CONNECT_TIMEOUT: Duration = Duration.ofSeconds(10) - - /** How long to wait for data from a silent server while downloading an update file. */ - val READ_TIMEOUT: Duration = Duration.ofSeconds(30) - - /** The largest single update file accepted. */ - const val MAX_ARTIFACT_BYTES: Long = 512L * 1024 * 1024 - - /** Every downloaded file must carry a SHA-256 checksum. */ - const val REQUIRE_SHA256: Boolean = true - - /** Plugins already managed by pnLibrary may be updated when installation is allowed. */ - const val ALLOW_MANAGED_PLUGINS: Boolean = true -} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdatePolicyOverrides.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdatePolicyOverrides.kt deleted file mode 100644 index 7175f98b3..000000000 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdatePolicyOverrides.kt +++ /dev/null @@ -1,84 +0,0 @@ -package org.pnfolder.pnlibrary.core.updates.policy - -import com.google.gson.GsonBuilder -import com.google.gson.JsonObject -import com.google.gson.JsonParser -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.common.io.AtomicFiles -import org.pnfolder.pnlibrary.common.io.TextFiles -import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import java.nio.charset.StandardCharsets.UTF_8 -import java.nio.file.Files -import java.nio.file.Path - -/** - * Per-component channel and automatic-download choices made at runtime, for example from `/pn updates settings`. - * - * `updates.yml` is hand-edited and commented, so it is never rewritten. Choices made through commands are kept - * here instead and take precedence over `updates.yml` until they are changed again. - */ -internal class UpdatePolicyOverrides( - private val file: Path, - private val warning: (String) -> Unit = {}, -) { - private data class State(val channels: Map, val automatic: Map) - - private val gson = GsonBuilder().setPrettyPrinting().create() - - @Volatile - private var state = load() - - /** The channel chosen for [product] at runtime, or null when `updates.yml` decides. */ - fun channel(product: String): UpdateChannel? = state.channels[product] - - /** The automatic-download choice for [product] at runtime, or null when `updates.yml` decides. */ - fun automatic(product: String): Boolean? = state.automatic[product] - - /** Whether any component was switched to automatic download at runtime. */ - fun anyAutomaticEnabled(): Boolean = state.automatic.values.any { it } - - /** Remembers [channel] for [product], or forgets the choice when [channel] is null. */ - @Synchronized - fun setChannel(product: String, channel: UpdateChannel?) { - state = state.copy(channels = if (channel == null) state.channels - product else state.channels + (product to channel)) - save() - } - - @Synchronized - fun setAutomatic(product: String, enabled: Boolean) { - state = state.copy(automatic = state.automatic + (product to enabled)) - save() - } - - private fun load(): State { - if (!Files.isRegularFile(file)) return State(emptyMap(), emptyMap()) - return try { - val root = JsonParser.parseString(TextFiles.read(file, UTF_8)).asJsonObject - State( - channels = root.getAsJsonObject("channels")?.entrySet().orEmpty().mapNotNull { (product, value) -> - runCatchingNonFatal { UpdateChannel.valueOf(value.asString) }.getOrNull()?.let { product to it } - }.toMap(), - automatic = root.getAsJsonObject("automatic")?.entrySet().orEmpty() - .associate { (product, value) -> product to value.asBoolean }, - ) - } catch (error: Exception) { - warning("Unreadable update settings ${file.fileName}: ${error.javaClass.simpleName}") - State(emptyMap(), emptyMap()) - } - } - - private fun save() { - Files.createDirectories(file.parent) - val json = JsonObject().apply { - add("channels", JsonObject().also { node -> state.channels.toSortedMap().forEach { (p, c) -> node.addProperty(p, c.name) } }) - add("automatic", JsonObject().also { node -> state.automatic.toSortedMap().forEach { (p, a) -> node.addProperty(p, a) } }) - } - val temporary = Files.createTempFile(file.parent, ".settings-", ".tmp") - try { - TextFiles.write(temporary, gson.toJson(json), UTF_8) - AtomicFiles.move(temporary, file) - } finally { - Files.deleteIfExists(temporary) - } - } -} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateSettings.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateSettings.kt deleted file mode 100644 index dac3b71b3..000000000 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateSettings.kt +++ /dev/null @@ -1,83 +0,0 @@ -package org.pnfolder.pnlibrary.core.updates.policy - -import org.pnfolder.pnlibrary.api.config.ConfigComment -import org.pnfolder.pnlibrary.api.config.ConfigDefaultOnInvalid -import org.pnfolder.pnlibrary.api.config.ConfigNewLine -import org.pnfolder.pnlibrary.api.config.ConfigPattern -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import java.util.Locale - -/** Content of `plugins/pnLibrary/updates.yml`: what pnLibrary downloads and installs on its own. */ -@ConfigComment( - "pnLibrary: обновления (updates.yml)", - "", - "Проверки, уведомления и защита файлов работают всегда и отключаются только командой на время (hold).", - "Канал, автозагрузку и паузу конкретного плагина меняют командами:", - " set <плагин> channel <канал>, set <плагин> auto , set <плагин> hold <период>.", -) -/** - * Configuration section with the few update choices an administrator makes in a file. - */ -internal class UpdateSettings { - @field:ConfigNewLine - @field:ConfigComment("=== Сама pnLibrary ===") - var library: Library = Library() - - @field:ConfigNewLine - @field:ConfigComment("=== Плагины, которые обновляет pnLibrary ===") - var plugins: Plugins = Plugins() - - @field:ConfigNewLine - @field:ConfigComment("=== Установка ===") - var installation: Installation = Installation() - - /** Update policy of pnLibrary itself. */ - class Library { - @field:ConfigComment("Канал релизов pnLibrary сейчас фиксирован (dev) и это значение не применяется.") - @field:ConfigPattern(CHANNEL_PATTERN) - var channel: String = "dev" - - @field:ConfigDefaultOnInvalid - @field:ConfigComment("Скачивать новую версию pnLibrary автоматически.") - var automaticDownload: Boolean = false - } - - /** Update policy shared by the plugins registered in pnLibrary. */ - class Plugins { - @field:ConfigDefaultOnInvalid - @field:ConfigComment("Скачивать обновления плагинов автоматически.") - var automaticDownload: Boolean = false - - @field:ConfigComment( - "Плагины, которые pnLibrary не обновляет никогда (их идентификаторы). Например: [pncases].", - "Остальные плагины обновляются по правилам выше.", - ) - var ignored: List = emptyList() - } - - /** Safety rules of installation. */ - class Installation { - @field:ConfigDefaultOnInvalid - @field:ConfigComment("Разрешить устанавливать плагины, которых на сервере ещё нет.") - var allowNewPlugins: Boolean = false - } - - /** Converts the file model to the immutable runtime policy. */ - fun toConfiguration(): UpdateConfiguration = UpdateConfiguration( - installation = UpdateConfiguration.Installation(allowNewPlugins = installation.allowNewPlugins), - library = UpdateConfiguration.LibraryPolicy( - // pnLibrary has only dev releases so far; library.channel takes effect once a stable one exists. - channel = UpdateChannel.DEV, - automaticDownload = library.automaticDownload, - ), - pluginAutomaticDownload = plugins.automaticDownload, - ignoredPlugins = plugins.ignored.map { it.trim().lowercase(Locale.ROOT) }.toSet(), - ) - - companion object { - /** Accepted plugin identifier in `plugins.ignored`. */ - val PLUGIN_ID = Regex("[a-z0-9][a-z0-9_.-]*") - - private const val CHANNEL_PATTERN = "(?i)stable|rc|beta|alpha|dev" - } -} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateServiceImpl.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateServiceImpl.kt deleted file mode 100644 index f3da16355..000000000 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateServiceImpl.kt +++ /dev/null @@ -1,289 +0,0 @@ -package org.pnfolder.pnlibrary.core.updates.service - -import org.pnfolder.pnlibrary.api.dependencies.PluginDependency -import org.pnfolder.pnlibrary.api.logging.LogLevel -import org.pnfolder.pnlibrary.api.updates.PluginUpdateRequest -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateRegistration -import org.pnfolder.pnlibrary.api.updates.UpdateService -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup -import org.pnfolder.pnlibrary.api.updates.backup.UpdateHistoryEntry -import org.pnfolder.pnlibrary.api.version.SemanticVersion -import org.pnfolder.pnlibrary.common.jvm.JavaRuntime -import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.console.ConsoleTheme -import org.pnfolder.pnlibrary.core.updates.catalog.UpdateAnnouncementRenderer -import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCommandWords -import org.pnfolder.pnlibrary.core.updates.engine.FreezeStore -import org.pnfolder.pnlibrary.core.updates.engine.RefreshMode -import org.pnfolder.pnlibrary.core.updates.engine.ResolutionResult -import org.pnfolder.pnlibrary.core.updates.install.UpdateGraphResolver -import org.pnfolder.pnlibrary.core.updates.install.UpdateInstaller -import org.pnfolder.pnlibrary.core.updates.policy.UpdateAutomaticPolicy -import org.pnfolder.pnlibrary.core.updates.policy.UpdateConfiguration -import org.pnfolder.pnlibrary.core.updates.policy.UpdatePolicyOverrides -import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity -import org.pnfolder.pnlibrary.spi.platform.PlatformLogging -import org.pnfolder.pnlibrary.spi.platform.PlatformOwnerMetadata -import org.pnfolder.pnlibrary.spi.platform.PlatformPluginInventory -import org.pnfolder.pnlibrary.spi.platform.PlatformReadiness -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths -import java.time.Duration -import java.time.Instant -import java.time.format.DateTimeFormatter -import java.util.Collections -import java.util.Locale -import java.util.Optional -import java.util.UUID -import java.util.concurrent.CompletableFuture -import java.util.concurrent.CompletionStage -import java.util.concurrent.atomic.AtomicBoolean - -/** One catalog → resolver → verifier → transaction pipeline for every component. */ -class UpdateServiceImpl( - private val logging: PlatformLogging, - private val ownership: PlatformOwnerMetadata, - private val inventory: PlatformPluginInventory, - private val identity: PlatformIdentity, - private val readiness: PlatformReadiness, - private val dataFolder: Path, - private val consoleTheme: ConsoleTheme, -) : UpdateService, AutoCloseable { - private val closed = AtomicBoolean(false) - private val registrations = UpdateRegistrationStore() - private val configuration = UpdateConfiguration.load(dataFolder.resolve("updates.yml")) { - logging.log(this, LogLevel.WARNING, it) - } - // Keep a manual `/pn update` responsive even when GitHub is unreachable. - // The check can cover several registered products, so long per-request - // timeouts otherwise add up and look like a frozen command. - private val resources = UpdateRuntimeResources(dataFolder, configuration) - private val overrides = UpdatePolicyOverrides(dataFolder.resolve("updates/settings.json")) { - logging.log(this, LogLevel.WARNING, it) - } - private val automaticPolicy = UpdateAutomaticPolicy(configuration, overrides) { registrations.snapshot() } - private val installer = UpdateInstaller(identity, dataFolder, configuration, resources.downloadHttp) - private val freezes = FreezeStore(dataFolder.resolve("updates/freezes.json")) - private val graphResolver = UpdateGraphResolver(inventory, identity, configuration, resources.catalogGateway, freezes, overrides) - private val runtime = UpdateOrchestratorRuntime( - configuration = configuration, - dataFolder = dataFolder, - logging = logging, - readiness = readiness, - installer = installer, - registrations = registrations::snapshot, - resolveGraph = ::resolveGraph, - stageGraph = ::stageGraph, - announce = ::announce, - automaticAllowed = { snapshot -> - automaticPolicy.allows(snapshot) && installer.automaticUpdatesHealthy(registrations.snapshot().map { it.descriptor.id }.toSet()) - }, - automaticOverridesActive = { overrides.anyAutomaticEnabled() }, - ) - private val orchestrator get() = runtime.orchestrator - - /** Implements [UpdateService.register]. */ - override fun register( - owner: Any, - product: ProductDescriptor, - request: PluginUpdateRequest, - dependencies: List, - ): UpdateRegistration { - check(!closed.get()) { "Update service is closed" } - val info = ownership.ownerDetails(owner) - val nativeProductName = info["name"] ?: request.repositoryName - listOf(nativeProductName, request.repositoryName).firstOrNull(UpdateCommandWords::isReserved)?.let { word -> - throw IllegalArgumentException( - "A plugin cannot be called '$word' for updates: it is a word of the /pn update command " + - "(${UpdateCommandWords.RESERVED.joinToString()}). Rename the plugin or its repository.", - ) - } - val version = info["version"] ?: error("Cannot determine the version of the registering plugin") - require(SemanticVersion.tryParse(version) != null) { - "Version of $nativeProductName must be semantic: $version" - } - val jar = Paths.get(owner.javaClass.protectionDomain.codeSource.location.toURI()).toAbsolutePath().normalize() - require(Files.isRegularFile(jar)) { "Plugin must be loaded from a JAR file" } - val pluginsDirectory = pluginsDirectoryOf(jar) - request.configurationBackup?.let { backup -> - require(backup.root != pluginsDirectory && backup.root.toAbsolutePath().normalize().startsWith(pluginsDirectory)) { - "Configuration backup root must be a component data directory inside the plugins directory" - } - } - val artifact = request.artifactFor(JavaRuntime.feature, identity.type) - ?: error("No artifact of ${request.repositoryName} is registered for Java ${JavaRuntime.feature}") - require(product.version == SemanticVersion.parse(version)) { - "Product version ${product.version} does not match native plugin version $version" - } - val registration = RegisteredUpdate( - descriptor = product, - request = request, - artifact = artifact, - jar = jar, - updateDirectory = pluginsDirectory.resolve("update"), - selectedChannel = { graphResolver.channelFor(product.id, request.channel) }, - checkForUpdates = orchestrator::checkNow, - stagePlan = { snapshot -> orchestrator.stage(snapshot.id) }, - onClose = ::removeRegistration, - effectiveAutomatic = { - overrides.automatic(product.id.value) ?: request.automaticDownload - }, - ) - check(!closed.get()) { "Update service is closed" } - registrations.add(registration) - orchestrator.registrationsChanged() - return registration - } - - /** Implements [UpdateService.all]. */ - override fun all(): List = registrations.publicSnapshot() - /** Implements [UpdateService.get]. */ - override fun get(product: String): UpdateRegistration? = registrations.find(product) - /** Implements [UpdateService.checkNow]. */ - override fun checkNow(): CompletionStage = orchestrator.checkNow() - /** Implements [UpdateService.checkNow]. */ - override fun checkNow(actor: UpdateActor): CompletionStage = orchestrator.checkNow(actor = actor) - /** Implements [UpdateService.currentPlan]. */ - override fun currentPlan(): Optional = orchestrator.currentPlan() - /** Implements [UpdateService.stage]. */ - override fun stage(planId: UUID): CompletionStage = orchestrator.stage(planId) - /** Implements [UpdateService.stage]. */ - override fun stage(planId: UUID, actor: UpdateActor): CompletionStage = orchestrator.stage(planId, actor) - /** Implements [UpdateService.history]. */ - override fun history(): List = orchestrator.history() - /** Implements [UpdateService.historyPage]. */ - override fun historyPage(page: Int, product: String?): CompletionStage> = runtime.historyPage(page, product) - /** Implements [UpdateService.historyCount]. */ - override fun historyCount(product: String?): CompletionStage = runtime.historyCount(product) - /** Implements [UpdateService.setChannel]. */ - override fun setChannel(product: String, channel: UpdateChannel?, actor: UpdateActor): CompletionStage = - changeSetting(product, actor, recheck = true) { registration -> - val before = registration.snapshot.channel - val chosen = overrides.channel(registration.product) - when { - chosen == channel -> null - channel == null -> { - overrides.setChannel(registration.product, null) - val after = graphResolver.channelFor(registration) - "выбор канала снят: ${before.name.lowercase()} → ${after.name.lowercase()}, канал определяет плагин" - } - else -> { - overrides.setChannel(registration.product, channel) - "канал: ${before.name.lowercase()} → ${channel.name.lowercase()}" - } - } - } - - /** Implements [UpdateService.setAutomaticDownload]. */ - override fun setAutomaticDownload(product: String, enabled: Boolean, actor: UpdateActor): CompletionStage = - changeSetting(product, actor, recheck = false) { registration -> - val before = registration.snapshot.automaticDownload - if (before == enabled) null - else { - overrides.setAutomatic(registration.product, enabled) - "автозагрузка: ${if (before) "вкл" else "выкл"} → ${if (enabled) "вкл" else "выкл"}" - } - } - - /** Implements [UpdateService.setHeld]. */ - override fun setHeld(product: String, duration: Duration?, actor: UpdateActor): CompletionStage = - changeSetting(product, actor, recheck = true) { registration -> - val id = registration.descriptor.id - if (duration == null) { - if (freezes.clear(id)) "удержание обновлений снято" else null - } else { - val until = freezes.freeze(id, duration) - "обновления удержаны до ${HOLD_FORMAT.format(until.atZone(org.pnfolder.pnlibrary.common.time.DisplayZone.zone))}" - } - } - - /** Implements [UpdateService.heldUntil]. */ - override fun heldUntil(product: String): Instant? = - registrations.find(product)?.let { freezes.active()[it.descriptor.id] } - - /** Applies one administrator setting, records it with its author and refreshes what readers see. */ - private fun changeSetting( - product: String, - actor: UpdateActor, - recheck: Boolean, - change: (RegisteredUpdate) -> String?, - ): CompletionStage { - val result = CompletableFuture() - try { - check(!closed.get()) { "Update service is closed" } - val registration = registrations.find(product) - ?: throw IllegalArgumentException("Плагин $product не зарегистрирован в pnLibrary") - val description = change(registration) - registration.refreshPolicy() - if (description != null) { - runtime.recordSettingsChange(registration, description, actor) - // The setting is already persisted, so a failed recheck is reported but does not fail the change. - if (recheck) runCatchingNonFatal { orchestrator.checkNow(actor = actor) }.onFailure { error -> - logging.log(this, LogLevel.WARNING, "Update recheck after a settings change failed", error) - } - } - result.complete(registration.snapshot) - } catch (error: Exception) { - result.completeExceptionally(error) - } - return result - } - - /** Implements [UpdateService.backups]. */ - override fun backups(): CompletionStage> = runtime.readAsync { - Collections.unmodifiableList(installer.backups()) - } - /** Implements [UpdateService.rollback]. */ - override fun rollback(): CompletionStage = rollback(UpdateActor.UNKNOWN) - /** Implements [UpdateService.rollback]. */ - override fun rollback(actor: UpdateActor): CompletionStage = orchestrator.rollbackTo(actor) { - installer.rollbackLatest() - } - /** Implements [UpdateService.rollback]. */ - override fun rollback(transactionId: UUID, actor: UpdateActor): CompletionStage = - orchestrator.rollbackTo(actor, transactionId) { installer.rollback(transactionId) } - /** Implements [UpdateService.rollback]. */ - override fun rollback(transactionId: UUID, restoreConfigurations: Boolean, actor: UpdateActor): CompletionStage = - orchestrator.rollbackTo(actor, transactionId) { installer.rollback(transactionId, restoreConfigurations) } - /** Implements [UpdateService.close]. */ - override fun close() { - if (!closed.compareAndSet(false, true)) return - registrations.close() - runtime.close() - resources.close() - } - - private companion object { - val HOLD_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMM HH:mm", Locale("ru")) - const val PAPER_REMAPPED = ".paper-remapped" - - /** Paper runs remapped copies from `plugins/.paper-remapped`; data folders and `update` still sit in `plugins`. */ - fun pluginsDirectoryOf(jar: Path): Path { - val folder = jar.parent - return if (folder.fileName?.toString() == PAPER_REMAPPED) folder.parent else folder - } - } - - private fun resolveGraph(refreshMode: RefreshMode = RefreshMode.CACHED): ResolutionResult = - graphResolver.resolve(registrations.snapshot(), refreshMode) - - private fun stageGraph(snapshot: UpdatePlanSnapshot) { - installer.stage(snapshot, registrations.snapshot()) - } - - private fun announce(snapshot: UpdatePlanSnapshot) { - UpdateAnnouncementRenderer.render(snapshot, consoleTheme, registrations.snapshot().map { it.snapshot }) - .forEach { logging.console(this, it) } - } - - private fun removeRegistration(registration: RegisteredUpdate) { - registrations.remove(registration) - orchestrator.registrationsChanged() - } -} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseBackups.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseBackups.kt new file mode 100644 index 000000000..8f1ce4c87 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseBackups.kt @@ -0,0 +1,94 @@ +package org.pnfolder.pnlibrary.updates.databases + +import org.pnfolder.pnlibrary.api.config.DatabaseKind +import org.pnfolder.pnlibrary.api.updates.backup.BackupKind +import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackupItem +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.updates.databases.mongo.MongoEngine +import org.pnfolder.pnlibrary.updates.databases.mysql.MysqlEngine +import org.pnfolder.pnlibrary.updates.databases.postgres.PostgresEngine +import org.pnfolder.pnlibrary.updates.history.BackupStorage +import org.pnfolder.pnlibrary.updates.history.PrivateFiles +import java.net.URLDecoder +import java.net.URLEncoder +import java.nio.file.Files +import java.nio.file.Path +import java.time.Instant +import java.util.UUID +import java.util.stream.Collectors + +/** + * Copies the databases plugins marked with `@BackupDatabase` before an update and puts them back on request. + * Copies live in `///.db.gz`; before a restore the current state is copied too, so a + * restore can itself be undone. + */ +internal class DatabaseBackups( + private val folder: Path, + private val sources: DatabaseSources, + private val engines: Map = mapOf( + DatabaseKind.MYSQL to MysqlEngine(), + DatabaseKind.POSTGRESQL to PostgresEngine(), + DatabaseKind.MONGODB to MongoEngine(), + ), +) { + /** Copies every marked database of [plugins]. A failure stops the update: it would run without its safety copy. */ + fun copyBefore(plan: UUID, plugins: Collection) { + plugins.forEach { plugin -> + sources.of(plugin).forEach { source -> + val target = file(plan, plugin, source.name) + try { + PrivateFiles.directories(target.parent) + dump(source, target) + } catch (error: Exception) { + BackupStorage.delete(folder.resolve(plan.toString())) + throw IllegalStateException("Не удалось сохранить базу «${source.name}» плагина $plugin: ${error.message}", error) + } + } + } + } + + /** The databases saved for [plan], for the lists of backups. */ + fun items(plan: UUID): List { + val root = folder.resolve(plan.toString()) + if (!Files.isDirectory(root)) return emptyList() + return Files.walk(root, 2).use { paths -> + paths.filter { it.fileName.toString().endsWith(SUFFIX) && it.parent != root }.map { path -> + UpdateBackupItem(ProductId.of(path.parent.fileName.toString()), BackupKind.DATABASE, nameOf(path), Files.size(path)) + }.collect(Collectors.toList()) + } + } + + /** Replaces the tables of the database with the saved ones. The state it replaces is kept first. */ + fun restore(plan: UUID, plugin: String, name: String) { + val saved = file(plan, plugin, name) + require(Files.isRegularFile(saved)) { "Для набора $plan нет сохранённой базы «$name» плагина $plugin" } + val source = sources.of(plugin).firstOrNull { it.name == name } + ?: error("Плагин $plugin сейчас не описывает базу «$name»: она не отмечена @BackupDatabase или плагин не загружен") + val before = folder.resolve(plan.toString()).resolve(BEFORE_RESTORE).resolve(Instant.now().toEpochMilli().toString()) + .resolve(plugin).resolve(saved.fileName) + PrivateFiles.directories(before.parent) + dump(source, before) + val connection = DatabaseConnection.read(source) + engineOf(source).restore(connection, saved) + } + + private fun dump(source: DatabaseSource, target: Path) { + val connection = DatabaseConnection.read(source) + engineOf(source).dump(connection, connection.tables, target) + } + + private fun engineOf(source: DatabaseSource): DatabaseEngine = + engines[source.kind] ?: error("Базы ${source.kind} пока не поддерживаются") + + private fun file(plan: UUID, plugin: String, name: String): Path = + folder.resolve(plan.toString()).resolve(plugin).resolve(URLEncoder.encode(name, "UTF-8") + SUFFIX) + + private fun nameOf(path: Path): String = URLDecoder.decode(path.fileName.toString().removeSuffix(SUFFIX), "UTF-8") + + private companion object { + /** Ending of every copy file. */ + const val SUFFIX = ".db.gz" + /** Folder under a plan that holds the state replaced by a restore. */ + const val BEFORE_RESTORE = "before-restore" + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseConnection.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseConnection.kt new file mode 100644 index 000000000..c5b33684e --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseConnection.kt @@ -0,0 +1,79 @@ +package org.pnfolder.pnlibrary.updates.databases + +import org.pnfolder.pnlibrary.api.config.DatabaseKind +import org.pnfolder.pnlibrary.api.config.DatabaseRole +import org.pnfolder.pnlibrary.common.io.TextFiles +import org.yaml.snakeyaml.LoaderOptions +import org.yaml.snakeyaml.Yaml +import org.yaml.snakeyaml.constructor.SafeConstructor +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.Files + +/** + * How to reach a database, read from the plugin's own configuration file at the moment it is needed. + * @property host server address + * @property port server port + * @property database database name + * @property user login + * @property password password, never printed + * @property uri a full connection string, when the plugin keeps one; it replaces host, port, user and password + * @property tables the tables or collections to copy, empty for all + */ +class DatabaseConnection( + val host: String, + val port: Int, + val database: String, + val user: String, + val password: String, + val uri: String? = null, + val tables: List = emptyList(), +) { + /** The password is left out so a connection never reaches a log by accident. */ + override fun toString(): String = if (uri != null) "uri/$database" else "$user@$host:$port/$database" + + companion object { + /** Names tried for a field that carries no `@DatabaseField`. */ + private val USUAL = mapOf( + DatabaseRole.HOST to listOf("host", "hostname", "address"), + DatabaseRole.PORT to listOf("port"), + DatabaseRole.DATABASE to listOf("database", "db", "name"), + DatabaseRole.USER to listOf("user", "username"), + DatabaseRole.PASSWORD to listOf("password", "pass"), + DatabaseRole.URI to listOf("uri", "url", "connection-string"), + ) + + /** Reads the connection of [source] from its configuration file, applying the usual defaults for the port. */ + fun read(source: DatabaseSource): DatabaseConnection { + require(Files.isRegularFile(source.file)) { "Файл настроек ${source.file.fileName} не найден" } + var node: Any? = Yaml(SafeConstructor(LoaderOptions())).load(TextFiles.read(source.file, UTF_8)) + source.path.split('.').filter(String::isNotEmpty).forEach { node = (node as? Map<*, *>)?.get(it) } + val section = node as? Map<*, *> ?: error("В ${source.file.fileName} нет раздела «${source.path}» с подключением к базе") + + fun text(role: DatabaseRole): String? { + val keys = source.keys[role]?.let(::listOf) ?: USUAL.getValue(role) + return keys.firstNotNullOfOrNull { section[it]?.toString()?.takeIf(String::isNotBlank) } + } + val mongo = source.kind == DatabaseKind.MONGODB + val uri = if (mongo) text(DatabaseRole.URI) else null + val database = text(DatabaseRole.DATABASE) ?: missing(source, "database") + val tables = source.tables + source.tableKeys.mapNotNull { section[it]?.toString()?.takeIf(String::isNotBlank) } + check(tables.isNotEmpty() || source.tableKeys.isEmpty()) { "В поле @BackupTable базы «${source.name}» нет имени таблицы" } + if (uri != null) return DatabaseConnection("", 0, database, "", "", uri, tables) + return DatabaseConnection( + host = text(DatabaseRole.HOST) ?: missing(source, "host"), + port = text(DatabaseRole.PORT)?.toIntOrNull() ?: when (source.kind) { + DatabaseKind.MONGODB -> 27017 + DatabaseKind.POSTGRESQL -> 5432 + DatabaseKind.MYSQL -> 3306 + }, + database = database, + user = text(DatabaseRole.USER) ?: if (mongo) "" else missing(source, "user"), + password = text(DatabaseRole.PASSWORD) ?: "", + tables = tables, + ) + } + + private fun missing(source: DatabaseSource, part: String): Nothing = + error("Не нашёл «$part» для базы «${source.name}»: назовите поле так или пометьте его @DatabaseField") + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseEngine.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseEngine.kt new file mode 100644 index 000000000..29ca0bd79 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseEngine.kt @@ -0,0 +1,12 @@ +package org.pnfolder.pnlibrary.updates.databases + +import java.nio.file.Path + +/** Copies one kind of database into a file and reads such a file back. */ +internal interface DatabaseEngine { + /** [tables] limits the copy to those tables or collections; empty copies all. */ + fun dump(connection: DatabaseConnection, tables: List, target: Path) + + /** Replaces what the file names; the caller has already kept the current state. */ + fun restore(connection: DatabaseConnection, source: Path) +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseSources.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseSources.kt new file mode 100644 index 000000000..0881c13ae --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseSources.kt @@ -0,0 +1,54 @@ +package org.pnfolder.pnlibrary.updates.databases + +import org.pnfolder.pnlibrary.api.config.DatabaseKind +import org.pnfolder.pnlibrary.api.config.DatabaseRole +import org.pnfolder.pnlibrary.config.ManagedConfigFile +import java.nio.file.Path +import java.util.Locale +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArrayList + +/** + * A database a plugin marked with `@BackupDatabase`: whose it is, what it is called and where its connection is written. + * @property plugin lowercase id of the plugin that owns the database + * @property kind database engine + * @property name name given in `@BackupDatabase`, unique within the plugin + * @property file configuration file that holds the connection + * @property path dotted path of the connection section inside [file] + * @property keys field names that replace the usual ones, by role + * @property tables fixed tables or collections to copy, empty for all + * @property tableKeys configuration fields that hold a table name + */ +class DatabaseSource( + val plugin: String, + val kind: DatabaseKind, + val name: String, + val file: Path, + val path: String, + val keys: Map = emptyMap(), + val tables: List = emptyList(), + val tableKeys: List = emptyList(), +) + +/** The databases of all plugins, filled while plugins register their configuration files. */ +class DatabaseSources { + private val sources = ConcurrentHashMap>() + + /** Remembers the databases of [file]; closing the result forgets them again. */ + fun register(file: ManagedConfigFile): AutoCloseable? { + if (file.databases.isEmpty()) return null + val key = file.pluginId.value.lowercase(Locale.ROOT) + val path = file.directory.resolve(file.path) + val added = file.databases.map { DatabaseSource(key, it.kind, it.name, path, it.path, it.keys, it.tables, it.tableKeys) } + val list = sources.getOrPut(key) { CopyOnWriteArrayList() } + val names = (added.map { it.name } + list.map { it.name }) + require(names.distinct().size == names.size) { + "У плагина ${file.pluginId.value} две базы с одним именем: имя в @BackupDatabase должно быть разным" + } + list.addAll(added) + return AutoCloseable { sources[key]?.removeAll(added.toSet()) } + } + + /** The databases registered for [plugin], whatever its letter case. */ + fun of(plugin: String): List = sources[plugin.lowercase(Locale.ROOT)].orEmpty() +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/JdbcConnections.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/JdbcConnections.kt new file mode 100644 index 000000000..99281cf69 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/JdbcConnections.kt @@ -0,0 +1,46 @@ +package org.pnfolder.pnlibrary.updates.databases + +import org.pnfolder.pnlibrary.spi.libraries.OptionalLibrary +import java.sql.Connection +import java.sql.Driver +import java.util.Properties + +/** + * Opens JDBC connections with a driver that is downloaded on first use. + * @property libraryId the loader's name for the driver + * @property driverClass the driver's class, also used to tell whether it is already loaded + * @property scheme the start of the connection address, such as `jdbc:mariadb://` + * @property timeouts connect and socket timeouts in the unit the driver wants (MariaDB milliseconds, PostgreSQL seconds) + */ +internal class JdbcConnections( + private val libraryId: String, + private val driverClass: String, + private val scheme: String, + private val timeouts: Map, + private val library: OptionalLibrary = OptionalLibrary(libraryId, driverClass, JdbcConnections::class.java.classLoader), +) { + /** Loads the driver if needed and connects; the caller closes the connection. */ + fun open(connection: DatabaseConnection): Connection { + check(library.ensure()) { "Не удалось загрузить драйвер базы данных: проверьте доступ сервера в интернет и повторите" } + val properties = Properties().apply { + setProperty("user", connection.user) + setProperty("password", connection.password) + timeouts.forEach { (name, value) -> setProperty(name, value) } + } + val url = "$scheme${connection.host}:${connection.port}/${connection.database}" + val driver = Class.forName(driverClass, true, javaClass.classLoader).getDeclaredConstructor().newInstance() as Driver + return driver.connect(url, properties) ?: error("Драйвер не принял адрес $url") + } + + companion object { + /** MariaDB's driver, which also speaks to MySQL. */ + fun mysql() = JdbcConnections( + "mysql", "org.mariadb.jdbc.Driver", "jdbc:mariadb://", mapOf("connectTimeout" to "10000", "socketTimeout" to "600000"), + ) + + /** PostgreSQL's driver. */ + fun postgres() = JdbcConnections( + "postgres", "org.postgresql.Driver", "jdbc:postgresql://", mapOf("connectTimeout" to "10", "socketTimeout" to "600"), + ) + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/SqlRowWriter.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/SqlRowWriter.kt new file mode 100644 index 000000000..bd01520a5 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/SqlRowWriter.kt @@ -0,0 +1,60 @@ +package org.pnfolder.pnlibrary.updates.databases + +import org.pnfolder.pnlibrary.updates.history.PrivateFiles +import java.io.BufferedWriter +import java.io.OutputStreamWriter +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.Files +import java.nio.file.Path +import java.sql.ResultSet +import java.sql.Types +import java.util.zip.GZIPOutputStream + +/** Opens the compressed copy at [target], writes [header] as its first line and lets [body] write the statements. */ +internal fun writeDumpFile(target: Path, header: String, body: (BufferedWriter) -> Unit) { + BufferedWriter(OutputStreamWriter(GZIPOutputStream(PrivateFiles.output(target)), UTF_8)).use { out -> + out.write(header + "\n") + body(out) + } +} + +/** + * Writes result sets as multi-row `INSERT` statements, [ROWS_PER_INSERT] rows each, and fails once the copy at + * [target] grows past [maximumBytes]. Each dialect supplies how one column becomes an SQL [literal]. + */ +internal class SqlRowWriter( + private val out: BufferedWriter, + private val target: Path, + private val maximumBytes: Long, + private val literal: (ResultSet, Int) -> String, +) { + /** Writes every row of [rows]; [insertHead] is the statement up to and including the opening parenthesis. */ + fun write(rows: ResultSet, insertHead: String) { + val columns = rows.metaData.columnCount + var inBatch = 0 + while (rows.next()) { + out.write(if (inBatch == 0) insertHead else ",(") + for (column in 1..columns) { + if (column > 1) out.write(",") + out.write(literal(rows, column)) + } + out.write(")") + if (++inBatch == ROWS_PER_INSERT) { + out.write(";\n") + inBatch = 0 + out.flush() + check(Files.size(target) <= maximumBytes) { "Копия базы больше ${maximumBytes / (1024 * 1024)} МБ" } + } + } + if (inBatch > 0) out.write(";\n") + } + + companion object { + /** Rows the driver fetches at once while a table is read. */ + const val FETCH_ROWS = 1000 + private const val ROWS_PER_INSERT = 200 + + /** Column types written as binary literals. */ + val BINARY_TYPES = setOf(Types.BINARY, Types.VARBINARY, Types.LONGVARBINARY, Types.BLOB) + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/SqlScriptRestore.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/SqlScriptRestore.kt new file mode 100644 index 000000000..787cb049a --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/SqlScriptRestore.kt @@ -0,0 +1,52 @@ +package org.pnfolder.pnlibrary.updates.databases + +import java.io.BufferedReader +import java.io.InputStreamReader +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.Files +import java.nio.file.Path +import java.sql.Connection +import java.sql.Statement +import java.util.zip.GZIPInputStream + +/** + * Puts a copy of a SQL database back by running its statements, one per line: the tables the file names are + * dropped and created again with their rows. Tables the file does not mention stay as they are. + * @property header first line of a file this restore accepts + * @property setup statements run before the file, such as relaxing foreign key checks + * @property teardown statements run after the file, even when it fails + * @property atomic run the whole file in one transaction that is rolled back on failure; only for databases with + * transactional DDL (PostgreSQL), since MySQL commits implicitly at every `DROP TABLE` + */ +internal class SqlScriptRestore( + private val header: String, + private val setup: List = emptyList(), + private val teardown: List = emptyList(), + private val atomic: Boolean = false, +) { + /** Runs the statements of [source] on [connection]; [teardown] runs even when a statement fails. */ + fun read(connection: Connection, source: Path) { + connection.autoCommit = !atomic + connection.createStatement().use { statement -> + setup.forEach(statement::execute) + try { + run(connection, statement, source) + } finally { + teardown.forEach(statement::execute) + } + } + } + + private fun run(connection: Connection, statement: Statement, source: Path) { + try { + BufferedReader(InputStreamReader(GZIPInputStream(Files.newInputStream(source)), UTF_8)).use { reader -> + require(reader.readLine() == header) { "Это не копия базы pnLibrary для этого типа базы" } + generateSequence { reader.readLine() }.filter { it.isNotBlank() }.forEach { statement.execute(it) } + } + if (atomic) connection.commit() + } catch (error: Throwable) { + if (atomic) runCatching { connection.rollback() }.onFailure(error::addSuppressed) + throw error + } + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/TableMask.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/TableMask.kt new file mode 100644 index 000000000..1c20539f7 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/TableMask.kt @@ -0,0 +1,9 @@ +package org.pnfolder.pnlibrary.updates.databases + +/** Picks tables or collections by name: an empty list takes all of them, `*` in a name stands for any text (`log_*`). */ +internal object TableMask { + /** True when [name] is taken by [masks]. */ + fun matches(masks: List, name: String): Boolean = masks.isEmpty() || masks.any { mask -> + Regex(mask.split('*').joinToString(".*") { Regex.escape(it) }).matches(name) + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mongo/MongoDump.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mongo/MongoDump.kt new file mode 100644 index 000000000..395721569 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mongo/MongoDump.kt @@ -0,0 +1,53 @@ +package org.pnfolder.pnlibrary.updates.databases.mongo + +import com.mongodb.client.MongoClients +import org.bson.BsonDocument +import org.bson.json.JsonMode +import org.bson.json.JsonWriterSettings +import org.pnfolder.pnlibrary.updates.databases.TableMask +import org.pnfolder.pnlibrary.updates.history.PrivateFiles +import java.io.BufferedWriter +import java.io.OutputStreamWriter +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.Files +import java.nio.file.Path +import java.util.zip.GZIPOutputStream + +/** + * Writes every collection of a database into one compressed text file: a `#collection` line, its indexes as + * `#index` lines, then one document per line in extended JSON, which keeps every value's type. MongoDB gives no + * snapshot across collections, so a plugin that writes during the copy can leave collections a moment apart. + */ +internal class MongoDump(private val maximumBytes: Long = 2L * 1024 * 1024 * 1024) { + /** Writes the collections of [database] matching [only] (all when empty) to [target], failing past [maximumBytes]. */ + fun write(address: String, database: String, only: List, target: Path) { + val json = JsonWriterSettings.builder().outputMode(JsonMode.EXTENDED).build() + MongoClients.create(address).use { client -> + val db = client.getDatabase(database) + BufferedWriter(OutputStreamWriter(GZIPOutputStream(PrivateFiles.output(target)), UTF_8)).use { out -> + out.write(HEADER + "\n") + db.listCollectionNames().filterNot { it.startsWith("system.") || !TableMask.matches(only, it) }.forEach { name -> + require(name.none { it == '\n' || it == '\r' }) { "Имя коллекции с переводом строки не поддерживается" } + out.write("#collection $name\n") + val collection = db.getCollection(name, BsonDocument::class.java) + collection.listIndexes(BsonDocument::class.java).filterNot { it.getString("name").value == "_id_" } + .forEach { out.write("#index ${it.toJson(json)}\n") } + var written = 0 + collection.find().batchSize(BATCH).forEach { document -> + out.write(document.toJson(json) + "\n") + if (++written % BATCH == 0) { + out.flush() + check(Files.size(target) <= maximumBytes) { "Копия базы больше ${maximumBytes / (1024 * 1024)} МБ" } + } + } + } + } + } + } + + companion object { + /** First line of every copy; the restore refuses a file without it. */ + const val HEADER = "-- pnlibrary-mongo 1" + private const val BATCH = 1000 + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mongo/MongoEngine.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mongo/MongoEngine.kt new file mode 100644 index 000000000..75805aa16 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mongo/MongoEngine.kt @@ -0,0 +1,42 @@ +package org.pnfolder.pnlibrary.updates.databases.mongo + +import org.pnfolder.pnlibrary.spi.libraries.OptionalLibrary +import org.pnfolder.pnlibrary.updates.databases.DatabaseConnection +import org.pnfolder.pnlibrary.updates.databases.DatabaseEngine +import java.net.URLEncoder +import java.nio.file.Path + +/** + * MongoDB through its Java driver, which is loaded through Libby the first time it is needed. The driver's classes + * are touched only by [MongoDump] and [MongoRestore], which run after the load. + */ +internal class MongoEngine( + private val library: OptionalLibrary = OptionalLibrary("mongo", PROBE, MongoEngine::class.java.classLoader), +) : DatabaseEngine { + private fun ensureDriver() { + check(library.ensure()) { "Не удалось загрузить драйвер MongoDB: проверьте доступ сервера в интернет и повторите" } + } + + override fun dump(connection: DatabaseConnection, tables: List, target: Path) { + ensureDriver() + MongoDump().write(address(connection), connection.database, tables, target) + } + + override fun restore(connection: DatabaseConnection, source: Path) { + ensureDriver() + MongoRestore().read(address(connection), connection.database, source) + } + + private fun address(connection: DatabaseConnection): String { + connection.uri?.let { return it } + val login = if (connection.user.isEmpty()) "" else "${encode(connection.user)}:${encode(connection.password)}@" + return "mongodb://$login${connection.host}:${connection.port}/?authSource=${encode(connection.database)}" + } + + private fun encode(text: String) = URLEncoder.encode(text, "UTF-8") + + private companion object { + /** Class whose presence shows the MongoDB driver is loaded. */ + const val PROBE = "com.mongodb.client.MongoClients" + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mongo/MongoRestore.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mongo/MongoRestore.kt new file mode 100644 index 000000000..597be5e17 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mongo/MongoRestore.kt @@ -0,0 +1,112 @@ +package org.pnfolder.pnlibrary.updates.databases.mongo + +import com.mongodb.client.MongoClients +import com.mongodb.client.MongoCollection +import com.mongodb.client.MongoDatabase +import com.mongodb.client.model.Collation +import com.mongodb.client.model.CollationAlternate +import com.mongodb.client.model.CollationCaseFirst +import com.mongodb.client.model.CollationMaxVariable +import com.mongodb.client.model.CollationStrength +import com.mongodb.client.model.IndexOptions +import org.bson.BsonBoolean +import org.bson.BsonDocument +import java.io.BufferedReader +import java.io.InputStreamReader +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.Files +import java.nio.file.Path +import java.util.concurrent.TimeUnit +import java.util.zip.GZIPInputStream + +/** Puts a copy written by [MongoDump] back: collections named in the file are dropped and filled again, with their indexes. */ +internal class MongoRestore { + /** Reads [source] into [database]; only the collections the file names are touched. */ + fun read(address: String, database: String, source: Path) { + MongoClients.create(address).use { client -> + BufferedReader(InputStreamReader(GZIPInputStream(Files.newInputStream(source)), UTF_8)).use { reader -> + require(reader.readLine() == MongoDump.HEADER) { "Это не копия базы MongoDB от pnLibrary" } + val load = CollectionLoad(client.getDatabase(database)) + generateSequence { reader.readLine() }.filter { it.isNotBlank() }.forEach(load::line) + load.finish() + } + } + } + + /** The collection being filled: documents are inserted in batches and its indexes are built once it is full. */ + private class CollectionLoad(private val database: MongoDatabase) { + private var collection: MongoCollection? = null + private val indexes = mutableListOf() + private val batch = mutableListOf() + + fun line(line: String) { + when { + line.startsWith("#collection ") -> { + finish() + val name = line.removePrefix("#collection ") + database.getCollection(name).drop() + collection = database.getCollection(name, BsonDocument::class.java) + } + line.startsWith("#index ") -> indexes += BsonDocument.parse(line.removePrefix("#index ")) + else -> { + batch += BsonDocument.parse(line) + if (batch.size >= BATCH) flush() + } + } + } + + fun finish() { + flush() + collection?.let { target -> indexes.forEach { createIndex(target, it) } } + indexes.clear() + } + + private fun flush() { + if (batch.isEmpty()) return + collection?.insertMany(batch.toList()) + batch.clear() + } + + private fun createIndex(collection: MongoCollection, index: BsonDocument) { + collection.createIndex(index.getDocument("key"), indexOptions(index)) + } + } + + internal companion object { + private const val BATCH = 500 + + /** Index options written by [MongoDump]: name, uniqueness, TTL, partial filter and collation are kept. */ + fun indexOptions(index: BsonDocument): IndexOptions { + val options = IndexOptions().name(index.getString("name").value) + if (index.getBoolean("unique", BsonBoolean.FALSE).value) options.unique(true) + if (index.getBoolean("sparse", BsonBoolean.FALSE).value) options.sparse(true) + if (index.containsKey("expireAfterSeconds")) { + options.expireAfter(index.getNumber("expireAfterSeconds").longValue(), TimeUnit.SECONDS) + } + if (index.containsKey("partialFilterExpression")) { + options.partialFilterExpression(index.getDocument("partialFilterExpression")) + } + if (index.containsKey("collation")) options.collation(collationOf(index.getDocument("collation"))) + return options + } + + private fun collationOf(document: BsonDocument): Collation { + val builder = Collation.builder().locale(document.getString("locale").value) + document.optionalBoolean("caseLevel")?.let(builder::caseLevel) + document.optionalBoolean("numericOrdering")?.let(builder::numericOrdering) + document.optionalBoolean("backwards")?.let(builder::backwards) + document.optionalBoolean("normalization")?.let(builder::normalization) + document.optionalString("caseFirst")?.let { builder.collationCaseFirst(CollationCaseFirst.fromString(it)) } + document.optionalString("alternate")?.let { builder.collationAlternate(CollationAlternate.fromString(it)) } + document.optionalString("maxVariable")?.let { builder.collationMaxVariable(CollationMaxVariable.fromString(it)) } + if (document.isNumber("strength")) { + builder.collationStrength(CollationStrength.fromInt(document.getNumber("strength").intValue())) + } + return builder.build() + } + + private fun BsonDocument.optionalBoolean(key: String): Boolean? = if (get(key)?.isBoolean == true) getBoolean(key).value else null + + private fun BsonDocument.optionalString(key: String): String? = if (get(key)?.isString == true) getString(key).value else null + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mysql/MysqlDump.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mysql/MysqlDump.kt new file mode 100644 index 000000000..f10cd32a4 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mysql/MysqlDump.kt @@ -0,0 +1,72 @@ +package org.pnfolder.pnlibrary.updates.databases.mysql + +import org.pnfolder.pnlibrary.updates.databases.SqlRowWriter +import org.pnfolder.pnlibrary.updates.databases.TableMask +import org.pnfolder.pnlibrary.updates.databases.writeDumpFile +import java.io.BufferedWriter +import java.nio.file.Path +import java.sql.Connection +import java.sql.ResultSet +import java.sql.Types + +/** + * Writes every table of a database into one compressed text file of SQL statements, one statement per line: the + * table definition, then its rows. All tables are read in one consistent transaction, so rows match each other. + */ +internal class MysqlDump(private val maximumBytes: Long = 2L * 1024 * 1024 * 1024) { + /** Writes the tables matching [only] (all when empty) to [target], failing past [maximumBytes]. */ + fun write(connection: Connection, only: List, target: Path) { + connection.autoCommit = false + connection.createStatement().use { it.execute("START TRANSACTION WITH CONSISTENT SNAPSHOT") } + try { + writeDumpFile(target, HEADER) { out -> + val rowWriter = SqlRowWriter(out, target, maximumBytes, ::value) + tables(connection).filter { TableMask.matches(only, it) }.forEach { table -> dumpTable(connection, table, out, rowWriter) } + } + } finally { + connection.rollback() + } + } + + private fun tables(connection: Connection): List = connection.createStatement().use { statement -> + statement.executeQuery("SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'").use { rows -> + generateSequence { if (rows.next()) rows.getString(1) else null }.toList() + } + } + + private fun dumpTable(connection: Connection, table: String, out: BufferedWriter, rowWriter: SqlRowWriter) { + val quoted = MysqlSyntax.identifier(table) + out.write("DROP TABLE IF EXISTS $quoted;\n") + out.write(createStatement(connection, quoted) + ";\n") + connection.createStatement().use { statement -> + statement.fetchSize = SqlRowWriter.FETCH_ROWS + statement.executeQuery("SELECT * FROM $quoted").use { rows -> rowWriter.write(rows, "INSERT INTO $quoted VALUES (") } + } + } + + private fun createStatement(connection: Connection, quoted: String): String = connection.createStatement().use { statement -> + statement.executeQuery("SHOW CREATE TABLE $quoted").use { rows -> + check(rows.next()) { "Нет описания таблицы $quoted" } + rows.getString(2).replace('\n', ' ') + } + } + + private fun value(rows: ResultSet, column: Int): String { + val type = rows.metaData.getColumnType(column) + if (type in SqlRowWriter.BINARY_TYPES) { + val bytes = rows.getBytes(column) ?: return "NULL" + return "X'" + bytes.joinToString("") { "%02x".format(it) } + "'" + } + val text = rows.getString(column) ?: return "NULL" + return if (type in NUMBER_TYPES) text else MysqlSyntax.literal(text) + } + + companion object { + /** First line of every copy; the restore refuses a file without it. */ + const val HEADER = "-- pnlibrary-db 1" + private val NUMBER_TYPES = setOf( + Types.TINYINT, Types.SMALLINT, Types.INTEGER, Types.BIGINT, Types.FLOAT, Types.REAL, Types.DOUBLE, + Types.DECIMAL, Types.NUMERIC, + ) + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mysql/MysqlEngine.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mysql/MysqlEngine.kt new file mode 100644 index 000000000..6191b62a0 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mysql/MysqlEngine.kt @@ -0,0 +1,23 @@ +package org.pnfolder.pnlibrary.updates.databases.mysql + +import org.pnfolder.pnlibrary.updates.databases.DatabaseConnection +import org.pnfolder.pnlibrary.updates.databases.DatabaseEngine +import org.pnfolder.pnlibrary.updates.databases.JdbcConnections +import org.pnfolder.pnlibrary.updates.databases.SqlScriptRestore +import java.nio.file.Path + +/** MySQL and MariaDB through JDBC. */ +internal class MysqlEngine(private val connections: JdbcConnections = JdbcConnections.mysql()) : DatabaseEngine { + override fun dump(connection: DatabaseConnection, tables: List, target: Path) { + connections.open(connection).use { MysqlDump().write(it, tables, target) } + } + + override fun restore(connection: DatabaseConnection, source: Path) { + val restore = SqlScriptRestore( + MysqlDump.HEADER, + setup = listOf("SET SESSION sql_mode = REPLACE(@@sql_mode, 'NO_BACKSLASH_ESCAPES', '')", "SET SESSION FOREIGN_KEY_CHECKS = 0"), + teardown = listOf("SET SESSION FOREIGN_KEY_CHECKS = 1"), + ) + connections.open(connection).use { restore.read(it, source) } + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mysql/MysqlSyntax.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mysql/MysqlSyntax.kt new file mode 100644 index 000000000..963f8e09b --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/mysql/MysqlSyntax.kt @@ -0,0 +1,46 @@ +package org.pnfolder.pnlibrary.updates.databases.mysql + +/** Quoting for the statements a copy of a MySQL database is made of. */ +internal object MysqlSyntax { + /** [name] quoted as a MySQL identifier. */ + fun identifier(name: String): String = "`" + name.replace("`", "``") + "`" + + /** A text literal on one line: every character that could end or change the statement is escaped. */ + fun literal(text: String): String = buildString(text.length + 2) { + append('\'') + for (char in text) { + when (char) { + '\\' -> append("\\\\") + '\'' -> append("\\'") + '\n' -> append("\\n") + '\r' -> append("\\r") + '\u0000' -> append("\\0") + '\u001a' -> append("\\Z") + else -> append(char) + } + } + append('\'') + } + + /** + * [sql] on one line. A line break inside a quoted string (a DEFAULT or COMMENT) becomes `\n`, which keeps the text; + * elsewhere it is only white space and becomes a space. + */ + fun singleLine(sql: String): String = buildString(sql.length) { + var quote: Char? = null + var index = 0 + while (index < sql.length) { + val char = sql[index++] + val inText = quote == '\'' || quote == '"' + when { + char == '\n' && inText -> append("\\n") + char == '\r' && inText -> append("\\r") + char == '\n' || char == '\r' -> append(' ') + inText && char == '\\' && index < sql.length -> append(char).append(sql[index++]) + quote == null && (char == '\'' || char == '"' || char == '`') -> { quote = char; append(char) } + char == quote -> { quote = null; append(char) } + else -> append(char) + } + } + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresDump.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresDump.kt new file mode 100644 index 000000000..4a83a9539 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresDump.kt @@ -0,0 +1,66 @@ +package org.pnfolder.pnlibrary.updates.databases.postgres + +import org.pnfolder.pnlibrary.updates.databases.SqlRowWriter +import org.pnfolder.pnlibrary.updates.databases.TableMask +import org.pnfolder.pnlibrary.updates.databases.writeDumpFile +import java.io.BufferedWriter +import java.nio.file.Path +import java.sql.Connection +import java.sql.ResultSet + +/** + * Writes the tables of the current schema into one compressed text file of SQL statements, one per line: sequences, + * then each table with its rows and indexes, then foreign keys and sequence positions. Every table is read in one + * consistent read-only transaction. Views, functions, triggers and other schemas are not copied. + */ +internal class PostgresDump(private val maximumBytes: Long = 2L * 1024 * 1024 * 1024) { + /** Writes the tables matching [only] (all when empty) to [target], failing past [maximumBytes]. */ + fun write(connection: Connection, only: List, target: Path) { + connection.autoCommit = false + connection.createStatement().use { it.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY") } + try { + val schema = PostgresSchema(connection) + writeDumpFile(target, HEADER) { out -> + val rowWriter = SqlRowWriter(out, target, maximumBytes, ::value) + val tables = schema.tables().filter { TableMask.matches(only, it) } + // Dropping a table also drops the sequences it owns, so all drops come before the sequences are created. + tables.forEach { out.write("DROP TABLE IF EXISTS ${PostgresSyntax.identifier(it)} CASCADE;\n") } + schema.enumTypes(tables).forEach { out.write("$it;\n") } + schema.sequences(only).forEach { out.write("$it;\n") } + tables.forEach { dumpTable(connection, schema, it, out, rowWriter) } + (tables.flatMap(schema::foreignKeys) + schema.externalForeignKeys(tables)).forEach { out.write("$it;\n") } + schema.sequencePositions(only).forEach { out.write("$it;\n") } + } + } finally { + connection.rollback() + } + } + + private fun dumpTable(connection: Connection, schema: PostgresSchema, table: String, out: BufferedWriter, rowWriter: SqlRowWriter) { + val quoted = PostgresSyntax.identifier(table) + out.write(schema.createTable(table) + ";\n") + val columns = schema.columns(table).filterNot { it.generated }.map { PostgresSyntax.identifier(it.name) } + if (columns.isNotEmpty()) { + val list = columns.joinToString(", ") + connection.createStatement().use { statement -> + statement.fetchSize = SqlRowWriter.FETCH_ROWS + statement.executeQuery("SELECT $list FROM $quoted").use { rows -> + rowWriter.write(rows, "INSERT INTO $quoted ($list) OVERRIDING SYSTEM VALUE VALUES (") + } + } + } + schema.indexes(table).forEach { out.write("$it;\n") } + } + + private fun value(rows: ResultSet, column: Int): String { + if (rows.metaData.getColumnType(column) in SqlRowWriter.BINARY_TYPES) { + return rows.getBytes(column)?.let(PostgresSyntax::bytes) ?: "NULL" + } + return rows.getString(column)?.let(PostgresSyntax::literal) ?: "NULL" + } + + companion object { + /** First line of every copy; the restore refuses a file without it. */ + const val HEADER = "-- pnlibrary-pg 1" + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresEngine.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresEngine.kt new file mode 100644 index 000000000..175e72d47 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresEngine.kt @@ -0,0 +1,19 @@ +package org.pnfolder.pnlibrary.updates.databases.postgres + +import org.pnfolder.pnlibrary.updates.databases.DatabaseConnection +import org.pnfolder.pnlibrary.updates.databases.DatabaseEngine +import org.pnfolder.pnlibrary.updates.databases.JdbcConnections +import org.pnfolder.pnlibrary.updates.databases.SqlScriptRestore +import java.nio.file.Path + +/** PostgreSQL through JDBC. */ +internal class PostgresEngine(private val connections: JdbcConnections = JdbcConnections.postgres()) : DatabaseEngine { + override fun dump(connection: DatabaseConnection, tables: List, target: Path) { + connections.open(connection).use { PostgresDump().write(it, tables, target) } + } + + override fun restore(connection: DatabaseConnection, source: Path) { + val restore = SqlScriptRestore(PostgresDump.HEADER, atomic = true) + connections.open(connection).use { restore.read(it, source) } + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresSchema.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresSchema.kt new file mode 100644 index 000000000..b9d5e9c42 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresSchema.kt @@ -0,0 +1,202 @@ +package org.pnfolder.pnlibrary.updates.databases.postgres + +import org.pnfolder.pnlibrary.updates.databases.TableMask +import java.sql.Connection +import java.sql.ResultSet + +/** Reads the shape of the tables of the current schema from the system catalogs and writes it as statements. */ +internal class PostgresSchema(private val connection: Connection) { + /** + * A table column; [generated] columns are computed by the server and are not copied. + * @property name column name + * @property generated true for a stored generated column + */ + class Column(val name: String, val generated: Boolean) + + /** Names of the base tables of the current schema. */ + fun tables(): List = strings( + "SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema() AND table_type = 'BASE TABLE' ORDER BY 1", + ) + + /** + * `CREATE SEQUENCE` for sequences that belong to no identity column; identity columns bring their own. + * [only] keeps those owned by the listed tables. + */ + fun sequences(only: List): List { + val wanted = sequenceNames(only).toSet() + return connection.createStatement().use { statement -> + statement.executeQuery( + "SELECT sequencename, data_type::text, start_value, increment_by, min_value, max_value, cycle " + + "FROM pg_sequences WHERE schemaname = current_schema() ORDER BY 1", + ).use { rows -> + generateSequence { if (rows.next()) rows.getString(1) to sequenceStatement(rows) else null } + .filter { (name, _) -> name in wanted }.map { it.second }.toList() + } + } + } + + private fun sequenceStatement(rows: ResultSet): String = PostgresSyntax.createSequence( + rows.getString(1), rows.getString(2), rows.getLong(3), rows.getLong(4), rows.getLong(5), rows.getLong(6), rows.getBoolean(7), + ) + + private fun sequenceNames(only: List): List = ownedSequences( + """ + SELECT s.relname, t.relname FROM pg_class s JOIN pg_namespace n ON n.oid = s.relnamespace + LEFT JOIN pg_depend d ON d.objid = s.oid AND d.deptype = 'a' LEFT JOIN pg_class t ON t.oid = d.refobjid + WHERE s.relkind = 'S' AND n.nspname = current_schema() + AND NOT EXISTS (SELECT 1 FROM pg_depend i WHERE i.objid = s.oid AND i.deptype = 'i') ORDER BY 1 + """, + only, + ) + + /** `setval` statements that give every sequence its current position back. */ + fun sequencePositions(only: List): List { + val owners = ownedSequences( + """ + SELECT s.relname, t.relname FROM pg_class s JOIN pg_namespace n ON n.oid = s.relnamespace + LEFT JOIN pg_depend d ON d.objid = s.oid AND d.deptype IN ('a', 'i') LEFT JOIN pg_class t ON t.oid = d.refobjid + WHERE s.relkind = 'S' AND n.nspname = current_schema() + """, + only, + ).toSet() + return connection.createStatement().use { statement -> + statement.executeQuery( + "SELECT sequencename, last_value FROM pg_sequences WHERE schemaname = current_schema() AND last_value IS NOT NULL", + ).use { rows -> + generateSequence { if (rows.next()) rows.getString(1) to rows.getLong(2) else null } + .filter { (name, _) -> name in owners } + .map { (name, value) -> "SELECT setval(${PostgresSyntax.literal(PostgresSyntax.identifier(name))}, $value, true)" }.toList() + } + } + } + + private fun ownedSequences(sql: String, only: List): List = connection.createStatement().use { statement -> + statement.executeQuery(sql).use { rows -> + generateSequence { if (rows.next()) rows.getString(1) to rows.getString(2) else null } + .filter { (_, owner) -> owner != null && TableMask.matches(only, owner) || only.isEmpty() }.map { it.first }.toList() + } + } + + /** Statements that create the enum types the columns of [tables] use; they run before the tables. */ + fun enumTypes(tables: List): List { + if (tables.isEmpty()) return emptyList() + val types = connection.prepareStatement( + """ + SELECT DISTINCT ty.oid, ty.typname FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid + JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_type col ON col.oid = a.atttypid + JOIN pg_type ty ON ty.oid = CASE WHEN col.typcategory = 'A' THEN col.typelem ELSE col.oid END + WHERE ty.typtype = 'e' AND ty.typnamespace = n.oid AND n.nspname = current_schema() AND c.relkind = 'r' + AND a.attnum > 0 AND NOT a.attisdropped AND c.relname = ANY (?) ORDER BY ty.typname + """, + ).use { statement -> + statement.setArray(1, connection.createArrayOf("text", tables.toTypedArray())) + statement.executeQuery().use { rows -> generateSequence { if (rows.next()) rows.getLong(1) to rows.getString(2) else null }.toList() } + } + return types.map { (oid, name) -> PostgresSyntax.createEnum(name, enumLabels(oid)) } + } + + private fun enumLabels(oid: Long): List = connection.prepareStatement( + "SELECT enumlabel FROM pg_enum WHERE enumtypid = ? ORDER BY enumsortorder", + ).use { statement -> + statement.setLong(1, oid) + statement.executeQuery().use { rows -> generateSequence { if (rows.next()) rows.getString(1) else null }.toList() } + } + + /** + * Foreign keys of tables outside [tables] that point at them. `DROP TABLE ... CASCADE` removes these, so they are + * added back as `NOT VALID`: the restored rows may differ from what those tables hold now, and a check must not undo the restore. + */ + fun externalForeignKeys(tables: List): List { + if (tables.isEmpty()) return emptyList() + return connection.prepareStatement( + """ + SELECT cl.relname, c.conname, pg_get_constraintdef(c.oid) FROM pg_constraint c + JOIN pg_class cl ON cl.oid = c.conrelid JOIN pg_namespace n ON n.oid = cl.relnamespace + JOIN pg_class ref ON ref.oid = c.confrelid + WHERE c.contype = 'f' AND n.nspname = current_schema() AND ref.relname = ANY (?) AND NOT (cl.relname = ANY (?)) + ORDER BY 1, 2 + """, + ).use { statement -> + val names = connection.createArrayOf("text", tables.toTypedArray()) + statement.setArray(1, names) + statement.setArray(2, names) + statement.executeQuery().use { rows -> + generateSequence { if (rows.next()) externalKey(rows.getString(1), rows.getString(2), rows.getString(3)) else null }.toList() + } + } + } + + private fun externalKey(table: String, name: String, definition: String): String { + val notValid = if (definition.endsWith(" NOT VALID")) "" else " NOT VALID" + return "ALTER TABLE ${PostgresSyntax.identifier(table)} ADD CONSTRAINT ${PostgresSyntax.identifier(name)} $definition$notValid" + } + + /** The columns of [table] in order. */ + fun columns(table: String): List = connection.prepareStatement( + "SELECT a.attname, a.attgenerated <> '' FROM pg_attribute a WHERE a.attrelid = ?::regclass AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum", + ).use { statement -> + statement.setString(1, PostgresSyntax.identifier(table)) + statement.executeQuery().use { rows -> generateSequence { if (rows.next()) Column(rows.getString(1), rows.getBoolean(2)) else null }.toList() } + } + + /** `CREATE TABLE` with columns, defaults and the primary key, unique and check constraints; foreign keys come later. */ + fun createTable(table: String): String { + val regclass = PostgresSyntax.identifier(table) + val columns = connection.prepareStatement( + """ + SELECT a.attname, format_type(a.atttypid, a.atttypmod), a.attnotnull, pg_get_expr(d.adbin, d.adrelid), a.attidentity, a.attgenerated + FROM pg_attribute a LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum + WHERE a.attrelid = ?::regclass AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum + """, + ).use { statement -> + statement.setString(1, regclass) + statement.executeQuery().use { rows -> + generateSequence { if (rows.next()) columnDefinition(rows) else null }.toList() + } + } + val constraints = constraints(regclass, "contype <> 'f'").map { "CONSTRAINT ${PostgresSyntax.identifier(it.first)} ${it.second}" } + return "CREATE TABLE $regclass (${(columns + constraints).joinToString(", ")})" + } + + private fun columnDefinition(rows: ResultSet): String { + val definition = StringBuilder(PostgresSyntax.identifier(rows.getString(1))).append(' ').append(rows.getString(2)) + val default = rows.getString(4) + when { + rows.getString(6) == "s" -> definition.append(" GENERATED ALWAYS AS ($default) STORED") + rows.getString(5) == "a" -> definition.append(" GENERATED ALWAYS AS IDENTITY") + rows.getString(5) == "d" -> definition.append(" GENERATED BY DEFAULT AS IDENTITY") + default != null -> definition.append(" DEFAULT ").append(default) + } + if (rows.getBoolean(3)) definition.append(" NOT NULL") + return definition.toString() + } + + /** `ALTER TABLE` statements that add the foreign keys of [table]; they run after every table exists. */ + fun foreignKeys(table: String): List { + val regclass = PostgresSyntax.identifier(table) + return constraints(regclass, "contype = 'f'").map { "ALTER TABLE $regclass ADD CONSTRAINT ${PostgresSyntax.identifier(it.first)} ${it.second}" } + } + + /** Indexes that are not behind a constraint, as the server writes them. */ + fun indexes(table: String): List = connection.prepareStatement( + """ + SELECT indexdef FROM pg_indexes WHERE schemaname = current_schema() AND tablename = ? + AND indexname NOT IN (SELECT conname FROM pg_constraint WHERE conrelid = ?::regclass AND contype IN ('p', 'u', 'x')) + """, + ).use { statement -> + statement.setString(1, table) + statement.setString(2, PostgresSyntax.identifier(table)) + statement.executeQuery().use { rows -> generateSequence { if (rows.next()) rows.getString(1) else null }.toList() } + } + + private fun constraints(regclass: String, filter: String): List> = connection.prepareStatement( + "SELECT conname, pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid = ?::regclass AND $filter ORDER BY conname", + ).use { statement -> + statement.setString(1, regclass) + statement.executeQuery().use { rows -> generateSequence { if (rows.next()) rows.getString(1) to rows.getString(2) else null }.toList() } + } + + private fun strings(sql: String): List = connection.createStatement().use { statement -> + statement.executeQuery(sql).use { rows -> generateSequence { if (rows.next()) rows.getString(1) else null }.toList() } + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresSyntax.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresSyntax.kt new file mode 100644 index 000000000..9724c279e --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresSyntax.kt @@ -0,0 +1,40 @@ +package org.pnfolder.pnlibrary.updates.databases.postgres + +/** Quoting for the statements a copy of a PostgreSQL database is made of. */ +internal object PostgresSyntax { + /** [name] quoted as a PostgreSQL identifier. */ + fun identifier(name: String): String = "\"" + name.replace("\"", "\"\"") + "\"" + + /** + * A text literal on one line. The E prefix lets line breaks and backslashes be written as escapes, and a quote is + * doubled; PostgreSQL turns the text into the column's type, so one form fits every column. + */ + fun literal(text: String): String = buildString(text.length + 3) { + append("E'") + for (char in text) { + when (char) { + '\\' -> append("\\\\") + '\'' -> append("''") + '\n' -> append("\\n") + '\r' -> append("\\r") + else -> append(char) + } + } + append('\'') + } + + /** Binary [value] as a hex literal. */ + fun bytes(value: ByteArray): String = "'\\x" + value.joinToString("") { "%02x".format(it) } + "'" + + /** Creates an enum type once; a type that is already there is left alone. */ + fun createEnum(name: String, labels: List): String { + val body = "CREATE TYPE ${identifier(name)} AS ENUM (${labels.joinToString(", ") { literal(it) }})" + val tag = if (labels.any { "$$" in it }) "${'$'}pn${'$'}" else "$$" + return "DO $tag BEGIN $body; EXCEPTION WHEN duplicate_object THEN NULL; END $tag" + } + + /** A sequence with the settings it has now, so numbering continues the way the plugin set it up. */ + fun createSequence(name: String, type: String, start: Long, increment: Long, min: Long, max: Long, cycle: Boolean): String = + "CREATE SEQUENCE IF NOT EXISTS ${identifier(name)} AS $type INCREMENT BY $increment MINVALUE $min MAXVALUE $max " + + "START WITH $start ${if (cycle) "" else "NO "}CYCLE" +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/FreezeDuration.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/FreezeDuration.kt similarity index 88% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/FreezeDuration.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/FreezeDuration.kt index 455ef5653..355008f60 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/FreezeDuration.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/FreezeDuration.kt @@ -1,14 +1,13 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine import java.time.Duration /** Parses and validates administrator-supplied update-freeze durations: from one minute to seven days. */ -internal object FreezeDuration { +object FreezeDuration { /** The longest pause: updates of a component can never be held for more than a week. */ val MAXIMUM: Duration = Duration.ofDays(7) private val minimum = Duration.ofMinutes(1) - private val maximum = MAXIMUM private val pattern = Regex("^(\\d+)([mhd])$", RegexOption.IGNORE_CASE) /** Parses a positive `m`, `h`, or `d` duration within supported bounds. */ @@ -28,7 +27,7 @@ internal object FreezeDuration { /** Returns [duration] after verifying the supported freeze interval. */ fun validate(duration: Duration): Duration { - require(duration >= minimum && duration <= maximum) { + require(duration >= minimum && duration <= MAXIMUM) { "Freeze duration must be between 1 minute and 7 days" } return duration diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/FreezeStore.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/FreezeStore.kt similarity index 56% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/FreezeStore.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/FreezeStore.kt index 4f71bd65d..548cc4f3a 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/FreezeStore.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/FreezeStore.kt @@ -1,21 +1,15 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine -import com.google.gson.Gson -import com.google.gson.reflect.TypeToken -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.common.io.AtomicFiles -import java.nio.charset.StandardCharsets -import java.nio.file.Files -import java.nio.file.Path +import org.pnfolder.pnlibrary.api.updates.product.ProductId import java.time.Clock import java.time.Duration import java.time.Instant +/** Persists per-component update pauses, as the freezes section of [store], and drops them once they expire. */ internal class FreezeStore( - private val path: Path, + private val store: UpdatePreferencesStore, private val clock: Clock = Clock.systemUTC(), ) { - private val gson = Gson() private val expiries = load() @Synchronized @@ -57,28 +51,15 @@ internal class FreezeStore( } private fun load(): MutableMap { - if (!Files.exists(path)) return linkedMapOf() - val type = object : TypeToken>() {}.type - val stored: Map = Files.newBufferedReader(path, StandardCharsets.UTF_8).use { - gson.fromJson(it, type) ?: emptyMap() - } // A pause saved under an older, longer limit still ends within the current maximum. val latest = clock.instant().plus(FreezeDuration.MAXIMUM) - return stored.entries.associateTo(linkedMapOf()) { + return store.current().freezes.entries.associateTo(linkedMapOf()) { ProductId.of(it.key) to minOf(Instant.ofEpochMilli(it.value), latest) } } private fun persist() { - val parent = path.toAbsolutePath().parent - Files.createDirectories(parent) - val temporary = Files.createTempFile(parent, path.fileName.toString(), ".tmp") - try { - val stored = expiries.entries.associate { it.key.value to it.value.toEpochMilli() } - Files.newBufferedWriter(temporary, StandardCharsets.UTF_8).use { gson.toJson(stored, it) } - AtomicFiles.move(temporary, path) - } finally { - Files.deleteIfExists(temporary) - } + val stored = expiries.entries.associate { it.key.value to it.value.toEpochMilli() } + store.update { it.copy(freezes = stored) } } } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdatePaths.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdatePaths.kt similarity index 89% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdatePaths.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdatePaths.kt index d7b9e904e..9d9968f02 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdatePaths.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdatePaths.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine import java.nio.file.Files import java.nio.file.LinkOption @@ -6,6 +6,7 @@ import java.nio.file.Path /** Shared confinement checks for transaction targets and configuration snapshots. */ internal object UpdatePaths { + /** Returns [path] normalized, failing if it escapes [allowedRoot]. */ fun inside(path: Path, allowedRoot: Path): Path { val normalized = path.toAbsolutePath().normalize() val allowed = allowedRoot.toAbsolutePath().normalize() diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdatePreferencesStore.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdatePreferencesStore.kt new file mode 100644 index 000000000..911d8d470 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdatePreferencesStore.kt @@ -0,0 +1,78 @@ +package org.pnfolder.pnlibrary.updates.engine + +import com.google.gson.GsonBuilder +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import org.pnfolder.pnlibrary.common.io.AtomicFiles +import org.pnfolder.pnlibrary.common.io.TextFiles +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.Files +import java.nio.file.Path + +/** + * The administrator's update choices in one file: release channels, Java builds, automatic download and component pauses. + * + * Several owners edit their own sections of the same file, so there is one in-memory model and one lock; every change + * is read, modified and written back under that lock, and a save never discards what another owner stored. + */ +internal class UpdatePreferencesStore( + private val file: Path, + private val warning: (String) -> Unit = {}, +) { + /** What is stored: channel and automatic-download choices by product, the all-plugins choice and pause expiries in epoch millis. */ + data class Preferences( + val channels: Map = emptyMap(), + val automatic: Map = emptyMap(), + val allPlugins: Boolean? = null, + val freezes: Map = emptyMap(), + val javaBuilds: Map = emptyMap(), + ) + + private val gson = GsonBuilder().setPrettyPrinting().create() + + @Volatile + private var preferences = load() + + /** The file name, for messages. */ + val fileName: String get() = file.fileName.toString() + + /** What is stored now. */ + fun current(): Preferences = preferences + + /** Applies [change] to what is stored and saves the result; a failed save leaves the stored model as it was. */ + @Synchronized + fun update(change: (Preferences) -> Preferences) { + val changed = change(preferences) + if (changed == preferences) return + write(changed) + preferences = changed + } + + private fun load(): Preferences { + if (!Files.isRegularFile(file)) return Preferences() + return try { + val root = JsonParser.parseString(TextFiles.read(file, UTF_8)).asJsonObject + Preferences( + channels = root.getAsJsonObject("channels")?.entrySet().orEmpty().associate { (product, value) -> product to value.asString }, + automatic = root.getAsJsonObject("automatic")?.entrySet().orEmpty().associate { (product, value) -> product to value.asBoolean }, + allPlugins = root.get("allPlugins")?.takeIf { !it.isJsonNull }?.asBoolean, + freezes = root.getAsJsonObject("freezes")?.entrySet().orEmpty().associate { (product, value) -> product to value.asLong }, + javaBuilds = root.getAsJsonObject("javaBuilds")?.entrySet().orEmpty().associate { (product, value) -> product to value.asInt }, + ) + } catch (error: Exception) { + warning("Unreadable update settings $fileName: ${error.javaClass.simpleName}") + Preferences() + } + } + + private fun write(value: Preferences) { + val json = JsonObject().apply { + value.allPlugins?.let { addProperty("allPlugins", it) } + add("channels", JsonObject().also { node -> value.channels.toSortedMap().forEach { (p, c) -> node.addProperty(p, c) } }) + add("automatic", JsonObject().also { node -> value.automatic.toSortedMap().forEach { (p, a) -> node.addProperty(p, a) } }) + add("freezes", JsonObject().also { node -> value.freezes.toSortedMap().forEach { (p, e) -> node.addProperty(p, e) } }) + add("javaBuilds", JsonObject().also { node -> value.javaBuilds.toSortedMap().forEach { (p, j) -> node.addProperty(p, j) } }) + } + AtomicFiles.write(file, gson.toJson(json).toByteArray(UTF_8)) + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateResolver.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdateResolver.kt similarity index 66% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateResolver.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdateResolver.kt index 33011f7ab..2d338e460 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateResolver.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdateResolver.kt @@ -1,14 +1,14 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.api.updates.BlockedReason -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.InstalledProduct import org.pnfolder.pnlibrary.api.updates.release.ProductChange import org.pnfolder.pnlibrary.api.updates.release.ProductDependency import org.pnfolder.pnlibrary.api.updates.release.ProductRelease import org.pnfolder.pnlibrary.api.updates.release.UpdatePlan +import org.pnfolder.pnlibrary.api.updates.state.BlockedReason /** * Environment capabilities applied during graph resolution. @@ -41,7 +41,7 @@ internal sealed class ResolutionResult { ) : ResolutionResult() } -/** Deterministic API, channel, freeze, and dependency resolver for pnUpdate. */ +/** Deterministic API, channel, pause, and dependency resolver for the managed components. */ internal class UpdateResolver(private val libraryComponent: ProductId) { /** Resolves all installed products and candidate releases as one atomic ecosystem. */ @JvmOverloads @@ -76,8 +76,7 @@ internal class UpdateResolver(private val libraryComponent: ProductId) { } else { (allowedReleases.filter { it.product == libraryComponent } + currentLibraryRelease) .filter { it.providesApi != null && it.version >= currentLibrary.version } - .distinctBy { it.version.toString() } - .sortedByDescending(ProductRelease::version) + .newestFirst() } var primaryFailure: List? = null @@ -119,19 +118,7 @@ internal class UpdateResolver(private val libraryComponent: ProductId) { val reasons = mutableListOf() installed.sortedBy { it.product }.filter { it.product != libraryComponent }.forEach { current -> - val currentRelease = current.asRelease() - val compatibleUpdates = releases - .filter { it.product == current.product && it.version >= current.version } - .filter { it.supportedApi.supports(targetApi) } - .filter { externalPluginDependenciesAvailable(it, policy) } - val domain = if (current.product in frozen) { - if (current.supportedApi.supports(targetApi)) listOf(currentRelease) else emptyList() - } else { - (compatibleUpdates + currentRelease.takeIf { current.supportedApi.supports(targetApi) }) - .filterNotNull() - .distinctBy { it.version.toString() } - .sortedByDescending(ProductRelease::version) - } + val domain = installedDomain(current, releases, targetApi, current.product in frozen, policy) if (domain.isEmpty()) { if (current.product in frozen) reasons += BlockedReason.Frozen(current.product) reasons += BlockedReason.NoCompatibleRelease(current.product, targetApi) @@ -141,24 +128,7 @@ internal class UpdateResolver(private val libraryComponent: ProductId) { } if (reasons.isNotEmpty()) return Attempt(null, reasons) - if (policy.allowManagedInstalls) { - var added: Boolean - do { - added = false - val missing = domains.values.flatten().flatMap(ProductRelease::dependencies) - .map(ProductDependency::product).filterNot(domains::containsKey).distinct().sorted() - missing.forEach { dependency -> - val candidates = releases.filter { - it.product == dependency && it.supportedApi.supports(targetApi) && externalPluginDependenciesAvailable(it, policy) - } - .distinctBy { it.version.toString() }.sortedByDescending(ProductRelease::version) - if (candidates.isNotEmpty()) { - domains[dependency] = candidates - added = true - } - } - } while (added) - } + if (policy.allowManagedInstalls) addMissingDependencyDomains(domains, releases, targetApi, policy) val ids = domains.keys.filter { it != libraryComponent }.sorted() val selected = linkedMapOf(libraryComponent to libraryRelease) @@ -172,29 +142,96 @@ internal class UpdateResolver(private val libraryComponent: ProductId) { if (current?.version == target.version) null else ProductChange(target.product, current?.version, target.version) } - val unavailableRequestedDependencies = if (policy.allowManagedInstalls) emptyList() else - releases.filter { candidate -> - val current = installedById[candidate.product] - current != null && candidate.version > current.version && candidate.supportedApi.supports(targetApi) - }.flatMap { candidate -> - candidate.dependencies.mapNotNull { dependency -> - if (domains.containsKey(dependency.product)) null - else BlockedReason.MissingDependency(candidate.product, dependency.product, dependency.minimumVersion) + val upgrades = upgradableCandidates(releases, installedById, targetApi) + val unavailableRequestedDependencies = + if (policy.allowManagedInstalls) emptyList() else missingDependencyReasons(upgrades, domains) + return Attempt( + UpdatePlan(targetApi, changes, ordered), + (unavailableRequestedDependencies + missingExternalPluginReasons(upgrades, policy)).distinct(), + ) + } + + /** Releases that [current] may move to (or stay on) under [targetApi]; frozen products keep only themselves. */ + private fun installedDomain( + current: InstalledProduct, + releases: List, + targetApi: Int, + frozen: Boolean, + policy: ResolverPolicy, + ): List { + val currentSupportsApi = current.supportedApi.supports(targetApi) + if (frozen) return if (currentSupportsApi) listOf(current.asRelease()) else emptyList() + val compatibleUpdates = releases + .filter { it.product == current.product && it.version >= current.version } + .filter { it.supportedApi.supports(targetApi) } + .filter { externalPluginDependenciesAvailable(it, policy) } + return (compatibleUpdates + current.asRelease().takeIf { currentSupportsApi }) + .filterNotNull() + .newestFirst() + } + + /** Adds domains for dependencies that are not installed yet, repeating until no new product appears. */ + private fun addMissingDependencyDomains( + domains: MutableMap>, + releases: List, + targetApi: Int, + policy: ResolverPolicy, + ) { + do { + var added = false + val missing = domains.values.flatten().flatMap(ProductRelease::dependencies) + .map(ProductDependency::product).filterNot(domains::containsKey).distinct().sorted() + missing.forEach { dependency -> + val candidates = releases.filter { + it.product == dependency && it.supportedApi.supports(targetApi) && + externalPluginDependenciesAvailable(it, policy) + }.newestFirst() + if (candidates.isNotEmpty()) { + domains[dependency] = candidates + added = true } - }.distinct() + } + } while (added) + } + + /** Newer releases of installed products that the target API supports. */ + private fun upgradableCandidates( + releases: List, + installedById: Map, + targetApi: Int, + ): List = releases.filter { candidate -> + val current = installedById[candidate.product] + current != null && candidate.version > current.version && candidate.supportedApi.supports(targetApi) + } + + private fun missingDependencyReasons( + upgrades: List, + domains: Map>, + ): List = upgrades.flatMap { candidate -> + candidate.dependencies.mapNotNull { dependency -> + if (domains.containsKey(dependency.product)) null + else BlockedReason.MissingDependency(candidate.product, dependency.product, dependency.minimumVersion) + } + }.distinct() + + private fun missingExternalPluginReasons( + upgrades: List, + policy: ResolverPolicy, + ): List { val installedExternal = policy.installedExternalPlugins.map { it.lowercase() }.toSet() - val externalReasons = releases.filter { candidate -> - val current = installedById[candidate.product] - current != null && candidate.version > current.version && candidate.supportedApi.supports(targetApi) - }.flatMap { release -> release.externalPluginDependencies.mapNotNull { dependency -> - if (dependency.plugin.lowercase() in installedExternal) null - else BlockedReason.MissingExternalPluginDependency( - release.product, dependency.plugin, dependency.minimumVersion, dependency.downloadPage?.toString(), - ) - } }.distinct() - return Attempt(UpdatePlan(targetApi, changes, ordered), (unavailableRequestedDependencies + externalReasons).distinct()) + return upgrades.flatMap { release -> + release.externalPluginDependencies.mapNotNull { dependency -> + if (dependency.plugin.lowercase() in installedExternal) null + else BlockedReason.MissingExternalPluginDependency( + release.product, dependency.plugin, dependency.minimumVersion, dependency.downloadPage?.toString(), + ) + } + }.distinct() } + private fun List.newestFirst(): List = + distinctBy { it.version.toString() }.sortedByDescending(ProductRelease::version) + private fun search( ids: List, index: Int, diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/catalog/CatalogArtifactPlatform.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/catalog/CatalogArtifactPlatform.kt new file mode 100644 index 000000000..9201bf028 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/catalog/CatalogArtifactPlatform.kt @@ -0,0 +1,7 @@ +package org.pnfolder.pnlibrary.updates.engine.catalog + +import org.pnfolder.pnlibrary.api.platform.PlatformType + +/** Whether this artifact runs on [target]: an exact platform match, or one built for every platform. */ +internal fun CatalogArtifact.matchesPlatform(target: PlatformType): Boolean = + platform == target || platform == PlatformType.UNIVERSAL diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalog.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/catalog/ReleaseCatalog.kt similarity index 98% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalog.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/catalog/ReleaseCatalog.kt index 3b745d421..27aa9e4fd 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalog.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/catalog/ReleaseCatalog.kt @@ -1,10 +1,10 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.catalog import com.google.gson.JsonArray import com.google.gson.JsonObject import com.google.gson.JsonParser import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.api.updates.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion import java.net.URI @@ -36,6 +36,7 @@ internal data class ReleaseCatalog(val product: String, val releases: List runCatchingNonFatal { isCandidate(journals.load(path)) }.getOrDefault(false) } - .maxByOrNull { Files.getLastModifiedTime(it).toMillis() } + fun latest(): Path? = candidates().map { it.first }.maxByOrNull { Files.getLastModifiedTime(it).toMillis() } /** Resolves exactly one saved transaction; never substitutes the latest one. */ fun resolve(id: UUID): Path { @@ -27,14 +27,14 @@ internal class RollbackCatalog( } /** Lists validated rollback candidates, newest first, skipping incomplete or corrupt transactions. */ - fun all(): List = journals.journals().filter { path -> - runCatchingNonFatal { isCandidate(journals.load(path)) }.getOrDefault(false) - }.sortedByDescending { path -> - journals.load(path).createdAt?.let(Instant::parse) ?: Instant.MIN - } + fun all(): List = candidates() + .sortedByDescending { (_, journal) -> journal.createdAt?.let(Instant::parse) ?: Instant.MIN } + .map { it.first } - private fun isCandidate(journal: TransactionJournal): Boolean = - journal.purpose in setOf(null, "STAGE") && journal.isRestorable() && journals.hasRollbackData(journal) + /** An unreadable journal is reported by the repository and skipped, so it cannot hide the other sets. */ + private fun candidates() = journals.loadAll().filter { (path, journal) -> + journal.purpose in setOf(null, "STAGE") && journal.isRestorable() && journals.hasReadableRollbackData(path, journal) + } } /** diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ArtifactDownloader.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/net/ArtifactDownloader.kt similarity index 97% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ArtifactDownloader.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/net/ArtifactDownloader.kt index 2a91abade..055d0dc50 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ArtifactDownloader.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/net/ArtifactDownloader.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.net import org.pnfolder.pnlibrary.common.io.AtomicFiles import java.io.InputStream diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ArtifactVerifier.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/net/ArtifactVerifier.kt similarity index 95% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ArtifactVerifier.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/net/ArtifactVerifier.kt index 504c6a114..fcd8e59ef 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ArtifactVerifier.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/net/ArtifactVerifier.kt @@ -1,6 +1,6 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.net -import org.pnfolder.pnlibrary.api.updates.ProductId +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.common.io.Digests diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/net/TrustedHosts.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/net/TrustedHosts.kt new file mode 100644 index 000000000..e348e5c7b --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/net/TrustedHosts.kt @@ -0,0 +1,35 @@ +package org.pnfolder.pnlibrary.updates.engine.net + +import java.net.URI + +/** + * Hosts a plugin JAR may be downloaded from. The SHA-256 comes from the same catalog as the link, so + * a hijacked catalog entry could otherwise point the automatic download at any server. + */ +internal object TrustedHosts { + private val downloads = setOf( + "github.com", + "objects.githubusercontent.com", + "raw.githubusercontent.com", + "release-assets.githubusercontent.com", + "cdn.jsdelivr.net", + ) + + /** Redirects of any update request may additionally land on the GitHub API. */ + private val redirects = downloads + "api.github.com" + + /** Refuses [uri] unless it is HTTPS on a download host. */ + fun requireDownload(uri: URI): URI { + require(uri.scheme.equals("https", true)) { "Update URL must use HTTPS: $uri" } + require(uri.host?.lowercase() in downloads) { + "Скачивание JAR с хоста ${uri.host} запрещено: разрешены ${downloads.joinToString()}" + } + return uri + } + + /** Refuses a redirect that leaves the trusted hosts. */ + fun requireRedirect(uri: URI): URI { + require(uri.host?.lowercase() in redirects) { "Редирект на недоверенный хост ${uri.host} отклонён: $uri" } + return uri + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TrustedHttpClient.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/net/TrustedHttpClient.kt similarity index 93% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TrustedHttpClient.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/net/TrustedHttpClient.kt index c13c56d39..8358a3201 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TrustedHttpClient.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/net/TrustedHttpClient.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.net import java.io.ByteArrayOutputStream import java.io.InputStream @@ -18,6 +18,7 @@ open class TrustedHttpClient( private val readTimeout: Duration, ) { + /** Checks that [uri] is an allowed download address and returns it. */ internal fun validate(uri: URI): URI { require(uri.scheme.equals("https", true)) { "Update URL must use HTTPS: $uri" } require(uri.userInfo == null && uri.fragment == null) { "Update URL contains forbidden components" } @@ -51,7 +52,7 @@ open class TrustedHttpClient( if (status in REDIRECT_CODES) { if (redirect == MAX_REDIRECTS) error("Too many update redirects") val location = connection.getHeaderField("Location") ?: error("Redirect has no Location") - current = validate(current.resolve(location)) + current = TrustedHosts.requireRedirect(validate(current.resolve(location))) return@repeat } require(status in 200..299) { "Update request failed with HTTP $status" } @@ -68,6 +69,7 @@ open class TrustedHttpClient( error("Unreachable redirect state") } + /** Reads the stream, failing if it exceeds [maximumBytes]. */ internal fun readBounded(input: InputStream, maximumBytes: Int): ByteArray { val output = ByteArrayOutputStream(minOf(maximumBytes, 8192)) val buffer = ByteArray(8192) diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TransactionHealth.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/TransactionHealth.kt similarity index 88% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TransactionHealth.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/TransactionHealth.kt index fefd0529e..c10bf88d4 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TransactionHealth.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/TransactionHealth.kt @@ -1,6 +1,5 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.transaction -import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import java.nio.file.Path import java.time.Instant @@ -25,9 +24,8 @@ internal class TransactionHealth( } /** Returns transactions waiting for post-restart product-version confirmation. */ - fun awaiting(): List = journals.journals() - .mapNotNull { path -> - val journal = runCatchingNonFatal { journals.load(path) }.getOrNull() ?: return@mapNotNull null + fun awaiting(): List = journals.loadAll() + .mapNotNull { (path, journal) -> if (journal.state != TransactionState.AWAITING_HEALTH || journal.purpose !in setOf(null, "STAGE")) return@mapNotNull null PendingTransaction(path, journal.artifacts.mapNotNull { artifact -> artifact.expectedVersion?.let { artifact.component to it } @@ -35,8 +33,7 @@ internal class TransactionHealth( } /** Returns requested rollbacks whose restored versions are not yet confirmed. */ - fun awaitingRollback(): List = journals.journals().mapNotNull { path -> - val journal = journals.load(path) + fun awaitingRollback(): List = journals.loadAll().mapNotNull { (path, journal) -> if (journal.purpose !in setOf(null, "STAGE") || journal.state != TransactionState.ROLLED_BACK || !journal.rollbackRequested || journal.rollbackHealthVerified) return@mapNotNull null PendingTransaction(path, journal.artifacts.mapNotNull { it.previousVersion?.let { version -> it.component to version } }.toMap(), @@ -61,8 +58,7 @@ internal class TransactionHealth( /** Returns whether the latest health check of every product in [products] succeeded. */ fun automaticUpdatesHealthy(products: Set): Boolean { val latest = mutableMapOf>() - journals.journals().forEach { path -> - val journal = journals.load(path) + journals.loadAll().forEach { (_, journal) -> if (journal.purpose !in setOf(null, "STAGE")) return@forEach val checkedAt = journal.healthCheckedAt?.let(Instant::parse) ?: return@forEach journal.artifacts.filter { it.component in products }.forEach { artifact -> @@ -75,8 +71,7 @@ internal class TransactionHealth( } /** Returns saved component sets whose last health check failed. */ - fun failed(): List = journals.journals().mapNotNull { path -> - val journal = journals.load(path) + fun failed(): List = journals.loadAll().mapNotNull { (path, journal) -> if (journal.purpose !in setOf(null, "STAGE") || journal.state != TransactionState.FAILED || !journal.healthFailure) return@mapNotNull null val versions = journal.artifacts.associate { it.component to (if (journal.rollbackRequested) it.previousVersion else it.expectedVersion) } PendingTransaction(path, versions.mapNotNull { (product, version) -> version?.let { product to it } }.toMap(), diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TransactionJournal.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/TransactionJournal.kt similarity index 96% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TransactionJournal.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/TransactionJournal.kt index 4734caec1..8779e90c6 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TransactionJournal.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/TransactionJournal.kt @@ -1,8 +1,9 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.transaction import com.google.gson.GsonBuilder import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.common.io.AtomicFiles +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactSpecification import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path @@ -113,6 +114,7 @@ internal data class TransactionJournal( companion object { private val gson = GsonBuilder().setPrettyPrinting().create() + /** Reads a journal written by [save]. */ fun load(path: Path): TransactionJournal = Files.newBufferedReader(path, StandardCharsets.UTF_8).use { gson.fromJson(it, TransactionJournal::class.java) } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TransactionJournalRepository.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/TransactionJournalRepository.kt similarity index 78% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TransactionJournalRepository.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/TransactionJournalRepository.kt index 5b1a49c82..02832bd25 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TransactionJournalRepository.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/TransactionJournalRepository.kt @@ -1,8 +1,9 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.transaction import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.common.io.Digests +import org.pnfolder.pnlibrary.updates.engine.UpdatePaths import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths @@ -14,6 +15,7 @@ import kotlin.streams.toList internal class TransactionJournalRepository( private val root: Path, private val publicationRoot: Path, + private val warn: (String) -> Unit = {}, ) { /** Lists every `journal.json` found in a direct child directory of the root. */ fun journals(): List { @@ -26,6 +28,16 @@ internal class TransactionJournalRepository( } } + /** Loads every readable journal; an empty, corrupt or foreign one is reported through the warning callback and skipped. */ + fun loadAll(): List> = journals().mapNotNull { path -> + try { + path to load(path) + } catch (error: Exception) { + warn("Журнал обновления $path нечитаем и пропущен: ${error.message ?: error.javaClass.simpleName}") + null + } + } + /** Loads the journal at [path] after checking its location, size, and contents. */ fun load(path: Path): TransactionJournal { val normalized = checkedPath(path, root) @@ -64,8 +76,10 @@ internal class TransactionJournalRepository( require(targets.distinct().size == targets.size) { "Transaction contains duplicate targets" } } + /** Writes the journal durably. */ fun save(path: Path, journal: TransactionJournal) = TransactionJournal.save(path, journal) + /** Moves the journal to [state] and persists it. */ fun transition(path: Path, journal: TransactionJournal, state: TransactionState) { journal.state = state save(path, journal) @@ -77,6 +91,15 @@ internal class TransactionJournalRepository( ((record.backupSha256 ?: record.prior?.sha256)?.let { digest(Paths.get(record.backup)) == it } ?: true)) } + /** Like [hasRollbackData], but an unreadable backup file is reported through the warning callback and counts as missing. */ + fun hasReadableRollbackData(path: Path, journal: TransactionJournal): Boolean = try { + hasRollbackData(journal) + } catch (error: java.io.IOException) { + warn("Резервные файлы набора $path нечитаемы: ${error.message ?: error.javaClass.simpleName}") + false + } + + /** SHA-256 of the file at [path]. */ fun digest(path: Path): String = Digests.sha256(path) /** Normalizes [path] and requires it to stay inside [allowedRoot]. */ diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateProcessSession.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/UpdateProcessSession.kt similarity index 78% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateProcessSession.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/UpdateProcessSession.kt index 051dce055..670bd2a89 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateProcessSession.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/UpdateProcessSession.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.transaction import java.util.UUID diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateTransaction.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/UpdateTransaction.kt similarity index 90% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateTransaction.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/UpdateTransaction.kt index e088bd6a9..aca85f254 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateTransaction.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/UpdateTransaction.kt @@ -1,7 +1,10 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.transaction import org.pnfolder.pnlibrary.common.io.AtomicFiles import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.updates.engine.catalog.RollbackCatalog +import org.pnfolder.pnlibrary.updates.engine.catalog.isRestorable +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactVerifier import java.nio.file.FileSystemException import java.nio.file.Files import java.nio.file.Path @@ -14,9 +17,10 @@ internal class UpdateTransaction( private val root: Path, private val verifier: ArtifactVerifier, publicationRoot: Path = root.toAbsolutePath().normalize().parent, + warn: (String) -> Unit = {}, ) { private val publicationRoot = publicationRoot.toAbsolutePath().normalize() - private val journals = TransactionJournalRepository(root, this.publicationRoot) + private val journals = TransactionJournalRepository(root, this.publicationRoot, warn) private val health = TransactionHealth(root, journals) private val rollbacks = RollbackCatalog(root, journals) @@ -110,12 +114,16 @@ internal class UpdateTransaction( /** Returns transactions waiting for post-restart product-version confirmation. */ fun awaitingHealth(): List = health.awaiting() + /** Rollbacks that were applied and still wait for a health check. */ internal fun awaitingRollbackHealth(): List = health.awaitingRollback() + /** Records the health result of the rollback journal at [path]. */ internal fun completeRollbackHealth(path: Path, healthy: Boolean) = health.completeRollback(path, healthy) + /** Whether no unhealthy update transaction involves [products]. */ internal fun automaticUpdatesHealthy(products: Set): Boolean = health.automaticUpdatesHealthy(products) + /** Transactions whose health check failed. */ internal fun failedHealthChecks(): List = health.failed() /** Recovers an interrupted transaction, rolling back unsafe publication states. */ @@ -158,17 +166,17 @@ internal class UpdateTransaction( */ fun recoverAll(): List { if (!Files.isDirectory(root)) return emptyList() - val paths = journals.journals() - require(paths.none { blocksServerStart(journals.load(it)) }) { + val readable = journals.loadAll() + require(readable.none { (_, journal) -> blocksServerStart(journal) }) { "interrupted offline installation must be recovered before starting the server" } - return paths.filter { journals.load(it).purpose in SAVED_SET_PURPOSES }.sorted().map(::recover) + return readable.filter { (_, journal) -> journal.purpose in SAVED_SET_PURPOSES }.map { it.first }.sorted().map(::recover) } /** Recovers every journal, internal installations included; called only by the offline installer. */ fun recoverAllOffline(): List { if (!Files.isDirectory(root)) return emptyList() - return journals.journals().sorted().map(::recover) + return journals.loadAll().map { it.first }.sorted().map(::recover) } private fun interruptedInstallation(journal: TransactionJournal): Boolean = @@ -215,27 +223,30 @@ internal class UpdateTransaction( private fun publishingCopy(target: Path): Path = target.resolveSibling("${target.fileName}.publishing") + /** Loads the journal at [path]. */ internal fun readJournal(path: Path): TransactionJournal = journals.load(path) - internal fun pendingInstallations(): List = journals.journals().filter { path -> - val journal = journals.load(path) + /** Saved-set journals that were applied but not yet installed or restored. */ + internal fun pendingInstallations(): List = journals.loadAll().filter { (_, journal) -> journal.purpose in SAVED_SET_PURPOSES && ( (journal.state == TransactionState.AWAITING_HEALTH && journal.appliedOperation != "INSTALL") || (journal.state == TransactionState.ROLLED_BACK && journal.rollbackRequested && journal.appliedOperation != "RESTORE") ) - } + }.map { it.first } - internal fun appliedChildJournal(parent: UUID, purpose: String): Path? = journals.journals().firstOrNull { path -> - val journal = journals.load(path) + /** The committed journal of [purpose] that belongs to [parent], if any. */ + internal fun appliedChildJournal(parent: UUID, purpose: String): Path? = journals.loadAll().firstOrNull { (_, journal) -> journal.parentTransaction == parent.toString() && journal.purpose == purpose && journal.state == TransactionState.COMMITTED - } + }?.first + /** Rolls back an internal installation transaction. */ internal fun revertInstallation(path: Path) { val journal = journals.load(path) require(journal.purpose in INTERNAL_PURPOSES) { "Not an internal installation transaction" } rollbackInternal(path, journal) } + /** Remembers that [operation] was applied for the journal at [path]. */ internal fun markInstalled(path: Path, operation: String) { require(operation in INTERNAL_PURPOSES) val journal = journals.load(path) diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/BackupItemText.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/BackupItemText.kt new file mode 100644 index 000000000..a16c3b3cd --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/BackupItemText.kt @@ -0,0 +1,32 @@ +package org.pnfolder.pnlibrary.updates.history + +import org.pnfolder.pnlibrary.api.updates.backup.BackupKind +import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackupItem +import java.util.Locale + +/** How a saved file is shown to an administrator: "example: База данных «Игроки» · 12.5 МБ". */ +object BackupItemText { + /** The name of a kind of saved file. */ + fun kind(kind: BackupKind): String = when (kind) { + BackupKind.CONFIGURATION -> "Конфигурация" + BackupKind.DATABASE -> "База данных" + BackupKind.PLAYER_DATA -> "Данные игроков" + BackupKind.OTHER -> "Файл" + } + + /** [bytes] as bytes, KB or MB. */ + fun size(bytes: Long): String = when { + bytes >= MB -> String.format(Locale.ROOT, "%.1f МБ", bytes.toDouble() / MB) + bytes >= KB -> String.format(Locale.ROOT, "%.1f КБ", bytes.toDouble() / KB) + else -> "$bytes Б" + } + + /** One line about [item]: product, kind, name and size. */ + fun describe(item: UpdateBackupItem): String { + val title = if (item.name.isBlank()) kind(item.kind) else "${kind(item.kind)} «${item.name}»" + return "${item.product}: $title · ${size(item.bytes)}" + } + + private const val KB = 1024L + private const val MB = 1024L * 1024 +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/BackupStorage.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/BackupStorage.kt new file mode 100644 index 000000000..555811c01 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/BackupStorage.kt @@ -0,0 +1,54 @@ +package org.pnfolder.pnlibrary.updates.history + +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption +import java.time.Duration +import java.time.Instant + +/** Disk space of saved rollback sets and their removal. */ +internal object BackupStorage { + /** Rollback sets older than this are removed on their own. */ + val RETENTION: Duration = Duration.ofDays(30) + + /** A set this large is reported to the administrator, who can delete it. */ + const val LARGE_BYTES: Long = 500L * 1024 * 1024 + + /** Total size of the files under [folder]; 0 when it does not exist. */ + fun bytes(folder: Path): Long { + if (!Files.isDirectory(folder)) return 0 + return Files.walk(folder).use { paths -> paths.filter(Files::isRegularFile).mapToLong(Files::size).sum() } + } + + /** True when a set created at [createdAt] has outlived [RETENTION]; a set with no date is kept. */ + fun expired(createdAt: Instant?, now: Instant): Boolean = createdAt != null && createdAt.plus(RETENTION).isBefore(now) + + /** Removes [folder] with everything in it; does nothing when it does not exist. */ + fun delete(folder: Path) { + if (!Files.isDirectory(folder)) return + Files.walk(folder).use { paths -> paths.sorted(Comparator.reverseOrder()).forEach(Files::delete) } + } + + /** The folder of [name] inside [parent], whatever its letter case, or null when there is none. */ + fun child(parent: Path, name: String): Path? { + if (!Files.isDirectory(parent)) return null + return Files.list(parent).use { paths -> + paths.filter { Files.isDirectory(it) && it.fileName.toString().equals(name, ignoreCase = true) }.findFirst().orElse(null) + } + } + + /** Copies every file under [from] into [to], keeping the folder structure. */ + fun copy(from: Path, to: Path) { + Files.walk(from).use { paths -> + paths.forEach { path -> + val target = to.resolve(from.relativize(path).toString()) + if (Files.isDirectory(path)) { + PrivateFiles.directories(target) + } else { + PrivateFiles.directories(target.parent) + Files.copy(path, target, StandardCopyOption.REPLACE_EXISTING) + } + } + } + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/history/ConfigurationRestorer.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/ConfigurationRestorer.kt similarity index 89% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/history/ConfigurationRestorer.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/ConfigurationRestorer.kt index 33d370133..f1a7e5302 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/history/ConfigurationRestorer.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/ConfigurationRestorer.kt @@ -1,12 +1,13 @@ -package org.pnfolder.pnlibrary.core.updates.history +package org.pnfolder.pnlibrary.updates.history import com.google.gson.Gson -import org.pnfolder.pnlibrary.api.updates.ProductId +import org.pnfolder.pnlibrary.api.updates.backup.BackupLabel import org.pnfolder.pnlibrary.api.updates.backup.UpdateConfigurationBackup +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.common.io.AtomicFiles import org.pnfolder.pnlibrary.common.io.TextFiles import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.updates.engine.UpdatePaths +import org.pnfolder.pnlibrary.updates.engine.UpdatePaths import java.nio.charset.StandardCharsets.UTF_8 import java.nio.file.FileSystems import java.nio.file.Files @@ -18,8 +19,12 @@ import java.nio.file.attribute.PosixFilePermissions import java.util.UUID import kotlin.streams.toList -/** Offline-only restoration engine. Runtime commands must queue work, never call this on live files. */ +/** + * Offline-only restoration engine. Runtime commands must queue work, never call this on live files. + * Every restore is journaled, so one interrupted by a crash is rolled back to the state kept before it. + */ internal class ConfigurationRestorer(private val snapshots: ConfigurationSnapshots, private val directory: Path) { + /** The progress of one restore, saved after each step; [state] says how far it got. */ data class Journal(val id: String, val source: String, val before: String, var state: String, val operation: String? = null) private val gson = Gson() @@ -33,7 +38,10 @@ internal class ConfigurationRestorer(private val snapshots: ConfigurationSnapsho } val declarations = snapshot.files.groupBy { it.product }.map { (product, files) -> require(files.map { it.root }.distinct().size == 1) { "Component has conflicting configuration roots" } - ProductId.of(product) to UpdateConfigurationBackup(Paths.get(files.first().root), files.map { it.relative }) + ProductId.of(product) to UpdateConfigurationBackup( + Paths.get(files.first().root), files.map { it.relative }, + files.associate { it.relative to BackupLabel(it.backupKind, it.name.orEmpty()) }, + ) }.toMap() val before = requireNotNull(snapshots.capture(UUID.fromString(snapshot.planId), declarations)) val id = UUID.randomUUID() diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/history/ConfigurationSnapshots.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/ConfigurationSnapshots.kt similarity index 57% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/history/ConfigurationSnapshots.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/ConfigurationSnapshots.kt index 023b424c7..a868de4ad 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/history/ConfigurationSnapshots.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/ConfigurationSnapshots.kt @@ -1,11 +1,14 @@ -package org.pnfolder.pnlibrary.core.updates.history +package org.pnfolder.pnlibrary.updates.history import com.google.gson.Gson -import org.pnfolder.pnlibrary.api.updates.ProductId +import org.pnfolder.pnlibrary.api.updates.backup.BackupKind +import org.pnfolder.pnlibrary.api.updates.backup.BackupLabel import org.pnfolder.pnlibrary.api.updates.backup.UpdateConfigurationBackup +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.common.io.AtomicFiles import org.pnfolder.pnlibrary.common.io.TextFiles -import org.pnfolder.pnlibrary.core.updates.engine.UpdatePaths +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.updates.engine.UpdatePaths import java.nio.channels.FileChannel import java.nio.charset.StandardCharsets.UTF_8 import java.nio.file.FileSystems @@ -27,54 +30,97 @@ internal class ConfigurationSnapshots( private val pluginsDirectory: Path, private val maximumFileBytes: Long = 4L * 1024 * 1024, private val maximumTotalBytes: Long = 16L * 1024 * 1024, + private val maximumDataFileBytes: Long = 1024L * 1024 * 1024, + private val maximumDataTotalBytes: Long = 4L * 1024 * 1024 * 1024, ) { + /** One file of a snapshot: where it lives, and the saved copy ([blob]) with its size and checksum. */ data class FileRecord(val product: String, val root: String, val relative: String, val existed: Boolean, - val blob: String?, val size: Long, val sha256: String?) + val blob: String?, val size: Long, val sha256: String?, val kind: String? = null, val name: String? = null) { + /** What the file holds; snapshots from older versions held configuration only. */ + val backupKind: BackupKind get() = kind?.let(BackupKind::valueOf) ?: BackupKind.CONFIGURATION + } + /** The manifest of a snapshot: the plan it was taken for and its files. */ data class Snapshot(val schema: Int, val id: String, val planId: String, val createdAt: String, val files: List) private val gson = Gson() - init { require(maximumFileBytes > 0 && maximumTotalBytes > 0) } + init { require(maximumFileBytes > 0 && maximumTotalBytes > 0 && maximumDataFileBytes > 0 && maximumDataTotalBytes > 0) } + + private fun fileLimit(kind: BackupKind) = if (kind == BackupKind.CONFIGURATION) maximumFileBytes else maximumDataFileBytes + /** Saves the selected files of [selections] for [planId]; returns the snapshot id, or null when nothing is selected. */ fun capture(planId: UUID, selections: Map): UUID? { if (selections.isEmpty()) return null require(selections.values.sumOf { it.files.size } <= 100) { "Configuration snapshot exceeds 100 files" } - val sources = selections.flatMap { (product, selection) -> selection.files.map { relative -> - Triple(product, selection, relative) to checkedSource(selection.root, relative) - } } - require(sources.map { it.second }.distinct().size == sources.size) { "Configuration files overlap across components" } + val sources = selections.flatMap { (product, selection) -> + selection.files.map { relative -> Source(product, selection, relative, checkedSource(selection.root, relative)) } + } + require(sources.map { it.path }.distinct().size == sources.size) { "Configuration files overlap across components" } val id = UUID.randomUUID() val target = directory.toAbsolutePath().normalize().resolve(id.toString()) UpdatePaths.inside(target.resolve("manifest.json"), directory) Files.createDirectories(directory) + createPrivateDirectory(target) + try { + val snapshot = Snapshot(1, id.toString(), planId.toString(), Instant.now().toString(), copyAll(sources, target)) + writeManifest(target, snapshot) + } catch (error: Throwable) { + runCatchingNonFatal { BackupStorage.delete(target) }.onFailure(error::addSuppressed) + throw error + } + return id + } + + private class Source(val product: ProductId, val request: UpdateConfigurationBackup, val relative: String, val path: Path) + + private fun createPrivateDirectory(target: Path) { if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) { Files.createDirectory(target, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))) - } else Files.createDirectory(target) - var total = 0L - val records = sources.mapIndexed { index, (selection, source) -> - val (product, request, relative) = selection - if (!Files.exists(source, LinkOption.NOFOLLOW_LINKS)) { - FileRecord(product.value, request.root.toString(), relative, false, null, 0, null) - } else { - val before = Files.readAttributes(source, BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS) - require(before.isRegularFile) { "Configuration selection must name a regular file" } - val limit = minOf(maximumFileBytes, maximumTotalBytes - total) - require(before.size() <= limit) { "Configuration snapshot exceeds size limit" } - val blob = index.toString().padStart(4, '0') + ".bin" - val (size, hash) = copyBounded(source, target.resolve(blob), limit) - val after = Files.readAttributes(source, BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS) - require(before.size() == after.size() && before.lastModifiedTime() == after.lastModifiedTime() && before.fileKey() == after.fileKey()) { - "Configuration changed while being captured" - } - total += size - FileRecord(product.value, request.root.toString(), relative, true, blob, size, hash) + } else { + Files.createDirectory(target) + } + } + + private fun copyAll(sources: List, target: Path): List { + var configurationTotal = 0L + var dataTotal = 0L + return sources.mapIndexed { index, source -> + val label = source.request.labelOf(source.relative) + if (!Files.exists(source.path, LinkOption.NOFOLLOW_LINKS)) { + return@mapIndexed FileRecord( + source.product.value, source.request.root.toString(), source.relative, false, null, 0, null, + label.kind.name, label.name, + ) } + val isConfiguration = label.kind == BackupKind.CONFIGURATION + val room = if (isConfiguration) maximumTotalBytes - configurationTotal else maximumDataTotalBytes - dataTotal + val blob = index.toString().padStart(4, '0') + ".bin" + val record = copyFile(source, label, blob, target, minOf(fileLimit(label.kind), room)) + if (isConfiguration) configurationTotal += record.size else dataTotal += record.size + record } - val snapshot = Snapshot(1, id.toString(), planId.toString(), Instant.now().toString(), records) + } + + /** Copies one existing file and fails when it changed while it was being read. */ + private fun copyFile(source: Source, label: BackupLabel, blob: String, target: Path, limit: Long): FileRecord { + val before = Files.readAttributes(source.path, BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS) + require(before.isRegularFile) { "Configuration selection must name a regular file" } + require(before.size() <= limit) { "Backup of ${source.relative} exceeds the size limit" } + val (size, hash) = copyBounded(source.path, target.resolve(blob), limit) + val after = Files.readAttributes(source.path, BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS) + require(before.size() == after.size() && before.lastModifiedTime() == after.lastModifiedTime() && before.fileKey() == after.fileKey()) { + "Configuration changed while being captured" + } + return FileRecord( + source.product.value, source.request.root.toString(), source.relative, true, blob, size, hash, + label.kind.name, label.name, + ) + } + + private fun writeManifest(target: Path, snapshot: Snapshot) { val temporary = target.resolve("manifest.tmp") TextFiles.write(temporary, gson.toJson(snapshot), UTF_8) FileChannel.open(temporary, StandardOpenOption.WRITE).use { it.force(true) } AtomicFiles.move(temporary, target.resolve("manifest.json"), replaceExisting = false) - return id } /** Validates the complete manifest and every backup byte before any restoration may begin. */ @@ -89,19 +135,21 @@ internal class ConfigurationSnapshots( require(snapshot.files.isNotEmpty() && snapshot.files.size <= 100) { "Invalid configuration file count" } val sources = mutableSetOf() val blobs = mutableSetOf() - var total = 0L + var configurationTotal = 0L + var dataTotal = 0L snapshot.files.forEach { file -> ProductId.of(file.product) val declaration = UpdateConfigurationBackup(Paths.get(file.root), listOf(file.relative)) require(sources.add(checkedSource(declaration.root, declaration.files.single()))) { "Duplicate configuration target" } - require(file.size in 0..maximumFileBytes) { "Invalid configuration size" } - total += file.size - require(total <= maximumTotalBytes) { "Configuration snapshot exceeds size limit" } + val kind = file.backupKind + require(file.size in 0..fileLimit(kind)) { "Invalid backup size" } + if (kind == BackupKind.CONFIGURATION) configurationTotal += file.size else dataTotal += file.size + require(configurationTotal <= maximumTotalBytes && dataTotal <= maximumDataTotalBytes) { "Backup snapshot exceeds size limit" } if (file.existed) { require(file.blob != null && file.blob.matches(Regex("[0-9]{4}\\.bin")) && blobs.add(file.blob)) { "Invalid configuration blob" } val blob = UpdatePaths.inside(folder.resolve(file.blob), folder) require(Files.isRegularFile(blob, LinkOption.NOFOLLOW_LINKS) && Files.size(blob) == file.size) { "Configuration backup size mismatch" } - require(hash(blob) == file.sha256) { "Configuration backup checksum mismatch" } + require(hash(blob, fileLimit(kind)) == file.sha256) { "Configuration backup checksum mismatch" } } else require(file.blob == null && file.sha256 == null && file.size == 0L) { "Invalid absent configuration record" } } return snapshot @@ -113,6 +161,7 @@ internal class ConfigurationSnapshots( return UpdatePaths.inside(source, pluginsDirectory) } + /** The live path a [file] record would be restored to, checked to stay inside the plugins folder. */ fun target(file: FileRecord): Path = checkedSource(Paths.get(file.root), file.relative) /** Copies a validated blob to a temporary file, checking its bytes again during the copy. */ @@ -146,7 +195,7 @@ internal class ConfigurationSnapshots( return count to hex(digest.digest()) } - private fun hash(path: Path): String { + private fun hash(path: Path, limit: Long): String { val digest = MessageDigest.getInstance("SHA-256") Files.newInputStream(path, LinkOption.NOFOLLOW_LINKS).use { input -> val buffer = ByteArray(8192) @@ -155,7 +204,7 @@ internal class ConfigurationSnapshots( val read = input.read(buffer) if (read < 0) break total += read - require(total <= maximumFileBytes) { "Configuration backup exceeds size limit" } + require(total <= limit) { "Configuration backup exceeds size limit" } digest.update(buffer, 0, read) } } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/PrivateFiles.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/PrivateFiles.kt new file mode 100644 index 000000000..df1669b00 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/PrivateFiles.kt @@ -0,0 +1,30 @@ +package org.pnfolder.pnlibrary.updates.history + +import java.io.OutputStream +import java.nio.file.FileSystems +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.attribute.FileAttribute +import java.nio.file.attribute.PosixFilePermissions + +/** Creates copies readable by the server user only: databases and exports hold passwords and player data. */ +internal object PrivateFiles { + private val posix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix") + private val directoryAttributes = attributes("rwx------") + private val fileAttributes = attributes("rw-------") + + /** Creates [directory] and its missing parents with `rwx------` where the file system has POSIX permissions. */ + fun directories(directory: Path) { + Files.createDirectories(directory, *directoryAttributes) + } + + /** Opens [file] anew with `rw-------`; the mode is set at creation, so the content is never readable by others. */ + fun output(file: Path): OutputStream { + Files.deleteIfExists(file) + Files.createFile(file, *fileAttributes) + return Files.newOutputStream(file) + } + + private fun attributes(mode: String): Array> = + if (posix) arrayOf(PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(mode))) else emptyArray() +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/history/UpdateEventJournal.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/UpdateEventJournal.kt similarity index 92% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/history/UpdateEventJournal.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/UpdateEventJournal.kt index db0a91ee8..6d5c87cfb 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/history/UpdateEventJournal.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/UpdateEventJournal.kt @@ -1,17 +1,17 @@ -package org.pnfolder.pnlibrary.core.updates.history +package org.pnfolder.pnlibrary.updates.history import com.google.gson.JsonArray import com.google.gson.JsonObject import com.google.gson.JsonParser -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.common.io.AtomicFiles import org.pnfolder.pnlibrary.common.io.TextFiles -import org.pnfolder.pnlibrary.core.updates.install.ComponentLedger -import org.pnfolder.pnlibrary.core.updates.service.UpdateHealthReport +import org.pnfolder.pnlibrary.updates.install.ComponentOperation +import org.pnfolder.pnlibrary.updates.service.UpdateHealthReport import java.nio.charset.StandardCharsets.UTF_8 import java.nio.file.Files import java.nio.file.LinkOption @@ -36,8 +36,10 @@ internal class UpdateEventJournal( private val maxAge: Duration = Duration.ofDays(DEFAULT_MAX_AGE_DAYS), private val maxEvents: Int = DEFAULT_MAX_EVENTS, ) { + /** A product that moved from [from] (null when it was absent) to [to]. */ data class Change(val product: String, val from: String?, val to: String) + /** One journal entry: what was observed for a plan, who caused it and which products changed. */ data class Event( val id: UUID, val occurredAt: Instant, @@ -240,12 +242,15 @@ internal class UpdateEventJournal( } private companion object { + /** Events older than this many days are pruned. */ const val DEFAULT_MAX_AGE_DAYS = 90L + /** Newest events kept when there are more. */ const val DEFAULT_MAX_EVENTS = 1_000 + /** Pruning runs once per this many writes. */ const val PRUNE_EVERY_WRITES = 25 val COMPONENT_OPERATIONS = setOf( - ComponentLedger.OPERATION_ADDED, ComponentLedger.OPERATION_REMOVED, - ComponentLedger.OPERATION_VERSION_CHANGED, ComponentLedger.OPERATION_SETTINGS_CHANGED, + ComponentOperation.ADDED, ComponentOperation.REMOVED, + ComponentOperation.VERSION_CHANGED, ComponentOperation.SETTINGS_CHANGED, ) val OPERATIONS = setOf("STATE_OBSERVED", "CHECK", "STAGE", "ROLLBACK", "HEALTH", "HEALTH_ROLLBACK") + COMPONENT_OPERATIONS } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/history/UpdateStateStore.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/UpdateStateStore.kt similarity index 94% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/history/UpdateStateStore.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/UpdateStateStore.kt index d0db50c92..516e05593 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/history/UpdateStateStore.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/history/UpdateStateStore.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.history +package org.pnfolder.pnlibrary.updates.history import com.google.gson.Gson import com.google.gson.GsonBuilder @@ -8,11 +8,11 @@ import com.google.gson.JsonObject import com.google.gson.JsonParser import com.google.gson.JsonPrimitive import com.google.gson.JsonSerializer -import org.pnfolder.pnlibrary.api.updates.BlockedReason -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.updates.release.UpdatePlan +import org.pnfolder.pnlibrary.api.updates.state.BlockedReason +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.common.io.AtomicFiles @@ -51,6 +51,7 @@ internal class UpdateStateStore( } @Synchronized + /** Writes [snapshot] as the current state and into the history, then trims the history. */ fun save(snapshot: UpdatePlanSnapshot) { val bytes = encode(snapshot) writeAtomic(stateFile, bytes) @@ -58,8 +59,10 @@ internal class UpdateStateStore( prune() } + /** The saved current state; an unreadable file is moved aside and null is returned. */ fun current(): UpdatePlanSnapshot? = read(stateFile, quarantine = true) + /** Earlier states, newest first; unreadable ones are skipped. */ fun history(): List = historyFiles().mapNotNull { read(it, quarantine = false) } private fun read(path: Path, quarantine: Boolean): UpdatePlanSnapshot? { diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/ComponentLedger.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/ComponentLedger.kt similarity index 82% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/ComponentLedger.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/ComponentLedger.kt index 81031225d..b638b6ada 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/ComponentLedger.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/ComponentLedger.kt @@ -1,10 +1,10 @@ -package org.pnfolder.pnlibrary.core.updates.install +package org.pnfolder.pnlibrary.updates.install import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import org.pnfolder.pnlibrary.common.io.AtomicFiles import org.pnfolder.pnlibrary.common.io.TextFiles -import org.pnfolder.pnlibrary.core.updates.history.UpdateEventJournal +import org.pnfolder.pnlibrary.updates.history.UpdateEventJournal import java.nio.charset.StandardCharsets.UTF_8 import java.nio.file.Files import java.nio.file.Path @@ -39,16 +39,16 @@ internal class ComponentLedger( current.toSortedMap().forEach { (product, now) -> val before = previous[product] when { - before == null -> journal.recordComponent(OPERATION_ADDED, product, null, now.version, null) + before == null -> journal.recordComponent(ComponentOperation.ADDED, product, null, now.version, null) before.version != now.version && product !in verifiedByHealth -> - journal.recordComponent(OPERATION_VERSION_CHANGED, product, before.version, now.version, null) + journal.recordComponent(ComponentOperation.VERSION_CHANGED, product, before.version, now.version, null) } if (before != null) describeSettings(before, now)?.let { message -> - journal.recordComponent(OPERATION_SETTINGS_CHANGED, product, now.version, now.version, message) + journal.recordComponent(ComponentOperation.SETTINGS_CHANGED, product, now.version, now.version, message) } } previous.toSortedMap().filterKeys { it !in current }.forEach { (product, before) -> - journal.recordComponent(OPERATION_REMOVED, product, before.version, before.version, null) + journal.recordComponent(ComponentOperation.REMOVED, product, before.version, before.version, null) } } save(current) @@ -96,11 +96,4 @@ internal class ComponentLedger( Files.deleteIfExists(temporary) } } - - internal companion object { - const val OPERATION_ADDED = "COMPONENT_ADDED" - const val OPERATION_REMOVED = "COMPONENT_REMOVED" - const val OPERATION_VERSION_CHANGED = "VERSION_CHANGED" - const val OPERATION_SETTINGS_CHANGED = "SETTINGS_CHANGED" - } } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/ComponentOperation.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/ComponentOperation.kt new file mode 100644 index 000000000..5a77db26c --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/ComponentOperation.kt @@ -0,0 +1,9 @@ +package org.pnfolder.pnlibrary.updates.install + +/** Operation names the component ledger writes to the update history. */ +object ComponentOperation { + const val ADDED = "COMPONENT_ADDED" + const val REMOVED = "COMPONENT_REMOVED" + const val VERSION_CHANGED = "VERSION_CHANGED" + const val SETTINGS_CHANGED = "SETTINGS_CHANGED" +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/OfflineUpdateInstaller.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/OfflineUpdateInstaller.kt similarity index 55% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/OfflineUpdateInstaller.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/OfflineUpdateInstaller.kt index 0eac7974e..37bb8c808 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/OfflineUpdateInstaller.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/OfflineUpdateInstaller.kt @@ -1,18 +1,20 @@ -package org.pnfolder.pnlibrary.core.updates.install +package org.pnfolder.pnlibrary.updates.install -import org.pnfolder.pnlibrary.api.updates.ProductId +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.updates.engine.ArtifactSpecification -import org.pnfolder.pnlibrary.core.updates.engine.ArtifactVerifier -import org.pnfolder.pnlibrary.core.updates.engine.TransactionArtifact -import org.pnfolder.pnlibrary.core.updates.engine.TransactionState -import org.pnfolder.pnlibrary.core.updates.engine.UpdatePaths -import org.pnfolder.pnlibrary.core.updates.engine.UpdateTransaction -import org.pnfolder.pnlibrary.core.updates.history.ConfigurationRestorer -import org.pnfolder.pnlibrary.core.updates.history.ConfigurationSnapshots -import org.pnfolder.pnlibrary.core.updates.service.UpdateInstallationLock +import org.pnfolder.pnlibrary.updates.engine.UpdatePaths +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactSpecification +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactVerifier +import org.pnfolder.pnlibrary.updates.engine.transaction.TransactionArtifact +import org.pnfolder.pnlibrary.updates.engine.transaction.TransactionState +import org.pnfolder.pnlibrary.updates.engine.transaction.UpdateTransaction +import org.pnfolder.pnlibrary.updates.history.ConfigurationRestorer +import org.pnfolder.pnlibrary.updates.history.ConfigurationSnapshots +import org.pnfolder.pnlibrary.updates.paths.LegacyPathsMigration +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import org.pnfolder.pnlibrary.updates.service.UpdateInstallationLock import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths @@ -30,51 +32,59 @@ object OfflineUpdateInstaller { println("Applied $applied prepared component sets. Start the server to verify loaded versions.") } - internal fun apply(dataDirectory: Path): Int { - val data = dataDirectory.toAbsolutePath().normalize() + /** Installs every prepared set found in the plugin folder [pluginFolder] and returns how many were applied. */ + internal fun apply(pluginFolder: Path): Int { + val data = pluginFolder.toAbsolutePath().normalize() require(Files.isDirectory(data) && data.parent != null) { "Library data directory does not exist" } - return UpdateInstallationLock.acquire(data).use { - val plugins = data.parent + val layout = LibraryPaths(data) + LegacyPathsMigration(layout) { System.err.println(it) }.run() + return UpdateInstallationLock.acquire(layout).use { + val plugins = layout.plugins val verifier = ArtifactVerifier(512L * 1024 * 1024) - val transactions = UpdateTransaction(data.resolve("updates/transactions"), verifier, plugins) - val snapshots = ConfigurationSnapshots(data.resolve("updates/configurations"), plugins) - val restorer = ConfigurationRestorer(snapshots, data.resolve("updates/configuration-restores")) + val transactions = UpdateTransaction(layout.transactions, verifier, plugins) + val snapshots = ConfigurationSnapshots(layout.configurations, plugins) + val restorer = ConfigurationRestorer(snapshots, layout.configurationRestores) restorer.recoverInterrupted() transactions.recoverAllOffline() val pending = transactions.pendingInstallations().map { path -> prepare(transactions, verifier, snapshots, plugins, path) } require(pending.flatMap { it.artifacts }.map { it.target }.distinct().size == pending.sumOf { it.artifacts.size }) { "Conflicting prepared component sets; resolve them before starting the server" } - pending.forEach { prepared -> - val child = transactions.appliedChildJournal(prepared.id, prepared.purpose) ?: run { - val result = transactions.prepareForRestart(prepared.artifacts, purpose = prepared.purpose, parentTransaction = prepared.id) - // This child commits disk publication, not server/plugin health. - transactions.completeHealth(result.journal, true) - result.journal - } - var restoredConfigurations: UUID? = null - try { - restoredConfigurations = prepared.configurationSnapshot?.let { restorer.restore(it, prepared.id) } - prepared.pendingFiles.zip(prepared.artifacts).forEach { (file, artifact) -> - if (Files.exists(file)) { - verifier.verify(file, artifact.specification.copy(fileName = file.fileName.toString())) - Files.delete(file) - } - } - transactions.markInstalled(prepared.journal, prepared.purpose) - } catch (error: Throwable) { - restoredConfigurations?.let { runCatchingNonFatal { restorer.undo(it) }.onFailure(error::addSuppressed) } - runCatchingNonFatal { transactions.revertInstallation(child) }.onFailure(error::addSuppressed) - throw error + pending.forEach { install(it, transactions, verifier, restorer) } + pending.size + } + } + + /** Publishes one prepared set; on failure the configurations and JARs it touched are put back. */ + private fun install(prepared: Prepared, transactions: UpdateTransaction, verifier: ArtifactVerifier, restorer: ConfigurationRestorer) { + val child = transactions.appliedChildJournal(prepared.id, prepared.purpose) ?: run { + val result = transactions.prepareForRestart(prepared.artifacts, purpose = prepared.purpose, parentTransaction = prepared.id) + // This child commits disk publication, not server/plugin health. + transactions.completeHealth(result.journal, true) + result.journal + } + var restoredConfigurations: UUID? = null + try { + restoredConfigurations = prepared.configurationSnapshot?.let { restorer.restore(it, prepared.id) } + prepared.pendingFiles.zip(prepared.artifacts).forEach { (file, artifact) -> + if (Files.exists(file)) { + verifier.verify(file, artifact.specification.copy(fileName = file.fileName.toString())) + Files.delete(file) } } - pending.size + transactions.markInstalled(prepared.journal, prepared.purpose) + } catch (error: Throwable) { + restoredConfigurations?.let { runCatchingNonFatal { restorer.undo(it) }.onFailure(error::addSuppressed) } + runCatchingNonFatal { transactions.revertInstallation(child) }.onFailure(error::addSuppressed) + throw error } } + /** A set whose files are checked and ready to be published. */ private data class Prepared(val id: UUID, val journal: Path, val purpose: String, val artifacts: List, val pendingFiles: List, val configurationSnapshot: UUID?) + /** Checks the journal and every artifact of a pending set before anything is touched. */ private fun prepare(transactions: UpdateTransaction, verifier: ArtifactVerifier, snapshots: ConfigurationSnapshots, plugins: Path, path: Path): Prepared { val journal = transactions.readJournal(path) val restoring = journal.state == TransactionState.ROLLED_BACK diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/ReleaseCatalogGateway.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/ReleaseCatalogGateway.kt similarity index 55% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/ReleaseCatalogGateway.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/ReleaseCatalogGateway.kt index 2ecf8b208..6014bc51f 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/ReleaseCatalogGateway.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/ReleaseCatalogGateway.kt @@ -1,12 +1,12 @@ -package org.pnfolder.pnlibrary.core.updates.install +package org.pnfolder.pnlibrary.updates.install import com.google.gson.JsonParser -import org.pnfolder.pnlibrary.api.updates.CatalogSource -import org.pnfolder.pnlibrary.core.updates.engine.RefreshMode -import org.pnfolder.pnlibrary.core.updates.engine.ReleaseCatalog -import org.pnfolder.pnlibrary.core.updates.engine.ReleaseCatalogClient -import org.pnfolder.pnlibrary.core.updates.engine.ReleaseCatalogCodec -import org.pnfolder.pnlibrary.core.updates.engine.TrustedHttpClient +import org.pnfolder.pnlibrary.api.updates.request.CatalogSource +import org.pnfolder.pnlibrary.updates.engine.catalog.RefreshMode +import org.pnfolder.pnlibrary.updates.engine.catalog.ReleaseCatalog +import org.pnfolder.pnlibrary.updates.engine.catalog.ReleaseCatalogClient +import org.pnfolder.pnlibrary.updates.engine.catalog.ReleaseCatalogCodec +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient import java.net.URI import java.util.Base64 import java.util.Collections @@ -17,7 +17,7 @@ import java.util.concurrent.atomic.AtomicInteger /** * Loads one release catalog through independent GitHub endpoints. * - * All endpoint probes run concurrently. The caller itself does not occupy the + * The GitHub endpoints run concurrently; jsDelivr is the last resort. The caller itself does not occupy the * request executor, preventing the nested-executor starvation that previously * made update checks wait forever when several products were registered. */ @@ -26,31 +26,38 @@ internal class ReleaseCatalogGateway( private val http: TrustedHttpClient, private val requestExecutor: Executor, ) { + /** + * Returns the first catalog GitHub raw or the Contents API delivers. jsDelivr caches for hours and may + * serve a stale catalog, so it is asked only when both GitHub endpoints failed. + */ fun load(source: CatalogSource, refreshMode: RefreshMode): ReleaseCatalog { val endpoints = CatalogEndpoints(source) val result = CompletableFuture() val failures = Collections.synchronizedList(mutableListOf()) - val remaining = AtomicInteger(ENDPOINT_COUNT) + val remaining = AtomicInteger(PRIMARY_ENDPOINT_COUNT) - submit("raw", result, failures, remaining, endpoints) { + val fallback = { + submit("jsDelivr", result, failures, endpoints = endpoints) { client.load(endpoints.cdn, RefreshMode.FORCE_REMOTE).join() } + } + submit("raw", result, failures, { onAllFailed(remaining, fallback) }) { client.load(endpoints.raw, refreshMode).join() } - submit("api", result, failures, remaining, endpoints) { + submit("api", result, failures, { onAllFailed(remaining, fallback) }) { loadFromContentsApi(endpoints.api) } - submit("jsDelivr", result, failures, remaining, endpoints) { - client.load(endpoints.cdn, RefreshMode.FORCE_REMOTE).join() - } - return result.join() } + private fun onAllFailed(remaining: AtomicInteger, fallback: () -> Unit) { + if (remaining.decrementAndGet() == 0) fallback() + } + private fun submit( label: String, result: CompletableFuture, failures: MutableList, - remaining: AtomicInteger, - endpoints: CatalogEndpoints, + onFailure: (() -> Unit)? = null, + endpoints: CatalogEndpoints? = null, request: () -> ReleaseCatalog, ) { CompletableFuture.supplyAsync(request, requestExecutor) @@ -61,16 +68,18 @@ internal class ReleaseCatalogGateway( } failures += "$label: ${failureMessage(error)}" - if (remaining.decrementAndGet() == 0) { - result.completeExceptionally( - IllegalStateException( - "Release catalog not found at ${endpoints.raw}; check the repository branch " + - "(PluginUpdateRequest.Builder.branch). " + - "Tried GitHub raw, Contents API and jsDelivr: " + failures.joinToString("; "), - error.cause ?: error, - ), - ) + if (onFailure != null) { + onFailure() + return@whenComplete } + result.completeExceptionally( + IllegalStateException( + "Release catalog not found at ${endpoints?.raw}; check the repository branch " + + "(PluginUpdateRequest.Builder.branch). " + + "Tried GitHub raw, Contents API and jsDelivr: " + failures.joinToString("; "), + error.cause ?: error, + ), + ) } } @@ -100,6 +109,7 @@ internal class ReleaseCatalogGateway( } private companion object { - const val ENDPOINT_COUNT = 3 + /** GitHub endpoints queried in parallel before jsDelivr is tried. */ + const val PRIMARY_ENDPOINT_COUNT = 2 } } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdateGraphResolver.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/UpdateGraphResolver.kt similarity index 75% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdateGraphResolver.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/UpdateGraphResolver.kt index 1c3344656..3406b8c05 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdateGraphResolver.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/UpdateGraphResolver.kt @@ -1,23 +1,23 @@ -package org.pnfolder.pnlibrary.core.updates.install +package org.pnfolder.pnlibrary.updates.install import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ProductRelease import org.pnfolder.pnlibrary.api.updates.release.UpdatePlan import org.pnfolder.pnlibrary.api.version.PnLibraryApi import org.pnfolder.pnlibrary.common.jvm.JavaRuntime import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.updates.engine.FreezeStore -import org.pnfolder.pnlibrary.core.updates.engine.RefreshMode -import org.pnfolder.pnlibrary.core.updates.engine.ResolutionResult -import org.pnfolder.pnlibrary.core.updates.engine.ResolverPolicy -import org.pnfolder.pnlibrary.core.updates.engine.UpdateResolver -import org.pnfolder.pnlibrary.core.updates.policy.UpdateConfiguration -import org.pnfolder.pnlibrary.core.updates.policy.UpdatePolicyOverrides -import org.pnfolder.pnlibrary.core.updates.service.RegisteredUpdate import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import org.pnfolder.pnlibrary.spi.platform.PlatformPluginInventory +import org.pnfolder.pnlibrary.updates.engine.FreezeStore +import org.pnfolder.pnlibrary.updates.engine.ResolutionResult +import org.pnfolder.pnlibrary.updates.engine.ResolverPolicy +import org.pnfolder.pnlibrary.updates.engine.UpdateResolver +import org.pnfolder.pnlibrary.updates.engine.catalog.RefreshMode +import org.pnfolder.pnlibrary.updates.policy.UpdateConfiguration +import org.pnfolder.pnlibrary.updates.policy.UpdatePolicyOverrides +import org.pnfolder.pnlibrary.updates.service.RegisteredUpdate /** Loads release catalogs and resolves one coherent update plan for all registered products. */ internal class UpdateGraphResolver( @@ -27,7 +27,9 @@ internal class UpdateGraphResolver( private val catalogs: ReleaseCatalogGateway, private val freezes: FreezeStore, private val overrides: UpdatePolicyOverrides? = null, + private val failure: (String, Throwable) -> Unit = { _, _ -> }, ) { + /** Resolves one plan for [registrations]; an empty list gives an empty plan. */ fun resolve( registrations: List, refreshMode: RefreshMode = RefreshMode.CACHED, @@ -42,16 +44,18 @@ internal class UpdateGraphResolver( releases = releases, channels = registrations.associate { it.descriptor.id to channelFor(it) }, defaultChannel = UpdateChannel.STABLE, - frozen = frozenProducts(registrations), + frozen = frozenProducts(), platform = identity.type, javaFeature = JavaRuntime.feature, policy = resolverPolicy(), ) } + /** The channel of [registration]: an administrator's override, the library's own setting, or what the plugin asked for. */ fun channelFor(registration: RegisteredUpdate): UpdateChannel = channelFor(registration.descriptor.id, registration.request.channel) + /** The channel of [product], or [fallback] when nothing overrides it. */ fun channelFor(product: ProductId, fallback: UpdateChannel): UpdateChannel = overrides?.channel(product.value) ?: if (product.value == PnLibraryIdentity.PRODUCT_ID) configuration.library.channel @@ -83,12 +87,7 @@ internal class UpdateGraphResolver( } } - private fun frozenProducts(registrations: List): Set { - val configuredFreezes = registrations.mapNotNull { registration -> - registration.descriptor.id.takeIf { registration.product in configuration.ignoredPlugins } - } - return (freezes.active().keys + configuredFreezes).toSet() - } + private fun frozenProducts(): Set = freezes.active().keys.toSet() private fun resolverPolicy() = ResolverPolicy( allowManagedInstalls = configuration.downloads.allowManagedPlugins && @@ -96,6 +95,7 @@ internal class UpdateGraphResolver( // An unreadable inventory makes external plugin dependencies count as missing, // so releases that need them are skipped instead of installed blindly. installedExternalPlugins = runCatchingNonFatal { inventory.installedPlugins() } + .onFailure { failure("Could not read the installed plugins; releases that need other plugins are skipped", it) } .getOrNull() .orEmpty() .keys, diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/UpdateInstaller.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/UpdateInstaller.kt new file mode 100644 index 000000000..73802e45d --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/UpdateInstaller.kt @@ -0,0 +1,309 @@ +package org.pnfolder.pnlibrary.updates.install + +import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity +import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup +import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackupComponent +import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackupItem +import org.pnfolder.pnlibrary.api.updates.backup.UpdateConfigurationBackup +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.release.ProductChange +import org.pnfolder.pnlibrary.api.updates.release.UpdatePlan +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState +import org.pnfolder.pnlibrary.api.version.SemanticVersion +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity +import org.pnfolder.pnlibrary.updates.databases.DatabaseBackups +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactVerifier +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient +import org.pnfolder.pnlibrary.updates.engine.transaction.PendingTransaction +import org.pnfolder.pnlibrary.updates.engine.transaction.TransactionJournal +import org.pnfolder.pnlibrary.updates.engine.transaction.UpdateProcessSession +import org.pnfolder.pnlibrary.updates.engine.transaction.UpdateTransaction +import org.pnfolder.pnlibrary.updates.history.BackupItemText +import org.pnfolder.pnlibrary.updates.history.BackupStorage +import org.pnfolder.pnlibrary.updates.history.ConfigurationSnapshots +import org.pnfolder.pnlibrary.updates.history.PrivateFiles +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import org.pnfolder.pnlibrary.updates.policy.UpdateConfiguration +import org.pnfolder.pnlibrary.updates.service.RegisteredUpdate +import org.pnfolder.pnlibrary.updates.service.UpdateHealthReport +import java.nio.file.Path +import java.time.Instant +import java.util.UUID + +/** + * Stages update files together with their safety copies, and verifies a staged transaction after the next server + * start. Also lists, prunes and applies the saved rollback sets. + */ +internal class UpdateInstaller( + platform: PlatformIdentity, + paths: LibraryPaths, + private val configuration: UpdateConfiguration, + http: TrustedHttpClient, + private val databases: DatabaseBackups, + private val javaChoice: (ProductId) -> Int? = { null }, + private val installedJava: (ProductId) -> Int? = { null }, + private val warn: (String) -> Unit = {}, +) { + private val configurationsFolder = paths.configurations + private val configurations = ConfigurationSnapshots(configurationsFolder, paths.plugins) + private val libraryConfiguration = UpdateConfigurationBackup(paths.pluginFolder, listOf(paths.pluginFolder.relativize(paths.settings).joinToString("/"))) + private val transactionsFolder = paths.transactions + private val exportsFolder = paths.exports + private val databasesFolder = paths.databases + private val handoutFolder = paths.handout + private val transaction = UpdateTransaction( + transactionsFolder, + ArtifactVerifier(configuration.downloads.maxArtifactBytes), + paths.plugins, + warn, + ) + private val stager = UpdatePlanStager( + platform = platform.type, + paths = paths, + http = http, + transaction = transaction, + maximumArtifactBytes = configuration.downloads.maxArtifactBytes, + requireSha256 = configuration.installation.requireSha256, + javaChoice = javaChoice, + installedJava = installedJava, + ) + + /** Finishes or rolls back transactions a crash interrupted, then drops sets past their retention. */ + fun recoverInterruptedTransactions() { + transaction.recoverAll() + pruneBackups() + } + + /** Removes saved sets older than the retention period, except those a restart still has to verify. Returns how many went. */ + fun pruneBackups(now: Instant = Instant.now()): Int { + val busy = busyBackups() + val old = transaction.rollbackCandidates().filter { path -> + val journal = TransactionJournal.load(path) + journal.id !in busy && BackupStorage.expired(journal.createdAt?.let(Instant::parse), now) + } + old.forEach(::removeBackup) + warnIfLarge() + return old.size + } + + /** Deletes one saved set with its configuration and data copies; a set that a restart still verifies is refused. */ + fun deleteBackup(id: UUID) { + val path = transaction.rollbackCandidate(id) + require(id.toString() !in busyBackups()) { "Набор $id ещё проверяется после перезапуска" } + removeBackup(path) + } + + /** Lets each plugin write its own copies; a plugin that fails stops the update, since the copy would be missing. */ + private fun runExports(planId: UUID, changed: List) { + changed.forEach { registration -> + if (registration.request.exports.isEmpty()) return@forEach + val folder = exportsFolder.resolve(planId.toString()).resolve(registration.product) + PrivateFiles.directories(folder) + registration.request.exports.forEach { export -> + try { + export.export(folder.resolve(export.fileName)) + } catch (error: Exception) { + BackupStorage.delete(exportsFolder.resolve(planId.toString())) + throw IllegalStateException("Плагин ${registration.product} не смог сохранить копию «${export.name}»: ${error.message}", error) + } + } + } + } + + /** Puts a saved database of [product] back for the set [id]; what it replaces is kept first. */ + fun restoreDatabase(id: UUID, product: String, name: String) { + val journal = TransactionJournal.load(transaction.rollbackCandidate(id)) + databases.restore(UUID.fromString(requireNotNull(journal.planId) { "У набора нет плана" }), product, name) + } + + /** Copies the saved databases and exports of [product] from the set [id] into a new folder and returns it. */ + fun extractBackup(id: UUID, product: String): Path { + val journal = TransactionJournal.load(transaction.rollbackCandidate(id)) + val plan = requireNotNull(journal.planId) { "У набора нет плана" }.toString() + val target = handoutFolder.resolve("${id.toString().take(HANDOUT_ID)}-$product") + val sources = listOf(databasesFolder, exportsFolder).mapNotNull { BackupStorage.child(it.resolve(plan), product) } + require(sources.isNotEmpty()) { "В наборе $id нет сохранённых баз и выгрузок плагина $product" } + sources.forEach { BackupStorage.copy(it, target) } + return target + } + + private fun busyBackups(): Set = + (transaction.awaitingHealth() + transaction.awaitingRollbackHealth()).map { transaction.readJournal(it.journal).id }.toSet() + + transaction.pendingInstallations().map { transaction.readJournal(it).id } + + private fun removeBackup(journalPath: Path) { + val journal = TransactionJournal.load(journalPath) + journal.configurationSnapshot?.let { BackupStorage.delete(configurationsFolder.resolve(it)) } + journal.planId?.let { BackupStorage.delete(exportsFolder.resolve(it)) } + journal.planId?.let { BackupStorage.delete(databasesFolder.resolve(it)) } + BackupStorage.delete(journalPath.parent) + } + + private fun warnIfLarge() { + val total = listOf(configurationsFolder, transactionsFolder, exportsFolder, databasesFolder).sumOf(BackupStorage::bytes) + if (total < BackupStorage.LARGE_BYTES) return + warn( + "Резервные копии занимают ${BackupItemText.size(total)}. Старше ${BackupStorage.RETENTION.toDays()} дней удаляются сами; " + + "копии плагинов лежат в data/updates/exports; ненужные можно удалить командой /pn updates backups delete .", + ) + } + + /** Saves exports, databases and configurations of the changed plugins, then downloads and prepares the plan for restart. */ + fun stage(snapshot: UpdatePlanSnapshot, registrations: List) { + require(transaction.awaitingHealth().isEmpty() && + transaction.awaitingRollbackHealth().isEmpty()) { "A prepared change is still awaiting restart verification" } + require(transaction.pendingInstallations().isEmpty()) { "A prepared rollback must be applied before preparing another update" } + val plan = requireNotNull(snapshot.plan) { "Update plan has no installable target" } + + val targets = registrations.associate { registration -> + registration.descriptor.id to InstalledUpdateTarget( + currentJar = registration.jar, + updateDirectory = registration.updateDirectory, + supportedApi = registration.descriptor.supportedApi, + ) + } + val changed = plan.changes.map { it.product }.toSet() + val selections = registrations.filter { it.descriptor.id in changed }.mapNotNull { registration -> + val selection = registration.request.configurationBackup + ?: libraryConfiguration.takeIf { registration.product == PnLibraryIdentity.PRODUCT_ID } + selection?.let { registration.descriptor.id to it } + }.toMap() + runExports(snapshot.id, registrations.filter { it.descriptor.id in changed }) + databases.copyBefore(snapshot.id, registrations.filter { it.descriptor.id in changed }.map { it.product }) + val configurationSnapshot = configurations.capture(snapshot.id, selections) + stager.stage(snapshot.id, plan, targets, configurationSnapshot) + warnIfLarge() + } + + /** The saved rollback sets with the configurations and databases kept for each. */ + fun backups(): List = transaction.rollbackCandidates().map { path -> + val journal = TransactionJournal.load(path) + val files = journal.configurationSnapshot + ?.let { id -> + runCatchingNonFatal { configurations.read(UUID.fromString(id)).files.filter { it.existed } } + .onFailure { warn("Копия настроек $id набора ${journal.id} нечитаема: ${it.message ?: it.javaClass.simpleName}") } + .getOrNull() + } + .orEmpty() + UpdateBackup(UUID.fromString(journal.id), journal.createdAt?.let(Instant::parse), journal.planId?.let(UUID::fromString), + journal.artifacts.map { UpdateBackupComponent(ProductId.of(it.component), it.expectedVersion, it.previousVersion) }, + files.size, + files.map { UpdateBackupItem(ProductId.of(it.product), it.backupKind, it.name.orEmpty(), it.size) } + + journal.planId?.let { databases.items(UUID.fromString(it)) }.orEmpty()) + } + + /** Prepares a rollback to the newest saved set. */ + fun rollbackLatest(): UpdatePlanSnapshot { + val candidate = transaction.latestRollbackCandidate() + ?: error("Нет сохранённого набора JAR для отката") + return rollback(UUID.fromString(TransactionJournal.load(candidate).id)) + } + + /** Prepares a rollback to set [id] for the next restart, putting configurations back too when asked. */ + fun rollback(id: UUID, restoreConfigurations: Boolean = false): UpdatePlanSnapshot { + require(transaction.awaitingHealth().isEmpty() && + transaction.awaitingRollbackHealth().isEmpty()) { "A prepared change is still awaiting restart verification" } + require(transaction.pendingInstallations().isEmpty()) { "Another rollback is already prepared for restart" } + val candidate = transaction.rollbackCandidate(id) + val journal = TransactionJournal.load(candidate) + if (restoreConfigurations) { + val saved = requireNotNull(journal.configurationSnapshot) { "У этого набора нет снимка конфигураций" } + require(configurations.read(UUID.fromString(saved)).planId == journal.planId) { "Configuration snapshot belongs to another plan" } + } + // Legacy backups may lack version information. Never invent a version from the current plan. + val changes = journal.artifacts.mapNotNull { artifact -> + val updated = artifact.expectedVersion?.let(SemanticVersion::tryParse) + val previous = artifact.previousVersion?.let(SemanticVersion::tryParse) + if (previous == null || updated == null) null else ProductChange(ProductId.of(artifact.component), previous, updated) + } + val snapshot = UpdatePlanSnapshot(journal.planId?.let(UUID::fromString) ?: id, 0, UpdateState.ROLLED_BACK, + journal.targetApi?.let { UpdatePlan(it, changes, emptyList()) }, emptyList(), + "Резервный набор $id подготовлен к следующему перезапуску" + + "${if (restoreConfigurations) " с восстановлением конфигураций" else " без изменения конфигураций"}.") + transaction.rollback(candidate, restoreConfigurations) + return snapshot + } + + /** After a restart, compares the versions that loaded with those a prepared set expected and reports the outcome. */ + fun reconcilePending( + registrations: List, + reportHealth: (UpdateHealthReport) -> Unit, + ) = reconcileVersions(registrations.associate { it.product to it.version }, reportHealth) + + /** Reports every set that waits for verification, oldest first, and closes it as healthy or failed. */ + internal fun reconcileVersions( + installedVersions: Map, + reportHealth: (UpdateHealthReport) -> Unit, + recoveredFailuresOnly: Boolean = false, + ) { + pendingChecks(installedVersions, recoveredFailuresOnly).forEach { (pending, source) -> + val mismatches = pending.expectedVersions.filter { (product, expected) -> installedVersions[product] != expected } + val healthy = mismatches.isEmpty() && pending.unknownProducts.isEmpty() + val id = UUID.fromString(source.id) + val message = "Набор $id. " + outcome(pending, mismatches, installedVersions, healthy) + reportHealth(UpdateHealthReport(id, source.planId?.let(UUID::fromString) ?: id, healthChanges(pending, source), healthy, pending.rollback, message)) + if (pending.rollback) transaction.completeRollbackHealth(pending.journal, healthy) + else transaction.completeHealth(pending.journal, healthy) + } + } + + private fun pendingChecks(installedVersions: Map, recoveredFailuresOnly: Boolean) = run { + val recovered = transaction.failedHealthChecks().filter { pending -> + pending.unknownProducts.isEmpty() && pending.expectedVersions.all { (product, expected) -> installedVersions[product] == expected } + } + val awaiting = if (recoveredFailuresOnly) emptyList() else transaction.awaitingHealth() + transaction.awaitingRollbackHealth() + (awaiting + recovered) + .filter { it.preparedSession != UpdateProcessSession.id } + .map { it to transaction.readJournal(it.journal) } + .sortedBy { it.second.createdAt?.let(Instant::parse) ?: Instant.MIN } + } + + private fun outcome( + pending: PendingTransaction, + mismatches: Map, + installedVersions: Map, + healthy: Boolean, + ): String { + if (healthy) return "Подтверждены загруженные версии: ${pending.expectedVersions.entries.joinToString { "${it.key}=${it.value}" }}" + val details = mismatches.entries.map { (product, expected) -> + "$product: ожидалась $expected, загружена ${installedVersions[product] ?: "не загружена"}" + } + pending.unknownProducts.map { "$it: ожидаемая версия не записана в старом журнале" } + return "Версии после перезапуска не подтвердились: ${details.joinToString()}" + } + + private fun healthChanges(pending: PendingTransaction, source: TransactionJournal): List = + source.artifacts.mapNotNull { artifact -> + val previous = artifact.previousVersion?.let(SemanticVersion::tryParse) + val updated = artifact.expectedVersion?.let(SemanticVersion::tryParse) + val product = ProductId.of(artifact.component) + when { + pending.rollback && previous != null && updated != null -> ProductChange(product, updated, previous) + !pending.rollback && updated != null && (previous != null || !artifact.targetExisted) -> + ProductChange(product, previous, updated) + else -> null + } + } + + /** Closes sets whose check failed earlier but whose expected versions are loaded now. */ + fun reconcileRecoveredFailures(registrations: List, reportHealth: (UpdateHealthReport) -> Unit) = + reconcileVersions(registrations.associate { it.product to it.version }, reportHealth, recoveredFailuresOnly = true) + + /** True when nothing waits for verification and none of [products] has a failed check, so automatic updates may go on. */ + fun automaticUpdatesHealthy(products: Set): Boolean = transaction.awaitingHealth().isEmpty() && + transaction.awaitingRollbackHealth().isEmpty() && transaction.automaticUpdatesHealthy(products.map { it.value }.toSet()) + + /** True when a prepared set expects a product that has not registered yet, so verification must wait. */ + fun awaitingRegistrations(registrations: List): Boolean { + val installed = registrations.map { it.product }.toSet() + return (transaction.awaitingHealth() + transaction.awaitingRollbackHealth()) + .filter { it.preparedSession != UpdateProcessSession.id } + .any { pending -> (pending.expectedVersions.keys + pending.unknownProducts).any { it !in installed } } + } + + private companion object { + /** Characters of the set id used in a handout folder name. */ + const val HANDOUT_ID = 8 + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdatePlanStager.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/UpdatePlanStager.kt similarity index 53% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdatePlanStager.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/UpdatePlanStager.kt index 8dde26c82..306c95a06 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdatePlanStager.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/install/UpdatePlanStager.kt @@ -1,22 +1,29 @@ -package org.pnfolder.pnlibrary.core.updates.install +package org.pnfolder.pnlibrary.updates.install import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.api.updates.ProductId +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.updates.release.ArtifactDescriptor import org.pnfolder.pnlibrary.api.updates.release.ProductChange import org.pnfolder.pnlibrary.api.updates.release.ProductRelease import org.pnfolder.pnlibrary.api.updates.release.UpdatePlan import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.common.jvm.JavaRuntime -import org.pnfolder.pnlibrary.core.updates.engine.ArtifactDownloader -import org.pnfolder.pnlibrary.core.updates.engine.ArtifactSpecification -import org.pnfolder.pnlibrary.core.updates.engine.TransactionArtifact -import org.pnfolder.pnlibrary.core.updates.engine.TrustedHttpClient -import org.pnfolder.pnlibrary.core.updates.engine.UpdateTransaction +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactDownloader +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactSpecification +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHosts +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient +import org.pnfolder.pnlibrary.updates.engine.transaction.TransactionArtifact +import org.pnfolder.pnlibrary.updates.engine.transaction.UpdateTransaction +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths import java.nio.file.Path import java.util.UUID -/** Where an installed component lives and where its update is placed for the next restart. */ +/** + * Where an installed component lives and where its update is placed for the next restart. + * @property currentJar the jar now in use + * @property updateDirectory folder the new jar is placed in + * @property supportedApi API versions the component accepts, null when it does not say + */ internal data class InstalledUpdateTarget( val currentJar: Path, val updateDirectory: Path, @@ -26,19 +33,24 @@ internal data class InstalledUpdateTarget( /** Downloads every artifact in an update plan and prepares one restart transaction. */ internal class UpdatePlanStager( private val platform: PlatformType, - private val dataFolder: Path, + private val paths: LibraryPaths, private val http: TrustedHttpClient, private val transaction: UpdateTransaction, private val maximumArtifactBytes: Long, private val requireSha256: Boolean = true, + /** The Java build the administrator chose for a product, if any. */ + private val javaChoice: (ProductId) -> Int? = { null }, + /** The Java version the installed build of a product was made for, if known. */ + private val installedJava: (ProductId) -> Int? = { null }, ) { + /** Downloads the artifacts of [plan] and hands them to the transaction as one set for the next restart. */ fun stage( planId: UUID, plan: UpdatePlan, installedTargets: Map, configurationSnapshot: UUID? = null, ) { - val stagingDirectory = dataFolder.resolve("updates/staging/$planId") + val stagingDirectory = paths.staging.resolve(planId.toString()) val artifacts = plan.changes.map { change -> prepareArtifact(change, plan, stagingDirectory, installedTargets[change.product]) } @@ -52,13 +64,14 @@ internal class UpdatePlanStager( installedTarget: InstalledUpdateTarget?, ): TransactionArtifact { val release = plan.selected.single { it.product == change.product } - val artifact = selectArtifact(change, release) + val artifact = selectArtifact(change, release, installedTarget?.currentJar?.fileName?.toString()) require(!requireSha256 || artifact.sha256 != null) { "Release artifact has no published SHA-256: ${artifact.file}" } val downloadUri = requireNotNull(artifact.downloadUri) { "Release artifact has no verified download URL: ${artifact.file}" } + TrustedHosts.requireDownload(downloadUri) val stagedFile = stagingDirectory.resolve(change.product.value).resolve(artifact.file) // The body goes straight to disk, so a large file never sits in memory. http.stream(downloadUri, maximumArtifactBytes) { input -> @@ -74,7 +87,7 @@ internal class UpdatePlanStager( sha256 = artifact.sha256, ) val target = installedTarget?.updateDirectory?.resolve(installedTarget.currentJar.fileName) - ?: dataFolder.parent.resolve("update").resolve(artifact.file) + ?: paths.serverUpdateFolder.resolve(artifact.file) return TransactionArtifact( specification = specification, @@ -83,17 +96,30 @@ internal class UpdatePlanStager( rollbackSource = installedTarget?.currentJar ?: target, previousVersion = change.from?.toString(), previousApi = installedTarget?.supportedApi, - installedTarget = installedTarget?.currentJar ?: dataFolder.parent.resolve(artifact.file), + installedTarget = installedTarget?.currentJar ?: paths.plugins.resolve(artifact.file), ) } - /** The artifact built exactly for [platform], or, when none is listed, one built for every platform. */ + /** + * Keeps the variant that is installed: a universal JAR (the one the bootstrap puts into `plugins`) is replaced by the + * newer universal one, a platform JAR by the platform one. A fresh install prefers the platform JAR, then the universal. + * When a release has builds for several Java versions, the one the administrator chose wins, then the one that + * matches the installed product. + */ private fun selectArtifact( change: ProductChange, release: ProductRelease, + installedFile: String?, ): ArtifactDescriptor { - val candidates = release.artifacts.filter { it.matchesPlatform(platform) && it.supports(JavaRuntime.feature) } - return candidates.firstOrNull { it.platform == platform } + val fitting = release.artifacts.filter { it.matchesPlatform(platform) && it.supports(JavaRuntime.feature) } + // The build the administrator chose, else the one that matches the installed product, else any that fits. + val candidates = listOfNotNull(javaChoice(change.product), installedJava(change.product)) + .firstNotNullOfOrNull { level -> fitting.filter { it.minimumJava == level }.takeIf { it.isNotEmpty() } } + ?: fitting + val universalInstalled = installedFile?.endsWith("-universal.jar", ignoreCase = true) == true + val preferred = if (universalInstalled) PlatformType.UNIVERSAL else platform + return candidates.firstOrNull { it.platform == preferred } + ?: candidates.firstOrNull { it.platform == platform } ?: candidates.firstOrNull() ?: error("No ${platform.id} artifact for ${change.product} ${change.to}") } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/paths/LegacyPathsMigration.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/paths/LegacyPathsMigration.kt new file mode 100644 index 000000000..e3f467da5 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/paths/LegacyPathsMigration.kt @@ -0,0 +1,116 @@ +package org.pnfolder.pnlibrary.updates.paths + +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import org.pnfolder.pnlibrary.common.io.AtomicFiles +import org.pnfolder.pnlibrary.common.io.TextFiles +import org.pnfolder.pnlibrary.updates.engine.UpdatePreferencesStore +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.DirectoryNotEmptyException +import java.nio.file.Files +import java.nio.file.Path + +/** + * Moves the state of older versions, which lay directly in the plugin folder, into `data`, and merges the two old + * settings files into one. It never overwrites, never throws and reports what it could not do through [warning]. + */ +class LegacyPathsMigration( + private val paths: LibraryPaths, + private val warning: (String) -> Unit = {}, +) { + /** Moves every old location that exists and whose new place is still free. */ + fun run() { + guarded("the library data") { + val old = paths.pluginFolder + move(old.resolve("updates"), paths.updates) + move(old.resolve("journal"), paths.journal) + move(old.resolve("reports"), paths.reports) + move(old.resolve("observability"), paths.observability) + move(old.resolve("diagnostics").resolve("history"), paths.diagnosticsHistory) + removeIfEmpty(old.resolve("diagnostics")) + move(old.resolve("task-history.tsv"), paths.taskHistory) + move(old.resolve("event-history.tsv"), paths.eventHistory) + move(old.resolve("upload-ledger.json"), paths.uploadLedger) + move(old.resolve("downloads"), paths.downloads) + mergeSettings() + } + } + + /** Moves [source] to [target] unless [target] exists; two folders are merged entry by entry. */ + private fun move(source: Path, target: Path) { + if (!Files.exists(source)) return + guarded(source.fileName.toString()) { + when { + !Files.exists(target) -> { + Files.createDirectories(target.parent) + AtomicFiles.move(source, target, replaceExisting = false) + } + Files.isDirectory(source) && Files.isDirectory(target) -> { + Files.newDirectoryStream(source).use { it.toList() }.forEach { move(it, target.resolve(it.fileName.toString())) } + removeIfEmpty(source) + } + } + } + } + + private fun removeIfEmpty(folder: Path) { + if (!Files.isDirectory(folder)) return + try { + Files.delete(folder) + } catch (_: DirectoryNotEmptyException) { + // Something else lives there; it stays. + } catch (error: Exception) { + warning("Could not remove the empty legacy folder ${folder.fileName}: ${error.javaClass.simpleName}") + } + } + + /** Folds the old `settings.json` and `freezes.json` into the preferences file, then removes them. */ + private fun mergeSettings() { + val settings = paths.updates.resolve("settings.json") + val freezes = paths.updates.resolve("freezes.json") + if (Files.exists(paths.preferences) || !(Files.isRegularFile(settings) || Files.isRegularFile(freezes))) return + guarded("the update settings") { + val store = UpdatePreferencesStore(paths.preferences, warning) + val merged = legacy(settings) { root -> + UpdatePreferencesStore.Preferences( + channels = root.getAsJsonObject("channels")?.entrySet().orEmpty().associate { (product, value) -> product to value.asString }, + automatic = root.getAsJsonObject("automatic")?.entrySet().orEmpty().associate { (product, value) -> product to value.asBoolean }, + allPlugins = root.get("allPlugins")?.takeIf { !it.isJsonNull }?.asBoolean, + ) + } + val paused = legacy(freezes) { root -> root.entrySet().associate { (product, value) -> product to value.asLong } } + store.update { + it.copy( + channels = merged.value.channels, + automatic = merged.value.automatic, + allPlugins = merged.value.allPlugins, + freezes = paused.value, + ) + } + if (merged.readable) Files.deleteIfExists(settings) + if (paused.readable) Files.deleteIfExists(freezes) + } + } + + private class Legacy(val value: T, val readable: Boolean) + + /** Reads [file] with [read]; a missing file gives the empty value, an unreadable one is reported and kept. */ + private fun legacy(file: Path, read: (JsonObject) -> T): Legacy { + val empty = read(JsonObject()) + if (!Files.isRegularFile(file)) return Legacy(empty, true) + return try { + Legacy(read(JsonParser.parseString(TextFiles.read(file, UTF_8)).asJsonObject), true) + } catch (error: Exception) { + warning("Unreadable legacy file ${file.fileName} was left in place: ${error.javaClass.simpleName}") + Legacy(empty, false) + } + } + + private fun guarded(what: String, action: () -> Unit) { + try { + action() + } catch (error: Exception) { + warning("Could not migrate $what to the new layout: ${error.javaClass.simpleName}: ${error.message}") + } + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/paths/LibraryPaths.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/paths/LibraryPaths.kt new file mode 100644 index 000000000..186321722 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/paths/LibraryPaths.kt @@ -0,0 +1,82 @@ +package org.pnfolder.pnlibrary.updates.paths + +import java.nio.file.Path + +/** + * The two names of a text file the library writes for administrators: [preferred] is in Russian, [ascii] is used when the + * server's JVM cannot create a file with a Russian name (a non-UTF-8 `sun.jnu.encoding`). + * + * Only names, never [Path]s: building a path from [preferred] already fails on such a JVM, which must not stop the library. + */ +class InfoFileNames(val preferred: String, val ascii: String) + +/** + * Every location the library reads or writes under its plugin folder, defined in one place. + * + * The library's own state and its settings ([settings]) live in [data]; [localization] stays beside it, the two old + * settings files ([legacyConfig], [legacyDownloadsConfig]) are only read once to import their values, and + * [serverUpdateFolder] belongs to the server rather than to the library. + * + * @param pluginFolder the plugin data folder, `plugins/pnLibrary` + */ +class LibraryPaths(val pluginFolder: Path) { + /** The server's plugins folder. */ + val plugins: Path = requireNotNull(pluginFolder.toAbsolutePath().parent) { "The plugin folder must have a parent folder" } + + // Read once by the settings import, or owned by the server: outside data. + val legacyConfig: Path = pluginFolder.resolve("config.yml") + val legacyDownloadsConfig: Path = pluginFolder.resolve("downloads.yml") + val localization: Path = pluginFolder.resolve("localization") + + /** Generated help for administrators in the plugin folder; rewritten at every start, edits are lost. */ + val help = InfoFileNames("Помощь.txt", "HELP.txt") + + /** Generated overview of every library setting with its current value; rewritten at start and at every change. */ + val settingsOverview = InfoFileNames("Настройки.txt", "SETTINGS.txt") + + /** Generated list of every command and permission; rewritten at every start, edits are lost. */ + val commandGuide = InfoFileNames("Команды.txt", "COMMANDS.txt") + + /** Where the server picks up prepared plugin jars on its next start. */ + val serverUpdateFolder: Path = plugins.resolve("update") + + /** Root of the library's own state. */ + val data: Path = pluginFolder.resolve("data") + + /** Every setting an administrator changed, in one file; see the settings command and the menu. */ + val settings: Path = data.resolve("settings.json") + + // Updates. + val updates: Path = data.resolve("updates") + + /** Channel, automatic-download and freeze choices, in one file. */ + val preferences: Path = updates.resolve("preferences.json") + val components: Path = updates.resolve("components.json") + val events: Path = updates.resolve("events") + val catalog: Path = updates.resolve("catalog") + val configurations: Path = updates.resolve("configurations") + val configurationRestores: Path = updates.resolve("configuration-restores") + val transactions: Path = updates.resolve("transactions") + val exports: Path = updates.resolve("exports") + val databases: Path = updates.resolve("databases") + val handout: Path = updates.resolve("handout") + val staging: Path = updates.resolve("staging") + val installLock: Path = updates.resolve("install.lock") + + // Journal and history. + val journal: Path = data.resolve("journal") + val history: Path = data.resolve("history") + val taskHistory: Path = history.resolve("task-history.tsv") + val eventHistory: Path = history.resolve("event-history.tsv") + + /** Download state; the download classes take [data] and keep their files in this folder. */ + val downloads: Path = data.resolve("downloads") + + // Support. + val reports: Path = data.resolve("reports") + val observability: Path = data.resolve("observability") + val observations: Path = observability.resolve("observations.jsonl") + val attachments: Path = observability.resolve("attachments") + val diagnosticsHistory: Path = data.resolve("diagnostics").resolve("history") + val uploadLedger: Path = data.resolve("upload-ledger.json") +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/ReleaseChannelSelector.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/ReleaseChannelSelector.kt similarity index 78% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/ReleaseChannelSelector.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/ReleaseChannelSelector.kt index 1ff38c42c..5d5a23fc5 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/ReleaseChannelSelector.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/ReleaseChannelSelector.kt @@ -1,7 +1,7 @@ -package org.pnfolder.pnlibrary.core.updates.policy +package org.pnfolder.pnlibrary.updates.policy -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ProductRelease /** A product's releases and the newest one its channel allows. */ @@ -12,6 +12,7 @@ internal data class ReleaseChannelSelection( /** Builds the release view for one product using the channel chosen in configuration. */ internal object ReleaseChannelSelector { + /** Picks the releases of [product] the channel allows. */ fun select( product: ProductId, releases: List, diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateAutomaticPolicy.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateAutomaticPolicy.kt similarity index 63% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateAutomaticPolicy.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateAutomaticPolicy.kt index 5b5d489c7..5378b2118 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateAutomaticPolicy.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateAutomaticPolicy.kt @@ -1,9 +1,9 @@ -package org.pnfolder.pnlibrary.core.updates.policy +package org.pnfolder.pnlibrary.updates.policy import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot import org.pnfolder.pnlibrary.api.updates.release.ProductChange -import org.pnfolder.pnlibrary.core.updates.service.RegisteredUpdate +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.updates.service.RegisteredUpdate /** Decides whether a resolved plan may be staged without an explicit user action. */ internal class UpdateAutomaticPolicy( @@ -11,16 +11,15 @@ internal class UpdateAutomaticPolicy( private val overrides: UpdatePolicyOverrides? = null, private val registrations: () -> List, ) { + /** Whether the plan may be installed without an administrator. */ fun allows(snapshot: UpdatePlanSnapshot): Boolean { val changed = snapshot.plan?.changes?.map(ProductChange::product).orEmpty() return changed.all { component -> val chosen = overrides?.automatic(component.value) if (component.value == PnLibraryIdentity.PRODUCT_ID) chosen ?: configuration.library.automaticDownload else { - component.value !in configuration.ignoredPlugins && - (chosen ?: (configuration.pluginAutomaticDownload || - registrations().firstOrNull { it.descriptor.id == component } - ?.request?.automaticDownload == true)) + chosen ?: overrides?.allPlugins() ?: (configuration.pluginAutomaticDownload || + registrations().firstOrNull { it.descriptor.id == component }?.request?.automaticDownload == true) } } } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateChannelLabels.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateChannelLabels.kt new file mode 100644 index 000000000..ee49b579b --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateChannelLabels.kt @@ -0,0 +1,36 @@ +package org.pnfolder.pnlibrary.updates.policy + +import net.kyori.adventure.text.format.TextColor +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import java.util.Locale + +/** The channel as it is typed in commands and shown in tags: `stable`, `rc`, `beta`. */ +fun UpdateChannel.commandName(): String = name.lowercase(Locale.ROOT) + +/** Channels are colored by risk, from green for stable to red for development builds. */ +fun UpdateChannel.color(): TextColor = when (this) { + UpdateChannel.STABLE -> ChatPalette.OK + UpdateChannel.RC -> ChatPalette.INFO + UpdateChannel.BETA -> ChatPalette.WARN + UpdateChannel.ALPHA -> ChatPalette.ORANGE + UpdateChannel.DEV -> ChatPalette.DANGER +} + +/** What a server on this channel receives. */ +fun UpdateChannel.hint(): String = when (this) { + UpdateChannel.STABLE -> "Только стабильные релизы" + UpdateChannel.RC -> "Кандидаты в релиз и стабильные" + UpdateChannel.BETA -> "Бета-версии и стабильные" + UpdateChannel.ALPHA -> "Экспериментальные alpha-версии: возможны ошибки" + UpdateChannel.DEV -> "Все сборки, включая разрабатываемые: только для тестового сервера" +} + +/** The channel in a sentence, such as `тестовый канал Beta`. */ +fun UpdateChannel.title(): String = when (this) { + UpdateChannel.STABLE -> "стабильный канал" + UpdateChannel.RC -> "канал RC" + UpdateChannel.BETA -> "тестовый канал Beta" + UpdateChannel.ALPHA -> "экспериментальный канал Alpha" + UpdateChannel.DEV -> "разрабатываемый канал Dev" +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateConfiguration.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateConfiguration.kt new file mode 100644 index 000000000..8f7e5bf24 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateConfiguration.kt @@ -0,0 +1,40 @@ +package org.pnfolder.pnlibrary.updates.policy + +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import java.time.Duration + +/** + * Update policy: fixed rules from [UpdateDefaults]. Nothing here is read from a file; an administrator changes the + * channel, automatic download and pause of a plugin with commands or in the menu, and those choices are kept by + * [UpdatePolicyOverrides]. + */ +internal data class UpdateConfiguration( + val checks: Checks = Checks(), + val downloads: Downloads = Downloads(), + val installation: Installation = Installation(), + val library: LibraryPolicy = LibraryPolicy(), + val pluginAutomaticDownload: Boolean = true, +) { + /** Channel and automatic-download choice for the library itself. */ + data class LibraryPolicy( + val channel: UpdateChannel = UpdateChannel.DEV, + val automaticDownload: Boolean = true, + ) + /** How often the release catalog is checked. */ + data class Checks(val interval: Duration = UpdateDefaults.CHECK_INTERVAL) + /** Limits and timeouts for artifact downloads. */ + data class Downloads( + val allowManagedPlugins: Boolean = UpdateDefaults.ALLOW_MANAGED_PLUGINS, + val connectTimeout: Duration = UpdateDefaults.CONNECT_TIMEOUT, + val readTimeout: Duration = UpdateDefaults.READ_TIMEOUT, + val maxArtifactBytes: Long = UpdateDefaults.MAX_ARTIFACT_BYTES, + ) + /** Rules for what may be installed. */ + data class Installation( + val allowNewPlugins: Boolean = false, + val requireSha256: Boolean = UpdateDefaults.REQUIRE_SHA256, + ) + + /** Whether any component may be downloaded without a command. */ + val effectiveAutomaticDownloads get() = library.automaticDownload || pluginAutomaticDownload +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateDefaults.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateDefaults.kt new file mode 100644 index 000000000..bea63527f --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateDefaults.kt @@ -0,0 +1,46 @@ +package org.pnfolder.pnlibrary.updates.policy + +import java.time.Duration + +/** + * The update rules and their default values. + * + * Checks and warnings are never switched off: an administrator pauses one plugin with a command (`hold`), which always + * expires. Every number the update system relies on lives here, so it is found in one place. The check interval and the + * two download timeouts are only defaults: an administrator changes them with `/pn settings` (see [UpdateTiming]). + */ +object UpdateDefaults { + /** How often the release catalogs are asked for new versions; the first check runs at startup. */ + val CHECK_INTERVAL: Duration = Duration.ofHours(6) + + val MIN_REMINDER_INTERVAL: Duration = Duration.ofMinutes(1) + val MAX_REMINDER_INTERVAL: Duration = Duration.ofHours(6) + + /** + * How often administrators are reminded in the console and in chat about an update that is available or waits + * for a restart. The reminder uses the known state and never asks GitHub: the check above does that on its own + * schedule, and a release that disappeared there stops the reminders. Only a developer changes this value, between + * [MIN_REMINDER_INTERVAL] and [MAX_REMINDER_INTERVAL]. + */ + val REMINDER_INTERVAL: Duration = reminderInterval(Duration.ofHours(6)) + + private fun reminderInterval(value: Duration): Duration { + require(value >= MIN_REMINDER_INTERVAL && value <= MAX_REMINDER_INTERVAL) { "Reminder interval must be 1 minute to 6 hours" } + return value + } + + /** How long to wait for a connection while downloading an update file. */ + val CONNECT_TIMEOUT: Duration = Duration.ofSeconds(10) + + /** How long to wait for data from a silent server while downloading an update file. */ + val READ_TIMEOUT: Duration = Duration.ofSeconds(30) + + /** The largest single update file accepted. */ + const val MAX_ARTIFACT_BYTES: Long = 512L * 1024 * 1024 + + /** Every downloaded file must carry a SHA-256 checksum. */ + const val REQUIRE_SHA256: Boolean = true + + /** Plugins already managed by pnLibrary may be updated when installation is allowed. */ + const val ALLOW_MANAGED_PLUGINS: Boolean = true +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdatePolicyOverrides.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdatePolicyOverrides.kt new file mode 100644 index 000000000..739573174 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdatePolicyOverrides.kt @@ -0,0 +1,94 @@ +package org.pnfolder.pnlibrary.updates.policy + +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.updates.engine.UpdatePreferencesStore + +/** + * The channel and automatic-download choices an administrator makes with commands or in the menu: one per component, + * and one for all plugins together. They are kept until changed again and take precedence over the defaults. + * + * The choices are the channel, automatic and all-plugins sections of [store]; the pause section belongs to another owner. + */ +internal class UpdatePolicyOverrides( + private val store: UpdatePreferencesStore, + private val warning: (String) -> Unit = {}, +) { + private data class State( + val channels: Map, + val automatic: Map, + val allPlugins: Boolean? = null, + val javaBuilds: Map = emptyMap(), + ) + + @Volatile + private var state = load() + + /** The channel chosen for [product] at runtime, or null when the default decides. */ + fun channel(product: String): UpdateChannel? = state.channels[product] + + /** The Java build chosen for [product], or null when the recommended one is used. */ + fun javaBuild(product: String): Int? = state.javaBuilds[product] + + /** Remembers the Java build [java] for [product], or forgets the choice when it is null. */ + @Synchronized + fun setJavaBuild(product: String, java: Int?) { + state = state.copy(javaBuilds = if (java == null) state.javaBuilds - product else state.javaBuilds + (product to java)) + save() + } + + /** The automatic-download choice for [product] at runtime, or null when the default decides. */ + fun automatic(product: String): Boolean? = state.automatic[product] + + /** The automatic-download choice for all plugins together, or null when none was made. */ + fun allPlugins(): Boolean? = state.allPlugins + + /** Whether any component was switched to automatic download at runtime. */ + fun anyAutomaticEnabled(): Boolean = state.allPlugins == true || state.automatic.values.any { it } + + /** Remembers [channel] for [product], or forgets the choice when [channel] is null. */ + @Synchronized + fun setChannel(product: String, channel: UpdateChannel?) { + state = state.copy(channels = if (channel == null) state.channels - product else state.channels + (product to channel)) + save() + } + + @Synchronized + fun setAutomatic(product: String, enabled: Boolean) { + state = state.copy(automatic = state.automatic + (product to enabled)) + save() + } + + /** Sets automatic download for every plugin and forgets the choices made for single ones; [libraryProduct] keeps its own. */ + @Synchronized + fun setAllPlugins(enabled: Boolean, libraryProduct: String) { + state = state.copy(allPlugins = enabled, automatic = state.automatic.filterKeys { it == libraryProduct }) + save() + } + + private fun load(): State { + val stored = store.current() + return State( + channels = stored.channels.mapNotNull { (product, name) -> + runCatchingNonFatal { UpdateChannel.valueOf(name) } + .onFailure { warning("Unknown update channel for $product in ${store.fileName}; the default is used") } + .getOrNull()?.let { product to it } + }.toMap(), + automatic = stored.automatic, + allPlugins = stored.allPlugins, + javaBuilds = stored.javaBuilds, + ) + } + + private fun save() { + val saved = state + store.update { + it.copy( + channels = saved.channels.mapValues { (_, channel) -> channel.name }, + automatic = saved.automatic, + allPlugins = saved.allPlugins, + javaBuilds = saved.javaBuilds, + ) + } + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateTiming.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateTiming.kt new file mode 100644 index 000000000..fc2f09da7 --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateTiming.kt @@ -0,0 +1,16 @@ +package org.pnfolder.pnlibrary.updates.policy + +import java.time.Duration + +/** + * The update times an administrator may change; the library reads them once at startup. + * + * @property checkInterval how often the release catalogs are asked for new versions + * @property connectTimeout how long to wait for a connection while downloading an update file + * @property readTimeout how long to wait for data from a silent server while downloading an update file + */ +data class UpdateTiming( + val checkInterval: Duration = UpdateDefaults.CHECK_INTERVAL, + val connectTimeout: Duration = UpdateDefaults.CONNECT_TIMEOUT, + val readTimeout: Duration = UpdateDefaults.READ_TIMEOUT, +) diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/RegisteredUpdate.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/RegisteredUpdate.kt similarity index 77% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/RegisteredUpdate.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/RegisteredUpdate.kt index aa8f6de36..2d53de1f8 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/RegisteredUpdate.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/RegisteredUpdate.kt @@ -1,21 +1,22 @@ -package org.pnfolder.pnlibrary.core.updates.service +package org.pnfolder.pnlibrary.updates.service +import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.PluginUpdateArtifact -import org.pnfolder.pnlibrary.api.updates.PluginUpdateRequest -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot import org.pnfolder.pnlibrary.api.updates.UpdateRegistration -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ArtifactDescriptor import org.pnfolder.pnlibrary.api.updates.release.InstalledProduct import org.pnfolder.pnlibrary.api.updates.release.ProductRelease import org.pnfolder.pnlibrary.api.updates.release.ReleaseSummary +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateArtifact +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.common.jvm.JavaRuntime -import org.pnfolder.pnlibrary.core.updates.engine.CatalogRelease -import org.pnfolder.pnlibrary.core.updates.policy.ReleaseChannelSelector +import org.pnfolder.pnlibrary.updates.engine.catalog.CatalogRelease +import org.pnfolder.pnlibrary.updates.policy.ReleaseChannelSelector import java.nio.file.Path import java.util.concurrent.CompletionStage import java.util.concurrent.atomic.AtomicBoolean @@ -33,6 +34,8 @@ internal class RegisteredUpdate( private val stagePlan: (UpdatePlanSnapshot) -> CompletionStage, private val onClose: (RegisteredUpdate) -> Unit, private val effectiveAutomatic: () -> Boolean = { request.automaticDownload }, + private val platform: PlatformType? = null, + private val chosenJava: () -> Int? = { null }, ) : UpdateRegistration { val product: String = descriptor.id.value val version: String = descriptor.version.toString() @@ -54,6 +57,7 @@ internal class RegisteredUpdate( checkForUpdates().thenCompose(stagePlan) } + /** The product as the resolver sees it installed. */ fun installedProduct(providedApi: Int?) = InstalledProduct( descriptor.id, descriptor.version, @@ -61,6 +65,7 @@ internal class RegisteredUpdate( providedApi, ) + /** Converts a catalog release into a resolver release for this product. */ fun releaseFrom(catalogRelease: CatalogRelease): ProductRelease = ProductRelease( product = descriptor.id, version = catalogRelease.version, @@ -84,12 +89,17 @@ internal class RegisteredUpdate( changelogUrl = catalogRelease.changelogUrl?.toString(), ) + /** Remembers the releases found for [channel] and updates the snapshot. */ fun observe(releases: List, channel: UpdateChannel) { if (closed.get()) return val selection = ReleaseChannelSelector.select(descriptor.id, releases, channel) val latest = selection.latestAllowed val current = descriptor.version + val builds = latest?.artifacts.orEmpty() + .filter { (platform == null || it.matchesPlatform(platform)) && it.supports(JavaRuntime.feature) } + .map { it.minimumJava }.distinct().sorted() + val recommended = descriptor.minimumJava.takeIf { it in builds } ?: builds.maxOrNull() state.set( UpdateSnapshot( product = product, @@ -107,6 +117,9 @@ internal class RegisteredUpdate( availableReleases = selection.all .sortedByDescending(ProductRelease::version) .map { release -> ReleaseSummary(release.version.toString(), release.channel, release.publishedAt, release.changelogUrl) }, + javaBuilds = builds, + javaBuild = chosenJava(), + recommendedJava = recommended, ), ) } @@ -118,6 +131,7 @@ internal class RegisteredUpdate( old.product, old.currentVersion, old.latestVersion, selectedChannel(), old.state, old.currentJava, old.requiredJava, effectiveAutomatic(), old.releaseUrl, old.message, old.latestChangelogUrl, old.supportedApi, old.availableReleases, + old.javaBuilds, chosenJava(), old.recommendedJava, ) } } @@ -126,6 +140,7 @@ internal class RegisteredUpdate( if (closed.compareAndSet(false, true)) onClose(this) } + /** Marks the registration as closed so later results are ignored. */ fun markClosed() { closed.set(true) } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/RegistrationValidator.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/RegistrationValidator.kt new file mode 100644 index 000000000..f807c1ade --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/RegistrationValidator.kt @@ -0,0 +1,66 @@ +package org.pnfolder.pnlibrary.updates.service + +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateArtifact +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest +import org.pnfolder.pnlibrary.api.version.SemanticVersion +import org.pnfolder.pnlibrary.common.jvm.JavaRuntime +import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity +import org.pnfolder.pnlibrary.spi.platform.PlatformOwnerMetadata +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths + +/** What a plugin must provide on disk to be updated: its [jar], the [pluginsDirectory] it sits in and its [artifact]. */ +internal data class ValidatedRegistration(val jar: Path, val pluginsDirectory: Path, val artifact: PluginUpdateArtifact) + +/** Checks that a registering plugin can be updated and finds the files the update pipeline works with. */ +internal class RegistrationValidator( + private val ownership: PlatformOwnerMetadata, + private val identity: PlatformIdentity, +) { + /** Returns the files of [owner] or throws when its names, version, location or request are not updatable. */ + fun validate(owner: Any, product: ProductDescriptor, request: PluginUpdateRequest): ValidatedRegistration { + val info = ownership.ownerDetails(owner) + val nativeProductName = info["name"] ?: request.repositoryName + listOf(nativeProductName, request.repositoryName).firstOrNull(UpdateCommandWords::isReserved)?.let { word -> + throw IllegalArgumentException( + "A plugin cannot be called '$word' for updates: it is a word of the /pn update command " + + "(${UpdateCommandWords.RESERVED.joinToString()}). Rename the plugin or its repository.", + ) + } + val version = info["version"] ?: error("Cannot determine the version of the registering plugin") + require(SemanticVersion.tryParse(version) != null) { + "Version of $nativeProductName must be semantic: $version" + } + val jar = Paths.get(owner.javaClass.protectionDomain.codeSource.location.toURI()).toAbsolutePath().normalize() + require(Files.isRegularFile(jar)) { "Plugin must be loaded from a JAR file" } + val pluginsDirectory = pluginsDirectoryOf(jar) + request.configurationBackup?.let { backup -> + require(backup.root != pluginsDirectory && backup.root.toAbsolutePath().normalize().startsWith(pluginsDirectory)) { + "Configuration backup root must be a component data directory inside the plugins directory" + } + } + // Without own rules the Java range the product declares is enough: the catalogue says which file fits. + val artifact = if (request.artifacts.isEmpty()) { + PluginUpdateArtifact(".*", product.minimumJava, product.maximumJava) + } else { + request.artifactFor(JavaRuntime.feature, identity.type) + ?: error("No artifact of ${request.repositoryName} is registered for Java ${JavaRuntime.feature}") + } + require(product.version == SemanticVersion.parse(version)) { + "Product version ${product.version} does not match native plugin version $version" + } + return ValidatedRegistration(jar, pluginsDirectory, artifact) + } + + private companion object { + const val PAPER_REMAPPED = ".paper-remapped" + + /** Paper runs remapped copies from `plugins/.paper-remapped`; data folders and `update` still sit in `plugins`. */ + fun pluginsDirectoryOf(jar: Path): Path { + val folder = jar.parent + return if (folder.fileName?.toString() == PAPER_REMAPPED) folder.parent else folder + } + } +} diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateAnnouncementRenderer.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateAnnouncementRenderer.kt similarity index 88% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateAnnouncementRenderer.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateAnnouncementRenderer.kt index bdb4a14fb..c8d0bbfcb 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateAnnouncementRenderer.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateAnnouncementRenderer.kt @@ -1,16 +1,18 @@ -package org.pnfolder.pnlibrary.core.updates.catalog +package org.pnfolder.pnlibrary.updates.service import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState import org.pnfolder.pnlibrary.api.updates.release.ProductChange import org.pnfolder.pnlibrary.api.updates.release.ReleaseSummary +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.console.ConsoleCard import org.pnfolder.pnlibrary.console.ConsoleTheme +import org.pnfolder.pnlibrary.updates.policy.title /** Renders automatic update notifications with the same card used by console status. */ internal object UpdateAnnouncementRenderer { + /** Builds the announcement shown to administrators. */ fun render( snapshot: UpdatePlanSnapshot, theme: ConsoleTheme, @@ -40,6 +42,7 @@ internal object UpdateAnnouncementRenderer { .lastItem("Автозагрузка выключена; используйте /pn update <плагин>") .blank() } + card.section("ПОДДЕРЖКА").lastItem("Вопросы, ошибки и идеи — пишите нам в Discord: ${PnLibraryIdentity.SUPPORT_URL}").blank() return card.status(result).build().render() } @@ -47,7 +50,7 @@ internal object UpdateAnnouncementRenderer { card.section("ОБНОВЛЕНИЯ") changes.forEachIndexed { index, change -> val release = snapshot.plan?.selected?.firstOrNull { it.product == change.product } - val channel = release?.channel?.let(UpdateChannelLabels::channelTitle) ?: "не указан" + val channel = release?.channel?.title() ?: "не указан" val api = release?.supportedApi?.let { "${it.minimum}–${it.maximum}" } ?: "не указан" val artifact = release?.artifacts?.firstOrNull() val platform = artifact?.platform?.displayName ?: "не указана" @@ -79,7 +82,7 @@ internal object UpdateAnnouncementRenderer { .groupBy(ReleaseSummary::channel) .mapValues { (_, releases) -> releases.maxByOrNull { it.version } } latestByChannel.values.filterNotNull().forEach { release -> - card.firstDetail(UpdateChannelLabels.channelTitle(release.channel), release.version) + card.firstDetail(release.channel.title(), release.version) .lastDetail("Опубликована", release.publishedAt?.toString() ?: "дата неизвестна") } if (index != histories.lastIndex) card.blank() diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCommandWords.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateCommandWords.kt similarity index 90% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCommandWords.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateCommandWords.kt index 368e1acb9..889d073da 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateCommandWords.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateCommandWords.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.catalog +package org.pnfolder.pnlibrary.updates.service /** * Words that follow `/pn update` and mean a step of the update flow, not a plugin. @@ -9,7 +9,7 @@ package org.pnfolder.pnlibrary.core.updates.catalog */ object UpdateCommandWords { /** The reserved words, in lower case. */ - val RESERVED: Set = setOf("confirm", "status", "rollback", "restart") + val RESERVED: Set = setOf("confirm", "status", "rollback", "restart", "all") /** Whether [name] is one of the reserved words, ignoring case. */ fun isReserved(name: String): Boolean = name.trim().lowercase() in RESERVED diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateHealthReport.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateHealthReport.kt similarity index 88% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateHealthReport.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateHealthReport.kt index 0eb8ecf1c..ae9e7db59 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateHealthReport.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateHealthReport.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.service +package org.pnfolder.pnlibrary.updates.service import org.pnfolder.pnlibrary.api.updates.release.ProductChange import java.util.UUID diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateInstallationLock.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateInstallationLock.kt similarity index 76% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateInstallationLock.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateInstallationLock.kt index 2ba7bde32..3c18d1ae3 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateInstallationLock.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateInstallationLock.kt @@ -1,10 +1,10 @@ -package org.pnfolder.pnlibrary.core.updates.service +package org.pnfolder.pnlibrary.updates.service -import org.pnfolder.pnlibrary.core.updates.engine.UpdatePaths +import org.pnfolder.pnlibrary.updates.engine.UpdatePaths +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths import java.nio.channels.FileChannel import java.nio.channels.FileLock import java.nio.file.Files -import java.nio.file.Path import java.nio.file.StandardOpenOption import java.util.concurrent.atomic.AtomicBoolean @@ -17,8 +17,9 @@ internal class UpdateInstallationLock private constructor(private val channel: F } companion object { - fun acquire(dataDirectory: Path): UpdateInstallationLock { - val path = UpdatePaths.inside(dataDirectory.resolve("updates/install.lock"), dataDirectory) + /** Takes the lock of [paths], failing if another process holds it. */ + fun acquire(paths: LibraryPaths): UpdateInstallationLock { + val path = UpdatePaths.inside(paths.installLock, paths.data) Files.createDirectories(path.parent) val channel = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE) try { diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateOrchestrator.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateOrchestrator.kt similarity index 83% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateOrchestrator.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateOrchestrator.kt index 7eac2cdec..763d3875f 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateOrchestrator.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateOrchestrator.kt @@ -1,15 +1,15 @@ -package org.pnfolder.pnlibrary.core.updates.service +package org.pnfolder.pnlibrary.updates.service -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState import org.pnfolder.pnlibrary.api.updates.release.UpdatePlan +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.updates.engine.ResolutionResult -import org.pnfolder.pnlibrary.core.updates.history.UpdateStateStore -import org.pnfolder.pnlibrary.core.updates.policy.UpdateConfiguration -import java.time.Clock -import java.time.Instant +import org.pnfolder.pnlibrary.updates.engine.ResolutionResult +import org.pnfolder.pnlibrary.updates.history.UpdateStateStore +import org.pnfolder.pnlibrary.updates.policy.UpdateConfiguration +import org.pnfolder.pnlibrary.updates.policy.UpdateDefaults +import java.time.Duration import java.util.Collections import java.util.Optional import java.util.UUID @@ -29,12 +29,13 @@ internal class UpdateOrchestrator( private val resolver: () -> ResolutionResult, private val stageAction: (UpdatePlanSnapshot) -> Unit, private val announcement: (UpdatePlanSnapshot) -> Unit, - private val clock: Clock = Clock.systemUTC(), private val automaticAllowed: (UpdatePlanSnapshot) -> Boolean = { true }, private val remoteResolver: (() -> ResolutionResult)? = null, private val observeState: (UpdatePlanSnapshot, UpdateActor, String) -> Unit = { _, _, _ -> }, private val beforeCheck: () -> Unit = {}, private val automaticOverridesActive: () -> Boolean = { false }, + private val reminderInterval: Duration = UpdateDefaults.REMINDER_INTERVAL, + private val unexpectedFailure: (String, Throwable) -> Unit = { _, _ -> }, ) : AutoCloseable { private val lock = Any() private val closed = AtomicBoolean(false) @@ -54,19 +55,43 @@ internal class UpdateOrchestrator( private var current: UpdatePlanSnapshot? = store.current() private val revision = java.util.concurrent.atomic.AtomicLong(current?.revision ?: 0L) private var announcedFingerprint: String? = null - private var announcedAt: Instant? = null private val sessionHistory = ArrayDeque() + /** Begins periodic checks. */ fun start() { if (closed.get() || !started.compareAndSet(false, true)) return executor.scheduleWithFixedDelay( - { checkNow(false, UpdateActor.SYSTEM).exceptionally { null } }, + { scheduledCheck() }, 0, configuration.checks.interval.toMillis(), TimeUnit.MILLISECONDS, ) + executor.scheduleWithFixedDelay( + { runCatchingNonFatal(::remind).onFailure { unexpectedFailure("Update reminder failed", it) } }, + reminderInterval.toMillis(), + reminderInterval.toMillis(), + TimeUnit.MILLISECONDS, + ) + } + + private fun scheduledCheck() { + checkNow(false, UpdateActor.SYSTEM).whenComplete { _, error -> + // A closed orchestrator rejects the check on purpose; any other failure means the state could not be saved. + if (error != null && !closed.get()) unexpectedFailure("Scheduled update check failed", error) + } } + /** + * Repeats the announcement of an update that is still waiting. It works on the state already known, so it never + * asks GitHub; once a check finds the release gone, the state is up to date and the reminders stop. + */ + internal fun remind() { + val snapshot = synchronized(lock) { current } ?: return + if (closed.get()) return + if (snapshot.state == UpdateState.UPDATE_AVAILABLE || snapshot.state == UpdateState.UPDATE_STAGED) announcement(snapshot) + } + + /** Checks for updates right away and returns the resulting plan. */ fun checkNow(forceRemote: Boolean = true, actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage = synchronized(lock) { check(!closed.get()) { "Update orchestrator is closed" } inFlight?.let { active -> @@ -138,19 +163,21 @@ internal class UpdateOrchestrator( } } + /** The latest plan, if one exists. */ fun currentPlan(): Optional = Optional.ofNullable(synchronized(lock) { current }) /** Queues a fresh graph check after any currently running check has released the coalescing slot. */ fun registrationsChanged() { if (closed.get() || !started.get()) return try { - executor.execute { if (!closed.get()) checkNow(false, UpdateActor.SYSTEM) } + executor.execute { if (!closed.get()) scheduledCheck() } } catch (_: RejectedExecutionException) { // A concurrent executor shutdown is a normal lifecycle race. The owner // will close the orchestrator and no follow-up check is required. } } + /** Downloads and prepares the plan with [planId]. */ fun stage(planId: UUID, actor: UpdateActor = UpdateActor.UNKNOWN): CompletionStage { val promise = operationPromise() if (promise.isDone) return promise @@ -174,10 +201,12 @@ internal class UpdateOrchestrator( return promise } + /** Recent plans, newest last. */ fun history(): List = synchronized(lock) { Collections.unmodifiableList(ArrayList(sessionHistory)) } + /** Runs [action] as a rollback and records the result. */ fun rollback(actor: UpdateActor = UpdateActor.UNKNOWN, action: () -> Unit): CompletionStage = rollbackTo(actor) { val selected = synchronized(lock) { current } ?: error("No update plan is available for rollback") action() @@ -185,6 +214,7 @@ internal class UpdateOrchestrator( "Предыдущие версии JAR подготовлены к следующему перезапуску.") } + /** Runs [action] as a rollback, optionally of the failure [failureId]. */ fun rollbackTo(actor: UpdateActor, failureId: UUID? = null, action: () -> UpdatePlanSnapshot): CompletionStage { val promise = operationPromise() if (promise.isDone) return promise @@ -239,13 +269,9 @@ internal class UpdateOrchestrator( observeState(snapshot, actor, operation) if (closed.get()) return val fingerprint = fingerprint(snapshot.state, snapshot.plan, snapshot.blockers) - val now = clock.instant() - val repeat = announcedAt?.let { !now.isBefore(it.plus(configuration.notifications.repeatInterval)) } ?: true - if (fingerprint != announcedFingerprint || repeat) { - announcement(snapshot) - announcedFingerprint = fingerprint - announcedAt = now - } + if (fingerprint == announcedFingerprint) return + announcement(snapshot) + announcedFingerprint = fingerprint } private fun observeFailure(planId: UUID, actor: UpdateActor, operation: String, error: Throwable) { diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateOrchestratorRuntime.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateOrchestratorRuntime.kt similarity index 79% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateOrchestratorRuntime.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateOrchestratorRuntime.kt index 19d8500c5..5e0c36905 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateOrchestratorRuntime.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateOrchestratorRuntime.kt @@ -1,24 +1,25 @@ -package org.pnfolder.pnlibrary.core.updates.service +package org.pnfolder.pnlibrary.updates.service import org.pnfolder.pnlibrary.api.logging.LogLevel -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdateActor -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState -import org.pnfolder.pnlibrary.api.updates.backup.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.updates.release.ProductChange +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.updates.engine.RefreshMode -import org.pnfolder.pnlibrary.core.updates.engine.ResolutionResult -import org.pnfolder.pnlibrary.core.updates.history.UpdateEventJournal -import org.pnfolder.pnlibrary.core.updates.history.UpdateStateStore -import org.pnfolder.pnlibrary.core.updates.install.ComponentLedger -import org.pnfolder.pnlibrary.core.updates.install.UpdateInstaller -import org.pnfolder.pnlibrary.core.updates.policy.UpdateConfiguration import org.pnfolder.pnlibrary.spi.platform.PlatformLogging import org.pnfolder.pnlibrary.spi.platform.PlatformReadiness -import java.nio.file.Path +import org.pnfolder.pnlibrary.updates.engine.ResolutionResult +import org.pnfolder.pnlibrary.updates.engine.catalog.RefreshMode +import org.pnfolder.pnlibrary.updates.history.UpdateEventJournal +import org.pnfolder.pnlibrary.updates.history.UpdateStateStore +import org.pnfolder.pnlibrary.updates.install.ComponentLedger +import org.pnfolder.pnlibrary.updates.install.ComponentOperation +import org.pnfolder.pnlibrary.updates.install.UpdateInstaller +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import org.pnfolder.pnlibrary.updates.policy.UpdateConfiguration import java.util.Collections import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage @@ -31,7 +32,7 @@ import java.util.concurrent.atomic.AtomicBoolean /** Owns the scheduler and lifecycle wiring around the update orchestrator. */ internal class UpdateOrchestratorRuntime( private val configuration: UpdateConfiguration, - dataFolder: Path, + paths: LibraryPaths, private val logging: PlatformLogging, readiness: PlatformReadiness, installer: UpdateInstaller, @@ -48,13 +49,13 @@ internal class UpdateOrchestratorRuntime( Thread(action, "pnLibrary-update-orchestrator").apply { isDaemon = true } } - private val installationLock = UpdateInstallationLock.acquire(dataFolder) - private val journal by lazy { UpdateEventJournal(dataFolder.resolve("updates/events"), warning = { + private val installationLock = UpdateInstallationLock.acquire(paths) + private val journal by lazy { UpdateEventJournal(paths.events, warning = { logging.log(this, LogLevel.WARNING, it) }) } private val componentLedger by lazy { - ComponentLedger(dataFolder.resolve("updates/components.json"), journal, warning = { + ComponentLedger(paths.components, journal, warning = { logging.log(this, LogLevel.WARNING, it) }) } @@ -62,7 +63,7 @@ internal class UpdateOrchestratorRuntime( val orchestrator = try { UpdateOrchestrator( configuration, - UpdateStateStore(dataFolder.resolve("updates"), warning = { logging.log(this, LogLevel.WARNING, it) }), + UpdateStateStore(paths.updates, warning = { logging.log(this, LogLevel.WARNING, it) }), executor, { resolveGraph(RefreshMode.CACHED) }, stageGraph, @@ -71,10 +72,11 @@ internal class UpdateOrchestratorRuntime( remoteResolver = { resolveGraph(RefreshMode.FORCE_REMOTE) }, beforeCheck = { installer.reconcileRecoveredFailures(registrations(), ::recordHealth) }, automaticOverridesActive = automaticOverridesActive, + unexpectedFailure = { message, error -> if (!closed.get()) logging.log(this, LogLevel.ERROR, message, error) }, observeState = { snapshot, actor, operation -> runCatchingNonFatal { journal.record(snapshot, actor, operation) }.onFailure { error -> // An observation failure must not turn an already staged transaction into a failed operation. - if (!closed.get()) runCatchingNonFatal { logging.log(this, LogLevel.WARNING, "Could not persist update observation", error) } + if (!closed.get()) runCatchingNonFatal { logging.log(this, LogLevel.ERROR, "Could not persist update observation", error) } } }, ).also { created -> @@ -104,7 +106,7 @@ internal class UpdateOrchestratorRuntime( observeComponents(installed) created.start() } catch (error: Exception) { - if (!closed.get()) logging.log(this, LogLevel.WARNING, "Could not verify restarted component versions; automatic checks were not started", + if (!closed.get()) logging.log(this, LogLevel.CRITICAL, "Could not verify restarted component versions; automatic checks were not started", error) } } @@ -112,18 +114,17 @@ internal class UpdateOrchestratorRuntime( catch (error: RejectedExecutionException) { if (!closed.get()) throw error } } - /** Records components that appeared, disappeared or changed since the previous start. */ /** Records a change an administrator made to one component's settings and remembers it for the next start. */ fun recordSettingsChange(registration: RegisteredUpdate, message: String, actor: UpdateActor) { runCatchingNonFatal { journal.recordComponent( - ComponentLedger.OPERATION_SETTINGS_CHANGED, registration.product, registration.version, registration.version, + ComponentOperation.SETTINGS_CHANGED, registration.product, registration.version, registration.version, message, actor, ) val snapshot = registration.snapshot componentLedger.updateSettings(registration.product, snapshot.channel.name.lowercase(), snapshot.automaticDownload) }.onFailure { error -> - if (!closed.get()) logging.log(this, LogLevel.WARNING, "Could not record a settings change", error) + if (!closed.get()) logging.log(this, LogLevel.ERROR, "Could not record a settings change", error) } } @@ -139,7 +140,7 @@ internal class UpdateOrchestratorRuntime( verifiedByHealth.toSet(), ) }.onFailure { error -> - if (!closed.get()) logging.log(this, LogLevel.WARNING, "Could not record component changes", error) + if (!closed.get()) logging.log(this, LogLevel.ERROR, "Could not record component changes", error) } } @@ -149,6 +150,7 @@ internal class UpdateOrchestratorRuntime( if (!closed.get()) runCatchingNonFatal { logging.log(this, if (report.healthy) LogLevel.INFO else LogLevel.WARNING, report.message) } } + /** One page of history entries, read off the calling thread. */ fun historyPage(page: Int, product: String?): CompletionStage> = readAsync { require(page > 0) { "Page must be positive" } val normalized = product?.let { ProductId.of(it).value } @@ -160,10 +162,12 @@ internal class UpdateOrchestratorRuntime( }.let { Collections.unmodifiableList(it) } } + /** Number of history entries, optionally for one product. */ fun historyCount(product: String?): CompletionStage = readAsync { journal.count(product?.let { ProductId.of(it).value }) } + /** Runs a blocking read on the update executor. */ fun readAsync(action: () -> T): CompletionStage { val result = CompletableFuture() pendingReads.add(result) diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateRegistrationStore.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateRegistrationStore.kt similarity index 70% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateRegistrationStore.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateRegistrationStore.kt index 92f9c2321..886be3b9a 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateRegistrationStore.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateRegistrationStore.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.service +package org.pnfolder.pnlibrary.updates.service import org.pnfolder.pnlibrary.api.updates.UpdateRegistration import java.util.Collections @@ -8,13 +8,19 @@ import java.util.concurrent.CopyOnWriteArrayList internal class UpdateRegistrationStore { private val entries = CopyOnWriteArrayList() + /** Adds a registration. */ fun add(entry: RegisteredUpdate) { entries += entry } + /** Removes a registration. */ fun remove(entry: RegisteredUpdate) { entries.remove(entry) } + /** Copy of the registrations for internal use. */ fun snapshot(): List = entries.toList() + /** Read-only copy exposed to plugins. */ fun publicSnapshot(): List = Collections.unmodifiableList(ArrayList(entries)) + /** Finds a registration by product id or repository name, ignoring case. */ fun find(product: String): RegisteredUpdate? = entries.firstOrNull { it.product.equals(product, true) || it.request.repositoryName.equals(product, true) } + /** Marks all registrations closed and clears the store. */ fun close() { entries.forEach(RegisteredUpdate::markClosed) entries.clear() diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateRuntimeResources.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateRuntimeResources.kt similarity index 60% rename from modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateRuntimeResources.kt rename to modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateRuntimeResources.kt index eb62a061b..eb4f016b6 100644 --- a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateRuntimeResources.kt +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateRuntimeResources.kt @@ -1,17 +1,16 @@ -package org.pnfolder.pnlibrary.core.updates.service +package org.pnfolder.pnlibrary.updates.service -import org.pnfolder.pnlibrary.core.updates.engine.ReleaseCatalogClient -import org.pnfolder.pnlibrary.core.updates.engine.ReleaseCatalogStore -import org.pnfolder.pnlibrary.core.updates.engine.TrustedHttpClient -import org.pnfolder.pnlibrary.core.updates.install.ReleaseCatalogGateway -import org.pnfolder.pnlibrary.core.updates.policy.UpdateConfiguration +import org.pnfolder.pnlibrary.updates.engine.catalog.ReleaseCatalogClient +import org.pnfolder.pnlibrary.updates.engine.catalog.ReleaseCatalogStore +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient +import org.pnfolder.pnlibrary.updates.install.ReleaseCatalogGateway +import org.pnfolder.pnlibrary.updates.policy.UpdateConfiguration import java.nio.file.Path import java.time.Duration -import java.util.concurrent.ExecutorService import java.util.concurrent.Executors /** Owns shared network and release-catalog resources used by the update pipeline. */ -internal class UpdateRuntimeResources(dataFolder: Path, configuration: UpdateConfiguration = UpdateConfiguration()) : AutoCloseable { +internal class UpdateRuntimeResources(catalogFolder: Path, configuration: UpdateConfiguration = UpdateConfiguration()) : AutoCloseable { private val catalogExecutor = Executors.newFixedThreadPool(4) { action -> Thread(action, "pnLibrary-catalog-fetch").apply { isDaemon = true } } @@ -26,7 +25,7 @@ internal class UpdateRuntimeResources(dataFolder: Path, configuration: UpdateCon val downloadHttp = TrustedHttpClient(configuration.downloads.connectTimeout, configuration.downloads.readTimeout) private val releaseCatalog = ReleaseCatalogClient( http, - ReleaseCatalogStore(dataFolder.resolve("updates/catalog")), + ReleaseCatalogStore(catalogFolder), catalogExecutor, Duration.ofMinutes(30), ) @@ -37,11 +36,7 @@ internal class UpdateRuntimeResources(dataFolder: Path, configuration: UpdateCon ) override fun close() { - shutdown(catalogExecutor) - shutdown(catalogRequestExecutor) - } - - private fun shutdown(executor: ExecutorService) { - executor.shutdownNow() + catalogExecutor.shutdownNow() + catalogRequestExecutor.shutdownNow() } } diff --git a/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateServiceImpl.kt b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateServiceImpl.kt new file mode 100644 index 000000000..da99a112d --- /dev/null +++ b/modules/updates/src/main/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateServiceImpl.kt @@ -0,0 +1,321 @@ +package org.pnfolder.pnlibrary.updates.service + +import org.pnfolder.pnlibrary.api.dependencies.PluginDependency +import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity +import org.pnfolder.pnlibrary.api.updates.UpdateBackups +import org.pnfolder.pnlibrary.api.updates.UpdateHistory +import org.pnfolder.pnlibrary.api.updates.UpdatePlans +import org.pnfolder.pnlibrary.api.updates.UpdateProducts +import org.pnfolder.pnlibrary.api.updates.UpdateRegistration +import org.pnfolder.pnlibrary.api.updates.UpdateService +import org.pnfolder.pnlibrary.api.updates.UpdateSettings +import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackup +import org.pnfolder.pnlibrary.api.updates.history.UpdateHistoryEntry +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import org.pnfolder.pnlibrary.console.ConsoleTheme +import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity +import org.pnfolder.pnlibrary.spi.platform.PlatformLogging +import org.pnfolder.pnlibrary.spi.platform.PlatformOwnerMetadata +import org.pnfolder.pnlibrary.spi.platform.PlatformPluginInventory +import org.pnfolder.pnlibrary.spi.platform.PlatformReadiness +import org.pnfolder.pnlibrary.updates.databases.DatabaseBackups +import org.pnfolder.pnlibrary.updates.databases.DatabaseSources +import org.pnfolder.pnlibrary.updates.engine.FreezeStore +import org.pnfolder.pnlibrary.updates.engine.ResolutionResult +import org.pnfolder.pnlibrary.updates.engine.UpdatePreferencesStore +import org.pnfolder.pnlibrary.updates.engine.catalog.RefreshMode +import org.pnfolder.pnlibrary.updates.install.UpdateGraphResolver +import org.pnfolder.pnlibrary.updates.install.UpdateInstaller +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import org.pnfolder.pnlibrary.updates.policy.UpdateAutomaticPolicy +import org.pnfolder.pnlibrary.updates.policy.UpdateConfiguration +import org.pnfolder.pnlibrary.updates.policy.UpdatePolicyOverrides +import org.pnfolder.pnlibrary.updates.policy.UpdateTiming +import java.nio.file.Files +import java.time.Duration +import java.time.Instant +import java.time.format.DateTimeFormatter +import java.util.Collections +import java.util.Locale +import java.util.Optional +import java.util.UUID +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CompletionStage +import java.util.concurrent.atomic.AtomicBoolean + +/** One catalog → resolver → verifier → transaction pipeline for every component. */ +class UpdateServiceImpl( + private val logging: PlatformLogging, + private val ownership: PlatformOwnerMetadata, + private val inventory: PlatformPluginInventory, + private val identity: PlatformIdentity, + private val readiness: PlatformReadiness, + private val paths: LibraryPaths, + private val consoleTheme: ConsoleTheme, + timing: UpdateTiming = UpdateTiming(), +) : UpdateService, AutoCloseable { + private val closed = AtomicBoolean(false) + private val registrations = UpdateRegistrationStore() + private val configuration = UpdateConfiguration( + checks = UpdateConfiguration.Checks(timing.checkInterval), + downloads = UpdateConfiguration.Downloads(connectTimeout = timing.connectTimeout, readTimeout = timing.readTimeout), + ) + private val registrationValidator = RegistrationValidator(ownership, identity) + init { + retireOldSettingsFile() + } + private val resources = UpdateRuntimeResources(paths.catalog, configuration) + private val preferences = UpdatePreferencesStore(paths.preferences) { logging.log(this, LogLevel.WARNING, it) } + private val overrides = UpdatePolicyOverrides(preferences) { + logging.log(this, LogLevel.WARNING, it) + } + private val automaticPolicy = UpdateAutomaticPolicy(configuration, overrides) { registrations.snapshot() } + /** Where plugins say their databases are; the configuration service fills it as files are registered. */ + val databaseSources = DatabaseSources() + private val installer = UpdateInstaller( + identity, paths, configuration, resources.downloadHttp, + DatabaseBackups(paths.databases, databaseSources), + javaChoice = { product -> overrides.javaBuild(product.value) }, + installedJava = { product -> registrations.find(product.value)?.descriptor?.minimumJava }, + ) { + logging.log(this, LogLevel.WARNING, it) + } + private val freezes = FreezeStore(preferences) + private val graphResolver = UpdateGraphResolver(inventory, identity, configuration, resources.catalogGateway, freezes, overrides) { message, error -> + logging.log(this, LogLevel.ERROR, message, error) + } + private val runtime = UpdateOrchestratorRuntime( + configuration = configuration, + paths = paths, + logging = logging, + readiness = readiness, + installer = installer, + registrations = registrations::snapshot, + resolveGraph = ::resolveGraph, + stageGraph = ::stageGraph, + announce = ::announce, + automaticAllowed = { snapshot -> + automaticPolicy.allows(snapshot) && installer.automaticUpdatesHealthy(registrations.snapshot().map { it.descriptor.id }.toSet()) + }, + automaticOverridesActive = { overrides.anyAutomaticEnabled() }, + ) + private val orchestrator get() = runtime.orchestrator + + /** The settings file of older versions no longer does anything; it is kept aside so nothing is lost. */ + private fun retireOldSettingsFile() { + val old = paths.pluginFolder.resolve("updates.yml") + if (!Files.isRegularFile(old)) return + val kept = paths.pluginFolder.resolve("updates.yml.old") + Files.move(old, kept, java.nio.file.StandardCopyOption.REPLACE_EXISTING) + logging.log( + this, LogLevel.WARNING, + "updates.yml больше не используется: обновления настраиваются командой /pn update и в меню. Файл сохранён как ${kept.fileName}.", + ) + } + + override fun register( + owner: Any, + product: ProductDescriptor, + request: PluginUpdateRequest, + dependencies: List, + ): UpdateRegistration { + check(!closed.get()) { "Update service is closed" } + val (jar, pluginsDirectory, artifact) = registrationValidator.validate(owner, product, request) + val registration = RegisteredUpdate( + descriptor = product, + request = request, + artifact = artifact, + jar = jar, + updateDirectory = pluginsDirectory.resolve("update"), + selectedChannel = { graphResolver.channelFor(product.id, request.channel) }, + checkForUpdates = orchestrator::checkNow, + stagePlan = { snapshot -> orchestrator.stage(snapshot.id) }, + onClose = ::removeRegistration, + effectiveAutomatic = { + overrides.automatic(product.id.value) ?: request.automaticDownload + }, + platform = identity.type, + chosenJava = { overrides.javaBuild(product.id.value) }, + ) + check(!closed.get()) { "Update service is closed" } + registrations.add(registration) + orchestrator.registrationsChanged() + return registration + } + + override val products: UpdateProducts = object : UpdateProducts { + override fun all(): List = registrations.publicSnapshot() + override fun get(product: String): UpdateRegistration? = registrations.find(product) + } + + override val plans: UpdatePlans = object : UpdatePlans { + override fun check(actor: UpdateActor): CompletionStage = orchestrator.checkNow(actor = actor) + override fun current(): Optional = orchestrator.currentPlan() + override fun recent(): List = orchestrator.history() + override fun stage(planId: UUID, actor: UpdateActor): CompletionStage = orchestrator.stage(planId, actor) + } + + override val history: UpdateHistory = object : UpdateHistory { + override fun page(page: Int, product: String?): CompletionStage> = runtime.historyPage(page, product) + override fun count(product: String?): CompletionStage = runtime.historyCount(product) + } + + override val settings: UpdateSettings = object : UpdateSettings { + override fun channel(product: String, channel: UpdateChannel?, actor: UpdateActor): CompletionStage = + changeSetting(product, actor, recheck = true) { registration -> + val before = registration.snapshot.channel + val chosen = overrides.channel(registration.product) + when { + chosen == channel -> null + channel == null -> { + overrides.setChannel(registration.product, null) + val after = graphResolver.channelFor(registration) + "выбор канала снят: ${before.name.lowercase()} → ${after.name.lowercase()}, канал определяет плагин" + } + else -> { + overrides.setChannel(registration.product, channel) + "канал: ${before.name.lowercase()} → ${channel.name.lowercase()}" + } + } + } + + override fun javaBuild(product: String, java: Int?, actor: UpdateActor): CompletionStage = + changeSetting(product, actor, recheck = false) { registration -> + val available = registration.snapshot.javaBuilds + require(java == null || available.isEmpty() || java in available) { + "Для ${registration.product} нет сборки под Java $java. Есть: ${available.joinToString()}" + } + val before = overrides.javaBuild(registration.product) + if (before == java) null + else { + overrides.setJavaBuild(registration.product, java) + if (java == null) "сборка Java: выбор снят, подбирается подходящая" else "сборка Java: ${before ?: "подбор"} → $java" + } + } + + override fun automaticDownload(product: String, enabled: Boolean, actor: UpdateActor): CompletionStage = + changeSetting(product, actor, recheck = false) { registration -> + val before = registration.snapshot.automaticDownload + if (before == enabled) null + else { + overrides.setAutomatic(registration.product, enabled) + "автозагрузка: ${if (before) "вкл" else "выкл"} → ${if (enabled) "вкл" else "выкл"}" + } + } + + override fun automaticDownloadForAll(enabled: Boolean, actor: UpdateActor): CompletionStage> { + overrides.setAllPlugins(enabled, PnLibraryIdentity.PRODUCT_ID) + val state = if (enabled) "включена" else "выключена" + logging.log(this@UpdateServiceImpl, LogLevel.INFO, "Автозагрузка обновлений плагинов: $state для всех (${actor.name})") + return CompletableFuture.completedFuture(registrations.snapshot().map { it.snapshot }) + } + + override fun hold(product: String, duration: Duration, actor: UpdateActor): CompletionStage = + changeSetting(product, actor, recheck = true) { registration -> + val until = freezes.freeze(registration.descriptor.id, duration) + "обновления удержаны до ${HOLD_FORMAT.format(until.atZone(org.pnfolder.pnlibrary.common.time.DisplayZone.zone))}" + } + + override fun release(product: String, actor: UpdateActor): CompletionStage = + changeSetting(product, actor, recheck = true) { registration -> + if (freezes.clear(registration.descriptor.id)) "удержание обновлений снято" else null + } + + override fun heldUntil(product: String): Instant? = + registrations.find(product)?.let { freezes.active()[it.descriptor.id] } + } + + /** Applies one administrator setting, records it with its author and refreshes what readers see. */ + private fun changeSetting( + product: String, + actor: UpdateActor, + recheck: Boolean, + change: (RegisteredUpdate) -> String?, + ): CompletionStage { + val result = CompletableFuture() + try { + check(!closed.get()) { "Update service is closed" } + val registration = registrations.find(product) + ?: throw IllegalArgumentException("Плагин $product не зарегистрирован в pnLibrary") + val description = change(registration) + registration.refreshPolicy() + if (description != null) { + runtime.recordSettingsChange(registration, description, actor) + // The setting is already persisted, so a failed recheck is reported but does not fail the change. + if (recheck) runCatchingNonFatal { orchestrator.checkNow(actor = actor) }.onFailure { error -> + logging.log(this, LogLevel.ERROR, "Update recheck after a settings change failed", error) + } + } + result.complete(registration.snapshot) + } catch (error: Exception) { + result.completeExceptionally(error) + } + return result + } + + override val backups: UpdateBackups = object : UpdateBackups { + override fun list(): CompletionStage> = runtime.readAsync { + Collections.unmodifiableList(installer.backups()) + } + + override fun rollback(actor: UpdateActor): CompletionStage = + orchestrator.rollbackTo(actor) { installer.rollbackLatest() } + + override fun rollback(transactionId: UUID, actor: UpdateActor, restoreConfigurations: Boolean): CompletionStage = + orchestrator.rollbackTo(actor, transactionId) { installer.rollback(transactionId, restoreConfigurations) } + + override fun delete(transactionId: UUID, actor: UpdateActor): CompletionStage = runtime.readAsync { + installer.deleteBackup(transactionId) + logging.log(this@UpdateServiceImpl, LogLevel.INFO, "Резервный набор $transactionId удалён (${actor.name})") + null + } + + override fun restoreDatabase(transactionId: UUID, product: String, name: String, actor: UpdateActor): CompletionStage = + runtime.readAsync { + installer.restoreDatabase(transactionId, product, name) + logging.log(this@UpdateServiceImpl, LogLevel.WARNING, "База «$name» плагина $product возвращена из набора $transactionId (${actor.name})") + null + } + + override fun extract(transactionId: UUID, product: String, actor: UpdateActor): CompletionStage = runtime.readAsync { + val folder = installer.extractBackup(transactionId, product).toAbsolutePath().toString() + logging.log(this@UpdateServiceImpl, LogLevel.INFO, "Файлы плагина $product из набора $transactionId выданы в $folder (${actor.name})") + folder + } + } + + override fun close() { + if (!closed.compareAndSet(false, true)) return + registrations.close() + runtime.close() + resources.close() + } + + private companion object { + val HOLD_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMM HH:mm", Locale("ru")) + } + + private fun resolveGraph(refreshMode: RefreshMode = RefreshMode.CACHED): ResolutionResult = + graphResolver.resolve(registrations.snapshot(), refreshMode) + + private fun stageGraph(snapshot: UpdatePlanSnapshot) { + installer.stage(snapshot, registrations.snapshot()) + } + + private fun announce(snapshot: UpdatePlanSnapshot) { + UpdateAnnouncementRenderer.render(snapshot, consoleTheme, registrations.snapshot().map { it.snapshot }) + .forEach { logging.console(this, it) } + } + + private fun removeRegistration(registration: RegisteredUpdate) { + registrations.remove(registration) + orchestrator.registrationsChanged() + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalogSelectionTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalogSelectionTest.kt deleted file mode 100644 index 505e4bc6d..000000000 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalogSelectionTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -package org.pnfolder.pnlibrary.core.updates.engine - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.api.updates.UpdateChannel - -class ReleaseCatalogSelectionTest { - private val catalog = ReleaseCatalogCodec().decode( - requireNotNull(javaClass.getResourceAsStream("/catalog/releases.json")).readBytes(), - ) - - @Test - fun `stable ignores newer beta and dev releases`() { - val release = ReleaseCatalogSelector.select(catalog, UpdateChannel.STABLE, PlatformType.BUKKIT, 21, 1) - assertEquals("2.5.1", release!!.version.toString()) - } - - @Test - fun `beta selects newest stable or beta release`() { - val release = ReleaseCatalogSelector.select(catalog, UpdateChannel.BETA, PlatformType.BUKKIT, 21, 1) - assertEquals("2.6.0-beta.40", release!!.version.toString()) - } -} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdatePlanStagerTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdatePlanStagerTest.kt deleted file mode 100644 index c9eac409e..000000000 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdatePlanStagerTest.kt +++ /dev/null @@ -1,88 +0,0 @@ -package org.pnfolder.pnlibrary.core.updates.install - -import org.junit.jupiter.api.Assertions.* -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.api.updates.* -import org.pnfolder.pnlibrary.api.updates.release.* -import org.pnfolder.pnlibrary.api.version.ApiVersionRange -import org.pnfolder.pnlibrary.api.version.SemanticVersion -import org.pnfolder.pnlibrary.core.updates.engine.ArtifactVerificationException -import org.pnfolder.pnlibrary.core.updates.engine.ArtifactVerifier -import org.pnfolder.pnlibrary.core.updates.engine.TransactionJournal -import org.pnfolder.pnlibrary.core.updates.engine.TrustedHttpClient -import org.pnfolder.pnlibrary.core.updates.engine.UpdateTransaction -import java.net.URI -import java.nio.file.Files -import java.nio.file.Path -import java.security.MessageDigest -import java.time.Duration -import java.time.Instant -import java.util.UUID - -class UpdatePlanStagerTest { - @TempDir lateinit var directory: Path - private val bytes = byteArrayOf(1, 2, 3) - private val product = ProductId.of("pnlibrary") - private val version = SemanticVersion.parse("2.0.0") - private var downloads = 0 - - @Test - fun `published digest and size are checked before an update is exposed`() { - assertThrows(ArtifactVerificationException::class.java) { stage("00".repeat(32), bytes.size.toLong()) } - assertFalse(Files.exists(directory.resolve("plugins/update/library.jar"))) - assertArrayEquals(byteArrayOf(9), Files.readAllBytes(directory.resolve("plugins/library.jar"))) - assertThrows(ArtifactVerificationException::class.java) { stage(digest(), 100) } - assertFalse(Files.exists(directory.resolve("plugins/update/library.jar"))) - } - - @Test - fun `missing required checksum is rejected before making a download request`() { - assertThrows(IllegalArgumentException::class.java) { stage(null, null) } - assertEquals(0, downloads) - } - - @Test - fun `matching release metadata stages bytes while leaving the running artifact alone`() { - stage(digest(), bytes.size.toLong()) - assertArrayEquals(bytes, Files.readAllBytes(directory.resolve("plugins/update/library.jar"))) - assertArrayEquals(byteArrayOf(9), Files.readAllBytes(directory.resolve("plugins/library.jar"))) - } - - @Test - fun `saved transaction identifies the backup version time and originating plan`() { - val before = Instant.now() - stage(digest(), bytes.size.toLong()) - val root = directory.resolve("plugins/pnLibrary/updates/transactions") - val path = Files.list(root).use { it.findFirst().get().resolve("journal.json") } - val journal = TransactionJournal.load(path) - assertFalse(Instant.parse(journal.createdAt).isBefore(before)) - assertNotNull(UUID.fromString(journal.planId)) - assertEquals("1.0.0", journal.artifacts.single().previousVersion) - assertEquals("2.0.0", journal.artifacts.single().expectedVersion) - } - - private fun stage(hash: String?, size: Long?) { - val plugins = directory.resolve("plugins") - val data = plugins.resolve("pnLibrary") - Files.createDirectories(data) - val current = plugins.resolve("library.jar") - Files.write(current, byteArrayOf(9)) - val http = object : TrustedHttpClient(Duration.ofSeconds(1), Duration.ofSeconds(1)) { - override fun stream(uri: URI, maximumBytes: Long, reader: (java.io.InputStream) -> T): T { - downloads++ - return reader(java.io.ByteArrayInputStream(bytes)) - } - } - val artifact = ArtifactDescriptor("library-new.jar", PlatformType.BUKKIT, 8, null, - size, hash, URI("https://github.com/example/repo/releases/download/v2/library-new.jar")) - val release = ProductRelease(product, version, UpdateChannel.STABLE, ApiVersionRange(1, 1), artifacts = listOf(artifact)) - val plan = UpdatePlan(1, listOf(ProductChange(product, SemanticVersion.parse("1.0.0"), version)), listOf(release)) - val transaction = UpdateTransaction(data.resolve("updates/transactions"), ArtifactVerifier(1024), plugins) - UpdatePlanStager(PlatformType.BUKKIT, data, http, transaction, 1024).stage(UUID.randomUUID(), plan, - mapOf(product to InstalledUpdateTarget(current, plugins.resolve("update")))) - } - - private fun digest() = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } -} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateAutomaticPolicyTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateAutomaticPolicyTest.kt deleted file mode 100644 index 3756e88af..000000000 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateAutomaticPolicyTest.kt +++ /dev/null @@ -1,39 +0,0 @@ -package org.pnfolder.pnlibrary.core.updates.policy - -import org.junit.jupiter.api.Assertions.* -import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.updates.* -import org.pnfolder.pnlibrary.api.updates.release.* -import org.pnfolder.pnlibrary.api.version.SemanticVersion -import java.util.UUID - -class UpdateAutomaticPolicyTest { - @Test - fun `plugin automatic download does not opt the library into automatic replacement`() { - val config = UpdateConfiguration(pluginAutomaticDownload = true) - assertFalse(UpdateAutomaticPolicy(config) { emptyList() }.allows(plan("pnlibrary"))) - assertTrue(UpdateAutomaticPolicy(config.copy(library = UpdateConfiguration.LibraryPolicy(automaticDownload = true))) { - emptyList() - }.allows(plan("pnlibrary"))) - } - - @Test - fun `every member of an atomic plan needs automatic permission`() { - val config = UpdateConfiguration(library = UpdateConfiguration.LibraryPolicy(automaticDownload = true)) - val combined = plan("pnlibrary", "managed-module") - assertFalse(UpdateAutomaticPolicy(config) { emptyList() }.allows(combined)) - val allowed = config.copy(pluginAutomaticDownload = true) - assertTrue(UpdateAutomaticPolicy(allowed) { emptyList() }.allows(combined)) - assertFalse(UpdateAutomaticPolicy(allowed.copy(ignoredPlugins = setOf("managed-module"))) { emptyList() }.allows(combined)) - } - - @Test - fun `an explicitly disabled product cannot inherit a global automatic permission`() { - val config = UpdateConfiguration(pluginAutomaticDownload = true, ignoredPlugins = setOf("managed-module")) - assertFalse(UpdateAutomaticPolicy(config) { emptyList() }.allows(plan("managed-module"))) - } - - private fun plan(vararg products: String) = UpdatePlanSnapshot(UUID.randomUUID(), 1, UpdateState.UPDATE_AVAILABLE, - UpdatePlan(1, products.map { ProductChange(ProductId.of(it), SemanticVersion.parse("1.0.0"), SemanticVersion.parse("2.0.0")) }, - emptyList()), emptyList(), null) -} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateConfigurationTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateConfigurationTest.kt deleted file mode 100644 index 3a3981747..000000000 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdateConfigurationTest.kt +++ /dev/null @@ -1,142 +0,0 @@ -package org.pnfolder.pnlibrary.core.updates.policy - -import org.junit.jupiter.api.Assertions.* -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import java.nio.file.Files -import java.nio.file.Path - -class UpdateConfigurationTest { - @TempDir lateinit var directory: Path - - @Test - fun `lists plugins that are never updated and normalizes their identifiers`() { - val file = directory.resolve("updates.yml") - Files.writeString(file, """ - plugins: - ignored: [PnCases, acceptance] - """.trimIndent()) - - val configuration = UpdateConfiguration.load(file) - - assertEquals(setOf("pncases", "acceptance"), configuration.ignoredPlugins) - } - - @Test - fun `reads library and plugin download policy`() { - val file = directory.resolve("updates.yml") - Files.writeString(file, """ - library: - channel: beta - automatic-download: true - plugins: - automatic-download: false - """.trimIndent()) - - val configuration = UpdateConfiguration.load(file) - - // the library channel is fixed to dev in code; the file value is not applied - assertEquals(UpdateChannel.DEV, configuration.library.channel) - assertTrue(configuration.library.automaticDownload) - assertFalse(configuration.pluginAutomaticDownload) - assertTrue(configuration.ignoredPlugins.isEmpty()) - } - - @Test - fun `per-plugin policies and pause are not file options and are removed with a warning`() { - val file = directory.resolve("updates.yml") - Files.writeString(file, """ - plugins: - policies: - acceptance: { update: paused } - """.trimIndent()) - val warnings = mutableListOf() - - val configuration = UpdateConfiguration.load(file, warnings::add) - - assertTrue(configuration.ignoredPlugins.isEmpty()) - assertTrue(warnings.any { it.contains("policies") }) - assertFalse(Files.readString(file).contains("policies")) - } - - @Test - fun `an invalid plugin identifier makes the file fall back to safe defaults`() { - val file = directory.resolve("updates.yml") - Files.writeString(file, "plugins:\n ignored: [\"bad id!\"]\n") - val warnings = mutableListOf() - - val configuration = UpdateConfiguration.load(file, warnings::add) - - assertTrue(configuration.ignoredPlugins.isEmpty()) - assertTrue(warnings.isNotEmpty()) - } - - @Test - fun `switches, intervals and limits of the old file are ignored and cannot weaken the fixed rules`() { - val file = directory.resolve("updates.yml") - Files.writeString(file, """ - enabled: false - checks: { enabled: false, interval: 30m } - notifications: { console: false, repeat-interval: 1d } - downloads: { connect-timeout: 1s, max-artifact-megabytes: 1 } - installation: { require-sha256: false } - plugins: { enabled: false } - """.trimIndent()) - val warnings = mutableListOf() - - val configuration = UpdateConfiguration.load(file, warnings::add) - - assertEquals(UpdateDefaults.CHECK_INTERVAL, configuration.checks.interval) - assertEquals(UpdateDefaults.NOTIFICATION_REPEAT, configuration.notifications.repeatInterval) - assertEquals(UpdateDefaults.CONNECT_TIMEOUT, configuration.downloads.connectTimeout) - assertEquals(UpdateDefaults.MAX_ARTIFACT_BYTES, configuration.downloads.maxArtifactBytes) - assertTrue(configuration.installation.requireSha256) - val text = Files.readString(file) - listOf("checks", "notifications", "downloads", "require-sha256", "interval").forEach { assertFalse(text.contains(it), it) } - } - - @Test - fun `creates a short commented file with only the choices of an administrator`() { - val warnings = mutableListOf() - val file = directory.resolve("updates.yml") - val configuration = UpdateConfiguration.load(file, warnings::add) - - assertFalse(configuration.effectiveAutomaticDownloads) - assertFalse(configuration.installation.allowNewPlugins) - assertTrue(configuration.installation.requireSha256) - assertTrue(warnings.isEmpty()) - val text = Files.readString(file) - assertTrue(text.contains("allow-new-plugins: false")) - assertTrue(text.contains("ignored: []")) - assertFalse(text.contains("interval")) - } - - @Test - fun `an unreadable file falls back to safe defaults with a warning`() { - val file = directory.resolve("updates.yml") - Files.writeString(file, "plugins: [unclosed\n") - val warnings = mutableListOf() - - val configuration = UpdateConfiguration.load(file, warnings::add) - - assertFalse(configuration.effectiveAutomaticDownloads) - assertTrue(warnings.isNotEmpty()) - } - - @Test - fun `an invalid flag falls back to its safe default without granting rights`() { - val file = directory.resolve("updates.yml") - Files.writeString(file, """ - library: { automatic-download: perhaps } - installation: { allow-new-plugins: perhaps } - """.trimIndent()) - val warnings = mutableListOf() - - val configuration = UpdateConfiguration.load(file, warnings::add) - - assertFalse(configuration.library.automaticDownload) - assertFalse(configuration.installation.allowNewPlugins) - assertTrue(warnings.isNotEmpty()) - } -} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseBackupsTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseBackupsTest.kt new file mode 100644 index 000000000..5dfd3933d --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseBackupsTest.kt @@ -0,0 +1,59 @@ +package org.pnfolder.pnlibrary.updates.databases + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.config.DatabaseKind +import java.nio.file.Files +import java.nio.file.Path +import java.util.UUID + +class DatabaseBackupsTest { + @TempDir + lateinit var directory: Path + + private val restored = mutableListOf() + private val engine = object : DatabaseEngine { + override fun dump(connection: DatabaseConnection, tables: List, target: Path) { + Files.write(target, "dump".toByteArray()) + } + + override fun restore(connection: DatabaseConnection, source: Path) { + restored.add(source) + } + } + + private fun backups(sources: DatabaseSources = DatabaseSources()) = + DatabaseBackups(directory.resolve("databases"), sources, mapOf(DatabaseKind.MYSQL to engine)) + + @Test + fun `restore without a saved copy fails and touches nothing`() { + val error = assertThrows(IllegalArgumentException::class.java) { backups().restore(UUID.randomUUID(), "pnclans", "Кланы") } + assertTrue(error.message!!.contains("нет сохранённой базы")) + assertTrue(restored.isEmpty()) + } + + @Test + fun `restore of a copy whose plugin no longer describes the database fails before restoring`() { + val plan = UUID.randomUUID() + val saved = directory.resolve("databases/$plan/pnclans") + Files.createDirectories(saved) + Files.write(saved.resolve("%D0%9A.db.gz"), ByteArray(3)) + assertThrows(IllegalStateException::class.java) { backups().restore(plan, "pnclans", "К") } + assertTrue(restored.isEmpty()) + } + + @Test + fun `items of a plan without copies is empty`() { + assertEquals(emptyList(), backups().items(UUID.randomUUID())) + } + + @Test + fun `copying nothing creates nothing`() { + val plan = UUID.randomUUID() + backups().copyBefore(plan, listOf("pnclans")) + assertTrue(!Files.exists(directory.resolve("databases/$plan"))) + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseConnectionTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseConnectionTest.kt new file mode 100644 index 000000000..e8ef68bcc --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseConnectionTest.kt @@ -0,0 +1,79 @@ +package org.pnfolder.pnlibrary.updates.databases + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.config.DatabaseKind +import org.pnfolder.pnlibrary.api.config.DatabaseRole +import java.nio.file.Files +import java.nio.file.Path + +class DatabaseConnectionTest { + @TempDir + lateinit var directory: Path + + private fun source(yaml: String, path: String, keys: Map = emptyMap(), name: String = "Кланы"): DatabaseSource { + val file = directory.resolve("config.yml") + Files.write(file, yaml.toByteArray()) + return DatabaseSource("pnclans", DatabaseKind.MYSQL, name, file, path, keys) + } + + @Test + fun `usual names are found and the port defaults to 3306`() { + val connection = DatabaseConnection.read(source("storage:\n host: db.local\n database: clans\n username: root\n password: pw\n", "storage")) + assertEquals("root@db.local:3306/clans", connection.toString()) + assertEquals("pw", connection.password) + } + + @Test + fun `fields with other names are read through their roles`() { + val keys = mapOf( + DatabaseRole.HOST to "server-address", DatabaseRole.PORT to "tcp", DatabaseRole.DATABASE to "schema", + DatabaseRole.USER to "login", DatabaseRole.PASSWORD to "secret", + ) + val yaml = "mysql:\n server-address: 10.0.0.5\n tcp: 3307\n schema: s\n login: u\n secret: p\n" + assertEquals("u@10.0.0.5:3307/s", DatabaseConnection.read(source(yaml, "mysql", keys)).toString()) + } + + @Test + fun `a root level connection has an empty path`() { + assertEquals("u@h:3306/d", DatabaseConnection.read(source("host: h\ndatabase: d\nuser: u\n", "")).toString()) + } + + @Test + fun `two databases of one file do not get mixed up`() { + val yaml = "clans:\n host: a\n database: one\n user: u\nbank:\n host: b\n database: two\n user: u\n" + assertEquals("u@a:3306/one", DatabaseConnection.read(source(yaml, "clans", name = "Кланы")).toString()) + assertEquals("u@b:3306/two", DatabaseConnection.read(source(yaml, "bank", name = "Банк")).toString()) + } + + @Test + fun `a missing part is reported with the database name`() { + val error = assertThrows(IllegalStateException::class.java) { DatabaseConnection.read(source("storage:\n host: h\n", "storage")) } + assertEquals(true, error.message!!.contains("Кланы")) + } + + @Test + fun `a mongo connection may be a single connection string or parts without a user`() { + fun mongo(yaml: String) = source(yaml, "mongo").let { DatabaseSource(it.plugin, DatabaseKind.MONGODB, it.name, it.file, it.path, it.keys) } + assertEquals("uri/clans", DatabaseConnection.read(mongo("mongo:\n uri: mongodb://u:p@h/clans\n database: clans\n")).toString()) + assertEquals("@h:27017/clans", DatabaseConnection.read(mongo("mongo:\n host: h\n database: clans\n")).toString()) + } + + @Test + fun `only the listed tables and the tables named in marked fields are copied`() { + val yaml = "storage:\n host: h\n database: d\n user: u\n members: clan_members\n" + val base = source(yaml, "storage") + val marked = DatabaseSource(base.plugin, base.kind, base.name, base.file, base.path, base.keys, listOf("clans"), listOf("members")) + assertEquals(listOf("clans", "clan_members"), DatabaseConnection.read(marked).tables) + assertEquals(emptyList(), DatabaseConnection.read(base).tables) + } + + @Test + fun `an empty marked table field is an error and not a copy of everything`() { + val base = source("storage:\n host: h\n database: d\n user: u\n table: ''\n", "storage") + val marked = DatabaseSource(base.plugin, base.kind, base.name, base.file, base.path, base.keys, emptyList(), listOf("table")) + assertThrows(IllegalStateException::class.java) { DatabaseConnection.read(marked) } + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseSourcesTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseSourcesTest.kt new file mode 100644 index 000000000..0823bc321 --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/DatabaseSourcesTest.kt @@ -0,0 +1,31 @@ +package org.pnfolder.pnlibrary.updates.databases + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.config.DatabaseKind +import org.pnfolder.pnlibrary.api.plugin.PluginId +import org.pnfolder.pnlibrary.config.ManagedConfigFile +import org.pnfolder.pnlibrary.config.yaml.DatabasePath +import java.nio.file.Paths + +class DatabaseSourcesTest { + private fun file(vararg names: String) = ManagedConfigFile( + PluginId.of("pnClans"), Paths.get("plugins/pnClans"), "config.yml", emptyList(), + names.map { DatabasePath(it.lowercase(), DatabaseKind.MYSQL, it) }, + ) + + @Test + fun `databases are found by plugin without regard to case and forgotten on close`() { + val sources = DatabaseSources() + val handle = sources.register(file("Кланы", "Банк"))!! + assertEquals(listOf("Кланы", "Банк"), sources.of("PNCLANS").map { it.name }) + handle.close() + assertEquals(0, sources.of("pnclans").size) + } + + @Test + fun `two databases with one name are refused`() { + assertThrows(IllegalArgumentException::class.java) { DatabaseSources().register(file("Кланы", "Кланы")) } + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/SqlScriptRestoreTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/SqlScriptRestoreTest.kt new file mode 100644 index 000000000..8add7f95d --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/SqlScriptRestoreTest.kt @@ -0,0 +1,58 @@ +package org.pnfolder.pnlibrary.updates.databases + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.mockito.Mockito.inOrder +import org.mockito.Mockito.mock +import org.mockito.Mockito.never +import org.mockito.Mockito.verify +import org.mockito.Mockito.`when` +import java.nio.file.Files +import java.nio.file.Path +import java.sql.Connection +import java.sql.SQLException +import java.sql.Statement +import java.util.zip.GZIPOutputStream + +class SqlScriptRestoreTest { + @TempDir + lateinit var directory: Path + + private val statement = mock(Statement::class.java) + private val connection = mock(Connection::class.java).also { `when`(it.createStatement()).thenReturn(statement) } + + private fun script(vararg lines: String): Path { + val file = directory.resolve("copy.gz") + GZIPOutputStream(Files.newOutputStream(file)).use { it.write(lines.joinToString("\n").toByteArray()) } + return file + } + + @Test + fun `an atomic restore commits after the last statement`() { + SqlScriptRestore("-- h", atomic = true).read(connection, script("-- h", "A", "B")) + val order = inOrder(connection, statement) + order.verify(connection).autoCommit = false + order.verify(statement).execute("A") + order.verify(statement).execute("B") + order.verify(connection).commit() + } + + @Test + fun `an atomic restore rolls back when a statement fails`() { + `when`(statement.execute("B")).thenThrow(SQLException("boom")) + assertThrows(SQLException::class.java) { SqlScriptRestore("-- h", atomic = true).read(connection, script("-- h", "A", "B")) } + verify(connection).rollback() + verify(connection, never()).commit() + } + + @Test + fun `a plain restore uses autocommit and a foreign file is refused`() { + SqlScriptRestore("-- h").read(connection, script("-- h", "A")) + verify(connection).autoCommit = true + verify(connection, never()).commit() + assertThrows(IllegalArgumentException::class.java) { SqlScriptRestore("-- h").read(connection, script("-- other", "A")) } + assertEquals(1, Files.list(directory).use { it.count() }) + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/TableMaskTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/TableMaskTest.kt new file mode 100644 index 000000000..503b090fd --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/TableMaskTest.kt @@ -0,0 +1,24 @@ +package org.pnfolder.pnlibrary.updates.databases + +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class TableMaskTest { + @Test + fun `an empty list takes everything and a star stands for any text`() { + assertTrue(TableMask.matches(emptyList(), "anything")) + assertTrue(TableMask.matches(listOf("clans", "log_*"), "log_2026_11")) + assertTrue(TableMask.matches(listOf("clans"), "clans")) + assertFalse(TableMask.matches(listOf("clans"), "clans_old")) + assertFalse(TableMask.matches(listOf("log_*"), "blog_1")) + } + + @Test + fun `regex characters in a mask are plain text`() { + assertTrue(TableMask.matches(listOf("a.b"), "a.b")) + assertFalse(TableMask.matches(listOf("a.b"), "axb")) + assertTrue(TableMask.matches(listOf("t(1)+*"), "t(1)+rest")) + assertTrue(TableMask.matches(listOf("*"), "")) + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/mongo/MongoRestoreTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/mongo/MongoRestoreTest.kt new file mode 100644 index 000000000..de9d9ed13 --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/mongo/MongoRestoreTest.kt @@ -0,0 +1,33 @@ +package org.pnfolder.pnlibrary.updates.databases.mongo + +import com.mongodb.client.model.CollationStrength +import org.bson.BsonDocument +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class MongoRestoreTest { + @Test + fun `index keeps partial filter and collation`() { + val index = BsonDocument.parse( + """{"name":"a_1","key":{"a":1},"unique":true,"partialFilterExpression":{"a":{"${'$'}gt":1}}, + "collation":{"locale":"en","strength":2,"caseLevel":true,"caseFirst":"off"}}""", + ) + val options = MongoRestore.indexOptions(index) + assertEquals("a_1", options.name) + assertTrue(options.isUnique) + assertEquals(index.getDocument("partialFilterExpression"), options.partialFilterExpression!!.toBsonDocument()) + assertEquals("en", options.collation!!.locale) + assertEquals(CollationStrength.SECONDARY, options.collation!!.strength) + assertEquals(true, options.collation!!.caseLevel) + } + + @Test + fun `plain index has no extras`() { + val options = MongoRestore.indexOptions(BsonDocument.parse("""{"name":"b_1","key":{"b":1}}""")) + assertNull(options.partialFilterExpression) + assertNull(options.collation) + assertNull(options.getExpireAfter(java.util.concurrent.TimeUnit.SECONDS)) + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/mysql/MysqlSyntaxTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/mysql/MysqlSyntaxTest.kt new file mode 100644 index 000000000..b1d4942f6 --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/mysql/MysqlSyntaxTest.kt @@ -0,0 +1,24 @@ +package org.pnfolder.pnlibrary.updates.databases.mysql + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class MysqlSyntaxTest { + @Test + fun `a literal stays on one line and escapes quotes and backslashes`() { + val text = "it's a\\b\nc\r" + '\u0000' + '\u001a' + assertEquals("'it\\'s a\\\\b\\nc\\r\\0\\Z'", MysqlSyntax.literal(text)) + } + + @Test + fun `an identifier doubles its backticks`() { + assertEquals("`a``b`", MysqlSyntax.identifier("a`b")) + } + + @Test + fun `line breaks inside quotes are escaped and others become spaces`() { + val sql = "CREATE TABLE `t` (\n `a` int DEFAULT 'x\ny\\'z\r' COMMENT \"c\nd\"\n)" + val expected = "CREATE TABLE `t` ( `a` int DEFAULT 'x\\ny\\'z\\r' COMMENT \"c\\nd\" )" + assertEquals(expected, MysqlSyntax.singleLine(sql)) + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresSyntaxTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresSyntaxTest.kt new file mode 100644 index 000000000..2edb487ab --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/databases/postgres/PostgresSyntaxTest.kt @@ -0,0 +1,35 @@ +package org.pnfolder.pnlibrary.updates.databases.postgres + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class PostgresSyntaxTest { + @Test + fun `a literal stays on one line and escapes quotes backslashes and line breaks`() { + assertEquals("E'it''s a\\\\b\\nc\\r'", PostgresSyntax.literal("it's a\\b\nc\r")) + } + + @Test + fun `an identifier doubles its quotes and bytes become a hex literal`() { + assertEquals("\"a\"\"b\"", PostgresSyntax.identifier("a\"b")) + assertEquals("'\\x00ff'", PostgresSyntax.bytes(byteArrayOf(0, -1))) + } + + @Test + fun `an enum type is created once and quotes its labels`() { + assertEquals( + "DO \$\$ BEGIN CREATE TYPE \"mood\" AS ENUM (E'happy', E'it''s'); EXCEPTION WHEN duplicate_object THEN NULL; END \$\$", + PostgresSyntax.createEnum("mood", listOf("happy", "it's")), + ) + assertEquals(true, PostgresSyntax.createEnum("m", listOf("a\$\$b")).startsWith("DO \$pn\$ ")) + } + + @Test + fun `a sequence keeps its settings`() { + assertEquals( + "CREATE SEQUENCE IF NOT EXISTS \"s\" AS bigint INCREMENT BY 5 MINVALUE 1 MAXVALUE 99 START WITH 10 CYCLE", + PostgresSyntax.createSequence("s", "bigint", 10, 5, 1, 99, true), + ) + assertEquals(true, PostgresSyntax.createSequence("s", "integer", 1, 1, 1, 9, false).endsWith("START WITH 1 NO CYCLE")) + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/FreezePolicyTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/FreezePolicyTest.kt similarity index 74% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/FreezePolicyTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/FreezePolicyTest.kt index 055b5deb2..28f96d4c7 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/FreezePolicyTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/FreezePolicyTest.kt @@ -1,9 +1,9 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.updates.ProductId +import org.pnfolder.pnlibrary.api.updates.product.ProductId import java.nio.file.Files import java.nio.file.Path import java.time.Clock @@ -27,27 +27,27 @@ class FreezePolicyTest { @Test fun `a pause saved under the older thirty day limit ends within seven days`() { val clock = MutableClock(Instant.parse("2026-09-17T10:00:00Z")) - val file = directory.resolve("freezes.json") - Files.write(file, """{"pnmarket":${clock.instant().plus(Duration.ofDays(30)).toEpochMilli()}}""".toByteArray()) - assertEquals(Duration.ofDays(7), FreezeStore(file, clock).remaining(ProductId.of("pnmarket"))) + val file = directory.resolve("preferences.json") + Files.write(file, """{"freezes":{"pnmarket":${clock.instant().plus(Duration.ofDays(30)).toEpochMilli()}}}""".toByteArray()) + assertEquals(Duration.ofDays(7), FreezeStore(UpdatePreferencesStore(file), clock).remaining(ProductId.of("pnmarket"))) } @Test fun `persists absolute expiry and does not restart duration`() { val clock = MutableClock(Instant.parse("2026-09-17T10:00:00Z")) - val file = directory.resolve("freezes.json") + val file = directory.resolve("preferences.json") val market = ProductId.of("pnmarket") - FreezeStore(file, clock).freeze(market, Duration.ofHours(2)) + FreezeStore(UpdatePreferencesStore(file), clock).freeze(market, Duration.ofHours(2)) clock.advance(Duration.ofMinutes(30)) - val restarted = FreezeStore(file, clock) + val restarted = FreezeStore(UpdatePreferencesStore(file), clock) assertEquals(Duration.ofMinutes(90), restarted.remaining(market)) } @Test fun `expiry removes only the elapsed component`() { val clock = MutableClock(Instant.parse("2026-09-17T10:00:00Z")) - val store = FreezeStore(directory.resolve("freezes.json"), clock) + val store = FreezeStore(UpdatePreferencesStore(directory.resolve("preferences.json")), clock) val market = ProductId.of("pnmarket") val auth = ProductId.of("pnauth") store.freeze(market, Duration.ofMinutes(1)) diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/RepositoryLayoutTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/RepositoryLayoutTest.kt similarity index 95% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/RepositoryLayoutTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/RepositoryLayoutTest.kt index 042d97fe3..4731b576b 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/RepositoryLayoutTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/RepositoryLayoutTest.kt @@ -1,10 +1,12 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.updates.engine.catalog.ReleaseCatalog +import org.pnfolder.pnlibrary.updates.engine.catalog.ReleaseCatalogCodec import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdatePreferencesStoreTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdatePreferencesStoreTest.kt new file mode 100644 index 000000000..d8b1107b2 --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdatePreferencesStoreTest.kt @@ -0,0 +1,102 @@ +package org.pnfolder.pnlibrary.updates.engine + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.updates.policy.UpdatePolicyOverrides +import java.nio.file.Files +import java.nio.file.Path +import java.time.Clock +import java.time.Duration +import java.time.Instant +import java.time.ZoneOffset +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit + +class UpdatePreferencesStoreTest { + @TempDir + lateinit var directory: Path + + private val file get() = directory.resolve("updates/preferences.json") + private val clock = Clock.fixed(Instant.parse("2026-09-17T10:00:00Z"), ZoneOffset.UTC) + + @Test + fun `everything is saved in one file and read back`() { + val store = UpdatePreferencesStore(file) + store.update { it.copy(channels = mapOf("shop" to "BETA"), automatic = mapOf("shop" to true), allPlugins = false, freezes = mapOf("shop" to 5L)) } + + val reopened = UpdatePreferencesStore(file).current() + assertEquals(mapOf("shop" to "BETA"), reopened.channels) + assertEquals(mapOf("shop" to true), reopened.automatic) + assertEquals(false, reopened.allPlugins) + assertEquals(mapOf("shop" to 5L), reopened.freezes) + } + + @Test + fun `the choices and the pauses keep each others sections`() { + val store = UpdatePreferencesStore(file) + val overrides = UpdatePolicyOverrides(store) + val freezes = FreezeStore(store, clock) + val shop = ProductId.of("shop") + + freezes.freeze(shop, Duration.ofHours(2)) + overrides.setChannel("shop", UpdateChannel.RC) + overrides.setAutomatic("shop", true) + freezes.freeze(ProductId.of("auth"), Duration.ofHours(1)) + + val reopened = UpdatePreferencesStore(file) + assertEquals(UpdateChannel.RC, UpdatePolicyOverrides(reopened).channel("shop")) + assertEquals(true, UpdatePolicyOverrides(reopened).automatic("shop")) + assertEquals(setOf(shop, ProductId.of("auth")), FreezeStore(reopened, clock).active().keys) + } + + @Test + fun `concurrent saves from both owners are all kept`() { + val store = UpdatePreferencesStore(file) + val overrides = UpdatePolicyOverrides(store) + val freezes = FreezeStore(store, clock) + val workers = Executors.newFixedThreadPool(2) + val start = CountDownLatch(1) + val rounds = 40 + try { + val first = workers.submit { start.await(); repeat(rounds) { overrides.setAutomatic("p$it", true) } } + val second = workers.submit { start.await(); repeat(rounds) { freezes.freeze(ProductId.of("c$it"), Duration.ofHours(1)) } } + start.countDown() + first.get(30, TimeUnit.SECONDS) + second.get(30, TimeUnit.SECONDS) + } finally { + workers.shutdownNow() + } + + val reopened = UpdatePreferencesStore(file) + assertEquals(rounds, reopened.current().automatic.size) + assertEquals(rounds, FreezeStore(reopened, clock).active().size) + } + + @Test + fun `an unreadable file is reported and replaced by the next save`() { + Files.createDirectories(file.parent) + Files.writeString(file, "{ not json") + val warnings = mutableListOf() + val store = UpdatePreferencesStore(file, warnings::add) + + assertEquals(UpdatePreferencesStore.Preferences(), store.current()) + assertEquals(1, warnings.size) + store.update { it.copy(allPlugins = true) } + assertEquals(true, UpdatePreferencesStore(file).current().allPlugins) + } + + @Test + fun `nothing is written until something changes`() { + val store = UpdatePreferencesStore(file) + store.update { it } + assertFalse(Files.exists(file)) + store.update { it.copy(allPlugins = true) } + assertTrue(Files.exists(file)) + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateResolverTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdateResolverTest.kt similarity index 96% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateResolverTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdateResolverTest.kt index 17536e529..c0c2bd72d 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateResolverTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/UpdateResolverTest.kt @@ -1,12 +1,16 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.dependencies.* +import org.pnfolder.pnlibrary.api.dependencies.external.ExternalPluginDependency import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.updates.* +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.* +import org.pnfolder.pnlibrary.api.updates.state.BlockedReason import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalogClientTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/catalog/ReleaseCatalogClientTest.kt similarity index 92% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalogClientTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/catalog/ReleaseCatalogClientTest.kt index 9e8aa6a04..bfbfc84e9 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalogClientTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/catalog/ReleaseCatalogClientTest.kt @@ -1,8 +1,9 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.catalog import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient import java.net.URI import java.nio.file.Path import java.time.Duration diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalogCodecTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/catalog/ReleaseCatalogCodecTest.kt similarity index 96% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalogCodecTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/catalog/ReleaseCatalogCodecTest.kt index fdd1a31a1..c2e19256b 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/ReleaseCatalogCodecTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/catalog/ReleaseCatalogCodecTest.kt @@ -1,10 +1,10 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.catalog import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.api.updates.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel class ReleaseCatalogCodecTest { private val codec = ReleaseCatalogCodec() diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/net/TrustedHostsTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/net/TrustedHostsTest.kt new file mode 100644 index 000000000..87792f4e6 --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/net/TrustedHostsTest.kt @@ -0,0 +1,27 @@ +package org.pnfolder.pnlibrary.updates.engine.net + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import java.net.URI + +class TrustedHostsTest { + @Test + fun `github release and cdn links pass`() { + listOf( + "https://github.com/PnFolder/pnLibrary/releases/download/v1/pnLibrary-1.0.0-universal.jar", + "https://objects.githubusercontent.com/x/y.jar", + "https://release-assets.githubusercontent.com/x/y.jar", + "https://raw.githubusercontent.com/PnFolder/pnLibrary/main/x.jar", + "https://cdn.jsdelivr.net/gh/PnFolder/pnLibrary@main/x.jar", + ).forEach { assertEquals(URI(it), TrustedHosts.requireDownload(URI(it))) } + } + + @Test + fun `foreign host and plain http are refused`() { + assertThrows(IllegalArgumentException::class.java) { TrustedHosts.requireDownload(URI("https://evil.example.com/a.jar")) } + assertThrows(IllegalArgumentException::class.java) { TrustedHosts.requireDownload(URI("https://github.com.evil.com/a.jar")) } + assertThrows(IllegalArgumentException::class.java) { TrustedHosts.requireDownload(URI("http://github.com/a.jar")) } + assertThrows(IllegalArgumentException::class.java) { TrustedHosts.requireRedirect(URI("https://evil.example.com/a.jar")) } + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TrustedHttpClientTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/net/TrustedHttpClientTest.kt similarity index 96% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TrustedHttpClientTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/net/TrustedHttpClientTest.kt index 70c10f5bf..b7fb13f79 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/TrustedHttpClientTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/net/TrustedHttpClientTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.net import org.junit.jupiter.api.Assertions.assertArrayEquals import org.junit.jupiter.api.Assertions.assertEquals diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateTransactionFailureAfterPublishTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/UpdateTransactionFailureAfterPublishTest.kt similarity index 90% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateTransactionFailureAfterPublishTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/UpdateTransactionFailureAfterPublishTest.kt index c00e0e3ff..523760986 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateTransactionFailureAfterPublishTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/UpdateTransactionFailureAfterPublishTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.transaction import org.junit.jupiter.api.Assertions.assertArrayEquals import org.junit.jupiter.api.Assertions.assertEquals @@ -7,11 +7,13 @@ import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.updates.ProductId import org.pnfolder.pnlibrary.api.updates.backup.UpdateConfigurationBackup +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion -import org.pnfolder.pnlibrary.core.updates.history.ConfigurationSnapshots +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactSpecification +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactVerifier +import org.pnfolder.pnlibrary.updates.history.ConfigurationSnapshots import java.nio.file.Files import java.nio.file.Path import java.security.MessageDigest diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateTransactionTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/UpdateTransactionTest.kt similarity index 86% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateTransactionTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/UpdateTransactionTest.kt index 95a41047f..284744de1 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/engine/UpdateTransactionTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/engine/transaction/UpdateTransactionTest.kt @@ -1,13 +1,18 @@ -package org.pnfolder.pnlibrary.core.updates.engine +package org.pnfolder.pnlibrary.updates.engine.transaction import org.junit.jupiter.api.Assertions.assertArrayEquals import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.updates.ProductId +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactDownloadException +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactDownloader +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactSpecification +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactVerificationException +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactVerifier import java.io.ByteArrayInputStream import java.nio.file.Files import java.nio.file.Path @@ -19,6 +24,23 @@ import java.util.jar.JarOutputStream class UpdateTransactionTest { @TempDir lateinit var directory: Path + @Test + fun `corrupt journal is skipped with a warning and does not break other operations`() { + val root = directory.resolve("transactions") + val broken = root.resolve(UUID.randomUUID().toString()).also(Files::createDirectories).resolve("journal.json") + Files.write(broken, ByteArray(0)) + val warnings = mutableListOf() + val transaction = UpdateTransaction(root, ArtifactVerifier(1024), warn = { warnings += it }) + + assertEquals(emptyList(), transaction.recoverAll()) + assertEquals(emptyList(), transaction.awaitingHealth()) + assertEquals(emptyList(), transaction.awaitingRollbackHealth()) + assertEquals(emptyList(), transaction.pendingInstallations()) + assertEquals(emptyList(), transaction.failedHealthChecks()) + assertTrue(transaction.automaticUpdatesHealthy(setOf("market"))) + assertTrue(warnings.isNotEmpty() && warnings.all { it.contains("journal.json") }, warnings.toString()) + } + @Test fun `verifier rejects checksum mismatches`() { val jar = artifact("market.jar", "market", "2.0.0", 4, byteArrayOf(1, 2, 3)) @@ -255,6 +277,22 @@ class UpdateTransactionTest { assertThrows(Exception::class.java) { transaction.rollbackCandidate(UUID.randomUUID()) } } + @Test + fun `an unreadable journal is reported and does not hide the other rollback sets`() { + val plugins = directory.resolve("plugins").also(Files::createDirectories) + val target = plugins.resolve("market.jar").also { Files.write(it, byteArrayOf(9)) } + val root = directory.resolve("transactions") + val warnings = mutableListOf() + val transaction = UpdateTransaction(root, ArtifactVerifier(1024 * 1024), plugins, warn = { warnings += it }) + val source = artifact("first.jar", "market", "2.0.0", 4, byteArrayOf(1)) + val saved = transaction.apply(listOf(TransactionArtifact(specification(source, "market", "2.0.0", 4), source, target))) { true } + Files.write(root.resolve(UUID.randomUUID().toString()).also(Files::createDirectories).resolve("journal.json"), ByteArray(0)) + + assertEquals(listOf(saved.journal), transaction.rollbackCandidates()) + assertEquals(saved.journal, transaction.latestRollbackCandidate()) + assertTrue(warnings.any { it.contains("journal.json") }, warnings.toString()) + } + @Test fun `tampered target is rejected before any rollback file is changed`() { val plugins = directory.resolve("plugins").also(Files::createDirectories) diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/BackupStorageTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/BackupStorageTest.kt new file mode 100644 index 000000000..8c4b7995b --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/BackupStorageTest.kt @@ -0,0 +1,70 @@ +package org.pnfolder.pnlibrary.updates.history + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.updates.backup.BackupKind +import org.pnfolder.pnlibrary.api.updates.backup.UpdateBackupItem +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import java.nio.file.Files +import java.nio.file.Path +import java.time.Duration +import java.time.Instant + +class BackupStorageTest { + @TempDir + lateinit var directory: Path + + @Test + fun `a set expires only after thirty days and never without a date`() { + val now = Instant.parse("2026-11-06T00:00:00Z") + assertFalse(BackupStorage.expired(now.minus(Duration.ofDays(29)), now)) + assertTrue(BackupStorage.expired(now.minus(Duration.ofDays(31)), now)) + assertFalse(BackupStorage.expired(null, now)) + } + + @Test + fun `deleting a folder removes its files and counts their size first`() { + val folder = Files.createDirectories(directory.resolve("set/blobs")) + Files.write(folder.resolve("a.bin"), ByteArray(1500)) + Files.write(directory.resolve("set/manifest.json"), ByteArray(500)) + assertEquals(2000, BackupStorage.bytes(directory.resolve("set"))) + BackupStorage.delete(directory.resolve("set")) + assertFalse(Files.exists(directory.resolve("set"))) + assertEquals(0, BackupStorage.bytes(directory.resolve("set"))) + } + + @Test + fun `an item is described by its kind, name and size`() { + val item = UpdateBackupItem(ProductId.of("pnclans"), BackupKind.DATABASE, "Кланы", 3L * 1024 * 1024) + assertEquals("pnclans: База данных «Кланы» · 3.0 МБ", BackupItemText.describe(item)) + assertEquals("pnclans: Конфигурация · 10 Б", BackupItemText.describe(UpdateBackupItem(ProductId.of("pnclans"), BackupKind.CONFIGURATION, "", 10))) + } + + @Test + fun `child ignores letter case and returns null for a missing name or parent`() { + Files.createDirectories(directory.resolve("parent/PnClans")) + Files.write(directory.resolve("parent/file"), ByteArray(1)) + assertEquals("PnClans", BackupStorage.child(directory.resolve("parent"), "pnclans")?.fileName.toString()) + assertEquals(null, BackupStorage.child(directory.resolve("parent"), "file")) + assertEquals(null, BackupStorage.child(directory.resolve("parent"), "other")) + assertEquals(null, BackupStorage.child(directory.resolve("missing"), "x")) + } + + @Test + fun `copy keeps the structure, replaces existing files and copies empty folders`() { + val from = Files.createDirectories(directory.resolve("from/sub")) + Files.createDirectories(directory.resolve("from/empty")) + Files.write(from.resolve("a.txt"), "new".toByteArray()) + Files.createDirectories(directory.resolve("to")) + Files.write(directory.resolve("to/a.txt"), "old".toByteArray()) + Files.write(directory.resolve("from/top.txt"), "t".toByteArray()) + BackupStorage.copy(directory.resolve("from"), directory.resolve("to")) + assertEquals("new", Files.readString(directory.resolve("to/sub/a.txt"))) + assertEquals("t", Files.readString(directory.resolve("to/top.txt"))) + assertTrue(Files.isDirectory(directory.resolve("to/empty"))) + assertEquals("old", Files.readString(directory.resolve("to/a.txt"))) + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/history/ConfigurationRestorerTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/ConfigurationRestorerTest.kt similarity index 97% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/history/ConfigurationRestorerTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/ConfigurationRestorerTest.kt index 57112fa45..0b6df7b17 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/history/ConfigurationRestorerTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/ConfigurationRestorerTest.kt @@ -1,11 +1,11 @@ -package org.pnfolder.pnlibrary.core.updates.history +package org.pnfolder.pnlibrary.updates.history import com.google.gson.Gson import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.updates.ProductId import org.pnfolder.pnlibrary.api.updates.backup.UpdateConfigurationBackup +import org.pnfolder.pnlibrary.api.updates.product.ProductId import java.nio.file.Files import java.nio.file.Path import java.util.UUID diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/history/ConfigurationSnapshotsTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/ConfigurationSnapshotsTest.kt similarity index 82% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/history/ConfigurationSnapshotsTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/ConfigurationSnapshotsTest.kt index 9cd28f7f9..f6a46c7c5 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/history/ConfigurationSnapshotsTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/ConfigurationSnapshotsTest.kt @@ -1,11 +1,11 @@ -package org.pnfolder.pnlibrary.core.updates.history +package org.pnfolder.pnlibrary.updates.history import com.google.gson.Gson import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.updates.ProductId import org.pnfolder.pnlibrary.api.updates.backup.UpdateConfigurationBackup +import org.pnfolder.pnlibrary.api.updates.product.ProductId import java.nio.file.Files import java.nio.file.Path import java.util.UUID @@ -61,6 +61,17 @@ class ConfigurationSnapshotsTest { assertThrows(IllegalArgumentException::class.java) { UpdateConfigurationBackup(data, listOf("../outside.yml")) } } + @Test + fun `a failed capture leaves no half-written snapshot folder`() { + val (_, data) = fixture() + val store = ConfigurationSnapshots(directory.resolve("snapshots"), directory.resolve("plugins"), maximumTotalBytes = 4) + Files.writeString(data.resolve("a.yml"), "123") + Files.writeString(data.resolve("b.yml"), "456") + val selection = UpdateConfigurationBackup(data, listOf("a.yml", "b.yml")) + assertThrows(IllegalArgumentException::class.java) { store.capture(UUID.randomUUID(), mapOf(ProductId.of("example") to selection)) } + Files.list(directory.resolve("snapshots")).use { assertEquals(0, it.count()) } + } + private fun fixture(): Pair { val plugins = directory.resolve("plugins") val data = plugins.resolve("example").also(Files::createDirectories) diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/PrivateFilesTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/PrivateFilesTest.kt new file mode 100644 index 000000000..88a109ed5 --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/PrivateFilesTest.kt @@ -0,0 +1,28 @@ +package org.pnfolder.pnlibrary.updates.history + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assumptions.assumeTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.FileSystems +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.attribute.PosixFilePermissions + +class PrivateFilesTest { + @TempDir + lateinit var directory: Path + + @Test + fun `files and folders are private and an old file is replaced`() { + assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) + val folder = directory.resolve("a/b") + PrivateFiles.directories(folder) + val file = folder.resolve("x.gz") + Files.write(file, ByteArray(5)) + PrivateFiles.output(file).use { it.write(1) } + assertEquals("rwx------", PosixFilePermissions.toString(Files.getPosixFilePermissions(folder))) + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(file))) + assertEquals(1, Files.size(file)) + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/history/UpdateEventJournalTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/UpdateEventJournalTest.kt similarity index 95% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/history/UpdateEventJournalTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/UpdateEventJournalTest.kt index 0a007f363..4b1307a6d 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/history/UpdateEventJournalTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/UpdateEventJournalTest.kt @@ -1,10 +1,14 @@ -package org.pnfolder.pnlibrary.core.updates.history +package org.pnfolder.pnlibrary.updates.history import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import org.pnfolder.pnlibrary.api.updates.* +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.updates.release.* +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.SemanticVersion import java.nio.file.Files import java.nio.file.Path diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/history/UpdateStateStoreTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/UpdateStateStoreTest.kt similarity index 91% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/history/UpdateStateStoreTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/UpdateStateStoreTest.kt index f47ac6a24..dd405e6f6 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/history/UpdateStateStoreTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/history/UpdateStateStoreTest.kt @@ -1,12 +1,15 @@ -package org.pnfolder.pnlibrary.core.updates.history +package org.pnfolder.pnlibrary.updates.history import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import org.pnfolder.pnlibrary.api.updates.* -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.* +import org.pnfolder.pnlibrary.api.updates.state.BlockedReason +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion import java.nio.file.Files diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/CatalogSourceRefTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/CatalogSourceRefTest.kt similarity index 82% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/CatalogSourceRefTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/CatalogSourceRefTest.kt index 0239af228..95c20e65e 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/CatalogSourceRefTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/CatalogSourceRefTest.kt @@ -1,10 +1,10 @@ -package org.pnfolder.pnlibrary.core.updates.install +package org.pnfolder.pnlibrary.updates.install import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.updates.CatalogSource -import org.pnfolder.pnlibrary.api.updates.CatalogSource.RefType +import org.pnfolder.pnlibrary.api.updates.request.CatalogSource +import org.pnfolder.pnlibrary.api.updates.request.CatalogSource.RefType class CatalogSourceRefTest { @Test diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/ComponentLedgerTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/ComponentLedgerTest.kt similarity index 89% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/ComponentLedgerTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/ComponentLedgerTest.kt index ae39a4ef2..7ab97aaaf 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/ComponentLedgerTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/ComponentLedgerTest.kt @@ -1,10 +1,11 @@ -package org.pnfolder.pnlibrary.core.updates.install +package org.pnfolder.pnlibrary.updates.install import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.core.updates.history.UpdateEventJournal +import org.pnfolder.pnlibrary.updates.history.UpdateEventJournal +import org.pnfolder.pnlibrary.updates.install.ComponentOperation import java.nio.file.Files import java.nio.file.Path import java.time.Clock @@ -41,9 +42,9 @@ class ComponentLedgerTest { val recorded = history().toSet() assertEquals( setOf( - ComponentLedger.OPERATION_ADDED to "shop", - ComponentLedger.OPERATION_REMOVED to "currency", - ComponentLedger.OPERATION_VERSION_CHANGED to "pnlibrary", + ComponentOperation.ADDED to "shop", + ComponentOperation.REMOVED to "currency", + ComponentOperation.VERSION_CHANGED to "pnlibrary", ), recorded, ) @@ -65,7 +66,7 @@ class ComponentLedgerTest { ledger.observe(mapOf("pnlibrary" to component("2.0.0", "beta", true))) val event = journal.read().single() - assertEquals(ComponentLedger.OPERATION_SETTINGS_CHANGED, event.operation) + assertEquals(ComponentOperation.SETTINGS_CHANGED, event.operation) assertEquals("канал: stable → beta; автозагрузка: выкл → вкл", event.message) } diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/OfflineUpdateInstallerTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/OfflineUpdateInstallerTest.kt similarity index 88% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/OfflineUpdateInstallerTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/OfflineUpdateInstallerTest.kt index c65c5fa16..940eef97a 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/OfflineUpdateInstallerTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/OfflineUpdateInstallerTest.kt @@ -1,15 +1,19 @@ -package org.pnfolder.pnlibrary.core.updates.install +package org.pnfolder.pnlibrary.updates.install import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.updates.ProductId import org.pnfolder.pnlibrary.api.updates.backup.UpdateConfigurationBackup +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion -import org.pnfolder.pnlibrary.core.updates.engine.* -import org.pnfolder.pnlibrary.core.updates.history.ConfigurationSnapshots -import org.pnfolder.pnlibrary.core.updates.service.UpdateInstallationLock +import org.pnfolder.pnlibrary.updates.engine.* +import org.pnfolder.pnlibrary.updates.engine.catalog.* +import org.pnfolder.pnlibrary.updates.engine.net.* +import org.pnfolder.pnlibrary.updates.engine.transaction.* +import org.pnfolder.pnlibrary.updates.history.ConfigurationSnapshots +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import org.pnfolder.pnlibrary.updates.service.UpdateInstallationLock import java.nio.file.Files import java.nio.file.Path import java.security.MessageDigest @@ -38,7 +42,7 @@ class OfflineUpdateInstallerTest { @Test fun `active runtime lock prevents any offline changes`() { val fixture = prepare() - UpdateInstallationLock.acquire(fixture.data).use { + UpdateInstallationLock.acquire(LibraryPaths(fixture.data)).use { assertThrows(IllegalStateException::class.java) { OfflineUpdateInstaller.apply(fixture.data) } } assertArrayEquals(byteArrayOf(1), Files.readAllBytes(fixture.active)) @@ -98,11 +102,11 @@ class OfflineUpdateInstallerTest { val api = ApiVersionRange(8, 8) val digest = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } val specification = ArtifactSpecification(ProductId.of("pnlibrary"), SemanticVersion.parse("2.0.0"), api, "release.jar", bytes.size.toLong(), digest) - val transactions = UpdateTransaction(data.resolve("updates/transactions"), ArtifactVerifier(1024), plugins) + val transactions = UpdateTransaction(LibraryPaths(data).transactions, ArtifactVerifier(1024), plugins) val plan = UUID.randomUUID() val snapshot = if (configuration) { Files.writeString(data.resolve("config.yml"), "version: 1") - ConfigurationSnapshots(data.resolve("updates/configurations"), plugins).capture(plan, + ConfigurationSnapshots(LibraryPaths(data).configurations, plugins).capture(plan, mapOf(ProductId.of("pnlibrary") to UpdateConfigurationBackup(data, listOf("config.yml")))) } else null val result = transactions.prepareForRestart(listOf(TransactionArtifact(specification, source, pending, active, diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/OfflineUpdaterJarTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/OfflineUpdaterJarTest.kt similarity index 82% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/OfflineUpdaterJarTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/OfflineUpdaterJarTest.kt index 7e023363b..be2b8f213 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/OfflineUpdaterJarTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/OfflineUpdaterJarTest.kt @@ -1,16 +1,20 @@ -package org.pnfolder.pnlibrary.core.updates.install +package org.pnfolder.pnlibrary.updates.install import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.io.TempDir import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource -import org.pnfolder.pnlibrary.api.updates.ProductId import org.pnfolder.pnlibrary.api.updates.backup.UpdateConfigurationBackup +import org.pnfolder.pnlibrary.api.updates.product.ProductId import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion -import org.pnfolder.pnlibrary.core.updates.engine.* -import org.pnfolder.pnlibrary.core.updates.history.ConfigurationSnapshots -import org.pnfolder.pnlibrary.core.updates.service.UpdateInstallationLock +import org.pnfolder.pnlibrary.updates.engine.* +import org.pnfolder.pnlibrary.updates.engine.catalog.* +import org.pnfolder.pnlibrary.updates.engine.net.* +import org.pnfolder.pnlibrary.updates.engine.transaction.* +import org.pnfolder.pnlibrary.updates.history.ConfigurationSnapshots +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import org.pnfolder.pnlibrary.updates.service.UpdateInstallationLock import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths @@ -30,16 +34,16 @@ class OfflineUpdaterJarTest { val source = directory.resolve("release.jar").also { Files.write(it, byteArrayOf(2, 3)) } val api = ApiVersionRange(8, 8) val specification = ArtifactSpecification(ProductId.of("pnlibrary"), SemanticVersion.parse("2.0.0"), api, "release.jar") - val transactions = UpdateTransaction(data.resolve("updates/transactions"), ArtifactVerifier(1024), plugins) + val transactions = UpdateTransaction(LibraryPaths(data).transactions, ArtifactVerifier(1024), plugins) val plan = UUID.randomUUID() val config = data.resolve("config.yml").also { Files.writeString(it, "version: 1") } val unrelated = data.resolve("unrelated.yml").also { Files.writeString(it, "keep") } - val snapshots = ConfigurationSnapshots(data.resolve("updates/configurations"), plugins) + val snapshots = ConfigurationSnapshots(LibraryPaths(data).configurations, plugins) val snapshot = snapshots.capture(plan, mapOf(ProductId.of("pnlibrary") to UpdateConfigurationBackup(data, listOf("config.yml", "optional.yml")))) val saved = transactions.prepareForRestart(listOf(TransactionArtifact(specification, source, plugins.resolve("update/library.jar"), active, "1.0.0", api, active)), planId = plan, targetApi = 8, configurationSnapshot = snapshot) - UpdateInstallationLock.acquire(data).use { assertNotEquals(0, runUpdater(data)) } + UpdateInstallationLock.acquire(LibraryPaths(data)).use { assertNotEquals(0, runUpdater(data)) } assertArrayEquals(byteArrayOf(1), Files.readAllBytes(active)) assertEquals(0, runUpdater(data)) assertArrayEquals(byteArrayOf(2, 3), Files.readAllBytes(active)) diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/ReleaseCatalogGatewayTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/ReleaseCatalogGatewayTest.kt similarity index 67% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/ReleaseCatalogGatewayTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/ReleaseCatalogGatewayTest.kt index 4cdeb22a2..e5a8fcaa3 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/ReleaseCatalogGatewayTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/ReleaseCatalogGatewayTest.kt @@ -1,15 +1,15 @@ -package org.pnfolder.pnlibrary.core.updates.install +package org.pnfolder.pnlibrary.updates.install import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTimeoutPreemptively import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.updates.CatalogSource -import org.pnfolder.pnlibrary.core.updates.engine.RefreshMode -import org.pnfolder.pnlibrary.core.updates.engine.ReleaseCatalog -import org.pnfolder.pnlibrary.core.updates.engine.ReleaseCatalogClient -import org.pnfolder.pnlibrary.core.updates.engine.ReleaseCatalogStore -import org.pnfolder.pnlibrary.core.updates.engine.TrustedHttpClient +import org.pnfolder.pnlibrary.api.updates.request.CatalogSource +import org.pnfolder.pnlibrary.updates.engine.catalog.RefreshMode +import org.pnfolder.pnlibrary.updates.engine.catalog.ReleaseCatalog +import org.pnfolder.pnlibrary.updates.engine.catalog.ReleaseCatalogClient +import org.pnfolder.pnlibrary.updates.engine.catalog.ReleaseCatalogStore +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient import java.net.URI import java.nio.file.Path import java.time.Duration @@ -86,6 +86,41 @@ class ReleaseCatalogGatewayTest { } } + @Test + fun `jsDelivr is asked only when raw and api both fail`() { + val executor = Executors.newFixedThreadPool(4) + val requested = java.util.concurrent.CopyOnWriteArrayList() + val fresh = catalogJson().toByteArray() + val stale = catalogJson().replace("1.0.0", "0.9.0").toByteArray() + fun gateway(githubWorks: Boolean): ReleaseCatalogGateway { + val http = object : TrustedHttpClient(Duration.ofSeconds(1), Duration.ofSeconds(1)) { + override fun get(uri: URI, maximumBytes: Int): ByteArray { + requested += uri.host + return when { + uri.host == "cdn.jsdelivr.net" -> stale + !githubWorks -> throw java.io.IOException("HTTP 503") + uri.host == "api.github.com" -> + """{"content":"${Base64.getEncoder().encodeToString(fresh)}"}""".toByteArray() + else -> fresh + } + } + } + val store = ReleaseCatalogStore(temporaryDirectory.resolve("cdn-$githubWorks")) + return ReleaseCatalogGateway(ReleaseCatalogClient(http, store, executor, Duration.ofMinutes(30)), http, executor) + } + try { + val source = CatalogSource("owner", "example") + val ok = gateway(true).load(source, RefreshMode.FORCE_REMOTE) + assertEquals("1.0.0", ok.releases.single().version.toString()) + org.junit.jupiter.api.Assertions.assertFalse(requested.contains("cdn.jsdelivr.net"), requested.toString()) + + val fallback = gateway(false).load(source, RefreshMode.FORCE_REMOTE) + assertEquals("0.9.0", fallback.releases.single().version.toString()) + } finally { + executor.shutdownNow() + } + } + private fun catalogJson(): String = """ { "schema": 1, diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdateGraphResolverTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/UpdateGraphResolverTest.kt similarity index 82% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdateGraphResolverTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/UpdateGraphResolverTest.kt index e6bbec9ef..8b63ef425 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/install/UpdateGraphResolverTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/UpdateGraphResolverTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.install +package org.pnfolder.pnlibrary.updates.install import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows @@ -12,20 +12,21 @@ import org.mockito.Mockito.verifyNoInteractions import org.mockito.Mockito.`when` import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.CatalogSource -import org.pnfolder.pnlibrary.api.updates.PluginUpdateRequest -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.core.updates.engine.FreezeStore -import org.pnfolder.pnlibrary.core.updates.engine.RefreshMode -import org.pnfolder.pnlibrary.core.updates.engine.ReleaseCatalog -import org.pnfolder.pnlibrary.core.updates.engine.ResolutionResult -import org.pnfolder.pnlibrary.core.updates.policy.UpdateConfiguration -import org.pnfolder.pnlibrary.core.updates.policy.UpdatePolicyOverrides -import org.pnfolder.pnlibrary.core.updates.service.RegisteredUpdate +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.request.CatalogSource +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity import org.pnfolder.pnlibrary.spi.platform.PlatformPluginInventory +import org.pnfolder.pnlibrary.updates.engine.FreezeStore +import org.pnfolder.pnlibrary.updates.engine.ResolutionResult +import org.pnfolder.pnlibrary.updates.engine.UpdatePreferencesStore +import org.pnfolder.pnlibrary.updates.engine.catalog.RefreshMode +import org.pnfolder.pnlibrary.updates.engine.catalog.ReleaseCatalog +import org.pnfolder.pnlibrary.updates.policy.UpdateConfiguration +import org.pnfolder.pnlibrary.updates.policy.UpdatePolicyOverrides +import org.pnfolder.pnlibrary.updates.service.RegisteredUpdate import java.nio.file.Path import java.nio.file.Paths import java.util.concurrent.CompletableFuture @@ -63,7 +64,7 @@ class UpdateGraphResolverTest { private fun resolver( configuration: UpdateConfiguration = UpdateConfiguration(), overrides: UpdatePolicyOverrides? = null, - ) = UpdateGraphResolver(inventory, identity, configuration, catalogs, FreezeStore(directory.resolve("freezes.json")), overrides) + ) = UpdateGraphResolver(inventory, identity, configuration, catalogs, FreezeStore(UpdatePreferencesStore(directory.resolve("preferences.json"))), overrides) @Test fun `nothing registered resolves to an empty plan without loading any catalog`() { diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/UpdatePlanStagerTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/UpdatePlanStagerTest.kt new file mode 100644 index 000000000..7fe600323 --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/install/UpdatePlanStagerTest.kt @@ -0,0 +1,139 @@ +package org.pnfolder.pnlibrary.updates.install + +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.platform.PlatformType +import org.pnfolder.pnlibrary.api.updates.* +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.release.* +import org.pnfolder.pnlibrary.api.version.ApiVersionRange +import org.pnfolder.pnlibrary.api.version.SemanticVersion +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactVerificationException +import org.pnfolder.pnlibrary.updates.engine.net.ArtifactVerifier +import org.pnfolder.pnlibrary.updates.engine.net.TrustedHttpClient +import org.pnfolder.pnlibrary.updates.engine.transaction.TransactionJournal +import org.pnfolder.pnlibrary.updates.engine.transaction.UpdateTransaction +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import java.net.URI +import java.nio.file.Files +import java.nio.file.Path +import java.security.MessageDigest +import java.time.Duration +import java.time.Instant +import java.util.UUID + +class UpdatePlanStagerTest { + @TempDir lateinit var directory: Path + private val bytes = byteArrayOf(1, 2, 3) + private val product = ProductId.of("pnlibrary") + private val version = SemanticVersion.parse("2.0.0") + private var downloads = 0 + + @Test + fun `published digest and size are checked before an update is exposed`() { + assertThrows(ArtifactVerificationException::class.java) { stage("00".repeat(32), bytes.size.toLong()) } + assertFalse(Files.exists(directory.resolve("plugins/update/library.jar"))) + assertArrayEquals(byteArrayOf(9), Files.readAllBytes(directory.resolve("plugins/library.jar"))) + assertThrows(ArtifactVerificationException::class.java) { stage(digest(), 100) } + assertFalse(Files.exists(directory.resolve("plugins/update/library.jar"))) + } + + @Test + fun `missing required checksum is rejected before making a download request`() { + assertThrows(IllegalArgumentException::class.java) { stage(null, null) } + assertEquals(0, downloads) + } + + @Test + fun `matching release metadata stages bytes while leaving the running artifact alone`() { + stage(digest(), bytes.size.toLong()) + assertArrayEquals(bytes, Files.readAllBytes(directory.resolve("plugins/update/library.jar"))) + assertArrayEquals(byteArrayOf(9), Files.readAllBytes(directory.resolve("plugins/library.jar"))) + } + + @Test + fun `saved transaction identifies the backup version time and originating plan`() { + val before = Instant.now() + stage(digest(), bytes.size.toLong()) + val root = directory.resolve("plugins/pnLibrary/data/updates/transactions") + val path = Files.list(root).use { it.findFirst().get().resolve("journal.json") } + val journal = TransactionJournal.load(path) + assertFalse(Instant.parse(journal.createdAt).isBefore(before)) + assertNotNull(UUID.fromString(journal.planId)) + assertEquals("1.0.0", journal.artifacts.single().previousVersion) + assertEquals("2.0.0", journal.artifacts.single().expectedVersion) + } + + @Test + fun `refuses to download from a host outside the trusted list`() { + val error = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException::class.java) { + stage(digest(), bytes.size.toLong(), "https://evil.example.com/library-new.jar") + } + org.junit.jupiter.api.Assertions.assertTrue(error.message!!.contains("evil.example.com")) + assertEquals(0, downloads) + } + + @Test + fun `the Java build the administrator chose wins, then the one that matches the installed product`() { + assertEquals("build-11.jar", downloadedBuild(choice = 11, installed = 8)) + assertEquals("build-8.jar", downloadedBuild(choice = 8, installed = 11)) + assertEquals("build-8.jar", downloadedBuild(choice = null, installed = 8)) + assertEquals("build-11.jar", downloadedBuild(choice = null, installed = 11)) + // nothing chosen and nothing known: the old behaviour, the first build that fits + assertEquals("build-8.jar", downloadedBuild(choice = null, installed = null)) + // a choice no build fits is ignored in favour of the installed one + assertEquals("build-11.jar", downloadedBuild(choice = 99, installed = 11)) + } + + private fun downloadedBuild(choice: Int?, installed: Int?): String { + val root = java.nio.file.Files.createTempDirectory(directory, "choice") + val plugins = root.resolve("plugins") + val data = plugins.resolve("pnLibrary") + Files.createDirectories(data) + val current = plugins.resolve("library.jar") + Files.write(current, byteArrayOf(9)) + var downloaded = "" + val http = object : TrustedHttpClient(Duration.ofSeconds(1), Duration.ofSeconds(1)) { + override fun stream(uri: URI, maximumBytes: Long, reader: (java.io.InputStream) -> T): T { + downloaded = uri.path.substringAfterLast('/') + return reader(java.io.ByteArrayInputStream(bytes)) + } + } + val artifacts = listOf(8, 11).map { java -> + ArtifactDescriptor("build-$java.jar", PlatformType.BUKKIT, java, null, bytes.size.toLong(), digest(), + URI("https://github.com/example/repo/releases/download/v2/build-$java.jar")) + } + val release = ProductRelease(product, version, UpdateChannel.STABLE, ApiVersionRange(1, 1), artifacts = artifacts) + val plan = UpdatePlan(1, listOf(ProductChange(product, SemanticVersion.parse("1.0.0"), version)), listOf(release)) + val transaction = UpdateTransaction(LibraryPaths(data).transactions, ArtifactVerifier(1024), plugins) + UpdatePlanStager(PlatformType.BUKKIT, LibraryPaths(data), http, transaction, 1024, true, { choice }, { installed }).stage( + UUID.randomUUID(), plan, mapOf(product to InstalledUpdateTarget(current, plugins.resolve("update"))), + ) + return downloaded + } + + private fun stage(hash: String?, size: Long?, url: String = "https://github.com/example/repo/releases/download/v2/library-new.jar") { + val plugins = directory.resolve("plugins") + val data = plugins.resolve("pnLibrary") + Files.createDirectories(data) + val current = plugins.resolve("library.jar") + Files.write(current, byteArrayOf(9)) + val http = object : TrustedHttpClient(Duration.ofSeconds(1), Duration.ofSeconds(1)) { + override fun stream(uri: URI, maximumBytes: Long, reader: (java.io.InputStream) -> T): T { + downloads++ + return reader(java.io.ByteArrayInputStream(bytes)) + } + } + val artifact = ArtifactDescriptor("library-new.jar", PlatformType.BUKKIT, 8, null, + size, hash, URI(url)) + val release = ProductRelease(product, version, UpdateChannel.STABLE, ApiVersionRange(1, 1), artifacts = listOf(artifact)) + val plan = UpdatePlan(1, listOf(ProductChange(product, SemanticVersion.parse("1.0.0"), version)), listOf(release)) + val transaction = UpdateTransaction(LibraryPaths(data).transactions, ArtifactVerifier(1024), plugins) + UpdatePlanStager(PlatformType.BUKKIT, LibraryPaths(data), http, transaction, 1024).stage(UUID.randomUUID(), plan, + mapOf(product to InstalledUpdateTarget(current, plugins.resolve("update")))) + } + + private fun digest() = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/paths/LegacyPathsMigrationTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/paths/LegacyPathsMigrationTest.kt new file mode 100644 index 000000000..7d727abef --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/paths/LegacyPathsMigrationTest.kt @@ -0,0 +1,132 @@ +package org.pnfolder.pnlibrary.updates.paths + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.updates.engine.FreezeStore +import org.pnfolder.pnlibrary.updates.engine.UpdatePreferencesStore +import org.pnfolder.pnlibrary.updates.policy.UpdatePolicyOverrides +import java.nio.file.Files +import java.nio.file.Path +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset + +class LegacyPathsMigrationTest { + @TempDir + lateinit var directory: Path + + private val plugin get() = directory.resolve("plugins/pnLibrary") + private val paths get() = LibraryPaths(plugin) + private val warnings = mutableListOf() + + private fun write(relative: String, text: String): Path = + plugin.resolve(relative).also { Files.createDirectories(it.parent); Files.writeString(it, text) } + + private fun migrate() = LegacyPathsMigration(paths, warnings::add).run() + + @Test + fun `old state is moved into data and the old places are gone`() { + write("updates/components.json", "components") + write("updates/transactions/one/journal.json", "transaction") + write("journal/day.log", "journal") + write("reports/report.zip", "report") + write("observability/observations.jsonl", "observations") + write("diagnostics/history/incident.json", "incident") + write("task-history.tsv", "tasks") + write("event-history.tsv", "events") + write("upload-ledger.json", "ledger") + write("downloads/pins.state", "pins") + write("config.yml", "keep") + + migrate() + + assertEquals("components", Files.readString(paths.components)) + assertEquals("transaction", Files.readString(paths.transactions.resolve("one/journal.json"))) + assertEquals("journal", Files.readString(paths.journal.resolve("day.log"))) + assertEquals("report", Files.readString(paths.reports.resolve("report.zip"))) + assertEquals("observations", Files.readString(paths.observations)) + assertEquals("incident", Files.readString(paths.diagnosticsHistory.resolve("incident.json"))) + assertEquals("tasks", Files.readString(paths.taskHistory)) + assertEquals("events", Files.readString(paths.eventHistory)) + assertEquals("ledger", Files.readString(paths.uploadLedger)) + assertEquals("pins", Files.readString(paths.downloads.resolve("pins.state"))) + listOf("updates", "journal", "reports", "observability", "diagnostics", "task-history.tsv", "event-history.tsv", "upload-ledger.json", "downloads") + .forEach { assertFalse(Files.exists(plugin.resolve(it)), it) } + assertEquals("keep", Files.readString(paths.legacyConfig)) + assertTrue(warnings.isEmpty(), warnings.toString()) + } + + @Test + fun `an existing new location is never overwritten`() { + write("task-history.tsv", "old") + write("data/history/task-history.tsv", "new") + write("updates/components.json", "old") + write("data/updates/components.json", "new") + write("updates/catalog/cache.json", "old catalog") + + migrate() + + assertEquals("new", Files.readString(paths.taskHistory)) + assertEquals("old", Files.readString(plugin.resolve("task-history.tsv"))) + assertEquals("new", Files.readString(paths.components)) + assertEquals("old", Files.readString(plugin.resolve("updates/components.json"))) + assertEquals("old catalog", Files.readString(paths.catalog.resolve("cache.json"))) + } + + @Test + fun `a fresh install and a repeated run change nothing`() { + migrate() + assertFalse(Files.exists(paths.data)) + write("task-history.tsv", "tasks") + migrate() + migrate() + assertEquals("tasks", Files.readString(paths.taskHistory)) + assertTrue(warnings.isEmpty()) + } + + @Test + fun `the two old settings files become one preferences file and are removed`() { + write("updates/settings.json", """{"allPlugins":true,"channels":{"shop":"BETA"},"automatic":{"shop":false}}""") + write("updates/freezes.json", """{"shop":${Instant.parse("2026-09-17T12:00:00Z").toEpochMilli()}}""") + + migrate() + + assertFalse(Files.exists(paths.updates.resolve("settings.json"))) + assertFalse(Files.exists(paths.updates.resolve("freezes.json"))) + val store = UpdatePreferencesStore(paths.preferences) + val overrides = UpdatePolicyOverrides(store) + assertEquals(UpdateChannel.BETA, overrides.channel("shop")) + assertEquals(false, overrides.automatic("shop")) + assertEquals(true, overrides.allPlugins()) + val clock = Clock.fixed(Instant.parse("2026-09-17T10:00:00Z"), ZoneOffset.UTC) + assertEquals(setOf(ProductId.of("shop")), FreezeStore(store, clock).active().keys) + } + + @Test + fun `an unreadable old settings file is kept and the other one is still merged`() { + write("updates/settings.json", "{ broken") + write("updates/freezes.json", """{"shop":4102444800000}""") + + migrate() + + assertTrue(Files.exists(paths.updates.resolve("settings.json"))) + assertFalse(Files.exists(paths.updates.resolve("freezes.json"))) + assertEquals(mapOf("shop" to 4102444800000L), UpdatePreferencesStore(paths.preferences).current().freezes) + assertEquals(1, warnings.size, warnings.toString()) + } + + @Test + fun `old settings do not replace a preferences file that already exists`() { + write("data/updates/preferences.json", """{"allPlugins":false}""") + write("data/updates/settings.json", """{"allPlugins":true}""") + + migrate() + + assertEquals(false, UpdatePreferencesStore(paths.preferences).current().allPlugins) + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/paths/LibraryPathsTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/paths/LibraryPathsTest.kt new file mode 100644 index 000000000..bd429a781 --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/paths/LibraryPathsTest.kt @@ -0,0 +1,51 @@ +package org.pnfolder.pnlibrary.updates.paths + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path + +class LibraryPathsTest { + @TempDir + lateinit var directory: Path + + private val outsideData = setOf( + "pluginFolder", "plugins", "serverUpdateFolder", "legacyConfig", "legacyDownloadsConfig", "localization", "data", + ) + + private fun locations(paths: LibraryPaths): Map = + LibraryPaths::class.java.methods + .filter { it.parameterCount == 0 && Path::class.java.isAssignableFrom(it.returnType) && it.name.startsWith("get") } + .associate { it.name.removePrefix("get").replaceFirstChar(Char::lowercaseChar) to it.invoke(paths) as Path } + + @Test + fun `every state location lies under the data folder and nothing else does`() { + val plugin = directory.resolve("plugins/pnLibrary") + val paths = LibraryPaths(plugin) + + val (outside, inside) = locations(paths).entries.partition { it.key in outsideData } + assertEquals(outsideData, outside.map { it.key }.toSet()) + assertTrue(inside.isNotEmpty()) + inside.forEach { (name, path) -> assertTrue(path.startsWith(paths.data) && path != paths.data, "$name is $path") } + assertEquals(plugin.resolve("data"), paths.data) + } + + @Test + fun `administrator files and the server update folder stay out of data`() { + val plugin = directory.resolve("plugins/pnLibrary") + val paths = LibraryPaths(plugin) + + assertEquals(plugin.resolve("config.yml"), paths.legacyConfig) + assertEquals(plugin.resolve("downloads.yml"), paths.legacyDownloadsConfig) + assertEquals(plugin.resolve("localization"), paths.localization) + assertEquals(directory.resolve("plugins/update"), paths.serverUpdateFolder) + assertEquals(directory.resolve("plugins"), paths.plugins) + } + + @Test + fun `no two state locations are the same`() { + val inside = locations(LibraryPaths(directory.resolve("plugins/pnLibrary"))).filterKeys { it !in outsideData } + assertEquals(inside.size, inside.values.toSet().size) + } +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/policy/ReleaseChannelSelectorTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/policy/ReleaseChannelSelectorTest.kt similarity index 91% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/policy/ReleaseChannelSelectorTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/policy/ReleaseChannelSelectorTest.kt index 957551ef5..8ad81934a 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/policy/ReleaseChannelSelectorTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/policy/ReleaseChannelSelectorTest.kt @@ -1,10 +1,10 @@ -package org.pnfolder.pnlibrary.core.updates.policy +package org.pnfolder.pnlibrary.updates.policy import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ArtifactDescriptor import org.pnfolder.pnlibrary.api.updates.release.ProductRelease import org.pnfolder.pnlibrary.api.version.ApiVersionRange diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateAutomaticPolicyTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateAutomaticPolicyTest.kt new file mode 100644 index 000000000..aaf93b92f --- /dev/null +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdateAutomaticPolicyTest.kt @@ -0,0 +1,66 @@ +package org.pnfolder.pnlibrary.updates.policy + +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.pnfolder.pnlibrary.api.updates.* +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.release.* +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState +import org.pnfolder.pnlibrary.api.version.SemanticVersion +import org.pnfolder.pnlibrary.updates.engine.UpdatePreferencesStore +import java.nio.file.Path +import java.util.UUID + +class UpdateAutomaticPolicyTest { + @TempDir + lateinit var directory: Path + + private fun overrides() = UpdatePolicyOverrides(UpdatePreferencesStore(directory.resolve("preferences.json"))) + + @Test + fun `plugin automatic download does not opt the library into automatic replacement`() { + val config = UpdateConfiguration(pluginAutomaticDownload = true, library = UpdateConfiguration.LibraryPolicy(automaticDownload = false)) + assertFalse(UpdateAutomaticPolicy(config) { emptyList() }.allows(plan("pnlibrary"))) + assertTrue(UpdateAutomaticPolicy(config.copy(library = UpdateConfiguration.LibraryPolicy(automaticDownload = true))) { + emptyList() + }.allows(plan("pnlibrary"))) + } + + @Test + fun `every member of an atomic plan needs automatic permission`() { + val config = UpdateConfiguration(pluginAutomaticDownload = false) + val combined = plan("pnlibrary", "managed-module") + assertFalse(UpdateAutomaticPolicy(config) { emptyList() }.allows(combined)) + assertTrue(UpdateAutomaticPolicy(config.copy(pluginAutomaticDownload = true)) { emptyList() }.allows(combined)) + } + + @Test + fun `plugins update automatically unless an administrator switched it off`() { + assertTrue(UpdateAutomaticPolicy(UpdateConfiguration()) { emptyList() }.allows(plan("managed-module"))) + } + + @Test + fun `an explicitly disabled product cannot inherit a global automatic permission`() { + val overrides = overrides().apply { setAutomatic("managed-module", false) } + assertFalse(UpdateAutomaticPolicy(UpdateConfiguration(pluginAutomaticDownload = true), overrides) { emptyList() }.allows(plan("managed-module"))) + } + + @Test + fun `switching all plugins off drops single choices and keeps the library choice`() { + val overrides = overrides().apply { + setAutomatic("managed-module", true) + setAutomatic("pnlibrary", true) + setAllPlugins(false, "pnlibrary") + } + val policy = UpdateAutomaticPolicy(UpdateConfiguration(), overrides) { emptyList() } + assertFalse(policy.allows(plan("managed-module"))) + assertTrue(policy.allows(plan("pnlibrary"))) + assertEquals(false, overrides.allPlugins()) + } + + private fun plan(vararg products: String) = UpdatePlanSnapshot(UUID.randomUUID(), 1, UpdateState.UPDATE_AVAILABLE, + UpdatePlan(1, products.map { ProductChange(ProductId.of(it), SemanticVersion.parse("1.0.0"), SemanticVersion.parse("2.0.0")) }, + emptyList()), emptyList(), null) +} diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdatePolicyOverridesTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdatePolicyOverridesTest.kt similarity index 75% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdatePolicyOverridesTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdatePolicyOverridesTest.kt index 7e819e02f..ec5a6e804 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/policy/UpdatePolicyOverridesTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/policy/UpdatePolicyOverridesTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.policy +package org.pnfolder.pnlibrary.updates.policy import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse @@ -6,7 +6,8 @@ import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir -import org.pnfolder.pnlibrary.api.updates.UpdateChannel +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel +import org.pnfolder.pnlibrary.updates.engine.UpdatePreferencesStore import java.nio.file.Files import java.nio.file.Path @@ -14,11 +15,11 @@ class UpdatePolicyOverridesTest { @TempDir lateinit var directory: Path - private val file get() = directory.resolve("updates/settings.json") + private val file get() = directory.resolve("updates/preferences.json") @Test fun `nothing is overridden until a choice is made`() { - val overrides = UpdatePolicyOverrides(file) + val overrides = UpdatePolicyOverrides(UpdatePreferencesStore(file)) assertNull(overrides.channel("pnlibrary")) assertNull(overrides.automatic("pnlibrary")) assertFalse(overrides.anyAutomaticEnabled()) @@ -27,7 +28,7 @@ class UpdatePolicyOverridesTest { @Test fun `choices apply immediately and survive reopening`() { - val overrides = UpdatePolicyOverrides(file) + val overrides = UpdatePolicyOverrides(UpdatePreferencesStore(file)) overrides.setChannel("pnlibrary", UpdateChannel.BETA) overrides.setAutomatic("pnlibrary", true) overrides.setAutomatic("shop", false) @@ -35,7 +36,7 @@ class UpdatePolicyOverridesTest { assertEquals(UpdateChannel.BETA, overrides.channel("pnlibrary")) assertTrue(overrides.anyAutomaticEnabled()) - val reopened = UpdatePolicyOverrides(file) + val reopened = UpdatePolicyOverrides(UpdatePreferencesStore(file)) assertEquals(UpdateChannel.BETA, reopened.channel("pnlibrary")) assertEquals(true, reopened.automatic("pnlibrary")) assertEquals(false, reopened.automatic("shop")) @@ -44,7 +45,7 @@ class UpdatePolicyOverridesTest { @Test fun `a later choice replaces the earlier one and turning everything off clears the flag`() { - val overrides = UpdatePolicyOverrides(file) + val overrides = UpdatePolicyOverrides(UpdatePreferencesStore(file)) overrides.setAutomatic("pnlibrary", true) overrides.setAutomatic("pnlibrary", false) overrides.setChannel("pnlibrary", UpdateChannel.RC) @@ -56,14 +57,14 @@ class UpdatePolicyOverridesTest { @Test fun `removing a channel choice hands the decision back to the plugin and survives reopening`() { - val overrides = UpdatePolicyOverrides(file) + val overrides = UpdatePolicyOverrides(UpdatePreferencesStore(file)) overrides.setChannel("shop", UpdateChannel.BETA) overrides.setChannel("pnlibrary", UpdateChannel.RC) overrides.setChannel("shop", null) assertNull(overrides.channel("shop")) - val reopened = UpdatePolicyOverrides(file) + val reopened = UpdatePolicyOverrides(UpdatePreferencesStore(file)) assertNull(reopened.channel("shop")) assertEquals(UpdateChannel.RC, reopened.channel("pnlibrary")) } @@ -73,11 +74,11 @@ class UpdatePolicyOverridesTest { Files.createDirectories(file.parent) Files.writeString(file, "{ not json") val warnings = mutableListOf() - assertNull(UpdatePolicyOverrides(file, warnings::add).channel("pnlibrary")) + assertNull(UpdatePolicyOverrides(UpdatePreferencesStore(file, warnings::add)).channel("pnlibrary")) assertEquals(1, warnings.size) Files.writeString(file, """{"channels":{"pnlibrary":"nightly","shop":"BETA"},"automatic":{}}""") - val tolerant = UpdatePolicyOverrides(file) + val tolerant = UpdatePolicyOverrides(UpdatePreferencesStore(file)) assertNull(tolerant.channel("pnlibrary")) assertEquals(UpdateChannel.BETA, tolerant.channel("shop")) } diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/service/NativeProxyUpdateTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/NativeProxyUpdateTest.kt similarity index 94% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/service/NativeProxyUpdateTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/NativeProxyUpdateTest.kt index d7295e85c..508ab04d9 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/service/NativeProxyUpdateTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/NativeProxyUpdateTest.kt @@ -1,16 +1,22 @@ -package org.pnfolder.pnlibrary.core.updates.service +package org.pnfolder.pnlibrary.updates.service import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.updates.* import org.pnfolder.pnlibrary.api.updates.backup.* +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.PnLibraryApi import org.pnfolder.pnlibrary.api.version.SemanticVersion -import org.pnfolder.pnlibrary.core.updates.engine.* -import org.pnfolder.pnlibrary.core.updates.history.ConfigurationSnapshots -import org.pnfolder.pnlibrary.core.updates.history.UpdateEventJournal +import org.pnfolder.pnlibrary.updates.engine.* +import org.pnfolder.pnlibrary.updates.engine.catalog.* +import org.pnfolder.pnlibrary.updates.engine.net.* +import org.pnfolder.pnlibrary.updates.engine.transaction.* +import org.pnfolder.pnlibrary.updates.history.ConfigurationSnapshots +import org.pnfolder.pnlibrary.updates.history.UpdateEventJournal +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths import java.net.InetAddress import java.net.ServerSocket import java.nio.file.Files @@ -72,9 +78,9 @@ class NativeProxyUpdateTest { val product = ProductId.of("pnlibrary") val api = ApiVersionRange(PnLibraryApi.VERSION, PnLibraryApi.VERSION) val planId = UUID.randomUUID() - val configs = ConfigurationSnapshots(data.resolve("updates/configurations"), plugins) + val configs = ConfigurationSnapshots(LibraryPaths(data).configurations, plugins) val configId = configs.capture(planId, mapOf(product to UpdateConfigurationBackup(data, listOf("updates.yml")))) - val transactions = UpdateTransaction(data.resolve("updates/transactions"), ArtifactVerifier(128L * 1024 * 1024), plugins) + val transactions = UpdateTransaction(LibraryPaths(data).transactions, ArtifactVerifier(128L * 1024 * 1024), plugins) val saved = transactions.prepareForRestart(listOf(TransactionArtifact( ArtifactSpecification(product, SemanticVersion.parse(targetVersion), api, "release.jar", Files.size(release), digest(release)), release, plugins.resolve("update/pnLibrary.jar"), installed, originalVersion, api, installed, @@ -107,7 +113,7 @@ class NativeProxyUpdateTest { } server.command("$command history", "откат подтверждён после перезапуска") } - val events = UpdateEventJournal(data.resolve("updates/events")).read(pageSize = 100) + val events = UpdateEventJournal(LibraryPaths(data).events).read(pageSize = 100) val applied = events.single { it.operation == "HEALTH" && it.planId == planId } assertEquals(UpdateActor.Kind.SYSTEM, applied.actor.kind) assertEquals(listOf(UpdateEventJournal.Change("pnlibrary", originalVersion, targetVersion)), applied.changes) diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/service/RegisteredUpdateTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/RegisteredUpdateTest.kt similarity index 93% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/service/RegisteredUpdateTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/RegisteredUpdateTest.kt index dc8633283..43c28bb7e 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/service/RegisteredUpdateTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/RegisteredUpdateTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.core.updates.service +package org.pnfolder.pnlibrary.updates.service import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull @@ -7,16 +7,16 @@ import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.mockito.Mockito.mock import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.api.updates.PluginUpdateRequest -import org.pnfolder.pnlibrary.api.updates.ProductDescriptor -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.product.ProductDescriptor +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ProductRelease +import org.pnfolder.pnlibrary.api.updates.request.PluginUpdateRequest +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion -import org.pnfolder.pnlibrary.core.updates.engine.CatalogArtifact -import org.pnfolder.pnlibrary.core.updates.engine.CatalogRelease +import org.pnfolder.pnlibrary.updates.engine.catalog.CatalogArtifact +import org.pnfolder.pnlibrary.updates.engine.catalog.CatalogRelease import java.net.URI import java.nio.file.Paths import java.time.Instant diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateAnnouncementRendererTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateAnnouncementRendererTest.kt similarity index 90% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateAnnouncementRendererTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateAnnouncementRendererTest.kt index 34621ff80..ebf9bd56b 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/catalog/UpdateAnnouncementRendererTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateAnnouncementRendererTest.kt @@ -1,16 +1,16 @@ -package org.pnfolder.pnlibrary.core.updates.catalog +package org.pnfolder.pnlibrary.updates.service import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.platform.PlatformType -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ArtifactDescriptor import org.pnfolder.pnlibrary.api.updates.release.ProductChange import org.pnfolder.pnlibrary.api.updates.release.ProductRelease import org.pnfolder.pnlibrary.api.updates.release.UpdatePlan +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion import java.net.URI diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateHealthHistoryTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateHealthHistoryTest.kt similarity index 81% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateHealthHistoryTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateHealthHistoryTest.kt index 85a82a291..540fd7c3f 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateHealthHistoryTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateHealthHistoryTest.kt @@ -1,18 +1,27 @@ -package org.pnfolder.pnlibrary.core.updates.service +package org.pnfolder.pnlibrary.updates.service import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.updates.* +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion -import org.pnfolder.pnlibrary.core.updates.engine.* -import org.pnfolder.pnlibrary.core.updates.history.UpdateEventJournal -import org.pnfolder.pnlibrary.core.updates.history.UpdateStateStore -import org.pnfolder.pnlibrary.core.updates.install.UpdateInstaller -import org.pnfolder.pnlibrary.core.updates.policy.UpdateConfiguration import org.pnfolder.pnlibrary.spi.platform.PlatformIdentity +import org.pnfolder.pnlibrary.updates.databases.DatabaseBackups +import org.pnfolder.pnlibrary.updates.databases.DatabaseSources +import org.pnfolder.pnlibrary.updates.engine.* +import org.pnfolder.pnlibrary.updates.engine.catalog.* +import org.pnfolder.pnlibrary.updates.engine.net.* +import org.pnfolder.pnlibrary.updates.engine.transaction.* +import org.pnfolder.pnlibrary.updates.history.UpdateEventJournal +import org.pnfolder.pnlibrary.updates.history.UpdateStateStore +import org.pnfolder.pnlibrary.updates.install.UpdateInstaller +import org.pnfolder.pnlibrary.updates.paths.LibraryPaths +import org.pnfolder.pnlibrary.updates.policy.UpdateConfiguration import java.net.URI import java.nio.file.Files import java.nio.file.Path @@ -26,9 +35,9 @@ class UpdateHealthHistoryTest { fun `health history uses the original transaction rather than the latest resolver snapshot`() { val fixture = fixture() val unrelated = UUID.randomUUID() - val state = UpdateStateStore(fixture.data.resolve("updates")) + val state = UpdateStateStore(LibraryPaths(fixture.data).updates) state.save(UpdatePlanSnapshot(unrelated, 99, UpdateState.UPDATE_AVAILABLE, null, emptyList(), "newer check")) - val events = UpdateEventJournal(fixture.data.resolve("updates/events")) + val events = UpdateEventJournal(LibraryPaths(fixture.data).events) fixture.installer.reconcileVersions(mapOf("pnlibrary" to "2.0.0"), { events.recordHealth(it) }) val event = events.read().single() assertEquals(fixture.plan, event.planId) @@ -98,7 +107,7 @@ class UpdateHealthHistoryTest { val source = directory.resolve("release.jar").also { Files.write(it, byteArrayOf(2)) } val api = ApiVersionRange(8, 8) val specification = ArtifactSpecification(ProductId.of("pnlibrary"), SemanticVersion.parse("2.0.0"), api, "release.jar") - val transactions = UpdateTransaction(data.resolve("updates/transactions"), ArtifactVerifier(1024), plugins) + val transactions = UpdateTransaction(LibraryPaths(data).transactions, ArtifactVerifier(1024), plugins) val plan = UUID.randomUUID() val result = transactions.prepareForRestart(listOf(TransactionArtifact(specification, source, plugins.resolve("update/library.jar"), installed, "1.0.0", api, installed)), planId = plan, targetApi = 8) @@ -110,6 +119,7 @@ class UpdateHealthHistoryTest { val http = object : TrustedHttpClient(Duration.ofSeconds(1), Duration.ofSeconds(1)) { override fun get(uri: URI, maximumBytes: Int): ByteArray = error("health verification must not access the network") } - return Fixture(data, plan, result.journal, transactions, UpdateInstaller(platform, data, UpdateConfiguration(), http)) + val databases = DatabaseBackups(LibraryPaths(data).databases, DatabaseSources()) + return Fixture(data, plan, result.journal, transactions, UpdateInstaller(platform, LibraryPaths(data), UpdateConfiguration(), http, databases)) } } diff --git a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateOrchestratorTest.kt b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateOrchestratorTest.kt similarity index 84% rename from modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateOrchestratorTest.kt rename to modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateOrchestratorTest.kt index e8a642f7e..eb46be1f9 100644 --- a/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/core/updates/service/UpdateOrchestratorTest.kt +++ b/modules/updates/src/test/kotlin/org/pnfolder/pnlibrary/updates/service/UpdateOrchestratorTest.kt @@ -1,20 +1,21 @@ -package org.pnfolder.pnlibrary.core.updates.service +package org.pnfolder.pnlibrary.updates.service import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import org.pnfolder.pnlibrary.api.updates.* -import org.pnfolder.pnlibrary.api.updates.UpdateActor +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.* +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.ApiVersionRange import org.pnfolder.pnlibrary.api.version.SemanticVersion -import org.pnfolder.pnlibrary.core.updates.engine.ResolutionResult -import org.pnfolder.pnlibrary.core.updates.history.UpdateStateStore -import org.pnfolder.pnlibrary.core.updates.policy.UpdateConfiguration +import org.pnfolder.pnlibrary.updates.engine.ResolutionResult +import org.pnfolder.pnlibrary.updates.history.UpdateStateStore +import org.pnfolder.pnlibrary.updates.policy.UpdateConfiguration import java.nio.file.Path -import java.time.Clock -import java.time.Instant -import java.time.ZoneId import java.util.UUID import java.util.concurrent.CountDownLatch import java.util.concurrent.ExecutionException @@ -23,6 +24,8 @@ import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger class UpdateOrchestratorTest { + private val MANUAL = UpdateConfiguration(pluginAutomaticDownload = false, library = UpdateConfiguration.LibraryPolicy(automaticDownload = false)) + @TempDir lateinit var directory: Path @Test @@ -69,7 +72,7 @@ class UpdateOrchestratorTest { assertTrue(entered.await(2, TimeUnit.SECONDS)) val mutations = AtomicInteger() val orchestrator = UpdateOrchestrator( - UpdateConfiguration(), UpdateStateStore(directory), executor, + MANUAL, UpdateStateStore(directory), executor, resolver = { ResolutionResult.Ready(plan("2.0.0")) }, stageAction = { mutations.incrementAndGet() }, announcement = {}, ) @@ -102,7 +105,7 @@ class UpdateOrchestratorTest { var result: ResolutionResult = ResolutionResult.Ready(plan("2.0.0")) val executor = Executors.newSingleThreadScheduledExecutor() val orchestrator = UpdateOrchestrator( - UpdateConfiguration(), UpdateStateStore(directory), executor, + MANUAL, UpdateStateStore(directory), executor, resolver = { calls.incrementAndGet(); entered.countDown(); release.await(2, TimeUnit.SECONDS); result }, @@ -133,22 +136,26 @@ class UpdateOrchestratorTest { } @Test - fun `throttles identical announcements until repeat interval`() { - val clock = MutableClock(Instant.EPOCH) + fun `an unchanged state is announced once and reminders repeat it until the release is gone`() { val announcements = mutableListOf() val executor = Executors.newSingleThreadScheduledExecutor() + var available = true val orchestrator = UpdateOrchestrator( - UpdateConfiguration(), UpdateStateStore(directory), executor, - resolver = { ResolutionResult.Ready(plan("2.0.0")) }, - stageAction = {}, announcement = announcements::add, clock = clock, + MANUAL, UpdateStateStore(directory), executor, + resolver = { ResolutionResult.Ready(if (available) plan("2.0.0") else UpdatePlan(1, emptyList(), emptyList())) }, + stageAction = {}, announcement = announcements::add, ) try { orchestrator.checkNow().toCompletableFuture().get() orchestrator.checkNow().toCompletableFuture().get() assertEquals(1, announcements.size) - clock.instant = clock.instant.plusSeconds(6 * 60 * 60) - orchestrator.checkNow().toCompletableFuture().get() + orchestrator.remind() assertEquals(2, announcements.size) + available = false + orchestrator.checkNow().toCompletableFuture().get() + val afterGone = announcements.size + orchestrator.remind() + assertEquals(afterGone, announcements.size) } finally { orchestrator.close() } } @@ -156,7 +163,7 @@ class UpdateOrchestratorTest { fun `executor rejection completes check and stage futures instead of leaking`() { val executor = Executors.newSingleThreadScheduledExecutor() val orchestrator = UpdateOrchestrator( - UpdateConfiguration(), UpdateStateStore(directory), executor, + MANUAL, UpdateStateStore(directory), executor, resolver = { ResolutionResult.Ready(plan("2.0.0")) }, stageAction = {}, announcement = {}, ) @@ -174,7 +181,7 @@ class UpdateOrchestratorTest { val executor = Executors.newSingleThreadScheduledExecutor() var rollbackRuns = 0 val orchestrator = UpdateOrchestrator( - UpdateConfiguration(), UpdateStateStore(directory), executor, + MANUAL, UpdateStateStore(directory), executor, resolver = { ResolutionResult.Ready(plan("2.0.0")) }, stageAction = {}, announcement = {}, ) @@ -199,7 +206,7 @@ class UpdateOrchestratorTest { val remoteCalls = AtomicInteger() val executor = Executors.newSingleThreadScheduledExecutor() val orchestrator = UpdateOrchestrator( - UpdateConfiguration(), UpdateStateStore(directory), executor, + MANUAL, UpdateStateStore(directory), executor, resolver = { cachedEntered.countDown() cachedRelease.await(2, TimeUnit.SECONDS) @@ -229,7 +236,7 @@ class UpdateOrchestratorTest { fun `failed remote check publishes durable failed snapshot with cause`() { val executor = Executors.newSingleThreadScheduledExecutor() val orchestrator = UpdateOrchestrator( - UpdateConfiguration(), UpdateStateStore(directory), executor, + MANUAL, UpdateStateStore(directory), executor, resolver = { error("GitHub вернул HTTP 404") }, stageAction = {}, announcement = {}, ) @@ -252,7 +259,7 @@ class UpdateOrchestratorTest { val observations = mutableListOf>() val executor = Executors.newSingleThreadScheduledExecutor() val orchestrator = UpdateOrchestrator( - UpdateConfiguration(), UpdateStateStore(directory), executor, + MANUAL, UpdateStateStore(directory), executor, resolver = { ResolutionResult.Ready(plan("2.0.0")) }, stageAction = {}, announcement = {}, observeState = { _, recordedActor, operation -> observations.add(operation to recordedActor) }, ) @@ -291,7 +298,7 @@ class UpdateOrchestratorTest { val observations = mutableListOf() val executor = Executors.newSingleThreadScheduledExecutor() val orchestrator = UpdateOrchestrator( - UpdateConfiguration(), UpdateStateStore(directory), executor, + MANUAL, UpdateStateStore(directory), executor, resolver = { ResolutionResult.Ready(plan("2.0.0")) }, stageAction = { error("checksum mismatch") }, announcement = {}, observeState = { snapshot, recordedActor, operation -> @@ -314,7 +321,7 @@ class UpdateOrchestratorTest { fun `saved rollback can publish its own plan without an unrelated current plan`() { val executor = Executors.newSingleThreadScheduledExecutor() val orchestrator = UpdateOrchestrator( - UpdateConfiguration(), UpdateStateStore(directory), executor, + MANUAL, UpdateStateStore(directory), executor, resolver = { ResolutionResult.Ready(plan("3.0.0")) }, stageAction = {}, announcement = {}, ) val id = UUID.randomUUID() @@ -329,6 +336,24 @@ class UpdateOrchestratorTest { } finally { orchestrator.close() } } + @Test + fun `a scheduled check that cannot save its result is reported instead of lost`() { + val executor = Executors.newSingleThreadScheduledExecutor() + val reported = java.util.concurrent.LinkedBlockingQueue>() + val orchestrator = UpdateOrchestrator( + MANUAL, UpdateStateStore(directory), executor, + resolver = { ResolutionResult.Ready(plan("2.0.0")) }, + stageAction = {}, announcement = { error("announcement broke") }, + unexpectedFailure = { message, error -> reported.add(message to error) }, + ) + try { + orchestrator.start() + val (message, error) = requireNotNull(reported.poll(5, TimeUnit.SECONDS)) + assertEquals("Scheduled update check failed", message) + assertEquals("announcement broke", error.cause?.message ?: error.message) + } finally { orchestrator.close() } + } + private fun plan(version: String): UpdatePlan { val id = ProductId.of("pnlibrary") val semantic = SemanticVersion.parse(version) @@ -336,10 +361,4 @@ class UpdateOrchestratorTest { ProductRelease(id, semantic, UpdateChannel.STABLE, ApiVersionRange(1, 1), providesApi = 1), )) } - - private class MutableClock(var instant: Instant) : Clock() { - override fun getZone(): ZoneId = ZoneId.of("UTC") - override fun withZone(zone: ZoneId): Clock = this - override fun instant(): Instant = instant - } } diff --git a/modules/updates/src/test/resources/catalog/releases.json b/modules/updates/src/test/resources/catalog/releases.json deleted file mode 100644 index 254f76cf5..000000000 --- a/modules/updates/src/test/resources/catalog/releases.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "schema": 1, - "product": "demo", - "releases": [ - { - "version": "2.6.0-dev.80", - "channel": "dev", - "description": "Development build", - "publishedAt": "2026-09-29T12:00:00Z", - "api": { "minimum": 1, "maximum": 2 }, - "artifacts": [{ - "file": "demo-2.6.0-dev.80-bukkit-java8.jar", - "platform": "BUKKIT", - "minecraft": { "minimum": "1.20" }, - "java": { "minimum": 8 }, - "url": "https://example.org/demo-dev.jar" - }] - }, - { - "version": "2.6.0-beta.40", - "channel": "beta", - "description": "Beta build", - "publishedAt": "2026-09-28T12:00:00Z", - "api": { "minimum": 1, "maximum": 2 }, - "artifacts": [{ - "file": "demo-2.6.0-beta.40-bukkit-java8.jar", - "platform": "BUKKIT", - "minecraft": { "minimum": "1.20" }, - "java": { "minimum": 8 }, - "url": "https://example.org/demo-beta.jar" - }] - }, - { - "version": "2.5.1", - "channel": "stable", - "description": "Stable build", - "publishedAt": "2026-09-20T12:00:00Z", - "api": { "minimum": 1, "maximum": 1 }, - "artifacts": [{ - "file": "demo-2.5.1-bukkit-java8.jar", - "platform": "BUKKIT", - "minecraft": { "minimum": "1.20", "maximum": "1.21.11" }, - "java": { "minimum": 8, "maximum": 21 }, - "url": "https://example.org/demo-stable.jar" - }] - }, - { - "version": "2.4.0", - "channel": "stable", - "description": "Older stable build", - "publishedAt": "2026-08-20T12:00:00Z", - "api": { "minimum": 1, "maximum": 1 }, - "artifacts": [{ - "file": "demo-2.4.0-bukkit-java8.jar", - "platform": "BUKKIT", - "minecraft": { "minimum": "1.20", "maximum": "1.21.11" }, - "java": { "minimum": 8, "maximum": 21 }, - "url": "https://example.org/demo-old.jar" - }] - } - ] -} diff --git a/modules/upload/build.gradle.kts b/modules/upload/build.gradle.kts deleted file mode 100644 index 8d7f783ac..000000000 --- a/modules/upload/build.gradle.kts +++ /dev/null @@ -1,51 +0,0 @@ -plugins { - alias(libs.plugins.kotlin.jvm) - `java-library` - alias(libs.plugins.maven.publish) -} - -base { archivesName = "${rootProject.property("pnlibrary.name")}-upload" } - -dependencies { - api(project(":modules:api")) - implementation(project(":modules:common")) - implementation(libs.gson) - implementation(libs.kotlin.stdlib) - - testImplementation(libs.junit.jupiter) - testImplementation(libs.mockito.core) - testRuntimeOnly(libs.junit.launcher) -} - -mavenPublishing { - publishToMavenCentral() - signAllPublications() - coordinates("io.github.pnfolder", "pnlibrary-upload", project.version.toString()) - pom { - name.set("pnLibrary upload") - description.set("Encrypted report upload for pnLibrary.") - inceptionYear.set("2026") - url.set("https://github.com/${rootProject.property("pnlibrary.repository")}") - licenses { - license { - name.set(providers.gradleProperty("POM_LICENSE_NAME")) - url.set(providers.gradleProperty("POM_LICENSE_URL")) - distribution.set(providers.gradleProperty("POM_LICENSE_DIST").orElse("repo")) - } - } - developers { - rootProject.property("pnlibrary.authors").toString().split(",").map(String::trim).forEach { author -> - developer { - id.set(author) - name.set(author) - url.set("https://github.com/" + rootProject.property("pnlibrary.organization")) - } - } - } - scm { - url.set("https://github.com/${rootProject.property("pnlibrary.repository")}") - connection.set("scm:git:git://github.com/${rootProject.property("pnlibrary.repository")}.git") - developerConnection.set("scm:git:ssh://git@github.com/${rootProject.property("pnlibrary.repository")}.git") - } - } -} diff --git a/platforms/bukkit/api/build.gradle.kts b/platforms/bukkit/api/build.gradle.kts index 272f526bc..80dc8e24b 100644 --- a/platforms/bukkit/api/build.gradle.kts +++ b/platforms/bukkit/api/build.gradle.kts @@ -6,7 +6,8 @@ plugins { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates( groupId = "io.github.pnfolder", diff --git a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/api/BukkitPlatform.kt b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/api/BukkitPlatform.kt index 02eae1acb..4a6234390 100644 --- a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/api/BukkitPlatform.kt +++ b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/api/BukkitPlatform.kt @@ -12,13 +12,18 @@ import org.pnfolder.pnlibrary.bukkit.server.ServerInfo * This module holds contracts only; the implementations live in the Bukkit runtime and are installed by it. */ interface BukkitPlatform { + /** The running Bukkit server. */ val server: Server + /** Name and version of the server software, resolved once at startup. */ val serverInfo: ServerInfo + /** Opens and tracks inventory menus. */ val menus: MenuService + /** Creates, reads and writes items. */ val items: ItemService + /** Spawns floating items, blocks and text. */ val visuals: VisualService } diff --git a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/entity/VisualEntity.kt b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/entity/VisualEntity.kt index d09becf31..802cf3042 100644 --- a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/entity/VisualEntity.kt +++ b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/entity/VisualEntity.kt @@ -13,15 +13,19 @@ import org.bukkit.inventory.ItemStack */ interface VisualEntity { + /** The backing Bukkit entity. */ val entity: Entity + /** Whether the visual still exists in the world. */ val isValid: Boolean + /** Where the visual is seen. */ val location: Location /** Moves the visual; if the server rejects the teleport, [location] stays as it was. */ fun teleport(location: Location) + /** Turns the visual to [yaw] and [pitch], in degrees. */ fun setRotation(yaw: Float, pitch: Float) /** Uses the small model for scales between 0 and 0.72, the normal one otherwise. */ @@ -52,5 +56,6 @@ interface VisualService { /** Spawns a floating block seen at [location]; `null` or air shows a chest. */ fun block(location: Location, material: Material?): VisualEntity + /** Spawns a floating label seen at [location]; `null` shows an empty label. */ fun text(location: Location, text: String?): VisualEntity } diff --git a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/Menu.kt b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/Menu.kt index bf6c92d86..4f4e1ee09 100644 --- a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/Menu.kt +++ b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/Menu.kt @@ -43,11 +43,13 @@ data class MenuClose( */ data class Menu( + /** Inventory title shown to the player. */ val title: String, /** Chest row count; ignored by non-chest menu types. */ val rows: Int, + /** Inventory type; chest by default. */ val type: MenuType, /** Static slot definitions keyed by raw top-inventory slot. */ @@ -69,5 +71,6 @@ data class Menu( val cancelPlayerInventory: Boolean, ) { + /** Total slot count of the top inventory. */ val size: Int get() = if (type == MenuType.CHEST) rows * 9 else type.defaultSize } diff --git a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuBuilder.kt b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuBuilder.kt index 18b6580b1..af2560297 100644 --- a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuBuilder.kt +++ b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuBuilder.kt @@ -62,10 +62,13 @@ class MenuBuilder internal constructor(private val title: String, private val ty } } + /** Sets the function that fills the menu each time it is opened or refreshed. */ fun render(renderer: MenuRenderer): MenuBuilder = apply { this.renderer = renderer } + /** Sets the callback that runs after the menu is opened for a player. */ fun onOpen(handler: MenuOpenHandler): MenuBuilder = apply { openHandler = handler } + /** Sets the callback that runs after a player's session ends. */ fun onClose(handler: MenuCloseHandler): MenuBuilder = apply { closeHandler = handler } /** Creates an immutable menu and snapshot of all current slot definitions. */ diff --git a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuClick.kt b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuClick.kt index 7795bcbe4..39ba1bad3 100644 --- a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuClick.kt +++ b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuClick.kt @@ -32,8 +32,10 @@ data class MenuClick( val renameText: String? = null, ) { + /** The player who clicked. */ val player: Player get() = session.player + /** Closes the menu for the clicking player. */ fun close() = session.close() /** Immediately invokes the configured renderer when the session is still active. */ diff --git a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuService.kt b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuService.kt index 7da7b257d..ff05359a8 100644 --- a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuService.kt +++ b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuService.kt @@ -24,6 +24,7 @@ interface MenuService { */ fun open(owner: Plugin, player: Player, menu: Menu): MenuSession + /** Returns the menu [player] has open through this service, or `null` when there is none. */ fun session(player: Player): MenuSession? /** Closes every session owned by [owner] without invoking plugin close callbacks. */ diff --git a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuSession.kt b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuSession.kt index 48559deec..1955e58cc 100644 --- a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuSession.kt +++ b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuSession.kt @@ -8,15 +8,19 @@ import java.time.Duration /** One player's live view of a reusable [Menu] definition. */ interface MenuSession : AutoCloseable { + /** The viewer. */ val player: Player + /** The definition this session shows. */ val menu: Menu + /** The open Bukkit inventory. */ val inventory: Inventory /** Replaces [slot] with [item]; `null` clears it. */ fun set(slot: Int, item: ItemStack?) + /** Returns the item in [slot], or `null` when it is empty. */ fun get(slot: Int): ItemStack? /** Invokes [Menu.renderer] immediately unless the session has finished. */ diff --git a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemFormat.kt b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemFormat.kt index 813d9b2ec..724c3be43 100644 --- a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemFormat.kt +++ b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemFormat.kt @@ -36,6 +36,7 @@ class ItemFormat private constructor( val exact: String, val fields: Map, ) { + /** Returns a builder that starts with every key and field of this format. */ fun toBuilder(): Builder = Builder().also { builder -> builder.material(material).amount(amount).name(name).lore(lore).enchantments(enchantments) .texture(*textures.toTypedArray()).exact(exact) @@ -80,6 +81,7 @@ class ItemFormat private constructor( /** Reads a field of your own from [key]; it runs after the standard fields, in the order added. */ fun field(key: String, field: ItemField): Builder = apply { fields[key(key)] = field } + /** Creates the immutable format. */ fun build(): ItemFormat = ItemFormat( material, amount, name, lore, enchantments, textures, exact, Collections.unmodifiableMap(LinkedHashMap(fields)), diff --git a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemService.kt b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemService.kt index be34fa7f7..4dbb6f6ab 100644 --- a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemService.kt +++ b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemService.kt @@ -29,6 +29,7 @@ import org.bukkit.inventory.ItemStack */ interface ItemService { + /** Builds an item stack from [spec]. */ fun create(spec: ItemSpec): ItemStack /** Reads [section] in the default format; `null` when the section is absent. */ @@ -85,5 +86,6 @@ interface ItemService { */ fun decode(encoded: String): ItemStack + /** Whether [item] is a real item: not `null` and not air. */ fun isReal(item: ItemStack?): Boolean } diff --git a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemSpec.kt b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemSpec.kt index ff288e0cc..eb7f24afb 100644 --- a/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemSpec.kt +++ b/platforms/bukkit/api/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ItemSpec.kt @@ -5,6 +5,7 @@ import java.util.Collections /** Anything [ItemSpec] has no field for: flags, custom model data, persistent data. Runs last, on the created item. */ fun interface ItemCustomizer { + /** Changes [item] in place. */ fun apply(item: ItemStack) } @@ -43,6 +44,7 @@ class ItemSpec private constructor( val exact: String?, val customizers: List, ) { + /** Returns a builder that starts with every value of this spec. */ fun toBuilder(): Builder = Builder().also { builder -> builder.material(material).amount(amount).name(name).lore(lore).texture(texture).exact(exact) enchantments.forEach { (key, level) -> builder.enchant(key, level) } @@ -75,13 +77,16 @@ class ItemSpec private constructor( /** Sets the display name; `null` keeps the default. */ fun name(value: String?): Builder = apply { name = value } + /** Replaces the lore with [lines]. */ fun lore(lines: List): Builder = apply { lore.clear() lore += lines } + /** Replaces the lore with [lines]. */ fun lore(vararg lines: String): Builder = lore(lines.toList()) + /** Appends one line to the lore. */ fun addLore(line: String): Builder = apply { lore += line } /** Adds or replaces an enchantment by name, for example `sharpness`. */ @@ -99,6 +104,7 @@ class ItemSpec private constructor( /** Adds a change for anything the spec has no field for; changes run in the order they were added. */ fun customize(customizer: ItemCustomizer): Builder = apply { customizers += customizer } + /** Creates the immutable spec. */ fun build(): ItemSpec = ItemSpec( material, amount, name, Collections.unmodifiableList(ArrayList(lore)), diff --git a/platforms/bukkit/bootstrap/build.gradle.kts b/platforms/bukkit/bootstrap/build.gradle.kts index a3ce6e735..50b8d9330 100644 --- a/platforms/bukkit/bootstrap/build.gradle.kts +++ b/platforms/bukkit/bootstrap/build.gradle.kts @@ -18,7 +18,8 @@ tasks.withType().configureEach { useJUnitPlatform() } mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-bootstrap-bukkit", project.version.toString()) pom { name.set("pnLibrary Bukkit Bootstrap") diff --git a/platforms/bukkit/localization/build.gradle.kts b/platforms/bukkit/localization/build.gradle.kts index 20cd1eeb9..0d6b6ac7a 100644 --- a/platforms/bukkit/localization/build.gradle.kts +++ b/platforms/bukkit/localization/build.gradle.kts @@ -8,7 +8,7 @@ base { archivesName = "${rootProject.property("pnlibrary.name")}-minecraft-local dependencies { api(project(":modules:common")) - api(project(":modules:features:minecraft-localization-api")) + api(project(":modules:features:localization-api")) api(project(":platforms:bukkit:api")) api(libs.kotlin.stdlib) compileOnly(libs.spigot.api.v18) @@ -23,7 +23,8 @@ java { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-minecraft-localization", project.version.toString()) pom { name.set("pnLibrary Minecraft Localization") diff --git a/platforms/bukkit/localization/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/localization/BukkitLocaleTranslations.kt b/platforms/bukkit/localization/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/localization/BukkitLocaleTranslations.kt index 019796963..8a9143428 100644 --- a/platforms/bukkit/localization/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/localization/BukkitLocaleTranslations.kt +++ b/platforms/bukkit/localization/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/localization/BukkitLocaleTranslations.kt @@ -41,20 +41,28 @@ interface BukkitLocaleTranslations : LocaleTranslations { /** Translates [gameMode]; a convenience for `translate(BukkitTranslatables.GAME_MODE, gameMode)`. */ fun translate(gameMode: GameMode): Translation = translate(BukkitTranslatables.GAME_MODE, gameMode) + /** Reverse-search index from localized item and block names to [Material]. */ fun materials(): TranslationIndex + /** Reverse-search index from localized enchantment names to [Enchantment]. */ fun enchantments(): TranslationIndex + /** Reverse-search index from localized entity names to [EntityType]. */ fun entities(): TranslationIndex + /** Reverse-search index from localized potion effect names to [PotionEffectType]. */ fun effects(): TranslationIndex + /** Reverse-search index from localized biome names to [Biome]. */ fun biomes(): TranslationIndex + /** Reverse-search index from localized dye color names to [DyeColor]. */ fun colors(): TranslationIndex + /** Reverse-search index from localized game mode names to [GameMode]. */ fun gameModes(): TranslationIndex + /** Factory for wrapping neutral translation tables. */ companion object { /** Wraps a neutral [translations] table, resolving its entries to Bukkit value types. */ @JvmStatic @@ -62,6 +70,7 @@ interface BukkitLocaleTranslations : LocaleTranslations { } } +/** Delegates the neutral contract to [delegate] and builds each reverse index on first use, since most callers need one. */ private class BukkitLocaleTranslationsAdapter( private val delegate: LocaleTranslations, ) : BukkitLocaleTranslations, LocaleTranslations by delegate { diff --git a/platforms/bukkit/localization/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/localization/internal/BukkitTranslationIndexes.kt b/platforms/bukkit/localization/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/localization/internal/BukkitTranslationIndexes.kt index 08b39234a..f9858d7ae 100644 --- a/platforms/bukkit/localization/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/localization/internal/BukkitTranslationIndexes.kt +++ b/platforms/bukkit/localization/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/localization/internal/BukkitTranslationIndexes.kt @@ -36,6 +36,7 @@ internal object MaterialTranslatable : TranslatableType { override fun fallbackName(value: Material): String = value.name.lowercase(Locale.ROOT).replace('_', ' ') } +/** Translation keys of an [Enchantment]: the modern key, then the pre-1.13 one. */ internal object EnchantmentTranslatable : TranslatableType { override fun keysOf(value: Enchantment): List { val modern = namespacedKey(value)?.substringAfter(':') @@ -47,6 +48,7 @@ internal object EnchantmentTranslatable : TranslatableType { override fun fallbackName(value: Enchantment): String = legacyName(value).lowercase(Locale.ROOT).replace('_', ' ') } +/** Translation keys of an [EntityType]: the modern key, then the pre-1.13 one. */ internal object EntityTranslatable : TranslatableType { override fun keysOf(value: EntityType): List { val path = namespacedKey(value)?.substringAfter(':') ?: value.name.lowercase(Locale.ROOT) @@ -58,6 +60,7 @@ internal object EntityTranslatable : TranslatableType { override fun fallbackName(value: EntityType): String = value.name.lowercase(Locale.ROOT).replace('_', ' ') } +/** Translation keys of a [PotionEffectType]: the modern key, then the pre-1.13 one. */ internal object EffectTranslatable : TranslatableType { override fun keysOf(value: PotionEffectType): List { val modern = namespacedKey(value)?.substringAfter(':') @@ -69,6 +72,7 @@ internal object EffectTranslatable : TranslatableType { override fun fallbackName(value: PotionEffectType): String = effectName(value).lowercase(Locale.ROOT).replace('_', ' ') } +/** Translation key of a [Biome]. */ internal object BiomeTranslatable : TranslatableType { override fun keysOf(value: Biome): List { val path = namespacedKey(value)?.substringAfter(':') ?: value.name.lowercase(Locale.ROOT) @@ -78,11 +82,13 @@ internal object BiomeTranslatable : TranslatableType { override fun fallbackName(value: Biome): String = value.name.lowercase(Locale.ROOT).replace('_', ' ') } +/** Translation key of a [DyeColor]. */ internal object ColorTranslatable : TranslatableType { override fun keysOf(value: DyeColor): List = listOf(TranslationCategory.COLOR.key(value.name.lowercase(Locale.ROOT))) override fun fallbackName(value: DyeColor): String = value.name.lowercase(Locale.ROOT).replace('_', ' ') } +/** Translation key of a [GameMode]. */ internal object GameModeTranslatable : TranslatableType { override fun keysOf(value: GameMode): List = listOf(TranslationCategory.GAME_MODE.key(value.name.lowercase(Locale.ROOT))) override fun fallbackName(value: GameMode): String = value.name.lowercase(Locale.ROOT).replace('_', ' ') @@ -90,64 +96,51 @@ internal object GameModeTranslatable : TranslatableType { // --- Reverse lookup: translated text -> Bukkit value --- -internal fun bukkitMaterials(values: Map, layouts: KeyboardLayouts): TranslationIndex = TranslationIndex.of( +/** Builds an index of the entries of [values] whose key starts with one of [prefixes]; [resolve] maps the last key segment to a value. */ +private fun reverseIndex( + values: Map, + layouts: KeyboardLayouts, + prefixes: List, + resolve: (String) -> T?, +): TranslationIndex = TranslationIndex.of( values.asSequence() - .filter { (key, _) -> key.startsWith(TranslationCategory.ITEM.prefix()) || key.startsWith(TranslationCategory.BLOCK.prefix()) } - .map { (key, value) -> - TranslationMatch(key, value, Material.matchMaterial(key.substringAfterLast('.').uppercase(Locale.ROOT))) - } + .filter { (key, _) -> prefixes.any(key::startsWith) } + .map { (key, value) -> TranslationMatch(key, value, resolve(key.substringAfterLast('.').uppercase(Locale.ROOT))) } .toList(), layouts, ) -internal fun bukkitEnchantments(values: Map, layouts: KeyboardLayouts): TranslationIndex = TranslationIndex.of( - values.asSequence() - .filter { (key, _) -> key.startsWith(TranslationCategory.ENCHANTMENT.prefix()) } - .map { (key, value) -> TranslationMatch(key, value, enchantmentOf(key.substringAfterLast('.').uppercase(Locale.ROOT))) } - .toList(), - layouts, -) +private fun prefixOf(category: TranslationCategory) = listOf(category.prefix()) -internal fun bukkitEntities(values: Map, layouts: KeyboardLayouts): TranslationIndex = TranslationIndex.of( - values.asSequence() - .filter { (key, _) -> key.startsWith(TranslationCategory.ENTITY.prefix()) } - .map { (key, value) -> TranslationMatch(key, value, entityOf(key.substringAfterLast('.').uppercase(Locale.ROOT))) } - .toList(), - layouts, -) +/** Reverse index of item and block names. */ +internal fun bukkitMaterials(values: Map, layouts: KeyboardLayouts): TranslationIndex = + reverseIndex(values, layouts, listOf(TranslationCategory.ITEM.prefix(), TranslationCategory.BLOCK.prefix()), { Material.matchMaterial(it) }) -internal fun bukkitEffects(values: Map, layouts: KeyboardLayouts): TranslationIndex = TranslationIndex.of( - values.asSequence() - .filter { (key, _) -> key.startsWith(TranslationCategory.EFFECT.prefix()) } - .map { (key, value) -> TranslationMatch(key, value, effectOf(key.substringAfterLast('.').uppercase(Locale.ROOT))) } - .toList(), - layouts, -) +/** Reverse index of enchantment names. */ +internal fun bukkitEnchantments(values: Map, layouts: KeyboardLayouts): TranslationIndex = + reverseIndex(values, layouts, prefixOf(TranslationCategory.ENCHANTMENT), ::enchantmentOf) -internal fun bukkitBiomes(values: Map, layouts: KeyboardLayouts): TranslationIndex = TranslationIndex.of( - values.asSequence() - .filter { (key, _) -> key.startsWith(TranslationCategory.BIOME.prefix()) } - .map { (key, value) -> TranslationMatch(key, value, biomeOf(key.substringAfterLast('.').uppercase(Locale.ROOT))) } - .toList(), - layouts, -) +/** Reverse index of entity names. */ +internal fun bukkitEntities(values: Map, layouts: KeyboardLayouts): TranslationIndex = + reverseIndex(values, layouts, prefixOf(TranslationCategory.ENTITY), ::entityOf) -internal fun bukkitColors(values: Map, layouts: KeyboardLayouts): TranslationIndex = TranslationIndex.of( - values.asSequence() - .filter { (key, _) -> key.startsWith(TranslationCategory.COLOR.prefix()) } - .map { (key, value) -> TranslationMatch(key, value, colorOf(key.substringAfterLast('.').uppercase(Locale.ROOT))) } - .toList(), - layouts, -) +/** Reverse index of potion effect names. */ +internal fun bukkitEffects(values: Map, layouts: KeyboardLayouts): TranslationIndex = + reverseIndex(values, layouts, prefixOf(TranslationCategory.EFFECT), ::effectOf) -internal fun bukkitGameModes(values: Map, layouts: KeyboardLayouts): TranslationIndex = TranslationIndex.of( - values.asSequence() - .filter { (key, _) -> key.startsWith(TranslationCategory.GAME_MODE.prefix()) } - .map { (key, value) -> TranslationMatch(key, value, gameModeOf(key.substringAfterLast('.').uppercase(Locale.ROOT))) } - .toList(), - layouts, -) +/** Reverse index of biome names. */ +internal fun bukkitBiomes(values: Map, layouts: KeyboardLayouts): TranslationIndex = + reverseIndex(values, layouts, prefixOf(TranslationCategory.BIOME), ::biomeOf) + +/** Reverse index of dye color names. */ +internal fun bukkitColors(values: Map, layouts: KeyboardLayouts): TranslationIndex = + reverseIndex(values, layouts, prefixOf(TranslationCategory.COLOR), ::colorOf) + +/** Reverse index of game mode names. */ +internal fun bukkitGameModes(values: Map, layouts: KeyboardLayouts): TranslationIndex = + reverseIndex(values, layouts, prefixOf(TranslationCategory.GAME_MODE), ::gameModeOf) +/** Enchantment for a modern constant name, or null; tries the legacy alias and the namespaced key. */ private fun enchantmentOf(modernName: String): Enchantment? { val legacy = ENCHANTMENT_ALIASES[modernName] ?: modernName val constant = staticField(Enchantment::class.java, legacy) as? Enchantment @@ -156,10 +149,12 @@ private fun enchantmentOf(modernName: String): Enchantment? { } } +/** Entity type whose constant or namespaced key equals [path], or null. */ private fun entityOf(path: String): EntityType? = EntityType.values().firstOrNull { it.name.equals(path, true) || namespacedKey(it)?.equals(path.lowercase(Locale.ROOT), true) == true } +/** Potion effect for a modern constant name, or null; tries the legacy alias and the namespaced key. */ private fun effectOf(modernName: String): PotionEffectType? { val legacy = EFFECT_ALIASES[modernName] ?: modernName val constant = staticField(PotionEffectType::class.java, legacy) as? PotionEffectType @@ -168,12 +163,15 @@ private fun effectOf(modernName: String): PotionEffectType? { } } +/** Biome whose constant or namespaced key equals [path], or null. */ private fun biomeOf(path: String): Biome? = Biome.values().firstOrNull { it.name.equals(path, true) || namespacedKey(it)?.equals(path.lowercase(Locale.ROOT), true) == true } +/** Dye color named [path], or null. */ private fun colorOf(path: String): DyeColor? = DyeColor.values().firstOrNull { it.name.equals(path, true) } +/** Game mode named [path], or null. */ private fun gameModeOf(path: String): GameMode? = GameMode.values().firstOrNull { it.name.equals(path, true) } // --- Reflection kept out of the public API files (enforced by SourceConventionsTest) --- diff --git a/platforms/bukkit/localization/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/localization/internal/TranslationLegacyNames.kt b/platforms/bukkit/localization/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/localization/internal/TranslationLegacyNames.kt index a3f00e04c..e3247a3b5 100644 --- a/platforms/bukkit/localization/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/localization/internal/TranslationLegacyNames.kt +++ b/platforms/bukkit/localization/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/localization/internal/TranslationLegacyNames.kt @@ -13,15 +13,18 @@ internal val ENCHANTMENT_ALIASES = mapOf( "FLAME" to "ARROW_FIRE", "INFINITY" to "ARROW_INFINITE", ) +/** Inverse of [ENCHANTMENT_ALIASES]: legacy constant to modern name. */ internal val ENCHANTMENT_LEGACY_TO_MODERN: Map = ENCHANTMENT_ALIASES.entries.associate { (modern, legacy) -> legacy to modern } +/** Modern effect names to the legacy Bukkit constants. */ internal val EFFECT_ALIASES = mapOf( "SLOWNESS" to "SLOW", "HASTE" to "FAST_DIGGING", "MINING_FATIGUE" to "SLOW_DIGGING", "STRENGTH" to "INCREASE_DAMAGE", "INSTANT_HEALTH" to "HEAL", "INSTANT_DAMAGE" to "HARM", "JUMP_BOOST" to "JUMP", "NAUSEA" to "CONFUSION", "RESISTANCE" to "DAMAGE_RESISTANCE", ) +/** Inverse of [EFFECT_ALIASES]: legacy constant to modern name. */ internal val EFFECT_LEGACY_TO_MODERN: Map = EFFECT_ALIASES.entries.associate { (modern, legacy) -> legacy to modern } @@ -40,6 +43,7 @@ internal val ENCHANTMENT_LEGACY = mapOf( "mending" to "mending", "vanishing_curse" to "vanishing_curse", ) +/** Pre-1.13 effect key fragments by modern path. */ internal val EFFECT_LEGACY = mapOf( "speed" to "moveSpeed", "slowness" to "moveSlowdown", "haste" to "digSpeed", "mining_fatigue" to "digSlowDown", "strength" to "damageBoost", "instant_health" to "heal", "instant_damage" to "harm", "jump_boost" to "jump", diff --git a/platforms/bukkit/paper/build.gradle.kts b/platforms/bukkit/paper/build.gradle.kts index dbca42cc2..d53c1c9d0 100644 --- a/platforms/bukkit/paper/build.gradle.kts +++ b/platforms/bukkit/paper/build.gradle.kts @@ -12,11 +12,11 @@ base { archivesName = "${rootProject.property("pnlibrary.name")}-bukkit-paper" } dependencies { implementation(libs.kotlin.stdlib) compileOnly(project(":modules:api")) - compileOnly(project(":modules:runtime-spi")) + compileOnly(project(":modules:spi")) compileOnly(libs.paper.api) testImplementation(project(":modules:api")) - testImplementation(project(":modules:runtime-spi")) + testImplementation(project(":modules:spi")) testImplementation(libs.paper.api) testImplementation(libs.junit.jupiter) testRuntimeOnly(libs.junit.launcher) diff --git a/platforms/bukkit/paper/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/paper/BrigadierTrees.kt b/platforms/bukkit/paper/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/paper/BrigadierTrees.kt index 820b195b3..2a4381dfb 100644 --- a/platforms/bukkit/paper/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/paper/BrigadierTrees.kt +++ b/platforms/bukkit/paper/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/paper/BrigadierTrees.kt @@ -1,6 +1,7 @@ package org.pnfolder.pnlibrary.bukkit.paper import com.mojang.brigadier.Command +import com.mojang.brigadier.StringReader import com.mojang.brigadier.arguments.ArgumentType import com.mojang.brigadier.arguments.DoubleArgumentType import com.mojang.brigadier.arguments.IntegerArgumentType @@ -12,35 +13,24 @@ import com.mojang.brigadier.builder.RequiredArgumentBuilder import com.mojang.brigadier.suggestion.SuggestionProvider import com.mojang.brigadier.suggestion.Suggestions import com.mojang.brigadier.tree.LiteralCommandNode -import org.pnfolder.pnlibrary.api.commands.ArgumentSpec -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.CommandNode -import org.pnfolder.pnlibrary.api.commands.CommandNodeKind +import io.papermc.paper.command.brigadier.argument.CustomArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentSpec +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandNode +import org.pnfolder.pnlibrary.api.commands.definition.CommandNodeKind import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage -/** What a Brigadier node does when it is used: the portable router decides everything after the tree has matched. */ internal interface NativeInvocation { - /** Runs the command typed as [input], which is the whole line without the leading slash. */ fun execute(source: S, input: String) - - /** Returns the suggestions for the partial argument at the end of [input]. */ fun suggest(source: S, input: String): CompletionStage> - - /** - * Whether [source] may enter [node]. A node it may not enter is left out of the tree the client receives, so - * Tab does not offer it. Defaults to everything allowed. - */ fun allowed(source: S, node: CommandNode): Boolean = true } -/** - * Builds the Brigadier tree of a portable command, so a modern client validates the arguments and shows the - * usual red and gray hints while the shared router keeps doing the real work: permissions, custom messages, - * parsing and execution. Literals and arguments mirror the portable tree one to one. - */ +// Brigadier validates client-side; the portable router still handles all logic after the tree matches. internal object BrigadierTrees { - /** Returns the root node of [definition]; its aliases are registered by the caller. */ + private const val EXTRA_ARGUMENTS = "arguments" + fun build(definition: CommandDefinition, invocation: NativeInvocation): LiteralCommandNode { val root = LiteralArgumentBuilder.literal(definition.name) .requires { invocation.allowed(it, definition.root) } @@ -56,8 +46,11 @@ internal object BrigadierTrees { } } node.children.forEach { builder.then(child(it, invocation)) } - if (node.acceptsExtraArguments && node.isExecutable && node.children.none { it.kind == CommandNodeKind.ARGUMENT }) { - // Free words after this node are not rejected by the client: the portable router decides what they mean. + // Allow free words when no argument child exists — the portable router parses them itself. + if (node.acceptsExtraArguments && + node.isExecutable && + node.children.none { it.kind == CommandNodeKind.ARGUMENT } + ) { builder.then( RequiredArgumentBuilder.argument(EXTRA_ARGUMENTS, typeOf(ArgumentSpec.GREEDY)) .requires { invocation.allowed(it, node) } @@ -70,68 +63,89 @@ internal object BrigadierTrees { } } - private const val EXTRA_ARGUMENTS = "arguments" - - private fun child(node: CommandNode, invocation: NativeInvocation): ArgumentBuilder { - if (node.kind == CommandNodeKind.LITERAL) { - return LiteralArgumentBuilder.literal(node.name) + private fun child(node: CommandNode, invocation: NativeInvocation): ArgumentBuilder = + when (node.kind) { + CommandNodeKind.LITERAL -> LiteralArgumentBuilder.literal(node.name) .requires { invocation.allowed(it, node) } .also { populate(it, node, invocation) } + else -> { + val spec = node.argumentType?.spec ?: ArgumentSpec.TEXT + RequiredArgumentBuilder.argument(node.name, typeOf(spec)) + .requires { invocation.allowed(it, node) } + .suggests(suggestionsFor(invocation)) + .also { populate(it, node, invocation) } + } } - val spec = node.argumentType?.spec ?: ArgumentSpec.TEXT - val builder = RequiredArgumentBuilder.argument(node.name, typeOf(spec)) - .requires { invocation.allowed(it, node) } - .suggests(suggestionsFor(invocation)) - populate(builder, node, invocation) - return builder - } - /** - * Maps a portable spec to a Brigadier type. Anything the portable parser accepts in more spellings than - * Brigadier does (`yes` for a boolean, `1e3` for a decimal) stays a plain word, so the client never rejects - * what the server would take. - */ private fun bound(value: Double?, spec: ArgumentSpec): Double = requireNotNull(value) { "${spec.kind} argument needs both bounds" } + // Types the portable parser accepts in more spellings than Brigadier stay as SpacelessWord + // so the client never rejects input the server would take (e.g. `yes` for boolean, `1e3` for decimal). @Suppress("UNCHECKED_CAST") - internal fun typeOf(spec: ArgumentSpec): ArgumentType = when (spec.kind) { - ArgumentSpec.Kind.INTEGER -> - IntegerArgumentType.integer(bound(spec.minimum, spec).toInt(), bound(spec.maximum, spec).toInt()) - ArgumentSpec.Kind.LONG -> - LongArgumentType.longArg(bound(spec.minimum, spec).toLong(), bound(spec.maximum, spec).toLong()) - ArgumentSpec.Kind.DECIMAL -> - if (spec.minimum == -Double.MAX_VALUE && spec.maximum == Double.MAX_VALUE) StringArgumentType.word() - else DoubleArgumentType.doubleArg(bound(spec.minimum, spec), bound(spec.maximum, spec)) + internal fun typeOf(spec: ArgumentSpec): ArgumentType = (when (spec.kind) { + ArgumentSpec.Kind.INTEGER -> IntegerArgumentType.integer( + bound(spec.minimum, spec).toInt(), + bound(spec.maximum, spec).toInt(), + ) + ArgumentSpec.Kind.LONG -> LongArgumentType.longArg( + bound(spec.minimum, spec).toLong(), + bound(spec.maximum, spec).toLong(), + ) + ArgumentSpec.Kind.DECIMAL -> { + val min = spec.minimum + val max = spec.maximum + if (min == null || max == null || (min == -Double.MAX_VALUE && max == Double.MAX_VALUE)) SpacelessWord + else DoubleArgumentType.doubleArg(min, max) + } ArgumentSpec.Kind.GREEDY -> StringArgumentType.greedyString() - ArgumentSpec.Kind.BOOLEAN, ArgumentSpec.Kind.CHOICE, ArgumentSpec.Kind.TEXT -> StringArgumentType.word() - } as ArgumentType + ArgumentSpec.Kind.BOOLEAN, ArgumentSpec.Kind.CHOICE, ArgumentSpec.Kind.TEXT -> SpacelessWord + }) as ArgumentType - private fun suggestionsFor(invocation: NativeInvocation): SuggestionProvider = SuggestionProvider { context, builder -> - val result = CompletableFuture() - invocation.suggest(context.source, builder.input).whenComplete { values, error -> - if (error != null) { - result.complete(builder.build()) - } else { - values.orEmpty().forEach { builder.suggest(it) } - result.complete(builder.build()) + private fun suggestionsFor(invocation: NativeInvocation): SuggestionProvider = + SuggestionProvider { context, builder -> + val result = CompletableFuture() + // For greedy arguments (EXTRA_ARGUMENTS), builder.start points to the beginning of the entire + // greedy portion. Adjust to the last token so the suggestion replaces only the word being typed. + val lastSpace = builder.input.lastIndexOf(' ') + val target = if (lastSpace >= builder.start) builder.createOffset(lastSpace + 1) else builder + try { + invocation.suggest(context.source, builder.input).whenComplete { values, error -> + if (error == null) values.orEmpty().forEach { target.suggest(it) } + result.complete(target.build()) + } + } catch (_: Exception) { + result.complete(target.build()) } + result } - result +} + +// Brigadier's built-in word type stops at `/`, `:`, `;` and similar, breaking ids like `shop/main:config.yml`. +// Declared as greedy to the client so those chars are not painted red; the server reads it as one token. +@Suppress("UnstableApiUsage") +internal object SpacelessWord : CustomArgumentType { + override fun parse(reader: StringReader): String { + val start = reader.cursor + while (reader.canRead() && !reader.peek().isWhitespace()) reader.skip() + return reader.string.substring(start, reader.cursor) } + + override fun getNativeType(): ArgumentType = StringArgumentType.greedyString() } -/** A command line split into the label the player typed and its arguments. */ -internal class CommandLine(val label: String, val arguments: List) { +internal data class CommandLine(val label: String, val arguments: List) { companion object { - /** - * Splits [input]. A label such as `pnlibrary:pn` keeps only the command name. With [keepTrailing] a - * line that ends with a space has an empty last argument, which is what tab completion needs. - */ fun of(input: String, keepTrailing: Boolean): CommandLine { val trimmed = input.trimStart().removePrefix("/") - val parts = if (keepTrailing) trimmed.split(' ') else trimmed.trim().split(Regex(" +")) - return CommandLine(parts.first().substringAfterLast(':'), parts.drop(1)) + // keepTrailing: a trailing space produces an empty last argument, which tab completion needs. + // Both paths collapse multiple spaces; keepTrailing re-appends the empty token manually. + val collapsed = trimmed.trim().split(Regex(" +")) + val parts = if (keepTrailing && trimmed.endsWith(' ')) collapsed + "" else collapsed + return CommandLine( + label = parts.first().substringAfterLast(':'), + arguments = parts.drop(1), + ) } } } diff --git a/platforms/bukkit/paper/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/paper/PaperNativeCommandRegistrar.kt b/platforms/bukkit/paper/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/paper/PaperNativeCommandRegistrar.kt index a95cd984c..328dcfc40 100644 --- a/platforms/bukkit/paper/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/paper/PaperNativeCommandRegistrar.kt +++ b/platforms/bukkit/paper/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/paper/PaperNativeCommandRegistrar.kt @@ -8,28 +8,25 @@ import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents import org.bukkit.command.CommandSender import org.bukkit.command.ConsoleCommandSender import org.bukkit.plugin.Plugin -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.CommandNode -import org.pnfolder.pnlibrary.api.commands.SenderRule +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.CommandNode +import org.pnfolder.pnlibrary.api.commands.definition.SenderRule +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.spi.commands.NativeCommandRegistrar import org.pnfolder.pnlibrary.spi.commands.PlatformCommandRegistration import java.util.concurrent.CompletionStage import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicBoolean -/** - * Registers portable commands through Paper's Brigadier command API, falling back to [fallback], the classic - * command map, for anything the API cannot take. - * - * Paper builds its command tree once, when the server has loaded its plugins, and again on a datapack reload; - * plugins may add commands only while that happens. So commands registered before then are collected and - * registered natively in that event, and every later registration, or a command Paper refuses, goes through - * [fallback] and still works, only without client-side validation. - * - * Registering a handler for this event makes Paper turn off Bukkit's `/reload`; that is Paper's rule, not ours. - */ +// Paper builds its command tree on plugin load and on datapack reload — commands can only be added then. +// Everything registered before that event is queued here and submitted in bulk; anything later goes through +// [fallback] (classic command map) and still works, only without client-side validation. +// Registering a lifecycle handler also disables Bukkit's /reload — that is Paper's rule, not ours. +@Suppress("UnstableApiUsage") class PaperNativeCommandRegistrar( private val plugin: Plugin, private val fallback: NativeCommandRegistrar, + private val pnLogger: () -> PnLogger, ) : NativeCommandRegistrar { private class Entry( val owner: Plugin?, @@ -39,6 +36,7 @@ class PaperNativeCommandRegistrar( ) { @Volatile var active = true @Volatile var fallbackRegistration: PlatformCommandRegistration? = null + val suggestionFailureReported = AtomicBoolean(false) } private val entries = CopyOnWriteArrayList() @@ -49,7 +47,7 @@ class PaperNativeCommandRegistrar( init { plugin.lifecycleManager.registerEventHandler( LifecycleEvents.COMMANDS, - LifecycleEventHandler> { event -> + LifecycleEventHandler { event: ReloadableRegistrarEvent -> committed = true val registrar = event.registrar() entries.filter { it.active }.forEach { registerNative(registrar, it) } @@ -57,7 +55,6 @@ class PaperNativeCommandRegistrar( ) } - /** Registers [command] natively through Paper's Brigadier API on behalf of [owner]. */ override fun register( owner: Any, command: CommandDefinition, @@ -81,10 +78,7 @@ class PaperNativeCommandRegistrar( val meta = (entry.owner ?: plugin).pluginMeta registrar.register(meta, node, "pnLibrary portable command", entry.command.aliases.toList()) } catch (error: Exception) { - plugin.logger.warning( - "Command /${entry.command.name} could not use Paper's command API " + - "(${error.javaClass.simpleName}); using the classic command map", - ) + pnLogger().warning("Command /${entry.command.name} could not use Paper's command API; using the classic command map", error) entry.fallbackRegistration = fallback.register(entry.owner ?: plugin, entry.command, entry.execute, entry.suggest) } } @@ -92,7 +86,7 @@ class PaperNativeCommandRegistrar( private fun invocationOf(entry: Entry) = object : NativeInvocation { override fun execute(source: CommandSourceStack, input: String) { if (!entry.active) { - source.sender.sendMessage("Команда сейчас недоступна.") + source.sender.sendMessage("This command is currently unavailable.") return } val line = CommandLine.of(input, keepTrailing = false) @@ -117,7 +111,12 @@ class PaperNativeCommandRegistrar( override fun suggest(source: CommandSourceStack, input: String): CompletionStage> { val line = CommandLine.of(input, keepTrailing = true) - return entry.suggest(source.sender, line.label, line.arguments.toTypedArray()) + return entry.suggest(source.sender, line.label, line.arguments.toTypedArray()).whenComplete { _, error -> + // Tab runs on every keystroke, so one report per command is enough. + if (error != null && entry.suggestionFailureReported.compareAndSet(false, true)) { + pnLogger().error("Tab completion of /${entry.command.name} failed", error) + } + } } } } diff --git a/platforms/bukkit/paper/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/paper/BrigadierTreesTest.kt b/platforms/bukkit/paper/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/paper/BrigadierTreesTest.kt index eb9b371e0..d90dd394f 100644 --- a/platforms/bukkit/paper/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/paper/BrigadierTreesTest.kt +++ b/platforms/bukkit/paper/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/paper/BrigadierTreesTest.kt @@ -6,8 +6,8 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.commands.ArgumentType -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.command import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage @@ -96,7 +96,7 @@ class BrigadierTreesTest { override fun suggest(source: Set, input: String): CompletionStage> = CompletableFuture.completedFuture(emptyList()) - override fun allowed(source: Set, node: org.pnfolder.pnlibrary.api.commands.CommandNode): Boolean = + override fun allowed(source: Set, node: org.pnfolder.pnlibrary.api.commands.definition.CommandNode): Boolean = node.permission == null || node.permission in source } val dispatcher = CommandDispatcher>() diff --git a/platforms/bukkit/paper/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/paper/SpacelessWordTest.kt b/platforms/bukkit/paper/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/paper/SpacelessWordTest.kt new file mode 100644 index 000000000..9d9777d16 --- /dev/null +++ b/platforms/bukkit/paper/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/paper/SpacelessWordTest.kt @@ -0,0 +1,16 @@ +package org.pnfolder.pnlibrary.bukkit.paper + +import com.mojang.brigadier.StringReader +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class SpacelessWordTest { + @Test + fun `an id and a value with slashes colons and semicolons are read whole`() { + val reader = StringReader("shop/main:config.yml respawn world;0;64;0") + + assertEquals("shop/main:config.yml", SpacelessWord.parse(reader)) + reader.skip() + assertEquals("respawn", SpacelessWord.parse(reader)) + } +} diff --git a/platforms/bukkit/runtime/build.gradle.kts b/platforms/bukkit/runtime/build.gradle.kts index 531c3461d..6d1578925 100644 --- a/platforms/bukkit/runtime/build.gradle.kts +++ b/platforms/bukkit/runtime/build.gradle.kts @@ -11,7 +11,7 @@ base { archivesName = "${rootProject.property("pnlibrary.name")}-bukkit" } dependencies { implementation(project(":modules:api")) - implementation(project(":modules:runtime-spi")) + implementation(project(":modules:spi")) implementation(project(":modules:core")) implementation(project(":modules:features:currency-api")) implementation(project(":platforms:bukkit:api")) @@ -54,7 +54,8 @@ tasks.named("processResources") { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates( groupId = "io.github.pnfolder", diff --git a/platforms/bukkit/runtime/src/main/java/org/pnfolder/pnlibrary/bukkit/PnLibraryBukkitPlugin.java b/platforms/bukkit/runtime/src/main/java/org/pnfolder/pnlibrary/bukkit/PnLibraryBukkitPlugin.java index 93f07e0b4..aaafbfe63 100644 --- a/platforms/bukkit/runtime/src/main/java/org/pnfolder/pnlibrary/bukkit/PnLibraryBukkitPlugin.java +++ b/platforms/bukkit/runtime/src/main/java/org/pnfolder/pnlibrary/bukkit/PnLibraryBukkitPlugin.java @@ -26,6 +26,9 @@ public void onEnable() { LibrarySettings settings = LibrarySettings.DEFAULT; try { LibraryLoader.load(new BukkitLibraryManager(this, settings.directoryFor(getDataFolder().toPath())), getClassLoader(), settings, RuntimeLibraries.BUKKIT); + LibraryLoader.useManagers(owner -> owner instanceof org.bukkit.plugin.Plugin + ? new BukkitLibraryManager((org.bukkit.plugin.Plugin) owner, settings.directoryFor(((org.bukkit.plugin.Plugin) owner).getDataFolder().toPath())) + : null); Class type = Class.forName("org.pnfolder.pnlibrary.bukkit.BukkitRuntime", true, getClassLoader()); Constructor constructor = type.getDeclaredConstructors()[0]; runtime = constructor.newInstance(this); diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitDependentGuard.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitDependentGuard.kt index a8854c6ae..ea74667dd 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitDependentGuard.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitDependentGuard.kt @@ -31,6 +31,7 @@ internal class BukkitDependentGuard( } companion object { + /** Disables every enabled plugin that depends on [owner]; used when [owner] fails to start. */ fun disableDependentsOf(owner: Plugin, log: (String) -> Unit) { Bukkit.getPluginManager().plugins .filter { it !== owner && it.isEnabled && dependsOn(it, owner) } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitIntegration.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitIntegration.kt deleted file mode 100644 index a627de76e..000000000 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitIntegration.kt +++ /dev/null @@ -1,23 +0,0 @@ -package org.pnfolder.pnlibrary.bukkit - -import org.bukkit.plugin.java.JavaPlugin -import org.pnfolder.pnlibrary.core.runtime.PnLibraryRuntimeHost - -/** Everything an optional integration needs from the running plugin. */ -internal class IntegrationContext(val plugin: JavaPlugin, val runtime: PnLibraryRuntimeHost) - -/** - * One optional Bukkit plugin that pnLibrary can use when it is present. - * - * [pluginName] is the Bukkit plugin whose enable and disable events drive this integration. - * [connect] must be idempotent: it is called on every event that might make the integration available. - */ -internal interface BukkitIntegration : AutoCloseable { - val pluginName: String - - /** Connects when the optional plugin is available. Does nothing when already connected. */ - fun connect() - - /** Disconnects and releases the registration. Safe to call when not connected. */ - override fun close() -} diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLifecycleListener.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLifecycleListener.kt index a69ffee47..a5755826a 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLifecycleListener.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLifecycleListener.kt @@ -12,17 +12,13 @@ import org.bukkit.event.server.PluginDisableEvent import org.bukkit.plugin.EventExecutor import org.bukkit.plugin.Plugin import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskSpec -import org.pnfolder.pnlibrary.api.updates.UpdateState -import org.pnfolder.pnlibrary.bukkit.commands.BukkitControlCommand +import org.pnfolder.pnlibrary.bukkit.audience.JoinNoticeDelivery +import org.pnfolder.pnlibrary.bukkit.currency.error +import org.pnfolder.pnlibrary.bukkit.updates.UpdateReminders import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.events.PlayerLifecyclePublisher +import org.pnfolder.pnlibrary.core.events.player.PlayerLifecyclePublisher import org.pnfolder.pnlibrary.core.lifecycle.journalJoinNotice import org.pnfolder.pnlibrary.core.lifecycle.runtimeTaskScope -import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogView -import java.time.Duration import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.atomic.AtomicBoolean @@ -35,6 +31,7 @@ internal class BukkitLifecycleListener( private val closed = AtomicBoolean(false) private val readyCallbacks = CopyOnWriteArrayList() private val serverReady = AtomicBoolean(false) + private val reminders = UpdateReminders(plugin) { library } /** Runs a callback immediately when ready, otherwise queues it for server startup. */ fun whenServerReady(task: Runnable) { @@ -54,9 +51,9 @@ internal class BukkitLifecycleListener( if (serverReady.get() && readyCallbacks.remove(task)) task.run() } - /** Registers lifecycle events and the optional modern server-load notification. */ fun start(): BukkitLifecycleListener = apply { plugin.server.pluginManager.registerEvents(this, plugin) + reminders.start() // ServerLoadEvent exists on modern Bukkit/Paper, but this module also // targets old 1.8 APIs. Register it reflectively when available. runCatchingNonFatal { @@ -68,6 +65,9 @@ internal class BukkitLifecycleListener( EventExecutor { _, _ -> markServerReady() }, plugin, ) + }.onFailure { error -> + // Servers without the event are expected; any other failure leaves readiness callbacks waiting. + if (error !is ClassNotFoundException) library?.logging?.logger(plugin, "Runtime")?.error("Could not listen for server readiness", error) } } @@ -83,39 +83,25 @@ internal class BukkitLifecycleListener( library?.let { PlayerLifecyclePublisher.left(it, event.player.uniqueId, event.player.name) } } - /** Notifies authorized players about available or staged updates after joining, in the catalog's style. */ + /** Tells authorized players about updates and shows the journal notice after joining. */ @EventHandler fun onAdministratorJoin(event: PlayerJoinEvent) { val player = event.player - val canSeeUpdates = player.isOp || player.hasPermission("*") || - player.hasPermission("pnlibrary.admin") || player.hasPermission("pnlibrary.updates.notify") val canSeeJournal = player.isOp || player.hasPermission("pnlibrary.events.view") - if (!canSeeUpdates && !canSeeJournal) return - val runtime = library ?: return - runtime.runtimeTaskScope().schedule(TaskSpec.builder() - .execution(TaskExecution.entity(player)) - .delay(Duration.ofMillis(50)) - .action task@{ - val active = library ?: return@task - if (!player.isOnline) return@task - val audience = active.audiences.player(player.uniqueId) ?: return@task - if (canSeeJournal) active.journalJoinNotice().forEach(audience::sendMessage) - if (!canSeeUpdates) return@task - val snapshots = active.updates.all().map { it.snapshot } - val notice = UpdateCatalogView.announcement(snapshots, BukkitControlCommand.ROUTES, PnLibraryIdentity.SUPPORT_URL) - if (notice.isEmpty()) return@task - notice.forEach(audience::sendMessage) - val pending = snapshots.count { it.state == UpdateState.UPDATE_AVAILABLE || it.state == UpdateState.UPDATE_STAGED } - showTitle(player, pending) - } - .build()) + if (reminders.canSeeUpdates(player)) reminders.remind(player, withTitle = true) + if (canSeeJournal) showJournalNotice(player) } - /** The two-argument title is the only one 1.8 servers have; newer servers merely deprecate it. */ - @Suppress("DEPRECATION") - private fun showTitle(player: Player, pending: Int) { - val (title, subtitle) = BukkitTitle.updatesPending(pending) - player.sendTitle(title, subtitle) + private fun showJournalNotice(player: Player) { + val runtime = library ?: return + JoinNoticeDelivery(runtime.runtimeTaskScope()).deliver( + player, + build = { library?.journalJoinNotice().orEmpty() }, + send = { lines -> + val audience = library?.audiences?.player(player.uniqueId) + if (audience != null) lines.forEach(audience::sendMessage) + }, + ) } /** Closing the plugin registration releases all its module commands and task scopes. */ @@ -124,16 +110,20 @@ internal class BukkitLifecycleListener( library?.plugins?.unregister(event.plugin) } - /** Drains queued readiness callbacks once. */ private fun markServerReady() { if (!serverReady.compareAndSet(false, true)) return - readyCallbacks.toList().forEach { runCatchingNonFatal(it::run) } + readyCallbacks.toList().forEach { callback -> + runCatchingNonFatal(callback::run).onFailure { + library?.logging?.logger(plugin, "Runtime")?.error("A startup task failed after the server became ready", it) + } + } readyCallbacks.clear() } override fun close() { if (!closed.compareAndSet(false, true)) return HandlerList.unregisterAll(this) + reminders.close() readyCallbacks.clear() library = null } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLinkReporter.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLinkReporter.kt index 408a200ea..65853d6aa 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLinkReporter.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLinkReporter.kt @@ -7,12 +7,12 @@ import org.bukkit.plugin.messaging.PluginMessageListener import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.bukkit.tasks.ServerScheduler import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.link.DataChunks import org.pnfolder.pnlibrary.core.link.Link -import org.pnfolder.pnlibrary.core.link.LinkCodec -import org.pnfolder.pnlibrary.core.link.LinkReports -import org.pnfolder.pnlibrary.core.link.LinkSecret -import org.pnfolder.pnlibrary.core.link.RemoteExecutor +import org.pnfolder.pnlibrary.core.link.remote.RemoteExecutor +import org.pnfolder.pnlibrary.core.link.report.LinkReports +import org.pnfolder.pnlibrary.core.link.wire.DataChunks +import org.pnfolder.pnlibrary.core.link.wire.LinkCodec +import org.pnfolder.pnlibrary.core.link.wire.LinkSecret import java.util.UUID /** @@ -28,6 +28,7 @@ internal class BukkitLinkReporter( private val scheduler: ServerScheduler, ) : PluginMessageListener { private var task: ServerScheduler.Scheduled? = null + private var reportFailing = false private val executor = RemoteExecutor(library) fun start() { @@ -90,6 +91,10 @@ internal class BukkitLinkReporter( val platform = "${Bukkit.getName()} ${Bukkit.getBukkitVersion()}" runCatchingNonFatal { carrier.sendPluginMessage(plugin, LinkCodec.CHANNEL, LinkCodec.encode(LinkReports.build(library, platform, players.size), key)) + }.onSuccess { reportFailing = false }.onFailure { + // The report repeats every half minute; the first failure is enough until one succeeds again. + if (!reportFailing) library.logging.logger(plugin, "Reporter").error("Could not send the status report to the proxy", it) + reportFailing = true } } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitPlatformAdapter.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitPlatformAdapter.kt index 8847af9c8..73430d1b1 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitPlatformAdapter.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitPlatformAdapter.kt @@ -5,13 +5,17 @@ import org.bukkit.entity.Player import org.bukkit.plugin.Plugin import org.pnfolder.pnlibrary.api.currency.currencyProviders import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.remote.RemotePolicyContext import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.bukkit.audience.BukkitAudienceAdapter +import org.pnfolder.pnlibrary.bukkit.audience.BukkitAudienceService import org.pnfolder.pnlibrary.bukkit.commands.BukkitCommandAdapter import org.pnfolder.pnlibrary.bukkit.commands.BukkitCommandSender import org.pnfolder.pnlibrary.bukkit.commands.BukkitControlCommand import org.pnfolder.pnlibrary.bukkit.compat.ServerCapabilities +import org.pnfolder.pnlibrary.bukkit.integration.BukkitMetricsFactory import org.pnfolder.pnlibrary.bukkit.remote.BukkitRemotePolicyContextFactory import org.pnfolder.pnlibrary.bukkit.server.ServerInfo import org.pnfolder.pnlibrary.bukkit.tasks.BukkitTaskAdapter @@ -45,6 +49,8 @@ internal class BukkitPlatformAdapter( val plugin: Plugin, audienceService: BukkitAudienceService, private val link: Link = Link.OFF, + private val pnLogger: () -> PnLogger, + private val logBuffer: PnLoggerBuffer, ) : PlatformAdapter { private val lifecycle = PlatformLifecycle() @@ -73,6 +79,7 @@ internal class BukkitPlatformAdapter( private var lifecycleListener: BukkitLifecycleListener? = null override val type: PlatformType = PlatformType.BUKKIT + override val minecraftVersion: String? get() = runCatching { ServerCapabilities.rawMinecraftVersion }.getOrNull() override val dataFolder = plugin.dataFolder.toPath() override val implementationName: String @@ -88,10 +95,10 @@ internal class BukkitPlatformAdapter( } override val metricsFactory: PlatformMetricsFactory = - BukkitMetricsFactory() + BukkitMetricsFactory(pnLogger) override val commandAdapter: PlatformCommandAdapter = - BukkitCommandAdapter(audienceService, plugin) + BukkitCommandAdapter(audienceService, plugin, pnLogger, logBuffer) override val audienceAdapter: PlatformAudienceAdapter = BukkitAudienceAdapter(audienceService) @@ -107,7 +114,6 @@ internal class BukkitPlatformAdapter( Bukkit.getConsoleSender().sendMessage(message) } - /** Reads native plugin metadata, warning and returning null for unsupported owners. */ override fun ownerMetadata(owner: Any): PluginSnapshot? = plugins.metadata(owner, this) override fun ownerDataFolder(owner: Any): Path? = plugins.find(owner)?.dataFolder?.toPath() @@ -116,7 +122,6 @@ internal class BukkitPlatformAdapter( override fun installedPlugins(): Map = plugins.versions() - /** Collects typed platform metadata without individual player identities. */ override fun snapshot(): PlatformSnapshot = PlatformSnapshot( name = implementationName, @@ -133,7 +138,7 @@ internal class BukkitPlatformAdapter( override fun disableOwner(owner: Any): Boolean { val installed = plugins.requireInstalled(owner, "Disabled owner") - BukkitDependentGuard.disableDependentsOf(installed) { plugin.logger.warning(it) } + BukkitDependentGuard.disableDependentsOf(installed) { pnLogger().warning(it) } Bukkit.getPluginManager().disablePlugin(installed) return true } @@ -141,7 +146,9 @@ internal class BukkitPlatformAdapter( /** Disables dependents as they enable and switches [owner] off once the server has started. */ override fun disableDependents(owner: Any): Boolean { if (owner !== plugin) return false - return runCatchingNonFatal { BukkitDependentGuard(plugin, scheduler::nextTick) { plugin.logger.warning(it) }.arm() }.isSuccess + return runCatchingNonFatal { BukkitDependentGuard(plugin, scheduler::nextTick) { pnLogger().warning(it) }.arm() } + .onFailure { pnLogger().error("Could not watch plugins that depend on pnLibrary", it) } + .isSuccess } /** Registers or removes the observer of server and plugin warnings, errors and uncaught thread exceptions. */ diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitPlatformServices.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitPlatformServices.kt deleted file mode 100644 index 286584b8d..000000000 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitPlatformServices.kt +++ /dev/null @@ -1,20 +0,0 @@ -package org.pnfolder.pnlibrary.bukkit - -import org.bukkit.Server -import org.pnfolder.pnlibrary.bukkit.api.BukkitPlatform -import org.pnfolder.pnlibrary.bukkit.entity.ArmorStandVisual -import org.pnfolder.pnlibrary.bukkit.entity.VisualService -import org.pnfolder.pnlibrary.bukkit.inventory.MenuService -import org.pnfolder.pnlibrary.bukkit.item.BukkitItems -import org.pnfolder.pnlibrary.bukkit.item.ItemService -import org.pnfolder.pnlibrary.bukkit.server.ServerInfo - -/** Native-backed Bukkit platform API installed by the Bukkit runtime. */ -internal class BukkitPlatformServices( - override val server: Server, - override val serverInfo: ServerInfo, - override val menus: MenuService, -) : BukkitPlatform { - override val items: ItemService = BukkitItems - override val visuals: VisualService = ArmorStandVisual.Factory -} diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitRuntime.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitRuntime.kt index ed2e73d5f..6cecce835 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitRuntime.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitRuntime.kt @@ -1,9 +1,18 @@ package org.pnfolder.pnlibrary.bukkit +import org.bukkit.Server import org.bukkit.plugin.java.JavaPlugin +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.bukkit.api.BukkitPlatform +import org.pnfolder.pnlibrary.bukkit.audience.BukkitAudienceService +import org.pnfolder.pnlibrary.bukkit.currency.error +import org.pnfolder.pnlibrary.bukkit.entity.ArmorStandVisual +import org.pnfolder.pnlibrary.bukkit.entity.VisualService +import org.pnfolder.pnlibrary.bukkit.integration.BukkitIntegrations import org.pnfolder.pnlibrary.bukkit.inventory.BukkitMenus import org.pnfolder.pnlibrary.bukkit.inventory.MenuService +import org.pnfolder.pnlibrary.bukkit.item.BukkitItems +import org.pnfolder.pnlibrary.bukkit.item.ItemService import org.pnfolder.pnlibrary.bukkit.server.ServerInfo import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.core.lifecycle.runtimeTaskScope @@ -22,15 +31,23 @@ internal class BukkitRuntime(private val plugin: JavaPlugin) { private var menus: BukkitMenus? = null private var integrations: BukkitIntegrations? = null private var link: BukkitLinkReporter? = null + private var logger: PnLogger? = null fun start() { - val audienceService = BukkitAudienceService(plugin) + var startupLogger: PnLogger? = null + val logBuffer = PnLoggerBuffer(plugin.logger) { startupLogger } + val audienceService = BukkitAudienceService(plugin, logBuffer) audiences = audienceService val network = openLink(plugin) - val adapter = BukkitPlatformAdapter(plugin, audienceService, network) + var metricsLogger: PnLogger? = null + val adapter = BukkitPlatformAdapter(plugin, audienceService, network, { metricsLogger!! }, logBuffer) try { val runtime = PnLibraryRuntimeHost.start(plugin, adapter) host = runtime + startupLogger = runtime.library.logging.logger(plugin, "Runtime") + logBuffer.flush() + metricsLogger = runtime.library.logging.logger(plugin, "Metrics") + logger = startupLogger installServices(runtime, adapter, audienceService) val optional = BukkitIntegrations(plugin) integrations = optional @@ -44,21 +61,26 @@ internal class BukkitRuntime(private val plugin: JavaPlugin) { } fun stop() { - runCatchingNonFatal { link?.stop() } + release("link") { link?.stop() } link = null - runCatchingNonFatal { integrations?.stop() } + release("integrations") { integrations?.stop() } integrations = null - runCatchingNonFatal { menus?.close() } + release("menus") { menus?.close() } menus = null - runCatchingNonFatal { audiences?.close() } + release("audiences") { audiences?.close() } audiences = null - runCatchingNonFatal { host?.close() } + release("library") { host?.close() } host = null + logger = null + } + + /** One part failing to stop must not keep the others from stopping, but it must not vanish either. */ + private fun release(part: String, action: () -> Unit) { + runCatchingNonFatal(action).onFailure { logger?.error("Could not stop $part", it) } } - /** Registers Bukkit-only services and the native platform view on the running runtime. */ private fun installServices(runtime: PnLibraryRuntimeHost, adapter: BukkitPlatformAdapter, audienceService: BukkitAudienceService) { - val menuService = BukkitMenus(plugin, runtime.library.runtimeTaskScope()) + val menuService = BukkitMenus(plugin, runtime.library.runtimeTaskScope(), pnLogger = { runtime.library.logging.logger(plugin, "Menus") }) runtime.registerService(ServerInfo::class.java, adapter.serverInfo) runtime.registerService(MenuService::class.java, menuService) runtime.registerPlatform(BukkitPlatform::class.java, BukkitPlatformServices(plugin.server, adapter.serverInfo, menuService)) @@ -66,3 +88,13 @@ internal class BukkitRuntime(private val plugin: JavaPlugin) { menus = menuService } } + +/** Native-backed Bukkit platform API installed by the Bukkit runtime. */ +private class BukkitPlatformServices( + override val server: Server, + override val serverInfo: ServerInfo, + override val menus: MenuService, +) : BukkitPlatform { + override val items: ItemService = BukkitItems + override val visuals: VisualService = ArmorStandVisual.Factory +} diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/PnLoggerBuffer.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/PnLoggerBuffer.kt new file mode 100644 index 000000000..bc5fa7814 --- /dev/null +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/PnLoggerBuffer.kt @@ -0,0 +1,35 @@ +package org.pnfolder.pnlibrary.bukkit + +import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.api.logging.PnLogger +import java.util.logging.Level +import java.util.logging.Logger + +/** + * Routes log calls to PnLogger when the library has started. Before that, outputs immediately to + * the native console logger and buffers the entry. On [flush], buffered entries are replayed via + * [PnLogger.record] at their original level, going to the journal only — no second console line. + */ +internal class PnLoggerBuffer(private val native: Logger, private val source: () -> PnLogger?) { + private data class Entry(val level: LogLevel, val message: String, val error: Throwable?) + private val entries = mutableListOf() + + @JvmOverloads + fun log(level: LogLevel, message: String, error: Throwable? = null) { + source()?.log(level, message, error) ?: run { + val javaLevel = when (level) { + LogLevel.WARNING -> Level.WARNING + LogLevel.ERROR, LogLevel.CRITICAL -> Level.SEVERE + else -> Level.INFO + } + if (error != null) native.log(javaLevel, message, error) else native.log(javaLevel, message) + entries.add(Entry(level, message, error)) + } + } + + fun flush() { + val logger = source() ?: return + entries.forEach { (level, msg, err) -> logger.record(level, msg, err) } + entries.clear() + } +} diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitAudienceAdapter.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitAudienceAdapter.kt similarity index 89% rename from platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitAudienceAdapter.kt rename to platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitAudienceAdapter.kt index cca13d7de..b137a2a9b 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitAudienceAdapter.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitAudienceAdapter.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.bukkit +package org.pnfolder.pnlibrary.bukkit.audience import net.kyori.adventure.sound.Sound import net.kyori.adventure.text.Component @@ -9,7 +9,8 @@ import org.bukkit.command.ConsoleCommandSender import org.bukkit.entity.Player import org.pnfolder.pnlibrary.api.audiences.AudienceSender import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.bukkit.currency.LEGACY import org.pnfolder.pnlibrary.spi.audiences.PlatformAudienceAdapter import java.util.UUID @@ -22,12 +23,10 @@ internal class BukkitAudienceAdapter( override fun player(uniqueId: UUID): LibraryPlayer? = Bukkit.getPlayer(uniqueId)?.let { BukkitLibraryPlayer(it, audiences) } - /** Wraps native Bukkit senders; unsupported objects return null. */ override fun sender(native: Any): AudienceSender? = (native as? CommandSender)?.let(::wrap) override fun onlinePlayers(): List = Bukkit.getOnlinePlayers().map { BukkitLibraryPlayer(it, audiences) } - /** Uses the player transport where available, otherwise a legacy sender wrapper. */ private fun wrap(sender: CommandSender): AudienceSender = if (sender is Player) BukkitLibraryPlayer(sender, audiences) else BukkitSenderAudience(sender) diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitAudienceService.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitAudienceService.kt similarity index 78% rename from platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitAudienceService.kt rename to platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitAudienceService.kt index 942f82e14..c48e93b4c 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitAudienceService.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitAudienceService.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.bukkit +package org.pnfolder.pnlibrary.bukkit.audience import net.kyori.adventure.audience.Audience import net.kyori.adventure.platform.bukkit.BukkitAudiences @@ -10,11 +10,16 @@ import org.bukkit.entity.Player import org.bukkit.plugin.Plugin import org.pnfolder.pnlibrary.api.audiences.Delivery import org.pnfolder.pnlibrary.api.audiences.LibraryAudience -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.bukkit.PnLoggerBuffer +import org.pnfolder.pnlibrary.bukkit.currency.LEGACY +import org.pnfolder.pnlibrary.bukkit.currency.error import org.pnfolder.pnlibrary.common.lang.Failures import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import java.lang.reflect.Array import java.util.UUID +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean /** @@ -26,16 +31,19 @@ import java.util.concurrent.atomic.AtomicBoolean * native transport failure, later messages use the fallback to avoid repeatedly failing calls. * Close this service with the owning plugin to release Adventure platform resources. */ -internal class BukkitAudienceService internal constructor(plugin: Plugin, private val audiences: BukkitAudiences?) : AutoCloseable { - constructor(plugin: Plugin) : this(plugin, createProvider(plugin)) - - private val logger = plugin.logger +internal class BukkitAudienceService( + plugin: Plugin, + private val log: PnLoggerBuffer, + private val audiences: BukkitAudiences? = createProvider(plugin, log), +) : AutoCloseable { private val pluginServer = plugin.server private val fallbackOnly = AtomicBoolean(audiences == null && !NATIVE_ADVENTURE) + private val reportedFailures = ConcurrentHashMap.newKeySet() /** Whether the native Adventure transport is still available for new deliveries. */ val nativeTransportAvailable: Boolean get() = !fallbackOnly.get() + /** Wraps an online Bukkit [player] for the library API. */ fun player(player: Player): LibraryPlayer = BukkitLibraryPlayer(player, this) @@ -63,7 +71,6 @@ internal class BukkitAudienceService internal constructor(plugin: Plugin, privat send(player, message, true) } - /** Tries Adventure delivery before switching to the sticky legacy fallback. */ private fun send(player: Player, message: Component, actionBar: Boolean) { val provider = audiences if (!fallbackOnly.get() && (player is Audience || provider != null)) { @@ -81,7 +88,7 @@ internal class BukkitAudienceService internal constructor(plugin: Plugin, privat Failures.rethrowIfFatal(error) // A broken/incompatible platform bridge must not break the calling plugin. if (fallbackOnly.compareAndSet(false, true)) { - logger.warning("Adventure Bukkit transport failed (${error.javaClass.simpleName}); switched to legacy text fallback") + log.log(LogLevel.ERROR, "Adventure Bukkit transport failed; switched to legacy text fallback", error) } } } @@ -89,7 +96,6 @@ internal class BukkitAudienceService internal constructor(plugin: Plugin, privat if (actionBar) sendLegacyActionBar(player, legacy) else player.sendMessage(legacy) } - /** Uses optional Spigot action-bar APIs, falling back to ordinary chat. */ private fun sendLegacyActionBar(player: Player, message: String) { runCatchingNonFatal { val chatType = Class.forName("net.md_5.bungee.api.ChatMessageType").getField("ACTION_BAR").get(null) @@ -105,7 +111,13 @@ internal class BukkitAudienceService internal constructor(plugin: Plugin, privat /** Tries Adventure sound delivery, then the native Bukkit sound API. */ internal fun playSound(player: Player, sound: Sound): Delivery { if (player is Audience && !fallbackOnly.get()) { - try { player.playSound(sound); return Delivery.Delivered } catch (error: Throwable) { Failures.rethrowIfFatal(error) } + try { + player.playSound(sound) + return Delivery.Delivered + } catch (error: Throwable) { + Failures.rethrowIfFatal(error) + reportOnce("sound", error) + } } val provider = audiences if (provider != null && !fallbackOnly.get()) { @@ -114,6 +126,7 @@ internal class BukkitAudienceService internal constructor(plugin: Plugin, privat return Delivery.Delivered } catch (error: Throwable) { Failures.rethrowIfFatal(error) + reportOnce("sound", error) } } return deliver { player.playSound(player.location, sound.name().asString(), sound.volume(), sound.pitch()) } @@ -130,25 +143,31 @@ internal class BukkitAudienceService internal constructor(plugin: Plugin, privat return Delivery.Delivered } catch (error: Throwable) { Failures.rethrowIfFatal(error) + reportOnce("title", error) } } return deliver { player.sendTitle(LEGACY.serialize(title.title()), LEGACY.serialize(title.subtitle())) } } + /** The legacy fallback still delivers, so one report per kind is enough to show the Adventure transport is broken. */ + private fun reportOnce(kind: String, error: Throwable) { + if (reportedFailures.add(kind)) log.log(LogLevel.ERROR, "Adventure $kind delivery failed; using the legacy fallback", error) + } + /** Releases the underlying Adventure audience provider when one was created. */ override fun close() { - runCatchingNonFatal { audiences?.close() } + runCatchingNonFatal { audiences?.close() }.onFailure { log.log(LogLevel.ERROR, "Could not close the Adventure transport", it) } } private companion object { val LEGACY: LegacyComponentSerializer = LegacyComponentSerializer.legacySection() val NATIVE_ADVENTURE = Audience::class.java.isAssignableFrom(Player::class.java) - fun createProvider(plugin: Plugin): BukkitAudiences? { + fun createProvider(plugin: Plugin, log: PnLoggerBuffer): BukkitAudiences? { if (NATIVE_ADVENTURE) return null return try { BukkitAudiences.create(plugin) } catch (error: Throwable) { Failures.rethrowIfFatal(error) - plugin.logger.warning("Adventure Bukkit transport is unavailable (${error.javaClass.simpleName}); using legacy text fallback") + log.log(LogLevel.WARNING, "Adventure Bukkit transport is unavailable (${error.javaClass.simpleName}); using legacy text fallback") null } } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLibraryPlayer.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitLibraryPlayer.kt similarity index 92% rename from platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLibraryPlayer.kt rename to platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitLibraryPlayer.kt index c3cd39178..13f117403 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLibraryPlayer.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitLibraryPlayer.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.bukkit +package org.pnfolder.pnlibrary.bukkit.audience import net.kyori.adventure.sound.Sound import net.kyori.adventure.text.Component @@ -11,11 +11,13 @@ import org.bukkit.inventory.ItemStack import org.bukkit.potion.PotionEffect import org.bukkit.potion.PotionEffectType import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.audiences.ItemQuery -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.audiences.PlayerCapability -import org.pnfolder.pnlibrary.api.audiences.PlayerEffect -import org.pnfolder.pnlibrary.api.audiences.PlayerParticle +import org.pnfolder.pnlibrary.api.audiences.player.ItemQuery +import org.pnfolder.pnlibrary.api.audiences.player.LibraryPlayer +import org.pnfolder.pnlibrary.api.audiences.player.PlayerCapability +import org.pnfolder.pnlibrary.api.audiences.player.PlayerEffect +import org.pnfolder.pnlibrary.api.audiences.player.PlayerParticle +import org.pnfolder.pnlibrary.bukkit.currency.configured +import org.pnfolder.pnlibrary.bukkit.currency.error import org.pnfolder.pnlibrary.common.lang.Failures import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import java.time.Duration @@ -46,7 +48,6 @@ internal class BukkitLibraryPlayer( audiences.sendActionBar(player, text) } - /** Plays a sound, falling back to the native Bukkit API where needed. */ override fun playSound(sound: Sound): Delivery = audiences.playSound(player, sound) override fun showTitle(title: Component, subtitle: Component, fadeIn: Duration, stay: Duration, fadeOut: Duration): Delivery = diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitTitle.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitTitle.kt similarity index 91% rename from platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitTitle.kt rename to platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitTitle.kt index 7e9842dcf..640a0dba1 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitTitle.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitTitle.kt @@ -1,9 +1,10 @@ -package org.pnfolder.pnlibrary.bukkit +package org.pnfolder.pnlibrary.bukkit.audience import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.TextColor import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.bukkit.currency.LEGACY import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogCommands.SettingSaved /** diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/JoinNoticeDelivery.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/JoinNoticeDelivery.kt new file mode 100644 index 000000000..35d0723dc --- /dev/null +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/audience/JoinNoticeDelivery.kt @@ -0,0 +1,29 @@ +package org.pnfolder.pnlibrary.bukkit.audience + +import net.kyori.adventure.text.Component +import org.bukkit.entity.Player +import org.pnfolder.pnlibrary.api.tasks.TaskScope +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec +import java.time.Duration + +/** Builds the journal notice off the server thread and sends it from the player's own thread. */ +internal class JoinNoticeDelivery(private val tasks: TaskScope) { + /** Reading the journal can take long, so [build] runs asynchronously; only [send] touches the player. */ + fun deliver(player: Player, build: () -> List, send: (List) -> Unit) { + tasks.schedule(TaskSpec.builder() + .execution(TaskExecution.async()) + .delay(Duration.ofMillis(50)) + .action { + val lines = build() + if (lines.isNotEmpty()) tasks.schedule(sendTask(player, lines, send)) + } + .build()) + } + + private fun sendTask(player: Player, lines: List, send: (List) -> Unit): TaskSpec = + TaskSpec.builder() + .execution(TaskExecution.entity(player)) + .action { if (player.isOnline) send(lines) } + .build() +} diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitCommandAdapter.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitCommandAdapter.kt index 6b692735c..a9bb23321 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitCommandAdapter.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitCommandAdapter.kt @@ -12,12 +12,14 @@ import org.bukkit.plugin.java.JavaPlugin import org.pnfolder.pnlibrary.api.audiences.AudienceSender import org.pnfolder.pnlibrary.api.audiences.Delivery import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition import org.pnfolder.pnlibrary.api.commands.CommandSender -import org.pnfolder.pnlibrary.bukkit.BukkitAudienceAdapter -import org.pnfolder.pnlibrary.bukkit.BukkitAudienceService -import org.pnfolder.pnlibrary.core.commands.MAIN_THREAD_SUGGESTION_MILLIS -import org.pnfolder.pnlibrary.core.commands.suggestionsWithin +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.logging.PnLogger +import org.pnfolder.pnlibrary.bukkit.PnLoggerBuffer +import org.pnfolder.pnlibrary.bukkit.audience.BukkitAudienceAdapter +import org.pnfolder.pnlibrary.bukkit.audience.BukkitAudienceService +import org.pnfolder.pnlibrary.core.commands.engine.MAIN_THREAD_SUGGESTION_MILLIS +import org.pnfolder.pnlibrary.core.commands.engine.suggestionsWithin import org.pnfolder.pnlibrary.spi.commands.GenericPlatformCommandAdapter import org.pnfolder.pnlibrary.spi.commands.NativeCommandRegistrar import org.pnfolder.pnlibrary.spi.commands.PlatformCommandRegistration @@ -25,21 +27,14 @@ import java.lang.reflect.Constructor import java.util.concurrent.CompletionStage import org.bukkit.command.CommandSender as NativeCommandSender -/** - * Registers portable commands and owns their native Bukkit registrations. - * - * Native tab completion is synchronous, so suggestion requests use a bounded one-second wait. - * Commands are released in reverse registration order when this adapter closes. - */ internal class BukkitCommandAdapter internal constructor( private val nativeRegistrar: NativeCommandRegistrar, private val audience: (NativeCommandSender) -> AudienceSender, private val interactive: () -> Boolean = { true }, ) : GenericPlatformCommandAdapter() { override val registrar: NativeCommandRegistrar = nativeRegistrar - /** Creates the native registrar, preferring Paper's command API where the server has it, and the audience bridge. */ - constructor(audiences: BukkitAudienceService, plugin: Plugin) : this( - nativeRegistrar = PaperCommandSupport.choose(plugin, DefaultBukkitNativeCommandRegistrar()), + constructor(audiences: BukkitAudienceService, plugin: Plugin, pnLogger: () -> PnLogger, logBuffer: PnLoggerBuffer) : this( + nativeRegistrar = PaperCommandSupport.choose(plugin, DefaultBukkitNativeCommandRegistrar(), pnLogger, logBuffer), { sender -> requireNotNull(BukkitAudienceAdapter(audiences).sender(sender)) }, { audiences.nativeTransportAvailable }, ) @@ -57,14 +52,13 @@ internal class BukkitCommandAdapter internal constructor( } -/** Internal wrapper; native access never crosses the public command API. */ internal class BukkitCommandSender( internal val native: NativeCommandSender, private val audience: AudienceSender, private val transportAvailable: () -> Boolean = { true }, ) : CommandSender, AudienceSender by audience { - /** Buttons work for players only while the Adventure transport is in use; the fallback sends plain text. */ + // Buttons need the Adventure transport; without it the sender receives plain text and can't click anything. override val supportsInteraction: Boolean get() = !isConsole && transportAvailable() @@ -77,8 +71,6 @@ internal class BukkitCommandSender( override fun playSound(sound: Sound): Delivery = audience.playSound(sound) } -/** Native registration boundary used by the runtime and command tests. */ -/** Uses declared plugin commands where available, otherwise the legacy command map. */ private class DefaultBukkitNativeCommandRegistrar : NativeCommandRegistrar { override fun register( owner: Any, @@ -123,7 +115,6 @@ private class DefaultBukkitNativeCommandRegistrar : NativeCommandRegistrar = PluginCommand::class.java.getDeclaredConstructor( String::class.java, diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitCommandReplies.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitCommandReplies.kt index 51c5fb859..b2150ca2a 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitCommandReplies.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitCommandReplies.kt @@ -4,11 +4,11 @@ import org.bukkit.command.CommandSender import org.bukkit.command.ConsoleCommandSender import org.bukkit.entity.Player import org.pnfolder.pnlibrary.api.chat.ChatNotice -import org.pnfolder.pnlibrary.api.chat.ChatTone import org.pnfolder.pnlibrary.api.chat.ConfirmChoice +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandContext import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.updates.UpdateActor +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor import org.pnfolder.pnlibrary.bukkit.tasks.ServerScheduler import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogRoutes import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogView @@ -27,9 +27,11 @@ internal class BukkitCommandReplies( fun routes(reply: Reply): UpdateCatalogRoutes = BukkitControlCommand.ROUTES.copy(interactive = reply.supportsInteraction, ascii = reply.isConsole) + /** Sends one notice with [text] and an optional [detail] line. */ fun say(reply: Reply, tone: ChatTone, text: String, detail: String? = null) = notices(reply, listOf(ChatNotice(tone, text, detail))) + /** Sends several notices in one message. */ fun notices(reply: Reply, notices: List) = UpdateCatalogView.notices(notices, routes(reply)).forEach(reply::send) diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitConsoleStatusRenderer.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitConsoleStatusRenderer.kt index 9dff33e59..67ae9177c 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitConsoleStatusRenderer.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitConsoleStatusRenderer.kt @@ -2,16 +2,17 @@ package org.pnfolder.pnlibrary.bukkit.commands import org.bukkit.Bukkit import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.UpdateChannel import org.pnfolder.pnlibrary.api.updates.UpdateRegistration -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ReleaseSummary +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.common.text.RussianText import org.pnfolder.pnlibrary.console.ConsoleCard -import org.pnfolder.pnlibrary.core.ui.ConsoleStyle -import org.pnfolder.pnlibrary.core.updates.catalog.UpdateChannelLabels +import org.pnfolder.pnlibrary.core.text.ConsoleStyle +import org.pnfolder.pnlibrary.updates.policy.color +import org.pnfolder.pnlibrary.updates.policy.title import java.time.Duration import java.time.Instant import java.time.ZoneOffset @@ -20,7 +21,6 @@ import java.util.Locale /** Builds the detailed console-only pnLibrary status card. */ internal object BukkitConsoleStatusRenderer { - /** Builds the console status card from registered update snapshots. */ fun render(entries: List): List { val card = ConsoleCard.builder(ConsoleStyle.THEME, "СОСТОЯНИЕ PNFOLDER") .mascot("^.^", PnLibraryIdentity.NAME, "библиотека платформы") @@ -52,7 +52,6 @@ internal object BukkitConsoleStatusRenderer { .render() } - /** Appends channel settings, release history, and the selected update. */ private fun renderRegisteredUpdates( card: ConsoleCard.Builder, entries: List, @@ -110,7 +109,6 @@ internal object BukkitConsoleStatusRenderer { ) } - /** Displays the latest known release in each configured display channel. */ private fun renderReleaseHistory( card: ConsoleCard.Builder, snapshot: UpdateSnapshot, @@ -134,8 +132,8 @@ internal object BukkitConsoleStatusRenderer { card.blank() channels.forEachIndexed { index, (channel, release) -> - card.section(UpdateChannelLabels.channelTitle(channel).replaceFirstChar { it.titlecase(Locale.ROOT) }) - .detail("Версия", ConsoleStyle.paint(release.version, UpdateChannelLabels.channelColor(channel))) + card.section(channel.title().replaceFirstChar { it.titlecase(Locale.ROOT) }) + .detail("Версия", ConsoleStyle.paint(release.version, channel.color())) .lastDetail( "Опубликована", release.publishedAt?.let(::publishedAtLabel) ?: "дата неизвестна", @@ -146,7 +144,6 @@ internal object BukkitConsoleStatusRenderer { } } - /** Ensures the selected compatible release is represented in the displayed history. */ private fun mergeSelectedRelease( history: MutableList, snapshot: UpdateSnapshot, @@ -164,18 +161,15 @@ internal object BukkitConsoleStatusRenderer { } } - /** Summarizes whether a registered product has an available update. */ private fun status(entries: List): String { val available = entries.firstOrNull { it.snapshot.hasAvailableUpdate() }?.snapshot ?: return "Все зарегистрированные компоненты актуальны" return "Доступно обновление · ${BukkitStatusLabels.channel(available)}" } - /** Checks whether the snapshot represents a downloadable update. */ private fun UpdateSnapshot.hasAvailableUpdate(): Boolean = state == UpdateState.UPDATE_AVAILABLE - /** Combines the publication age with an absolute UTC timestamp. */ private fun publishedAtLabel(instant: Instant): String = "${publishedAge(instant)} · ${UTC_DATE_TIME.format(instant)}" @@ -184,7 +178,6 @@ internal object BukkitConsoleStatusRenderer { return "опубликована ${RussianText.ago(Duration.between(instant, Instant.now()))}" } - /** Formats the current instant in the console UTC format. */ private fun utcNow(): String = UTC_DATE_TIME.format(Instant.now()) private val ZERO_VERSION = SemanticVersion.parse("0.0.0") @@ -202,7 +195,6 @@ internal object BukkitConsoleStatusRenderer { /** Shared human-readable labels used by console and in-game status output. */ internal object BukkitStatusLabels { - /** Reads the JVM implementation and version from runtime properties. */ fun javaRuntime(): String { val version = System.getProperty("java.version")?.trim().orEmpty() val vm = System.getProperty("java.vm.name")?.trim().orEmpty() @@ -217,11 +209,9 @@ internal object BukkitStatusLabels { .ifBlank { System.getProperty("java.runtime.version", "unknown") } } - /** Returns the localized, colored channel label for a snapshot. */ fun channel(snapshot: UpdateSnapshot): String = - ConsoleStyle.paint(UpdateChannelLabels.channelTitle(snapshot.channel), UpdateChannelLabels.channelColor(snapshot.channel)) + ConsoleStyle.paint(snapshot.channel.title(), snapshot.channel.color()) - /** Returns the branded library name or the registered product name. */ fun product(product: String): String = if (product.equals(PnLibraryIdentity.PRODUCT_ID, true)) PnLibraryIdentity.NAME else product } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitControlCommand.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitControlCommand.kt index 5fb102b57..6ba48df41 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitControlCommand.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitControlCommand.kt @@ -2,21 +2,26 @@ package org.pnfolder.pnlibrary.bukkit.commands import org.bukkit.entity.Player import org.bukkit.plugin.Plugin -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.commands.ArgumentType -import org.pnfolder.pnlibrary.api.commands.CommandBuilder +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandBuilder +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command import org.pnfolder.pnlibrary.api.currency.CurrencyProviderRegistry import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.bukkit.currency.CurrencyCommandExecutor import org.pnfolder.pnlibrary.bukkit.menu.PluginsMenu import org.pnfolder.pnlibrary.bukkit.tasks.ServerScheduler +import org.pnfolder.pnlibrary.core.commands.configs.ConfigsCommand +import org.pnfolder.pnlibrary.core.commands.deps.DepsCommand import org.pnfolder.pnlibrary.core.commands.events.EventBusCommand +import org.pnfolder.pnlibrary.core.commands.modules.ModulesCommand import org.pnfolder.pnlibrary.core.commands.proxy.ServersCommand import org.pnfolder.pnlibrary.core.commands.tasks.TaskCommand +import org.pnfolder.pnlibrary.core.lifecycle.MountableCommands import org.pnfolder.pnlibrary.core.lifecycle.mountableCommand +import org.pnfolder.pnlibrary.core.lifecycle.settingPicker import org.pnfolder.pnlibrary.core.link.Link import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogCommands import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogRoutes @@ -68,7 +73,17 @@ internal class BukkitControlCommand( private val support = BukkitSupportCommands(plugin, library, replies) private val menu = PluginsMenu(plugin, library, replies, link, scheduler) - override fun close() = menu.close() + init { + // `/pn settings pick` is a shared command; the menu it opens exists only here. + library.settingPicker()?.opener = { context, key, filter -> + (context.sender as? BukkitCommandSender)?.native?.let { menu.pickFor(it, key, filter) } ?: false + } + } + + override fun close() { + library.settingPicker()?.opener = null + menu.close() + } fun definition(): CommandDefinition = command("pn") { // Other labels for the same command: they keep it reachable when another plugin already owns `/pn`. @@ -76,12 +91,12 @@ internal class BukkitControlCommand( executes(::overview) statusViews() updateViews() - library.mountableCommand("events")?.let { mount("events", it) } - library.mountableCommand("debug")?.let { mount("debug", it) } - library.mountableCommand("stats")?.let { mount("stats", it) } - library.mountableCommand("placeholders")?.let { mount("placeholders", it) } + for (name in MountableCommands.ALL) library.mountableCommand(name)?.let { mount(name, it) } mount("bus", EventBusCommand(library).definition()) mount("tasks", TaskCommand(library).definition()) + mount("modules", ModulesCommand(library).definition()) + mount("configs", ConfigsCommand(library).definition()) + mount("deps", DepsCommand(library).definition()) mount("servers", ServersCommand(link, ServersCommand.fromNetworkMap(link)).definition()) mount("money", CurrencyCommandExecutor(currencies, scheduler).definition()) literal("support") { @@ -158,6 +173,7 @@ internal class BukkitControlCommand( if (sender.hasPermission("pnlibrary.tasks")) add("/pn tasks") if (sender.hasPermission("pnlibrary.stats")) add("/pn stats") if (sender.hasPermission("pnlibrary.placeholders")) add("/pn placeholders") + if (sender.hasPermission("pnlibrary.settings")) add("/pn settings") if (sender.hasPermission(ServersCommand.PERMISSION)) add("/pn servers") if (sender.hasPermission("pnlibrary.debug")) add("/pn debug") add("/pn money") @@ -165,7 +181,7 @@ internal class BukkitControlCommand( replies.say(sender, ChatTone.INFO, "Команды pnLibrary, доступные вам:", available.joinToString(" ")) } - private fun productNames(): List = library.updates.all().map { it.snapshot.product } + private fun productNames(): List = library.updates.products.all().map { it.snapshot.product } internal companion object { /** Catalog routes of the `/pn` tree, shared with the join notice. */ diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitDiagnosticTestErrors.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitDiagnosticTestErrors.kt index 0132cb5e4..aec9802bf 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitDiagnosticTestErrors.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitDiagnosticTestErrors.kt @@ -13,13 +13,14 @@ internal class BukkitDiagnosticTestErrors( ) { private val logger get() = library.logging.logger(plugin, "diagnostic-test") + /** Logs one error with a fresh id, to try the diagnostics pipeline. */ fun unique(report: (String) -> Unit) { val id = UUID.randomUUID().toString().substring(0, 8) logger.error("Unique diagnostic test error [$id]", IllegalStateException("Generated unique failure [$id]")) report("Создана уникальная тестовая ошибка: $id") } - /** Emits the same failure repeatedly to exercise deduplication. */ + /** Logs the same error [requested] times (default and maximum are bounded) to try error grouping. */ fun repeated(report: (String) -> Unit, requested: Int?) { val count = requested?.coerceIn(1, MAX_REPEATS) ?: DEFAULT_REPEATS val logger = logger @@ -27,7 +28,7 @@ internal class BukkitDiagnosticTestErrors( report("Одинаковая тестовая ошибка вызвана $count раз.") } - /** Emits a nested failure to exercise cause-chain reporting. */ + /** Logs an error with a cause chain, to try how causes are shown. */ fun chained(report: (String) -> Unit) { val root = IllegalArgumentException("Invalid test database response") val database = SQLException("Test query execution failed", root) diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitRestartFlow.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitRestartFlow.kt index 8794f5c17..2fbd3820b 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitRestartFlow.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitRestartFlow.kt @@ -3,10 +3,10 @@ package org.pnfolder.pnlibrary.bukkit.commands import org.bukkit.Bukkit import org.bukkit.command.CommandSender import org.bukkit.entity.Player -import org.pnfolder.pnlibrary.api.chat.ChatTone import org.pnfolder.pnlibrary.api.chat.ConfirmChoice +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.core.updates.catalog.UpdateAction import org.pnfolder.pnlibrary.core.updates.catalog.UpdateConfirmationTokens import java.time.Duration @@ -34,7 +34,7 @@ internal class BukkitRestartFlow( if (!sender.hasPermission("pnlibrary.updates.restart")) { return replies.say(reply, ChatTone.FAILURE, "Недостаточно прав для перезапуска.") } - val plan = library.updates.currentPlan().orElse(null) + val plan = library.updates.plans.current().orElse(null) if (plan == null || plan.state != UpdateState.UPDATE_STAGED && plan.state != UpdateState.ROLLED_BACK) { return replies.say(reply, ChatTone.WARNING, "Нет подготовленных обновлений, которым нужен перезапуск.") } @@ -73,9 +73,11 @@ internal class BukkitRestartFlow( else replies.say(reply, ChatTone.WARNING, "Перезапуск не запланирован.") } + /** Whether the confirmed update plan is still the current one, so the restart acts on what was approved. */ fun isStill(grant: UpdateConfirmationTokens.Grant): Boolean = - library.updates.currentPlan().orElse(null)?.let { it.id == grant.plan && it.revision == grant.revision } == true + library.updates.plans.current().orElse(null)?.let { it.id == grant.plan && it.revision == grant.revision } == true + /** Starts the restart in [mode] after checking the permission and that [grant] still matches the plan. */ fun run(sender: CommandSender, reply: Reply, grant: UpdateConfirmationTokens.Grant, mode: ServerRestarter.Mode) { if (!sender.hasPermission("pnlibrary.updates.restart")) { return replies.say(reply, ChatTone.FAILURE, "Недостаточно прав для перезапуска.") diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitSettingFeedback.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitSettingFeedback.kt index 24381711d..100afa886 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitSettingFeedback.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitSettingFeedback.kt @@ -1,7 +1,7 @@ package org.pnfolder.pnlibrary.bukkit.commands import org.bukkit.entity.Player -import org.pnfolder.pnlibrary.bukkit.BukkitTitle +import org.pnfolder.pnlibrary.bukkit.audience.BukkitTitle import org.pnfolder.pnlibrary.bukkit.tasks.ServerScheduler import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogCommands.SettingSaved diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitSupportCommands.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitSupportCommands.kt index bb89fab20..5d3d075e3 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitSupportCommands.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitSupportCommands.kt @@ -1,7 +1,7 @@ package org.pnfolder.pnlibrary.bukkit.commands import org.bukkit.plugin.Plugin -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity import org.pnfolder.pnlibrary.api.commands.CommandSender as Reply diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitUpdateFlow.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitUpdateFlow.kt index 449a3d46c..bf70b4101 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitUpdateFlow.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitUpdateFlow.kt @@ -4,14 +4,14 @@ import org.bukkit.Bukkit import org.bukkit.command.CommandSender import org.bukkit.command.ConsoleCommandSender import org.bukkit.plugin.Plugin -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandContext import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot import org.pnfolder.pnlibrary.api.updates.UpdateRegistration -import org.pnfolder.pnlibrary.api.updates.UpdateState import org.pnfolder.pnlibrary.api.updates.release.ProductChange +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.bukkit.tasks.ServerScheduler import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import org.pnfolder.pnlibrary.core.updates.catalog.UpdateAction @@ -46,7 +46,7 @@ internal class BukkitUpdateFlow( if (!replies.ready(context.sender)) return val native = (context.sender as? BukkitCommandSender)?.native ?: return replies.say(context.sender, ChatTone.PROGRESS, "Проверяю обновления…") - library.updates.checkNow(replies.updateActor(native)).whenComplete { _, error -> + library.updates.plans.check(replies.updateActor(native)).whenComplete { _, error -> replies.onServerThread { if (error != null) replies.fail(context.sender, "Не удалось проверить обновления", error) else catalog.showAvailable(context) @@ -73,7 +73,6 @@ internal class BukkitUpdateFlow( ) } - /** Shows the confirmation card for [action] with a fresh token and the command that redeems it. */ private fun askToConfirm( native: CommandSender, reply: Reply, @@ -92,7 +91,7 @@ internal class BukkitUpdateFlow( /** The detailed console card, or the server state card styled like the catalog. */ fun sendStatus(sender: CommandSender, reply: Reply, requested: String?) { - val entries = if (requested == null) library.updates.all() else listOfNotNull(library.updates.get(requested)) + val entries = if (requested == null) library.updates.products.all() else listOfNotNull(library.updates.products.get(requested)) if (sender is ConsoleCommandSender && requested == null) { BukkitConsoleStatusRenderer.render(entries).forEach(sender::sendMessage) return @@ -107,9 +106,9 @@ internal class BukkitUpdateFlow( } fun sendUpdateStatus(reply: Reply, requested: String?) { - val plan = library.updates.currentPlan().orElse(null) + val plan = library.updates.plans.current().orElse(null) ?: return replies.say(reply, ChatTone.WARNING, "Проверка обновлений ещё не завершалась.", "Запустите её командой /pn check.") - val registrations = if (requested == null) library.updates.all() else listOfNotNull(library.updates.get(requested)) + val registrations = if (requested == null) library.updates.products.all() else listOfNotNull(library.updates.products.get(requested)) if (registrations.isEmpty()) return replies.notRegistered(reply, requested ?: "с указанным именем") replies.notices(reply, registrations.flatMap { UpdateStatusMessages.status(plan to it.snapshot) }) } @@ -121,7 +120,7 @@ internal class BukkitUpdateFlow( if (!sender.hasPermission("pnlibrary.updates.download")) { return replies.say(reply, ChatTone.FAILURE, "Недостаточно прав для загрузки обновлений.") } - val registration = library.updates.get(name) ?: return replies.notRegistered(reply, name) + val registration = library.updates.products.get(name) ?: return replies.notRegistered(reply, name) checkAndInstallUpdate(sender, reply, registration) } @@ -144,7 +143,7 @@ internal class BukkitUpdateFlow( "Проверьте доступ сервера к raw.githubusercontent.com и повторите команду.") } } - library.updates.checkNow(replies.updateActor(sender)).whenComplete { result, error -> + library.updates.plans.check(replies.updateActor(sender)).whenComplete { result, error -> if (!finished.compareAndSet(false, true)) return@whenComplete replies.onServerThread { if (error != null) replies.fail(reply, "Проверка обновления не удалась", error) @@ -153,7 +152,6 @@ internal class BukkitUpdateFlow( } } - /** Stages the requested product change or reports its current update state. */ private fun handleUpdateCheck(sender: CommandSender, reply: Reply, registration: UpdateRegistration, result: UpdatePlanSnapshot) { val change = result.plan?.changes?.firstOrNull { it.product.value.equals(registration.snapshot.product, ignoreCase = true) @@ -165,11 +163,10 @@ internal class BukkitUpdateFlow( stageUpdate(sender, reply, result, change) } - /** Downloads and validates the selected compatible update plan. */ private fun stageUpdate(sender: CommandSender, reply: Reply, plan: UpdatePlanSnapshot, change: ProductChange) { val transition = "${change.product} v${change.from} » v${change.to}" replies.say(reply, ChatTone.PROGRESS, "Найдено $transition. Скачиваю и проверяю…") - library.updates.stage(plan.id, replies.updateActor(sender)).whenComplete { _, error -> + library.updates.plans.stage(plan.id, replies.updateActor(sender)).whenComplete { _, error -> replies.onServerThread { if (error != null) replies.fail(reply, "Не удалось подготовить обновление", error) else { @@ -182,12 +179,11 @@ internal class BukkitUpdateFlow( // --- rollback, restart and the confirmation ------------------------------------------------------------------ - /** Asks to confirm a rollback of the whole current update plan. */ fun rollbackUpdate(sender: CommandSender, reply: Reply) { if (!sender.hasPermission("pnlibrary.updates.rollback")) { return replies.say(reply, ChatTone.FAILURE, "Недостаточно прав для отката обновлений.") } - val plan = library.updates.currentPlan().orElse(null) + val plan = library.updates.plans.current().orElse(null) ?: return replies.say(reply, ChatTone.WARNING, "Нет плана обновления, который можно откатить.") askToConfirm( sender, reply, plan.id, plan.revision, UpdateAction.PLAN_ROLLBACK, @@ -197,10 +193,8 @@ internal class BukkitUpdateFlow( ) } - /** Asks to confirm the restart that applies the staged plan. */ fun restartUpdate(sender: CommandSender, reply: Reply) = restart.restartUpdate(sender, reply) - /** Withdraws a restart that is counting down or waiting for the server to empty. */ fun cancelRestart(reply: Reply) = restart.cancelRestart(reply) /** Runs what [token] grants: a rollback of the plan, a rollback to a saved backup set, or the restart. */ @@ -222,7 +216,7 @@ internal class BukkitUpdateFlow( return replies.say(reply, ChatTone.FAILURE, "Недостаточно прав для отката обновлений.") } if (!restart.isStill(grant)) return replies.say(reply, ChatTone.FAILURE, "План обновления изменился; запросите откат заново.") - library.updates.rollback(replies.updateActor(sender)).whenComplete { _, error -> + library.updates.backups.rollback(replies.updateActor(sender)).whenComplete { _, error -> replies.onServerThread { if (error != null) replies.fail(reply, "Не удалось подготовить откат", error) else { @@ -237,7 +231,7 @@ internal class BukkitUpdateFlow( if (!sender.hasPermission("pnlibrary.updates.rollback")) { return replies.say(reply, ChatTone.FAILURE, "Недостаточно прав для отката обновлений.") } - library.updates.rollback(id, restoreConfigurations, replies.updateActor(sender)).whenComplete { _, error -> + library.updates.backups.rollback(id, replies.updateActor(sender), restoreConfigurations).whenComplete { _, error -> replies.onServerThread { if (error != null) replies.fail(reply, "Не удалось подготовить откат", error) else { diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/PaperCommandSupport.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/PaperCommandSupport.kt index d6d650274..da83dd3e0 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/PaperCommandSupport.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/PaperCommandSupport.kt @@ -2,37 +2,38 @@ package org.pnfolder.pnlibrary.bukkit.commands import org.bukkit.command.CommandSender import org.bukkit.plugin.Plugin +import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.api.logging.PnLogger +import org.pnfolder.pnlibrary.bukkit.PnLoggerBuffer import org.pnfolder.pnlibrary.spi.commands.NativeCommandRegistrar -/** - * Chooses how commands reach the server. On a Paper server that has the Brigadier command API and runs Java 21, - * the Paper module registers them natively, so the client validates arguments and shows hints. Everywhere else, - * and whenever anything about that fails, the classic registrar is used, so commands always work. - * - * Start the server with `-Dpnlibrary.native-commands=false` to skip the native path. Registering natively makes - * Paper turn off Bukkit's `/reload`, which some servers may prefer to keep. - */ +// -Dpnlibrary.native-commands=false skips the Paper path. +// Registering natively makes Paper disable Bukkit's /reload — servers that rely on it should use this flag. internal object PaperCommandSupport { private const val SWITCH = "pnlibrary.native-commands" private const val REGISTRAR = "org.pnfolder.pnlibrary.bukkit.paper.PaperNativeCommandRegistrar" private const val PAPER_COMMANDS = "io.papermc.paper.command.brigadier.Commands" private const val PAPER_LIFECYCLE = "io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents" - /** Returns the registrar to use: the Paper one when it can run here, otherwise [classic]. */ - fun choose(plugin: Plugin, classic: NativeCommandRegistrar): NativeCommandRegistrar { + fun choose( + plugin: Plugin, + classic: NativeCommandRegistrar, + pnLogger: () -> PnLogger, + logBuffer: PnLoggerBuffer, + ): NativeCommandRegistrar { if (System.getProperty(SWITCH)?.equals("false", ignoreCase = true) == true) return classic if (!present(PAPER_COMMANDS, plugin) || !present(PAPER_LIFECYCLE, plugin)) return classic return try { @Suppress("UNCHECKED_CAST") Class.forName(REGISTRAR, true, plugin.javaClass.classLoader) - .getConstructor(Plugin::class.java, NativeCommandRegistrar::class.java) - .newInstance(plugin, classic) as NativeCommandRegistrar + .getConstructor(Plugin::class.java, NativeCommandRegistrar::class.java, Function0::class.java) + .newInstance(plugin, classic, pnLogger) as NativeCommandRegistrar } catch (error: Exception) { - plugin.logger.info("Paper's command API is not used (${error.javaClass.simpleName}); using the classic command map") + logBuffer.log(LogLevel.INFO, "Paper's command API is not used (${error.javaClass.simpleName}); using the classic command map") classic } catch (error: LinkageError) { // Java older than 21 cannot load the Paper module, and a different Paper API can miss a class. - plugin.logger.info("Paper's command API is not used (${error.javaClass.simpleName}); using the classic command map") + logBuffer.log(LogLevel.INFO, "Paper's command API is not used (${error.javaClass.simpleName}); using the classic command map") classic } } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/ServerRestarter.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/ServerRestarter.kt index b16978a9c..37ee7bd9d 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/ServerRestarter.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/commands/ServerRestarter.kt @@ -5,7 +5,7 @@ import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer import org.bukkit.Bukkit import org.bukkit.configuration.file.YamlConfiguration import org.bukkit.plugin.Plugin -import org.pnfolder.pnlibrary.api.chat.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.bukkit.tasks.ServerScheduler import java.io.File @@ -25,8 +25,10 @@ internal class ServerRestarter(private val plugin: Plugin, private val scheduler @Volatile private var waiting: ServerScheduler.Scheduled? = null + /** What [start] set up. */ enum class Started { COUNTDOWN, WAITING_FOR_EMPTY } + /** Cancels any waiting restart, then begins the restart in the requested [mode]. */ fun start(mode: Mode): Started { cancel() return when (mode) { diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/compat/Folia.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/compat/Folia.kt index dfc56cc12..246ddb1e5 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/compat/Folia.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/compat/Folia.kt @@ -44,7 +44,6 @@ internal object Folia { entityType.getMethod("runAtFixedRate", Plugin::class.java, Consumer::class.java, Runnable::class.java, LONG, LONG) private val cancelTask = taskType.getMethod("cancel") - /** Whether the current thread owns the region of [entity]. */ fun ownsRegionOf(entity: Entity): Boolean = ownedByCurrentRegion.call(null, entity) == true fun runAsync(plugin: Plugin, task: Runnable): Any? = asyncNow.call(asyncScheduler, plugin, consumer(task)) @@ -73,7 +72,6 @@ internal object Folia { fun runOnRepeating(entity: Entity, plugin: Plugin, delayTicks: Long, periodTicks: Long, task: Runnable, retired: Runnable? = null): Any? = entityRepeating.call(scheduler(entity), plugin, consumer(task), retired, delayTicks, periodTicks) - /** Cancels a task returned by one of the `run` functions. */ fun cancel(task: Any) { cancelTask.call(task) } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/compat/ServerCapabilities.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/compat/ServerCapabilities.kt index a6679c6cd..8334f1526 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/compat/ServerCapabilities.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/compat/ServerCapabilities.kt @@ -47,7 +47,6 @@ internal object ServerCapabilities { runCatching { Bukkit.getServer().javaClass.getMethod("getTPS") }.getOrNull() } - /** Whether the server reports its TPS (Paper and its forks). */ val hasTPS: Boolean get() = tpsMethod != null /** The TPS over the last 1, 5 and 15 minutes, or `null` when the server does not report it. */ @@ -55,7 +54,7 @@ internal object ServerCapabilities { runCatching { method.invoke(Bukkit.getServer()) as? DoubleArray }.getOrNull() } - /** Returns whether [className] can be linked without initializing the class. */ + /** Whether [className] can be loaded on this server. */ fun hasClass(className: String): Boolean = try { Class.forName(className, false, javaClass.classLoader) @@ -66,7 +65,7 @@ internal object ServerCapabilities { false } - /** Returns whether [clazz] exposes a public method with the exact supplied parameter types. */ + /** Whether [clazz] declares or inherits a public method with that name and parameters. */ fun hasMethod(clazz: Class<*>, methodName: String, vararg paramTypes: Class<*>): Boolean = try { clazz.getMethod(methodName, *paramTypes) diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/BukkitCurrencyAdapters.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/BukkitCurrencyAdapters.kt index 42d95f2c0..2b590b449 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/BukkitCurrencyAdapters.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/BukkitCurrencyAdapters.kt @@ -12,7 +12,9 @@ import org.pnfolder.pnlibrary.api.currency.CurrencyRejectReason import org.pnfolder.pnlibrary.api.currency.CurrencyReset import org.pnfolder.pnlibrary.api.currency.CurrencyResult import org.pnfolder.pnlibrary.api.currency.CurrencyWithdrawals +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal +import java.lang.reflect.InvocationTargetException import java.math.BigDecimal import java.math.RoundingMode import java.util.concurrent.CompletableFuture @@ -20,21 +22,33 @@ import java.util.concurrent.CompletionStage /** Discovers optional economy plugins without linking their APIs on unsupported servers. */ internal object BukkitCurrencyAdapters { - /** Loads the registered Vault economy service, or null when unavailable. */ - fun vault(plugin: Plugin): CurrencyProvider? = runCatchingNonFatal { + fun vault(plugin: Plugin, log: PnLogger): CurrencyProvider? = runCatchingNonFatal { val type = Class.forName("net.milkbowl.vault.economy.Economy") @Suppress("UNCHECKED_CAST") val economy = plugin.server.servicesManager.load(type as Class) ?: return null - ReflectiveVaultCurrency(economy) + vaultCurrency(economy) + }.onFailure { + if (it !is ClassNotFoundException) log.error("Vault is installed but its economy could not be connected", it) }.getOrNull() - /** Resolves the enabled PlayerPoints plugin API, or null when unavailable. */ - fun playerPoints(plugin: Plugin): CurrencyProvider? = runCatchingNonFatal { + /** + * Returns `null` while the economy plugin is still starting: Essentials registers its Vault provider + * before its settings load, so the first read fails with a NullPointerException. The caller retries on + * the next plugin or service event. + */ + internal fun vaultCurrency(economy: Any): CurrencyProvider? = try { + ReflectiveVaultCurrency(economy) + } catch (failure: InvocationTargetException) { + if (failure.cause is NullPointerException) null else throw failure + } + + fun playerPoints(plugin: Plugin, log: PnLogger): CurrencyProvider? = runCatchingNonFatal { val target = plugin.server.pluginManager.getPlugin("PlayerPoints") ?: return null val api = target.javaClass.methods.firstOrNull { it.name == "getAPI" && it.parameterCount == 0 } ?.invoke(target) ?: return null ReflectivePlayerPointsCurrency(api) - }.getOrNull() + }.onFailure { log.error("PlayerPoints is installed but its currency could not be connected", it) } + .getOrNull() } /** Adapts a Vault economy provider to the portable currency contracts. */ @@ -114,14 +128,12 @@ private class ReflectivePlayerPointsCurrency(private val api: Any) : else CurrencyResult.rejected(CurrencyRejectReason.PROVIDER_REJECTED, failure) } -/** Converts numeric provider responses while rejecting non-numeric balances. */ private fun decimal(value: Any?): BigDecimal = when (value) { is BigDecimal -> value is Number -> BigDecimal(value.toString()) else -> error("Currency provider returned a non-numeric balance: $value") } -/** Exposes a synchronous provider operation as a completed or failed stage. */ private fun completed(operation: () -> T): CompletionStage = try { CompletableFuture.completedFuture(operation()) } catch (error: Throwable) { diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyChat.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyChat.kt index 046d68828..3a7c066d1 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyChat.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyChat.kt @@ -5,9 +5,9 @@ import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer import org.bukkit.ChatColor import org.pnfolder.pnlibrary.api.chat.ChatKit import org.pnfolder.pnlibrary.api.chat.ChatNotice -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.currency.Currency import org.pnfolder.pnlibrary.api.currency.CurrencyCommandSettings import org.pnfolder.pnlibrary.api.currency.CurrencyResult diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyCommandExecutor.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyCommandExecutor.kt index 6a89c7a51..e5f8afd24 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyCommandExecutor.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyCommandExecutor.kt @@ -5,11 +5,11 @@ import org.bukkit.entity.Player import org.pnfolder.pnlibrary.api.chat.ChatKit import org.pnfolder.pnlibrary.api.chat.ChatNotice import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.commands.ArgumentType +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.ArgumentType +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command import org.pnfolder.pnlibrary.api.currency.Currency import org.pnfolder.pnlibrary.api.currency.CurrencyProviderRegistry import org.pnfolder.pnlibrary.bukkit.commands.BukkitCommandSender @@ -29,7 +29,6 @@ internal class CurrencyCommandExecutor( private val confirmations = CurrencyConfirmationStore() private val operations = CurrencyOperations(currencies, confirmations, scheduler) - /** Builds the currency command tree with capability-aware permissions and suggestions. */ fun definition(): CommandDefinition = command("money") { executes(::executePortable) literal("list") { diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyConfirmationStore.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyConfirmationStore.kt index e36a60359..d310fdc27 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyConfirmationStore.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyConfirmationStore.kt @@ -5,12 +5,10 @@ import java.security.SecureRandom import java.util.concurrent.CompletionStage import java.util.concurrent.ConcurrentHashMap -/** Console-confirmation queue holding currency operations until an administrator approves them. */ internal class CurrencyConfirmationStore { private val pending = ConcurrentHashMap() private val random = SecureRandom() - /** Stores an operation and returns its confirmation code, or null when the queue is full. */ fun add( timeoutSeconds: Int, currency: String, @@ -26,7 +24,6 @@ internal class CurrencyConfirmationStore { .also { pending[token] = it } } - /** Removes and returns the operation for [token], or null when unknown. */ fun take(token: String): PendingOperation? = pending.remove(token.uppercase()) fun discardExpired() { diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyOperations.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyOperations.kt index c309b1ac3..3d9e39a76 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyOperations.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/currency/CurrencyOperations.kt @@ -5,9 +5,9 @@ import org.bukkit.command.ConsoleCommandSender import org.bukkit.entity.Player import org.pnfolder.pnlibrary.api.chat.ChatKit import org.pnfolder.pnlibrary.api.chat.ChatNotice -import org.pnfolder.pnlibrary.api.chat.ChatPalette import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatPalette +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.currency.Currency import org.pnfolder.pnlibrary.api.currency.CurrencyAccount import org.pnfolder.pnlibrary.api.currency.CurrencyActor diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitBStats.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/BukkitBStats.kt similarity index 61% rename from platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitBStats.kt rename to platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/BukkitBStats.kt index c404308bb..dd0a9bde1 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitBStats.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/BukkitBStats.kt @@ -1,17 +1,20 @@ -package org.pnfolder.pnlibrary.bukkit +package org.pnfolder.pnlibrary.bukkit.integration import org.bukkit.Bukkit import org.bukkit.plugin.Plugin +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.bukkit.compat.ServerCapabilities +import org.pnfolder.pnlibrary.bukkit.currency.error +import org.pnfolder.pnlibrary.bukkit.currency.settings +import org.pnfolder.pnlibrary.bukkit.tasks.ServerScheduler import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsClient import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsSettings import java.io.File -import java.util.logging.Level /** What bStats needs to know about a Bukkit server; the sending itself is shared by every platform. */ internal object BukkitBStats { - /** Opens the sender for [plugin], which is reported under the bStats [serviceId]. */ - fun open(plugin: Plugin, serviceId: Int): BStatsClient = BStatsClient( + /** Creates the bStats client for [plugin] with the Bukkit-specific fields and thread hand-off. */ + fun open(plugin: Plugin, serviceId: Int, pnLogger: () -> PnLogger): BStatsClient = BStatsClient( platform = "bukkit", serviceId = serviceId, settings = BStatsSettings.yaml(File(File(plugin.dataFolder.parentFile, "bStats"), "config.yml")), @@ -23,10 +26,9 @@ internal object BukkitBStats { data.appendField("bukkitName", Bukkit.getName()) }, // Folia has no single main thread to hand the task to, see https://github.com/Bastian/bstats-metrics/pull/126 - mainThread = if (ServerCapabilities.isFolia) null else { task -> Bukkit.getScheduler().runTask(plugin, task) }, + mainThread = if (ServerCapabilities.isFolia) null else ServerScheduler(plugin)::nextTick, ownerEnabled = plugin::isEnabled, - warn = { message, error -> plugin.logger.log(Level.WARNING, message, error) }, - info = { message -> plugin.logger.log(Level.INFO, message) }, + warn = { message, error -> pnLogger().warning(message, error) }, + info = { message -> pnLogger().info(message) }, ) - } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/BukkitIntegration.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/BukkitIntegration.kt new file mode 100644 index 000000000..ac7878961 --- /dev/null +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/BukkitIntegration.kt @@ -0,0 +1,13 @@ +package org.pnfolder.pnlibrary.bukkit.integration + +import org.bukkit.plugin.java.JavaPlugin +import org.pnfolder.pnlibrary.core.runtime.PnLibraryRuntimeHost + +internal class IntegrationContext(val plugin: JavaPlugin, val runtime: PnLibraryRuntimeHost) + +// connect() must be idempotent — it is called on every event that might make the integration available. +internal interface BukkitIntegration : AutoCloseable { + val pluginName: String + fun connect() + override fun close() +} diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitIntegrations.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/BukkitIntegrations.kt similarity index 81% rename from platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitIntegrations.kt rename to platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/BukkitIntegrations.kt index c91f8434d..f6b8ff55b 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitIntegrations.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/BukkitIntegrations.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.bukkit +package org.pnfolder.pnlibrary.bukkit.integration import org.bukkit.event.EventHandler import org.bukkit.event.HandlerList @@ -11,22 +11,15 @@ import org.bukkit.plugin.java.JavaPlugin import org.pnfolder.pnlibrary.bukkit.currency.BukkitCurrencyAdapters import org.pnfolder.pnlibrary.core.runtime.PnLibraryRuntimeHost -/** - * Connects optional integrations as their plugins come and go, without a server restart. - * - * Every event is cheap: [BukkitIntegration.connect] checks availability and does nothing when the - * integration is already connected. - */ internal class BukkitIntegrations(private val plugin: JavaPlugin) : Listener { private var integrations: List = emptyList() - /** Creates the integrations for [runtime] and connects those already available. */ fun start(runtime: PnLibraryRuntimeHost) { val context = IntegrationContext(plugin, runtime) integrations = listOf( PlaceholderApiIntegration(context), - CurrencyIntegration(context, "Vault", "vault", "money", BukkitCurrencyAdapters::vault), - CurrencyIntegration(context, "PlayerPoints", "playerpoints", "points", BukkitCurrencyAdapters::playerPoints), + CurrencyIntegration(context, "Vault", "vault", "money") { plugin, log -> BukkitCurrencyAdapters.vault(plugin, log) }, + CurrencyIntegration(context, "PlayerPoints", "playerpoints", "points") { plugin, log -> BukkitCurrencyAdapters.playerPoints(plugin, log) }, ) connectAll() } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitMetricsFactory.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/BukkitMetricsFactory.kt similarity index 64% rename from platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitMetricsFactory.kt rename to platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/BukkitMetricsFactory.kt index 16c51859f..4a8385172 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitMetricsFactory.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/BukkitMetricsFactory.kt @@ -1,17 +1,18 @@ -package org.pnfolder.pnlibrary.bukkit +package org.pnfolder.pnlibrary.bukkit.integration import dev.faststats.bukkit.BukkitContext import org.bukkit.plugin.Plugin -import org.pnfolder.pnlibrary.core.metrics.NativePluginMetricsFactory +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsMetricsSession +import org.pnfolder.pnlibrary.core.metrics.factory.NativePluginMetricsFactory import org.pnfolder.pnlibrary.core.metrics.faststats.SimpleFastStatsMetricsSession /** Opens independently managed bStats and FastStats sessions for Bukkit plugins. */ -internal class BukkitMetricsFactory : NativePluginMetricsFactory( +internal class BukkitMetricsFactory(private val pnLogger: () -> PnLogger) : NativePluginMetricsFactory( ownerType = Plugin::class.java, platformName = "Bukkit", bStats = { plugin, projectId -> - val client = BukkitBStats.open(plugin, projectId) + val client = BukkitBStats.open(plugin, projectId, pnLogger) BStatsMetricsSession(projectId, client::addCustomChart, client::shutdown) }, fastStats = { plugin, token -> diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/CurrencyIntegration.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/CurrencyIntegration.kt similarity index 69% rename from platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/CurrencyIntegration.kt rename to platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/CurrencyIntegration.kt index da46692a3..6e5d8cd5e 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/CurrencyIntegration.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/CurrencyIntegration.kt @@ -1,9 +1,10 @@ -package org.pnfolder.pnlibrary.bukkit +package org.pnfolder.pnlibrary.bukkit.integration import org.bukkit.plugin.Plugin import org.pnfolder.pnlibrary.api.currency.CurrencyProvider import org.pnfolder.pnlibrary.api.currency.CurrencyRegistration import org.pnfolder.pnlibrary.api.currency.currencyProviders +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal @@ -18,19 +19,24 @@ internal class CurrencyIntegration( override val pluginName: String, private val providerId: String, private val currencyName: String, - private val createProvider: (Plugin) -> CurrencyProvider?, + private val createProvider: (Plugin, PnLogger) -> CurrencyProvider?, ) : BukkitIntegration { private var registration: CurrencyRegistration? = null override fun connect() { if (registration != null || !context.plugin.server.pluginManager.isPluginEnabled(pluginName)) return - val provider = createProvider(context.plugin) ?: return + val log = context.runtime.library.logging.logger(context.plugin, pluginName) + val provider = createProvider(context.plugin, log) ?: return registration = context.runtime.library.currencyProviders.register(PluginId.of(providerId), currencyName, provider) context.runtime.library.logging.logger(context.plugin, "pnLibrary").info("$pluginName currency connected as $providerId:$currencyName") } override fun close() { - registration?.let { runCatchingNonFatal(it::close) } + registration?.let { active -> + runCatchingNonFatal(active::close).onFailure { + context.runtime.library.logging.logger(context.plugin, "pnLibrary").error("$pluginName currency did not close cleanly", it) + } + } registration = null } } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/PlaceholderApiIntegration.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/PlaceholderApiIntegration.kt similarity index 94% rename from platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/PlaceholderApiIntegration.kt rename to platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/PlaceholderApiIntegration.kt index 55dfe5292..334aae2a8 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/PlaceholderApiIntegration.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/integration/PlaceholderApiIntegration.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.bukkit +package org.pnfolder.pnlibrary.bukkit.integration import org.pnfolder.pnlibrary.bukkit.placeholders.PlaceholderApiAdapter diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/BukkitMenuSession.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/BukkitMenuSession.kt index 3153e303a..e9e340a5c 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/BukkitMenuSession.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/BukkitMenuSession.kt @@ -4,9 +4,9 @@ import org.bukkit.entity.Player import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack import org.bukkit.plugin.Plugin -import org.pnfolder.pnlibrary.api.tasks.TaskExecution import org.pnfolder.pnlibrary.api.tasks.TaskScope -import org.pnfolder.pnlibrary.api.tasks.TaskSpec +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec import java.time.Duration import java.util.UUID import java.util.concurrent.atomic.AtomicBoolean @@ -75,19 +75,16 @@ internal class BukkitMenuSession( return inventory === this.inventory && holder.id == id } - /** Stops tracking without notifying the owner. Returns `false` if the session had already ended. */ fun end(): Boolean { if (!ended.compareAndSet(false, true)) return false sessions.remove(this) return true } - /** Ends the session after the player left the menu and tells the owner. */ fun endAndNotify() { if (end() && owner.isEnabled && !sessions.isClosed) menu.closeHandler?.handle(MenuClose(this)) } - /** Ends the session without notifying the owner and closes the player's view. */ fun discard() { if (end()) execution.execute(player, ::closeViewIfShown) } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/BukkitMenus.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/BukkitMenus.kt index 715ffdfa3..c31c2949d 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/BukkitMenus.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/BukkitMenus.kt @@ -3,14 +3,17 @@ package org.pnfolder.pnlibrary.bukkit.inventory import org.bukkit.entity.Player import org.bukkit.event.HandlerList import org.bukkit.plugin.Plugin +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.api.tasks.TaskScope import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import java.util.UUID +/** Opens, tracks and closes the menus of every plugin; one instance serves the whole library. */ internal class BukkitMenus( private val host: Plugin, private val tasks: TaskScope, - private val execution: MenuExecution = NativeMenuExecution(host), + pnLogger: () -> PnLogger, + private val execution: MenuExecution = NativeMenuExecution(host, pnLogger), private val inventories: MenuInventories = NativeMenuInventories, ) : MenuService, AutoCloseable { private val sessions = MenuSessions() diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuExecution.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuExecution.kt index e58116fde..3bc32e3c3 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuExecution.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuExecution.kt @@ -2,11 +2,14 @@ package org.pnfolder.pnlibrary.bukkit.inventory import org.bukkit.entity.Player import org.bukkit.plugin.Plugin +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.bukkit.tasks.ServerScheduler /** Native inventory access must run on the player's owning thread, including bulk cleanup. */ internal interface MenuExecution { + /** Fails when the current thread may not touch [player]'s inventory. */ fun requireOwner(player: Player) + /** Runs [action] on the thread that owns [player]. */ fun execute(player: Player, action: () -> Unit) } @@ -14,7 +17,7 @@ internal interface MenuExecution { * Runs menu actions on the thread that owns the player: immediately when already there, otherwise * scheduled on the player's region (Folia) or the main thread. */ -internal class NativeMenuExecution(private val plugin: Plugin) : MenuExecution { +internal class NativeMenuExecution(private val plugin: Plugin, private val pnLogger: () -> PnLogger) : MenuExecution { private val scheduler = ServerScheduler(plugin) override fun requireOwner(player: Player) { @@ -28,7 +31,7 @@ internal class NativeMenuExecution(private val plugin: Plugin) : MenuExecution { } // A disabled plugin may not schedule anything; the server closes the views itself. if (!plugin.isEnabled) { - plugin.logger.warning("Menu tracking was cleared during shutdown; native views require server/player cleanup") + pnLogger().warning("Menu tracking was cleared during shutdown; native views require server/player cleanup") return } scheduler.onPlayer(player, Runnable(action)) diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuInventories.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuInventories.kt index c9146ddbb..cbb279826 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuInventories.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuInventories.kt @@ -6,10 +6,12 @@ import org.bukkit.inventory.Inventory import org.bukkit.inventory.InventoryHolder import java.util.UUID +/** Creates the Bukkit inventory behind a menu; replaced in tests. */ internal fun interface MenuInventories { fun create(menu: Menu, holder: InventoryHolder): Inventory } +/** Creates real server inventories. */ internal object NativeMenuInventories : MenuInventories { @Suppress("DEPRECATION") override fun create(menu: Menu, holder: InventoryHolder): Inventory = @@ -24,6 +26,7 @@ internal object NativeMenuInventories : MenuInventories { internal class MenuHolder(val id: UUID) : InventoryHolder { private var inventory: Inventory? = null + /** Remembers the inventory created for this holder. */ fun bind(inventory: Inventory) { this.inventory = inventory } @@ -38,6 +41,7 @@ internal fun Inventory.anvilRenameText(): String? = try { (method?.invoke(this) as? String)?.takeIf(String::isNotBlank) ?: getItem(2)?.itemMeta?.displayName ?: getItem(0)?.itemMeta?.displayName -} catch (_: Exception) { - null +} catch (_: ReflectiveOperationException) { + // The accessor is missing on older servers; the item name is read instead. + getItem(2)?.itemMeta?.displayName ?: getItem(0)?.itemMeta?.displayName } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuSessions.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuSessions.kt index 08a378e57..bfb3aa520 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuSessions.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/MenuSessions.kt @@ -6,7 +6,7 @@ import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal import java.util.IdentityHashMap import java.util.UUID -/** Open menus by player and by owning plugin. Regions open menus in parallel on Folia, so access is locked. */ +// Folia opens menus in parallel across regions, so all state is guarded by a lock. internal class MenuSessions { private val lock = Any() private val byPlayer = HashMap() @@ -33,7 +33,6 @@ internal class MenuSessions { if (owned.isEmpty()) byOwner.remove(session.owner) } - /** Marks the registry closed and returns the menus still open, or `null` if it was already closed. */ fun shutdown(): List? = synchronized(lock) { if (isClosed) return null isClosed = true @@ -41,7 +40,7 @@ internal class MenuSessions { } } -/** Runs every action even when some fail, then throws the first failure with the rest suppressed. */ +// Runs every action even when some fail; throws the first failure with the rest suppressed. internal fun runEach(actions: List<() -> Unit>) { val failures = actions.mapNotNull { action -> runCatchingNonFatal(action).exceptionOrNull() } val first = failures.firstOrNull() ?: return diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/CopyingCache.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/CopyingCache.kt new file mode 100644 index 000000000..41ac54539 --- /dev/null +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/CopyingCache.kt @@ -0,0 +1,17 @@ +package org.pnfolder.pnlibrary.bukkit.item + +/** A bounded, least-recently-used cache that stores and hands out copies, so a caller can never change what the cache holds. */ +internal class CopyingCache(private val capacity: Int, private val copy: (V) -> V) { + private val entries = object : LinkedHashMap(64, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry?): Boolean = size > capacity + } + + val size: Int get() = synchronized(entries) { entries.size } + + operator fun get(key: String): V? = synchronized(entries) { entries[key] }?.let(copy) + + operator fun set(key: String, value: V) { + val stored = copy(value) + synchronized(entries) { entries[key] = stored } + } +} diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/PlayerHeads.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/PlayerHeads.kt index 1c4ae306f..7d46a72cc 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/PlayerHeads.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/PlayerHeads.kt @@ -1,22 +1,23 @@ package org.pnfolder.pnlibrary.bukkit.item -import org.bukkit.Bukkit import org.bukkit.Material import org.bukkit.inventory.ItemStack import org.bukkit.inventory.meta.SkullMeta -import java.lang.reflect.Field import java.net.URI import java.net.URL import java.util.Base64 -import java.util.UUID -/** Creates player heads from a Minecraft texture hash, URL, or Base64 texture payload. */ internal object PlayerHeads { private const val TEXTURES = "https://textures.minecraft.net/texture/" + private const val FINISHED_CAPACITY = 128 private val textureUrl = Regex("https?://textures\\.minecraft\\.net/texture/[A-Za-z0-9]+") private val textureHash = Regex("[A-Fa-f0-9]{32,}") + private val modern by lazy { ModernProfileSetter.resolve(Reflection.Runtime) } + private val legacy by lazy { LegacyProfileSetter.resolve(Reflection.Runtime) } + + // Callers get clones so nobody mutates a shared cached stack. + private val finished = CopyingCache(FINISHED_CAPACITY) { it.clone() } - /** Invalid textures produce an untextured head. [displayName] accepts legacy color codes. */ @JvmStatic fun create(texture: String?, displayName: String?): ItemStack { val head = skinUrl(normalizeTexture(texture))?.let(::textured) ?: playerHead() @@ -27,19 +28,23 @@ internal object PlayerHeads { return head } - /** A head wearing the skin published under texture [hash], or `null` when this server cannot apply skins. */ fun textured(hash: String): ItemStack? = textured(URI(TEXTURES + hash).toURL()) - // 1.18.1+ has the Bukkit profile API; older servers take an authlib GameProfile in a private field. private fun textured(url: URL): ItemStack? { + val key = url.toString() + finished[key]?.let { return it } val head = playerHead() val meta = head.itemMeta as? SkullMeta ?: return null - if (!applyModernProfile(meta, url) && !applyLegacyProfile(meta, url)) return null + if (!applied(meta, url)) return null head.itemMeta = meta + finished[key] = head return head } - /** Removes an optional Base64 prefix and returns null for unsupported texture values. */ + // 1.18.1+ has the Bukkit profile API; older servers take an authlib GameProfile in a private field. + private fun applied(meta: SkullMeta, url: URL): Boolean = + modern?.let { tryProfile { it.apply(meta, url) } } == true || legacy?.let { tryProfile { it.apply(meta, url) } } == true + @JvmStatic fun normalizeTexture(input: String?): String? { var value = input?.trim()?.takeIf { it.isNotEmpty() } ?: return null @@ -59,35 +64,7 @@ internal object PlayerHeads { return ItemStack(Material.matchMaterial("SKULL_ITEM") ?: Material.STONE, 1, 3.toShort()) } - private fun applyModernProfile(meta: SkullMeta, url: URL): Boolean = tryProfile { - val id = profileId(url) - val profileType = Class.forName("org.bukkit.profile.PlayerProfile") - val texturesType = Class.forName("org.bukkit.profile.PlayerTextures") - val profile = Bukkit::class.java.getMethod("createPlayerProfile", UUID::class.java, String::class.java) - .invoke(null, id, profileName(id)) - val textures = profileType.getMethod("getTextures").invoke(profile) - texturesType.getMethod("setSkin", URL::class.java).invoke(textures, url) - profileType.getMethod("setTextures", texturesType).invoke(profile, textures) - SkullMeta::class.java.getMethod("setOwnerProfile", profileType).invoke(meta, profile) - } - - private fun applyLegacyProfile(meta: SkullMeta, url: URL): Boolean = tryProfile { - val id = profileId(url) - val profileType = Class.forName("com.mojang.authlib.GameProfile") - val profile = profileType.getConstructor(UUID::class.java, String::class.java) - .newInstance(id, profileName(id)) - val properties = profileType.getMethod("getProperties").invoke(profile) - val propertyType = Class.forName("com.mojang.authlib.properties.Property") - val payload = "{\"textures\":{\"SKIN\":{\"url\":\"$url\"}}}" - val encoded = Base64.getEncoder().encodeToString(payload.toByteArray(Charsets.UTF_8)) - val property = propertyType.getConstructor(String::class.java, String::class.java) - .newInstance("textures", encoded) - properties.javaClass.getMethod("put", Any::class.java, Any::class.java) - .invoke(properties, "textures", property) - profileField(meta.javaClass).apply { isAccessible = true }.set(meta, profile) - } - - /** Each server version supports one of the two profile APIs; a failure means "try the other one". */ + // A failure means "try the other one" — each server version supports exactly one of the two profile APIs. private inline fun tryProfile(action: () -> Unit): Boolean = try { action() true @@ -99,18 +76,6 @@ internal object PlayerHeads { false } - private fun profileField(type: Class<*>): Field { - var current: Class<*>? = type - while (current != null) { - try { - return current.getDeclaredField("profile") - } catch (_: NoSuchFieldException) { - current = current.superclass - } - } - throw NoSuchFieldException("profile") - } - private fun skinUrl(value: String?): URL? { if (value == null) return null return when { @@ -121,6 +86,4 @@ internal object PlayerHeads { } private fun decodeTexture(value: String): String = String(Base64.getDecoder().decode(value), Charsets.UTF_8) - private fun profileId(url: URL): UUID = UUID.nameUUIDFromBytes("pnLibrary:$url".toByteArray(Charsets.UTF_8)) - private fun profileName(id: UUID): String = "pn" + id.toString().replace("-", "").take(14) } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ProfileSetters.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ProfileSetters.kt new file mode 100644 index 000000000..dcad367a0 --- /dev/null +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/item/ProfileSetters.kt @@ -0,0 +1,127 @@ +package org.pnfolder.pnlibrary.bukkit.item + +import org.bukkit.Bukkit +import org.bukkit.inventory.meta.SkullMeta +import java.lang.reflect.Constructor +import java.lang.reflect.Field +import java.lang.reflect.Method +import java.net.URL +import java.util.Base64 +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap + +/** Looks up classes and methods by name; a seam so tests can count the lookups. */ +internal interface Reflection { + fun type(name: String): Class<*> + + fun method(type: Class<*>, name: String, vararg parameters: Class<*>): Method + + object Runtime : Reflection { + override fun type(name: String): Class<*> = Class.forName(name) + + override fun method(type: Class<*>, name: String, vararg parameters: Class<*>): Method = type.getMethod(name, *parameters) + } +} + +/** Puts a skin from a texture URL on a skull; each server version supports one of the two implementations. */ +internal interface ProfileSetter { + fun apply(meta: SkullMeta, url: URL) +} + +/** Profile ids and names derived from the texture URL, so one texture always gives the same profile. */ +private object ProfileNames { + fun id(url: URL): UUID = UUID.nameUUIDFromBytes("pnLibrary:$url".toByteArray(Charsets.UTF_8)) + + fun name(id: UUID): String = "pn" + id.toString().replace("-", "").take(14) +} + +/** Bukkit profile API (1.18.1+). Every class and method is looked up once, when the setter is made. */ +internal class ModernProfileSetter private constructor( + private val createProfile: Method, + private val getTextures: Method, + private val setSkin: Method, + private val setTextures: Method, + private val setOwnerProfile: Method, +) : ProfileSetter { + override fun apply(meta: SkullMeta, url: URL) { + val id = ProfileNames.id(url) + val profile = createProfile.invoke(null, id, ProfileNames.name(id)) + val textures = getTextures.invoke(profile) + setSkin.invoke(textures, url) + setTextures.invoke(profile, textures) + setOwnerProfile.invoke(meta, profile) + } + + companion object { + /** The setter, or null when this server has no profile API. */ + fun resolve( + reflection: Reflection, + bukkit: Class<*> = Bukkit::class.java, + skull: Class<*> = SkullMeta::class.java, + ): ModernProfileSetter? = try { + val profileType = reflection.type("org.bukkit.profile.PlayerProfile") + val texturesType = reflection.type("org.bukkit.profile.PlayerTextures") + ModernProfileSetter( + reflection.method(bukkit, "createPlayerProfile", UUID::class.java, String::class.java), + reflection.method(profileType, "getTextures"), + reflection.method(texturesType, "setSkin", URL::class.java), + reflection.method(profileType, "setTextures", texturesType), + reflection.method(skull, "setOwnerProfile", profileType), + ) + } catch (_: ReflectiveOperationException) { + null + } catch (_: LinkageError) { + null + } + } +} + +/** Older servers: an authlib GameProfile written into the private `profile` field of the skull. */ +internal class LegacyProfileSetter private constructor( + private val newProfile: Constructor<*>, + private val getProperties: Method, + private val putProperty: Method, + private val newProperty: Constructor<*>, +) : ProfileSetter { + private val fields = ConcurrentHashMap, Field>() + + override fun apply(meta: SkullMeta, url: URL) { + val id = ProfileNames.id(url) + val profile = newProfile.newInstance(id, ProfileNames.name(id)) + val payload = "{\"textures\":{\"SKIN\":{\"url\":\"$url\"}}}" + val encoded = Base64.getEncoder().encodeToString(payload.toByteArray(Charsets.UTF_8)) + putProperty.invoke(getProperties.invoke(profile), "textures", newProperty.newInstance("textures", encoded)) + fields.computeIfAbsent(meta.javaClass, ::profileField).set(meta, profile) + } + + private fun profileField(type: Class<*>): Field { + var current: Class<*>? = type + while (current != null) { + try { + return current.getDeclaredField("profile").apply { isAccessible = true } + } catch (_: NoSuchFieldException) { + current = current.superclass + } + } + throw NoSuchFieldException("profile") + } + + companion object { + /** The setter, or null when this server has no authlib. */ + fun resolve(reflection: Reflection): LegacyProfileSetter? = try { + val profileType = reflection.type("com.mojang.authlib.GameProfile") + val propertyType = reflection.type("com.mojang.authlib.properties.Property") + val getProperties = reflection.method(profileType, "getProperties") + LegacyProfileSetter( + profileType.getConstructor(UUID::class.java, String::class.java), + getProperties, + reflection.method(getProperties.returnType, "put", Any::class.java, Any::class.java), + propertyType.getConstructor(String::class.java, String::class.java), + ) + } catch (_: ReflectiveOperationException) { + null + } catch (_: LinkageError) { + null + } + } +} diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/BukkitMenuAdapter.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/BukkitMenuAdapter.kt index 721ceab68..683d21b30 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/BukkitMenuAdapter.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/BukkitMenuAdapter.kt @@ -9,14 +9,15 @@ import org.bukkit.plugin.Plugin import org.pnfolder.pnlibrary.api.chat.ChatKit import org.pnfolder.pnlibrary.api.chat.ChatNotice import org.pnfolder.pnlibrary.api.chat.ChatReader -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.platform.platform import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.api.tasks.TaskSpec -import org.pnfolder.pnlibrary.api.updates.UpdateActor +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec +import org.pnfolder.pnlibrary.api.updates.state.UpdateActor import org.pnfolder.pnlibrary.bukkit.api.BukkitPlatform import org.pnfolder.pnlibrary.bukkit.inventory.MenuSession +import org.pnfolder.pnlibrary.bukkit.item.PlayerHeads import org.pnfolder.pnlibrary.bukkit.tasks.ServerScheduler import org.pnfolder.pnlibrary.core.lifecycle.runtimeTaskScope import org.pnfolder.pnlibrary.core.menu.ClickType @@ -25,6 +26,7 @@ import org.pnfolder.pnlibrary.core.menu.Menu import org.pnfolder.pnlibrary.core.menu.MenuViewer import java.time.Duration import java.util.UUID +import java.util.concurrent.ConcurrentHashMap import org.pnfolder.pnlibrary.bukkit.inventory.Menus as BukkitMenus /** Turns the portable menu into Bukkit inventories. */ @@ -40,7 +42,7 @@ internal class BukkitMenuAdapter( fun stack(spec: ItemSpec): ItemStack { val name = HexColors.downgrade(spec.name) val lore = spec.lore.map(HexColors::downgrade) - val head = spec.texture?.let { MenuHeads.head(it) } + val head = spec.texture?.let(::head) val base = head ?: ItemStack(listOfNotNull(spec.material, spec.alternative).firstNotNullOfOrNull(::resolve) ?: Material.PAPER) if (head == null && spec.legacyData != 0.toShort() && base.type.name in LEGACY_GLASS) base.durability = spec.legacyData return base.also { @@ -53,6 +55,12 @@ internal class BukkitMenuAdapter( } } + /** + * A copy of the textured player head for [hash], built once per texture and cached after that. + * A head the server cannot make is `null`, and the caller shows an ordinary item instead. + */ + private fun head(hash: String): ItemStack? = HEADS[hash]?.clone() ?: PlayerHeads.textured(hash)?.also { HEADS[hash] = it.clone() } + /** The inventory page for [menu]; a click goes to its handler as a click by the local player. */ fun page(menu: Menu): org.pnfolder.pnlibrary.bukkit.inventory.Menu { val builder = BukkitMenus.chest(menu.title).rows(menu.rows) @@ -146,6 +154,7 @@ internal class BukkitMenuAdapter( fun playerOf(viewer: MenuViewer): Player? = (viewer as? BukkitViewer)?.native private companion object { + val HEADS = ConcurrentHashMap() /** Any of these opens `/pn gui`; losing all of them closes the menu. */ val MENU_ACCESS = listOf("pnlibrary.admin", "pnlibrary.updates.view") val RECHECK: Duration = Duration.ofSeconds(2) diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/BukkitMenuHost.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/BukkitMenuHost.kt index 4110cfc53..55546adde 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/BukkitMenuHost.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/BukkitMenuHost.kt @@ -9,7 +9,7 @@ import org.pnfolder.pnlibrary.core.menu.LibraryMenu import org.pnfolder.pnlibrary.core.menu.MenuHost import org.pnfolder.pnlibrary.core.menu.MenuViewer import org.pnfolder.pnlibrary.core.menu.OwnerInfo -import org.pnfolder.pnlibrary.core.menu.RemoteMenuData +import org.pnfolder.pnlibrary.core.menu.data.RemoteMenuData import java.util.concurrent.ConcurrentHashMap /** What the portable menu needs from a Bukkit server. */ diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/MenuHeads.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/MenuHeads.kt deleted file mode 100644 index dd045b7a1..000000000 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/MenuHeads.kt +++ /dev/null @@ -1,15 +0,0 @@ -package org.pnfolder.pnlibrary.bukkit.menu - -import org.bukkit.inventory.ItemStack -import org.pnfolder.pnlibrary.bukkit.item.PlayerHeads -import java.util.concurrent.ConcurrentHashMap - -/** - * Textured heads for the library menu, built once per texture and copied after that. - * A head the server cannot make is `null`, and the caller shows an ordinary item instead. - */ -internal object MenuHeads { - private val cache = ConcurrentHashMap() - - fun head(hash: String): ItemStack? = cache[hash]?.clone() ?: PlayerHeads.textured(hash)?.also { cache[hash] = it.clone() } -} diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/PluginsMenu.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/PluginsMenu.kt index 55ae55e58..5b538f6cc 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/PluginsMenu.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/PluginsMenu.kt @@ -1,16 +1,17 @@ package org.pnfolder.pnlibrary.bukkit.menu +import org.bukkit.Bukkit import org.bukkit.entity.Player import org.bukkit.plugin.Plugin -import org.pnfolder.pnlibrary.api.chat.ChatTone +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.bukkit.commands.BukkitCommandReplies import org.pnfolder.pnlibrary.bukkit.tasks.ServerScheduler import org.pnfolder.pnlibrary.core.link.Link import org.pnfolder.pnlibrary.core.menu.LibraryMenu -import org.pnfolder.pnlibrary.core.menu.LocalMenuData -import org.pnfolder.pnlibrary.core.menu.MenuDataServer import org.pnfolder.pnlibrary.core.menu.MenuViewer +import org.pnfolder.pnlibrary.core.menu.data.LocalMenuData +import org.pnfolder.pnlibrary.core.menu.data.MenuDataServer import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import org.bukkit.command.CommandSender as NativeSender @@ -40,7 +41,7 @@ internal class PluginsMenu( if (link.enabled) { val executor = Executors.newCachedThreadPool { task -> Thread(task, "pnlibrary-menu-data").apply { isDaemon = true } } menuData = executor - link.answerCallsWith(MenuDataServer(data, executor)) + link.answerCallsWith(MenuDataServer(data, executor) { viewer, permission -> Bukkit.getPlayerExact(viewer)?.hasPermission(permission) == true }) } } @@ -55,5 +56,12 @@ internal class PluginsMenu( else replies.say(reply, ChatTone.INFO, "Меню доступно только игроку.", "В консоли используйте /pn updates.") } + /** Opens the values of the choice setting [key] for [sender], narrowed to [filter]; `false` when [sender] is not a player. */ + fun pickFor(sender: NativeSender, key: String, filter: String): Boolean { + val player = sender as? Player ?: return false + menu.pickSetting(adapter.viewer(player), key, filter) + return true + } + fun home(viewer: MenuViewer) = menu.home(viewer) } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/RemoteMenus.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/RemoteMenus.kt index 5ed35f968..e1e38bf7e 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/RemoteMenus.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/menu/RemoteMenus.kt @@ -6,7 +6,7 @@ import org.bukkit.command.CommandSender import org.bukkit.command.ConsoleCommandSender import org.pnfolder.pnlibrary.bukkit.tasks.ServerScheduler import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.menu.ViewerInfo +import org.pnfolder.pnlibrary.core.menu.data.ViewerInfo import java.lang.reflect.Proxy import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PlaceholderApiAdapter.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PlaceholderApiAdapter.kt index 5de2ad9d7..1c9ae94c7 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PlaceholderApiAdapter.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PlaceholderApiAdapter.kt @@ -4,13 +4,12 @@ import me.clip.placeholderapi.PlaceholderAPI import me.clip.placeholderapi.expansion.PlaceholderExpansion import org.bukkit.OfflinePlayer import org.bukkit.plugin.Plugin -import org.pnfolder.pnlibrary.api.placeholders.ExternalPlaceholderRegistration -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapter -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterCapabilities -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderAdapterState -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderPublication -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderRequest -import org.pnfolder.pnlibrary.api.placeholders.PlaceholderResolver +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapter +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapterCapabilities +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapterState +import org.pnfolder.pnlibrary.api.placeholders.model.ExternalPlaceholderRegistration +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderPublication +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderResolver import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity import java.util.Locale @@ -61,11 +60,11 @@ internal class PlaceholderApiAdapter( val namespace = (publication.namespace ?: owner.value).lowercase(Locale.ROOT) val externalName = (publication.name ?: key.replace('.', '_')).lowercase(Locale.ROOT) require('_' !in namespace) { "PlaceholderAPI prefix '$namespace' must not contain '_'" } - val expansion = groups.computeIfAbsent(namespace) { Expansion(it) } + val expansion = groups.computeIfAbsent(namespace) { Expansion(it, PlaceholderApiRequests(plugin.server::isPrimaryThread)) } if (!expansion.isRegistered) { check(expansion.register()) } - require(expansion.handlers.putIfAbsent(externalName, Handler(owner, resolver)) == null) { + require(expansion.requests.handlers.add(externalName, PublishedHandler(owner, resolver))) { "Placeholder %${namespace}_${externalName}% is already published" } return object : ExternalPlaceholderRegistration { @@ -73,8 +72,8 @@ internal class PlaceholderApiAdapter( override val state: PlaceholderAdapterState get() = if (active.get()) PlaceholderAdapterState.REGISTERED else PlaceholderAdapterState.CLOSED override fun close() { if (!active.compareAndSet(true, false)) return - expansion.handlers.remove(externalName) - if (expansion.handlers.isEmpty()) { + expansion.requests.handlers.remove(externalName) + if (expansion.requests.handlers.isEmpty) { expansion.unregister() groups.remove(namespace, expansion) } @@ -91,30 +90,17 @@ internal class PlaceholderApiAdapter( /** Groups published resolvers under one PlaceholderAPI namespace. */ private inner class Expansion( private val namespace: String, + val requests: PlaceholderApiRequests, ) : PlaceholderExpansion() { - val handlers = ConcurrentHashMap() override fun getIdentifier() = namespace override fun getAuthor() = this@PlaceholderApiAdapter.plugin.description.authors.joinToString(",").ifBlank { PnLibraryIdentity.NAME } override fun getVersion() = this@PlaceholderApiAdapter.plugin.description.version override fun persist() = true - /** Finds the published name that fits [params] best and hands its parameters to the resolver. */ - override fun onRequest(player: OfflinePlayer?, params: String): String? { - val wait = if (this@PlaceholderApiAdapter.plugin.server.isPrimaryThread) MAIN_THREAD_WAIT_MILLIS else OTHER_THREAD_WAIT_MILLIS - val values = mapOf(PlaceholderAdapter.WAIT_MILLIS_KEY to wait) - val (handler, parameters) = PublishedNames.find(handlers, params) ?: return null - return answer(handler, PlaceholderRequest(handler.owner, handler.owner, player?.uniqueId, parameters, values)) - } - - private fun answer(handler: Handler, request: PlaceholderRequest): String? = - handler.resolver.resolve(request)?.toString() + override fun onRequest(player: OfflinePlayer?, params: String): String? = requests.answer(player?.uniqueId, params) } - /** Associates a published resolver with its portable owner. */ - private data class Handler( - val owner: PluginId, - val resolver: PlaceholderResolver, - ) } -private const val MAIN_THREAD_WAIT_MILLIS = 50L -private const val OTHER_THREAD_WAIT_MILLIS = 1000L +/** The server thread never waits: a late value is answered from the last known one and warmed up for the next ask. */ +internal const val MAIN_THREAD_WAIT_MILLIS = 0L +internal const val OTHER_THREAD_WAIT_MILLIS = 1000L diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PlaceholderApiRequests.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PlaceholderApiRequests.kt new file mode 100644 index 000000000..d09929254 --- /dev/null +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PlaceholderApiRequests.kt @@ -0,0 +1,23 @@ +package org.pnfolder.pnlibrary.bukkit.placeholders + +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapter +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderResolver +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.util.UUID + +/** Associates a published resolver with its portable owner. */ +internal data class PublishedHandler(val owner: PluginId, val resolver: PlaceholderResolver) + +/** Answers PlaceholderAPI's `onRequest` for one prefix from the names published under it. */ +internal class PlaceholderApiRequests(private val onPrimaryThread: () -> Boolean) { + val handlers = PublishedNames() + + /** Finds the published name that fits [params] best and hands its parameters to the resolver; the server thread is told not to wait. */ + fun answer(playerId: UUID?, params: String): String? { + val (handler, parameters) = handlers.find(params) ?: return null + val wait = if (onPrimaryThread()) MAIN_THREAD_WAIT_MILLIS else OTHER_THREAD_WAIT_MILLIS + val values = mapOf(PlaceholderAdapter.WAIT_MILLIS_KEY to wait) + return handler.resolver.resolve(PlaceholderRequest(handler.owner, handler.owner, playerId, parameters, values))?.toString() + } +} diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PublishedNames.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PublishedNames.kt index ca6ceeb8a..09df99584 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PublishedNames.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PublishedNames.kt @@ -1,21 +1,82 @@ package org.pnfolder.pnlibrary.bukkit.placeholders -/** Finds which published name PlaceholderAPI's text (`war~score.Alex`, `tag_x`) belongs to. */ -internal object PublishedNames { +import java.util.Locale +import java.util.concurrent.atomic.AtomicLong + +/** + * The names published to PlaceholderAPI under one prefix, and the lookup of which one PlaceholderAPI's text + * (`war~score.Alex`, `tag_x`) belongs to. Lookups read an immutable snapshot, so they never wait for a publication. + */ +internal class PublishedNames { /** A found name with the values of its brace parts. */ data class Found(val handler: H, val parameters: Map) - /** The name that equals [params], then the most specific pattern that fits, otherwise the longest plain name that [params] equals or continues after `_`. */ - fun find(handlers: Map, params: String): Found? { - handlers.entries.firstOrNull { '{' !in it.key && params.equals(it.key, true) }?.let { return Found(it.value, emptyMap()) } - val byPattern = handlers.entries - .mapNotNull { (name, handler) -> ExternalNames.match(name, params)?.let { Triple(name, handler, it) } } - .maxByOrNull { (name, _, _) -> ExternalNames.specificity(name) } - if (byPattern != null) return Found(byPattern.second, byPattern.third) - val match = handlers.entries.sortedByDescending { it.key.length }.firstOrNull { - '{' !in it.key && (params.equals(it.key, true) || params.startsWith(it.key + "_", true)) - } ?: return null - val suffix = params.removePrefix(match.key).removePrefix("_") - return Found(match.value, if (suffix.isEmpty()) emptyMap() else mapOf("value" to suffix)) + private class Snapshot(val names: Map) { + /** Plain names by lowercase text for the direct hit. */ + val exact: Map = names.filterKeys { '{' !in it }.mapKeys { it.key.lowercase(Locale.ROOT) } + val patterns: List> = names.filterKeys { '{' in it }.toList() + val specificity: Map = patterns.associate { (name, _) -> name to ExternalNames.specificity(name) } + + /** Longest plain name first, for the "name, underscore, rest" form. */ + val byLength: List> = names.filterKeys { '{' !in it }.toList().sortedByDescending { it.first.length } + } + + private val scannedCounter = AtomicLong() + + @Volatile + private var snapshot = Snapshot(emptyMap()) + + /** How many names were tried one by one since start; a direct hit tries none. */ + val scanned: Long get() = scannedCounter.get() + + val isEmpty: Boolean get() = snapshot.names.isEmpty() + + /** Publishes [handler] under [name]; `false` when the name is taken. */ + @Synchronized + fun add(name: String, handler: H): Boolean { + if (name in snapshot.names) return false + snapshot = Snapshot(snapshot.names + (name to handler)) + return true + } + + /** Withdraws [name]. */ + @Synchronized + fun remove(name: String) { + if (name in snapshot.names) snapshot = Snapshot(snapshot.names - name) + } + + /** + * The name that equals [params], then the most specific pattern that fits, otherwise the longest plain name + * that [params] equals or continues after `_`. + */ + fun find(params: String): Found? { + val current = snapshot + current.exact[params.lowercase(Locale.ROOT)]?.let { return Found(it, emptyMap()) } + return byPattern(current, params) ?: byPrefix(current, params) + } + + private fun byPattern(current: Snapshot, params: String): Found? { + var best: Found? = null + var bestSpecificity = -1 + for ((name, handler) in current.patterns) { + scannedCounter.incrementAndGet() + val parameters = ExternalNames.match(name, params) ?: continue + val specificity = current.specificity.getValue(name) + if (specificity > bestSpecificity) { + best = Found(handler, parameters) + bestSpecificity = specificity + } + } + return best + } + + private fun byPrefix(current: Snapshot, params: String): Found? { + for ((name, handler) in current.byLength) { + scannedCounter.incrementAndGet() + if (!params.equals(name, true) && !params.startsWith(name + "_", true)) continue + val suffix = params.removePrefix(name).removePrefix("_") + return Found(handler, if (suffix.isEmpty()) emptyMap() else mapOf("value" to suffix)) + } + return null } } diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/BukkitTaskAdapter.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/BukkitTaskAdapter.kt index 406c7496e..8731fef7e 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/BukkitTaskAdapter.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/BukkitTaskAdapter.kt @@ -4,7 +4,7 @@ import org.bukkit.Bukkit import org.bukkit.plugin.Plugin import org.bukkit.scheduler.BukkitScheduler import org.bukkit.scheduler.BukkitTask -import org.pnfolder.pnlibrary.api.tasks.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import org.pnfolder.pnlibrary.bukkit.compat.ServerCapabilities import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskHandle import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest @@ -18,12 +18,6 @@ private const val NANOS_PER_TICK = 50_000_000.0 internal fun durationToTicks(value: Duration): Long = if (value.isZero) 0 else ceil(value.toNanos() / NANOS_PER_TICK).toLong().coerceAtLeast(1) -/** - * Owns scheduled tasks and adapts requests to Bukkit or Folia. - * - * Ordinary Bukkit executes entity and global tasks on the primary thread. Folia dispatches - * entity tasks to their player scheduler and global tasks to the global-region scheduler. - */ internal class BukkitTaskAdapter( private val plugin: Plugin, ) : TrackingPlatformTaskAdapter() { @@ -34,7 +28,6 @@ internal class BukkitTaskAdapter( return NativeHandle(native) } - /** Routes ordinary Bukkit requests to asynchronous or primary-thread scheduling. */ private fun scheduleBukkit(request: PlatformTaskRequest): Any { val scheduler = Bukkit.getScheduler() val delay = durationToTicks(request.delay) diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/FoliaSchedulerBridge.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/FoliaSchedulerBridge.kt index 6c771366a..3a65ab144 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/FoliaSchedulerBridge.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/FoliaSchedulerBridge.kt @@ -2,19 +2,14 @@ package org.pnfolder.pnlibrary.bukkit.tasks import org.bukkit.entity.Player import org.bukkit.plugin.Plugin -import org.pnfolder.pnlibrary.api.tasks.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import org.pnfolder.pnlibrary.bukkit.commands.BukkitCommandSender import org.pnfolder.pnlibrary.bukkit.compat.Folia import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest import org.pnfolder.pnlibrary.spi.tasks.RetirableCallback import java.time.Duration -/** - * Puts a portable task on the Folia scheduler that matches its execution: asynchronous, a player's region or global. - * - * Region schedulers count from one tick: they refuse a delay or period of zero for delayed and repeating work, so - * both are raised to one tick there. - */ +// Region schedulers refuse delay/period of zero for repeating work — both are raised to one tick (see ticks()). internal class FoliaSchedulerBridge(private val plugin: Plugin) { fun schedule(request: PlatformTaskRequest): Any { diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/ServerScheduler.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/ServerScheduler.kt index e80dd7792..cfbd972ef 100644 --- a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/ServerScheduler.kt +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/ServerScheduler.kt @@ -16,6 +16,7 @@ import org.pnfolder.pnlibrary.bukkit.compat.ServerCapabilities internal class ServerScheduler(private val plugin: Plugin) { /** Work that is waiting and can still be withdrawn. */ fun interface Scheduled { + /** Withdraws the work if it has not run yet. */ fun cancel() } @@ -29,12 +30,13 @@ internal class ServerScheduler(private val plugin: Plugin) { if (ServerCapabilities.isFolia) Folia.runGlobal(plugin, task) else Bukkit.getScheduler().runTask(plugin, task) } - // Folia refuses a delay of zero ticks for delayed and repeating work. + /** Runs [task] once after [delayTicks]. Folia refuses a delay of zero ticks, so it is raised to one. */ fun later(delayTicks: Long, task: Runnable): Scheduled { if (!ServerCapabilities.isFolia) return Scheduled(Bukkit.getScheduler().runTaskLater(plugin, task, delayTicks)::cancel) return foliaTask(Folia.runGlobalLater(plugin, delayTicks.coerceAtLeast(1), task)) } + /** Runs [task] every [periodTicks] after [delayTicks]; on Folia both are raised to at least one tick. */ fun repeat(delayTicks: Long, periodTicks: Long, task: Runnable): Scheduled { if (!ServerCapabilities.isFolia) return Scheduled(Bukkit.getScheduler().runTaskTimer(plugin, task, delayTicks, periodTicks)::cancel) return foliaTask(Folia.runGlobalRepeating(plugin, delayTicks.coerceAtLeast(1), periodTicks.coerceAtLeast(1), task)) diff --git a/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/updates/UpdateReminders.kt b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/updates/UpdateReminders.kt new file mode 100644 index 000000000..134014b10 --- /dev/null +++ b/platforms/bukkit/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bukkit/updates/UpdateReminders.kt @@ -0,0 +1,81 @@ +package org.pnfolder.pnlibrary.bukkit.updates + +import org.bukkit.entity.Player +import org.bukkit.plugin.Plugin +import org.pnfolder.pnlibrary.api.runtime.PnLibrary +import org.pnfolder.pnlibrary.api.runtime.PnLibraryIdentity +import org.pnfolder.pnlibrary.api.tasks.TaskHandle +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec +import org.pnfolder.pnlibrary.api.updates.state.UpdateState +import org.pnfolder.pnlibrary.bukkit.audience.BukkitTitle +import org.pnfolder.pnlibrary.bukkit.commands.BukkitControlCommand +import org.pnfolder.pnlibrary.core.lifecycle.runtimeTaskScope +import org.pnfolder.pnlibrary.core.updates.catalog.UpdateCatalogView +import org.pnfolder.pnlibrary.updates.policy.UpdateDefaults +import java.time.Duration + +/** + * Tells administrators in chat about updates: once when they join and again every [UpdateDefaults.REMINDER_INTERVAL] + * while an update is available or waits for a restart. It reads the state the library already knows, so it never + * asks GitHub, and it stops by itself when the release is gone. Neither the reminder nor its interval can be turned + * off by an administrator. + */ +internal class UpdateReminders( + private val plugin: Plugin, + private val library: () -> PnLibrary?, +) : AutoCloseable { + private var timer: TaskHandle? = null + + /** Begins the periodic reminder for administrators. */ + fun start(): UpdateReminders = apply { + val active = library() ?: return@apply + timer = active.runtimeTaskScope().schedule( + TaskSpec.builder() + .name("update reminders") + .description("Напоминание администраторам об обновлениях.") + .cancellable(false) + .runnableNow(false) + .execution(TaskExecution.global()) + .delay(UpdateDefaults.REMINDER_INTERVAL) + .interval(UpdateDefaults.REMINDER_INTERVAL) + .action { plugin.server.onlinePlayers.filter(::canSeeUpdates).forEach { remind(it, withTitle = false) } } + .build(), + ) + } + + /** Whether [player] is an operator or holds a permission that allows update notices. */ + fun canSeeUpdates(player: Player): Boolean = player.isOp || player.hasPermission("*") || + player.hasPermission("pnlibrary.admin") || player.hasPermission("pnlibrary.updates.notify") + + /** Sends the update notice to [player] on the player's own thread; a title is shown only on join. */ + fun remind(player: Player, withTitle: Boolean) { + val active = library() ?: return + active.runtimeTaskScope().schedule( + TaskSpec.builder() + .execution(TaskExecution.entity(player)) + .delay(Duration.ofMillis(50)) + .action { send(active, player, withTitle) } + .build(), + ) + } + + private fun send(active: PnLibrary, player: Player, withTitle: Boolean) { + if (!player.isOnline) return + val audience = active.audiences.player(player.uniqueId) ?: return + val snapshots = active.updates.products.all().map { it.snapshot } + val notice = UpdateCatalogView.announcement(snapshots, BukkitControlCommand.ROUTES, PnLibraryIdentity.SUPPORT_URL) + if (notice.isEmpty()) return + notice.forEach(audience::sendMessage) + if (!withTitle) return + val pending = snapshots.count { it.state == UpdateState.UPDATE_AVAILABLE || it.state == UpdateState.UPDATE_STAGED } + val (title, subtitle) = BukkitTitle.updatesPending(pending) + @Suppress("DEPRECATION") + player.sendTitle(title, subtitle) + } + + override fun close() { + timer?.cancel() + timer = null + } +} diff --git a/platforms/bukkit/runtime/src/main/resources/plugin.yml b/platforms/bukkit/runtime/src/main/resources/plugin.yml index 2661128b6..cd1c71202 100644 --- a/platforms/bukkit/runtime/src/main/resources/plugin.yml +++ b/platforms/bukkit/runtime/src/main/resources/plugin.yml @@ -27,12 +27,30 @@ permissions: pnlibrary.tasks: description: 'Смотреть задачи плагинов (/pn tasks) и отменять их' default: op + pnlibrary.deps: + description: 'Недостающие плагины: список, установка по коду, автозагрузка (/pn deps)' + default: op + pnlibrary.settings: + description: 'Настройки библиотеки: смотреть и менять (/pn settings, раздел меню «Параметры библиотеки»)' + default: op pnlibrary.placeholders: description: 'Смотреть и проверять плейсхолдеры (/pn placeholders)' default: op pnlibrary.stats: description: 'Смотреть сводную статистику библиотеки (/pn stats)' default: op + pnlibrary.configs: + description: 'Смотреть конфигурации плагинов и перечитывать их (/pn configs)' + default: op + pnlibrary.configs.edit: + description: 'Менять настройки конфигураций плагинов в игре (/pn configs edit)' + default: op + pnlibrary.servers: + description: 'Серверы сети и удалённые действия обновлений (/pn servers)' + default: op + pnlibrary.currency.list: + description: 'Список валют (/pn money list)' + default: op pnlibrary.updates.view: description: Просматривать совместимый план обновлений default: op diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/PlayerCommandReplyTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/PlayerCommandReplyTest.kt index 097fb170c..88915af5e 100644 --- a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/PlayerCommandReplyTest.kt +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/PlayerCommandReplyTest.kt @@ -15,12 +15,16 @@ import org.pnfolder.pnlibrary.api.commands.CommandContext import org.pnfolder.pnlibrary.api.currency.CurrencyProviderRegistry import org.pnfolder.pnlibrary.api.runtime.PnLibrary import org.pnfolder.pnlibrary.api.updates.UpdateService +import org.pnfolder.pnlibrary.bukkit.audience.BukkitAudienceAdapter +import org.pnfolder.pnlibrary.bukkit.audience.BukkitAudienceService import org.pnfolder.pnlibrary.bukkit.commands.BukkitCommandSender import org.pnfolder.pnlibrary.bukkit.commands.BukkitControlCommand import java.util.UUID import java.util.logging.Logger class PlayerCommandReplyTest { + private fun buffer() = PnLoggerBuffer(Logger.getAnonymousLogger()) { null } + private fun plugin(): Plugin = mock(Plugin::class.java).also { `when`(it.logger).thenReturn(Logger.getAnonymousLogger()) `when`(it.server).thenReturn(mock(Server::class.java)) @@ -30,7 +34,7 @@ class PlayerCommandReplyTest { fun `Paper command reply targets the actual player and preserves click events`() { val player = mock(Player::class.java, withSettings().extraInterfaces(Audience::class.java)) val provider = mock(BukkitAudiences::class.java) - val service = BukkitAudienceService(plugin(), provider) + val service = BukkitAudienceService(plugin(), buffer(), provider) val message = Component.text("[История]").clickEvent(ClickEvent.runCommand("/pn updates history")) try { service.player(player).sendMessage(message) @@ -47,7 +51,7 @@ class PlayerCommandReplyTest { `when`(player.uniqueId).thenReturn(id) val provider = mock(BukkitAudiences::class.java) `when`(provider.player(id)).thenReturn(Audience.empty()) - val service = BukkitAudienceService(plugin(), provider) + val service = BukkitAudienceService(plugin(), buffer(), provider) try { service.player(player).sendMessage(Component.text("Каталог pnLibrary")) verify(player).sendMessage("Каталог pnLibrary") @@ -59,11 +63,13 @@ class PlayerCommandReplyTest { val plugin = plugin() val player = mock(Player::class.java, withSettings().extraInterfaces(Audience::class.java)) val provider = mock(BukkitAudiences::class.java) - val service = BukkitAudienceService(plugin, provider) + val service = BukkitAudienceService(plugin, buffer(), provider) val library = mock(PnLibrary::class.java) val updates = mock(UpdateService::class.java) `when`(library.updates).thenReturn(updates) - `when`(updates.all()).thenReturn(emptyList()) + val products = mock(org.pnfolder.pnlibrary.api.updates.UpdateProducts::class.java) + `when`(updates.products).thenReturn(products) + `when`(products.all()).thenReturn(emptyList()) val definition = BukkitControlCommand(plugin, library, mock(CurrencyProviderRegistry::class.java)).definition() val root = definition.root val catalog = root.children.single { it.name == "updates" } diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLibraryPlayerTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitLibraryPlayerTest.kt similarity index 89% rename from platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLibraryPlayerTest.kt rename to platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitLibraryPlayerTest.kt index de513321b..8ec210561 100644 --- a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitLibraryPlayerTest.kt +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitLibraryPlayerTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.bukkit +package org.pnfolder.pnlibrary.bukkit.audience import net.kyori.adventure.key.Key import net.kyori.adventure.sound.Sound @@ -18,8 +18,9 @@ import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.Mockito.`when` import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.audiences.PlayerEffect -import org.pnfolder.pnlibrary.api.audiences.PlayerParticle +import org.pnfolder.pnlibrary.api.audiences.player.PlayerEffect +import org.pnfolder.pnlibrary.api.audiences.player.PlayerParticle +import org.pnfolder.pnlibrary.bukkit.PnLoggerBuffer import java.time.Duration import java.util.UUID import java.util.logging.Logger @@ -28,7 +29,10 @@ class BukkitLibraryPlayerTest { private val server = mock(Server::class.java) private val console = mock(ConsoleCommandSender::class.java) private val player = mock(Player::class.java) - private val library = BukkitLibraryPlayer(player, BukkitAudienceService(plugin(), null)) + private val library = BukkitLibraryPlayer( + player, + BukkitAudienceService(plugin(), PnLoggerBuffer(java.util.logging.Logger.getAnonymousLogger()) { null }, null), + ) private val bell = Sound.sound(Key.key("minecraft:block.note_block.bell"), Sound.Source.MASTER, 1f, 1f) init { diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitTitleTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitTitleTest.kt similarity index 95% rename from platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitTitleTest.kt rename to platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitTitleTest.kt index e132ea99d..88630d4ab 100644 --- a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/BukkitTitleTest.kt +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/audience/BukkitTitleTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.bukkit +package org.pnfolder.pnlibrary.bukkit.audience import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/audience/JoinNoticeDeliveryTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/audience/JoinNoticeDeliveryTest.kt new file mode 100644 index 000000000..abcbb7580 --- /dev/null +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/audience/JoinNoticeDeliveryTest.kt @@ -0,0 +1,67 @@ +package org.pnfolder.pnlibrary.bukkit.audience + +import net.kyori.adventure.text.Component +import org.bukkit.entity.Player +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.mockito.Mockito.mock +import org.mockito.Mockito.`when` +import org.mockito.stubbing.Answer +import org.pnfolder.pnlibrary.api.tasks.TaskHandle +import org.pnfolder.pnlibrary.api.tasks.TaskScope +import org.pnfolder.pnlibrary.api.tasks.run.TaskContext +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskSpec +import org.pnfolder.pnlibrary.bukkit.currency.error +import java.util.concurrent.atomic.AtomicReference + +class JoinNoticeDeliveryTest { + private val specs = mutableListOf() + private val scope: TaskScope = mock(TaskScope::class.java, Answer { call -> + if (call.method.name != "schedule") return@Answer null + specs += call.arguments[0] as TaskSpec + mock(TaskHandle::class.java) + }) + private val player: Player = mock(Player::class.java).also { `when`(it.isOnline).thenReturn(true) } + private val context: TaskContext = mock(TaskContext::class.java) + + @Test + fun `the journal is read by the asynchronous task and only the send runs on the player thread`() { + val builtOn = AtomicReference() + val sentOn = AtomicReference() + val sent = mutableListOf() + val lines = listOf(Component.text("one"), Component.text("two")) + val main = Thread.currentThread() + + JoinNoticeDelivery(scope).deliver(player, build = { builtOn.set(Thread.currentThread()); lines }) { text -> + sentOn.set(Thread.currentThread()) + sent += text + } + + assertEquals(1, specs.size) + assertEquals(TaskExecution.Kind.ASYNC, specs[0].execution.kind) + assertEquals(null, builtOn.get(), "nothing is read while the join event is handled") + + val worker = Thread { specs[0].action.run(context) }.also { it.start(); it.join() } + assertNotEquals(main, builtOn.get()) + assertEquals(worker, builtOn.get()) + assertEquals(2, specs.size) + assertEquals(TaskExecution.Kind.ENTITY, specs[1].execution.kind) + assertEquals(null, sentOn.get()) + + specs[1].action.run(context) + assertEquals(main, sentOn.get()) + assertEquals(lines, sent) + } + + @Test + fun `an empty notice schedules no send`() { + JoinNoticeDelivery(scope).deliver(player, build = { emptyList() }) { error("must not send") } + + specs[0].action.run(context) + + assertTrue(specs.size == 1) + } +} diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitCommandAdapterTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitCommandAdapterTest.kt index f672b771f..e3fe7a7b0 100644 --- a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitCommandAdapterTest.kt +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitCommandAdapterTest.kt @@ -9,8 +9,8 @@ import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.audiences.AudienceSender import org.pnfolder.pnlibrary.api.audiences.Delivery import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command import org.pnfolder.pnlibrary.spi.commands.NativeCommandRegistrar import org.pnfolder.pnlibrary.spi.commands.PlatformCommandDispatcher import org.pnfolder.pnlibrary.spi.commands.PlatformCommandRegistration diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitControlCommandTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitControlCommandTest.kt index 7889c331b..37f8573e8 100644 --- a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitControlCommandTest.kt +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/commands/BukkitControlCommandTest.kt @@ -6,19 +6,19 @@ import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.chat.ChatNotice -import org.pnfolder.pnlibrary.api.chat.ChatTone -import org.pnfolder.pnlibrary.api.commands.CommandNodeKind +import org.pnfolder.pnlibrary.api.chat.style.ChatTone import org.pnfolder.pnlibrary.api.commands.CommandSender +import org.pnfolder.pnlibrary.api.commands.definition.CommandNodeKind import org.pnfolder.pnlibrary.api.currency.CurrencyProviderRegistry import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.api.updates.BlockedReason -import org.pnfolder.pnlibrary.api.updates.ProductId -import org.pnfolder.pnlibrary.api.updates.UpdateChannel -import org.pnfolder.pnlibrary.api.updates.UpdatePlanSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateSnapshot -import org.pnfolder.pnlibrary.api.updates.UpdateState +import org.pnfolder.pnlibrary.api.updates.product.ProductId +import org.pnfolder.pnlibrary.api.updates.product.UpdateChannel import org.pnfolder.pnlibrary.api.updates.release.ProductChange import org.pnfolder.pnlibrary.api.updates.release.UpdatePlan +import org.pnfolder.pnlibrary.api.updates.state.BlockedReason +import org.pnfolder.pnlibrary.api.updates.state.UpdatePlanSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateSnapshot +import org.pnfolder.pnlibrary.api.updates.state.UpdateState import org.pnfolder.pnlibrary.api.version.PnLibraryApi import org.pnfolder.pnlibrary.api.version.SemanticVersion import org.pnfolder.pnlibrary.core.updates.catalog.UpdateStatusMessages @@ -38,10 +38,11 @@ class BukkitControlCommandTest { // The root has no permission of its own: every administrative word asks for pnlibrary.admin by itself. assertEquals(null, definition.permission) assertEquals( - listOf("status", "check", "gui", "updates", "update", "support", "bus", "tasks", "servers", "money"), + listOf("status", "check", "gui", "updates", "update", "support", "bus", "tasks", "modules", "configs", "deps", "servers", "money"), definition.root.children.map { it.name }, ) - val administrative = definition.root.children.filter { it.name != "money" && it.name != "bus" && it.name != "tasks" && it.name != "servers" } + val hidden = setOf("money", "bus", "tasks", "modules", "configs", "deps", "servers") + val administrative = definition.root.children.filter { it.name !in hidden } assertTrue(administrative.all { it.permission == "pnlibrary.admin" }, administrative.map { it.name }.toString()) val update = definition.root.children.single { it.name == "update" } // A narrower permission opens the same word next to the wide one. diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/currency/BukkitCurrencyCommandTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/currency/BukkitCurrencyCommandTest.kt index 07016b6c4..8de5d1680 100644 --- a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/currency/BukkitCurrencyCommandTest.kt +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/currency/BukkitCurrencyCommandTest.kt @@ -10,12 +10,12 @@ import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.audiences.AudienceSender import org.pnfolder.pnlibrary.api.audiences.Delivery import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandNodeKind +import org.pnfolder.pnlibrary.api.commands.definition.CommandNodeKind import org.pnfolder.pnlibrary.api.currency.Currency -import org.pnfolder.pnlibrary.api.currency.CurrencyAccess import org.pnfolder.pnlibrary.api.currency.CurrencyProvider import org.pnfolder.pnlibrary.api.currency.CurrencyProviderRegistry import org.pnfolder.pnlibrary.api.currency.CurrencyRegistration +import org.pnfolder.pnlibrary.api.plugin.PluginAccess import org.pnfolder.pnlibrary.api.plugin.PluginId import org.pnfolder.pnlibrary.bukkit.commands.BukkitCommandSender import org.pnfolder.pnlibrary.bukkit.tasks.ServerScheduler @@ -88,7 +88,7 @@ class BukkitCurrencyCommandTest { } private object EmptyCurrencies : CurrencyProviderRegistry { - override fun register(owner: PluginId, name: String, provider: CurrencyProvider, access: CurrencyAccess): CurrencyRegistration = + override fun register(owner: PluginId, name: String, provider: CurrencyProvider, access: PluginAccess): CurrencyRegistration = error("not used") override fun get(reference: String): Currency? = null override fun all(): List = emptyList() diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/currency/VaultCurrencyStartupTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/currency/VaultCurrencyStartupTest.kt new file mode 100644 index 000000000..bc6ee95d2 --- /dev/null +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/currency/VaultCurrencyStartupTest.kt @@ -0,0 +1,37 @@ +package org.pnfolder.pnlibrary.bukkit.currency + +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows + +class VaultCurrencyStartupTest { + @Test + fun `economy that is still starting is not connected yet`() { + assertNull(BukkitCurrencyAdapters.vaultCurrency(StartingEconomy())) + } + + @Test + fun `ready economy is connected`() { + assertNotNull(BukkitCurrencyAdapters.vaultCurrency(ReadyEconomy())) + } + + @Test + fun `other provider failures are not hidden`() { + assertThrows { + BukkitCurrencyAdapters.vaultCurrency(BrokenEconomy()) + } + } + + class StartingEconomy { + fun currencyNamePlural(): String = throw NullPointerException("settings are not loaded") + } + + class ReadyEconomy { + fun currencyNamePlural(): String = "Coins" + } + + class BrokenEconomy { + fun currencyNamePlural(): String = throw IllegalStateException("broken") + } +} diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/BukkitMenusTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/BukkitMenusTest.kt index e8fc48a13..6c25940b0 100644 --- a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/BukkitMenusTest.kt +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/inventory/BukkitMenusTest.kt @@ -17,6 +17,7 @@ import org.mockito.Mockito.mock import org.mockito.Mockito.never import org.mockito.Mockito.verify import org.mockito.Mockito.`when` +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.api.tasks.TaskScope import java.util.UUID import java.util.concurrent.ConcurrentLinkedQueue @@ -39,7 +40,7 @@ class BukkitMenusTest { if (region.get() == player.uniqueId) action() else queued.add(player to action) } } - private val service = BukkitMenus(host, mock(), execution) { menu, holder -> + private val service = BukkitMenus(host, mock(), { mock() }, execution) { menu, holder -> mock().also { `when`(it.holder).thenReturn(holder); `when`(it.size).thenReturn(menu.size) } } private fun menu(renderer: MenuRenderer? = null) = Menu("test", 1, MenuType.CHEST, diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/item/CopyingCacheTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/item/CopyingCacheTest.kt new file mode 100644 index 000000000..865ae155f --- /dev/null +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/item/CopyingCacheTest.kt @@ -0,0 +1,53 @@ +package org.pnfolder.pnlibrary.bukkit.item + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotSame +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit + +class CopyingCacheTest { + private class Stack(var name: String) + + private fun cache(capacity: Int) = CopyingCache(capacity) { Stack(it.name) } + + @Test + fun `callers get copies and cannot change what is stored`() { + val cache = cache(4) + val original = Stack("head") + cache["a"] = original + original.name = "changed after storing" + + val first = cache["a"]!! + first.name = "changed after reading" + + assertNotSame(first, cache["a"]) + assertEquals("head", cache["a"]!!.name) + } + + @Test + fun `the cache never grows past its capacity and drops the least recently used`() { + val cache = cache(3) + listOf("a", "b", "c").forEach { cache[it] = Stack(it) } + cache["a"] + cache["d"] = Stack("d") + + assertEquals(3, cache.size) + assertNull(cache["b"]) + assertEquals(setOf("a", "c", "d"), listOf("a", "c", "d").filter { cache[it] != null }.toSet()) + repeat(1000) { cache["k$it"] = Stack("k$it") } + assertEquals(3, cache.size) + } + + @Test + fun `parallel use stays within capacity`() { + val cache = cache(16) + val pool = Executors.newFixedThreadPool(4) + repeat(4) { thread -> pool.execute { repeat(2000) { cache["${thread}-${it % 50}"] = Stack("x"); cache["${thread}-${it % 50}"] } } } + pool.shutdown() + assertTrue(pool.awaitTermination(10, TimeUnit.SECONDS)) + assertTrue(cache.size <= 16) + } +} diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/item/ProfileSettersTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/item/ProfileSettersTest.kt new file mode 100644 index 000000000..39e1c8d3d --- /dev/null +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/item/ProfileSettersTest.kt @@ -0,0 +1,127 @@ +package org.pnfolder.pnlibrary.bukkit.item + +import org.bukkit.inventory.meta.SkullMeta +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Test +import java.lang.reflect.Method +import java.lang.reflect.Proxy +import java.net.URI +import java.net.URL +import java.util.UUID + +interface FakeTextures { + fun setSkin(url: URL) +} + +interface FakeProfile { + fun getTextures(): FakeTextures + + fun setTextures(textures: FakeTextures) +} + +interface FakeSkull { + fun setOwnerProfile(profile: FakeProfile) +} + +object FakeBukkit { + val log = mutableListOf() + + @JvmStatic + fun createPlayerProfile(id: UUID, name: String): FakeProfile { + log += "create $id $name" + val textures = object : FakeTextures { + override fun setSkin(url: URL) { + log += "skin $url" + } + } + return object : FakeProfile { + override fun getTextures() = textures.also { log += "getTextures" } + + override fun setTextures(textures: FakeTextures) { + log += "setTextures" + } + } + } +} + +class ProfileSettersTest { + private class CountingReflection : Reflection { + var lookups = 0 + private val types = mapOf( + "org.bukkit.profile.PlayerProfile" to FakeProfile::class.java, + "org.bukkit.profile.PlayerTextures" to FakeTextures::class.java, + ) + + override fun type(name: String): Class<*> = types[name] ?: throw ClassNotFoundException(name) + + override fun method(type: Class<*>, name: String, vararg parameters: Class<*>): Method { + lookups++ + return type.getMethod(name, *parameters) + } + } + + private val urls = (1..100).map { URI("https://textures.minecraft.net/texture/hash$it").toURL() } + + private fun skull(): SkullMeta = Proxy.newProxyInstance( + javaClass.classLoader, arrayOf(SkullMeta::class.java, FakeSkull::class.java), + ) { _, method, _ -> + if (method.name == "setOwnerProfile") FakeBukkit.log += "owner" + null + } as SkullMeta + + /** The way heads were made before: every class and method looked up again for each head. */ + private fun oldWay(reflection: CountingReflection, url: URL, meta: SkullMeta) { + val id = UUID.nameUUIDFromBytes("pnLibrary:$url".toByteArray(Charsets.UTF_8)) + val name = "pn" + id.toString().replace("-", "").take(14) + val profileType = reflection.type("org.bukkit.profile.PlayerProfile") + val texturesType = reflection.type("org.bukkit.profile.PlayerTextures") + val profile = reflection.method(FakeBukkit::class.java, "createPlayerProfile", UUID::class.java, String::class.java).invoke(null, id, name) + val textures = reflection.method(profileType, "getTextures").invoke(profile) + reflection.method(texturesType, "setSkin", URL::class.java).invoke(textures, url) + reflection.method(profileType, "setTextures", texturesType).invoke(profile, textures) + reflection.method(FakeSkull::class.java, "setOwnerProfile", profileType).invoke(meta, profile) + } + + @Test + fun `the setter makes the same calls as the lookup on every head did`() { + val reflection = CountingReflection() + val setter = ModernProfileSetter.resolve(reflection, FakeBukkit::class.java, FakeSkull::class.java) + assertNotNull(setter) + + FakeBukkit.log.clear() + urls.forEach { oldWay(reflection, it, skull()) } + val before = FakeBukkit.log.toList() + FakeBukkit.log.clear() + urls.forEach { setter!!.apply(skull(), it) } + + assertEquals(before, FakeBukkit.log.toList()) + } + + @Test + fun `a hundred heads look up each method once instead of once per head`() { + val old = CountingReflection() + urls.forEach { oldWay(old, it, skull()) } + + val fresh = CountingReflection() + val setter = ModernProfileSetter.resolve(fresh, FakeBukkit::class.java, FakeSkull::class.java)!! + urls.forEach { setter.apply(skull(), it) } + + assertEquals(500, old.lookups) + assertEquals(5, fresh.lookups) + } + + @Test + fun `a server without the profile API gives no setter after a single failed lookup`() { + val reflection = object : Reflection { + var types = 0 + override fun type(name: String): Class<*> = throw ClassNotFoundException(name).also { types++ } + + override fun method(type: Class<*>, name: String, vararg parameters: Class<*>): Method = error("unreachable") + } + assertNull(ModernProfileSetter.resolve(reflection)) + assertNull(LegacyProfileSetter.resolve(reflection)) + assertEquals(2, reflection.types) + } +} diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PlaceholderApiRequestsTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PlaceholderApiRequestsTest.kt new file mode 100644 index 000000000..e58bc86ff --- /dev/null +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PlaceholderApiRequestsTest.kt @@ -0,0 +1,57 @@ +package org.pnfolder.pnlibrary.bukkit.placeholders + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.pnfolder.pnlibrary.api.placeholders.adapter.PlaceholderAdapter +import org.pnfolder.pnlibrary.api.placeholders.model.PlaceholderRequest +import org.pnfolder.pnlibrary.api.plugin.PluginId +import java.util.UUID + +class PlaceholderApiRequestsTest { + private val owner = PluginId.of("war") + private val player = UUID(1, 2) + private val seen = mutableListOf() + + private fun requests(primary: Boolean) = PlaceholderApiRequests { primary }.also { requests -> + requests.handlers.add("score.{who}", PublishedHandler(owner) { seen += it; "score of ${it.parameters["who"]}" }) + requests.handlers.add("empty", PublishedHandler(owner) { seen += it; null }) + } + + @Test + fun `the answer is the resolver's text with the brace parts and the player`() { + assertEquals("score of Alex", requests(primary = false).answer(player, "score.Alex")) + val request = seen.single() + assertEquals(mapOf("who" to "Alex"), request.parameters) + assertEquals(player, request.playerId) + assertEquals(owner, request.owner) + } + + @Test + fun `an unknown name or an empty value gives null`() { + val requests = requests(primary = false) + assertNull(requests.answer(null, "missing")) + assertNull(requests.answer(null, "empty")) + } + + @Test + fun `the server thread is told not to wait and other threads may wait a second`() { + requests(primary = true).answer(player, "score.A") + requests(primary = false).answer(player, "score.B") + assertEquals(listOf(0L, 1000L), seen.map { it.values[PlaceholderAdapter.WAIT_MILLIS_KEY] }) + } + + @Test + fun `a slow resolver that honours the wait value does not hold the server thread`() { + val requests = PlaceholderApiRequests { true } + requests.handlers.add("slow", PublishedHandler(owner) { request -> + val wait = request.values[PlaceholderAdapter.WAIT_MILLIS_KEY] as Long + if (wait > 0) Thread.sleep(wait) + "late" + }) + val started = System.nanoTime() + assertEquals("late", requests.answer(null, "slow")) + assertTrue((System.nanoTime() - started) / 1_000_000 < 500) + } +} diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PublishedNamesTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PublishedNamesTest.kt index a6a62d3db..aa9959275 100644 --- a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PublishedNamesTest.kt +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/placeholders/PublishedNamesTest.kt @@ -1,34 +1,95 @@ package org.pnfolder.pnlibrary.bukkit.placeholders import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class PublishedNamesTest { private val handlers = mapOf("war~score" to "plain", "war~score.{who}" to "player", "war~score.top" to "top", "tag" to "tag") + private fun index(names: Map) = PublishedNames().also { index -> + names.forEach { (name, handler) -> assertTrue(index.add(name, handler)) } + } + + /** The lookup as it was before the index: a walk over every published name. */ + private fun scan(names: Map, params: String): PublishedNames.Found? { + names.entries.firstOrNull { '{' !in it.key && params.equals(it.key, true) }?.let { return PublishedNames.Found(it.value, emptyMap()) } + val byPattern = names.entries + .mapNotNull { (name, handler) -> ExternalNames.match(name, params)?.let { Triple(name, handler, it) } } + .maxByOrNull { (name, _, _) -> ExternalNames.specificity(name) } + if (byPattern != null) return PublishedNames.Found(byPattern.second, byPattern.third) + val match = names.entries.sortedByDescending { it.key.length }.firstOrNull { + '{' !in it.key && (params.equals(it.key, true) || params.startsWith(it.key + "_", true)) + } ?: return null + val suffix = params.removePrefix(match.key).removePrefix("_") + return PublishedNames.Found(match.value, if (suffix.isEmpty()) emptyMap() else mapOf("value" to suffix)) + } + @Test fun `a plain name matches exactly`() { - assertEquals(PublishedNames.Found("plain", emptyMap()), PublishedNames.find(handlers, "war~score")) + assertEquals(PublishedNames.Found("plain", emptyMap()), index(handlers).find("war~score")) } @Test fun `a brace part reads the value from the text`() { - assertEquals(PublishedNames.Found("player", mapOf("who" to "Alex")), PublishedNames.find(handlers, "war~score.Alex")) + assertEquals(PublishedNames.Found("player", mapOf("who" to "Alex")), index(handlers).find("war~score.Alex")) } @Test fun `fixed text beats a brace part`() { - assertEquals("top", PublishedNames.find(handlers, "war~score.top")?.handler) + assertEquals("top", index(handlers).find("war~score.top")?.handler) } @Test fun `the rest after an underscore goes to the value`() { - assertEquals(PublishedNames.Found("tag", mapOf("value" to "x")), PublishedNames.find(handlers, "tag_x")) + assertEquals(PublishedNames.Found("tag", mapOf("value" to "x")), index(handlers).find("tag_x")) } @Test fun `an unknown name gives nothing`() { - assertNull(PublishedNames.find(handlers, "other")) + assertNull(index(handlers).find("other")) + } + + @Test + fun `a taken name is refused and a removed one is gone`() { + val names = index(handlers) + assertFalse(names.add("tag", "again")) + names.remove("tag") + assertNull(names.find("tag")) + assertFalse(names.isEmpty) + } + + @Test + fun `the index answers like the walk over all names`() { + val names = buildMap { + repeat(300) { put("m$it~score", "plain$it"); put("m$it~top.{n}", "top$it"); put("m$it~p.{a}.{b}", "pair$it") } + put("tag", "tag"); put("tag_long", "long") + } + val index = index(names) + val asked = buildList { + repeat(300) { add("m$it~score"); add("M$it~SCORE"); add("m$it~top.$it"); add("m$it~p.x.y"); add("m$it~p.x") } + addAll(listOf("tag", "tag_x", "TAG_x", "tag_long", "tag_long_more", "nothing", "", "m5~score_extra", "m5~top.1.2")) + } + for (params in asked) assertEquals(scan(names, params), index.find(params), params) + } + + @Test + fun `a direct hit tries no name one by one`() { + val names = buildMap { repeat(500) { put("m$it~score", "plain$it"); put("m$it~top.{n}", "top$it") } } + val index = index(names) + + repeat(2_000) { assertEquals("plain${it % 500}", index.find("m${it % 500}~score")?.handler) } + + assertEquals(0L, index.scanned) + index.find("m1~top.7") + assertEquals(500L, index.scanned) // only the parameterized names, never the 500 plain ones + } + + @Test + fun `the server thread does not wait for placeholder values`() { + assertEquals(0L, MAIN_THREAD_WAIT_MILLIS) + assertTrue(OTHER_THREAD_WAIT_MILLIS > 0) } } diff --git a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/BukkitTaskAdapterTest.kt b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/BukkitTaskAdapterTest.kt index 97040b526..81c61772c 100644 --- a/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/BukkitTaskAdapterTest.kt +++ b/platforms/bukkit/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bukkit/tasks/BukkitTaskAdapterTest.kt @@ -2,7 +2,7 @@ package org.pnfolder.pnlibrary.bukkit.tasks import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.tasks.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskHandle import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest import org.pnfolder.pnlibrary.spi.tasks.TrackingPlatformTaskAdapter @@ -20,7 +20,7 @@ class BukkitTaskAdapterTest { fun `one shot task is released after callback`() { val adapter = RecordingTaskAdapter() val request = PlatformTaskRequest(TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, Runnable {}) - val handle = adapter.schedule(request) + val handle = adapter.buildTask().from(request).schedule() assertEquals(1, adapter.active) adapter.callback!!.run() assertEquals(true, handle.cancel()) diff --git a/platforms/bungee/api/build.gradle.kts b/platforms/bungee/api/build.gradle.kts index 7cd41b402..f1e47d7e6 100644 --- a/platforms/bungee/api/build.gradle.kts +++ b/platforms/bungee/api/build.gradle.kts @@ -6,7 +6,8 @@ plugins { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-bungee-api", project.version.toString()) pom { name.set("pnLibrary Bungee API") diff --git a/platforms/bungee/bootstrap/build.gradle.kts b/platforms/bungee/bootstrap/build.gradle.kts index 4fb1b00dc..f87af37ed 100644 --- a/platforms/bungee/bootstrap/build.gradle.kts +++ b/platforms/bungee/bootstrap/build.gradle.kts @@ -18,7 +18,8 @@ tasks.withType().configureEach { useJUnitPlatform() } mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-bootstrap-bungee", project.version.toString()) pom { name.set("pnLibrary BungeeCord Bootstrap") diff --git a/platforms/bungee/runtime/build.gradle.kts b/platforms/bungee/runtime/build.gradle.kts index 90fcb7776..0e130927d 100644 --- a/platforms/bungee/runtime/build.gradle.kts +++ b/platforms/bungee/runtime/build.gradle.kts @@ -9,7 +9,7 @@ base { archivesName = "${rootProject.property("pnlibrary.name")}-bungee" } dependencies { implementation(project(":modules:api")) - implementation(project(":modules:runtime-spi")) + implementation(project(":modules:spi")) implementation(project(":modules:core")) implementation(project(":platforms:bungee:api")) implementation(libs.kotlin.stdlib) diff --git a/platforms/bungee/runtime/src/main/java/org/pnfolder/pnlibrary/bungee/PnLibraryBungeePlugin.java b/platforms/bungee/runtime/src/main/java/org/pnfolder/pnlibrary/bungee/PnLibraryBungeePlugin.java index 8eb7ddf27..8bf251586 100644 --- a/platforms/bungee/runtime/src/main/java/org/pnfolder/pnlibrary/bungee/PnLibraryBungeePlugin.java +++ b/platforms/bungee/runtime/src/main/java/org/pnfolder/pnlibrary/bungee/PnLibraryBungeePlugin.java @@ -21,12 +21,15 @@ public final class PnLibraryBungeePlugin extends Plugin { private Object runtime; - /** Starts the runtime; a refused remote policy or failed startup stops it. */ @Override public void onEnable() { LibrarySettings settings = LibrarySettings.DEFAULT; try { - LibraryLoader.load(new BungeeLibraryManager(this, settings.directoryFor(getDataFolder().toPath())), getClass().getClassLoader(), settings, RuntimeLibraries.BUNGEE); + BungeeLibraryManager manager = new BungeeLibraryManager(this, settings.directoryFor(getDataFolder().toPath())); + LibraryLoader.load(manager, getClass().getClassLoader(), settings, RuntimeLibraries.BUNGEE); + LibraryLoader.useManagers(owner -> owner instanceof net.md_5.bungee.api.plugin.Plugin + ? new BungeeLibraryManager((net.md_5.bungee.api.plugin.Plugin) owner, settings.directoryFor(((net.md_5.bungee.api.plugin.Plugin) owner).getDataFolder().toPath())) + : null); Class type = Class.forName("org.pnfolder.pnlibrary.bungee.BungeeRuntime", true, getClass().getClassLoader()); Constructor constructor = type.getDeclaredConstructors()[0]; runtime = constructor.newInstance(this); diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeBStats.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeBStats.kt deleted file mode 100644 index 579253e1f..000000000 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeBStats.kt +++ /dev/null @@ -1,27 +0,0 @@ -package org.pnfolder.pnlibrary.bungee - -import net.md_5.bungee.api.plugin.Plugin -import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsClient -import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsSettings -import java.io.File -import java.util.logging.Level - -/** What bStats needs to know about a BungeeCord proxy; the sending itself is shared by every platform. */ -internal object BungeeBStats { - /** Opens the sender for [plugin], which is reported under the bStats [serviceId]. */ - fun open(plugin: Plugin, serviceId: Int): BStatsClient = BStatsClient( - platform = "bungeecord", - serviceId = serviceId, - settings = BStatsSettings.yaml(File(File(plugin.dataFolder.parentFile, "bStats"), "config.yml")), - pluginVersion = plugin.description.version, - appendPlatformData = { data -> - data.appendField("playerAmount", plugin.proxy.onlineCount) - data.appendField("managedServers", plugin.proxy.servers.size) - data.appendField("onlineMode", if (plugin.proxy.config.isOnlineMode) 1 else 0) - data.appendField("bungeecordVersion", plugin.proxy.version) - data.appendField("bungeecordName", plugin.proxy.name) - }, - warn = { message, error -> plugin.logger.log(Level.WARNING, message, error) }, - info = { message -> plugin.logger.log(Level.INFO, message) }, - ) -} diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeLibraryPlayer.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeLibraryPlayer.kt deleted file mode 100644 index 7dacb72c1..000000000 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeLibraryPlayer.kt +++ /dev/null @@ -1,61 +0,0 @@ -package org.pnfolder.pnlibrary.bungee - -import net.kyori.adventure.sound.Sound -import net.kyori.adventure.text.Component -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer -import net.md_5.bungee.api.ChatMessageType -import net.md_5.bungee.api.chat.TextComponent -import net.md_5.bungee.api.connection.ProxiedPlayer -import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.audiences.PlayerCapability -import org.pnfolder.pnlibrary.api.audiences.PlayerEffect -import org.pnfolder.pnlibrary.api.audiences.PlayerParticle -import java.util.UUID - -/** - * [LibraryPlayer] bridge backed by a BungeeCord [ProxiedPlayer]. - * - * Components are converted to legacy Bungee chat components. The proxy cannot directly render - * server-side potion effects or particles, so those operations return `false`. - * - * Bungee's legacy component parser is deprecated in newer API releases but remains the only - * binary-compatible conversion path across the module's supported proxy baseline. - */ -@Suppress("DEPRECATION") -internal class BungeeLibraryPlayer private constructor( - private val player: ProxiedPlayer, -) : LibraryPlayer { - override val capabilities: Set = setOf( - PlayerCapability.MESSAGE, - PlayerCapability.ACTION_BAR, - ) - override val uniqueId: UUID get() = player.uniqueId - override val name: String get() = player.name - - override fun hasPermission(permission: String): Boolean = player.hasPermission(permission) - - override fun sendMessage(text: Component) { - player.sendMessage(*TextComponent.fromLegacyText(LEGACY.serialize(text))) - } - - override fun actionBar(text: Component) { - player.sendMessage(ChatMessageType.ACTION_BAR, *TextComponent.fromLegacyText(LEGACY.serialize(text))) - } - - /** Returns [Delivery.Unsupported] because this proxy adapter cannot play server-side sounds. */ - override fun playSound(sound: Sound): Delivery = Delivery.Unsupported - - /** Returns [Delivery.Unsupported] because potion effects require a backend server. */ - override fun applyEffect(effect: PlayerEffect): Delivery = Delivery.Unsupported - - /** Returns [Delivery.Unsupported] because particle rendering requires a backend server. */ - override fun spawnParticle(particle: PlayerParticle): Delivery = Delivery.Unsupported - - companion object { - private val LEGACY = LegacyComponentSerializer.legacySection() - - @JvmStatic - fun of(player: ProxiedPlayer): LibraryPlayer = BungeeLibraryPlayer(player) - } -} diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeMetricsFactory.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeMetricsFactory.kt deleted file mode 100644 index aae4170f1..000000000 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeMetricsFactory.kt +++ /dev/null @@ -1,20 +0,0 @@ -package org.pnfolder.pnlibrary.bungee - -import dev.faststats.bungee.BungeeContext -import net.md_5.bungee.api.plugin.Plugin -import org.pnfolder.pnlibrary.core.metrics.NativePluginMetricsFactory -import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsMetricsSession -import org.pnfolder.pnlibrary.core.metrics.faststats.SimpleFastStatsMetricsSession - -/** Opens independently managed bStats and FastStats sessions for BungeeCord plugins. */ -internal class BungeeMetricsFactory : NativePluginMetricsFactory( - ownerType = Plugin::class.java, - platformName = "BungeeCord", - bStats = { plugin, projectId -> - val client = BungeeBStats.open(plugin, projectId) - BStatsMetricsSession(projectId, client::addCustomChart, client::shutdown) - }, - fastStats = { plugin, token -> - SimpleFastStatsMetricsSession(token) { contextToken -> BungeeContext.Factory(plugin, contextToken) } - }, -) diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeePlatformAdapter.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeePlatformAdapter.kt index 847556bf2..8e1e99067 100644 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeePlatformAdapter.kt +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeePlatformAdapter.kt @@ -3,33 +3,33 @@ package org.pnfolder.pnlibrary.bungee import net.md_5.bungee.api.chat.TextComponent import net.md_5.bungee.api.plugin.Plugin import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.remote.RemotePolicyContext import org.pnfolder.pnlibrary.bungee.commands.BungeeCommandAdapter +import org.pnfolder.pnlibrary.bungee.diagnostics.BungeeDiagnosticDetailsCollector +import org.pnfolder.pnlibrary.bungee.metrics.BungeeMetricsFactory +import org.pnfolder.pnlibrary.bungee.network.BungeeAudienceAdapter +import org.pnfolder.pnlibrary.bungee.network.BungeeNetworkProxy import org.pnfolder.pnlibrary.bungee.remote.BungeeRemotePolicyContextFactory import org.pnfolder.pnlibrary.bungee.tasks.BungeeTaskAdapter -import org.pnfolder.pnlibrary.spi.audiences.PlatformAudienceAdapter import org.pnfolder.pnlibrary.spi.commands.PlatformCommandAdapter import org.pnfolder.pnlibrary.spi.metrics.PlatformMetricsFactory import org.pnfolder.pnlibrary.spi.platform.JulLogObserver -import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter -import org.pnfolder.pnlibrary.spi.platform.PlatformLifecycle import org.pnfolder.pnlibrary.spi.platform.PlatformPlugins import org.pnfolder.pnlibrary.spi.platform.PlatformSnapshot import org.pnfolder.pnlibrary.spi.platform.PluginSnapshot -import org.pnfolder.pnlibrary.spi.platform.StartupGate -import org.pnfolder.pnlibrary.spi.platform.UncaughtExceptionLogObserver +import org.pnfolder.pnlibrary.spi.platform.ProxyPlatformAdapter import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskAdapter import java.nio.file.Path import java.util.logging.Logger -/** Runtime adapter for BungeeCord-compatible proxy servers. */ internal class BungeePlatformAdapter( - val plugin: Plugin, -) : PlatformAdapter { + private val plugin: Plugin, + pnLogger: () -> PnLogger, +) : ProxyPlatformAdapter(plugin) { private val diagnosticDetailsCollector = BungeeDiagnosticDetailsCollector(plugin) - private val lifecycle = PlatformLifecycle() private val plugins = PlatformPlugins( platformName = "BungeeCord", installed = { plugin.proxy.pluginManager.plugins }, @@ -44,9 +44,7 @@ internal class BungeePlatformAdapter( mainClass = description.main, ) } - private val startup = StartupGate(lifecycle, ::executeGlobal) - private val uncaughtExceptionObserver = UncaughtExceptionLogObserver(plugin) private val logObserver = JulLogObserver({ plugin.proxy.logger }, plugin) { loggerName -> JulLogObserver.matchPlugin(loggerName, plugin.proxy.pluginManager.plugins) { it.description.name } } @@ -58,36 +56,31 @@ internal class BungeePlatformAdapter( get() = plugin.proxy.name.ifBlank { type.displayName } override val metricsFactory: PlatformMetricsFactory = - BungeeMetricsFactory() + BungeeMetricsFactory(pnLogger) - override val commandAdapter: PlatformCommandAdapter = - BungeeCommandAdapter(plugin) + override val networkProxy: BungeeNetworkProxy by lazy { BungeeNetworkProxy(plugin.proxy) } - override val audienceAdapter: PlatformAudienceAdapter = + override val audienceAdapter: BungeeAudienceAdapter = BungeeAudienceAdapter(plugin) + override val commandAdapter: PlatformCommandAdapter = + BungeeCommandAdapter(audienceAdapter) + override val taskAdapter: PlatformTaskAdapter = BungeeTaskAdapter(plugin) override val logHandler: (Any, LogLevel, String, Throwable?) -> Unit = logObserver.logHandler { owner -> (owner as? Plugin)?.logger ?: plugin.logger } - /** Forwards proxy and plugin warnings/errors and uncaught JVM exceptions, preserving the previous handler. */ - @Synchronized - override fun observeNativeLogs(observer: ((Any, LogLevel, String, Throwable?) -> Unit)?) { - if (observer != null) lifecycle.checkOpen() + override fun observeProxyLogs(observer: ((Any, LogLevel, String, Throwable?) -> Unit)?) { logObserver.observe(observer) - uncaughtExceptionObserver.observe(observer) } @Suppress("DEPRECATION") override fun console(owner: Any, message: String) { - plugin.proxy.console.sendMessage( - *TextComponent.fromLegacyText(message), - ) + plugin.proxy.console.sendMessage(*TextComponent.fromLegacyText(message)) } - /** Reads native plugin metadata, warning and returning null for unsupported owners. */ override fun ownerMetadata(owner: Any): PluginSnapshot? = plugins.metadata(owner, this) override fun ownerDataFolder(owner: Any): Path? = plugins.find(owner)?.dataFolder?.toPath() @@ -96,7 +89,6 @@ internal class BungeePlatformAdapter( override fun installedPlugins(): Map = plugins.versions() - /** Collects typed proxy metadata without exposing individual player identities. */ override fun snapshot(): PlatformSnapshot { val proxy = plugin.proxy @@ -118,29 +110,10 @@ internal class BungeePlatformAdapter( ): RemotePolicyContext = BungeeRemotePolicyContextFactory.create(plugins.requireInstalled(owner, "Remote policy owner"), values) - /** Dispatches work asynchronously; BungeeCord has no global main-thread scheduler. */ + // BungeeCord has no main-thread scheduler; global work runs asynchronously. override fun executeGlobal(task: Runnable) { if (lifecycle.isClosed) return plugin.proxy.scheduler.runAsync(plugin, task) } - - /** Waits until the entry point has published the runtime and native platform API. */ - override fun whenServerReady(task: Runnable) { - startup.whenReady(task) - } - - /** Releases startup callbacks once; other managed plugins may still use the startup grace. */ - internal fun markReady() { - startup.markReady() - } - - override fun executeReply(recipient: Any, task: Runnable) { - executeGlobal(task) - } - - /** Discards pending startup work, cancels native tasks and stops native log observation once. */ - override fun close() { - lifecycle.closeAdapter(startup, taskAdapter) { observeNativeLogs(null) } - } } diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeePlatformServices.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeePlatformServices.kt deleted file mode 100644 index 2a587c027..000000000 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeePlatformServices.kt +++ /dev/null @@ -1,9 +0,0 @@ -package org.pnfolder.pnlibrary.bungee - -import net.md_5.bungee.api.ProxyServer -import org.pnfolder.pnlibrary.bungee.api.BungeePlatform - -/** Native-backed Bungee platform API installed by the Bungee runtime. */ -internal class BungeePlatformServices( - override val proxy: ProxyServer, -) : BungeePlatform diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeRuntime.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeRuntime.kt index 178cccfd8..eaa097bf9 100644 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeRuntime.kt +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeRuntime.kt @@ -1,97 +1,68 @@ package org.pnfolder.pnlibrary.bungee import net.md_5.bungee.api.plugin.Plugin -import net.md_5.bungee.api.scheduler.ScheduledTask +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.bungee.api.BungeePlatform +import org.pnfolder.pnlibrary.bungee.link.BungeeLinkListener +import org.pnfolder.pnlibrary.bungee.network.BungeePlayerEvents import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.link.LinkCodec -import org.pnfolder.pnlibrary.core.menu.OwnerInfo -import org.pnfolder.pnlibrary.core.proxy.ProxyLink +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup +import org.pnfolder.pnlibrary.core.link.LinkReceiver +import org.pnfolder.pnlibrary.core.runtime.PnLibraryRuntime import org.pnfolder.pnlibrary.core.runtime.PnLibraryRuntimeHost -import java.util.concurrent.TimeUnit +import org.pnfolder.pnlibrary.core.runtime.ProxyRuntime -/** - * Owns the shared pnLibrary runtime for the BungeeCord plugin. - * - * [start] binds the Bungee platform and marks the adapter ready once the runtime is up; a failure - * rolls back inside [PnLibraryRuntimeHost.launchPlatform]. [stop] closes the host and is safe to - * call more than once. - */ internal class BungeeRuntime(private val plugin: Plugin) { - private var host: PnLibraryRuntimeHost? = null + private var proxyRuntime: ProxyRuntime? = null + private var runtimeHost: PnLibraryRuntimeHost? = null private var playerEvents: BungeePlayerEvents? = null - private var linkListener: BungeeLinkListener? = null - private var link: ProxyLink? = null - private var networkTask: ScheduledTask? = null fun start() { try { open() } catch (error: Throwable) { - // Whatever opened before the failure must not stay registered on a proxy that goes on without us. - runCatchingNonFatal(::stop) + runCatchingNonFatal(::stop).onFailure(error::addSuppressed) throw error } } private fun open() { - val adapter = BungeePlatformAdapter(plugin) - val started = PnLibraryRuntimeHost.launchPlatform( - plugin, - adapter, - BungeePlatform::class.java, - BungeePlatformServices(plugin.proxy), - adapter::markReady, - ) - host = started - val listener = BungeePlayerEvents(started.library) - plugin.proxy.pluginManager.registerListener(plugin, listener) - playerEvents = listener - connectLink(started) + var metricsLogger: PnLogger? = null + val adapter = BungeePlatformAdapter(plugin) { metricsLogger!! } + val host = PnLibraryRuntime.builder() + .owner(plugin) + .adapter(adapter) + .platform(object : BungeePlatform { override val proxy = plugin.proxy }) + .launch(adapter::markReady) + runtimeHost = host + metricsLogger = host.library.logging.logger(plugin, "Metrics") + + val proxy = ProxyRuntime(adapter, ::registerLinkListener, adapter.networkProxy::describePlugin) + proxyRuntime = proxy + proxy.start(host) + + playerEvents = BungeePlayerEvents(host.library) + .also { plugin.proxy.pluginManager.registerListener(plugin, it) } } - /** Opens the link to the game servers and, when it is secured, starts announcing this proxy. */ - private fun connectLink(started: PnLibraryRuntimeHost) { - val proxyLink = ProxyLink( - library = started.library, - folder = plugin.dataFolder.toPath(), - warn = plugin.logger::warning, - transport = { name, bytes -> - val server = plugin.proxy.servers.entries.firstOrNull { it.key.equals(name, ignoreCase = true) }?.value - server?.sendData(LinkCodec.CHANNEL, bytes, false) ?: false - }, - describe = { owner -> (owner as? Plugin)?.description?.let { OwnerInfo(it.name, it.version, listOfNotNull(it.author)) } }, - platformName = { "${plugin.proxy.name} ${plugin.proxy.version}" }, - players = { plugin.proxy.onlineCount }, - broadcast = { message -> plugin.proxy.servers.values.forEach { runCatchingNonFatal { it.sendData(LinkCodec.CHANNEL, message, false) } } }, - ) - link = proxyLink - val listener = BungeeLinkListener(proxyLink.receiver) - plugin.proxy.registerChannel(LinkCodec.CHANNEL) + private fun registerLinkListener(receiver: LinkReceiver): AutoCloseable { + val listener = BungeeLinkListener(receiver) plugin.proxy.pluginManager.registerListener(plugin, listener) - linkListener = listener - if (proxyLink.announces) { - networkTask = plugin.proxy.scheduler.schedule( - plugin, - proxyLink::announce, - ProxyLink.NETWORK_DELAY_SECONDS, - ProxyLink.NETWORK_PERIOD_SECONDS, - TimeUnit.SECONDS, - ) - } + return AutoCloseable { plugin.proxy.pluginManager.unregisterListener(listener) } } fun stop() { - networkTask?.cancel() - networkTask = null - linkListener?.let { runCatchingNonFatal { plugin.proxy.pluginManager.unregisterListener(it) } } - linkListener = null - link?.let { runCatchingNonFatal(it::close) } - link = null - runCatchingNonFatal { plugin.proxy.unregisterChannel(LinkCodec.CHANNEL) } - playerEvents?.let { runCatchingNonFatal { plugin.proxy.pluginManager.unregisterListener(it) } } + val proxy = proxyRuntime + val events = playerEvents + val host = runtimeHost + proxyRuntime = null playerEvents = null - host?.close() - host = null + runtimeHost = null + + ResourceCleanup.closeAll( + { proxy?.close() }, + { events?.let { plugin.proxy.pluginManager.unregisterListener(it) } }, + { host?.close() }, + ) } } diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/commands/BungeeCommandAdapter.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/commands/BungeeCommandAdapter.kt index ef97a4d63..9cd19027d 100644 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/commands/BungeeCommandAdapter.kt +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/commands/BungeeCommandAdapter.kt @@ -1,73 +1,40 @@ package org.pnfolder.pnlibrary.bungee.commands -import net.kyori.adventure.sound.Sound -import net.kyori.adventure.text.Component import net.md_5.bungee.api.plugin.Command import net.md_5.bungee.api.plugin.Plugin import net.md_5.bungee.api.plugin.TabExecutor import org.pnfolder.pnlibrary.api.audiences.AudienceSender -import org.pnfolder.pnlibrary.api.audiences.Delivery import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.CommandSender -import org.pnfolder.pnlibrary.bungee.BungeeAudienceAdapter -import org.pnfolder.pnlibrary.core.commands.PROXY_SUGGESTION_MILLIS -import org.pnfolder.pnlibrary.core.commands.proxy.ProxyCommandNames -import org.pnfolder.pnlibrary.core.commands.suggestionsWithin +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.bungee.network.BungeeAudienceAdapter +import org.pnfolder.pnlibrary.core.commands.engine.PROXY_SUGGESTION_MILLIS +import org.pnfolder.pnlibrary.core.commands.engine.suggestionsWithin +import org.pnfolder.pnlibrary.core.commands.proxy.proxyCommandContext import org.pnfolder.pnlibrary.spi.commands.GenericPlatformCommandAdapter import org.pnfolder.pnlibrary.spi.commands.NativeCommandRegistrar import org.pnfolder.pnlibrary.spi.commands.PlatformCommandRegistration import java.util.concurrent.CompletionStage import net.md_5.bungee.api.CommandSender as NativeCommandSender -/** - * Registers portable commands with BungeeCord and owns their native registrations. - * - * Native tab completion is synchronous, so suggestions have a bounded one-second wait. - * Closing this adapter unregisters commands in reverse registration order. - */ -internal class BungeeCommandAdapter internal constructor( - private val nativeRegistrar: NativeCommandRegistrar, +internal class BungeeCommandAdapter( + nativeRegistrar: NativeCommandRegistrar, private val audience: (NativeCommandSender) -> AudienceSender, ) : GenericPlatformCommandAdapter() { - override val registrar: NativeCommandRegistrar = nativeRegistrar - constructor(plugin: Plugin) : this( + constructor(audiences: BungeeAudienceAdapter) : this( nativeRegistrar = DefaultBungeeNativeCommandRegistrar(), - { sender -> requireNotNull(BungeeAudienceAdapter(plugin).sender(sender)) }, + audience = { sender -> requireNotNull(audiences.sender(sender)) }, ) + override val registrar: NativeCommandRegistrar = nativeRegistrar + override fun context( source: NativeCommandSender, alias: String, arguments: Array, - ): CommandContext = CommandContext( - sender = BungeeCommandSender(audience(source), ProxyCommandNames.owns(alias)), - arguments = arguments.toList(), - invokedAlias = alias, - currentInput = arguments.lastOrNull().orEmpty(), - ) - -} - -/** Delegates portable command replies to the native audience bridge. */ -private class BungeeCommandSender( - private val audience: AudienceSender, - private val proxyControl: Boolean, -) : CommandSender, AudienceSender by audience { - - override fun send(message: Component) = audience.sendMessage(shown(message)) - - override fun sendMessage(text: Component) = audience.sendMessage(shown(text)) - - private fun shown(message: Component) = if (proxyControl) ProxyCommandNames.rewrite(message) else message - - override fun actionBar(text: Component) = audience.actionBar(text) - - override fun playSound(sound: Sound): Delivery = audience.playSound(sound) + ): CommandContext = proxyCommandContext(audience(source), alias, arguments) } -/** Installs command and tab-completion handlers in the proxy plugin manager. */ private class DefaultBungeeNativeCommandRegistrar : NativeCommandRegistrar { override fun register( owner: Any, @@ -77,14 +44,22 @@ private class DefaultBungeeNativeCommandRegistrar : NativeCommandRegistrar) = executeHandler(sender, command.name, args) - override fun onTabComplete(sender: NativeCommandSender, args: Array): Iterable = - suggestionHandler(sender, command.name, args).suggestionsWithin(PROXY_SUGGESTION_MILLIS) - } + val native = NativeBungeeCommand(command, execute, suggest) ownerPlugin.proxy.pluginManager.registerCommand(ownerPlugin, native) return PlatformCommandRegistration { ownerPlugin.proxy.pluginManager.unregisterCommand(native) } } } + +private class NativeBungeeCommand( + private val definition: CommandDefinition, + private val onExecute: (NativeCommandSender, String, Array) -> Unit, + private val onSuggest: (NativeCommandSender, String, Array) -> CompletionStage>, +) : Command(definition.name, null, *definition.aliases.toTypedArray()), TabExecutor { + + override fun execute(sender: NativeCommandSender, args: Array) = + onExecute(sender, definition.name, args) + + // Bungee tab completion is synchronous; do not block the proxy beyond the suggestion budget. + override fun onTabComplete(sender: NativeCommandSender, args: Array): Iterable = + onSuggest(sender, definition.name, args).suggestionsWithin(PROXY_SUGGESTION_MILLIS) +} diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeDiagnosticDetailsCollector.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/diagnostics/BungeeDiagnosticDetailsCollector.kt similarity index 92% rename from platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeDiagnosticDetailsCollector.kt rename to platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/diagnostics/BungeeDiagnosticDetailsCollector.kt index afdf07946..bf9f977f0 100644 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeDiagnosticDetailsCollector.kt +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/diagnostics/BungeeDiagnosticDetailsCollector.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.bungee +package org.pnfolder.pnlibrary.bungee.diagnostics import net.md_5.bungee.api.plugin.Plugin import org.pnfolder.pnlibrary.spi.platform.DiagnosticDetailsCollector @@ -6,10 +6,10 @@ import org.pnfolder.pnlibrary.spi.platform.DiagnosticSections import org.pnfolder.pnlibrary.spi.platform.PlatformSnapshot import org.pnfolder.pnlibrary.spi.platform.ProxyBackend -/** Collects the small set of BungeeCord facts that is useful during incident diagnosis. */ internal class BungeeDiagnosticDetailsCollector( private val plugin: Plugin, ) { + fun collect(snapshot: PlatformSnapshot, includeSensitive: Boolean): Map = DiagnosticDetailsCollector { snapshot }.collect(includeSensitive) { details -> val proxy = plugin.proxy diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeLinkListener.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/link/BungeeLinkListener.kt similarity index 77% rename from platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeLinkListener.kt rename to platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/link/BungeeLinkListener.kt index 3dd5c2078..00ef95c8f 100644 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeLinkListener.kt +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/link/BungeeLinkListener.kt @@ -1,14 +1,14 @@ -package org.pnfolder.pnlibrary.bungee +package org.pnfolder.pnlibrary.bungee.link import net.md_5.bungee.api.connection.Server import net.md_5.bungee.api.event.PluginMessageEvent import net.md_5.bungee.api.plugin.Listener import net.md_5.bungee.event.EventHandler -import org.pnfolder.pnlibrary.core.link.LinkCodec import org.pnfolder.pnlibrary.core.link.LinkReceiver +import org.pnfolder.pnlibrary.core.link.wire.LinkCodec -/** Takes the reports that game servers send on the pnLibrary link channel; messages from players are dropped. */ internal class BungeeLinkListener(private val receiver: LinkReceiver) : Listener { + @EventHandler fun onMessage(event: PluginMessageEvent) { if (event.tag != LinkCodec.CHANNEL) return diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/metrics/BungeeMetricsFactory.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/metrics/BungeeMetricsFactory.kt new file mode 100644 index 000000000..c786dd9c1 --- /dev/null +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/metrics/BungeeMetricsFactory.kt @@ -0,0 +1,39 @@ +package org.pnfolder.pnlibrary.bungee.metrics + +import dev.faststats.bungee.BungeeContext +import net.md_5.bungee.api.plugin.Plugin +import org.pnfolder.pnlibrary.api.logging.PnLogger +import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsClient +import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsMetricsSession +import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsSettings +import org.pnfolder.pnlibrary.core.metrics.factory.NativePluginMetricsFactory +import org.pnfolder.pnlibrary.core.metrics.faststats.SimpleFastStatsMetricsSession +import java.io.File + +internal class BungeeMetricsFactory(pnLogger: () -> PnLogger) : NativePluginMetricsFactory( + ownerType = Plugin::class.java, + platformName = "BungeeCord", + bStats = { plugin, projectId -> + val client = openBStats(plugin, projectId, pnLogger) + BStatsMetricsSession(projectId, client::addCustomChart, client::shutdown) + }, + fastStats = { plugin, token -> + SimpleFastStatsMetricsSession(token) { contextToken -> BungeeContext.Factory(plugin, contextToken) } + }, +) + +private fun openBStats(plugin: Plugin, serviceId: Int, pnLogger: () -> PnLogger): BStatsClient = BStatsClient( + platform = "bungeecord", + serviceId = serviceId, + settings = BStatsSettings.yaml(File(File(plugin.dataFolder.parentFile, "bStats"), "config.yml")), + pluginVersion = plugin.description.version, + appendPlatformData = { data -> + data.appendField("playerAmount", plugin.proxy.onlineCount) + data.appendField("managedServers", plugin.proxy.servers.size) + data.appendField("onlineMode", if (plugin.proxy.config.isOnlineMode) 1 else 0) + data.appendField("bungeecordVersion", plugin.proxy.version) + data.appendField("bungeecordName", plugin.proxy.name) + }, + warn = { message, error -> pnLogger().warning(message, error) }, + info = { message -> pnLogger().info(message) }, +) diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeAudienceAdapter.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeAudienceAdapter.kt similarity index 71% rename from platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeAudienceAdapter.kt rename to platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeAudienceAdapter.kt index 9a13def4d..50f1fce0c 100644 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeeAudienceAdapter.kt +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeAudienceAdapter.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.bungee +package org.pnfolder.pnlibrary.bungee.network import net.kyori.adventure.sound.Sound import net.kyori.adventure.text.Component @@ -9,11 +9,10 @@ import net.md_5.bungee.api.connection.ProxiedPlayer import net.md_5.bungee.api.plugin.Plugin import org.pnfolder.pnlibrary.api.audiences.AudienceSender import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer +import org.pnfolder.pnlibrary.api.network.NetworkPlayer import org.pnfolder.pnlibrary.spi.audiences.PlatformAudienceAdapter import java.util.UUID -/** Converts native proxy recipients to portable audiences using legacy chat serialization. */ @Suppress("DEPRECATION") internal class BungeeAudienceAdapter( private val plugin: Plugin, @@ -21,18 +20,18 @@ internal class BungeeAudienceAdapter( override fun console(): AudienceSender = wrap(plugin.proxy.console) - override fun player(uniqueId: UUID): LibraryPlayer? = plugin.proxy.getPlayer(uniqueId)?.let(BungeeLibraryPlayer::of) + override fun player(uniqueId: UUID): NetworkPlayer? = + plugin.proxy.getPlayer(uniqueId)?.let(BungeeNetworkPlayer::of) - /** Wraps supported native senders; unsupported objects return null. */ override fun sender(native: Any): AudienceSender? = when (native) { - is ProxiedPlayer -> BungeeLibraryPlayer.of(native) + is ProxiedPlayer -> BungeeNetworkPlayer.of(native) is CommandSender -> wrap(native) else -> null } - override fun onlinePlayers(): List = plugin.proxy.players.map(BungeeLibraryPlayer::of) + override fun onlinePlayers(): List = + plugin.proxy.players.map(BungeeNetworkPlayer::of) - /** Wraps generic senders; action-bar messages fall back to chat and sounds are unsupported. */ private fun wrap(sender: CommandSender): AudienceSender = object : AudienceSender { override val id get() = sender.name override val name get() = sender.name diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeNetworkPlayer.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeNetworkPlayer.kt new file mode 100644 index 000000000..bc33c654f --- /dev/null +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeNetworkPlayer.kt @@ -0,0 +1,54 @@ +package org.pnfolder.pnlibrary.bungee.network + +import net.kyori.adventure.sound.Sound +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer +import net.md_5.bungee.api.ChatMessageType +import net.md_5.bungee.api.chat.TextComponent +import net.md_5.bungee.api.connection.ProxiedPlayer +import org.pnfolder.pnlibrary.api.audiences.Delivery +import org.pnfolder.pnlibrary.api.audiences.player.PlayerCapability +import org.pnfolder.pnlibrary.api.audiences.player.PlayerEffect +import org.pnfolder.pnlibrary.api.audiences.player.PlayerParticle +import org.pnfolder.pnlibrary.api.network.NetworkPlayer +import org.pnfolder.pnlibrary.api.network.NetworkServer +import java.net.InetSocketAddress +import java.util.UUID + +@Suppress("DEPRECATION") +internal class BungeeNetworkPlayer( + internal val native: ProxiedPlayer, +) : NetworkPlayer { + + override val capabilities: Set = setOf( + PlayerCapability.MESSAGE, + PlayerCapability.ACTION_BAR, + ) + + override val uniqueId: UUID get() = native.uniqueId + override val name: String get() = native.name + override val address: InetSocketAddress? get() = native.address + override val ping: Long get() = native.ping.toLong() + override val currentServer: NetworkServer? + get() = native.server?.info?.let(::BungeeNetworkServer) + + override fun hasPermission(permission: String): Boolean = native.hasPermission(permission) + + override fun sendMessage(text: Component) = + native.sendMessage(*TextComponent.fromLegacyText(LEGACY.serialize(text))) + + override fun actionBar(text: Component) = + native.sendMessage(ChatMessageType.ACTION_BAR, *TextComponent.fromLegacyText(LEGACY.serialize(text))) + + override fun playSound(sound: Sound): Delivery = Delivery.Unsupported + override fun applyEffect(effect: PlayerEffect): Delivery = Delivery.Unsupported + override fun spawnParticle(particle: PlayerParticle): Delivery = Delivery.Unsupported + + override fun disconnect(reason: String) = native.disconnect(TextComponent(reason)) + + companion object { + private val LEGACY = LegacyComponentSerializer.legacySection() + + fun of(player: ProxiedPlayer): NetworkPlayer = BungeeNetworkPlayer(player) + } +} diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeNetworkProxy.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeNetworkProxy.kt new file mode 100644 index 000000000..460ad7892 --- /dev/null +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeNetworkProxy.kt @@ -0,0 +1,42 @@ +package org.pnfolder.pnlibrary.bungee.network + +import net.md_5.bungee.api.ProxyServer +import net.md_5.bungee.api.chat.TextComponent +import net.md_5.bungee.api.plugin.Plugin +import org.pnfolder.pnlibrary.api.network.NetworkPlayer +import org.pnfolder.pnlibrary.api.network.NetworkProxy +import org.pnfolder.pnlibrary.api.network.NetworkServer +import org.pnfolder.pnlibrary.core.menu.OwnerInfo +import java.util.UUID + +@Suppress("DEPRECATION") +internal class BungeeNetworkProxy(private val proxy: ProxyServer) : NetworkProxy { + + override val name: String get() = proxy.name + override val version: String get() = proxy.version + override val playerCount: Int get() = proxy.onlineCount + + override val players get() = proxy.players.map(::BungeeNetworkPlayer) + override val servers get() = proxy.servers.values.map(::BungeeNetworkServer) + + override fun player(name: String): NetworkPlayer? = + proxy.getPlayer(name)?.let(::BungeeNetworkPlayer) + + override fun player(uuid: UUID): NetworkPlayer? = + proxy.getPlayer(uuid)?.let(::BungeeNetworkPlayer) + + override fun server(name: String): NetworkServer? = + proxy.servers.entries.firstOrNull { it.key.equals(name, ignoreCase = true) } + ?.value?.let(::BungeeNetworkServer) + + override fun registerChannel(channel: String) = proxy.registerChannel(channel) + override fun unregisterChannel(channel: String) = proxy.unregisterChannel(channel) + + override fun broadcast(message: String) = proxy.broadcast(TextComponent(message)) + override fun stop(reason: String?) = + if (reason != null) proxy.stop(reason) else proxy.stop() + + fun describePlugin(instance: Any?): OwnerInfo? = + (instance as? Plugin)?.description + ?.let { OwnerInfo(it.name, it.version, listOfNotNull(it.author)) } +} diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeNetworkServer.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeNetworkServer.kt new file mode 100644 index 000000000..49ec4c801 --- /dev/null +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeNetworkServer.kt @@ -0,0 +1,31 @@ +package org.pnfolder.pnlibrary.bungee.network + +import net.md_5.bungee.api.chat.TextComponent +import net.md_5.bungee.api.config.ServerInfo +import org.pnfolder.pnlibrary.api.network.NetworkPlayer +import org.pnfolder.pnlibrary.api.network.NetworkServer +import java.net.InetSocketAddress + +@Suppress("DEPRECATION") +internal class BungeeNetworkServer(private val server: ServerInfo) : NetworkServer { + + override val name: String get() = server.name + override val address: InetSocketAddress get() = server.address + override val onlinePlayers: Int get() = server.players.size + override val ping: Long? get() = server.players + .map { it.ping.toLong() } + .takeIf { it.isNotEmpty() } + ?.average() + ?.toLong() + override val motd: String get() = server.motd + override val isRestricted: Boolean get() = server.isRestricted + + override fun send(channel: String, bytes: ByteArray): Boolean = + server.sendData(channel, bytes, false) + + override fun canAccess(player: NetworkPlayer): Boolean = + (player as? BungeeNetworkPlayer)?.native?.let { server.canAccess(it) } ?: true + + override fun broadcast(message: String) = + server.players.forEach { it.sendMessage(TextComponent(message)) } +} diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeePlayerEvents.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeePlayerEvents.kt similarity index 79% rename from platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeePlayerEvents.kt rename to platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeePlayerEvents.kt index 6ee7c2d9a..2aea82e26 100644 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/BungeePlayerEvents.kt +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeePlayerEvents.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.bungee +package org.pnfolder.pnlibrary.bungee.network import net.md_5.bungee.api.event.PlayerDisconnectEvent import net.md_5.bungee.api.event.PostLoginEvent @@ -6,10 +6,10 @@ import net.md_5.bungee.api.plugin.Listener import net.md_5.bungee.event.EventHandler import net.md_5.bungee.event.EventPriority import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.core.events.PlayerLifecyclePublisher +import org.pnfolder.pnlibrary.core.events.player.PlayerLifecyclePublisher -/** Publishes the portable player join and quit events from BungeeCord's native ones. */ internal class BungeePlayerEvents(private val library: PnLibrary) : Listener { + @EventHandler(priority = EventPriority.HIGHEST) fun onPostLogin(event: PostLoginEvent) { PlayerLifecyclePublisher.joined(library, event.player.uniqueId, event.player.name) diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/remote/BungeeRemotePolicyContextFactory.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/remote/BungeeRemotePolicyContextFactory.kt index 31f1e84dc..30b6a57b1 100644 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/remote/BungeeRemotePolicyContextFactory.kt +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/remote/BungeeRemotePolicyContextFactory.kt @@ -9,14 +9,8 @@ import org.pnfolder.pnlibrary.api.remote.ServerInfo import org.pnfolder.pnlibrary.common.minecraft.MinecraftVersion import java.util.Locale -/** Creates remote-policy contexts from BungeeCord runtime metadata. */ internal object BungeeRemotePolicyContextFactory { - /** - * Builds a context for [plugin] and appends caller-defined policy [values]. - * - * @param plugin BungeeCord plugin that owns the policy evaluation. - * @param values Additional non-sensitive values exposed to policy rules. - */ + fun create(plugin: Plugin, values: Map = emptyMap()): RemotePolicyContext { val proxy = plugin.proxy val description = plugin.description diff --git a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/tasks/BungeeTaskAdapter.kt b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/tasks/BungeeTaskAdapter.kt index 589df6b76..cbd6289c4 100644 --- a/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/tasks/BungeeTaskAdapter.kt +++ b/platforms/bungee/runtime/src/main/kotlin/org/pnfolder/pnlibrary/bungee/tasks/BungeeTaskAdapter.kt @@ -6,15 +6,11 @@ import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest import org.pnfolder.pnlibrary.spi.tasks.TrackingPlatformTaskAdapter import java.util.concurrent.TimeUnit -/** - * Adapts portable task requests to BungeeCord's asynchronous scheduler. - * - * BungeeCord has no main-thread or entity-region scheduler. Every execution kind uses the - * same native scheduler; completed one-shot tasks are released from lifecycle tracking. - */ -internal class BungeeTaskAdapter internal constructor( +// BungeeCord runs every execution kind on the same asynchronous scheduler. +internal class BungeeTaskAdapter( private val nativeSchedule: (PlatformTaskRequest) -> PlatformTaskHandle, ) : TrackingPlatformTaskAdapter() { + constructor(plugin: Plugin) : this({ request -> val scheduler = plugin.proxy.scheduler val interval = request.interval diff --git a/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/BungeeReadinessTest.kt b/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/BungeeReadinessTest.kt index db7d8e2e9..9a38264ab 100644 --- a/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/BungeeReadinessTest.kt +++ b/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/BungeeReadinessTest.kt @@ -6,8 +6,10 @@ import net.md_5.bungee.api.scheduler.TaskScheduler import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.mockito.Mockito.* +import org.pnfolder.pnlibrary.api.logging.PnLogger import java.io.File +/** Checks that startup-dependent work waits until the Bungee adapter is marked ready. */ class BungeeReadinessTest { @Test fun `startup callbacks wait for runtime publication and are released once`() { @@ -20,7 +22,7 @@ class BungeeReadinessTest { val scheduled = mutableListOf() doAnswer { invocation -> scheduled.add(invocation.getArgument(1)); null } .`when`(scheduler).runAsync(same(plugin), any(Runnable::class.java)) - val adapter = BungeePlatformAdapter(plugin) + val adapter = BungeePlatformAdapter(plugin) { mock(PnLogger::class.java) } var calls = 0 try { adapter.whenServerReady(Runnable { calls++ }) @@ -43,7 +45,7 @@ class BungeeReadinessTest { fun `closing before readiness discards pending startup callbacks`() { val plugin = mock(Plugin::class.java) `when`(plugin.dataFolder).thenReturn(File("build/readiness-test")) - val adapter = BungeePlatformAdapter(plugin) + val adapter = BungeePlatformAdapter(plugin) { mock(PnLogger::class.java) } adapter.whenServerReady(Runnable { fail("Closed adapter must not release startup work") }) adapter.close() adapter.markReady() diff --git a/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/commands/BungeeCommandAdapterTest.kt b/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/commands/BungeeCommandAdapterTest.kt index 19f847903..2e905e883 100644 --- a/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/commands/BungeeCommandAdapterTest.kt +++ b/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/commands/BungeeCommandAdapterTest.kt @@ -9,8 +9,8 @@ import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.audiences.AudienceSender import org.pnfolder.pnlibrary.api.audiences.Delivery import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command import org.pnfolder.pnlibrary.spi.commands.NativeCommandRegistrar import org.pnfolder.pnlibrary.spi.commands.PlatformCommandDispatcher import org.pnfolder.pnlibrary.spi.commands.PlatformCommandRegistration @@ -19,6 +19,7 @@ import java.lang.reflect.Proxy import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage +/** Checks command registration, execution, tab completion and cleanup on BungeeCord. */ class BungeeCommandAdapterTest { @Test fun `native callbacks translate sender execution and suggestions`() { diff --git a/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/BungeeAudienceAdapterTest.kt b/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeAudienceAdapterTest.kt similarity index 93% rename from platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/BungeeAudienceAdapterTest.kt rename to platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeAudienceAdapterTest.kt index 060aa7d7f..b4e620971 100644 --- a/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/BungeeAudienceAdapterTest.kt +++ b/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/network/BungeeAudienceAdapterTest.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.bungee +package org.pnfolder.pnlibrary.bungee.network import net.kyori.adventure.sound.Sound import net.kyori.adventure.text.Component @@ -16,9 +16,10 @@ import org.junit.jupiter.api.Test import org.mockito.Mockito.mock import org.mockito.Mockito.`when` import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.audiences.PlayerCapability +import org.pnfolder.pnlibrary.api.audiences.player.PlayerCapability import java.util.UUID +/** Checks how proxy senders and players are converted to portable audiences. */ class BungeeAudienceAdapterTest { private val proxy = mock(ProxyServer::class.java) private val plugin = mock(Plugin::class.java).also { `when`(it.proxy).thenReturn(proxy) } @@ -89,7 +90,7 @@ class BungeeAudienceAdapterTest { @Test fun `a player can read messages and the action bar but nothing a backend must render`() { - val library = BungeeLibraryPlayer.of(player("Alex")) + val library = BungeeNetworkPlayer.of(player("Alex")) assertEquals(setOf(PlayerCapability.MESSAGE, PlayerCapability.ACTION_BAR), library.capabilities) assertEquals(Delivery.Unsupported, library.playSound(mock(Sound::class.java))) } diff --git a/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/remote/BungeeRemotePolicyContextFactoryTest.kt b/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/remote/BungeeRemotePolicyContextFactoryTest.kt index 848c4f26a..a85518ccc 100644 --- a/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/remote/BungeeRemotePolicyContextFactoryTest.kt +++ b/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/remote/BungeeRemotePolicyContextFactoryTest.kt @@ -11,6 +11,7 @@ import org.mockito.Mockito.mock import org.mockito.Mockito.`when` import org.pnfolder.pnlibrary.api.platform.PlatformType +/** Checks the remote-policy context built from BungeeCord metadata. */ class BungeeRemotePolicyContextFactoryTest { private val manager = mock(PluginManager::class.java) private val proxy = mock(ProxyServer::class.java).also { diff --git a/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/tasks/BungeeTaskAdapterTest.kt b/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/tasks/BungeeTaskAdapterTest.kt index 6fff229e1..0ce86a3a5 100644 --- a/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/tasks/BungeeTaskAdapterTest.kt +++ b/platforms/bungee/runtime/src/test/kotlin/org/pnfolder/pnlibrary/bungee/tasks/BungeeTaskAdapterTest.kt @@ -2,11 +2,12 @@ package org.pnfolder.pnlibrary.bungee.tasks import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.tasks.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import org.pnfolder.pnlibrary.spi.tasks.* import java.time.Duration import java.util.concurrent.atomic.AtomicBoolean +/** Checks task scheduling and lifecycle tracking on the BungeeCord scheduler. */ class BungeeTaskAdapterTest { @Test fun `adapter forwards request and cancels native handle once`() { @@ -18,7 +19,7 @@ class BungeeTaskAdapterTest { } val request = PlatformTaskRequest(TaskExecution.Kind.ENTITY, "player", Duration.ofSeconds(2), Duration.ofSeconds(3), Runnable {}) - val handle = adapter.schedule(request) + val handle = adapter.buildTask().from(request).schedule() assertEquals(request.executionKind, seen?.executionKind) assertEquals(request.target, seen?.target) assertEquals(request.delay, seen?.delay) @@ -36,7 +37,7 @@ class BungeeTaskAdapterTest { callback = request.callback PlatformTaskHandle { cancelled.compareAndSet(false, true) } } - adapter.schedule(PlatformTaskRequest(TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, Runnable {})) + adapter.buildTask().from(PlatformTaskRequest(TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, Runnable {})).schedule() callback.run() adapter.close() assertFalse(cancelled.get()) diff --git a/platforms/loader/build.gradle.kts b/platforms/loader/build.gradle.kts index a27f8985a..4dc5a67f6 100644 --- a/platforms/loader/build.gradle.kts +++ b/platforms/loader/build.gradle.kts @@ -31,12 +31,24 @@ fun lib(dependency: Provider, vararg repositori Root(dependency, repositories.toList()) val platformLibraries: Map> = mapOf( - "BUKKIT" to listOf(lib(libs.kotlin.stdlib), lib(libs.adventure.legacy), lib(libs.adventure.platform.bukkit)), - "BUNGEE" to listOf(lib(libs.kotlin.stdlib), lib(libs.adventure.legacy)), + // The runtime uses MiniMessage, the plain-text and Gson serializers; the light JAR packs no net.kyori, so they come from here. + // Velocity brings all of them with Adventure itself. + "BUKKIT" to listOf( + lib(libs.kotlin.stdlib), lib(libs.adventure.legacy), lib(libs.adventure.platform.bukkit), + lib(libs.adventure.minimessage), lib(libs.adventure.plain), + ), + "BUNGEE" to listOf( + lib(libs.kotlin.stdlib), lib(libs.adventure.legacy), + lib(libs.adventure.minimessage), lib(libs.adventure.plain), lib(libs.adventure.gson), + ), "VELOCITY" to listOf(lib(libs.kotlin.stdlib)), // The compiler for remote policies, loaded only on a server that runs a JRE without javac. "COMPILER_LEGACY" to listOf(lib(libs.ecj.legacy)), "COMPILER_MODERN" to listOf(lib(libs.ecj.modern)), + // Loaded the first time a database backup needs it, never at start. + "DRIVER_MYSQL" to listOf(lib(libs.mariadb.jdbc)), + "DRIVER_MONGO" to listOf(lib(libs.mongodb.driver.sync)), + "DRIVER_POSTGRES" to listOf(lib(libs.postgresql.jdbc)), ) val skippedGroups = listOf("com.google") diff --git a/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/LibraryLoadException.java b/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/LibraryLoadException.java index 14b406769..945b2d9da 100644 --- a/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/LibraryLoadException.java +++ b/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/LibraryLoadException.java @@ -9,6 +9,7 @@ public final class LibraryLoadException extends RuntimeException { private final String library; private final int attempts; + /** Records the failed {@code library}, the number of {@code attempts} made and the last {@code cause}. */ LibraryLoadException(Library library, int attempts, Throwable cause) { super("Failed to load library " + id(library) + " after " + attempts + " attempt(s)", cause); this.library = id(library); @@ -19,10 +20,12 @@ private static String id(Library library) { return library.getGroupId() + ":" + library.getArtifactId() + ":" + library.getVersion(); } + /** The library that failed, as {@code group:artifact:version}. */ public String library() { return library; } + /** How many times the download was tried. */ public int attempts() { return attempts; } diff --git a/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/LibraryLoader.java b/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/LibraryLoader.java index 585b805a3..f34b156a3 100644 --- a/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/LibraryLoader.java +++ b/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/LibraryLoader.java @@ -2,8 +2,8 @@ import net.byteflux.libby.Library; import net.byteflux.libby.LibraryManager; - -import javax.tools.ToolProvider; +import java.nio.file.Path; +import java.util.function.Function; /** * Loads the libraries a light pnLibrary JAR does not pack, through Libby. @@ -11,25 +11,28 @@ *

Libby downloads each file, checks its SHA-256 and adds it to the plugin classloader. Where it downloads from * is set by {@link LibrarySettings}; what it downloads is listed in {@link RuntimeLibraries}. The full JARs already * hold Kotlin, so nothing is downloaded for them. + * + *

Only Kotlin is loaded at start. Everything else is optional and loaded by {@link #loadOptional} the moment + * something needs it, so a server that never uses a database backup or a remote policy downloads nothing for them. */ public final class LibraryLoader { private static final String PROBE = "kotlin.Unit"; - private static final String COMPILER_PROBE = "org.eclipse.jdt.internal.compiler.tool.EclipseCompiler"; // 3.26 is the last ECJ that runs on Java 8; the newer one needs Java 17. private static final int MODERN_COMPILER_JAVA = 17; + // Libby is tied to the plugin that started it, so later loads have to reuse that one manager. + private static volatile OptionalLoader optional; + private LibraryLoader() { } /** - * Loads {@code libraries} as {@code settings} say, unless Kotlin is already visible to {@code loader}. On a server - * that runs a JRE without javac it also loads the ECJ compiler, which remote policies are compiled with. + * Loads {@code libraries} as {@code settings} say, unless Kotlin is already visible to {@code loader}. * @throws LibraryLoadException if a library cannot be loaded after every attempt */ public static void load(LibraryManager manager, ClassLoader loader, LibrarySettings settings, Library... libraries) { - boolean kotlinMissing = !present(loader, PROBE); - boolean compilerMissing = needsCompiler(loader); - if (!kotlinMissing && !compilerMissing) { + optional = new OptionalLoader(manager, settings); + if (present(loader, PROBE)) { return; } for (String repository : settings.repositories()) { @@ -41,36 +44,96 @@ public static void load(LibraryManager manager, ClassLoader loader, LibrarySetti for (String fallback : settings.fallbacks()) { manager.addRepository(fallback); } - if (kotlinMissing) { - for (Library library : libraries) { - loadWithRetry(manager, library, settings.attempts()); - } + for (Library library : libraries) { + loadWithRetry(manager, library, settings.attempts()); } - if (compilerMissing) { - loadCompiler(manager, javaFeature()); + } + + /** + * Loads an optional library group the first time it is needed: {@code mysql}, {@code postgres}, {@code mongo} or {@code compiler}. + * Returns false when it cannot be loaded, for example offline; the caller says what is missing. Called by name + * from the runtime, which cannot see this module. + */ + public static boolean loadOptional(String id) { + OptionalLoader loader = optional; + Library[] libraries = librariesFor(id, javaFeature()); + return loader != null && libraries != null && loader.load(libraries); + } + + /** + * Tells the loader how to make a Libby manager for another plugin, so a shared library of a module is added to the + * plugin that owns the module and not to pnLibrary. The factory returns {@code null} for an owner it cannot handle. + */ + public static void useManagers(Function factory) { + OptionalLoader loader = optional; + if (loader != null) { + loader.useManagers(factory); } } /** - * A policy can still be checked without the compiler, so a failure here must not stop the server: the policy - * check reports the missing compiler itself and {@code onError} decides. One attempt only, so an offline - * server does not wait on every start. + * Loads a library a module asked for, through Libby, and returns the class loader that holds it: a loader of its own + * named {@code owner} when {@code isolated}, otherwise {@code null} (the library joins pnLibrary's loader). Called by + * name from the runtime, which cannot see this module; every value is a plain string for that reason. + * + * @param sha256 hexadecimal SHA-256 of the jar, or {@code null} to skip the check + * @param plugin the plugin that owns the module, or {@code null}; a shared library is added to its class loader + * @param url a direct link to the jar, or {@code null} to build it from {@code repositories} + * @throws IllegalStateException with the reason when the library cannot be loaded */ - static void loadCompiler(LibraryManager manager, int feature) { - Library[] compiler = feature >= MODERN_COMPILER_JAVA ? RuntimeLibraries.COMPILER_MODERN : RuntimeLibraries.COMPILER_LEGACY; - for (Library library : compiler) { - try { - manager.loadLibrary(library); - } catch (RuntimeException failure) { - return; - } + public static ClassLoader loadExternal(String owner, String group, String artifact, String version, String classifier, + String sha256, String url, String[] repositories, boolean isolated, Object plugin) { + OptionalLoader loader = optional; + if (loader == null) { + throw new IllegalStateException("The library loader is not started"); + } + Library.Builder builder = Library.builder().groupId(group).artifactId(artifact).version(version).id(owner).isolatedLoad(isolated); + if (classifier != null) { + builder.classifier(classifier); + } + if (sha256 != null) { + builder.checksum(sha256); + } + if (url != null) { + builder.url(url); + } + for (String repository : repositories) { + builder.repository(repository); + } + try { + return loader.loadExternal(builder.build(), plugin); + } catch (RuntimeException failure) { + throw new IllegalStateException("Cannot load " + group + ":" + artifact + ":" + version + ": " + failure.getMessage(), failure); } } - private static boolean needsCompiler(ClassLoader loader) { - return ToolProvider.getSystemJavaCompiler() == null && !present(loader, COMPILER_PROBE); + /** + * The jar file of a library loaded by {@link #loadExternal}, as a path text, or {@code null} when unknown. The key is + * {@code group:artifact:version} or {@code group:artifact:version:classifier}. + */ + public static String fileOf(String coordinates) { + OptionalLoader loader = optional; + Path file = loader == null ? null : loader.fileOf(coordinates); + return file == null ? null : file.toAbsolutePath().toString(); + } + + /** The libraries of an optional group, or {@code null} for an unknown id; {@code javaFeature} picks the compiler. */ + static Library[] librariesFor(String id, int javaFeature) { + switch (id) { + case "mysql": + return RuntimeLibraries.DRIVER_MYSQL; + case "postgres": + return RuntimeLibraries.DRIVER_POSTGRES; + case "mongo": + return RuntimeLibraries.DRIVER_MONGO; + case "compiler": + return javaFeature >= MODERN_COMPILER_JAVA ? RuntimeLibraries.COMPILER_MODERN : RuntimeLibraries.COMPILER_LEGACY; + default: + return null; + } } + /** The running Java feature version (8, 11, 17, ...); 8 when it cannot be read. */ static int javaFeature() { String version = System.getProperty("java.specification.version", "8"); String feature = version.startsWith("1.") ? version.substring(2) : version; diff --git a/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/LibrarySettings.java b/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/LibrarySettings.java index 42836c1f8..258d91e15 100644 --- a/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/LibrarySettings.java +++ b/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/LibrarySettings.java @@ -18,6 +18,7 @@ * SHA-256 recorded at build time, so a mirror cannot swap a library. */ public final class LibrarySettings { + /** The settings the pnLibrary JAR uses. */ public static final LibrarySettings DEFAULT = builder() // .repository("https://example.com/maven/") // your own mirror, tried before Maven Central .fallback("https://maven-central.storage-download.googleapis.com/maven2/") @@ -39,6 +40,7 @@ private LibrarySettings(Builder builder) { this.attempts = builder.attempts; } + /** Starts a settings description with the defaults: server folder, Maven Central, three attempts. */ public static Builder builder() { return new Builder(); } @@ -74,6 +76,7 @@ public int attempts() { return attempts; } + /** Collects {@link LibrarySettings} values; every method returns the builder. */ public static final class Builder { private String directory = "libraries/pnlibrary"; private boolean inServerFolder = true; @@ -105,6 +108,7 @@ public Builder repository(String url) { return this; } + /** Adds a mirror tried after Maven Central. Call again for more; the order is kept. */ public Builder fallback(String url) { fallbacks.add(requireUrl(url)); return this; diff --git a/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/OptionalLoader.java b/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/OptionalLoader.java new file mode 100644 index 000000000..50f1d8fc8 --- /dev/null +++ b/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/OptionalLoader.java @@ -0,0 +1,101 @@ +package org.pnfolder.pnlibrary.loader; + +import net.byteflux.libby.Library; +import net.byteflux.libby.LibraryManager; +import java.nio.file.Path; +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; + +/** + * Loads a library through Libby the first time something needs it: a database driver, the policy compiler. It is never + * loaded at start, because most servers never need it. + */ +final class OptionalLoader { + private final LibraryManager manager; + private final LibrarySettings settings; + private final Map perPlugin = new IdentityHashMap<>(); + private volatile Function managers; + private final Map files = new ConcurrentHashMap<>(); + + OptionalLoader(LibraryManager manager, LibrarySettings settings) { + this.manager = manager; + this.settings = settings; + } + + /** + * One attempt only: the caller reports a missing library itself, and an offline server must not wait. + * Calls are serialized because Libby's manager is not safe for two threads loading at once. + */ + synchronized boolean load(Library[] libraries) { + for (String repository : settings.repositories()) { + manager.addRepository(repository); + } + if (settings.mavenCentral()) { + manager.addMavenCentral(); + } + for (String fallback : settings.fallbacks()) { + manager.addRepository(fallback); + } + try { + for (Library library : libraries) { + manager.loadLibrary(library); + } + return true; + } catch (RuntimeException failure) { + return false; + } + } + + /** Sets how a Libby manager for another plugin is made; without it a shared library joins pnLibrary's own loader. */ + void useManagers(Function factory) { + this.managers = factory; + } + + /** + * Loads one library a module asked for. The library names its own repositories; the repositories of the server's + * settings are not added to it. An isolated library goes into a class loader of its own, named by the library's id, + * and that loader is returned. A shared library joins the class loader of {@code plugin}, the plugin that asked, when + * the platform can reach it; otherwise it joins pnLibrary's loader. {@code null} is returned for a shared library. + * + * @throws RuntimeException with the reason when the library cannot be downloaded or loaded + */ + synchronized ClassLoader loadExternal(Library library, Object plugin) { + LibraryManager target = library.isIsolatedLoad() ? manager : managerFor(plugin); + target.loadLibrary(library); + remember(target, library); + return library.isIsolatedLoad() ? manager.getIsolatedClassLoaderOf(library.getId()) : null; + } + + /** The jar a loaded library lives in, or {@code null} when it is unknown; the size and place shown to administrators. */ + Path fileOf(String coordinates) { + return files.get(coordinates); + } + + private void remember(LibraryManager target, Library library) { + try { + String key = library.getGroupId() + ":" + library.getArtifactId() + ":" + library.getVersion() + + (library.hasClassifier() ? ":" + library.getClassifier() : ""); + files.put(key, target.downloadLibrary(library)); + } catch (RuntimeException ignored) { + // the place is only informative; the library is already loaded + } + } + + private LibraryManager managerFor(Object plugin) { + Function factory = managers; + if (plugin == null || factory == null) { + return manager; + } + LibraryManager own = perPlugin.get(plugin); + if (own == null) { + own = factory.apply(plugin); + if (own == null) { + return manager; + } + perPlugin.put(plugin, own); + } + return own; + } +} diff --git a/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/StartupFailure.java b/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/StartupFailure.java index 1b1d4b94d..eccfd006a 100644 --- a/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/StartupFailure.java +++ b/platforms/loader/src/main/java/org/pnfolder/pnlibrary/loader/StartupFailure.java @@ -21,6 +21,7 @@ public final class StartupFailure { private StartupFailure() { } + /** Builds the card for {@code error}: the reason, what to do and where to ask for help. */ public static ConsoleCard card(ConsoleTheme theme, LibrarySettings settings, Path dataFolder, Throwable error) { Throwable cause = unwrap(error); ConsoleCard.Builder card = ConsoleCard.builder(theme, "ОШИБКА ЗАПУСКА") @@ -68,6 +69,7 @@ public static void report(ConsoleTheme theme, ConsoleSink sink, LibrarySettings card(theme, settings, dataFolder, error).send(sink); } + /** The repositories in the order they are tried, as one line. */ private static String repositories(LibrarySettings settings) { List all = new ArrayList<>(settings.repositories()); if (settings.mavenCentral()) { diff --git a/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/ExternalLibraryTest.java b/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/ExternalLibraryTest.java new file mode 100644 index 000000000..9057c9934 --- /dev/null +++ b/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/ExternalLibraryTest.java @@ -0,0 +1,64 @@ +package org.pnfolder.pnlibrary.loader; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import net.byteflux.libby.Library; +import net.byteflux.libby.LibraryManager; +import net.byteflux.libby.classloader.IsolatedClassLoader; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** Checks that a library a module asks for keeps its repositories, checksum and class loader. */ +class ExternalLibraryTest { + private static final String SHA = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + + private static LibraryManager start() { + LibraryManager manager = mock(LibraryManager.class); + LibraryLoader.load(manager, ExternalLibraryTest.class.getClassLoader(), LibrarySettings.builder().build()); + return manager; + } + + @Test + void passesTheModulesRepositoriesAndChecksumToLibby() { + LibraryManager manager = start(); + IsolatedClassLoader holder = new IsolatedClassLoader(); + when(manager.getIsolatedClassLoaderOf("shop")).thenReturn(holder); + + ClassLoader result = LibraryLoader.loadExternal("shop", "com.zaxxer", "HikariCP", "5.1.0", null, SHA, null, + new String[] {"https://one.example/", "https://repo1.maven.org/maven2/"}, true, null); + + ArgumentCaptor loaded = ArgumentCaptor.forClass(Library.class); + verify(manager).loadLibrary(loaded.capture()); + assertSame(holder, result); + assertEquals("shop", loaded.getValue().getId()); + assertTrue(loaded.getValue().isIsolatedLoad()); + assertTrue(loaded.getValue().hasChecksum()); + assertEquals(2, loaded.getValue().getRepositories().size()); + } + + @Test + void aSharedLibraryJoinsTheLoaderOfPnLibrary() { + start(); + + assertEquals(null, LibraryLoader.loadExternal("shop", "g", "a", "1", null, null, null, new String[0], false, null)); + } + + @Test + void aFailureCarriesTheReason() { + LibraryManager manager = start(); + doThrow(new RuntimeException("404")).when(manager).loadLibrary(any(Library.class)); + + IllegalStateException failure = assertThrows(IllegalStateException.class, + () -> LibraryLoader.loadExternal("shop", "g", "a", "1", null, null, null, new String[0], true, null)); + assertTrue(failure.getMessage().contains("g:a:1")); + assertTrue(failure.getMessage().contains("404")); + } +} diff --git a/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/LibraryLoaderTest.java b/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/LibraryLoaderTest.java index 3658ed489..07617cd1e 100644 --- a/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/LibraryLoaderTest.java +++ b/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/LibraryLoaderTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; @@ -16,9 +17,11 @@ import net.byteflux.libby.LibraryManager; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; import org.mockito.InOrder; +/** Checks repository order, retries and optional library groups of {@link LibraryLoader}. */ class LibraryLoaderTest { // Kotlin is not on this module's classpath, which is exactly the light JAR's situation. private static final ClassLoader LOADER = LibraryLoaderTest.class.getClassLoader(); @@ -129,23 +132,50 @@ void settingsRejectNonsense() { @Test void newJavaGetsTheNewCompilerAndOldJavaTheOldOne() { - LibraryManager modern = mock(LibraryManager.class); - LibraryManager legacy = mock(LibraryManager.class); + assertSame(RuntimeLibraries.COMPILER_MODERN, LibraryLoader.librariesFor("compiler", 21)); + assertSame(RuntimeLibraries.COMPILER_LEGACY, LibraryLoader.librariesFor("compiler", 11)); + } - LibraryLoader.loadCompiler(modern, 21); - LibraryLoader.loadCompiler(legacy, 11); + @Test + void optionalGroupsAreLoadedOnlyWhenAsked() { + LibraryManager manager = mock(LibraryManager.class); + LibraryLoader.load(manager, LOADER, LibrarySettings.DEFAULT, LIBRARY); + verify(manager, never()).loadLibrary(RuntimeLibraries.DRIVER_MYSQL[0]); - verify(modern).loadLibrary(RuntimeLibraries.COMPILER_MODERN[0]); - verify(legacy).loadLibrary(RuntimeLibraries.COMPILER_LEGACY[0]); + assertEquals(true, LibraryLoader.loadOptional("mysql")); + verify(manager).loadLibrary(RuntimeLibraries.DRIVER_MYSQL[0]); + assertEquals(false, LibraryLoader.loadOptional("nothing")); } @Test - void aCompilerThatCannotBeLoadedDoesNotStopTheServer() { + void anOptionalLibraryThatCannotBeLoadedDoesNotThrow() { LibraryManager manager = mock(LibraryManager.class); + LibraryLoader.load(manager, LOADER, LibrarySettings.DEFAULT, LIBRARY); doThrow(new RuntimeException("offline")).when(manager).loadLibrary(any(Library.class)); - LibraryLoader.loadCompiler(manager, 21); + assertEquals(false, LibraryLoader.loadOptional("compiler")); + } - verify(manager, times(1)).loadLibrary(any(Library.class)); + @Test + void optionalLoadsFromTwoThreadsNeverOverlap() throws Exception { + LibraryManager manager = mock(LibraryManager.class); + AtomicInteger running = new AtomicInteger(); + AtomicInteger overlaps = new AtomicInteger(); + doAnswer(call -> { + if (running.incrementAndGet() > 1) overlaps.incrementAndGet(); + Thread.sleep(50); + running.decrementAndGet(); + return null; + }).when(manager).loadLibrary(any(Library.class)); + LibraryLoader.load(manager, LOADER, LibrarySettings.DEFAULT, LIBRARY); + + Thread first = new Thread(() -> LibraryLoader.loadOptional("mysql")); + Thread second = new Thread(() -> LibraryLoader.loadOptional("postgres")); + first.start(); + second.start(); + first.join(); + second.join(); + + assertEquals(0, overlaps.get()); } } diff --git a/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/RuntimeLibrariesTest.java b/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/RuntimeLibrariesTest.java new file mode 100644 index 000000000..9bb757a85 --- /dev/null +++ b/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/RuntimeLibrariesTest.java @@ -0,0 +1,38 @@ +package org.pnfolder.pnlibrary.loader; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.Set; +import java.util.stream.Collectors; +import net.byteflux.libby.Library; +import org.junit.jupiter.api.Test; + +/** The light JAR packs no Adventure, so everything the runtime imports from it must be in these lists. */ +class RuntimeLibrariesTest { + private static Set names(Library[] libraries) { + return Arrays.stream(libraries).map(Library::getArtifactId).collect(Collectors.toSet()); + } + + @Test + void bukkitGetsEveryAdventureModuleTheRuntimeUses() { + Set names = names(RuntimeLibraries.BUKKIT); + for (String required : new String[] { + "adventure-api", "adventure-text-minimessage", "adventure-text-serializer-plain", + "adventure-text-serializer-legacy", "adventure-text-serializer-gson", "adventure-platform-bukkit", "kotlin-stdlib" + }) { + assertTrue(names.contains(required), "Bukkit list lacks " + required); + } + } + + @Test + void bungeeGetsEveryAdventureModuleTheRuntimeUses() { + Set names = names(RuntimeLibraries.BUNGEE); + for (String required : new String[] { + "adventure-api", "adventure-text-minimessage", "adventure-text-serializer-plain", + "adventure-text-serializer-legacy", "adventure-text-serializer-gson", "kotlin-stdlib" + }) { + assertTrue(names.contains(required), "BungeeCord list lacks " + required); + } + } +} diff --git a/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/StartupFailureTest.java b/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/StartupFailureTest.java index 8fcb853ce..1a287afec 100644 --- a/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/StartupFailureTest.java +++ b/platforms/loader/src/test/java/org/pnfolder/pnlibrary/loader/StartupFailureTest.java @@ -12,6 +12,7 @@ import org.pnfolder.pnlibrary.console.ConsoleTheme; import org.pnfolder.pnlibrary.console.ReportedFailure; +/** Checks the console card that {@link StartupFailure} prints when pnLibrary cannot start. */ class StartupFailureTest { private static final Library LIBRARY = Library.builder().groupId("org.jetbrains.kotlin").artifactId("kotlin-stdlib").version("2.1.21").build(); diff --git a/platforms/velocity/api/build.gradle.kts b/platforms/velocity/api/build.gradle.kts index b6c7a7e4e..b3bb6deb2 100644 --- a/platforms/velocity/api/build.gradle.kts +++ b/platforms/velocity/api/build.gradle.kts @@ -6,7 +6,8 @@ plugins { mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-velocity-api", project.version.toString()) pom { name.set("pnLibrary Velocity API") diff --git a/platforms/velocity/api/src/main/kotlin/org/pnfolder/pnlibrary/velocity/api/VelocityPlatform.kt b/platforms/velocity/api/src/main/kotlin/org/pnfolder/pnlibrary/velocity/api/VelocityPlatform.kt index 290bb5630..fcd7e8aa2 100644 --- a/platforms/velocity/api/src/main/kotlin/org/pnfolder/pnlibrary/velocity/api/VelocityPlatform.kt +++ b/platforms/velocity/api/src/main/kotlin/org/pnfolder/pnlibrary/velocity/api/VelocityPlatform.kt @@ -6,5 +6,4 @@ import com.velocitypowered.api.proxy.ProxyServer interface VelocityPlatform { /** Active native proxy; its registered servers and players remain directly available. */ val proxy: ProxyServer - } diff --git a/platforms/velocity/bootstrap/build.gradle.kts b/platforms/velocity/bootstrap/build.gradle.kts index a824fe40c..826db3116 100644 --- a/platforms/velocity/bootstrap/build.gradle.kts +++ b/platforms/velocity/bootstrap/build.gradle.kts @@ -18,7 +18,8 @@ tasks.withType().configureEach { useJUnitPlatform() } mavenPublishing { publishToMavenCentral() - signAllPublications() + // Without a key (a local build) the artifacts are published unsigned. + if (providers.gradleProperty("signingInMemoryKey").isPresent) signAllPublications() coordinates("io.github.pnfolder", "pnlibrary-bootstrap-velocity", project.version.toString()) pom { name.set("pnLibrary Velocity Bootstrap") diff --git a/platforms/velocity/faststats/build.gradle.kts b/platforms/velocity/faststats/build.gradle.kts index 9c1fbafae..c0879f3f0 100644 --- a/platforms/velocity/faststats/build.gradle.kts +++ b/platforms/velocity/faststats/build.gradle.kts @@ -8,7 +8,7 @@ base { archivesName = "${rootProject.property("pnlibrary.name")}-faststats-veloc dependencies { implementation(project(":modules:api")) implementation(project(":modules:core")) - implementation(project(":modules:runtime-spi")) + implementation(project(":modules:spi")) implementation(libs.faststats.velocity) { isTransitive = false } // All platform adapters share the same Java 8-compatible SDK core. implementation(libs.faststats.core.j8) diff --git a/platforms/velocity/faststats/src/main/kotlin/org/pnfolder/pnlibrary/velocity/faststats/FastStatsVelocityProvider.kt b/platforms/velocity/faststats/src/main/kotlin/org/pnfolder/pnlibrary/velocity/faststats/FastStatsVelocityProvider.kt index 2d265847e..3b0b0b0aa 100644 --- a/platforms/velocity/faststats/src/main/kotlin/org/pnfolder/pnlibrary/velocity/faststats/FastStatsVelocityProvider.kt +++ b/platforms/velocity/faststats/src/main/kotlin/org/pnfolder/pnlibrary/velocity/faststats/FastStatsVelocityProvider.kt @@ -9,6 +9,7 @@ import java.nio.file.Path /** Velocity adapter that supplies a Velocity context to the shared FastStats session. */ class FastStatsVelocityProvider { + /** Opens a FastStats session with [token] for the plugin instance [owner]; it must be registered with [server]. */ fun open( owner: Any, server: ProxyServer, diff --git a/platforms/velocity/runtime/build.gradle.kts b/platforms/velocity/runtime/build.gradle.kts index f0c8e63f6..60011cad1 100644 --- a/platforms/velocity/runtime/build.gradle.kts +++ b/platforms/velocity/runtime/build.gradle.kts @@ -10,7 +10,7 @@ base { archivesName = "${rootProject.property("pnlibrary.name")}-velocity" } dependencies { implementation(project(":modules:api")) - implementation(project(":modules:runtime-spi")) + implementation(project(":modules:spi")) implementation(project(":modules:core")) implementation(project(":platforms:velocity:api")) implementation(libs.kotlin.stdlib) @@ -125,6 +125,7 @@ val generateVelocityDescriptor by tasks.registering { | private final Path dataDirectory; | private Object runtime; | + | /** Receives the proxy services Velocity injects. */ | @Inject | public PnLibraryVelocityPlugin(ProxyServer server, Logger logger, @DataDirectory Path dataDirectory) { | this.server = server; @@ -132,15 +133,19 @@ val generateVelocityDescriptor by tasks.registering { | this.dataDirectory = dataDirectory; | } | + | /** Loads the runtime libraries, creates {@code VelocityRuntime} and starts it; a failure prints the startup card. */ | @Subscribe | public void onInitialize(ProxyInitializeEvent event) throws Exception { | LibrarySettings settings = LibrarySettings.DEFAULT; | try { | ClassLoader loader = getClass().getClassLoader(); - | LibraryLoader.load(new VelocityLibraryManager<>(logger, dataDirectory, server.getPluginManager(), this, settings.directoryFor(dataDirectory)), loader, settings, RuntimeLibraries.VELOCITY); + | String libraries = settings.directoryFor(dataDirectory); + | VelocityLibraryManager manager = + | new VelocityLibraryManager<>(logger, dataDirectory, server.getPluginManager(), this, libraries); + | LibraryLoader.load(manager, loader, settings, RuntimeLibraries.VELOCITY); | Class type = Class.forName(RUNTIME, true, loader); | Constructor constructor = type.getConstructors()[0]; - | runtime = constructor.newInstance(this, server, logger, dataDirectory); + | runtime = constructor.newInstance(this, server, dataDirectory); | invoke("onInitialize", event); | } catch (Exception | LinkageError failure) { | runtime = null; @@ -148,6 +153,7 @@ val generateVelocityDescriptor by tasks.registering { | } | } | + | /** Prints the startup failure card to the proxy console, or a one-line message if the card itself fails. */ | private void report(LibrarySettings settings, Throwable failure) { | try { | StartupFailure.report(ConsoleTheme.plain(), @@ -158,6 +164,7 @@ val generateVelocityDescriptor by tasks.registering { | } | } | + | /** Closes the runtime if it started. */ | @Subscribe | public void onShutdown(ProxyShutdownEvent event) throws Exception { | if (runtime != null) { @@ -165,6 +172,7 @@ val generateVelocityDescriptor by tasks.registering { | } | } | + | /** Calls the one-argument runtime method {@code name}; the runtime class is not visible at compile time. */ | private void invoke(String name, Object event) throws Exception { | for (Method method : runtime.getClass().getMethods()) { | if (method.getName().equals(name) && method.getParameterCount() == 1) { diff --git a/platforms/velocity/runtime/src/main/java/META-INF/MANIFEST.MF b/platforms/velocity/runtime/src/main/java/META-INF/MANIFEST.MF deleted file mode 100644 index 59499bce4..000000000 --- a/platforms/velocity/runtime/src/main/java/META-INF/MANIFEST.MF +++ /dev/null @@ -1,2 +0,0 @@ -Manifest-Version: 1.0 - diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityBStats.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityBStats.kt deleted file mode 100644 index 923caa918..000000000 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityBStats.kt +++ /dev/null @@ -1,41 +0,0 @@ -package org.pnfolder.pnlibrary.velocity - -import com.velocitypowered.api.proxy.ProxyServer -import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsClient -import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsSettings -import org.slf4j.Logger -import java.nio.file.Path - -/** What bStats needs to know about a Velocity proxy; the sending itself is shared by every platform. */ -internal object VelocityBStats { - /** Opens the sender for the plugin instance [owner], which is reported under the bStats [serviceId]. */ - fun open(owner: Any, serviceId: Int, server: ProxyServer, logger: Logger, dataDirectory: Path): BStatsClient { - val container = server.pluginManager.fromInstance(owner) - .orElseThrow { IllegalArgumentException("The provided instance is not a plugin") } - val settings = BStatsSettings.properties(dataDirectory.parent.resolve("bStats").resolve("config.txt").toFile()) - if (settings.createdNow) { - logger.info("Velocity and some of its plugins collect metrics and send them to bStats (https://bStats.org).") - logger.info("bStats collects some basic information for plugin authors, like how many people use") - logger.info("their plugin and their total player count. It's recommend to keep bStats enabled, but") - logger.info("if you're not comfortable with this, you can opt-out by editing the config.txt file in") - logger.info("the '/plugins/bStats/' folder and setting enabled to false.") - } - return BStatsClient( - platform = "velocity", - serviceId = serviceId, - settings = settings, - pluginVersion = container.description.version.orElse("unknown"), - appendPlatformData = { data -> - data.appendField("playerAmount", server.playerCount) - data.appendField("managedServers", server.allServers.size) - data.appendField("onlineMode", if (server.configuration.isOnlineMode) 1 else 0) - data.appendField("velocityVersionVersion", server.version.version) - data.appendField("velocityVersionName", server.version.name) - data.appendField("velocityVersionVendor", server.version.vendor) - }, - mainThread = { task -> server.scheduler.buildTask(owner, task).schedule() }, - warn = { message, error -> logger.warn(message, error) }, - info = logger::info, - ) - } -} diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLibraryPlayer.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLibraryPlayer.kt deleted file mode 100644 index b778fc351..000000000 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLibraryPlayer.kt +++ /dev/null @@ -1,54 +0,0 @@ -package org.pnfolder.pnlibrary.velocity - -import com.velocitypowered.api.proxy.Player -import net.kyori.adventure.sound.Sound -import net.kyori.adventure.text.Component -import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer -import org.pnfolder.pnlibrary.api.audiences.PlayerCapability -import org.pnfolder.pnlibrary.api.audiences.PlayerEffect -import org.pnfolder.pnlibrary.api.audiences.PlayerParticle -import java.util.UUID - -/** - * [LibraryPlayer] bridge backed by a Velocity [Player]. - * - * Velocity accepts Adventure components and sounds directly. Potion effects and particles are - * server-side operations unavailable to the proxy and therefore return `false`. - */ -internal class VelocityLibraryPlayer private constructor( - private val player: Player, -) : LibraryPlayer { - override val capabilities: Set = setOf( - PlayerCapability.MESSAGE, - PlayerCapability.ACTION_BAR, - PlayerCapability.SOUND, - ) - override val uniqueId: UUID - get() = player.uniqueId - - override val name: String - get() = player.username - - override fun hasPermission(permission: String): Boolean = player.hasPermission(permission) - - override fun sendMessage(text: Component) = player.sendMessage(text) - - override fun actionBar(text: Component) = player.sendActionBar(text) - - override fun playSound(sound: Sound): Delivery { - player.playSound(sound) - return Delivery.Delivered - } - - /** Velocity cannot apply server-side potion effects through its proxy API. */ - override fun applyEffect(effect: PlayerEffect): Delivery = Delivery.Unsupported - - /** Velocity cannot spawn server-side particles through its proxy API. */ - override fun spawnParticle(particle: PlayerParticle): Delivery = Delivery.Unsupported - - companion object { - @JvmStatic - fun of(player: Player): LibraryPlayer = VelocityLibraryPlayer(player) - } -} diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityMetricsFactory.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityMetricsFactory.kt deleted file mode 100644 index 0778e96e3..000000000 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityMetricsFactory.kt +++ /dev/null @@ -1,44 +0,0 @@ -package org.pnfolder.pnlibrary.velocity - -import com.velocitypowered.api.proxy.ProxyServer -import org.pnfolder.pnlibrary.api.metrics.PluginMetrics -import org.pnfolder.pnlibrary.core.metrics.ProviderMetricsFactory -import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsMetricsSession -import org.slf4j.Logger -import java.lang.reflect.InvocationTargetException -import java.nio.file.Path - -/** Creates bStats and FastStats sessions for Velocity using explicit platform adapters. */ -internal class VelocityMetricsFactory( - private val server: ProxyServer, - private val logger: Logger, - private val dataDirectory: Path, -) : ProviderMetricsFactory() { - - override fun openBStats(owner: Any, projectId: Int): PluginMetrics { - val client = VelocityBStats.open(owner, projectId, server, logger, dataDirectory) - return BStatsMetricsSession(projectId, client::addCustomChart, client::shutdown) - } - - /** - * FastStats on Velocity is compiled for Java 21. It is loaded by name and never referenced directly, so a - * Java 17 proxy never links it: the check below rejects the run before the class is touched. - */ - override fun openFastStats(owner: Any, token: String): PluginMetrics { - check(Runtime.version().feature() >= 21) { - "FastStats on Velocity requires Java 21 or newer" - } - return try { - val type = Class.forName(FASTSTATS_PROVIDER, true, javaClass.classLoader) - val provider = type.getConstructor().newInstance() - type.getMethod("open", Any::class.java, ProxyServer::class.java, Logger::class.java, Path::class.java, String::class.java) - .invoke(provider, owner, server, logger, dataDirectory, token) as PluginMetrics - } catch (error: InvocationTargetException) { - throw error.targetException - } - } - - private companion object { - const val FASTSTATS_PROVIDER = "org.pnfolder.pnlibrary.velocity.faststats.FastStatsVelocityProvider" - } -} diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlatformAdapter.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlatformAdapter.kt index 8c4c47ab5..2615929f0 100644 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlatformAdapter.kt +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlatformAdapter.kt @@ -1,49 +1,61 @@ package org.pnfolder.pnlibrary.velocity +import com.velocitypowered.api.plugin.PluginContainer import com.velocitypowered.api.proxy.ProxyServer import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer import org.pnfolder.pnlibrary.api.logging.LogLevel import org.pnfolder.pnlibrary.api.platform.PlatformType import org.pnfolder.pnlibrary.api.remote.RemotePolicyContext -import org.pnfolder.pnlibrary.api.tasks.TaskExecution import org.pnfolder.pnlibrary.spi.commands.PlatformCommandAdapter import org.pnfolder.pnlibrary.spi.metrics.PlatformMetricsFactory -import org.pnfolder.pnlibrary.spi.platform.PlatformAdapter -import org.pnfolder.pnlibrary.spi.platform.PlatformLifecycle +import org.pnfolder.pnlibrary.spi.platform.PlatformPlugins import org.pnfolder.pnlibrary.spi.platform.PlatformSnapshot import org.pnfolder.pnlibrary.spi.platform.PluginSnapshot -import org.pnfolder.pnlibrary.spi.platform.StartupGate -import org.pnfolder.pnlibrary.spi.platform.UncaughtExceptionLogObserver +import org.pnfolder.pnlibrary.spi.platform.ProxyPlatformAdapter import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskAdapter -import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest import org.pnfolder.pnlibrary.velocity.commands.VelocityCommandAdapter +import org.pnfolder.pnlibrary.velocity.diagnostics.VelocityDiagnosticDetailsCollector +import org.pnfolder.pnlibrary.velocity.log.VelocityLogObserver +import org.pnfolder.pnlibrary.velocity.network.VelocityAudienceAdapter +import org.pnfolder.pnlibrary.velocity.network.VelocityNetworkProxy import org.pnfolder.pnlibrary.velocity.remote.VelocityRemotePolicyContextFactory import org.pnfolder.pnlibrary.velocity.tasks.VelocityTaskAdapter -import org.slf4j.Logger +import org.slf4j.LoggerFactory import java.nio.file.Path -import java.time.Duration +import kotlin.jvm.optionals.getOrDefault /** * Runtime adapter for Velocity proxy servers. * * Composes native command, task, audience, plugin metadata and diagnostics bridges. - * Consumer tasks carry their own plugin owner; internal global/reply work belongs to [plugin]. * Startup-dependent callbacks wait for [markReady], called by the plugin entry point after * runtime creation and native API registration. Velocity has no entity-region scheduler. */ internal class VelocityPlatformAdapter( + /** The pnLibrary plugin; every task and internal work such as global tasks runs on its behalf. */ private val plugin: Any, private val proxy: ProxyServer, override val metricsFactory: PlatformMetricsFactory, override val dataFolder: Path, - logger: Logger, -) : PlatformAdapter { +) : ProxyPlatformAdapter(plugin) { + private val nativeLogger = LoggerFactory.getLogger(plugin::class.java) private val diagnosticDetailsCollector = VelocityDiagnosticDetailsCollector(proxy) - private val lifecycle = PlatformLifecycle() - private val plugins = velocityPlugins(proxy) - private val startup = StartupGate(lifecycle, ::executeGlobal) + private val legacySerializer = LegacyComponentSerializer.legacySection() + + private val plugins = PlatformPlugins( + platformName = "Velocity", + installed = { proxy.pluginManager.plugins }, + resolve = { owner -> proxy.pluginManager.fromInstance(owner).orElse(null) }, + ) { container -> + val description = container.description + PluginSnapshot( + id = description.id, + name = description.name.getOrDefault(description.id), + version = description.version.getOrDefault("unknown"), + authors = description.authors, + ) + } - private val uncaughtExceptionObserver = UncaughtExceptionLogObserver(plugin) private val logObserver = VelocityLogObserver( plugin, pluginInstances = { proxy.pluginManager.plugins.mapNotNull { it.instance.orElse(null) } }, @@ -55,6 +67,8 @@ internal class VelocityPlatformAdapter( override val implementationName: String get() = proxy.version.name.ifBlank { type.displayName } + override val networkProxy: VelocityNetworkProxy = VelocityNetworkProxy(proxy) + override val audienceAdapter: VelocityAudienceAdapter = VelocityAudienceAdapter(proxy) @@ -62,47 +76,29 @@ internal class VelocityPlatformAdapter( VelocityCommandAdapter(proxy, audienceAdapter) override val taskAdapter: PlatformTaskAdapter = - VelocityTaskAdapter( - server = proxy, - describeOwner = { owner -> - owner?.let { proxy.pluginManager.fromInstance(it).orElse(null)?.description?.name?.orElse(null) } - ?: owner?.javaClass?.simpleName - ?: "неизвестен" - }, - warning = { message -> logger.error(message) }, - ) + VelocityTaskAdapter(proxy, plugin, ::warn) override val logHandler: (Any, LogLevel, String, Throwable?) -> Unit = { _, level, message, error -> - logObserver.runOwn { - when (level) { - LogLevel.WARNING -> logger.warn(message, error) - LogLevel.ERROR, LogLevel.CRITICAL -> logger.error(message, error) - else -> logger.info(message, error) - } + when (level) { + LogLevel.WARNING -> nativeLogger.warn(message, error) + LogLevel.ERROR, LogLevel.CRITICAL -> nativeLogger.error(message, error) + else -> nativeLogger.info(message, error) } } - override fun console(owner: Any, message: String) { - proxy.consoleCommandSource.sendMessage( - LEGACY_SERIALIZER.deserialize(message), - ) + override fun observeProxyLogs(observer: ((Any, LogLevel, String, Throwable?) -> Unit)?) { + logObserver.observe(observer) } - /** Forwards proxy and plugin warnings/errors and uncaught JVM exceptions, or stops doing so. */ - @Synchronized - override fun observeNativeLogs(observer: ((Any, LogLevel, String, Throwable?) -> Unit)?) { - if (observer != null) lifecycle.checkOpen() - logObserver.observe(observer) - uncaughtExceptionObserver.observe(observer) + override fun console(owner: Any, message: String) { + proxy.consoleCommandSource.sendMessage(legacySerializer.deserialize(message)) } override fun ownerMetadata(owner: Any): PluginSnapshot? = plugins.metadata(owner, this) - override fun installedPlugins(): Map = - plugins.versions() + override fun installedPlugins(): Map = plugins.versions() - /** Captures a lightweight, non-sensitive snapshot of the proxy. */ override fun snapshot(): PlatformSnapshot { val platformVersion = proxy.version @@ -122,40 +118,15 @@ internal class VelocityPlatformAdapter( override fun remotePolicyContext( owner: Any, values: Map, - ): RemotePolicyContext = - VelocityRemotePolicyContextFactory.create(owner, plugins.requireInstalled(owner, "Remote policy owner"), proxy, values) - - override fun executeGlobal(task: Runnable) { - if (lifecycle.isClosed) { - return - } - - taskAdapter.schedule(PlatformTaskRequest( - TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, task, plugin, - )) - } - - /** Defers startup-dependent work until the entry point has published the native API. */ - override fun whenServerReady(task: Runnable) { - startup.whenReady(task) - } - - /** Called once the runtime and Velocity API registration both succeeded. */ - internal fun markReady() { - startup.markReady() - } - - override fun executeReply(recipient: Any, task: Runnable) { - executeGlobal(task) + ): RemotePolicyContext { + val installed = plugins.requireInstalled(owner, "Remote policy owner") + return VelocityRemotePolicyContextFactory.create(owner, installed, proxy, values) } - /** Discards pending startup work, cancels native tasks and stops native log observation once. */ - override fun close() { - lifecycle.closeAdapter(startup, taskAdapter) { observeNativeLogs(null) } - } + /** Dispatches work on Velocity's scheduler on behalf of the pnLibrary plugin. */ + override fun executeGlobal(task: Runnable) { + if (lifecycle.isClosed) return - private companion object { - val LEGACY_SERIALIZER: LegacyComponentSerializer = - LegacyComponentSerializer.legacySection() + taskAdapter.buildTask().task(task).schedule() } } diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlatformServices.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlatformServices.kt deleted file mode 100644 index a658f85bf..000000000 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlatformServices.kt +++ /dev/null @@ -1,9 +0,0 @@ -package org.pnfolder.pnlibrary.velocity - -import com.velocitypowered.api.proxy.ProxyServer -import org.pnfolder.pnlibrary.velocity.api.VelocityPlatform - -/** Native-backed Velocity platform API installed by the Velocity runtime. */ -internal class VelocityPlatformServices( - override val proxy: ProxyServer, -) : VelocityPlatform diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlugins.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlugins.kt deleted file mode 100644 index 5b75aed94..000000000 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlugins.kt +++ /dev/null @@ -1,21 +0,0 @@ -package org.pnfolder.pnlibrary.velocity - -import com.velocitypowered.api.plugin.PluginContainer -import com.velocitypowered.api.proxy.ProxyServer -import org.pnfolder.pnlibrary.spi.platform.PlatformPlugins -import org.pnfolder.pnlibrary.spi.platform.PluginSnapshot - -/** Velocity plugins, resolved from their instances and described by their plugin descriptions. */ -internal fun velocityPlugins(proxy: ProxyServer): PlatformPlugins = PlatformPlugins( - platformName = "Velocity", - installed = { proxy.pluginManager.plugins }, - resolve = { owner -> proxy.pluginManager.fromInstance(owner).orElse(null) }, -) { container -> - val description = container.description - PluginSnapshot( - id = description.id, - name = description.name.orElse(description.id), - version = description.version.orElse("unknown"), - authors = description.authors, - ) -} diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityRuntime.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityRuntime.kt index c656b4468..2352fdf33 100644 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityRuntime.kt +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityRuntime.kt @@ -3,15 +3,18 @@ package org.pnfolder.pnlibrary.velocity import com.velocitypowered.api.event.proxy.ProxyInitializeEvent import com.velocitypowered.api.event.proxy.ProxyShutdownEvent import com.velocitypowered.api.proxy.ProxyServer -import com.velocitypowered.api.scheduler.ScheduledTask +import org.pnfolder.pnlibrary.api.logging.PnLogger import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.core.menu.OwnerInfo -import org.pnfolder.pnlibrary.core.proxy.ProxyLink +import org.pnfolder.pnlibrary.core.exceptions.ResourceCleanup +import org.pnfolder.pnlibrary.core.link.LinkReceiver +import org.pnfolder.pnlibrary.core.runtime.PnLibraryRuntime import org.pnfolder.pnlibrary.core.runtime.PnLibraryRuntimeHost +import org.pnfolder.pnlibrary.core.runtime.ProxyRuntime import org.pnfolder.pnlibrary.velocity.api.VelocityPlatform -import org.slf4j.Logger +import org.pnfolder.pnlibrary.velocity.link.VelocityLinkListener +import org.pnfolder.pnlibrary.velocity.metrics.VelocityMetricsFactory +import org.pnfolder.pnlibrary.velocity.network.VelocityPlayerEvents import java.nio.file.Path -import java.util.concurrent.TimeUnit /** * Velocity runtime behind the generated `PnLibraryVelocityPlugin` descriptor class. @@ -23,105 +26,67 @@ import java.util.concurrent.TimeUnit internal class VelocityRuntime( private val owner: Any, private val server: ProxyServer, - private val logger: Logger, private val dataDirectory: Path, ) { + private var proxyRuntime: ProxyRuntime? = null private var runtimeHost: PnLibraryRuntimeHost? = null private var playerEvents: VelocityPlayerEvents? = null - private var linkListener: VelocityLinkListener? = null - private var link: ProxyLink? = null - private var networkTask: ScheduledTask? = null - /** - * Starts the shared runtime when Velocity announces proxy initialization. - * - * @param event lifecycle signal supplied by Velocity; its payload is not required - */ - @Suppress("UNUSED_PARAMETER") - fun onInitialize(event: ProxyInitializeEvent) { + /** Starts the shared runtime when Velocity announces proxy initialization. */ + fun onInitialize(@Suppress("UNUSED_PARAMETER") event: ProxyInitializeEvent) { check(runtimeHost == null) { "Velocity runtime is already initialized" } try { open() } catch (error: Throwable) { - // Whatever opened before the failure must not stay registered on a proxy that goes on without us. - runCatchingNonFatal(::close) + runCatchingNonFatal(::close).onFailure(error::addSuppressed) throw error } } private fun open() { + var metricsLogger: PnLogger? = null val adapter = VelocityPlatformAdapter( plugin = owner, proxy = server, - metricsFactory = VelocityMetricsFactory(server, logger, dataDirectory), + metricsFactory = VelocityMetricsFactory(server, dataDirectory) { metricsLogger!! }, dataFolder = dataDirectory, - logger = logger, ) - val started = PnLibraryRuntimeHost.launchPlatform( - owner, - adapter, - VelocityPlatform::class.java, - VelocityPlatformServices(server), - adapter::markReady, - ) - runtimeHost = started - val listener = VelocityPlayerEvents(started.library) - server.eventManager.register(owner, listener) - playerEvents = listener - connectLink(started) + val host = PnLibraryRuntime.builder() + .owner(owner) + .adapter(adapter) + .platform(object : VelocityPlatform { override val proxy get() = server }) + .launch(adapter::markReady) + runtimeHost = host + metricsLogger = host.library.logging.logger(owner, "Metrics") + + val proxy = ProxyRuntime(adapter, ::registerLinkListener, adapter.networkProxy::describePlugin) + proxyRuntime = proxy + proxy.start(host) + + playerEvents = VelocityPlayerEvents(host.library).also { server.eventManager.register(owner, it) } } - /** Opens the link to the game servers and, when it is secured, starts announcing this proxy. */ - private fun connectLink(started: PnLibraryRuntimeHost) { - val proxyLink = ProxyLink( - library = started.library, - folder = dataDirectory, - warn = logger::warn, - transport = { name, bytes -> - server.getServer(name).map { it.sendPluginMessage(VelocityLinkListener.CHANNEL, bytes) }.orElse(false) - }, - describe = { instance -> - instance?.let { server.pluginManager.fromInstance(it).orElse(null)?.description }?.let { description -> - OwnerInfo(description.name.orElse(description.id), description.version.orElse(null), description.authors) - } - }, - platformName = { "Velocity ${server.version.version}" }, - players = { server.playerCount }, - broadcast = { message -> server.allServers.forEach { runCatchingNonFatal { it.sendPluginMessage(VelocityLinkListener.CHANNEL, message) } } }, - ) - link = proxyLink - val listener = VelocityLinkListener(proxyLink.receiver) - server.channelRegistrar.register(VelocityLinkListener.CHANNEL) + private fun registerLinkListener(receiver: LinkReceiver): AutoCloseable { + val listener = VelocityLinkListener(receiver) server.eventManager.register(owner, listener) - linkListener = listener - if (proxyLink.announces) { - networkTask = server.scheduler.buildTask(owner, Runnable(proxyLink::announce)) - .delay(ProxyLink.NETWORK_DELAY_SECONDS, TimeUnit.SECONDS) - .repeat(ProxyLink.NETWORK_PERIOD_SECONDS, TimeUnit.SECONDS) - .schedule() - } + return AutoCloseable { server.eventManager.unregisterListener(owner, listener) } } - /** - * Closes the runtime before the proxy completes shutdown. - * - * @param event lifecycle signal supplied by Velocity; its payload is not required - */ - @Suppress("UNUSED_PARAMETER") - fun onShutdown(event: ProxyShutdownEvent) = close() + /** Closes the runtime before the proxy completes shutdown. */ + fun onShutdown(@Suppress("UNUSED_PARAMETER") event: ProxyShutdownEvent) = close() private fun close() { - playerEvents?.let { runCatchingNonFatal { server.eventManager.unregisterListener(owner, it) } } - playerEvents = null - networkTask?.cancel() - networkTask = null - linkListener?.let { runCatchingNonFatal { server.eventManager.unregisterListener(owner, it) } } - linkListener = null - link?.let { runCatchingNonFatal(it::close) } - link = null - runCatchingNonFatal { server.channelRegistrar.unregister(VelocityLinkListener.CHANNEL) } + val events = playerEvents + val proxy = proxyRuntime val host = runtimeHost + playerEvents = null + proxyRuntime = null runtimeHost = null - host?.close() + + ResourceCleanup.closeAll( + { events?.let { server.eventManager.unregisterListener(owner, it) } }, + { proxy?.close() }, + { host?.close() }, + ) } } diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/commands/VelocityCommandAdapter.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/commands/VelocityCommandAdapter.kt index aae2f6d36..f5f93f3ed 100644 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/commands/VelocityCommandAdapter.kt +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/commands/VelocityCommandAdapter.kt @@ -3,21 +3,16 @@ package org.pnfolder.pnlibrary.velocity.commands import com.velocitypowered.api.command.CommandSource import com.velocitypowered.api.command.SimpleCommand import com.velocitypowered.api.proxy.ProxyServer -import net.kyori.adventure.sound.Sound -import net.kyori.adventure.text.Component import org.pnfolder.pnlibrary.api.audiences.AudienceSender -import org.pnfolder.pnlibrary.api.audiences.Delivery import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.CommandSender -import org.pnfolder.pnlibrary.core.commands.proxy.ProxyCommandNames +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.core.commands.proxy.proxyCommandContext import org.pnfolder.pnlibrary.spi.commands.GenericPlatformCommandAdapter import org.pnfolder.pnlibrary.spi.commands.NativeCommandRegistrar import org.pnfolder.pnlibrary.spi.commands.PlatformCommandRegistration -import org.pnfolder.pnlibrary.velocity.VelocityAudienceAdapter +import org.pnfolder.pnlibrary.velocity.network.VelocityAudienceAdapter import java.util.concurrent.CompletionStage -/** Bridges portable pnLibrary commands to the native Velocity command manager. */ internal class VelocityCommandAdapter internal constructor( override val registrar: NativeCommandRegistrar, private val audience: (CommandSource) -> AudienceSender, @@ -36,31 +31,9 @@ internal class VelocityCommandAdapter internal constructor( source: CommandSource, alias: String, arguments: Array, - ): CommandContext = CommandContext( - sender = VelocityCommandSender(audience(source), ProxyCommandNames.owns(alias)), - arguments = arguments.toList(), - invokedAlias = alias, - currentInput = arguments.lastOrNull().orEmpty(), - ) - -} - -/** Adapts a portable command sender to the native Velocity audience. */ -private class VelocityCommandSender( - private val audience: AudienceSender, - private val proxyControl: Boolean, -) : CommandSender, AudienceSender by audience { - override fun send(message: Component) = audience.sendMessage(shown(message)) - - // Explicit overrides preserve native delivery instead of CommandSender's fallback defaults. - override fun sendMessage(text: Component) = audience.sendMessage(shown(text)) - - private fun shown(message: Component) = if (proxyControl) ProxyCommandNames.rewrite(message) else message - override fun actionBar(text: Component) = audience.actionBar(text) - override fun playSound(sound: Sound): Delivery = audience.playSound(sound) + ): CommandContext = proxyCommandContext(audience(source), alias, arguments) } -/** Default registrar backed by Velocity's command manager. */ private class DefaultVelocityNativeCommandRegistrar( private val server: ProxyServer, ) : NativeCommandRegistrar { @@ -74,7 +47,7 @@ private class DefaultVelocityNativeCommandRegistrar( require(server.pluginManager.fromInstance(owner).isPresent) { "Command owner must be a registered Velocity plugin" } - (listOf(command.name) + command.aliases).forEach { name -> + for (name in listOf(command.name) + command.aliases) { require(!server.commandManager.hasCommand(name)) { "Command name or alias '$name' is already registered on Velocity" } @@ -85,16 +58,13 @@ private class DefaultVelocityNativeCommandRegistrar( .build() server.commandManager.register(metadata, object : SimpleCommand { - override fun execute(invocation: SimpleCommand.Invocation) { + override fun execute(invocation: SimpleCommand.Invocation) = execute(invocation.source(), invocation.alias(), invocation.arguments()) - } override fun suggestAsync(invocation: SimpleCommand.Invocation) = suggest(invocation.source(), invocation.alias(), invocation.arguments()).toCompletableFuture() }) - return PlatformCommandRegistration { - server.commandManager.unregister(metadata) - } + return PlatformCommandRegistration { server.commandManager.unregister(metadata) } } } diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityDiagnosticDetailsCollector.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/diagnostics/VelocityDiagnosticDetailsCollector.kt similarity index 91% rename from platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityDiagnosticDetailsCollector.kt rename to platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/diagnostics/VelocityDiagnosticDetailsCollector.kt index 7a5324c6e..27e9a52ce 100644 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityDiagnosticDetailsCollector.kt +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/diagnostics/VelocityDiagnosticDetailsCollector.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.velocity +package org.pnfolder.pnlibrary.velocity.diagnostics import com.velocitypowered.api.proxy.ProxyServer import org.pnfolder.pnlibrary.spi.platform.DiagnosticDetailsCollector @@ -10,6 +10,7 @@ import org.pnfolder.pnlibrary.spi.platform.ProxyBackend internal class VelocityDiagnosticDetailsCollector( private val server: ProxyServer, ) { + /** Adds proxy plugins, backend servers and player pings to [snapshot]; sensitive values only when [includeSensitive]. */ fun collect(snapshot: PlatformSnapshot, includeSensitive: Boolean): Map = DiagnosticDetailsCollector { snapshot }.collect(includeSensitive) { details -> val plugins = server.pluginManager.plugins diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLinkListener.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/link/VelocityLinkListener.kt similarity index 77% rename from platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLinkListener.kt rename to platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/link/VelocityLinkListener.kt index 404c58740..60fb53cd4 100644 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLinkListener.kt +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/link/VelocityLinkListener.kt @@ -1,13 +1,12 @@ -package org.pnfolder.pnlibrary.velocity +package org.pnfolder.pnlibrary.velocity.link import com.velocitypowered.api.event.Subscribe import com.velocitypowered.api.event.connection.PluginMessageEvent import com.velocitypowered.api.proxy.ServerConnection import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier -import org.pnfolder.pnlibrary.core.link.LinkCodec import org.pnfolder.pnlibrary.core.link.LinkReceiver +import org.pnfolder.pnlibrary.core.link.wire.LinkCodec -/** Takes the reports that game servers send on the pnLibrary link channel; messages from players are dropped. */ internal class VelocityLinkListener(private val receiver: LinkReceiver) { @Subscribe fun onMessage(event: PluginMessageEvent) { @@ -19,7 +18,6 @@ internal class VelocityLinkListener(private val receiver: LinkReceiver) { } companion object { - /** The link channel as Velocity names it. */ val CHANNEL: MinecraftChannelIdentifier = MinecraftChannelIdentifier.from(LinkCodec.CHANNEL) } } diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLogObserver.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/log/VelocityLogObserver.kt similarity index 90% rename from platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLogObserver.kt rename to platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/log/VelocityLogObserver.kt index c88d790a1..dfcb887d0 100644 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLogObserver.kt +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/log/VelocityLogObserver.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.velocity +package org.pnfolder.pnlibrary.velocity.log import org.apache.logging.log4j.Level import org.apache.logging.log4j.LogManager @@ -8,6 +8,7 @@ import org.apache.logging.log4j.core.LoggerContext import org.apache.logging.log4j.core.appender.AbstractAppender import org.apache.logging.log4j.core.config.Property import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.spi.platform.OwnLogScope /** * Forwards WARN and ERROR events of Velocity's Log4j2 backend to the shared log observation contract. @@ -21,7 +22,7 @@ internal class VelocityLogObserver( private val pluginById: (String) -> Any? = { null }, private val pluginInstances: () -> Collection, ) { - private val ownLogCall = ThreadLocal.withInitial { false } + private val ownLogs = OwnLogScope() @Volatile private var callback: ((Any, LogLevel, String, Throwable?) -> Unit)? = null @@ -35,15 +36,7 @@ internal class VelocityLogObserver( } /** Runs [block] while events produced by this thread are treated as the library's own. */ - fun runOwn(block: () -> T): T { - val previous = ownLogCall.get() - ownLogCall.set(true) - try { - return block() - } finally { - ownLogCall.set(previous) - } - } + fun runOwn(block: () -> T): T = ownLogs.run(block) /** Returns the plugin whose main-class package is the longest prefix of [loggerName]. */ internal fun resolveOwner(loggerName: String?): Any? { @@ -82,7 +75,7 @@ internal class VelocityLogObserver( } private fun accept(event: LogEvent) { - if (ownLogCall.get() || !event.level.isMoreSpecificThan(Level.WARN)) return + if (ownLogs.isActive || !event.level.isMoreSpecificThan(Level.WARN)) return val level = if (event.level.isMoreSpecificThan(Level.ERROR)) LogLevel.ERROR else LogLevel.WARNING val owner = resolveOwner(event.loggerName) ?: fallbackOwner callback?.invoke(owner, level, event.message?.formattedMessage ?: "Native platform error", event.thrown) diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/metrics/VelocityMetricsFactory.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/metrics/VelocityMetricsFactory.kt new file mode 100644 index 000000000..da8738bdc --- /dev/null +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/metrics/VelocityMetricsFactory.kt @@ -0,0 +1,82 @@ +package org.pnfolder.pnlibrary.velocity.metrics + +import com.velocitypowered.api.proxy.ProxyServer +import org.pnfolder.pnlibrary.api.logging.PnLogger +import org.pnfolder.pnlibrary.api.metrics.PluginMetrics +import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsClient +import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsMetricsSession +import org.pnfolder.pnlibrary.core.metrics.bstats.BStatsSettings +import org.pnfolder.pnlibrary.core.metrics.factory.ProviderMetricsFactory +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import java.lang.reflect.InvocationTargetException +import java.nio.file.Path + +/** Creates bStats and FastStats sessions for Velocity using explicit platform adapters. */ +internal class VelocityMetricsFactory( + private val server: ProxyServer, + private val dataDirectory: Path, + /** Provides the library logger for user-visible messages; resolved after the host is built. */ + private val pnLogger: () -> PnLogger, +) : ProviderMetricsFactory() { + private val nativeLogger = LoggerFactory.getLogger(VelocityMetricsFactory::class.java) + + /** Opens a bStats session for the plugin instance [owner] under [projectId]. */ + override fun openBStats(owner: Any, projectId: Int): PluginMetrics { + val client = openBStats(owner, projectId, server, pnLogger(), dataDirectory) + return BStatsMetricsSession(projectId, client::addCustomChart, client::shutdown) + } + + /** + * FastStats on Velocity is compiled for Java 21. It is loaded by name and never referenced directly, so a + * Java 17 proxy never links it: the check below rejects the run before the class is touched. + */ + override fun openFastStats(owner: Any, token: String): PluginMetrics { + check(Runtime.version().feature() >= 21) { + "FastStats on Velocity requires Java 21 or newer" + } + return try { + val type = Class.forName(FASTSTATS_PROVIDER, true, javaClass.classLoader) + val provider = type.getConstructor().newInstance() + type.getMethod("open", Any::class.java, ProxyServer::class.java, Logger::class.java, Path::class.java, String::class.java) + .invoke(provider, owner, server, nativeLogger, dataDirectory, token) as PluginMetrics + } catch (error: InvocationTargetException) { + throw error.targetException + } + } + + private companion object { + const val FASTSTATS_PROVIDER = "org.pnfolder.pnlibrary.velocity.faststats.FastStatsVelocityProvider" + } +} + +/** Opens the bStats sender for the plugin instance [owner], which is reported under the bStats [serviceId]; the sending itself is shared by every platform. */ +private fun openBStats(owner: Any, serviceId: Int, server: ProxyServer, log: PnLogger, dataDirectory: Path): BStatsClient { + val container = server.pluginManager.fromInstance(owner) + .orElseThrow { IllegalArgumentException("The provided instance is not a plugin") } + val settings = BStatsSettings.properties(dataDirectory.parent.resolve("bStats").resolve("config.txt").toFile()) + if (settings.createdNow) { + log.info("Velocity and some of its plugins collect metrics and send them to bStats (https://bStats.org).") + log.info("bStats collects some basic information for plugin authors, like how many people use") + log.info("their plugin and their total player count. It's recommend to keep bStats enabled, but") + log.info("if you're not comfortable with this, you can opt-out by editing the config.txt file in") + log.info("the '/plugins/bStats/' folder and setting enabled to false.") + } + return BStatsClient( + platform = "velocity", + serviceId = serviceId, + settings = settings, + pluginVersion = container.description.version.orElse("unknown"), + appendPlatformData = { data -> + data.appendField("playerAmount", server.playerCount) + data.appendField("managedServers", server.allServers.size) + data.appendField("onlineMode", if (server.configuration.isOnlineMode) 1 else 0) + data.appendField("velocityVersionVersion", server.version.version) + data.appendField("velocityVersionName", server.version.name) + data.appendField("velocityVersionVendor", server.version.vendor) + }, + mainThread = { task -> server.scheduler.buildTask(owner, task).schedule() }, + warn = { message, error -> log.warning(message, error) }, + info = log::info, + ) +} diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityAudienceAdapter.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/network/VelocityAudienceAdapter.kt similarity index 71% rename from platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityAudienceAdapter.kt rename to platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/network/VelocityAudienceAdapter.kt index c59241a64..57a2dcae4 100644 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityAudienceAdapter.kt +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/network/VelocityAudienceAdapter.kt @@ -1,4 +1,4 @@ -package org.pnfolder.pnlibrary.velocity +package org.pnfolder.pnlibrary.velocity.network import com.velocitypowered.api.command.CommandSource import com.velocitypowered.api.proxy.ConsoleCommandSource @@ -8,31 +8,28 @@ import net.kyori.adventure.sound.Sound import net.kyori.adventure.text.Component import org.pnfolder.pnlibrary.api.audiences.AudienceSender import org.pnfolder.pnlibrary.api.audiences.Delivery -import org.pnfolder.pnlibrary.api.audiences.LibraryPlayer +import org.pnfolder.pnlibrary.api.network.NetworkPlayer import org.pnfolder.pnlibrary.spi.audiences.PlatformAudienceAdapter import java.util.UUID -/** Adapts Velocity command sources and players to pnLibrary audiences. */ internal class VelocityAudienceAdapter( private val server: ProxyServer, ) : PlatformAudienceAdapter { override fun console(): AudienceSender = wrap(server.consoleCommandSource) - override fun player(uniqueId: UUID): LibraryPlayer? = - server.getPlayer(uniqueId).orElse(null)?.let(VelocityLibraryPlayer::of) + override fun player(uniqueId: UUID): NetworkPlayer? = + server.getPlayer(uniqueId).orElse(null)?.let(VelocityNetworkPlayer::of) - /** Adapts a native Velocity command source when its type is supported. */ override fun sender(native: Any): AudienceSender? = when (native) { - is Player -> VelocityLibraryPlayer.of(native) + is Player -> VelocityNetworkPlayer.of(native) is CommandSource -> wrap(native) else -> null } - override fun onlinePlayers(): List = - server.allPlayers.map(VelocityLibraryPlayer::of) + override fun onlinePlayers(): List = + server.allPlayers.map(VelocityNetworkPlayer::of) - /** Creates a portable audience backed by [source]. */ private fun wrap(source: CommandSource): AudienceSender = object : AudienceSender { override val id: String = source.toString() override val name: String = source.toString() diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/network/VelocityNetworkPlayer.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/network/VelocityNetworkPlayer.kt new file mode 100644 index 000000000..abc3804d6 --- /dev/null +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/network/VelocityNetworkPlayer.kt @@ -0,0 +1,47 @@ +package org.pnfolder.pnlibrary.velocity.network + +import com.velocitypowered.api.proxy.Player +import net.kyori.adventure.sound.Sound +import net.kyori.adventure.text.Component +import org.pnfolder.pnlibrary.api.audiences.Delivery +import org.pnfolder.pnlibrary.api.audiences.player.PlayerCapability +import org.pnfolder.pnlibrary.api.audiences.player.PlayerEffect +import org.pnfolder.pnlibrary.api.audiences.player.PlayerParticle +import org.pnfolder.pnlibrary.api.network.NetworkPlayer +import org.pnfolder.pnlibrary.api.network.NetworkServer +import java.net.InetSocketAddress +import java.util.UUID + +internal class VelocityNetworkPlayer( + internal val native: Player, +) : NetworkPlayer { + + override val capabilities: Set = setOf( + PlayerCapability.MESSAGE, + PlayerCapability.ACTION_BAR, + PlayerCapability.SOUND, + ) + + override val uniqueId: UUID get() = native.uniqueId + override val name: String get() = native.username + override val address: InetSocketAddress get() = native.remoteAddress + override val ping: Long get() = native.ping + override val currentServer: NetworkServer? + get() = native.currentServer.orElse(null)?.server?.let(::VelocityNetworkServer) + + override fun hasPermission(permission: String): Boolean = native.hasPermission(permission) + override fun sendMessage(text: Component) = native.sendMessage(text) + override fun actionBar(text: Component) = native.sendActionBar(text) + override fun playSound(sound: Sound): Delivery { + native.playSound(sound) + return Delivery.Delivered + } + + override fun applyEffect(effect: PlayerEffect): Delivery = Delivery.Unsupported + override fun spawnParticle(particle: PlayerParticle): Delivery = Delivery.Unsupported + override fun disconnect(reason: String) = native.disconnect(Component.text(reason)) + + companion object { + fun of(player: Player): NetworkPlayer = VelocityNetworkPlayer(player) + } +} diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/network/VelocityNetworkProxy.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/network/VelocityNetworkProxy.kt new file mode 100644 index 000000000..f2688d136 --- /dev/null +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/network/VelocityNetworkProxy.kt @@ -0,0 +1,70 @@ +package org.pnfolder.pnlibrary.velocity.network + +import com.velocitypowered.api.proxy.ProxyServer +import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier +import com.velocitypowered.api.proxy.server.RegisteredServer +import net.kyori.adventure.text.Component +import org.pnfolder.pnlibrary.api.network.NetworkPlayer +import org.pnfolder.pnlibrary.api.network.NetworkProxy +import org.pnfolder.pnlibrary.api.network.NetworkServer +import org.pnfolder.pnlibrary.core.menu.OwnerInfo +import java.net.InetSocketAddress +import java.util.UUID + +/** [NetworkProxy] backed by a Velocity [ProxyServer]. */ +internal class VelocityNetworkProxy(private val server: ProxyServer) : NetworkProxy { + + override val name: String get() = server.version.name + override val version: String get() = server.version.version + override val playerCount: Int get() = server.playerCount + + override val players get() = server.allPlayers.map(::VelocityNetworkPlayer) + override val servers get() = server.allServers.map(::VelocityNetworkServer) + + override fun player(name: String): NetworkPlayer? = + server.getPlayer(name).orElse(null)?.let(::VelocityNetworkPlayer) + + override fun player(uuid: UUID): NetworkPlayer? = + server.getPlayer(uuid).orElse(null)?.let(::VelocityNetworkPlayer) + + override fun server(name: String): NetworkServer? = + server.getServer(name).orElse(null)?.let(::VelocityNetworkServer) + + override fun registerChannel(channel: String) = + server.channelRegistrar.register(MinecraftChannelIdentifier.from(channel)) + + override fun unregisterChannel(channel: String) = + server.channelRegistrar.unregister(MinecraftChannelIdentifier.from(channel)) + + override fun broadcast(message: String) = + server.allPlayers.forEach { it.sendMessage(Component.text(message)) } + + override fun stop(reason: String?) = + if (reason != null) server.shutdown(Component.text(reason)) else server.shutdown() + + /** Resolves the pnLibrary [OwnerInfo] for a Velocity plugin instance. Not part of [NetworkProxy]. */ + fun describePlugin(instance: Any?): OwnerInfo? = + instance + ?.let { server.pluginManager.fromInstance(it).orElse(null)?.description } + ?.let { OwnerInfo(it.name.orElse(it.id), it.version.orElse(null), it.authors) } +} + +/** [NetworkServer] backed by a Velocity [RegisteredServer]. */ +internal class VelocityNetworkServer(private val rs: RegisteredServer) : NetworkServer { + + override val name: String get() = rs.serverInfo.name + override val address: InetSocketAddress get() = rs.serverInfo.address + override val onlinePlayers: Int get() = rs.playersConnected.size + + override val ping: Long? get() = rs.playersConnected + .map { it.ping } + .takeIf { it.isNotEmpty() } + ?.average() + ?.toLong() + + override fun send(channel: String, bytes: ByteArray): Boolean = + rs.sendPluginMessage(MinecraftChannelIdentifier.from(channel), bytes) + + // RegisteredServer implements Audience — broadcasts to all players on this server. + override fun broadcast(message: String) = rs.sendMessage(Component.text(message)) +} diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlayerEvents.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/network/VelocityPlayerEvents.kt similarity index 74% rename from platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlayerEvents.kt rename to platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/network/VelocityPlayerEvents.kt index f3c927e5d..d001a4782 100644 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/VelocityPlayerEvents.kt +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/network/VelocityPlayerEvents.kt @@ -1,19 +1,21 @@ -package org.pnfolder.pnlibrary.velocity +package org.pnfolder.pnlibrary.velocity.network import com.velocitypowered.api.event.PostOrder import com.velocitypowered.api.event.Subscribe import com.velocitypowered.api.event.connection.DisconnectEvent import com.velocitypowered.api.event.connection.PostLoginEvent import org.pnfolder.pnlibrary.api.runtime.PnLibrary -import org.pnfolder.pnlibrary.core.events.PlayerLifecyclePublisher +import org.pnfolder.pnlibrary.core.events.player.PlayerLifecyclePublisher /** Publishes the portable player join and quit events from Velocity's native ones. */ internal class VelocityPlayerEvents(private val library: PnLibrary) { + /** Publishes the portable join event once the player is logged in. */ @Subscribe(order = PostOrder.LAST) fun onPostLogin(event: PostLoginEvent) { PlayerLifecyclePublisher.joined(library, event.player.uniqueId, event.player.username) } + /** Publishes the portable quit event when the player leaves the proxy. */ @Subscribe(order = PostOrder.LAST) fun onDisconnect(event: DisconnectEvent) { PlayerLifecyclePublisher.left(library, event.player.uniqueId, event.player.username) diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/remote/VelocityRemotePolicyContextFactory.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/remote/VelocityRemotePolicyContextFactory.kt index 688073cec..49ea2c382 100644 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/remote/VelocityRemotePolicyContextFactory.kt +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/remote/VelocityRemotePolicyContextFactory.kt @@ -8,44 +8,36 @@ import org.pnfolder.pnlibrary.api.remote.ProductInfo import org.pnfolder.pnlibrary.api.remote.RemotePolicyContext import org.pnfolder.pnlibrary.api.remote.ServerInfo import org.pnfolder.pnlibrary.common.minecraft.MinecraftVersion +import kotlin.jvm.optionals.getOrDefault /** Creates remote-policy contexts from Velocity runtime metadata. */ internal object VelocityRemotePolicyContextFactory { - /** - * Builds a context for [plugin] on [server] and appends caller-defined policy [values]. - * - * @param plugin Native Velocity plugin instance that owns the policy evaluation. - * @param container Velocity container registered for [plugin]. - * @param server Velocity proxy that hosts the plugin. - * @param values Additional non-sensitive values exposed to policy rules. - */ + /** Builds a context for [plugin] on [server] and appends caller-defined policy [values]. */ fun create( plugin: Any, container: PluginContainer, server: ProxyServer, values: Map = emptyMap(), ): RemotePolicyContext { - val manager = server.pluginManager val descriptor = container.description - val proxy = server.version val product = ProductInfo( - descriptor.id, - descriptor.name.orElse(descriptor.id), - descriptor.version.orElse("unknown"), + id = descriptor.id, + name = descriptor.name.getOrDefault(descriptor.id), + version = descriptor.version.getOrDefault("unknown"), ) val platform = PlatformInfo( - PlatformType.VELOCITY, - proxy.name, - proxy.version, + type = PlatformType.VELOCITY, + name = proxy.name, + version = proxy.version, ) val runtime = ServerInfo( - proxy.version, - MinecraftVersion.parseInfo(null), + version = proxy.version, + minecraft = MinecraftVersion.parseInfo(null), ) return RemotePolicyContext.builder() @@ -55,7 +47,7 @@ internal object VelocityRemotePolicyContextFactory { .values(values) .nativeHandle(plugin) .nativeHandle(server) - .nativeHandle(manager) + .nativeHandle(server.pluginManager) .build() } } diff --git a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/tasks/VelocityTaskAdapter.kt b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/tasks/VelocityTaskAdapter.kt index 4bd23e180..65844fbb5 100644 --- a/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/tasks/VelocityTaskAdapter.kt +++ b/platforms/velocity/runtime/src/main/kotlin/org/pnfolder/pnlibrary/velocity/tasks/VelocityTaskAdapter.kt @@ -1,147 +1,37 @@ package org.pnfolder.pnlibrary.velocity.tasks import com.velocitypowered.api.proxy.ProxyServer -import org.pnfolder.pnlibrary.api.tasks.TaskExecution -import org.pnfolder.pnlibrary.common.lang.runCatchingNonFatal -import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskAdapter +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskHandle import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicReference +import org.pnfolder.pnlibrary.spi.tasks.TrackingPlatformTaskAdapter -/** - * Adapts pnLibrary task requests to the native Velocity scheduler. - * - * The adapter owns every scheduled handle and cancels all remaining tasks when it is closed. - * One-shot tasks are removed from the tracking set immediately after their callback finishes. - */ internal class VelocityTaskAdapter internal constructor( - private val describeOwner: (Any?) -> String, private val warning: (String) -> Unit, private val nativeSchedule: (PlatformTaskRequest) -> PlatformTaskHandle, -) : PlatformTaskAdapter { +) : TrackingPlatformTaskAdapter() { - /** - * Creates an adapter backed by Velocity's scheduler. [describeOwner] names the plugin that asked for a task, - * and [warning] receives a notice every time an entity task is run on the proxy scheduler instead. - */ - constructor(server: ProxyServer, describeOwner: (Any?) -> String, warning: (String) -> Unit) : this( - describeOwner = describeOwner, + constructor(server: ProxyServer, plugin: Any, warning: (String) -> Unit) : this( warning = warning, nativeSchedule = { request -> - val owner = requireNotNull(request.owner) { "Velocity tasks require a native plugin owner" } - require(server.pluginManager.fromInstance(owner).isPresent) { + require(server.pluginManager.fromInstance(plugin).isPresent) { "Task owner must be a registered Velocity plugin" } - val builder = server.scheduler.buildTask(owner, request.callback) - - if (!request.delay.isZero) { - builder.delay(request.delay) - } + val builder = server.scheduler.buildTask(plugin, request.callback) + if (!request.delay.isZero) builder.delay(request.delay) request.interval?.let(builder::repeat) val task = builder.schedule() - PlatformTaskHandle { - task.cancel() - true - } + PlatformTaskHandle { task.cancel(); true } }, ) - private val closed = AtomicBoolean(false) - private val handles = ConcurrentHashMap.newKeySet() + override fun scheduleNative(request: PlatformTaskRequest): PlatformTaskHandle = nativeSchedule(request) - /** - * Schedules a request and starts tracking its cancellation handle. - * - * Velocity has no entity scheduler, so an entity task runs on the proxy scheduler instead, and every such - * call writes a warning that names the plugin which asked for it. - */ - override fun schedule(request: PlatformTaskRequest): PlatformTaskHandle { - check(!closed.get()) { "Velocity task adapter is closed" } + // Velocity has no entity scheduler; entity tasks fall back to the proxy scheduler. + override fun beforeSchedule(request: PlatformTaskRequest) { if (request.executionKind == TaskExecution.Kind.ENTITY) { - warning( - "Плагин ${describeOwner(request.owner)} запросил задачу, привязанную к игроку. " + - "Velocity такие задачи не поддерживает: задача выполнена на общем планировщике прокси.", - ) - } - - val reference = AtomicReference() - val completed = AtomicBoolean(false) - val forwardedRequest = request.withLifecycle(reference, completed) - val handle = TrackedHandle(nativeSchedule(forwardedRequest)) - - reference.set(handle) - handles += handle - - if (closed.get()) { - handle.cancel() - error("Velocity task adapter is closed") - } - - if (completed.get()) { - handle.release() - } - - return handle - } - - override fun close() { - if (!closed.compareAndSet(false, true)) { - return - } - - var failure: Throwable? = null - handles.toList().forEach { handle -> - runCatchingNonFatal { handle.cancel() }.onFailure { error -> - if (failure == null) failure = error - else if (failure !== error) failure?.addSuppressed(error) - } - } - handles.clear() - failure?.let { throw it } - } - - /** Wraps a request callback so completed one-shot tasks can be untracked safely. */ - private fun PlatformTaskRequest.withLifecycle( - reference: AtomicReference, - completed: AtomicBoolean, - ): PlatformTaskRequest = copy( - callback = Runnable { - try { - callback.run() - } finally { - if (interval == null) { - completed.set(true) - reference.get()?.release() - } - } - }, - ) - - /** Tracks a native handle and makes cancellation idempotent. */ - private inner class TrackedHandle( - private val delegate: PlatformTaskHandle, - ) : PlatformTaskHandle { - private val cancelled = AtomicBoolean(false) - - override fun cancel(): Boolean { - if (!cancelled.compareAndSet(false, true)) { - return false - } - - try { - delegate.cancel() - } finally { - handles.remove(this) - } - return true - } - - /** Removes a completed one-shot task without cancelling its native handle. */ - fun release() { - handles.remove(this) + warning("Entity-bound task requested on Velocity, which has no entity scheduler; running on the proxy scheduler instead.") } } } diff --git a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityDiagnosticDetailsCollectorTest.kt b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityDiagnosticDetailsCollectorTest.kt index 1034be8b4..47154dcde 100644 --- a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityDiagnosticDetailsCollectorTest.kt +++ b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityDiagnosticDetailsCollectorTest.kt @@ -9,9 +9,11 @@ import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import org.pnfolder.pnlibrary.spi.platform.PlatformSnapshot +import org.pnfolder.pnlibrary.velocity.diagnostics.VelocityDiagnosticDetailsCollector import java.net.InetSocketAddress import java.util.Optional +/** Checks the Velocity facts collected for diagnostics. */ class VelocityDiagnosticDetailsCollectorTest { @Test fun `p95 includes high latency in a small player population`() { diff --git a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLogObserverTest.kt b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLogObserverTest.kt index 39e52e9c6..135494b62 100644 --- a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLogObserverTest.kt +++ b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityLogObserverTest.kt @@ -6,7 +6,9 @@ import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.logging.LogLevel +import org.pnfolder.pnlibrary.velocity.log.VelocityLogObserver +/** Checks attribution of Log4j events to the plugin that wrote them. */ class VelocityLogObserverTest { private class Seen(val owner: Any, val level: LogLevel, val message: String, val error: Throwable?) diff --git a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityNativeOwnershipTest.kt b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityNativeOwnershipTest.kt index 05d0465f7..5df311794 100644 --- a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityNativeOwnershipTest.kt +++ b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityNativeOwnershipTest.kt @@ -11,14 +11,13 @@ import org.mockito.kotlin.any import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command -import org.pnfolder.pnlibrary.api.tasks.TaskExecution +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import org.pnfolder.pnlibrary.spi.commands.PlatformCommandDispatcher -import org.pnfolder.pnlibrary.spi.tasks.PlatformTaskRequest import org.pnfolder.pnlibrary.velocity.commands.VelocityCommandAdapter +import org.pnfolder.pnlibrary.velocity.network.VelocityAudienceAdapter import org.pnfolder.pnlibrary.velocity.tasks.VelocityTaskAdapter -import java.time.Duration import java.util.Optional import java.util.concurrent.CompletableFuture @@ -54,14 +53,12 @@ class VelocityNativeOwnershipTest { } @Test - fun `native task is scheduled under caller plugin`() { + fun `native task is scheduled under the library plugin`() { val proxy = mock(ProxyServer::class.java, RETURNS_DEEP_STUBS) val owner = Any() whenever(proxy.pluginManager.fromInstance(owner)).thenReturn(Optional.of(mock())) - val adapter = VelocityTaskAdapter(proxy, { "demo" }, {}) - val handle = adapter.schedule(PlatformTaskRequest( - TaskExecution.Kind.ASYNC, null, Duration.ZERO, null, Runnable {}, owner, - )) + val adapter = VelocityTaskAdapter(proxy, owner, {}) + val handle = adapter.buildTask().task {}.execution(TaskExecution.Kind.ASYNC).schedule() verify(proxy.scheduler).buildTask(org.mockito.kotlin.eq(owner), any()) handle.cancel() adapter.close() @@ -77,9 +74,7 @@ class VelocityNativeOwnershipTest { .register(owner, command("owned") {}, dispatcher) } assertThrows(IllegalArgumentException::class.java) { - VelocityTaskAdapter(proxy, { "demo" }, {}).schedule(PlatformTaskRequest( - TaskExecution.Kind.ASYNC, null, Duration.ZERO, null, Runnable {}, owner, - )) + VelocityTaskAdapter(proxy, owner, {}).buildTask().task {}.schedule() } } diff --git a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityReadinessTest.kt b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityReadinessTest.kt index b6c80ecab..047c7960b 100644 --- a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityReadinessTest.kt +++ b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/VelocityReadinessTest.kt @@ -10,10 +10,10 @@ import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.whenever import org.pnfolder.pnlibrary.spi.metrics.NoopMetricsFactory -import org.slf4j.Logger import java.nio.file.Path import java.util.Optional +/** Checks that startup-dependent work waits until the Velocity adapter is marked ready. */ class VelocityReadinessTest { @TempDir lateinit var directory: Path @@ -55,6 +55,6 @@ class VelocityReadinessTest { callbacks += it.getArgument(1) builder } - return VelocityPlatformAdapter(owner, proxy, NoopMetricsFactory, directory, mock(Logger::class.java)) + return VelocityPlatformAdapter(owner, proxy, NoopMetricsFactory, directory) } } diff --git a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/commands/VelocityCommandAdapterTest.kt b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/commands/VelocityCommandAdapterTest.kt index c618520f3..be92e024b 100644 --- a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/commands/VelocityCommandAdapterTest.kt +++ b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/commands/VelocityCommandAdapterTest.kt @@ -11,8 +11,8 @@ import org.junit.jupiter.api.Test import org.pnfolder.pnlibrary.api.audiences.AudienceSender import org.pnfolder.pnlibrary.api.audiences.Delivery import org.pnfolder.pnlibrary.api.commands.CommandContext -import org.pnfolder.pnlibrary.api.commands.CommandDefinition -import org.pnfolder.pnlibrary.api.commands.command +import org.pnfolder.pnlibrary.api.commands.definition.CommandDefinition +import org.pnfolder.pnlibrary.api.commands.definition.command import org.pnfolder.pnlibrary.spi.commands.NativeCommandRegistrar import org.pnfolder.pnlibrary.spi.commands.PlatformCommandDispatcher import org.pnfolder.pnlibrary.spi.commands.PlatformCommandRegistration @@ -20,6 +20,7 @@ import java.lang.reflect.Proxy import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage +/** Checks command registration, execution, tab completion and cleanup on Velocity. */ class VelocityCommandAdapterTest { @Test fun `execution and asynchronous suggestions are transported without blocking`() { diff --git a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/remote/VelocityRemotePolicyContextFactoryTest.kt b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/remote/VelocityRemotePolicyContextFactoryTest.kt index 0336f040c..889dcc252 100644 --- a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/remote/VelocityRemotePolicyContextFactoryTest.kt +++ b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/remote/VelocityRemotePolicyContextFactoryTest.kt @@ -12,6 +12,7 @@ import org.mockito.kotlin.whenever import org.pnfolder.pnlibrary.api.platform.PlatformType import java.util.Optional +/** Checks the remote-policy context built from Velocity metadata. */ class VelocityRemotePolicyContextFactoryTest { private val server = mock().also { whenever(it.version).thenReturn(ProxyVersion("Velocity", "Velocity Team", "3.4-test")) diff --git a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/tasks/VelocityTaskAdapterTest.kt b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/tasks/VelocityTaskAdapterTest.kt index ba4be77da..2a4caa15c 100644 --- a/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/tasks/VelocityTaskAdapterTest.kt +++ b/platforms/velocity/runtime/src/test/kotlin/org/pnfolder/pnlibrary/velocity/tasks/VelocityTaskAdapterTest.kt @@ -2,26 +2,24 @@ package org.pnfolder.pnlibrary.velocity.tasks import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test -import org.pnfolder.pnlibrary.api.tasks.TaskExecution +import org.pnfolder.pnlibrary.api.tasks.spec.TaskExecution import org.pnfolder.pnlibrary.spi.tasks.* import java.time.Duration import java.util.concurrent.atomic.AtomicBoolean +/** Checks task scheduling, entity-task warnings and shutdown on the Velocity scheduler. */ class VelocityTaskAdapterTest { - private val NAMES: (Any?) -> String = { "demo" } private val WARN: (String) -> Unit = {} @Test - fun `task created during shutdown is cancelled and rejected`() { + fun `task created during shutdown is cancelled`() { val cancelled = AtomicBoolean() lateinit var adapter: VelocityTaskAdapter - adapter = VelocityTaskAdapter(NAMES, WARN) { + adapter = VelocityTaskAdapter(WARN) { adapter.close() PlatformTaskHandle { cancelled.compareAndSet(false, true) } } - assertThrows(IllegalStateException::class.java) { - adapter.schedule(PlatformTaskRequest(TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, Runnable {})) - } + adapter.buildTask().from(PlatformTaskRequest(TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, Runnable {})).schedule() assertTrue(cancelled.get()) } @@ -29,7 +27,7 @@ class VelocityTaskAdapterTest { fun `close attempts every cancellation even if one fails`() { var scheduled = 0 var cancellations = 0 - val adapter = VelocityTaskAdapter(NAMES, WARN) { + val adapter = VelocityTaskAdapter(WARN) { val index = scheduled++ PlatformTaskHandle { cancellations++ @@ -38,7 +36,7 @@ class VelocityTaskAdapterTest { } } repeat(2) { - adapter.schedule(PlatformTaskRequest(TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, Runnable {})) + adapter.buildTask().from(PlatformTaskRequest(TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, Runnable {})).schedule() } assertThrows(IllegalStateException::class.java) { adapter.close() } assertEquals(2, cancellations) @@ -47,50 +45,50 @@ class VelocityTaskAdapterTest { } @Test - fun `entity scheduling runs on the proxy scheduler and warns with the plugin name on every call`() { + fun `entity scheduling runs on the proxy scheduler and warns on every call`() { val warnings = mutableListOf() var scheduled = 0 - val adapter = VelocityTaskAdapter({ "shop" }, { warnings += it }) { + val adapter = VelocityTaskAdapter({ warnings += it }) { scheduled++ PlatformTaskHandle { true } } val request = PlatformTaskRequest(TaskExecution.Kind.ENTITY, Any(), Duration.ZERO, null, Runnable {}) - adapter.schedule(request) - adapter.schedule(request) + adapter.buildTask().from(request).schedule() + adapter.buildTask().from(request).schedule() assertEquals(2, scheduled) assertEquals(2, warnings.size) - assertTrue(warnings.all { it.contains("shop") && it.contains("игроку") }) + assertTrue(warnings.all { it.contains("Entity-bound") }) } @Test fun `adapter forwards native duration request and closes registrations`() { var seen: PlatformTaskRequest? = null val cancelled = AtomicBoolean() - val adapter = VelocityTaskAdapter(NAMES, WARN) { request -> + val adapter = VelocityTaskAdapter(WARN) { request -> seen = request PlatformTaskHandle { cancelled.compareAndSet(false, true) } } val request = PlatformTaskRequest(TaskExecution.Kind.ASYNC, null, Duration.ofMillis(5), null, Runnable {}) - adapter.schedule(request) + adapter.buildTask().from(request).schedule() adapter.close() assertEquals(request.executionKind, seen?.executionKind) assertEquals(request.delay, seen?.delay) assertEquals(request.interval, seen?.interval) assertTrue(cancelled.get()) - assertThrows(IllegalStateException::class.java) { adapter.schedule(request) } + assertThrows(IllegalStateException::class.java) { adapter.buildTask().from(request).schedule() } } @Test fun `completed one shot is released before adapter close`() { lateinit var callback: Runnable val cancelled = AtomicBoolean() - val adapter = VelocityTaskAdapter(NAMES, WARN) { request -> + val adapter = VelocityTaskAdapter(WARN) { request -> callback = request.callback PlatformTaskHandle { cancelled.compareAndSet(false, true) } } - adapter.schedule(PlatformTaskRequest(TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, Runnable {})) + adapter.buildTask().from(PlatformTaskRequest(TaskExecution.Kind.GLOBAL, null, Duration.ZERO, null, Runnable {})).schedule() callback.run() adapter.close() assertFalse(cancelled.get()) diff --git a/settings.gradle.kts b/settings.gradle.kts index 634065f0e..1eb2da3a8 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -4,14 +4,9 @@ include( // Public contracts and shared code. ":modules:common", ":modules:api", - ":modules:runtime-spi", + ":modules:spi", ":modules:console", // Runtime. - ":modules:link", - ":modules:placeholders", - ":modules:events", - ":modules:upload", - ":modules:journal", ":modules:core", ":modules:updates", ":modules:bootstrap", @@ -20,7 +15,7 @@ include( ":modules:features:config-runtime", ":modules:features:currency-api", ":modules:features:currency-runtime", - ":modules:features:minecraft-localization-api", + ":modules:features:localization-api", // Platforms. ":platforms:loader", ":platforms:bukkit:api", diff --git a/tools/api/check-api-generation.ps1 b/tools/api/check-api-generation.ps1 index 7b47514e9..ac78e61cf 100644 --- a/tools/api/check-api-generation.ps1 +++ b/tools/api/check-api-generation.ps1 @@ -64,7 +64,7 @@ function Get-RepositoryApiDeclarations { Where-Object { $_.Trim() -and -not $_.Trim().StartsWith('#') } | ForEach-Object { $_.Split('=')[0].Trim() }) $result = @() - foreach ($module in @($modules + 'modules/runtime-spi')) { + foreach ($module in @($modules + 'modules/spi')) { foreach ($file in @(Get-ChildItem -LiteralPath (Join-Path $module 'api') -Filter '*.api')) { $result += [IO.Path]::GetRelativePath((Get-Location).Path, $file.FullName).Replace('\', '/') } diff --git a/tools/api/check-api-generation.tests.ps1 b/tools/api/check-api-generation.tests.ps1 index 6dede36a3..ac27d6be7 100644 --- a/tools/api/check-api-generation.tests.ps1 +++ b/tools/api/check-api-generation.tests.ps1 @@ -60,11 +60,11 @@ try { Invoke-Case 'generation-increase' $base $removal 4 5 0 Invoke-Case 'generation-decrease' $base $addition 4 3 1 $repo = Join-Path $testRoot 'all-modules' - @('gradle', 'modules/api/api', 'modules/features/config-api/api', 'modules/runtime-spi/api', 'modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version') | + @('gradle', 'modules/api/api', 'modules/features/config-api/api', 'modules/spi/api', 'modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version') | ForEach-Object { New-Item -ItemType Directory -Path (Join-Path $repo $_) -Force | Out-Null } [IO.File]::WriteAllText((Join-Path $repo 'gradle/public-modules.properties'), "modules/api=modules/features/config-api`nmodules/features/config-api=`n") [IO.File]::WriteAllText((Join-Path $repo 'modules/api/api/api.api'), $base) - [IO.File]::WriteAllText((Join-Path $repo 'modules/runtime-spi/api/runtime-spi.api'), $base) + [IO.File]::WriteAllText((Join-Path $repo 'modules/spi/api/spi.api'), $base) $configDump = Join-Path $repo 'modules/features/config-api/api/config-api.api' [IO.File]::WriteAllText($configDump, $base) [IO.File]::WriteAllText((Join-Path $repo 'modules/api/src/main/kotlin/org/pnfolder/pnlibrary/api/version/PnLibraryApi.kt'), 'const val VERSION: Int = 4')