diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..e3d9c3c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Preserve the line endings generated by the Gradle Windows wrapper. +gradlew.bat text eol=crlf diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml index 6784e48..e2a85c8 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -3,103 +3,178 @@ name: Deployment on: push: tags: - # ドットをエスケープしなくていい(正規表現でない) + # ここは glob。タグの書式は parse_version で検証する。 - 'v[0-9]+.[0-9]+.[0-9]+*' workflow_dispatch: + inputs: + tag: + description: 'ビルドする既存のタグ(例: v1.2.3-rc.1)' + required: true + type: string + +permissions: + contents: read jobs: - parse_version: # プッシュされたタグの文字列からバージョンをパースする + parse_version: + if: github.event_name != 'push' || !github.event.deleted runs-on: ubuntu-latest + timeout-minutes: 5 outputs: + tag: ${{ steps.parse.outputs.tag }} full_version: ${{ steps.parse.outputs.full_version }} version: ${{ steps.parse.outputs.version }} - major: ${{ steps.parse.outputs.major }} - minor: ${{ steps.parse.outputs.minor }} - patch: ${{ steps.parse.outputs.patch }} - suffix: ${{ steps.parse.outputs.suffix }} + commit: ${{ steps.parse.outputs.commit }} + prerelease: ${{ steps.parse.outputs.prerelease }} steps: - - name: Parse version from tag + - name: Validate tag and resolve commit id: parse + env: + DISPATCH_TAG: ${{ inputs.tag }} + GH_TOKEN: ${{ github.token }} run: | - FULL_VERSION=${GITHUB_REF#refs/tags/v} - VERSION=$(echo $FULL_VERSION | cut -d'-' -f1) - SUFFIX=$(echo $FULL_VERSION | cut -s -d'-' -f2-) - echo "full_version=$FULL_VERSION" >> $GITHUB_OUTPUT - echo "version=$VERSION" >> $GITHUB_OUTPUT - echo "major=$(echo $VERSION | cut -d. -f1)" >> $GITHUB_OUTPUT - echo "minor=$(echo $VERSION | cut -d. -f2)" >> $GITHUB_OUTPUT - echo "patch=$(echo $VERSION | cut -d. -f3)" >> $GITHUB_OUTPUT - echo "suffix=$SUFFIX" >> $GITHUB_OUTPUT - make: # タグから識別したバージョン情報に基づくアプリケーションを生成する + set -euo pipefail + if [[ "$GITHUB_EVENT_NAME" == 'workflow_dispatch' ]]; then + TAG=$DISPATCH_TAG + else + [[ "$GITHUB_REF" == refs/tags/* ]] || { echo 'A release requires a tag.' >&2; exit 1; } + TAG=${GITHUB_REF#refs/tags/} + fi + VERSION_PATTERN='^v([0-9]+)\.([0-9]+)\.([0-9]+)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$' + [[ "$TAG" =~ $VERSION_PATTERN ]] || { echo 'Invalid release tag.' >&2; exit 1; } + VERSION=${BASH_REMATCH[1]}.${BASH_REMATCH[2]}.${BASH_REMATCH[3]} + PRERELEASE=false + if [[ -n "${BASH_REMATCH[4]}" ]]; then PRERELEASE=true; fi + COMMIT=$(gh api "repos/$GITHUB_REPOSITORY/commits/refs/tags/$TAG" --jq .sha) + [[ "$COMMIT" =~ ^[0-9a-f]{40}$ ]] || { echo 'Could not resolve tag commit.' >&2; exit 1; } + if [[ "$GITHUB_EVENT_NAME" == 'push' && "$COMMIT" != "$GITHUB_SHA" ]]; then + echo 'Release tag no longer points to the pushed commit.' >&2 + exit 1 + fi + printf '%s\n' "tag=$TAG" "full_version=${TAG#v}" "version=$VERSION" \ + "commit=$COMMIT" "prerelease=$PRERELEASE" >> "$GITHUB_OUTPUT" + + make: + needs: parse_version + runs-on: ${{ matrix.os }} + timeout-minutes: 60 strategy: + fail-fast: false matrix: - # WindowsランナーはWiX Toolset 3.14.1.8722入り - # MacOSはIntel CPU(macos-13)とApple Silicon CPU(macos-14) - # https://docs.github.com/ja/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners - os: [windows-latest, macos-13, macos-14] - runs-on: ${{ matrix.os }} - needs: parse_version + include: + - os: windows-2025 + target: windows-x64 + extension: exe + arch_suffix: '' + - os: macos-15-intel + target: macos-x86_64 + extension: dmg + arch_suffix: -x86_64 + - os: macos-15 + target: macos-arm64 + extension: dmg + arch_suffix: -arm64 + env: + APP_VERSION: ${{ needs.parse_version.outputs.full_version }} steps: - name: Checkout source - uses: actions/checkout@v4 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.parse_version.outputs.commit }} + persist-credentials: false - name: Setup JDK - uses: actions/setup-java@v4 + uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: - java-version: 21.0.1 + java-version: '25' distribution: 'temurin' + check-latest: true - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 - - name: Make an application for Windows - if: (matrix.os == 'windows-latest') - run: .\gradlew.bat "-Papp.version=${{ needs.parse_version.outputs.full_version }}" make - - name: Make an application - if: (matrix.os != 'windows-latest') - run: ./gradlew "-Papp.version=${{ needs.parse_version.outputs.full_version }}" make - - name: Rename an application for Windows - if: (matrix.os == 'windows-latest') - shell: bash - run: | - mv '.\build\app\Twitch Chat Viewer-${{ needs.parse_version.outputs.version }}.exe' '.\build\app\Twitch Chat Viewer-${{ needs.parse_version.outputs.full_version }}.exe' - - name: Rename an application for Intel Mac - if: (matrix.os == 'macos-13') - shell: bash - run: | - mv "build/app/Twitch Chat Viewer-${{ needs.parse_version.outputs.version }}.dmg" "build/app/Twitch Chat Viewer-${{ needs.parse_version.outputs.full_version }}-x86_64.dmg" - - name: Rename an application for Apple Silicon Mac - if: (matrix.os == 'macos-14') - shell: bash - run: | - mv "build/app/Twitch Chat Viewer-${{ needs.parse_version.outputs.version }}.dmg" "build/app/Twitch Chat Viewer-${{ needs.parse_version.outputs.full_version }}-arm64.dmg" - - name: Detect asset file for Windows - if: (matrix.os == 'windows-latest') + uses: gradle/actions/setup-gradle@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0 + with: + cache-provider: basic + cache-read-only: true + - name: Build Windows installer + if: runner.os == 'Windows' shell: pwsh - run: | - echo "asset_path=build\app\$(Get-ChildItem -name .\build\app)" >> $env:GITHUB_ENV - echo "asset_name=$(Get-ChildItem -name .\build\app)" >> $env:GITHUB_ENV - - name: Detect asset file - if: (matrix.os != 'windows-latest') + run: .\gradlew.bat "-Papp.version=$env:APP_VERSION" make + - name: Build macOS installer + if: runner.os == 'macOS' + run: ./gradlew "-Papp.version=$APP_VERSION" make + - name: Prepare installer for upload + id: installer shell: bash + env: + NATIVE_VERSION: ${{ needs.parse_version.outputs.version }} + EXTENSION: ${{ matrix.extension }} + ARCH_SUFFIX: ${{ matrix.arch_suffix }} run: | - echo "asset_path=build/app/$(ls build/app)" >> $GITHUB_ENV - echo "asset_name=$(ls build/app)" >> $GITHUB_ENV - - name: Upload artifacts - uses: actions/upload-artifact@v4 # https://github.com/actions/upload-artifact + source="build/app/Twitch Chat Viewer-$NATIVE_VERSION.$EXTENSION" + target="build/distribution/Twitch Chat Viewer-$APP_VERSION$ARCH_SUFFIX.$EXTENSION" + if [[ ! -f "$source" || ! -s "$source" ]]; then + echo "Missing or empty installer: $source" >&2 + exit 1 + fi + mkdir -p build/distribution + cp -- "$source" "$target" + printf 'path=%s\n' "$target" >> "$GITHUB_OUTPUT" + - name: Upload installer + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: ${{ env.asset_name }} - path: ${{ env.asset_path }} + name: installer-${{ matrix.target }} + path: ${{ steps.installer.outputs.path }} + if-no-files-found: error + overwrite: true compression-level: 0 + - name: Upload packaging log on failure + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: packaging-log-${{ matrix.target }} + path: build/reports/packaging/make.log + if-no-files-found: ignore + overwrite: true + release: + needs: [make, parse_version] runs-on: ubuntu-latest - needs: make + timeout-minutes: 15 + permissions: + contents: write + concurrency: + group: deployment-${{ needs.parse_version.outputs.tag }} + cancel-in-progress: false steps: - - name: Download Artifacts - uses: actions/download-artifact@v4.1.8 + - name: Download installers + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: + pattern: installer-* + merge-multiple: true path: build/distribution/ - - name: Create Release - uses: softprops/action-gh-release@v2 # https://github.com/softprops/action-gh-release + - name: Verify release target + id: verify env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.parse_version.outputs.tag }} + COMMIT: ${{ needs.parse_version.outputs.commit }} + run: | + current=$(gh api "repos/$GITHUB_REPOSITORY/commits/refs/tags/$TAG" --jq .sha) + if [[ "$current" != "$COMMIT" ]]; then + echo "Tag $TAG changed during the build." >&2 + exit 1 + fi + published_tags=$(gh api --paginate "repos/$GITHUB_REPOSITORY/releases" --jq '.[] | select(.draft | not) | .tag_name') + if grep -Fxq -- "$TAG" <<< "$published_tags"; then + echo "Release $TAG is already published; its assets will not be modified." >&2 + exit 1 + fi + - name: Create or update draft release + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 with: - draft: true # ドラフトリリースとし、公開は手動で行う - files: build/distribution/** + tag_name: ${{ needs.parse_version.outputs.tag }} + draft: true # 公開は手動で行う。 + prerelease: ${{ needs.parse_version.outputs.prerelease == 'true' }} + fail_on_unmatched_files: true + files: | + build/distribution/*-x86_64.dmg + build/distribution/*-arm64.dmg + build/distribution/*.exe diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index a5c8a09..901ad5a 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -7,18 +7,39 @@ on: - "**/*.md" - "docs/**" +permissions: + contents: read + jobs: build: runs-on: ubuntu-latest + timeout-minutes: 30 steps: - name: Checkout source - uses: actions/checkout@v4 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Setup JDK - uses: actions/setup-java@v4 + uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: - java-version: 21.0.1 + java-version: '25' distribution: 'temurin' + check-latest: true - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 - - name: Test with Gradle - run: ./gradlew test \ No newline at end of file + uses: gradle/actions/setup-gradle@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0 + with: + cache-provider: basic + - name: Test Gradle build logic + run: ./gradlew -p buildSrc test + - name: Test application + run: ./gradlew test + - name: Upload test reports on failure + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: test-reports + path: | + build/reports/tests/test + buildSrc/build/reports/tests/test + if-no-files-found: ignore + overwrite: true diff --git a/.gitignore b/.gitignore index d3ed74e..9c8d8b3 100644 --- a/.gitignore +++ b/.gitignore @@ -38,4 +38,15 @@ bin/ ### Mac OS ### .DS_Store -userinfo \ No newline at end of file +userinfo + +# ローカル専用の開発資料 +/docs/architecture.md +/docs/development.md +/docs/technical-debt*.md +/docs/internal/ + +# AI +.agents +.opencode +AGENTS.md \ No newline at end of file diff --git a/.java-version b/.java-version new file mode 100644 index 0000000..7273c0f --- /dev/null +++ b/.java-version @@ -0,0 +1 @@ +25 diff --git a/README.md b/README.md index ce77103..2dac4e6 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,15 @@ # Twitch Chat Viewer -[![Java CI](https://github.com/k7t3/TwitchChatViewer/actions/workflows/test.yaml/badge.svg)](https://github.com/k7t3/TwitchChatViewer/actions/workflows/test.yaml) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) このアプリケーションはライブストリーミングサービス[Twitch](https://www.twitch.tv/)の非公式チャットビューアです。 アプリケーション画面 -[使用方法](docs/usage.md) +## ダウンロードと使い方 + +[リリースページ](https://github.com/k7t3/TwitchChatViewer/releases)から、お使いの OS に合ったインストーラーをダウンロードしてください。 +初回起動時の Twitch 認証やチャットの開き方は、[使用方法](docs/usage.md)をご覧ください。 ## 主な機能 @@ -41,6 +43,8 @@ ### チャットメッセージのフィルタリング * 特定のユーザーのメッセージを非表示にしたり、正規表現を使用してフィルタリングできます。 -## License +## プライバシーとライセンス -詳細は [LICENSE](LICENSE.md) を参照してください。 \ No newline at end of file +- [プライバシーポリシー](docs/license.md#privacy-policy) +- [アプリケーションのライセンス](LICENSE.md) +- [使用ライブラリとライセンス](docs/external-libraries.md) diff --git a/build.gradle b/build.gradle index a1fe365..8c5f0a8 100644 --- a/build.gradle +++ b/build.gradle @@ -1,3 +1,10 @@ +import com.github.k7t3.tcv.build.JdkModulesTask +import com.github.k7t3.tcv.build.JdkToolTask +import com.github.k7t3.tcv.build.NativePackageTask +import com.github.k7t3.tcv.build.PackagePlan +import org.gradle.api.artifacts.component.ModuleComponentIdentifier +import org.gradle.process.CommandLineArgumentProvider + plugins { id 'application' id 'org.openjfx.javafxplugin' version '0.1.0' @@ -6,193 +13,204 @@ plugins { group = 'io.github.k7t3' version = project.findProperty("app.version") ?: '1.0.0-dev' +PackagePlan.nativeVersion(version.toString()) repositories { mavenCentral() } -java { - sourceCompatibility = JavaVersion.VERSION_21 - targetCompatibility = JavaVersion.VERSION_21 -} +def javaFeature = libs.versions.java.get().toInteger() +java { toolchain { languageVersion = JavaLanguageVersion.of(javaFeature) } } -compileJava { - options.encoding = 'UTF-8' -} - -compileTestJava { +tasks.withType(JavaCompile).configureEach { options.encoding = 'UTF-8' + options.release = javaFeature } javafx { - version = '22.0.1' + version = libs.versions.javafx.get() modules = [ 'javafx.controls', 'javafx.fxml', 'javafx.swing' ] } application { mainClass = 'com.github.k7t3.tcv.view.Launcher' applicationName = 'Twitch Chat Viewer' + applicationDefaultJvmArgs = ['--enable-native-access=ALL-UNNAMED'] +} + +configurations { + mockitoAgent { canBeConsumed = false; transitive = false } + runtimeClasspath { + // 旧Helix builderの設定依存は、上流SDKとの比較テスト側だけで使用する。 + exclude group: 'commons-configuration', module: 'commons-configuration' + exclude group: 'commons-lang', module: 'commons-lang' + exclude group: 'commons-logging', module: 'commons-logging' + } } dependencies { // Logger - implementation 'org.slf4j:slf4j-api:2.0.11' - implementation 'org.slf4j:slf4j-jdk14:2.0.11' + implementation libs.slf4j.api + implementation libs.slf4j.jdk14 // Twitchクライアント - // TODO 必要なモジュールのみにする - implementation 'com.github.twitch4j:twitch4j:1.21.0' + implementation libs.twitch.auth + implementation libs.twitch.chat + implementation libs.twitch.common + implementation(libs.twitch.helix) { + exclude group: 'io.github.openfeign', module: 'feign-hystrix' + } + implementation libs.feign.core + implementation libs.feign.jackson + implementation libs.feign.okhttp + implementation libs.bucket4j // キャッシュ - implementation 'com.github.ben-manes.caffeine:caffeine:3.1.8' + implementation libs.caffeine // 永続化 - implementation 'org.xerial:sqlite-jdbc:3.45.3.0' + implementation libs.sqlite // Twitch認証用のQRコード生成 - implementation 'com.google.zxing:javase:3.5.3' + implementation libs.zxing // AtlantaFXと同じアイコンパックを使用する - implementation 'io.github.mkpaz:atlantafx-base:2.0.1' - implementation 'org.kordamp.ikonli:ikonli-javafx:12.3.1' - implementation 'org.kordamp.ikonli:ikonli-feather-pack:12.3.1' - implementation 'org.kordamp.ikonli:ikonli-material2-pack:12.3.1' + implementation libs.atlantafx + implementation libs.ikonli.javafx + implementation libs.ikonli.feather + implementation libs.ikonli.material2 // アイコンパック - implementation 'org.kordamp.ikonli:ikonli-fontawesome5-pack:12.3.1' + implementation libs.ikonli.fontawesome5 // MVVM - implementation "de.saxsys:mvvmfx:1.8.0" + implementation libs.mvvmfx // チャットビュー用のVirtualFlow - implementation 'org.fxmisc.flowless:flowless:0.7.2' + implementation libs.flowless // テスト - testImplementation platform('org.junit:junit-bom:5.9.1') - testImplementation 'org.junit.jupiter:junit-jupiter' + testImplementation platform(libs.junit.bom) + testImplementation libs.junit.jupiter + testRuntimeOnly libs.junit.launcher - testImplementation 'org.testfx:testfx-junit5:4.0.18' - testImplementation 'org.testfx:openjfx-monocle:21.0.2' // headless + testImplementation libs.testfx.junit5 - testImplementation 'org.assertj:assertj-core:3.13.2' - testImplementation 'org.hamcrest:hamcrest:2.1' + testImplementation libs.assertj + testImplementation libs.hamcrest - testImplementation 'org.mockito:mockito-core:5.11.0' + testImplementation libs.mockito + // 上流SDKとのHTTP契約比較だけは、従来のコマンド実行をテスト側で維持する。 + testImplementation libs.twitch.helix + mockitoAgent libs.mockito } -// SSL通信のためにjdk.crypto.ecモジュールが必要 -// https://stackoverflow.com/questions/63932217/java-ssl-handshake-failure-if-app-built-with-jpackage -def cryptoPackage = 'jdk.crypto.ec' - -def jdkModules = '' -tasks.register('checkJDKModules', Exec) { - dependsOn jar, copyDependencies, copyJavaFXModules +// 配布入力を専用ディレクトリに同期する。古いアプリ JAR や依存 JAR を混入させない。 +def javafxArtifacts = configurations.runtimeClasspath.incoming.artifactView { + componentFilter { id -> id instanceof ModuleComponentIdentifier && id.group == 'org.openjfx' } +}.files +def applicationArtifacts = configurations.runtimeClasspath.incoming.artifactView { + componentFilter { id -> !(id instanceof ModuleComponentIdentifier && id.group == 'org.openjfx') } +}.files + +def packageInput = tasks.register('copyDependencies', Sync) { + from applicationArtifacts + from tasks.named('jar', Jar).flatMap { it.archiveFile } + from('LICENSE.md') + from('src/main/packaging') + from('docs') { include 'license.md', 'external-libraries.md', 'licenses/**'; into 'docs' } + into layout.buildDirectory.dir('packaging/input') +} - // プラットフォームに依存したクラスパスのセパレータ - var s = org.gradle.internal.os.OperatingSystem.current().isWindows() - ? ';' - : ':' +def javafxInput = tasks.register('copyJavaFXModules', Sync) { + from javafxArtifacts + into layout.buildDirectory.dir('packaging/javafx') +} - commandLine 'jdeps', - '--add-modules', 'ALL-MODULE-PATH', - '--multi-release', '9', - '--ignore-missing-deps', - '--print-module-deps', - '--class-path', "build/libs/*${s}build/javafx/*", - "build/libs/${-> tasks.jar.archiveFile.get().asFile.name}" +def packageJava = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(javaFeature) } +tasks.withType(JdkToolTask).configureEach { javaFeatureVersion = javaFeature } +def moduleCheck = tasks.register('checkJDKModules', JdkModulesTask) { + dependsOn packageInput, javafxInput + javaLauncher = packageJava + inputDirectory = layout.buildDirectory.dir('packaging/input') + moduleDirectory = layout.buildDirectory.dir('packaging/javafx') + mainJar = tasks.named('jar', Jar).flatMap { it.archiveFileName } + javafxModules = javafx.modules + modulesFile = layout.buildDirectory.file('packaging/jdk-modules.txt') +} - standardOutput = new ByteArrayOutputStream() - ext.output = { return standardOutput.toString().trim() } - doLast { - jdkModules = output() - if (!jdkModules.contains(cryptoPackage)) { - jdkModules += ',' + cryptoPackage - } - } +def packagePlatform = PackagePlan.Platform.fromOsName(System.getProperty('os.name')) +tasks.withType(NativePackageTask).configureEach { + group = 'distribution' + dependsOn moduleCheck + javaLauncher = packageJava + inputDirectory = layout.buildDirectory.dir('packaging/input') + moduleDirectory = layout.buildDirectory.dir('packaging/javafx') + modulesFile = moduleCheck.flatMap { it.modulesFile } + mainJar = tasks.named('jar', Jar).flatMap { it.archiveFileName } + mainClass = application.mainClass + fullVersion = project.version.toString() + platformName = packagePlatform.name() + projectRoot = layout.projectDirectory + packageResources.from(layout.projectDirectory.file('docs/license.md'), + layout.projectDirectory.file("src/main/resources/icons/${packagePlatform.iconName()}")) + logFile = layout.buildDirectory.file("reports/packaging/${name}.log") } -tasks.register('copyDependencies', Copy) { - from configurations.runtimeClasspath - into 'build/libs' - exclude 'javafx-**' +tasks.register('make', NativePackageTask) { + description = '現在の OS 向けインストーラーを生成する' + appImage = false + outputDirectory = layout.buildDirectory.dir('app') } -tasks.register('copyJavaFXModules', Copy) { - from configurations.runtimeClasspath - into 'build/javafx' - include 'javafx-**' +tasks.register('appImage', NativePackageTask) { + description = 'インストール不要のアプリケーションイメージを生成する' + appImage = true + outputDirectory = layout.buildDirectory.dir('app-image') } -def deployDir = 'build/app' -tasks.register('make', Exec) { - group = 'distribution' - description = 'アプリケーションパッケージを生成するタスク' - dependsOn checkJDKModules +abstract class MockitoAgentProvider implements CommandLineArgumentProvider { + @InputFiles + @PathSensitive(PathSensitivity.RELATIVE) + abstract ConfigurableFileCollection getAgentJar() - doFirst { - delete deployDir - } + @Override Iterable asArguments() { ["-javaagent:${agentJar.singleFile.absolutePath}"] } +} - ArrayList commandArgs = [ - 'jpackage', - '--verbose', - '--name', 'Twitch Chat Viewer', - '--description', 'Chat Viewer for twitch.tv', - '--copyright', 'Copyright (c) 2024 k7t3. All rights reserved.', - '--vendor', 'k7t3', - // バージョンの末尾に文字があると違反になるため取り除く処置 - '--app-version', version.toString().replaceAll('\\D+$', ''), - '--dest', deployDir, - '--module-path', 'build/javafx', - '--add-modules', "${-> jdkModules},${javafx.modules.join(',')}", - '--input', 'build/libs', - '--main-jar', "${-> tasks.jar.archiveFile.get().asFile.name}", - '--main-class', application.mainClass.get(), - '--license-file', 'docs/license.md', - '--java-options', "'-Dapp.version=${version}'" - ] - - def os = org.gradle.internal.os.OperatingSystem.current() - - if (os.isWindows()) { - commandArgs.addAll('--type', 'exe') - commandArgs.addAll('--icon', 'src/main/resources/icons/TwitchChatViewer.ico') - commandArgs.addAll('--win-shortcut') - commandArgs.addAll('--win-menu') - commandArgs.addAll('--win-menu-group', 'TwitchChatViewer') - commandArgs.addAll('--win-per-user-install') - commandArgs.addAll('--win-shortcut-prompt') - commandArgs.addAll('--win-upgrade-uuid', 'b78817e8-f9b8-4650-bf0a-34bca5ff4106') - commandArgs.addAll('--win-help-url', 'https://github.com/k7t3/TwitchChatViewer') - commandArgs.addAll('--win-update-url', 'https://github.com/k7t3/TwitchChatViewer/releases') - } - else if (os.isMacOsX()) { - commandArgs.addAll('--type', 'dmg') - commandArgs.addAll('--icon', 'src/main/resources/icons/TwitchChatViewer.icns') - commandArgs.addAll('--mac-package-identifier', 'TwitchChatViewer') - } - else if (os.isLinux()) { - commandArgs.addAll('--type', 'deb') - commandArgs.addAll('--icon', 'src/main/resources/icons/TwitchChatViewer-64.png') - commandArgs.addAll('--linux-menu-group', 'Network') - commandArgs.addAll('--linux-rpm-license-type', 'Apache-2.0') - commandArgs.addAll('--linux-shortcut') - } +abstract class ProductionClasspathProvider implements CommandLineArgumentProvider { + @InputFiles + @PathSensitive(PathSensitivity.RELATIVE) + abstract ConfigurableFileCollection getRuntimeClasspath() - commandLine commandArgs + @Override Iterable asArguments() { ["-Dtcv.test.production.classpath=${runtimeClasspath.asPath}"] } } test { - if (!project.hasProperty("headless") || project.headless == "true") { - // execute TestFX Tests headless -- switch off by using ./gradlew -Pheadless=false - systemProperty("testfx.robot", "glass") - systemProperty("testfx.headless", "true") + def headlessMode = !project.hasProperty('headless') || project.headless == 'true' + // GUI の toolkit とウィンドウの状態をテストクラス間で共有しない。 + forkEvery = headlessMode ? 0 : 1 + systemProperty('tcv.test.headless', headlessMode.toString()) + systemProperty('testfx.robot', 'glass') + // TestFX's legacy bootstrap selects Monocle; the toolkit now owns headless mode. + systemProperty('testfx.headless', 'false') + jvmArgs '--enable-native-access=ALL-UNNAMED' + jvmArgumentProviders.add(objects.newInstance(MockitoAgentProvider).tap { + agentJar.from(configurations.mockitoAgent) + }) + jvmArgumentProviders.add(objects.newInstance(ProductionClasspathProvider).tap { + runtimeClasspath.from(sourceSets.main.runtimeClasspath) + }) + if (headlessMode) { + systemProperty('glass.platform', 'headless') + systemProperty('java.awt.headless', 'true') systemProperty("prism.order", "sw") - systemProperty("prism.text", "t2k") - systemProperty("headless.geometry", "1600x1200-32") } - useJUnitPlatform() -} \ No newline at end of file + useJUnitPlatform { + if (!providers.gradleProperty('osKeychainTests').map { it.toBoolean() }.getOrElse(false)) { + excludeTags 'os-keychain' + } + } +} diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle new file mode 100644 index 0000000..2667cc9 --- /dev/null +++ b/buildSrc/build.gradle @@ -0,0 +1,21 @@ +plugins { id 'groovy' } + +repositories { mavenCentral() } + +def javaFeature = libs.versions.java.get().toInteger() +java { toolchain { languageVersion = JavaLanguageVersion.of(javaFeature) } } +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.release = javaFeature +} + +dependencies { + implementation gradleApi() + implementation localGroovy() + testImplementation platform(libs.junit.bom) + testImplementation libs.junit.jupiter + testImplementation libs.assertj + testRuntimeOnly libs.junit.launcher +} + +test { useJUnitPlatform() } diff --git a/buildSrc/settings.gradle b/buildSrc/settings.gradle new file mode 100644 index 0000000..e753c9d --- /dev/null +++ b/buildSrc/settings.gradle @@ -0,0 +1,7 @@ +rootProject.name = 'buildSrc' + +dependencyResolutionManagement { + versionCatalogs { + libs { from(files('../gradle/libs.versions.toml')) } + } +} diff --git a/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkModulesTask.groovy b/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkModulesTask.groovy new file mode 100644 index 0000000..874f475 --- /dev/null +++ b/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkModulesTask.groovy @@ -0,0 +1,48 @@ +package com.github.k7t3.tcv.build + +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.ListProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.* +import org.gradle.work.DisableCachingByDefault +import java.nio.charset.StandardCharsets +import java.nio.file.Files + +@DisableCachingByDefault(because = 'Invokes the selected native JDK tool') +abstract class JdkModulesTask extends JdkToolTask { + @InputDirectory @PathSensitive(PathSensitivity.RELATIVE) abstract DirectoryProperty getInputDirectory() + @InputDirectory @PathSensitive(PathSensitivity.RELATIVE) abstract DirectoryProperty getModuleDirectory() + @Input abstract Property getMainJar() + @Input abstract ListProperty getJavafxModules() + @OutputFile abstract RegularFileProperty getModulesFile() + @Override protected String getToolName() { 'jdeps' } + + @TaskAction void inspectModules() { + verifyToolchain() + def output = new ByteArrayOutputStream() + def errors = new ByteArrayOutputStream() + def toolExecutable = executable + def result = execOperations.exec { + executable = toolExecutable + args '--module-path', moduleDirectory.get().asFile.absolutePath, + '--add-modules', 'ALL-MODULE-PATH', '--multi-release', javaFeatureVersion.get().toString(), + '--ignore-missing-deps', '--print-module-deps', + '--class-path', new File(inputDirectory.get().asFile, '*').absolutePath, + inputDirectory.file(mainJar).get().asFile.absolutePath + standardOutput = output + errorOutput = errors + ignoreExitValue = true + } + if (result.exitValue != 0) { + logger.error(output.toString(StandardCharsets.UTF_8)) + logger.error(errors.toString(StandardCharsets.UTF_8)) + result.assertNormalExitValue() + } + def modules = PackagePlan.modules(output.toString(StandardCharsets.UTF_8), javafxModules.get()) + def target = modulesFile.get().asFile.toPath() + Files.createDirectories(target.parent) + Files.writeString(target, modules.join(',') + '\n', StandardCharsets.UTF_8) + logger.lifecycle("Runtime modules: ${modules.join(',')}") + } +} diff --git a/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkToolTask.groovy b/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkToolTask.groovy new file mode 100644 index 0000000..78d16d1 --- /dev/null +++ b/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkToolTask.groovy @@ -0,0 +1,32 @@ +package com.github.k7t3.tcv.build + +import org.gradle.api.DefaultTask +import org.gradle.api.GradleException +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Internal +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.Nested +import org.gradle.jvm.toolchain.JavaLauncher +import org.gradle.process.ExecOperations +import javax.inject.Inject + +/** コンパイル・テストと同じ toolchain の JDK ツールを使う。 */ +abstract class JdkToolTask extends DefaultTask { + @Nested abstract Property getJavaLauncher() + @Input abstract Property getJavaFeatureVersion() + @Inject protected abstract ExecOperations getExecOperations() + @Internal protected abstract String getToolName() + + @Internal String getExecutable() { + def suffix = System.getProperty('os.name').toLowerCase(Locale.ROOT).startsWith('windows') ? '.exe' : '' + javaLauncher.get().metadata.installationPath.file("bin/${toolName}${suffix}").asFile.absolutePath + } + + protected void verifyToolchain() { + def metadata = javaLauncher.get().metadata + if (metadata.languageVersion.asInt() != javaFeatureVersion.get() || !new File(executable).isFile()) { + throw new GradleException("${toolName} requires a complete Java ${javaFeatureVersion.get()} JDK: ${metadata.installationPath}") + } + logger.lifecycle("${toolName}: ${executable} (Java ${metadata.javaRuntimeVersion})") + } +} diff --git a/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/NativePackageTask.groovy b/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/NativePackageTask.groovy new file mode 100644 index 0000000..f3bce61 --- /dev/null +++ b/buildSrc/src/main/groovy/com/github/k7t3/tcv/build/NativePackageTask.groovy @@ -0,0 +1,64 @@ +package com.github.k7t3.tcv.build + +import org.gradle.api.GradleException +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.* +import org.gradle.work.DisableCachingByDefault +import java.nio.charset.StandardCharsets +import java.nio.file.Files + +@DisableCachingByDefault(because = 'Native packaging also depends on external OS tools') +abstract class NativePackageTask extends JdkToolTask { + @InputDirectory @PathSensitive(PathSensitivity.RELATIVE) abstract DirectoryProperty getInputDirectory() + @InputDirectory @PathSensitive(PathSensitivity.RELATIVE) abstract DirectoryProperty getModuleDirectory() + @InputFile @PathSensitive(PathSensitivity.NONE) abstract RegularFileProperty getModulesFile() + @Input abstract Property getMainJar() + @Input abstract Property getMainClass() + @Input abstract Property getFullVersion() + @Input abstract Property getPlatformName() + @Input abstract Property getAppImage() + @Internal abstract DirectoryProperty getProjectRoot() + @InputFiles @PathSensitive(PathSensitivity.RELATIVE) abstract ConfigurableFileCollection getPackageResources() + @OutputDirectory abstract DirectoryProperty getOutputDirectory() + @LocalState abstract RegularFileProperty getLogFile() + @Override protected String getToolName() { 'jpackage' } + + NativePackageTask() { + // WiX / hdiutil / dpkg と署名環境は Gradle の入力だけでは追跡できない。 + outputs.upToDateWhen { false } + } + + @TaskAction void createPackage() { + verifyToolchain() + def platform = PackagePlan.Platform.valueOf(platformName.get()) + def modules = PackagePlan.modules(Files.readString(modulesFile.get().asFile.toPath()).trim(), []) + def input = new PackagePlan.Inputs(platform, appImage.get(), fullVersion.get(), + inputDirectory.get().asFile.toPath(), moduleDirectory.get().asFile.toPath(), + mainJar.get(), mainClass.get(), projectRoot.get().asFile.toPath(), modules) + PackagePlan.validateInputs(input) + def log = logFile.get().asFile.toPath() + def toolExecutable = executable + Files.createDirectories(log.parent) + def produced = PackageOutput.produce(outputDirectory.get().asFile.toPath(), { staging -> + Files.newOutputStream(log).withCloseable { stream -> + def result = execOperations.exec { + executable = toolExecutable + args PackagePlan.arguments(input, staging) + standardOutput = stream + errorOutput = stream + ignoreExitValue = true + } + if (result.exitValue != 0) { + throw new GradleException("jpackage failed (${result.exitValue}); see ${log.toAbsolutePath()}") + } + } + } as PackageOutput.Generator) + logger.lifecycle("Created package: ${produced.output()}; log: ${log.toAbsolutePath()}") + produced.cleanupFailures().each { cleanup -> + logger.warn("Package was created, but cleanup failed for owned directory ${cleanup.directory()}", cleanup.failure()) + } + } +} diff --git a/buildSrc/src/main/java/com/github/k7t3/tcv/build/LinuxGlibcRequirement.java b/buildSrc/src/main/java/com/github/k7t3/tcv/build/LinuxGlibcRequirement.java new file mode 100644 index 0000000..91cdb51 --- /dev/null +++ b/buildSrc/src/main/java/com/github/k7t3/tcv/build/LinuxGlibcRequirement.java @@ -0,0 +1,135 @@ +package com.github.k7t3.tcv.build; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.regex.Pattern; +import java.util.zip.ZipFile; + +/** 解決済みの対象OS/CPU向けJavaFX JARから、ELF64の強いGLIBCバージョン参照を読む。 */ +final class LinuxGlibcRequirement { + private static final int VERSION_NEEDS = 0x6ffffffe; + private static final int WEAK_VERSION = 2; + private static final Pattern GLIBC_VERSION = Pattern.compile("GLIBC_(\\d+(?:\\.\\d+)+)"); + private LinuxGlibcRequirement() {} + + /** 解析不能なネイティブ資源は、要件を省略せずIOExceptionで報告する。 */ + static Optional minimumVersion(Path moduleDirectory) throws IOException { + Version highest = null; + try (var files = Files.list(moduleDirectory)) { + for (var path : files.filter(file -> file.getFileName().toString().endsWith(".jar")).sorted().toList()) { + try (var archive = new ZipFile(path.toFile())) { + var entries = archive.entries(); + while (entries.hasMoreElements()) { + var entry = entries.nextElement(); + if (entry.isDirectory() || !entry.getName().endsWith(".so")) continue; + try (var input = archive.getInputStream(entry)) { + highest = maximum(highest, read(input.readAllBytes())); + } catch (IOException failure) { + throw new IOException("Cannot inspect native ABI: " + path + "!/" + entry.getName(), failure); + } + } + } + } + } + return Optional.ofNullable(highest).map(Version::text); + } + + private static Version read(byte[] bytes) throws IOException { + try { + if (bytes.length < 64 || bytes[0] != 0x7f || bytes[1] != 'E' || bytes[2] != 'L' + || bytes[3] != 'F' || bytes[4] != 2 || bytes[5] != 1) + throw new IOException("Expected a little-endian ELF64 native resource"); + var data = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN); + var table = Math.toIntExact(data.getLong(40)); + var entrySize = Short.toUnsignedInt(data.getShort(58)); + var count = Short.toUnsignedInt(data.getShort(60)); + if (entrySize < 64 || count == 0) throw new IOException("ELF section headers unavailable"); + range(table, Math.multiplyExact(entrySize, count), bytes.length); + Version highest = null; + // 未使用の文字列や定義を拾わず、SHT_GNU_verneedとそのVernauxだけを辿る。 + for (var i = 0; i < count; i++) { + var header = table + i * entrySize; + if (data.getInt(header + 4) != VERSION_NEEDS) continue; + var linked = data.getInt(header + 40); + if (linked < 0 || linked >= count) throw new IOException("Invalid ELF version string-table link"); + var stringHeader = table + linked * entrySize; + if (data.getInt(stringHeader + 4) != 3) throw new IOException("ELF version link is not a string table"); + var strings = section(data, stringHeader); + var needs = section(data, header); + var record = needs.offset(); + while (record < needs.end()) { + range(record, 16, needs.end()); + if (data.getShort(record) != 1) throw new IOException("Unsupported ELF version-needs revision"); + var versions = Short.toUnsignedInt(data.getShort(record + 2)); + var auxiliary = Math.addExact(record, unsigned(data, record + 8)); + for (var j = 0; j < versions; j++) { + range(auxiliary, 16, needs.end()); + var name = string(bytes, strings, unsigned(data, auxiliary + 8)); + var match = GLIBC_VERSION.matcher(name); + if ((data.getShort(auxiliary + 4) & WEAK_VERSION) == 0) { + if (match.matches()) highest = maximum(highest, new Version(match.group(1))); + else if (name.startsWith("GLIBC_")) throw new IOException("Unsupported GLIBC version requirement: " + name); + } + var next = unsigned(data, auxiliary + 12); + if (j + 1 < versions && next < 16) throw new IOException("Truncated ELF auxiliary version chain"); + auxiliary = Math.addExact(auxiliary, next); + } + var next = unsigned(data, record + 12); + if (next == 0) break; + if (next < 16) throw new IOException("Invalid ELF version-needs chain"); + record = Math.addExact(record, next); + range(record, 16, needs.end()); + } + } + return highest; + } catch (IndexOutOfBoundsException | ArithmeticException | NumberFormatException failure) { + throw new IOException("Invalid ELF native version metadata", failure); + } + } + + private static Section section(ByteBuffer data, int header) throws IOException { + var offset = Math.toIntExact(data.getLong(header + 24)); + var size = Math.toIntExact(data.getLong(header + 32)); + range(offset, size, data.limit()); + return new Section(offset, size); + } + + private static String string(byte[] bytes, Section table, int index) throws IOException { + if (index < 0 || index >= table.size()) throw new IOException("Invalid ELF version string index"); + var start = table.offset() + index; + var end = start; + while (end < table.end() && bytes[end] != 0) end++; + if (end == table.end()) throw new IOException("Unterminated ELF version string"); + return new String(bytes, start, end - start, StandardCharsets.US_ASCII); + } + + private static int unsigned(ByteBuffer data, int offset) { return Math.toIntExact(Integer.toUnsignedLong(data.getInt(offset))); } + + private static void range(int offset, int size, int limit) throws IOException { + if (offset < 0 || size < 0 || offset > limit || size > limit - offset) throw new IOException("ELF metadata range outside section"); + } + + private static Version maximum(Version left, Version right) { + return right == null || left != null && left.compareTo(right) >= 0 ? left : right; + } + + private record Section(int offset, int size) { int end() { return offset + size; } } + + private record Version(String text, List parts) implements Comparable { + Version(String text) { this(text, Arrays.stream(text.split("\\.")).map(Integer::parseInt).toList()); } + @Override public int compareTo(Version other) { + for (var i = 0; i < Math.max(parts.size(), other.parts.size()); i++) { + var comparison = Integer.compare(i < parts.size() ? parts.get(i) : 0, i < other.parts.size() ? other.parts.get(i) : 0); + if (comparison != 0) return comparison; + } + return 0; + } + } +} diff --git a/buildSrc/src/main/java/com/github/k7t3/tcv/build/PackageOutput.java b/buildSrc/src/main/java/com/github/k7t3/tcv/build/PackageOutput.java new file mode 100644 index 0000000..d2de95a --- /dev/null +++ b/buildSrc/src/main/java/com/github/k7t3/tcv/build/PackageOutput.java @@ -0,0 +1,111 @@ +package com.github.k7t3.tcv.build; + +import java.io.IOException; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +/** 公開前の失敗では直前の成果物を残し、公開後の削除失敗は公開結果に付記する。 */ +public final class PackageOutput { + private PackageOutput() {} + @FunctionalInterface public interface Generator { void generate(Path staging) throws Exception; } + @FunctionalInterface interface Mover { void move(Path source, Path target) throws IOException; } + @FunctionalInterface interface Remover { void remove(Path path) throws IOException; } + + /** 公開済み出力と、呼出側が報告する削除失敗。 */ + public record Result(Path output, List cleanupFailures) { + public Result { Objects.requireNonNull(output); cleanupFailures = List.copyOf(cleanupFailures); } + } + + /** 削除できず残った自己所有領域と元のI/O失敗。 */ + public record CleanupFailure(Path directory, IOException failure) { + public CleanupFailure { Objects.requireNonNull(directory); Objects.requireNonNull(failure); } + } + + public static Result produce(Path output, Generator generator) throws Exception { return produce(output, generator, PackageOutput::move); } + + static Result produce(Path output, Generator generator, Mover mover) throws Exception { + return produce(output, generator, mover, PackageOutput::deleteTree); + } + + static Result produce(Path output, Generator generator, Mover mover, Remover remover) throws Exception { + var destination = output.toAbsolutePath().normalize(); + if (destination.getParent() == null || (Files.exists(destination, LinkOption.NOFOLLOW_LINKS) + && !Files.isDirectory(destination, LinkOption.NOFOLLOW_LINKS))) { + throw new IllegalArgumentException("package output must be an owned directory: " + destination); + } + Files.createDirectories(destination.getParent()); + var staging = Files.createTempDirectory(destination.getParent(), ".tcv-package-"); + var cleanupFailures = new ArrayList(); + boolean published = false; + Throwable failure = null; + try { + generator.generate(staging); + try (var generated = Files.list(staging)) { + if (generated.findAny().isEmpty()) throw new IOException("generator produced no package"); + } + publish(staging, destination, mover, remover, cleanupFailures); + published = true; + } catch (Exception | Error original) { + failure = original; + throw original; + } finally { + try { remover.remove(staging); } + catch (IOException cleanup) { + if (failure != null) failure.addSuppressed(cleanup); + else if (published) cleanupFailures.add(new CleanupFailure(staging, cleanup)); + else throw cleanup; + } + } + return new Result(destination, cleanupFailures); + } + + private static void publish(Path staging, Path destination, Mover mover, Remover remover, + List cleanupFailures) throws IOException { + var backup = destination.getParent().resolve(".tcv-previous-" + UUID.randomUUID()); + var previous = Files.exists(destination, LinkOption.NOFOLLOW_LINKS); + if (previous) mover.move(destination, backup); + try { mover.move(staging, destination); } + catch (IOException | RuntimeException | Error original) { + if (previous) { + try { mover.move(backup, destination); } + catch (IOException | RuntimeException | Error restore) { + if (restore != original) original.addSuppressed(restore); + original.addSuppressed(new IOException("Previous package remains at " + backup)); + } + } + throw original; + } + if (previous) { + try { remover.remove(backup); } + catch (IOException cleanup) { cleanupFailures.add(new CleanupFailure(backup, cleanup)); } + } + } + + private static void move(Path source, Path target) throws IOException { + try { Files.move(source, target, StandardCopyOption.ATOMIC_MOVE); } + catch (AtomicMoveNotSupportedException unsupported) { Files.move(source, target); } + } + + private static void deleteTree(Path path) throws IOException { + if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) return; + Files.walkFileTree(path, new SimpleFileVisitor<>() { + @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { + Files.delete(file); return FileVisitResult.CONTINUE; + } + @Override public FileVisitResult postVisitDirectory(Path directory, IOException failure) throws IOException { + if (failure != null) throw failure; + Files.delete(directory); return FileVisitResult.CONTINUE; + } + }); + } +} diff --git a/buildSrc/src/main/java/com/github/k7t3/tcv/build/PackagePlan.java b/buildSrc/src/main/java/com/github/k7t3/tcv/build/PackagePlan.java new file mode 100644 index 0000000..181efd2 --- /dev/null +++ b/buildSrc/src/main/java/com/github/k7t3/tcv/build/PackagePlan.java @@ -0,0 +1,115 @@ +package com.github.k7t3.tcv.build; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.TreeSet; +import java.util.regex.Pattern; + +/** jpackage の引数を不変の入力から組み立てる。外部コマンドや既存の配布物には作用しない。 */ +public final class PackagePlan { + private static final Pattern VERSION = Pattern.compile("([0-9]+)\\.([0-9]+)\\.([0-9]+)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?"); + private static final Pattern MODULE = Pattern.compile("[A-Za-z_][A-Za-z0-9_.]*"); + + private PackagePlan() {} + + public enum Platform { + WINDOWS("exe", "TwitchChatViewer.ico"), MAC("dmg", "TwitchChatViewer.icns"), LINUX("deb", "TwitchChatViewer-64.png"); + private final String installer; + private final String icon; + Platform(String installer, String icon) { this.installer = installer; this.icon = icon; } + public String installerType() { return installer; } + public String iconName() { return icon; } + public static Platform fromOsName(String name) { + var value = name.toLowerCase(Locale.ROOT); + if (value.startsWith("windows")) return WINDOWS; + if (value.startsWith("mac")) return MAC; + if (value.startsWith("linux")) return LINUX; + throw new IllegalArgumentException("unsupported packaging OS: " + name); + } + } + + public record Inputs(Platform platform, boolean appImage, String fullVersion, Path inputDirectory, Path moduleDirectory, + String mainJar, String mainClass, Path projectRoot, List modules) { + public Inputs { modules = List.copyOf(modules); } + } + + public static String nativeVersion(String version) { + var matcher = VERSION.matcher(version == null ? "" : version); + if (!matcher.matches()) throw new IllegalArgumentException("invalid application version: " + version); + return matcher.group(1) + "." + matcher.group(2) + "." + matcher.group(3); + } + + public static List modules(String output, List javafx) { + if (output == null || output.isBlank()) throw new IllegalArgumentException("jdeps returned no modules"); + var modules = new TreeSet(); + for (var name : output.trim().split(",", -1)) { + if (!MODULE.matcher(name).matches()) throw new IllegalArgumentException("invalid jdeps module: " + name); + modules.add(name); + } + for (var name : javafx) { + if (!MODULE.matcher(name).matches()) throw new IllegalArgumentException("invalid javafx module: " + name); + modules.add(name); + } + modules.add("jdk.crypto.ec"); + return List.copyOf(modules); + } + + public static void validateInputs(Inputs input) { + nativeVersion(input.fullVersion()); + var jar = input.mainJar(); + if (jar == null || jar.isBlank() || jar.contains("/") || jar.contains("\\") || jar.equals(".") || jar.equals("..")) + throw new IllegalArgumentException("main JAR must be an input file name"); + if (!Files.isRegularFile(input.inputDirectory().resolve(jar))) throw new IllegalArgumentException("missing main JAR: " + jar); + if (!Files.isRegularFile(input.inputDirectory().resolve("key-storage.properties"))) + throw new IllegalArgumentException("missing key storage launcher configuration"); + if (!Files.isDirectory(input.moduleDirectory())) throw new IllegalArgumentException("missing JavaFX module directory"); + if (!Files.isRegularFile(input.projectRoot().resolve("docs/license.md"))) throw new IllegalArgumentException("missing package license"); + if (!Files.isRegularFile(icon(input))) throw new IllegalArgumentException("missing package icon: " + icon(input)); + modules(String.join(",", input.modules()), List.of()); + } + + private static Path icon(Inputs input) { return input.projectRoot().resolve("src/main/resources/icons").resolve(input.platform().iconName()); } + + /** + * 検証済みの入力から引数を組み立て、Linuxインストーラーには対象JavaFXのGLIBC要件も加える。 + * @param input 配布対象と入力ファイル + * @param output 自己所有の生成先 + * @return 呼出側が変更できない引数一覧 + * @throws IOException Linuxネイティブ資源の読取・ABI解析に失敗した場合 + */ + public static List arguments(Inputs input, Path output) throws IOException { + validateInputs(input); + var args = new ArrayList<>(List.of( + "--verbose", "--type", input.appImage() ? "app-image" : input.platform().installerType(), + "--name", "Twitch Chat Viewer", "--description", "Chat Viewer for twitch.tv", + "--copyright", "Copyright (c) 2024 k7t3. All rights reserved.", "--vendor", "k7t3", + "--app-version", nativeVersion(input.fullVersion()), "--dest", output.toString(), + "--module-path", input.moduleDirectory().toString(), "--add-modules", String.join(",", modules(String.join(",", input.modules()), List.of())), + "--input", input.inputDirectory().toString(), "--main-jar", input.mainJar(), "--main-class", input.mainClass(), + "--add-launcher", "Twitch Key Storage=" + input.inputDirectory().resolve("key-storage.properties"), + "--java-options", "-Dapp.version=" + input.fullVersion(), + "--java-options", "--enable-native-access=javafx.graphics,ALL-UNNAMED", "--icon", icon(input).toString())); + if (input.platform() == Platform.MAC) args.addAll(List.of("--mac-package-identifier", "TwitchChatViewer")); + if (!input.appImage()) { + args.addAll(List.of("--license-file", input.projectRoot().resolve("docs/license.md").toString())); + switch (input.platform()) { + case WINDOWS -> args.addAll(List.of("--win-shortcut", "--win-menu", "--win-menu-group", "TwitchChatViewer", "--win-per-user-install", + "--win-shortcut-prompt", "--win-upgrade-uuid", "b78817e8-f9b8-4650-bf0a-34bca5ff4106", "--win-help-url", + "https://github.com/k7t3/TwitchChatViewer", "--win-update-url", "https://github.com/k7t3/TwitchChatViewer/releases")); + case LINUX -> { + var dependencies = new ArrayList<>(List.of("libsecret-1-0 (>= 0.19.0)", "libgtk-3-0 (>= 3.20.0)", "libxtst6")); + LinuxGlibcRequirement.minimumVersion(input.moduleDirectory()) + .ifPresent(version -> dependencies.add("libc6 (>= " + version + ")")); + args.addAll(List.of("--linux-menu-group", "Network", "--linux-rpm-license-type", "Apache-2.0", "--linux-shortcut", + "--linux-package-deps", String.join(", ", dependencies))); + } + case MAC -> {} + } + } + return List.copyOf(args); + } +} diff --git a/buildSrc/src/test/java/com/github/k7t3/tcv/build/LinuxGlibcRequirementTest.java b/buildSrc/src/test/java/com/github/k7t3/tcv/build/LinuxGlibcRequirementTest.java new file mode 100644 index 0000000..8972f63 --- /dev/null +++ b/buildSrc/src/test/java/com/github/k7t3/tcv/build/LinuxGlibcRequirementTest.java @@ -0,0 +1,170 @@ +package com.github.k7t3.tcv.build; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.Consumer; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class LinuxGlibcRequirementTest { + @TempDir Path directory; + + @Test + void theRequiredVersionComesFromTheHighestNativeReferenceAcrossModuleJars() throws Exception { + module("base.jar", elf("GLIBC_2.17", "GLIBC_2.9")); + module("graphics.jar", elf("GLIBC_2.38")); + + var required = LinuxGlibcRequirement.minimumVersion(directory); + + assertThat(required).contains("2.38"); + } + + @Test + void optionalWeakVersionsDoNotRaiseTheRequiredRuntimeVersion() throws Exception { + var data = ByteBuffer.wrap(elf("GLIBC_2.17", "GLIBC_9.99")).order(ByteOrder.LITTLE_ENDIAN); + var needs = Math.toIntExact(data.getLong(216)); + data.putShort(needs + 16 + 16 + 4, (short) 2); + module("graphics.jar", data.array()); + + assertThat(LinuxGlibcRequirement.minimumVersion(directory)).contains("2.17"); + } + + @Test + void unknownGlibcRequirementsCannotSilentlyDeclareAnOlderRuntime() throws Exception { + module("graphics.jar", elf("GLIBC_2.17", "GLIBC_FUTURE")); + + assertThatThrownBy(() -> LinuxGlibcRequirement.minimumVersion(directory)) + .isInstanceOf(IOException.class) + .hasMessageContaining("graphics.jar!/libsample.so") + .hasRootCauseMessage("Unsupported GLIBC version requirement: GLIBC_FUTURE"); + } + + @Test + void unreferencedVersionTextDoesNotRaiseTheRuntimeRequirement() throws Exception { + var library = elf("GLIBC_2.17"); + var extra = "GLIBC_99.0\0".getBytes(StandardCharsets.US_ASCII); + var withDebugText = Arrays.copyOf(library, library.length + extra.length); + System.arraycopy(extra, 0, withDebugText, library.length, extra.length); + module("graphics.jar", withDebugText); + + assertThat(LinuxGlibcRequirement.minimumVersion(directory)).contains("2.17"); + } + + @Test + void modulesWithoutNativeLibrariesHaveNoAdditionalGlibcRequirement() throws Exception { + try (var archive = new ZipOutputStream(Files.newOutputStream(directory.resolve("controls.jar")))) { + archive.putNextEntry(new ZipEntry("fixture/Control.class")); + archive.write("GLIBC_99.0".getBytes(StandardCharsets.US_ASCII)); + archive.closeEntry(); + } + + assertThat(LinuxGlibcRequirement.minimumVersion(directory)).isEmpty(); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("malformedMetadata") + void malformedMetadataFailsWithTheArchiveAndResourceContext(String reason, byte[] bytes) throws Exception { + module("graphics.jar", bytes); + + assertThatThrownBy(() -> LinuxGlibcRequirement.minimumVersion(directory)) + .isInstanceOf(IOException.class) + .hasMessageContaining("graphics.jar!/libsample.so"); + } + + @Test + void theInstallerDeclaresTheAbiRequiredByItsResolvedJavafxModules() throws Exception { + module("graphics.jar", elf("GLIBC_2.17", "GLIBC_2.38")); + var input = Files.createDirectories(directory.resolve("input")); + Files.writeString(input.resolve("app.jar"), "synthetic application fixture"); + Files.writeString(input.resolve("key-storage.properties"), "main-class=fixture.Helper"); + Files.createDirectories(directory.resolve("docs")); + Files.writeString(directory.resolve("docs/license.md"), "synthetic license"); + var icons = Files.createDirectories(directory.resolve("src/main/resources/icons")); + Files.writeString(icons.resolve("TwitchChatViewer-64.png"), "synthetic icon"); + var plan = new PackagePlan.Inputs(PackagePlan.Platform.LINUX, false, "1.0.0", input, directory, + "app.jar", "fixture.Main", directory, List.of("java.base")); + + var arguments = PackagePlan.arguments(plan, directory.resolve("output")); + + assertThat(arguments).contains("--linux-package-deps"); + assertThat(arguments.get(arguments.indexOf("--linux-package-deps") + 1)) + .contains("libc6 (>= 2.38)"); + } + + private static Stream malformedMetadata() throws Exception { + var valid = elf("GLIBC_2.17", "GLIBC_2.38"); + var header = ByteBuffer.wrap(valid).order(ByteOrder.LITTLE_ENDIAN); + var needs = Math.toIntExact(header.getLong(216)); + var lastStringByte = Math.toIntExact(header.getLong(152) + header.getLong(160) - 1); + return Stream.of( + Arguments.of("truncated header", Arrays.copyOf(valid, 32)), + Arguments.of("unsupported byte order", changed(valid, data -> data.put(5, (byte) 2))), + Arguments.of("section-table overflow", changed(valid, data -> data.putLong(40, Long.MAX_VALUE))), + Arguments.of("invalid string-table link", changed(valid, data -> data.putInt(232, 99))), + Arguments.of("invalid version string index", changed(valid, data -> data.putInt(needs + 16 + 8, Integer.MAX_VALUE))), + Arguments.of("unterminated version string", changed(valid, data -> data.put(lastStringByte, (byte) 'x'))), + Arguments.of("truncated auxiliary chain", changed(valid, data -> data.putInt(needs + 16 + 12, 0))), + Arguments.of("unsupported numeric version", elf("GLIBC_2.99999999999999999999"))); + } + + private static byte[] changed(byte[] bytes, Consumer edit) { + var result = bytes.clone(); + edit.accept(ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN)); + return result; + } + + private void module(String name, byte[] nativeLibrary) throws Exception { + try (var archive = new ZipOutputStream(Files.newOutputStream(directory.resolve(name)))) { + archive.putNextEntry(new ZipEntry("libsample.so")); + archive.write(nativeLibrary); + archive.closeEntry(); + } + } + + /** ELF64の公開ABIどおりに、文字列表と1件のVerneed/Vernaux列を持つfixtureを作る。 */ + private static byte[] elf(String... versions) throws Exception { + var strings = new ByteArrayOutputStream(); + strings.write(0); + strings.write("libc.so.6\0".getBytes(StandardCharsets.US_ASCII)); + var names = new ArrayList(); + for (var version : versions) { + names.add(strings.size()); + strings.write((version + "\0").getBytes(StandardCharsets.US_ASCII)); + } + var stringOffset = 256; + var needsOffset = (stringOffset + strings.size() + 7) / 8 * 8; + var needsSize = 16 + 16 * versions.length; + var data = ByteBuffer.allocate(needsOffset + needsSize).order(ByteOrder.LITTLE_ENDIAN); + data.put(new byte[]{0x7f, 'E', 'L', 'F', 2, 1, 1}); + data.putShort(16, (short) 3).putShort(18, (short) 183).putInt(20, 1); + data.putLong(40, 64).putShort(52, (short) 64).putShort(58, (short) 64).putShort(60, (short) 3); + data.putInt(132, 3).putLong(152, stringOffset).putLong(160, strings.size()); + data.putInt(196, 0x6ffffffe).putLong(216, needsOffset).putLong(224, needsSize).putInt(232, 1).putInt(236, 1); + data.position(stringOffset); + data.put(strings.toByteArray()); + data.putShort(needsOffset, (short) 1).putShort(needsOffset + 2, (short) versions.length) + .putInt(needsOffset + 4, 1).putInt(needsOffset + 8, 16); + for (var i = 0; i < versions.length; i++) { + var auxiliary = needsOffset + 16 + i * 16; + data.putInt(auxiliary + 8, names.get(i)).putInt(auxiliary + 12, i + 1 == versions.length ? 0 : 16); + } + return data.array(); + } +} diff --git a/buildSrc/src/test/java/com/github/k7t3/tcv/build/PackageOutputTest.java b/buildSrc/src/test/java/com/github/k7t3/tcv/build/PackageOutputTest.java new file mode 100644 index 0000000..93f6665 --- /dev/null +++ b/buildSrc/src/test/java/com/github/k7t3/tcv/build/PackageOutputTest.java @@ -0,0 +1,125 @@ +package com.github.k7t3.tcv.build; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import java.io.IOException; +import java.nio.file.DirectoryNotEmptyException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.concurrent.atomic.AtomicReference; +import static org.assertj.core.api.Assertions.*; + +class PackageOutputTest { + @TempDir Path directory; + + @Test + void aRetirementFailureReportsThePublishedPackageAndItsOwnedRemnant() throws Exception { + var output = previous(); + Files.writeString(output.resolve("retained.dmg"), "remaining old package"); + var failure = new DirectoryNotEmptyException("synthetic retired directory"); + var retired = new AtomicReference(); + + var result = PackageOutput.produce(output, staging -> Files.writeString(staging.resolve("new.dmg"), "new"), + (source, target) -> Files.move(source, target, StandardCopyOption.ATOMIC_MOVE), path -> { + if (path.getFileName().toString().startsWith(".tcv-previous-")) { + retired.set(path); + Files.delete(path.resolve("previous.dmg")); + throw failure; + } + Files.deleteIfExists(path); + }); + + assertThat(result.output()).isEqualTo(output.toAbsolutePath().normalize()); + assertThat(Files.readString(output.resolve("new.dmg"))).isEqualTo("new"); + assertThat(result.cleanupFailures()).singleElement().satisfies(cleanup -> { + assertThat(cleanup.directory()).isEqualTo(retired.get()); + assertThat(cleanup.failure()).isSameAs(failure); + }); + assertThat(Files.readString(retired.get().resolve("retained.dmg"))).isEqualTo("remaining old package"); + assertThat(retired.get().resolve("previous.dmg")).doesNotExist(); + } + + @Test + void aSuccessfulPackageReplacesThePreviousDirectoryAfterGeneration() throws Exception { + var output = previous(); + PackageOutput.produce(output, stage -> { + assertThat(Files.readString(output.resolve("previous.dmg"))).isEqualTo("previous"); + Files.writeString(stage.resolve("new.dmg"), "new"); + }); + assertThat(Files.readString(output.resolve("new.dmg"))).isEqualTo("new"); assertThat(output.resolve("previous.dmg")).doesNotExist(); + assertNoTemporaryDirectories(); + } + + @ParameterizedTest @ValueSource(booleans = {false, true}) + void aGeneratorFailureKeepsTheOldPackageAndRemovesOnlyItsOwnStaging(boolean error) throws Exception { + var output = previous(); Throwable failure = error ? new AssertionError("generator failed") : new IOException("generator failed"); + assertThatThrownBy(() -> PackageOutput.produce(output, stage -> { + Files.writeString(stage.resolve("partial.dmg"), "partial"); + if (failure instanceof Error fatal) throw fatal; throw (Exception) failure; + })).isSameAs(failure); + assertThat(Files.readString(output.resolve("previous.dmg"))).isEqualTo("previous"); assertNoTemporaryDirectories(); + } + + @Test + void publicationFailureRestoresThePreviousDirectoryAndPreservesTheCause() throws Exception { + var output = previous(); var failure = new IOException("publication failed"); + assertThatThrownBy(() -> PackageOutput.produce(output, stage -> Files.writeString(stage.resolve("new.dmg"), "new"), (source, target) -> { + if (source.getFileName().toString().startsWith(".tcv-package-")) throw failure; + Files.move(source, target, StandardCopyOption.ATOMIC_MOVE); + })).isSameAs(failure); + assertThat(Files.readString(output.resolve("previous.dmg"))).isEqualTo("previous"); assertNoTemporaryDirectories(); + } + + @Test + void failedRollbackKeepsTheBackupAndReportsItsLocationAlongsideTheOriginalFailures() throws Exception { + var output = previous(); var original = new IOException("publication failed"); var rollback = new IOException("restore failed"); + assertThatThrownBy(() -> PackageOutput.produce(output, stage -> Files.writeString(stage.resolve("new.dmg"), "new"), (source, target) -> { + if (source.getFileName().toString().startsWith(".tcv-package-")) throw original; + if (source.getFileName().toString().startsWith(".tcv-previous-")) throw rollback; + Files.move(source, target, StandardCopyOption.ATOMIC_MOVE); + })).isSameAs(original).satisfies(failure -> { + assertThat(failure.getSuppressed()).contains(rollback); + assertThat(failure.getSuppressed()).anySatisfy(suppressed -> assertThat(suppressed.getMessage()).contains("Previous package remains at")); + }); + try (var children = Files.list(directory)) { + var backup = children.filter(path -> path.getFileName().toString().startsWith(".tcv-previous-")).findFirst().orElseThrow(); + assertThat(Files.readString(backup.resolve("previous.dmg"))).isEqualTo("previous"); + } + } + + @Test + void aFirstFailedPackageDoesNotCreateAnEmptySuccessfulOutput() { + var output = directory.resolve("app"); var failure = new IOException("first package failed"); + assertThatThrownBy(() -> PackageOutput.produce(output, stage -> { throw failure; })).isSameAs(failure); + assertThat(output).doesNotExist(); assertNoTemporaryDirectories(); + } + + @Test + void anEmptyGenerationDoesNotReplaceThePreviousPackage() throws Exception { + var output = previous(); + assertThatThrownBy(() -> PackageOutput.produce(output, stage -> {})) + .isInstanceOf(IOException.class).hasMessageContaining("no package"); + assertThat(Files.readString(output.resolve("previous.dmg"))).isEqualTo("previous"); + assertNoTemporaryDirectories(); + } + + @Test + void anExistingNonDirectoryIsNeverReplaced() throws Exception { + var output = directory.resolve("app"); Files.writeString(output, "unrelated file"); + assertThatThrownBy(() -> PackageOutput.produce(output, stage -> Files.writeString(stage.resolve("new.dmg"), "new"))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(Files.readString(output)).isEqualTo("unrelated file"); assertNoTemporaryDirectories(); + } + + private Path previous() throws Exception { + var output = directory.resolve("app"); Files.createDirectories(output); Files.writeString(output.resolve("previous.dmg"), "previous"); return output; + } + private void assertNoTemporaryDirectories() { + try (var children = Files.list(directory)) { + assertThat(children.filter(path -> path.getFileName().toString().startsWith(".tcv-")).toList()).isEmpty(); + } catch (IOException failure) { throw new AssertionError(failure); } + } +} diff --git a/buildSrc/src/test/java/com/github/k7t3/tcv/build/PackagePlanTest.java b/buildSrc/src/test/java/com/github/k7t3/tcv/build/PackagePlanTest.java new file mode 100644 index 0000000..b41fe7b --- /dev/null +++ b/buildSrc/src/test/java/com/github/k7t3/tcv/build/PackagePlanTest.java @@ -0,0 +1,153 @@ +package com.github.k7t3.tcv.build; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import static org.assertj.core.api.Assertions.*; + +class PackagePlanTest { + @TempDir Path directory; + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void linuxInstallersRequireTheBinarySecretServiceLibrary(boolean image) throws Exception { + var arguments = PackagePlan.arguments(input(PackagePlan.Platform.LINUX, image), directory.resolve("package output")); + + if (image) assertThat(arguments).doesNotContain("--linux-package-deps"); + else { + assertThat(arguments).contains("--linux-package-deps"); + assertThat(arguments.get(arguments.indexOf("--linux-package-deps") + 1)) + .contains("libsecret-1-0 (>= 0.19.0)"); + } + } + + @Test + void linuxInstallersRequireTheGtkRuntimeUsedByJavafx() throws Exception { + var arguments = PackagePlan.arguments(input(PackagePlan.Platform.LINUX, false), directory.resolve("package output")); + + assertThat(arguments).contains("--linux-package-deps"); + assertThat(arguments.get(arguments.indexOf("--linux-package-deps") + 1)) + .contains("libgtk-3-0 (>= 3.20.0)"); + } + + @Test + void linuxInstallersRequireTheXTestLibraryLoadedByJavafx() throws Exception { + var arguments = PackagePlan.arguments(input(PackagePlan.Platform.LINUX, false), directory.resolve("package output")); + + assertThat(arguments).contains("--linux-package-deps"); + assertThat(arguments.get(arguments.indexOf("--linux-package-deps") + 1)) + .contains("libxtst6"); + } + + @ParameterizedTest + @CsvSource({"WINDOWS,true", "WINDOWS,false", "MAC,true", "MAC,false", "LINUX,true", "LINUX,false"}) + void packagesIncludeASeparateSecretStorageLauncher(PackagePlan.Platform platform, boolean image) throws Exception { + var input = input(platform, image); + + var arguments = PackagePlan.arguments(input, directory.resolve("package output")); + + assertThat(arguments).containsSequence("--add-launcher", "Twitch Key Storage=" + + input.inputDirectory().resolve("key-storage.properties")); + } + + @ParameterizedTest + @CsvSource({"WINDOWS,true", "WINDOWS,false", "MAC,true", "MAC,false", "LINUX,true", "LINUX,false"}) + void launchersEnableNativeAccessForJavafxAndClasspathLibraries(PackagePlan.Platform platform, boolean image) throws Exception { + assertThat(PackagePlan.arguments(input(platform, image), directory.resolve("package output"))) + .containsSequence("--java-options", "--enable-native-access=javafx.graphics,ALL-UNNAMED"); + } + + @ParameterizedTest @CsvSource({"WINDOWS,exe,TwitchChatViewer.ico", "MAC,dmg,TwitchChatViewer.icns", "LINUX,deb,TwitchChatViewer-64.png"}) + void nativePackagesKeepTheirPlatformOptionsAndPassUnquotedArguments(PackagePlan.Platform platform, String type, String icon) throws Exception { + var input = input(platform, false); var output = directory.resolve("native output"); + var args = PackagePlan.arguments(input, output); + assertThat(args).containsSequence("--type", type).containsSequence("--app-version", "2.3.4") + .containsSequence("--java-options", "-Dapp.version=2.3.4-beta.2+42") + .containsSequence("--input", input.inputDirectory().toString()).containsSequence("--dest", output.toString()) + .containsSequence("--main-jar", "tcv-2.3.4-beta.2+42.jar") + .containsSequence("--icon", input.projectRoot().resolve("src/main/resources/icons").resolve(icon).toString()) + .containsSequence("--license-file", input.projectRoot().resolve("docs/license.md").toString()); + assertThat(args.stream().noneMatch(argument -> argument.startsWith("'") || argument.startsWith("\""))).isTrue(); + switch (platform) { + case WINDOWS -> assertThat(args).containsSequence("--win-upgrade-uuid", "b78817e8-f9b8-4650-bf0a-34bca5ff4106").contains("--win-per-user-install"); + case MAC -> assertThat(args).containsSequence("--mac-package-identifier", "TwitchChatViewer"); + case LINUX -> assertThat(args).containsSequence("--linux-menu-group", "Network").contains("--linux-shortcut"); + } + } + + @ParameterizedTest @ValueSource(strings = {"WINDOWS", "MAC", "LINUX"}) + void applicationImagesUseLauncherOptionsAndOmitInstallerOnlyOptions(PackagePlan.Platform platform) throws Exception { + var args = PackagePlan.arguments(input(platform, true), directory.resolve("app image")); + assertThat(args).containsSequence("--type", "app-image").doesNotContain("--license-file", "--win-upgrade-uuid", "--win-menu", "--linux-shortcut"); + if (platform == PackagePlan.Platform.MAC) assertThat(args).containsSequence("--mac-package-identifier", "TwitchChatViewer"); + } + + @ParameterizedTest @CsvSource({"1.0.0-dev,1.0.0", "2.3.4-rc.2+build.9,2.3.4", "2.3.4+build.9,2.3.4", "3.0.1,3.0.1"}) + void nativeVersionsRemoveQualifiersIncludingThoseEndingInDigits(String full, String expected) { + assertThat(PackagePlan.nativeVersion(full)).isEqualTo(expected); + } + + @ParameterizedTest @NullAndEmptySource @ValueSource(strings = {"v1.2.3", "1.2", "../1.2.3", "1.2.3$(command)", "1.2.3\n--type", "1.2.3-"}) + void malformedVersionsAreRejectedBeforePackaging(String version) { + assertThatThrownBy(() -> PackagePlan.nativeVersion(version)).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("version"); + } + + @Test + void dependencyModulesAreDeduplicatedAndKeepCryptoAndJavafxRoots() { + assertThat(PackagePlan.modules("java.desktop,java.base,java.desktop\n", List.of("javafx.controls", "javafx.fxml", "javafx.swing"))) + .containsExactly("java.base", "java.desktop", "javafx.controls", "javafx.fxml", "javafx.swing", "jdk.crypto.ec"); + } + + @ParameterizedTest @ValueSource(strings = {"", " ", "Warning: missing dependencies\njava.base", "java.base,--add-modules"}) + void malformedDependencyOutputCannotBecomeLauncherArguments(String modules) { + assertThatThrownBy(() -> PackagePlan.modules(modules, List.of("javafx.controls"))).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("jdeps"); + } + + @Test + void missingInputsAndEscapingJarNamesAreRejected() throws Exception { + var input = input(PackagePlan.Platform.MAC, false); Files.delete(input.inputDirectory().resolve(input.mainJar())); + assertThatThrownBy(() -> PackagePlan.validateInputs(input)).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("main JAR"); + var escaped = new PackagePlan.Inputs(input.platform(), false, input.fullVersion(), input.inputDirectory(), input.moduleDirectory(), + "../outside.jar", input.mainClass(), input.projectRoot(), input.modules()); + assertThatThrownBy(() -> PackagePlan.arguments(escaped, directory)).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("main JAR"); + } + + @Test + void aMissingHelperConfigurationCannotProduceAPackageWithoutItsStorageLauncher() throws Exception { + var input = input(PackagePlan.Platform.MAC, true); + Files.delete(input.inputDirectory().resolve("key-storage.properties")); + + assertThatThrownBy(() -> PackagePlan.arguments(input, directory.resolve("package output"))) + .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("key storage launcher"); + } + + @Test + void platformDetectionDoesNotDependOnTheUsersLocaleAndRejectsUnknownSystems() { + var previous = Locale.getDefault(); + try { + Locale.setDefault(Locale.forLanguageTag("tr-TR")); + assertThat(PackagePlan.Platform.fromOsName("WINDOWS 11")).isEqualTo(PackagePlan.Platform.WINDOWS); + assertThat(PackagePlan.Platform.fromOsName("Mac OS X")).isEqualTo(PackagePlan.Platform.MAC); + assertThat(PackagePlan.Platform.fromOsName("Linux")).isEqualTo(PackagePlan.Platform.LINUX); + assertThatThrownBy(() -> PackagePlan.Platform.fromOsName("Plan 9")).isInstanceOf(IllegalArgumentException.class); + } finally { Locale.setDefault(previous); } + } + + private PackagePlan.Inputs input(PackagePlan.Platform platform, boolean appImage) throws Exception { + var root = directory.resolve("project with spaces"); var input = root.resolve("input"); var modules = root.resolve("javafx"); + Files.createDirectories(input); Files.createDirectories(modules); Files.createDirectories(root.resolve("docs")); + Files.createDirectories(root.resolve("src/main/resources/icons")); + Files.writeString(input.resolve("tcv-2.3.4-beta.2+42.jar"), "application"); Files.writeString(root.resolve("docs/license.md"), "license"); + Files.writeString(input.resolve("key-storage.properties"), "main-class=com.github.k7t3.tcv.app.secure.SecretStoreHelper\n"); + for (var icon : List.of("TwitchChatViewer.ico", "TwitchChatViewer.icns", "TwitchChatViewer-64.png")) Files.writeString(root.resolve("src/main/resources/icons").resolve(icon), "icon"); + return new PackagePlan.Inputs(platform, appImage, "2.3.4-beta.2+42", input, modules, "tcv-2.3.4-beta.2+42.jar", + "com.github.k7t3.tcv.view.Launcher", root, List.of("java.base", "javafx.controls", "jdk.crypto.ec")); + } +} diff --git a/docs/external-libraries.md b/docs/external-libraries.md index f4b9cfa..677e666 100644 --- a/docs/external-libraries.md +++ b/docs/external-libraries.md @@ -14,18 +14,6 @@ License: CC BY-SA 4.0 ## License -```yaml -Name: Apollo GraphQL Java libraries -URL: https://github.com/apollographql/apollo-kotlin -License: MIT -``` - -```yaml -Name: UUID (com.benasher44) -URL: https://github.com/benasher44/uuid -License: MIT -``` - ```yaml Name: JCommander URL: https://github.com/cbeust/jcommander @@ -92,18 +80,6 @@ URL: https://github.com/TakahikoKawasaki/nv-websocket-client License: Apache-2.0 ``` -```yaml -Name: Netflix Archaius -URL: https://github.com/Netflix/archaius -License: Apache-2.0 -``` - -```yaml -Name: Hystrix -URL: https://github.com/Netflix/Hystrix -License: Apache-2.0 -``` - ```yaml Name: OkHttp URL: https://github.com/square/okhttp @@ -116,24 +92,12 @@ URL: https://github.com/square/okio License: Apache-2.0 ``` -```yaml -Name: Apache Commons Configuration -URL: https://commons.apache.org/proper/commons-configuration/ -License: Apache-2.0 -``` - ```yaml Name: Apache Commons IO URL: https://commons.apache.org/proper/commons-io/ License: Apache-2.0 ``` -```yaml -Name: Apache Commons Lang -URL: https://commons.apache.org/proper/commons-lang/ -License: Apache-2.0 -``` - ```yaml Name: MVVMFX URL: https://github.com/sialcasa/mvvmFX @@ -158,18 +122,6 @@ URL: https://github.com/xanthic/cache License: Apache-2.0 ``` -```yaml -Name: RxJava -URL: https://github.com/ReactiveX/RxJava -License: Apache-2.0 -``` - -```yaml -Name: Byte Buddy -URL: https://github.com/raphw/byte-buddy -License: Apache-2.0 -``` - ```yaml Name: TypeTools URL: https://github.com/jhalterman/typetools @@ -182,24 +134,12 @@ URL: https://commons.apache.org/proper/commons-lang/ License: Apache-2.0 ``` -```yaml -Name: Checker Framework -URL: https://github.com/typetools/checker-framework -License: MIT -``` - ```yaml Name: Flowless URL: https://github.com/FXMisc/Flowless License: BSD-2-Clause ``` -```yaml -Name: HdrHistogram -URL: https://github.com/HdrHistogram/HdrHistogram -License: BSD-2-Clause or Public Domain -``` - ```yaml Name: Kotlin Standard Library URL: https://kotlinlang.org/ @@ -237,4 +177,27 @@ License: Apache-2.0 ``` -[Format Reference](https://github.com/JabRef/jabref) \ No newline at end of file +[Format Reference](https://github.com/JabRef/jabref) +```yaml +Name: JAI Image I/O Core +URL: https://github.com/jai-imageio/jai-imageio-core +License: BSD 3-clause License w/nuclear disclaimer +``` + +```yaml +Name: Doc Annotations +URL: https://github.com/lestard/doc-annotations +License: MIT +``` + +```yaml +Name: JSpecify +URL: https://jspecify.dev/ +License: Apache-2.0 +``` + +```yaml +Name: ReactFX +URL: https://github.com/FXMisc/ReactFX +License: BSD-2-Clause +``` diff --git a/docs/licenses/jai-imageio.txt b/docs/licenses/jai-imageio.txt new file mode 100644 index 0000000..c311718 --- /dev/null +++ b/docs/licenses/jai-imageio.txt @@ -0,0 +1,92 @@ +Copyright (c) 2005 Sun Microsystems, Inc. +Copyright © 2010-2014 University of Manchester +Copyright © 2010-2015 Stian Soiland-Reyes +Copyright © 2015 Peter Hull +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistribution of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistribution in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +Neither the name of Sun Microsystems, Inc. or the names of +contributors may be used to endorse or promote products derived +from this software without specific prior written permission. + +This software is provided "AS IS," without a warranty of any +kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND +WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY +EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL +NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF +USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS +DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR +ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, +CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND +REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR +INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + +You acknowledge that this software is not designed or intended for +use in the design, construction, operation or maintenance of any +nuclear facility. + + +Copyright (c) 2005 Sun Microsystems, Inc. +Copyright © 2010-2018 Stian Soiland-Reyes +Copyright © 2015 Peter Hull +Copyright © 2010-2018 University of Manchester +Copyright © 2015 Yannick De Turck +Copyright © 2015 Robin Stevens +Copyright © 2015 Mark Carroll +Copyright © 2015 Butch Howard +Copyright © 2015-2016 Luca Bellonda +Copyright © 2017 Ghislain Bonamy +Copyright © 2017 Curtis Rueden +Copyright © 2017 Roger Leigh +Copyright © 2017 Mykola Pavluchynskyi +Copyright © 2017 Sebastien Besson +Copyright © 2018 Peter Jodeleit + +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistribution of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistribution in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +Neither the name of Sun Microsystems, Inc. or the names of +contributors may be used to endorse or promote products derived +from this software without specific prior written permission. + +This software is provided "AS IS," without a warranty of any +kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND +WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY +EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL +NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF +USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS +DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR +ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, +CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND +REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR +INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + +You acknowledge that this software is not designed or intended for +use in the design, construction, operation or maintenance of any +nuclear facility. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..121a202 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,49 @@ +[versions] +java = "25" +javafx = "27.0.1" +junit = "6.1.3" +mockito = "5.24.0" +assertj = "3.27.7" +testfx = "4.0.18" +twitch4j = "1.27.0" +feign = "13.9.3" +bucket4j = "8.10.1" + +slf4j = "2.0.20" +caffeine = "3.3.1" +sqlite = "3.53.4.0" +zxing = "3.5.4" +atlantafx = "3.0.0" +ikonli = "12.4.0" +mvvmfx = "1.8.0" +flowless = "0.7.4" +hamcrest = "3.0" + +[libraries] +junit-bom = { module = "org.junit:junit-bom", version.ref = "junit" } +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" } +junit-launcher = { module = "org.junit.platform:junit-platform-launcher" } +mockito = { module = "org.mockito:mockito-core", version.ref = "mockito" } +assertj = { module = "org.assertj:assertj-core", version.ref = "assertj" } +testfx-junit5 = { module = "org.testfx:testfx-junit5", version.ref = "testfx" } +twitch-auth = { module = "com.github.twitch4j:twitch4j-auth", version.ref = "twitch4j" } +twitch-chat = { module = "com.github.twitch4j:twitch4j-chat", version.ref = "twitch4j" } +twitch-common = { module = "com.github.twitch4j:twitch4j-common", version.ref = "twitch4j" } +twitch-helix = { module = "com.github.twitch4j:twitch4j-helix", version.ref = "twitch4j" } +feign-core = { module = "io.github.openfeign:feign-core", version.ref = "feign" } +feign-jackson = { module = "io.github.openfeign:feign-jackson", version.ref = "feign" } +feign-okhttp = { module = "io.github.openfeign:feign-okhttp", version.ref = "feign" } +bucket4j = { module = "com.bucket4j:bucket4j_jdk8-core", version.ref = "bucket4j" } +slf4j-api = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" } +slf4j-jdk14 = { module = "org.slf4j:slf4j-jdk14", version.ref = "slf4j" } +caffeine = { module = "com.github.ben-manes.caffeine:caffeine", version.ref = "caffeine" } +sqlite = { module = "org.xerial:sqlite-jdbc", version.ref = "sqlite" } +zxing = { module = "com.google.zxing:javase", version.ref = "zxing" } +atlantafx = { module = "io.github.mkpaz:atlantafx-base", version.ref = "atlantafx" } +ikonli-javafx = { module = "org.kordamp.ikonli:ikonli-javafx", version.ref = "ikonli" } +ikonli-feather = { module = "org.kordamp.ikonli:ikonli-feather-pack", version.ref = "ikonli" } +ikonli-material2 = { module = "org.kordamp.ikonli:ikonli-material2-pack", version.ref = "ikonli" } +ikonli-fontawesome5 = { module = "org.kordamp.ikonli:ikonli-fontawesome5-pack", version.ref = "ikonli" } +mvvmfx = { module = "de.saxsys:mvvmfx", version.ref = "mvvmfx" } +flowless = { module = "org.fxmisc.flowless:flowless", version.ref = "flowless" } +hamcrest = { module = "org.hamcrest:hamcrest", version.ref = "hamcrest" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 249e583..9fa7f28 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 15fb9ed..5907d39 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,10 @@ -#Wed Jan 24 01:39:46 JST 2024 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +distributionSha256Sum=21bd5da2de49b642904077f38c0efdc7778e92b3ed0889392dca61b97e389607 +distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 1b6c787..249efbb 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright © 2015-2021 the original authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,10 +15,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # -# Gradle start up script for POSIX generated by Gradle. +# gradlew start up script for POSIX generated by Gradle. # # Important for running: # @@ -27,7 +29,7 @@ # bash, then to run this script, type that shell name before the whole # command line, like: # -# ksh Gradle +# ksh gradlew # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -80,13 +82,11 @@ do esac done -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" +# This is normally unused +# shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -114,7 +114,6 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -133,22 +132,29 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -165,7 +171,6 @@ fi # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) @@ -193,18 +198,27 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. diff --git a/gradlew.bat b/gradlew.bat index ac1b06f..3185a43 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,89 +1,112 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel + +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle b/settings.gradle index cda4ead..5349110 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1 @@ rootProject.name = 'tcv' - diff --git a/src/main/java/com/github/k7t3/tcv/app/auth/AuthenticatorViewModel.java b/src/main/java/com/github/k7t3/tcv/app/auth/AuthenticatorViewModel.java index 7023f33..5fe3feb 100644 --- a/src/main/java/com/github/k7t3/tcv/app/auth/AuthenticatorViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/auth/AuthenticatorViewModel.java @@ -16,14 +16,15 @@ package com.github.k7t3.tcv.app.auth; +import com.github.k7t3.tcv.app.service.BrowserActions; import com.github.k7t3.tcv.app.model.AbstractViewModel; -import com.github.k7t3.tcv.app.core.AppHelper; +import com.github.k7t3.tcv.app.core.Resources; import com.github.k7t3.tcv.app.event.LoginEvent; import com.github.k7t3.tcv.app.service.FXTask; import com.github.k7t3.tcv.domain.Twitch; import com.github.k7t3.tcv.domain.TwitchLoader; import com.github.k7t3.tcv.domain.auth.CredentialStore; -import com.github.k7t3.tcv.domain.event.EventSubscribers; +import com.github.k7t3.tcv.lifecycle.CloseActions; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.client.j2se.MatrixToImageWriter; @@ -38,13 +39,18 @@ import javafx.scene.input.DataFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import java.awt.*; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; import java.util.Map; import java.util.Optional; +import java.util.ArrayList; +import java.util.List; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; +import java.util.function.Supplier; +import java.util.function.Consumer; /** * Twitchユーザー認証用ViewModel @@ -68,43 +74,112 @@ public class AuthenticatorViewModel extends AbstractViewModel { private static final int QRCODE_HEIGHT = 480; private TwitchLoader twitchLoader; + private final Object authenticationLock = new Object(); + private Object attempt; + private Twitch pendingClient; private final ReadOnlyBooleanWrapper initialized = new ReadOnlyBooleanWrapper(false); + private final ReadOnlyBooleanWrapper busy = new ReadOnlyBooleanWrapper(false); private final ReadOnlyStringWrapper userCode = new ReadOnlyStringWrapper(); private final ReadOnlyStringWrapper authUri = new ReadOnlyStringWrapper(); private final ReadOnlyStringWrapper error = new ReadOnlyStringWrapper(); private final ReadOnlyObjectWrapper qrcode = new ReadOnlyObjectWrapper<>(); - private final CredentialStore credentialStore; + private final Supplier loaderFactory; + private final Consumer authenticated; + private final Executor executor; + private final BrowserActions browsers; + private final List> tasks = new ArrayList<>(); + private final Set operations = new HashSet<>(); + private final CompletableFuture released = new CompletableFuture<>(); + private final CompletionStage releasedResult = released.minimalCompletionStage(); + private boolean releasePrepared; + private Throwable releaseFailure; + + /** 認証URLのブラウザ起動失敗は、呼び出し元の通知先へ渡す。 */ + public AuthenticatorViewModel(CredentialStore store, Consumer authenticated, Executor executor, + Consumer failures) { + this(() -> new TwitchLoader(store), authenticated, executor, failures); + } - public AuthenticatorViewModel(CredentialStore credentialStore) { - this.credentialStore = credentialStore; + AuthenticatorViewModel(Supplier loaderFactory, Consumer authenticated, Executor executor, + Consumer failures) { + this.loaderFactory = loaderFactory; + this.authenticated = authenticated; + this.executor = executor; + browsers = new BrowserActions(executor, stage -> { + var work = beginWork(); + stage.whenComplete((ignored, failure) -> finishWork(work, failure)); + }, failures); + } + + /** 保存済み資格情報を確認し、利用できなければ Device Flow を開始する。実行中と終了後の呼び出しは無視する。 */ + public void beginAuthentication() { + if (isClosed() || isBusy()) return; + var load = loadClientAsync(); + load.onDone(result -> { + if (!isClosed() && isInitialized() && result.isEmpty()) startAuthenticateAsync(); + }); } public FXTask> loadClientAsync() { - twitchLoader = new TwitchLoader(credentialStore); - var task = FXTask.task(() -> twitchLoader.load()); + if (isClosed()) throw new IllegalStateException("authenticator is closed"); + if (isBusy()) throw new IllegalStateException("authentication is already running"); + resetAuthentication(); + error.set(null); + busy.set(true); + var token = new Object(); + synchronized (authenticationLock) { + attempt = token; + } + var task = FXTask.task(() -> { + var loader = loaderFactory.get(); + final boolean current; + synchronized (authenticationLock) { + current = isCurrent(token); + if (current) twitchLoader = loader; + } + if (!current) { releaseLoader(loader); return Optional.empty(); } + var result = loader.load(); + result.ifPresent(client -> retainClient(token, client)); + return result; + }); task.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, e -> { + if (!isCurrent(token)) return; initialized.set(true); - task.getValue().ifPresent(this::done); + busy.set(false); + task.getValue().ifPresent(client -> done(token, client)); }); LOGGER.info("load credential store"); - task.runAsync(); + submit(task, token); return task; } public FXTask startAuthenticateAsync() { + if (isClosed()) throw new IllegalStateException("authenticator is closed"); if (!initialized.get()) { throw new IllegalStateException("first, do loadCredentialAsync"); } + if (isBusy()) throw new IllegalStateException("authentication is already running"); + busy.set(true); LOGGER.info("start authenticate"); - var task = FXTask.task( - () -> twitchLoader.startAuthenticate( - twitch -> twitch.ifPresent(value -> Platform.runLater(() -> done(value))) - ) - ); + final Object token; + final TwitchLoader loader; + synchronized (authenticationLock) { + token = attempt; + loader = twitchLoader; + } + var task = FXTask.task(() -> loader.startAuthenticate(result -> { + if (result.isEmpty()) { + Platform.runLater(() -> failAuthentication(token)); + return; + } + var client = result.orElseThrow(); + if (retainClient(token, client)) Platform.runLater(() -> done(token, client)); + })); task.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, e -> { + if (!isCurrent(token)) return; var deviceFlow = task.getValue(); // 認証URI authUri.set(deviceFlow.completeURL()); @@ -112,17 +187,15 @@ public FXTask startAuthenticateAsync() { userCode.set(deviceFlow.userCode()); // QRコードを生成する - generateQRCode(deviceFlow.verificationURL()); - - LOGGER.info("device flow {}", deviceFlow); + generateQRCode(token, deviceFlow.verificationURL()); }); - task.runAsync(); + submit(task, token); return task; } - private void generateQRCode(String url) { + private void generateQRCode(Object token, String url) { var t = FXTask.task(() -> { var writer = new QRCodeWriter(); var matrix = writer.encode( @@ -135,58 +208,206 @@ private void generateQRCode(String url) { var bufferedImage = MatrixToImageWriter.toBufferedImage(matrix); return SwingFXUtils.toFXImage(bufferedImage, null); }); - t.onDone(() -> qrcode.set(t.getValue())); - t.runAsync(); + t.onDone(() -> { + if (isCurrent(token)) qrcode.set(t.getValue()); + }); + submit(t, token); + } + + private boolean isCurrent(Object token) { + synchronized (authenticationLock) { + return !isClosed() && token != null && attempt == token; + } } - private void done(Twitch twitch) { - var helper = AppHelper.getInstance(); - helper.setTwitch(twitch); + private boolean retainClient(Object token, Twitch client) { + synchronized (authenticationLock) { + if (isCurrent(token) && pendingClient == null) { + pendingClient = client; + return true; + } + } + releaseClient(client); + return false; + } + + private void done(Object token, Twitch twitch) { + synchronized (authenticationLock) { + if (!isCurrent(token) || pendingClient != twitch) return; + pendingClient = null; + } + busy.set(false); + try { + authenticated.accept(twitch); + } catch (RuntimeException | Error failure) { + try { releaseClient(twitch); } + catch (RuntimeException | Error cleanup) { if (cleanup != failure) failure.addSuppressed(cleanup); } + LOGGER.error("authenticated client was not accepted", failure); + failAuthentication(token); + return; + } // ログインイベントを発行 publish(new LoginEvent()); } - public void openAuthUri() { - var uri = getAuthUri(); - if (uri == null) return; + private void failAuthentication(Object token) { + if (!isCurrent(token)) return; + resetAuthentication(); + error.set(Resources.getString("auth.error.failed")); + } - var task = FXTask.task(() -> { - var desktop = Desktop.getDesktop(); - if (!desktop.isSupported(Desktop.Action.BROWSE)) return; - - try { - desktop.browse(new URI(uri)); - } catch (IOException e) { - LOGGER.error("NOT SUPPORTED OPEN BROWSE", e); - } catch (URISyntaxException e) { - LOGGER.error("ILLEGAL URL?", e); - } + private void submit(FXTask task, Object token) { + tasks.add(task); + task.setFinally(() -> tasks.remove(task)); + task.addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, e -> failAuthentication(token)); + task.addEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, e -> { + if (isCurrent(token)) resetAuthentication(); }); - task.runAsync(); + var operation = beginWork(); + try { + executor.execute(() -> { + try { task.run(); } + finally { finishWork(operation, null); } + }); + } catch (RuntimeException | Error rejected) { + finishWork(operation, null); + CloseActions.runAll(() -> failAuthentication(token), task::cancel); + if (!(rejected instanceof RejectedExecutionException)) rethrow(rejected); + } } - public void clipAuthUri() { - var uri = getAuthUri(); - if (uri == null) return; - - var cb = Clipboard.getSystemClipboard(); - cb.setContent(Map.of(DataFormat.PLAIN_TEXT, uri)); + @Override + protected void onClose() { + try { CloseActions.runAll(browsers::close, this::resetAuthentication); } + finally { + synchronized (authenticationLock) { + releasePrepared = true; + completeReleaseIfReady(); + } + } } @Override - public void subscribeEvents(EventSubscribers eventSubscribers) { - // no-op + protected void onLoggedOut() { + resetAuthentication(); + error.set(null); } - @Override - public void onLogout() { - // no-op + private void resetAuthentication() { + browsers.cancelAll(); + final TwitchLoader loader; + final Twitch client; + synchronized (authenticationLock) { + attempt = null; + loader = twitchLoader; + twitchLoader = null; + client = pendingClient; + pendingClient = null; + } + var pending = List.copyOf(tasks); + tasks.clear(); + CloseActions.runAll( + () -> CloseActions.runAll(pending.stream().map(task -> (Runnable) task::cancel).toArray(Runnable[]::new)), + () -> { if (loader != null) requestLoaderClose(loader); }, + () -> { if (client != null) releaseClient(client); }, + () -> { if (loader != null) executeCleanup(loader::awaitClosed); }, + () -> { + initialized.set(false); + busy.set(false); + authUri.set(null); + userCode.set(null); + qrcode.set(null); + }); } - @Override - public void close() { - // no-op + private void releaseClient(Twitch client) { + executeCleanup(client::close); + } + + private void releaseLoader(TwitchLoader loader) { + CloseActions.runAll(() -> requestLoaderClose(loader), () -> executeCleanup(loader::awaitClosed)); + } + + private void requestLoaderClose(TwitchLoader loader) { + try { loader.close(); } + catch (RuntimeException | Error failure) { + synchronized (authenticationLock) { rememberReleaseFailure(failure); } + throw failure; + } + } + + private Object beginWork() { + synchronized (authenticationLock) { + if (released.isDone()) throw new IllegalStateException("authentication resources already released"); + var operation = new Object(); + operations.add(operation); + return operation; + } + } + + private void finishWork(Object operation, Throwable failure) { + synchronized (authenticationLock) { + if (!operations.remove(operation)) return; + if (failure != null) rememberReleaseFailure(failure); + completeReleaseIfReady(); + } + } + + private void rememberReleaseFailure(Throwable failure) { + if (releaseFailure == null) releaseFailure = failure; + else if (releaseFailure != failure) releaseFailure.addSuppressed(failure); + } + + private void completeReleaseIfReady() { + if (!releasePrepared || !operations.isEmpty()) return; + if (releaseFailure == null) released.complete(null); + else released.completeExceptionally(releaseFailure); + } + + private void executeCleanup(Runnable action) { + var operation = beginWork(); + Runnable cleanup = () -> { + Throwable failure = null; + try { action.run(); } + catch (RuntimeException | Error error) { failure = error; LOGGER.error("authentication resource cleanup failed", error); } + finally { finishWork(operation, failure); } + }; + try { executor.execute(cleanup); } + catch (RuntimeException | Error rejected) { + if (!(rejected instanceof RejectedExecutionException)) { + synchronized (authenticationLock) { rememberReleaseFailure(rejected); } + } + try { Thread.ofVirtual().name("TCV-Authentication-Cleanup").start(cleanup); } + catch (RuntimeException | Error unavailable) { + unavailable.addSuppressed(rejected); + synchronized (authenticationLock) { rememberReleaseFailure(unavailable); } + cleanup.run(); + } + } + } + + /** 画面終了後、取消済みタスクの実終了と全リソース解放が終わった時点で完了する。 */ + public CompletionStage resourcesReleased() { return releasedResult; } + + private static void rethrow(Throwable failure) { + if (failure instanceof RuntimeException exception) throw exception; + if (failure instanceof Error error) throw error; + throw new RuntimeException(failure); + } + + public void openAuthUri() { + if (isClosed()) return; + var uri = getAuthUri(); + if (uri != null) browsers.open(uri); + } + + public void clipAuthUri() { + var uri = getAuthUri(); + if (uri == null) return; + + var cb = Clipboard.getSystemClipboard(); + cb.setContent(Map.of(DataFormat.PLAIN_TEXT, uri)); } // ******************** properties ******************** @@ -202,6 +423,10 @@ public void close() { public ReadOnlyBooleanProperty initializedProperty() { return initialized.getReadOnlyProperty(); } public boolean isInitialized() { return initialized.get(); } + /** キュー待機、資格情報の読み込み、ユーザーの認可待ちを含む認証中の状態。 */ + public ReadOnlyBooleanProperty busyProperty() { return busy.getReadOnlyProperty(); } + public boolean isBusy() { return busy.get(); } + public ReadOnlyObjectProperty qrcodeProperty() { return qrcode.getReadOnlyProperty(); } public Image getQRCode() { return qrcode.get(); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/auth/PreferencesCredentialStorage.java b/src/main/java/com/github/k7t3/tcv/app/auth/PreferencesCredentialStorage.java index b919f80..5895d67 100644 --- a/src/main/java/com/github/k7t3/tcv/app/auth/PreferencesCredentialStorage.java +++ b/src/main/java/com/github/k7t3/tcv/app/auth/PreferencesCredentialStorage.java @@ -16,172 +16,265 @@ package com.github.k7t3.tcv.app.auth; -import com.github.k7t3.tcv.app.secure.CipherOperator; import com.github.k7t3.tcv.domain.auth.CredentialStore; +import com.github.k7t3.tcv.io.PreferenceFileLock; import com.github.philippheuer.credentialmanager.domain.Credential; import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; +import java.util.HexFormat; import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; public class PreferencesCredentialStorage implements CredentialStore { - - private static final Logger LOGGER = LoggerFactory.getLogger(PreferencesCredentialStorage.class); - - private final String PREFERENCES_KEY = "credentials"; - + private static final String PREFERENCES_KEY = "credentials"; private static final String NULL_STRING = "NULL"; - - private final List credentials = new ArrayList<>(); - private final Preferences preferences; - - public PreferencesCredentialStorage(Preferences preferences) { - this.preferences = preferences; + private final UnaryOperator encrypt; + private final UnaryOperator decrypt; + private final Path lockFile; + private final Path coordinationFile; + + /** 呼出側が永続化を所有する借用ノード。排他は同じJVMのノード内に限る。 */ + public PreferencesCredentialStorage(Preferences preferences, UnaryOperator encrypt, UnaryOperator decrypt) { + this(preferences, encrypt, decrypt, null); } - private void loadOAuthCredentials() { - if (!credentials.isEmpty()) return; + /** + * 比較更新とflushをプロセス間で直列化する。構築時のI/Oは行わない。 + * @param preferences 同じlockFileを使う全プロセスが共有する保存ノード + * @param encrypt 暗号化処理 + * @param decrypt 復号処理 + * @param lockFile 移動するDBとは独立した共有ロック。nullは借用ノード用のJVM内排他 + */ + public PreferencesCredentialStorage(Preferences preferences, UnaryOperator encrypt, + UnaryOperator decrypt, Path lockFile) { + this(preferences, encrypt, decrypt, lockFile, null); + } - var bytes = preferences.getByteArray(PREFERENCES_KEY, null); - if (bytes == null) - return; + /** + * 設定と共有する排他を先に取得し、既存の資格情報専用排他も維持する。構築時のI/Oは行わない。 + * @param preferences 設定エディターと共有する保存ノード + * @param encrypt 暗号化処理 + * @param decrypt 復号処理 + * @param lockFile 既存の資格情報専用ロック。nullは専用排他なし + * @param coordinationFile 設定保存と共有するロック。nullは従来の専用排他だけを使う + */ + public PreferencesCredentialStorage(Preferences preferences, UnaryOperator encrypt, + UnaryOperator decrypt, Path lockFile, Path coordinationFile) { + this.preferences = Objects.requireNonNull(preferences); + this.encrypt = Objects.requireNonNull(encrypt); + this.decrypt = Objects.requireNonNull(decrypt); + this.lockFile = lockFile == null ? null : lockFile.toAbsolutePath().normalize(); + this.coordinationFile = coordinationFile == null ? null : coordinationFile.toAbsolutePath().normalize(); + } - // トークン情報を復号する - bytes = CipherOperator.decrypt(bytes); + private T exclusive(Supplier operation) { + if (lockFile == null && coordinationFile == null) { + synchronized (preferences) { return operation.get(); } + } + return PreferenceFileLock.exclusive(coordinationFile, () -> PreferenceFileLock.exclusive(lockFile, () -> { + synchronized (preferences) { + syncOwnedNode(); + return operation.get(); + } + })); + } - try (var bais = new ByteArrayInputStream(bytes); - var is = new DataInputStream(bais)) { + private void syncOwnedNode() { + try { preferences.sync(); } + catch (BackingStoreException failure) { throw new IllegalStateException("failed to synchronize credentials", failure); } + } - while (0 < is.available()) { - var identityProvider = is.readUTF(); - var accessToken = is.readUTF(); - var refreshToken = is.readUTF(); - var userId = is.readUTF(); - var userName = is.readUTF(); - var expireIn = is.readInt(); + private void flushOwnedNode() { + if (lockFile == null && coordinationFile == null) return; + try { preferences.flush(); } + catch (BackingStoreException failure) { throw new IllegalStateException("failed to flush credentials", failure); } + } - var scopeCount = is.readInt(); - var scopes = new ArrayList(scopeCount); - for (var i = 0; i < scopeCount; i++) { - scopes.add(is.readUTF()); + private void publish(byte[] next) { + var owned = lockFile != null || coordinationFile != null; + var previous = owned ? preferences.getByteArray(PREFERENCES_KEY, null) : null; + try { + replaceRaw(next); + flushOwnedNode(); + } catch (RuntimeException | Error failure) { + if (owned) { + try { replaceRaw(previous);flushOwnedNode(); } + catch (RuntimeException | Error compensation) { + if (compensation != failure) failure.addSuppressed(compensation); } + } + throw failure; + } + } - var contextCount = is.readInt(); - var context = new HashMap(contextCount); - for (var i = 0; i < contextCount; i++) { - var entry = is.readUTF(); - var split = entry.split("=", 2); - context.put(split[0], split[1]); - } + private void replaceRaw(byte[] value) { + if (value == null) preferences.remove(PREFERENCES_KEY); + else preferences.putByteArray(PREFERENCES_KEY, value); + } - var receiveAt = Instant.ofEpochMilli(is.readLong()); + /** 所有ノードは共有ロック内でsyncし、現在の資格情報を読む。 */ + @Override + public List loadCredentials() { + return exclusive(this::readCredentials); + } - var credential = new OAuth2Credential( - identityProvider, - accessToken, - refreshToken.equals(NULL_STRING) ? null : refreshToken, - userId.equals(NULL_STRING) ? null : userId, - userName.equals(NULL_STRING) ? null : userName, - expireIn, - scopes, - context - ); - credential.setReceivedAt(receiveAt); + private List readCredentials() { + return decode(preferences.getByteArray(PREFERENCES_KEY, null)); + } + private List decode(byte[] encrypted) { + var credentials = new ArrayList(); + if (encrypted == null) return credentials; + try (var input = new DataInputStream(new ByteArrayInputStream(decrypt.apply(encrypted)))) { + while (input.available() > 0) { + var provider = input.readUTF(); + var accessToken = input.readUTF(); + var refreshToken = input.readUTF(); + var userId = input.readUTF(); + var userName = input.readUTF(); + var expiresIn = input.readInt(); + var scopeCount = readCount(input); + var scopes = new ArrayList(scopeCount); + for (var i = 0; i < scopeCount; i++) scopes.add(input.readUTF()); + var contextCount = readCount(input); + var context = new HashMap(); + for (var i = 0; i < contextCount; i++) { + var entry = input.readUTF().split("=", 2); + if (entry.length != 2) throw new IOException("invalid credential context"); + context.put(entry[0], entry[1]); + } + var receivedAt = Instant.ofEpochMilli(input.readLong()); + var credential = new OAuth2Credential(provider, accessToken, nullable(refreshToken), nullable(userId), + nullable(userName), expiresIn, scopes, context); + credential.setReceivedAt(receivedAt); credentials.add(credential); - - LOGGER.info("loaded credential"); } - - } catch (IOException e) { - LOGGER.error(e.getMessage(), e); + return credentials; + } catch (IOException failure) { + throw new UncheckedIOException("failed to read stored credentials", failure); } } - @Override - public List loadCredentials() { - loadOAuthCredentials(); - return new ArrayList<>(credentials); - } - - private void saveOAuthCredentials() { - try (var baos = new ByteArrayOutputStream(); - var os = new DataOutputStream(baos)) { - - LOGGER.info("saved credential"); - - for (var credential : credentials) { - if (credential instanceof OAuth2Credential c) { - os.writeUTF(c.getIdentityProvider()); - os.writeUTF(c.getAccessToken()); - os.writeUTF(c.getRefreshToken() == null ? NULL_STRING : c.getRefreshToken()); - os.writeUTF(c.getUserId() == null ? NULL_STRING : c.getUserId()); - os.writeUTF(c.getUserName() == null ? NULL_STRING : c.getUserName()); - os.writeInt(c.getExpiresIn()); - - // scope - os.writeInt(c.getScopes().size()); - for (var scope : c.getScopes()) { - os.writeUTF(scope); - } - - // コンテキスト - os.writeInt(c.getContext().size()); - for (var entry : c.getContext().entrySet()) { - var v = entry.getKey() + "=" + entry.getValue(); - os.writeUTF(v); - } - - var epoch = c.getReceivedAt().toEpochMilli(); - os.writeLong(epoch); - } - } + private static int readCount(DataInputStream input) throws IOException { + var count = input.readInt(); + if (count < 0 || count > input.available() / 2) throw new IOException("invalid credential entry count"); + return count; + } + + private static String nullable(String value) { + return NULL_STRING.equals(value) ? null : value; + } - os.flush(); + private static String serialized(String value) { + return value == null ? NULL_STRING : value; + } - // トークン情報を暗号化 - var bytes = CipherOperator.encrypt(baos.toByteArray()); + @Override + public void saveCredentials(List credentials) { + exclusive(() -> { writeCredentials(credentials);return null; }); + } - preferences.putByteArray(PREFERENCES_KEY, bytes); + private void writeCredentials(List credentials) { + publish(encode(credentials)); + } - } catch (IOException e) { - LOGGER.error(e.getMessage(), e); + private byte[] encode(List credentials) { + try (var bytes = new ByteArrayOutputStream(); var output = new DataOutputStream(bytes)) { + for (var value : credentials) { + if (!(value instanceof OAuth2Credential credential)) continue; + output.writeUTF(credential.getIdentityProvider()); + output.writeUTF(credential.getAccessToken()); + output.writeUTF(serialized(credential.getRefreshToken())); + output.writeUTF(serialized(credential.getUserId())); + output.writeUTF(serialized(credential.getUserName())); + output.writeInt(credential.getExpiresIn()); + output.writeInt(credential.getScopes().size()); + for (var scope : credential.getScopes()) output.writeUTF(scope); + output.writeInt(credential.getContext().size()); + for (var entry : credential.getContext().entrySet()) output.writeUTF(entry.getKey() + "=" + entry.getValue()); + output.writeLong(credential.getReceivedAt().toEpochMilli()); + } + output.flush(); + return encrypt.apply(bytes.toByteArray()); + } catch (IOException failure) { + throw new UncheckedIOException("failed to save credentials", failure); } } @Override - public void saveCredentials(List credentials) { - this.credentials.clear(); - this.credentials.addAll(credentials); - saveOAuthCredentials(); + public Snapshot snapshot() { + return exclusive(() -> { + var encrypted = preferences.getByteArray(PREFERENCES_KEY, null); + return new Snapshot(revision(encrypted), decode(encrypted)); + }); + } + + @Override + public Optional compareAndSet(Snapshot expected, List replacement, BooleanSupplier permitted) { + return exclusive(() -> { + var current = preferences.getByteArray(PREFERENCES_KEY, null); + if (!Objects.equals(expected.revision(), revision(current))) return Optional.empty(); + // 空の一覧も暗号化して保存し、削除前の空状態と版を区別する。 + var encrypted = encode(replacement); + if (!permitted.getAsBoolean()) return Optional.empty(); + var result = new Snapshot(revision(encrypted), decode(encrypted)); + // 許可判定や暗号処理から再入した変更も、古い比較で上書きしない。 + if (!Arrays.equals(current, preferences.getByteArray(PREFERENCES_KEY, null))) return Optional.empty(); + publish(encrypted); + return Optional.of(result); + }); + } + + private static String revision(byte[] encrypted) { + if (encrypted == null) return ""; + try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(encrypted)); } + catch (NoSuchAlgorithmException impossible) { throw new AssertionError(impossible); } } @Override public Optional getCredentialByUserId(String userId) { - for (var credential : credentials) { - if (credential.getUserId().equalsIgnoreCase(userId)) { - return Optional.of(credential); - } - } - return Optional.empty(); + return exclusive(() -> readCredentials().stream() + .filter(value -> userId != null && userId.equalsIgnoreCase(value.getUserId())).findFirst()); } @Override public void clearCredentials() { - preferences.remove(PREFERENCES_KEY); - this.credentials.clear(); + exclusive(() -> { publish(null);return null; }); } + @Override + public boolean removeCredential(OAuth2Credential expected) { + Objects.requireNonNull(expected); + return exclusive(() -> { + var current = readCredentials(); + var removed = current.removeIf(value -> value instanceof OAuth2Credential credential + && Objects.equals(credential.getIdentityProvider(), expected.getIdentityProvider()) + && Objects.equals(credential.getAccessToken(), expected.getAccessToken())); + if (!removed) return false; + if (current.isEmpty()) { + publish(null); + } else writeCredentials(current); + return true; + }); + } } diff --git a/src/main/java/com/github/k7t3/tcv/app/channel/ChannelChatConnection.java b/src/main/java/com/github/k7t3/tcv/app/channel/ChannelChatConnection.java new file mode 100644 index 0000000..1d1ceef --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/channel/ChannelChatConnection.java @@ -0,0 +1,208 @@ +package com.github.k7t3.tcv.app.channel; + +import com.github.k7t3.tcv.app.service.FXTask; +import com.github.k7t3.tcv.domain.channel.TwitchChannel; +import com.github.k7t3.tcv.domain.chat.ChatRoom; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.function.Consumer; + +/** 一つの表示モデルの参加・退出を直列化し、観測の取消や終了登録の失敗でも受付済みの退出を止めない。 */ +final class ChannelChatConnection implements AutoCloseable { + private static final Logger LOGGER = LoggerFactory.getLogger(ChannelChatConnection.class); + private final Object lock = new Object(); + private final TwitchChannel channel; + private final Runnable releaseChannel; + private final Executor executor; + private final Consumer> shutdownAwaiter; + private CompletionStage tail = CompletableFuture.completedStage(null); + private Operation joining; + private Operation leaving; + private boolean desiredJoined; + private boolean closed; + private boolean retiring; + private long generation; + + ChannelChatConnection(TwitchChannel channel, Runnable releaseChannel, Executor executor, + Consumer> shutdownAwaiter) { + this.channel = channel; + this.releaseChannel = releaseChannel; + this.executor = executor; + this.shutdownAwaiter = shutdownAwaiter; + } + + FXTask join() { + final Operation operation; + final CompletionStage previous; + synchronized (lock) { + if (isRetiringLocked()) throw new IllegalStateException("channel chat connection is closed"); + if (desiredJoined && joining != null && !joining.result.isCancelled() && joining.failure == null) { + return joining.result; + } + desiredJoined = true; + long token = ++generation; + operation = new Operation<>(false, () -> { + checkCurrentJoin(token); + channel.loadBadgesIfNotLoaded(); + checkCurrentJoin(token); + return channel.getOrJoinChatRoom(); + }); + joining = operation; + previous = tail; + tail = operation.drained.minimalCompletionStage(); + operation.result.completion().whenComplete((ignored, failure) -> { + if (operation.result.isCancelled()) cancelJoin(operation); + }); + } + startAfter(previous, operation); + return operation.result; + } + + private void checkCurrentJoin(long token) { + synchronized (lock) { + if (closed || !desiredJoined || generation != token) throw new CancellationException("join was superseded"); + } + } + + private void cancelJoin(Operation operation) { + leave(operation); + } + + FXTask leave() { + return leave(null, false); + } + + private FXTask leave(Operation expectedJoin) { + return leave(expectedJoin, false); + } + + private FXTask leave(Operation expectedJoin, boolean closing) { + final Operation operation; + final CompletionStage previous; + synchronized (lock) { + if (closing) { + if (closed) return leaving == null ? FXTask.empty() : leaving.result; + closed = true; + } + if (expectedJoin != null && (joining != expectedJoin || !desiredJoined || closed)) return FXTask.empty(); + if (!desiredJoined && leaving != null && (closed || leaving.failure == null)) return leaving.result; + desiredJoined = false; + generation++; + if (joining == null) return FXTask.empty(); + if (!channel.isPersistent()) retiring = true; + joining.result.cancel(false); + operation = new Operation<>(true, () -> { + CloseActions.runAll(channel::leaveChat, releaseChannel); + return null; + }); + leaving = operation; + previous = tail; + tail = operation.drained.minimalCompletionStage(); + } + startAfter(previous, operation); + return operation.result; + } + + boolean isCurrentJoin(FXTask task) { + synchronized (lock) { + return !closed && desiredJoined && joining != null && joining.result == task && !task.isCancelled(); + } + } + + boolean isCurrentLeave(FXTask task) { + synchronized (lock) { return !closed && !desiredJoined && leaving != null && leaving.result == task; } + } + + private boolean isRetiringLocked() { + return retiring || closed || (!desiredJoined && leaving != null && !channel.isPersistent()); + } + boolean isRetiring() { synchronized (lock) { return isRetiringLocked(); } } + + CompletionStage retirement() { synchronized (lock) { return tail; } } + + @Override + public void close() { + leave(null, true); + } + + private void startAfter(CompletionStage previous, Operation operation) { + try { shutdownAwaiter.accept(operation.drained.minimalCompletionStage()); } + catch (RuntimeException | Error rejected) { + if (operation.cleanup) { + // 参加済み資源の後始末は、追跡の登録に失敗しても実行する。 + operation.registrationFailure = rejected; + executeAfter(previous, operation); + } else operation.finish(null, rejected); + throw rejected; + } + executeAfter(previous, operation); + } + + private void executeAfter(CompletionStage previous, Operation operation) { + previous.whenComplete((ignored, failure) -> { + try { + executor.execute(operation::run); + } catch (RuntimeException | Error rejected) { + if (operation.cleanup) { + try { Thread.ofVirtual().name("TCV-Chat-Leave").start(operation::run); } + catch (RuntimeException | Error fallbackFailure) { + if (fallbackFailure != rejected) rejected.addSuppressed(fallbackFailure); + operation.finish(null, rejected); + } + } else operation.finish(null, rejected); + } + }); + } + + private static final class Operation { + private final boolean cleanup; + private final Callable action; + private final CompletableFuture drained = new CompletableFuture<>(); + private T value; + private Throwable registrationFailure; + private volatile Throwable failure; + private final FXTask result = FXTask.observation(() -> { + if (failure instanceof Exception exception) throw exception; + if (failure instanceof Error error) throw error; + if (failure != null) throw new IllegalStateException(failure); + return value; + }); + + Operation(boolean cleanup, Callable action) { + this.cleanup = cleanup; + this.action = action; + } + + void run() { + T value = null; + Throwable failure = null; + try { value = action.call(); } + catch (Throwable error) { failure = error; } + finish(value, failure); + } + + void finish(T value, Throwable failure) { + if (registrationFailure != null) { + if (failure != null && failure != registrationFailure) registrationFailure.addSuppressed(failure); + failure = registrationFailure; + } + this.value = value; + this.failure = failure; + try { + result.run(); + } finally { + if (cleanup && failure != null && !(failure instanceof CancellationException)) { + LOGGER.error("Failed to release channel chat", failure); + drained.completeExceptionally(failure); + } else drained.complete(null); + } + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/channel/ChannelViewModelRepository.java b/src/main/java/com/github/k7t3/tcv/app/channel/ChannelViewModelRepository.java index a07d5c8..01834f3 100644 --- a/src/main/java/com/github/k7t3/tcv/app/channel/ChannelViewModelRepository.java +++ b/src/main/java/com/github/k7t3/tcv/app/channel/ChannelViewModelRepository.java @@ -17,9 +17,11 @@ package com.github.k7t3.tcv.app.channel; import com.github.k7t3.tcv.app.model.AbstractViewModel; +import com.github.k7t3.tcv.lifecycle.CloseActions; import com.github.k7t3.tcv.app.group.ChannelGroupRepository; import com.github.k7t3.tcv.app.reactive.DownCastFXSubscriber; import com.github.k7t3.tcv.app.service.FXTask; +import com.github.k7t3.tcv.app.image.ImageLoader; import com.github.k7t3.tcv.domain.channel.Broadcaster; import com.github.k7t3.tcv.domain.channel.ChannelRepository; import com.github.k7t3.tcv.domain.channel.StreamInfo; @@ -29,15 +31,23 @@ import com.github.k7t3.tcv.domain.event.channel.ChannelOnlineEvent; import com.github.k7t3.tcv.domain.event.channel.StreamStateUpdateEvent; import com.github.k7t3.tcv.domain.event.channel.TwitchChannelEvent; +import com.github.k7t3.tcv.entity.ChannelGroupEntity; import com.github.k7t3.tcv.reactive.FlowableSubscriber; -import javafx.beans.property.ObjectProperty; -import javafx.beans.property.SimpleObjectProperty; +import javafx.application.Platform; +import javafx.beans.property.ReadOnlyObjectProperty; +import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import java.util.*; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.Executor; import java.util.function.Consumer; +import java.util.function.Function; import java.util.stream.Collectors; /** @@ -47,66 +57,76 @@ public class ChannelViewModelRepository extends AbstractViewModel { /** * ユーザーIDとチャンネルのMap - * バックグラウンドスレッドで操作されるMapのためConcurrent + * FX スレッドで生成・反映・削除する。 */ - private final Map channelMap = new ConcurrentHashMap<>(); + private final Map channelMap = new HashMap<>(); /** * ロードされたチャンネルのリスト */ private final ObservableList channels = FXCollections.observableArrayList(); - private final ObjectProperty repository = new SimpleObjectProperty<>(); + private final ReadOnlyObjectWrapper repository = new ReadOnlyObjectWrapper<>(); private final ChannelGroupRepository groupRepository; - private final List> subscribers = new ArrayList<>(); + private final ImageLoader images; + private final Executor executor; + private final Consumer> shutdownAwaiter; + private final Consumer failures; + private final Map owners = new ConcurrentHashMap<>(); + private final Set> loads = new HashSet<>(); + private final Map> channelLoads = new HashMap<>(); + private FXTask initialLoad; + private long generation; - public ChannelViewModelRepository(ChannelGroupRepository groupRepository) { + public ChannelViewModelRepository(ChannelGroupRepository groupRepository, ImageLoader images, Executor executor, + Consumer> shutdownAwaiter, Consumer failures) { this.groupRepository = groupRepository; + this.images = images; + this.executor = executor; + this.shutdownAwaiter = shutdownAwaiter; + this.failures = failures; } + void trackChatOperation(CompletionStage operation) { shutdownAwaiter.accept(operation); } + @Override - public void subscribeEvents(EventSubscribers eventSubscribers) { - var onlineSub = subscriber(ChannelOnlineEvent.class, this::onOnlineEvent); - var offlineSub = subscriber(ChannelOfflineEvent.class, this::onOfflineEvent); - var stateSub = subscriber(StreamStateUpdateEvent.class, this::onStateUpdated); + protected void onSubscribeEvents(EventSubscribers eventSubscribers, SessionSubscriptions subscriptions) { + var onlineSub = subscriber(subscriptions, ChannelOnlineEvent.class, this::onOnlineEvent); + var offlineSub = subscriber(subscriptions, ChannelOfflineEvent.class, this::onOfflineEvent); + var stateSub = subscriber(subscriptions, StreamStateUpdateEvent.class, this::onStateUpdated); eventSubscribers.subscribeChannelEvent(onlineSub); eventSubscribers.subscribeChannelEvent(offlineSub); eventSubscribers.subscribeChannelEvent(stateSub); - subscribers.add(onlineSub); - subscribers.add(offlineSub); - subscribers.add(stateSub); } private FlowableSubscriber subscriber( - Class type, + SessionSubscriptions subscriptions, Class type, Consumer consumer ) { - return new DownCastFXSubscriber<>(type, consumer); + return subscriptions.own(new DownCastFXSubscriber<>(type, consumer)); } private void onOnlineEvent(ChannelOnlineEvent e) { var channel = e.getChannel(); - var userId = channel.getBroadcaster().getUserId(); - updateChannelState(userId, e.getInfo()); + updateChannelState(channel, e.getInfo()); } private void onOfflineEvent(ChannelOfflineEvent e) { var channel = e.getChannel(); - var userId = channel.getBroadcaster().getUserId(); - updateChannelState(userId, null); + updateChannelState(channel, null); } private void onStateUpdated(StreamStateUpdateEvent e) { var channel = e.getChannel(); - var userId = channel.getBroadcaster().getUserId(); - updateChannelState(userId, e.getInfo()); + updateChannelState(channel, e.getInfo()); } - private void updateChannelState(String userId, StreamInfo streamInfo) { + private void updateChannelState(TwitchChannel source, StreamInfo streamInfo) { + var userId = source.getBroadcaster().getUserId(); var viewModel = channelMap.get(userId); - if (viewModel == null) return; + if (viewModel == null || viewModel.getChannel() != source || viewModel.isRetiring()) return; viewModel.updateStreamInfo(streamInfo); } @@ -114,45 +134,46 @@ private void updateChannelState(String userId, StreamInfo streamInfo) { * リポジトリのすべてのチャンネルをロードする */ public FXTask loadAllAsync() { + checkOpen(); + if (initialLoad != null) return initialLoad; final var repository = Objects.requireNonNull(getRepository()); - - var task = FXTask.task(() -> { - // すべての登録しているチャンネルをロードする + final var token = generation; + var task = load(repository, () -> { repository.loadAllRelatedChannels(); - - // グループに登録しているチャンネルをロード - var groupChannelIds = groupRepository.retrieveAllChannelIds(); - var groupChannels = repository.getOrLoadChannels(groupChannelIds).stream() - .collect(Collectors.toMap( - c -> c.getBroadcaster().getUserId(), - c -> new TwitchChannelViewModel(c, this) - )); - // グループに関するチャンネルは永続化する - groupChannels.forEach((id, c) -> c.setPersistent(true)); - // ロードしたチャンネルをグループリポジトリに渡す - groupRepository.injectChannels(groupChannels); - - // フォローしているチャンネルをViewModelインスタンスとして生成する - var valMap = new HashMap<>(groupChannels); - repository.getOrLoadChannels().forEach(c -> { - var userId = c.getBroadcaster().getUserId(); - if (!groupChannelIds.contains(userId)) { - var viewModel = new TwitchChannelViewModel(c, this); - valMap.put(userId, viewModel); - } - }); - channelMap.putAll(valMap); - return valMap; - }); - task.setOnScheduled(e -> { - channelMap.clear(); - channels.clear(); + var groups = groupRepository.loadSnapshot(); + var ids = groups.stream().flatMap(group -> group.channelIds().stream()).distinct().toList(); + var loaded = new ArrayList<>(repository.getOrLoadChannels(ids)); + loaded.addAll(repository.getOrLoadChannels()); + return new ChannelSnapshot(groups, List.copyOf(loaded)); + }, snapshot -> { + for (var channel : snapshot.channels()) { + requireCurrent(repository, token); + adoptChannel(repository, channel); + } + requireCurrent(repository, token); + var groupIds = snapshot.groups().stream().flatMap(group -> group.channelIds().stream()).collect(Collectors.toSet()); + for (var id : groupIds) { + requireCurrent(repository, token); + var channel = channelMap.get(id); + if (channel != null) channel.setPersistent(true); + } + requireCurrent(repository, token); + groupRepository.applySnapshot(snapshot.groups(), Map.copyOf(channelMap)); + return null; }); - task.onDone(map -> channels.addAll(map.values())); - task.runAsync(); + initialLoad = task; + task.setFinally(() -> { if (initialLoad == task) initialLoad = null; }); return task; } + private void requireCurrent(ChannelRepository owner, long token) { + if (isClosed() || generation != token || getRepository() != owner) { + throw new java.util.concurrent.CancellationException("channel snapshot is no longer owned"); + } + } + + private record ChannelSnapshot(List groups, List channels) {} + public ObservableList getChannels() { return channels; } @@ -166,19 +187,100 @@ public ObservableList getChannels() { * @return チャンネル */ public FXTask getChannelAsync(Broadcaster broadcaster) { + checkOpen(); var channel = channelMap.get(broadcaster.getUserId()); - if (channel != null) return FXTask.of(channel); - + if (channel != null && !channel.isRetiring()) return FXTask.of(channel); + var pending = channelLoads.get(broadcaster.getUserId()); + if (pending != null && !pending.isDone()) return pending; final var repository = Objects.requireNonNull(getRepository()); - var t = FXTask.task(() -> { - var c = repository.getOrLoadChannel(broadcaster); - var c2 = new TwitchChannelViewModel(c, this); - channelMap.put(broadcaster.getUserId(), c2); - return c2; + var ready = channel == null ? CompletableFuture.completedStage(null) : channel.retirement(); + var task = load(repository, () -> repository.getOrLoadChannel(broadcaster), + loaded -> adoptChannel(repository, loaded), ready); + channelLoads.put(broadcaster.getUserId(), task); + task.setFinally(() -> channelLoads.remove(broadcaster.getUserId(), task)); + return task; + } + + private TwitchChannelViewModel adoptChannel(ChannelRepository repository, TwitchChannel channel) { + var id = channel.getBroadcaster().getUserId(); + var existing = channelMap.get(id); + if (existing != null && !existing.isRetiring()) return existing; + if (existing != null) { + channels.remove(existing); + owners.remove(existing); + existing.close(); + } + var model = new TwitchChannelViewModel(channel, this, images, executor, failures); + channelMap.put(id, model); + owners.put(model, repository); + channels.add(model); + return model; + } + + /** 取得はワーカー、返却タスクの成功とモデル生成は FX。取消は両方へ伝播する。 */ + private FXTask load(ChannelRepository owner, Callable fetch, Function publish) { + return load(owner, fetch, publish, CompletableFuture.completedStage(null)); + } + + /** ready の実処理終了後に投入する。ワーカー内で前の退出を待つと単一 executor で停止する。 */ + private FXTask load(ChannelRepository owner, Callable fetch, Function publish, + CompletionStage ready) { + var token = generation; + class Operation { + Callable publication; + final FXTask result = FXTask.observation(() -> publication.call()); + final FXTask worker = FXTask.task(fetch); + + void finish(Callable action) { + if (isClosed() || generation != token || getRepository() != owner || result.isCancelled()) { + result.cancel(); + return; + } + publication = action; + result.run(); + } + + void fail(Throwable error) { + Runnable publication = () -> finish(() -> { + Throwable failure = error; + while (failure instanceof CompletionException && failure.getCause() != null) failure = failure.getCause(); + if (failure instanceof Exception exception) throw exception; + if (failure instanceof Error fatal) throw fatal; + throw new IllegalStateException(failure); + }); + if (Platform.isFxApplicationThread()) publication.run(); + else Platform.runLater(publication); + } + } + var operation = new Operation(); + loads.add(operation.result); + operation.worker.cancelWhenCancelled(operation.result); + operation.result.setFinally(() -> { + loads.remove(operation.result); + operation.worker.cancel(); + }); + operation.worker.onDone(value -> operation.finish(() -> publish.apply(value))); + operation.worker.setOnFailed(event -> operation.finish(() -> { + var failure = operation.worker.getException(); + if (failure instanceof Exception exception) throw exception; + if (failure instanceof Error error) throw error; + throw new IllegalStateException(failure); + })); + operation.result.cancelWhenCancelled(operation.worker); + ready.whenComplete((ignored, failure) -> { + if (operation.result.isCancelled()) return; + if (failure != null) { operation.fail(failure); return; } + try { + executor.execute(operation.worker); + } catch (RuntimeException | Error rejected) { + operation.fail(rejected); + } }); - t.onDone(channels::add); - t.runAsync(); - return t; + return operation.result; + } + + private void checkOpen() { + if (isClosed()) throw new IllegalStateException("channel repository is closed"); } /** @@ -186,6 +288,8 @@ public FXTask getChannelAsync(Broadcaster broadcaster) { *

* {@link TwitchChannel#isPersistent()}が有効なら何もしない *

+ *

ドメインの解放が終わるまで呼び出し元で実行する。バックグラウンドから呼び出すこと。 + * 表示リストの更新だけを FX スレッドへ送る。

*/ public void releaseChannel(TwitchChannelViewModel channel) { // 永続化されたチャンネルのときは何もしない @@ -193,39 +297,57 @@ public void releaseChannel(TwitchChannelViewModel channel) { return; } - final var repository = Objects.requireNonNull(getRepository()); - var t = FXTask.task(() -> { + final var repository = owners.remove(channel); + if (repository == null) return; + try { repository.releaseChannel(channel.getChannel()); - channelMap.remove(channel.getBroadcaster().getUserId()); - return channel; - }); - t.onDone(channels::remove); - t.runAsync(); + } finally { + Platform.runLater(() -> { + channelMap.remove(channel.getBroadcaster().getUserId(), channel); + channels.remove(channel); + channel.close(); + }); + } } @Override - public void onLogout() { - subscribers.forEach(FlowableSubscriber::cancel); - subscribers.clear(); - channels.clear(); - channelMap.clear(); - - var repository = getRepository(); - if (repository != null) { - repository.clear(); - setRepository(null); - } + protected void onLoggedOut() { + endSession(); + releaseImages(); } @Override - public void close() { - // no-op + protected void onClose() { + endSession(); + releaseImages(); + } + + private void endSession() { + generation++; + repository.set(null); + owners.clear(); + for (var load : List.copyOf(loads)) load.cancel(); + channelLoads.clear(); + initialLoad = null; + } + + private void releaseImages() { + var owned = new HashSet<>(channelMap.values()); + owned.addAll(channels); + channelMap.clear(); + channels.clear(); + CloseActions.runAll(owned.stream().map(channel -> (Runnable) channel::close).toArray(Runnable[]::new)); } // ==================== PROPERTIES ==================== - public ObjectProperty repositoryProperty() { return repository; } + public ReadOnlyObjectProperty repositoryProperty() { return repository.getReadOnlyProperty(); } public ChannelRepository getRepository() { return repository.get(); } - public void setRepository(ChannelRepository repository) { this.repository.set(repository); } + public void setRepository(ChannelRepository repository) { + checkOpen(); + if (getRepository() == repository) return; + onLoggedOut(); + this.repository.set(repository); + } } diff --git a/src/main/java/com/github/k7t3/tcv/app/channel/FoundChannelViewModel.java b/src/main/java/com/github/k7t3/tcv/app/channel/FoundChannelViewModel.java index c132e11..a11ccbe 100644 --- a/src/main/java/com/github/k7t3/tcv/app/channel/FoundChannelViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/channel/FoundChannelViewModel.java @@ -16,17 +16,19 @@ package com.github.k7t3.tcv.app.channel; +import com.github.k7t3.tcv.app.service.BrowserActions; import com.github.k7t3.tcv.app.model.AbstractViewModel; import com.github.k7t3.tcv.app.event.ChatOpeningEvent; +import com.github.k7t3.tcv.app.image.ImageLoader; +import com.github.k7t3.tcv.app.image.LazyImage; import com.github.k7t3.tcv.app.service.FXTask; import com.github.k7t3.tcv.domain.channel.Broadcaster; import com.github.k7t3.tcv.domain.channel.FoundChannel; -import com.github.k7t3.tcv.domain.event.EventSubscribers; +import com.github.k7t3.tcv.lifecycle.CloseActions; import javafx.beans.property.*; import javafx.scene.image.Image; - -import java.awt.*; -import java.net.URI; +import java.util.concurrent.CancellationException; +import java.util.function.Consumer; public class FoundChannelViewModel extends AbstractViewModel { @@ -40,71 +42,116 @@ public class FoundChannelViewModel extends AbstractViewModel { private final ReadOnlyBooleanWrapper live; private final ReadOnlyStringWrapper gameName; private final ChannelViewModelRepository channelRepository; - - public FoundChannelViewModel( - ChannelViewModelRepository channelRepository, - FoundChannel channel - ) { + private final ImageLoader images; + private LazyImage profileLoad; + private final Consumer failures; + private final BrowserActions browsers; + private Opening opening; + private long revision; + private boolean loggedOut; + + FoundChannelViewModel(ChannelViewModelRepository channelRepository, FoundChannel channel, ImageLoader images, + Consumer failures, BrowserActions browsers) { + this.failures = failures; + this.browsers = browsers; broadcaster = new ReadOnlyObjectWrapper<>(); profileImage = new ReadOnlyObjectWrapper<>(); live = new ReadOnlyBooleanWrapper(); gameName = new ReadOnlyStringWrapper(); this.channelRepository = channelRepository; - update(channel); + this.images = images; + try { update(channel); } + catch (RuntimeException | Error failure) { + CloseActions.runAll(() -> { + if (failure instanceof RuntimeException exception) throw exception; + throw (Error) failure; + }, this::close); + } } public void update(FoundChannel channel) { + checkActive(); + var token = ++revision; + cancelOpening(); + releaseProfileImage(); + if (!isCurrent(token)) return; + var loaded = images.load(channel.getBroadcaster().getProfileImageUrl(), PROFILE_IMAGE_WIDTH, PROFILE_IMAGE_HEIGHT); + if (!isCurrent(token)) { loaded.close(); return; } + profileLoad = loaded; setBroadcaster(channel.getBroadcaster()); - setProfileImage(new Image(channel.getBroadcaster().getProfileImageUrl(), PROFILE_IMAGE_WIDTH, PROFILE_IMAGE_HEIGHT, true, true, true)); + if (!isCurrent(token)) return; + profileImage.bind(loaded.valueProperty()); + if (!isCurrent(token)) return; setGameName(channel.getGameName()); - setLive(channel.isLive()); + if (isCurrent(token)) setLive(channel.isLive()); } - public FXTask openChannelPageOnBrowser() { - var login = getBroadcaster().getUserLogin(); - - var task = FXTask.task(() -> { - var desktop = Desktop.getDesktop(); - if (!desktop.isSupported(Desktop.Action.BROWSE)) { - return false; - } - - desktop.browse(new URI(CHANNEL_URL_FORMAT.formatted(login))); - return true; - }); + private void releaseProfileImage() { + var owned = profileLoad; + profileLoad = null; + CloseActions.runAll(() -> { profileImage.unbind(); profileImage.set(null); }, + () -> { if (owned != null) owned.close(); }); + } - task.runAsync(); + private boolean isCurrent(long token) { return !isClosed() && !loggedOut && revision == token; } - return task; + private void checkActive() { + if (isClosed() || loggedOut) throw new IllegalStateException("search result is no longer active"); } - public FXTask joinChatAsync() { - var broadcaster = getBroadcaster(); - var t = channelRepository.getChannelAsync(broadcaster); - t.onDone(() -> { - var channel = t.getValue(); + private void cancelOpening() { + var owned = opening; + opening = null; + if (owned != null) owned.result.cancel(true); + } - // チャットを開くイベントを発行 - var opening = new ChatOpeningEvent(channel); - publish(opening); - }); - t.runAsync(); - return t; + private void endScope() { + loggedOut = true; + revision++; + CloseActions.runAll(this::cancelOpening, this::releaseProfileImage, browsers::cancelAll, + () -> { if (isClosed()) browsers.close(); }); } - @Override - public void subscribeEvents(EventSubscribers eventSubscribers) { - // no-op + @Override protected void onLoggedOut() { endScope(); } + @Override protected void onClose() { endScope(); } + + public FXTask openChannelPageOnBrowser() { + checkActive(); + return browsers.open(CHANNEL_URL_FORMAT.formatted(getBroadcaster().getUserLogin())); } - @Override - public void onLogout() { - // no-op + /** 共有取得の観測だけを所有する。他の検索結果・画面の取得は取り消さない。 */ + public FXTask joinChatAsync() { + checkActive(); + if (opening != null && !opening.result.isDone()) return opening.result; + var request = new Opening(); + opening = request; + request.result.onFailure(failure -> { if (request.isCurrent()) failures.accept(failure); }); + request.result.setFinally(() -> { if (opening == request) opening = null; }); + try { + var source = channelRepository.getChannelAsync(getBroadcaster()); + request.result.cancelWhenCancelled(source); + source.onDone(value -> { request.value = value; request.result.run(); }); + source.onFailure(failure -> { request.failure = failure; request.result.run(); }); + } catch (RuntimeException | Error failure) { + request.failure = failure; + request.result.run(); + } + return request.result; } - @Override - public void close() { - // no-op + private final class Opening { + final long token = revision; + TwitchChannelViewModel value; + Throwable failure; + final FXTask result = FXTask.observation(() -> { + if (!isCurrent()) throw new CancellationException("search result opening was retired"); + if (failure instanceof Error error) throw error; + if (failure instanceof Exception exception) throw exception; + publish(new ChatOpeningEvent(value)); + return value; + }); + boolean isCurrent() { return FoundChannelViewModel.this.isCurrent(token) && opening == this && !result.isCancelled(); } } // ******************** PROPERTIES ******************** @@ -117,7 +164,6 @@ public void close() { private ReadOnlyObjectWrapper profileImageWrapper() { return profileImage; } public ReadOnlyObjectProperty profileImageProperty() { return profileImage.getReadOnlyProperty(); } public Image getProfileImage() { return profileImage.get(); } - private void setProfileImage(Image profileImage) { this.profileImage.set(profileImage); } private ReadOnlyBooleanWrapper liveWrapper() { return live; } public ReadOnlyBooleanProperty liveProperty() { return live.getReadOnlyProperty(); } diff --git a/src/main/java/com/github/k7t3/tcv/app/channel/SearchChannelViewModel.java b/src/main/java/com/github/k7t3/tcv/app/channel/SearchChannelViewModel.java index 678a59d..9ad09e2 100644 --- a/src/main/java/com/github/k7t3/tcv/app/channel/SearchChannelViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/channel/SearchChannelViewModel.java @@ -16,11 +16,14 @@ package com.github.k7t3.tcv.app.channel; +import com.github.k7t3.tcv.app.service.BrowserActions; +import com.github.k7t3.tcv.app.image.ImageLoader; import com.github.k7t3.tcv.app.model.AbstractViewModel; -import com.github.k7t3.tcv.app.core.ExceptionHandler; import com.github.k7t3.tcv.domain.Twitch; import com.github.k7t3.tcv.domain.channel.ChannelFinder; -import com.github.k7t3.tcv.domain.event.EventSubscribers; +import com.github.k7t3.tcv.domain.channel.FoundChannel; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import javafx.beans.value.ChangeListener; import javafx.beans.property.*; import javafx.collections.FXCollections; import javafx.collections.ObservableList; @@ -29,9 +32,12 @@ import javafx.concurrent.WorkerStateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import java.util.List; +import java.util.ArrayList; +import java.util.Objects; +import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; public class SearchChannelViewModel extends AbstractViewModel { @@ -47,19 +53,32 @@ public class SearchChannelViewModel extends AbstractViewModel { private final SearchChannelService searchService = new SearchChannelService(); private final ObjectProperty twitch = new SimpleObjectProperty<>(); private final ChannelViewModelRepository channelRepository; - - public SearchChannelViewModel(ChannelViewModelRepository channelRepository) { + private final ImageLoader images; + private final Consumer failureHandler; + private boolean loggedOut; + private final ChangeListener sessionChanged = (observable, previous, next) -> { + loggedOut = next == null; + cancelSearch(); + try { clearChannels(); } + catch (RuntimeException | Error failure) { reportFailure(failure); } + }; + + /** executor と画像サービスは借用し、アプリの所有者が終了する。 */ + public SearchChannelViewModel(ChannelViewModelRepository channelRepository, ImageLoader images, Executor executor, + Consumer failureHandler) { this.channelRepository = channelRepository; + this.images = images; + this.failureHandler = Objects.requireNonNull(failureHandler); + searchService.setExecutor(Objects.requireNonNull(executor)); + twitch.addListener(sessionChanged); init(); } private void init() { - searchService.addEventHandler(WorkerStateEvent.WORKER_STATE_SCHEDULED, - e -> channels.clear()); searchService.addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, - e -> ExceptionHandler.handle(searchService.getException())); + e -> { if (isCurrent(searchService.request)) reportFailure(searchService.getException()); }); searchService.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, - e -> channels.setAll(searchService.getValue())); + e -> applyResults()); } public void search() { @@ -67,7 +86,16 @@ public void search() { } public void search(TimeUnit unit, long amount) { - searchService.search(unit.toMillis(amount), getKeyword(), isOnlyLive()); + if (isClosed()) throw new IllegalStateException("search view model is closed"); + if (amount < 0) throw new IllegalArgumentException("negative search delay"); + cancelSearch(); + try { + clearChannels(); + if (isClosed() || loggedOut || getTwitch() == null || getKeyword() == null || getKeyword().isBlank()) return; + searchService.search(unit.toMillis(amount), getKeyword(), isOnlyLive()); + } catch (RuntimeException | Error failure) { + CloseActions.runAll(this::cancelSearch, () -> reportFailure(failure)); + } } public ObservableList getChannels() { @@ -82,58 +110,104 @@ public boolean isLoading() { return searchService.isRunning(); } - @Override - public void subscribeEvents(EventSubscribers eventSubscribers) { - // no-op + private record SearchRequest(Twitch twitch, String keyword, boolean onlyLive, long delayMillis) { } @Override - public void onLogout() { - // no-op + protected void onClose() { + CloseActions.runAll(this::onLoggedOut, () -> { + twitch.removeListener(sessionChanged); + twitch.unbind(); + twitch.set(null); + }); } @Override - public void close() { - // no-op + protected void onLoggedOut() { + loggedOut = true; + CloseActions.runAll(this::cancelSearch, this::clearChannels); + } + + private void clearChannels() { + var previous = List.copyOf(channels); + channels.clear(); + closeResults(previous); + } + + private void cancelSearch() { + searchService.request = null; + searchService.cancel(); + // Task が捕捉した旧 Twitch と結果も、画面の寿命から切り離す。 + searchService.reset(); + } + + private boolean isCurrent(SearchRequest request) { + return request != null && request == searchService.request && !isClosed() && !loggedOut && request.twitch() == getTwitch(); + } + + private void applyResults() { + var request = searchService.request; + if (!isCurrent(request)) return; + var created = new ArrayList(); + try { + for (var channel : searchService.getValue()) { + if (!isCurrent(request)) break; + created.add(new FoundChannelViewModel(channelRepository, channel, images, failureHandler, + new BrowserActions(searchService.getExecutor(), channelRepository::trackChatOperation, failureHandler))); + } + if (!isCurrent(request)) { closeResults(created); return; } + channels.setAll(created); + } catch (RuntimeException | Error failure) { + try { CloseActions.runAll(() -> rethrow(failure), () -> closeResults(created)); } + catch (RuntimeException | Error accumulated) { reportFailure(accumulated); } + } + } + + private static void closeResults(List results) { + CloseActions.runAll(results.stream().map(model -> (Runnable) model::close).toArray(Runnable[]::new)); + } + + private void reportFailure(Throwable failure) { + if (isClosed()) LOGGER.error("search result cleanup failed", failure); + else failureHandler.accept(failure); + } + + private static void rethrow(Throwable failure) { + if (failure instanceof RuntimeException exception) throw exception; + if (failure instanceof Error error) throw error; + throw new RuntimeException(failure); } public ObjectProperty twitchProperty() { return twitch; } public Twitch getTwitch() { return twitch.get(); } public void setTwitch(Twitch twitch) { this.twitch.set(twitch); } - private class SearchChannelService extends Service> { - - public SearchChannelService() { - } + private class SearchChannelService extends Service> { - private String keyword; - private boolean onlyLive; - private long delayMillis; + private SearchRequest request; public void search(long delayMillis, String keyword, boolean live) { - this.delayMillis = delayMillis; - this.keyword = keyword; - this.onlyLive = live; + this.request = new SearchRequest(getTwitch(), keyword, live, delayMillis); restart(); } @Override - protected Task> createTask() { - final var twitch = getTwitch(); + protected Task> createTask() { + final var request = this.request; return new Task<>() { @Override - protected List call() { - if (twitch == null) { + protected List call() { + if (request.twitch() == null) { return List.of(); } - if (keyword == null || keyword.trim().isEmpty()) { + if (request.keyword() == null || request.keyword().trim().isEmpty()) { return List.of(); } try { // APIの過度なコールを避けるために検索を即座に // 行わず遅延時間を挟んでから検索する。 - Thread.sleep(delayMillis); + Thread.sleep(request.delayMillis()); } catch (InterruptedException e) { return List.of(); } @@ -142,13 +216,10 @@ protected List call() { return List.of(); } - LOGGER.info("search channels keyword={}, liveOnly={}", keyword, onlyLive); + LOGGER.info("search channels keyword={}, liveOnly={}", request.keyword(), request.onlyLive()); - var finder = new ChannelFinder(twitch); - return finder.search(keyword, onlyLive) - .stream() - .map(c -> new FoundChannelViewModel(channelRepository, c)) - .toList(); + var finder = new ChannelFinder(request.twitch()); + return finder.search(request.keyword(), request.onlyLive()); } }; } diff --git a/src/main/java/com/github/k7t3/tcv/app/channel/TwitchChannelListViewModel.java b/src/main/java/com/github/k7t3/tcv/app/channel/TwitchChannelListViewModel.java index 25a7b70..fed006a 100644 --- a/src/main/java/com/github/k7t3/tcv/app/channel/TwitchChannelListViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/channel/TwitchChannelListViewModel.java @@ -16,10 +16,10 @@ package com.github.k7t3.tcv.app.channel; +import com.github.k7t3.tcv.lifecycle.CloseActions; import com.github.k7t3.tcv.app.model.AbstractViewModel; import com.github.k7t3.tcv.app.event.ChatOpeningEvent; -import com.github.k7t3.tcv.app.service.FXTask; -import com.github.k7t3.tcv.domain.event.EventSubscribers; +import com.github.k7t3.tcv.app.service.BrowserActions; import com.github.k7t3.tcv.prefs.GeneralPreferences; import javafx.beans.Observable; import javafx.beans.binding.Bindings; @@ -28,9 +28,8 @@ import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; - -import java.util.Collections; import java.util.Comparator; +import java.util.Locale; /** * 永続化しているチャンネルのリスト @@ -65,7 +64,11 @@ public class TwitchChannelListViewModel extends AbstractViewModel { private final StringProperty filter = new SimpleStringProperty(); private final ObjectProperty multipleOpenType = new SimpleObjectProperty<>(MultipleChatOpenType.SEPARATED); - public TwitchChannelListViewModel() { + private final BrowserActions browsers; + private boolean loggedOut; + + public TwitchChannelListViewModel(BrowserActions browsers) { + this.browsers = browsers; var sorted = new SortedList<>(loadedChannels); sorted.setComparator(DEFAULT_COMPARATOR); @@ -83,16 +86,17 @@ public void bindGeneralPreferences(GeneralPreferences preferences) { private boolean filter(TwitchChannelViewModel channel) { var liveState = !isOnlyLive() || channel.isLive(); var followingState = !isOnlyFollow() || channel.isFollowing(); + if (!liveState || !followingState) return false; - var keyword = getFilter() == null ? "" : getFilter().trim().toLowerCase(); + var keyword = getFilter() == null ? "" : getFilter().trim().toLowerCase(Locale.ROOT); if (keyword.isEmpty()) { - return liveState && followingState; + return true; } var gameTitle = channel.getGameName() == null ? "" : channel.getGameName(); - return (liveState && followingState) && channel.getUserName().toLowerCase().contains(keyword) || - channel.getUserLogin().toLowerCase().contains(keyword) || - gameTitle.toLowerCase().contains(keyword); + return channel.getUserName().toLowerCase(Locale.ROOT).contains(keyword) || + channel.getUserLogin().toLowerCase(Locale.ROOT).contains(keyword) || + gameTitle.toLowerCase(Locale.ROOT).contains(keyword); } /** @@ -104,6 +108,10 @@ private boolean filter(TwitchChannelViewModel channel) { * @param channels バインドソース */ public void bindChannels(ObservableList channels) { + if (isClosed()) throw new IllegalStateException("channel list is closed"); + if (lazySource != null) Bindings.unbindContent(loadedChannels, lazySource); + loggedOut = false; + selectedChannels.clear(); lazySource = channels; Bindings.bindContent(loadedChannels, lazySource); } @@ -113,17 +121,13 @@ public ObservableList getLoadedChannels() { } public void openSelectedChannelPageOnBrowser() { - var selectedChannels = getSelectedChannels(); - if (selectedChannels.isEmpty()) return; - - var channels = Collections.unmodifiableList(selectedChannels); - - FXTask.task(() -> { - channels.forEach(TwitchChannelViewModel::openChannelPageOnBrowser); - }).runAsync(); + checkActive(); + var urls = selectedChannels.stream().map(channel -> "https://www.twitch.tv/" + channel.getBroadcaster().getUserLogin()).toList(); + if (!urls.isEmpty()) browsers.openAll(urls); } public void joinChat() { + checkActive(); var selectedChannels = getSelectedChannels(); if (selectedChannels.isEmpty()) return; @@ -150,12 +154,10 @@ public ObservableList getSelectedChannels() { } @Override - public void subscribeEvents(EventSubscribers eventSubscribers) { - // no-op - } - - @Override - public void onLogout() { + protected void onLoggedOut() { + loggedOut = true; + browsers.cancelAll(); + selectedChannels.clear(); if (lazySource != null) { Bindings.unbindContent(loadedChannels, lazySource); lazySource = null; @@ -163,9 +165,13 @@ public void onLogout() { loadedChannels.clear(); } - @Override - public void close() { - // no-op + private void checkActive() { + if (isClosed() || loggedOut) throw new IllegalStateException("channel list is no longer active"); + } + + @Override protected void onClose() { + CloseActions.runAll(this::onLoggedOut, browsers::close, + () -> multipleOpenType.unbind(), () -> transformedChannels.predicateProperty().unbind()); } public StringProperty filterProperty() { return filter; } diff --git a/src/main/java/com/github/k7t3/tcv/app/channel/TwitchChannelViewModel.java b/src/main/java/com/github/k7t3/tcv/app/channel/TwitchChannelViewModel.java index cbcfc0d..228e003 100644 --- a/src/main/java/com/github/k7t3/tcv/app/channel/TwitchChannelViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/channel/TwitchChannelViewModel.java @@ -16,8 +16,11 @@ package com.github.k7t3.tcv.app.channel; +import com.github.k7t3.tcv.app.service.BrowserActions; import com.github.k7t3.tcv.app.chat.ChannelChatBadgeStore; +import com.github.k7t3.tcv.lifecycle.CloseActions; import com.github.k7t3.tcv.app.image.LazyImage; +import com.github.k7t3.tcv.app.image.ImageLoader; import com.github.k7t3.tcv.app.service.FXTask; import com.github.k7t3.tcv.domain.channel.Broadcaster; import com.github.k7t3.tcv.domain.channel.StreamInfo; @@ -26,13 +29,11 @@ import javafx.beans.property.*; import javafx.beans.value.ObservableValue; import javafx.scene.image.Image; +import java.util.concurrent.Executor; +import java.util.concurrent.CompletionStage; +import java.util.function.Consumer; -import java.awt.*; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -public class TwitchChannelViewModel { +public class TwitchChannelViewModel implements AutoCloseable { private static final String CHANNEL_URL_FORMAT = "https://www.twitch.tv/%s"; @@ -47,13 +48,25 @@ public class TwitchChannelViewModel { private final ChannelChatBadgeStore chatBadgeStore; private final TwitchChannel channel; - private final ChannelViewModelRepository repository; - - public TwitchChannelViewModel(TwitchChannel channel, ChannelViewModelRepository repository) { + private final ImageLoader images; + private LazyImage offlineLoad; + private boolean closed; + private final ChannelChatConnection chatConnection; + private final Consumer reportFailure; + private final BrowserActions browsers; + private FXTask observedJoin; + private FXTask observedLeave; + + public TwitchChannelViewModel(TwitchChannel channel, ChannelViewModelRepository repository, ImageLoader images, + Executor executor, Consumer reportFailure) { this.channel = channel; - this.repository = repository; + this.images = images; + this.reportFailure = reportFailure; + browsers = new BrowserActions(executor, repository::trackChatOperation, reportFailure); + chatConnection = new ChannelChatConnection(channel, () -> repository.releaseChannel(this), executor, + repository::trackChatOperation); broadcaster = new ReadOnlyObjectWrapper<>(channel.getBroadcaster()); - chatBadgeStore = new ChannelChatBadgeStore(channel); + chatBadgeStore = new ChannelChatBadgeStore(channel, images); following = new ReadOnlyBooleanWrapper(channel.isFollowing()); persistent = new SimpleBooleanProperty(channel.isPersistent()) { @Override @@ -83,48 +96,38 @@ public TwitchChannel getChannel() { *

*/ public void openChannelPageOnBrowser() { - var login = getBroadcaster().getUserLogin(); - - var desktop = Desktop.getDesktop(); - if (!desktop.isSupported(Desktop.Action.BROWSE)) { - return; - } - - try { - desktop.browse(new URI(CHANNEL_URL_FORMAT.formatted(login))); - } catch (IOException | URISyntaxException e) { - throw new RuntimeException(e); - } + checkOpen(); + browsers.open(CHANNEL_URL_FORMAT.formatted(getBroadcaster().getUserLogin())); } public FXTask joinChatAsync() { - if (isChatJoined()) return FXTask.of(channel.getOrJoinChatRoom()); - - var task = FXTask.task(() -> { - channel.loadBadgesIfNotLoaded(); - return channel.getOrJoinChatRoom(); + checkOpen(); + var task = chatConnection.join(); + if (observedJoin == task) return task; + observedJoin = task; + task.onDone(() -> { + if (!closed && chatConnection.isCurrentJoin(task)) chatJoinedWrapper().set(true); + }); + task.onFailure(failure -> { + if (!closed && chatConnection.isCurrentJoin(task)) reportFailure.accept(failure); }); - task.onDone(() -> chatJoinedWrapper().set(true)); - task.runAsync(); return task; } public FXTask leaveChatAsync() { - if (!isChatJoined()) return FXTask.empty(); - - if (chatJoined != null) { - chatJoined.set(false); - } - - var task = FXTask.task(() -> { - channel.leaveChat(); - repository.releaseChannel(this); + if (chatJoined != null) chatJoined.set(false); + var task = chatConnection.leave(); + if (observedLeave == task) return task; + observedLeave = task; + task.onFailure(failure -> { + if (!closed && chatConnection.isCurrentLeave(task)) reportFailure.accept(failure); }); - task.runAsync(); - return task; } + public boolean isRetiring() { return closed || chatConnection.isRetiring(); } + CompletionStage retirement() { return chatConnection.retirement(); } + public ChannelChatBadgeStore getChatBadgeStore() { return chatBadgeStore; } @@ -150,8 +153,9 @@ public ChannelChatBadgeStore getChatBadgeStore() { public String getGameName() { return streamInfo == null ? "" : observableGameName().getValue(); } private ReadOnlyObjectWrapper profileImageWrapper() { + checkOpen(); if (profileImage == null) { - profileImage = new ReadOnlyObjectWrapper<>(new LazyImage( + profileImage = new ReadOnlyObjectWrapper<>(loadOwnedImage( channel.getBroadcaster().getProfileImageUrl(), 64, 64 @@ -163,15 +167,57 @@ private ReadOnlyObjectWrapper profileImageWrapper() { public LazyImage getProfileImage() { return profileImageWrapper().get(); } private ReadOnlyObjectWrapper offlineImageWrapper() { + checkOpen(); if (offlineImage == null) { offlineImage = new ReadOnlyObjectWrapper<>(); - channel.getBroadcaster().getOfflineImageUrl().ifPresent(url -> offlineImage.set(new Image(url, true))); + channel.getBroadcaster().getOfflineImageUrl().ifPresent(url -> { + offlineLoad = loadOwnedImage(url, 0, 0); + offlineImage.bind(offlineLoad.valueProperty()); + }); } return offlineImage; } public ReadOnlyObjectProperty offlineImageProperty() { return offlineImageWrapper().getReadOnlyProperty(); } public Image getOfflineImage() { return offlineImageWrapper().get(); } + private LazyImage loadOwnedImage(String url, double width, double height) { + checkOpen(); + var image = images.load(url, width, height); + if (closed) { + image.close(); + checkOpen(); + } + return image; + } + + private void checkOpen() { + if (closed) throw new IllegalStateException("channel view model is closed"); + } + + /** FX 上で参加の取消と退出を要求し、所有画像・binding を解放する。通信の終了待ちはアプリ側が行う。 */ + @Override + public void close() { + if (closed) return; + closed = true; + var profile = profileImage == null ? null : profileImage.get(); + var offline = offlineLoad; + offlineLoad = null; + CloseActions.runAll( + chatConnection::close, + browsers::close, + () -> { if (chatJoined != null) chatJoined.set(false); }, + () -> { if (profileImage != null) profileImage.set(null); }, + () -> { + if (offlineImage != null) { + offlineImage.unbind(); + offlineImage.set(null); + } + }, + () -> { if (profile != null) profile.close(); }, + () -> { if (offline != null) offline.close(); }, + chatBadgeStore::close); + } + private ReadOnlyObjectWrapper streamInfoWrapper() { if (streamInfo == null) { streamInfo = new ReadOnlyObjectWrapper<>(); diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChannelChatBadgeStore.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChannelChatBadgeStore.java index 7e1c8cc..af55c9b 100644 --- a/src/main/java/com/github/k7t3/tcv/app/chat/ChannelChatBadgeStore.java +++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChannelChatBadgeStore.java @@ -17,6 +17,7 @@ package com.github.k7t3.tcv.app.chat; import com.github.k7t3.tcv.app.image.LazyImage; +import com.github.k7t3.tcv.app.image.ImageLoader; import com.github.k7t3.tcv.app.service.CachedImageStore; import com.github.k7t3.tcv.domain.channel.TwitchChannel; import com.github.k7t3.tcv.domain.chat.ChatBadge; @@ -27,16 +28,18 @@ public class ChannelChatBadgeStore extends CachedImageStore { private final TwitchChannel channel; + private final ImageLoader images; - public ChannelChatBadgeStore(TwitchChannel channel) { + public ChannelChatBadgeStore(TwitchChannel channel, ImageLoader images) { super(8, Duration.ofMinutes(5)); this.channel = channel; + this.images = images; } @Override protected @Nullable LazyImage loadImage(ChatBadge key) { var url = channel.getBadgeUrl(key).orElse(null); if (url == null) return null; - return new LazyImage(url, 24, 24); + return images.load(url, 24, 24); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChatDataViewModel.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChatDataViewModel.java index 5347b22..78ee9f0 100644 --- a/src/main/java/com/github/k7t3/tcv/app/chat/ChatDataViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChatDataViewModel.java @@ -21,14 +21,11 @@ import com.github.k7t3.tcv.app.chat.filter.KeywordFilterEntry; import com.github.k7t3.tcv.app.chat.filter.UserFilterEntry; import com.github.k7t3.tcv.app.emoji.ChatEmojiStore; -import com.github.k7t3.tcv.app.event.KeywordFilteringEvent; -import com.github.k7t3.tcv.app.event.UserFilteringEvent; import com.github.k7t3.tcv.app.image.LazyImage; import com.github.k7t3.tcv.domain.chat.ChatData; import com.github.k7t3.tcv.domain.chat.ChatMessage; import com.github.k7t3.tcv.domain.chat.ChatMessageFragment; import com.github.k7t3.tcv.view.chat.ChatFont; -import de.saxsys.mvvmfx.MvvmFX; import de.saxsys.mvvmfx.ViewModel; import javafx.beans.property.*; import javafx.collections.FXCollections; @@ -188,8 +185,6 @@ public void keywordFilter() { var filter = KeywordFilterEntry.exactMatch(message); chatFilters.saveKeywordFilter(filter); - var event = new KeywordFilteringEvent(filter); - MvvmFX.getNotificationCenter().publish(event.getClass().getName(), event); } public void userFilter(String comment) { @@ -197,8 +192,6 @@ public void userFilter(String comment) { var filter = new UserFilterEntry(chat.userId(), chat.userName(), comment); chatFilters.saveUserFilter(filter); - var event = new UserFilteringEvent(filter); - MvvmFX.getNotificationCenter().publish(event.getClass().getName(), event); } // ********** PROPERTIES ********** diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChatEmoteStore.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChatEmoteStore.java index 784ff49..63bdb6b 100644 --- a/src/main/java/com/github/k7t3/tcv/app/chat/ChatEmoteStore.java +++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChatEmoteStore.java @@ -17,6 +17,7 @@ package com.github.k7t3.tcv.app.chat; import com.github.k7t3.tcv.app.image.LazyImage; +import com.github.k7t3.tcv.app.image.ImageLoader; import com.github.k7t3.tcv.app.service.CachedImageStore; import java.time.Duration; @@ -27,15 +28,17 @@ public class ChatEmoteStore extends CachedImageStore { private static final String CDN_FORMAT = "https://static-cdn.jtvnw.net/emoticons/v2/%s/default/light/1.0"; + private final ImageLoader images; - public ChatEmoteStore() { + public ChatEmoteStore(ImageLoader images) { super(100, Duration.ofMinutes(5)); + this.images = images; } @Override protected LazyImage loadImage(String key) { var uri = CDN_FORMAT.formatted(key); - return new LazyImage(uri, 0, 0); + return images.load(uri, 0, 0); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChatResources.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChatResources.java new file mode 100644 index 0000000..7d05167 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChatResources.java @@ -0,0 +1,46 @@ +package com.github.k7t3.tcv.app.chat; + +import com.github.k7t3.tcv.app.chat.filter.ChatFilters; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import com.github.k7t3.tcv.app.emoji.ChatEmojiStore; +import com.github.k7t3.tcv.app.emoji.Emoji; +import com.github.k7t3.tcv.app.image.ImageLoader; +import com.github.k7t3.tcv.domain.chat.GlobalChatBadges; + +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +/** 初期ロードの結果、画像キャッシュと絵文字アーカイブを所有する。未採用の結果も所有者が閉じる。 */ +public final class ChatResources implements AutoCloseable { + private final Emoji emoji; + private final GlobalChatBadges badges; + private final ChatFilters.Snapshot filters; + private final GlobalChatBadgeStore badgeStore; + private final ChatEmoteStore emoteStore; + private final ChatEmojiStore emojiStore; + private final AtomicBoolean closed = new AtomicBoolean(); + + ChatResources(Emoji emoji, GlobalChatBadges badges, ChatFilters.Snapshot filters, ImageLoader images) { + this.emoji = Objects.requireNonNull(emoji); + this.badges = Objects.requireNonNull(badges); + this.filters = Objects.requireNonNull(filters); + badgeStore = new GlobalChatBadgeStore(badges, images); + emoteStore = new ChatEmoteStore(images); + emojiStore = new ChatEmojiStore(emoji, images); + } + + Emoji emoji() { return emoji; } + GlobalChatBadges badges() { return badges; } + ChatFilters.Snapshot filters() { return filters; } + GlobalChatBadgeStore badgeStore() { return badgeStore; } + ChatEmoteStore emoteStore() { return emoteStore; } + ChatEmojiStore emojiStore() { return emojiStore; } + + /** 画像の取消を要求してからアーカイブを一度だけ閉じる。 */ + @Override + public void close() { + if (closed.compareAndSet(false, true)) { + CloseActions.runAll(badgeStore::close, emoteStore::close, emojiStore::close, emoji::close); + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChatResourcesLoader.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChatResourcesLoader.java new file mode 100644 index 0000000..d1d0313 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChatResourcesLoader.java @@ -0,0 +1,69 @@ +package com.github.k7t3.tcv.app.chat; + +import com.github.k7t3.tcv.app.chat.filter.ChatFilters; +import com.github.k7t3.tcv.app.emoji.Emoji; +import com.github.k7t3.tcv.app.image.ImageLoader; +import com.github.k7t3.tcv.domain.Twitch; +import com.github.k7t3.tcv.domain.chat.GlobalChatBadges; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.Objects; +import java.util.function.Supplier; + +/** UI 状態を変更せず、チャットに必要なデータを読み込む。途中失敗時は開いたリソースを解放する。 */ +public final class ChatResourcesLoader { + /** 後始末の失敗を通常の取得失敗と区別する。原因とそのsuppressedに両方の失敗を保持する。 */ + static final class CleanupFailure extends IllegalStateException { + private CleanupFailure(Throwable loadFailure) { + super("Failed to release chat resources after loading failed", loadFailure); + } + } + + private final Supplier emojiFactory; + private final Supplier badgeLoader; + private final Supplier filterLoader; + private final ImageLoader images; + + /** 取得に使うセッションと画像サービスを借用し、背景で読む入力を固定する。 */ + public ChatResourcesLoader(Path applicationDirectory, Twitch twitch, Supplier filterLoader, ImageLoader images) { + this(() -> new Emoji(applicationDirectory), () -> { + var badges = new GlobalChatBadges(); + badges.load(twitch); + return badges; + }, filterLoader, images); + } + + ChatResourcesLoader(Supplier emojiFactory, Supplier badgeLoader, + Supplier filterLoader, ImageLoader images) { + this.emojiFactory = Objects.requireNonNull(emojiFactory); + this.badgeLoader = Objects.requireNonNull(badgeLoader); + this.filterLoader = Objects.requireNonNull(filterLoader); + this.images = Objects.requireNonNull(images); + } + + /** + * 背景で取得し、返した資源の所有を呼出元へ移す。途中失敗では自身で解放する。 + * @throws IOException アーカイブの配置・検証が失敗した場合 + * @throws IllegalStateException 途中失敗の解放も失敗した場合。元の取得失敗を原因とし、 + * そのsuppressedに解放失敗を保持する + */ + public ChatResources load() throws IOException { + var emoji = Objects.requireNonNull(emojiFactory.get()); + try { + if (!emoji.validateArchive()) { + emoji.extractArchive(); + if (!emoji.validateArchive()) throw new IOException("emoji archive validation failed"); + } + return new ChatResources(emoji, badgeLoader.get(), filterLoader.get(), images); + } catch (IOException | RuntimeException | Error failure) { + try { + emoji.close(); + } catch (RuntimeException | Error cleanupFailure) { + if (cleanupFailure != failure) failure.addSuppressed(cleanupFailure); + throw new CleanupFailure(failure); + } + throw failure; + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomContainerViewModel.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomContainerViewModel.java index 442dfd5..ae58c13 100644 --- a/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomContainerViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomContainerViewModel.java @@ -19,19 +19,17 @@ import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel; import com.github.k7t3.tcv.app.chat.filter.ChatFilters; import com.github.k7t3.tcv.app.model.AbstractViewModel; -import com.github.k7t3.tcv.app.core.AppHelper; -import com.github.k7t3.tcv.app.core.OS; -import com.github.k7t3.tcv.app.model.TypeSafeNotificationObserver; +import com.github.k7t3.tcv.app.core.Resources; import com.github.k7t3.tcv.app.emoji.ChatEmojiStore; -import com.github.k7t3.tcv.app.emoji.Emoji; import com.github.k7t3.tcv.app.event.ChatOpeningEvent; import com.github.k7t3.tcv.app.event.KeywordFilteringEvent; import com.github.k7t3.tcv.app.event.UserFilteringEvent; import com.github.k7t3.tcv.app.reactive.ChatMessageSubscriber; import com.github.k7t3.tcv.app.reactive.DownCastFXSubscriber; import com.github.k7t3.tcv.app.service.FXTask; +import com.github.k7t3.tcv.app.service.FXTaskGroup; +import com.github.k7t3.tcv.lifecycle.CloseActions; import com.github.k7t3.tcv.domain.channel.TwitchChannel; -import com.github.k7t3.tcv.domain.chat.GlobalChatBadges; import com.github.k7t3.tcv.domain.event.EventSubscribers; import com.github.k7t3.tcv.domain.event.chat.*; import com.github.k7t3.tcv.prefs.ChatPreferences; @@ -44,17 +42,26 @@ import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; +import javafx.concurrent.WorkerStateEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; +import java.util.Objects; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; +import java.util.function.Supplier; public class ChatRoomContainerViewModel extends AbstractViewModel { + private static final Logger LOGGER = LoggerFactory.getLogger(ChatRoomContainerViewModel.class); + private final ObservableList chatRoomList = FXCollections.observableArrayList(c -> new Observable[] { c.selectedProperty() }); private final ObservableList floatingChatRoomList = FXCollections.observableArrayList(); private final ObservableList allChatRooms = FXCollections.observableArrayList(); @@ -65,11 +72,24 @@ public class ChatRoomContainerViewModel extends AbstractViewModel { private final ReadOnlyBooleanWrapper selectMode = new ReadOnlyBooleanWrapper(false); private final ReadOnlyIntegerWrapper selectingCount = new ReadOnlyIntegerWrapper(); private final ReadOnlyBooleanWrapper loaded = new ReadOnlyBooleanWrapper(false); + private final ReadOnlyBooleanWrapper loading = new ReadOnlyBooleanWrapper(false); + private final ReadOnlyStringWrapper error = new ReadOnlyStringWrapper(); + private final Supplier loadRequestFactory; + private final Executor executor; + private final Consumer> shutdownAwaiter; + private final Object loadLock = new Object(); + private Object loadAttempt; + private FXTask activeLoad; + private ChatResources pendingResources; + private ChatResources resources; + private final List pendingChatOpenings = new ArrayList<>(); + + /** 読込開始時のFX上で固定したフィルターと背景の取得処理。 */ + public record LoadRequest(ChatFilters filters, Callable loader) {} private GlobalChatBadgeStore globalBadgeStore; private ChatEmoteStore chatEmoteStore; private final DefinedChatColors definedChatColors = new DefinedChatColors(); - private Emoji emoji; private ChatEmojiStore emojiStore; private ChatFilters chatFilters; @@ -78,13 +98,16 @@ public class ChatRoomContainerViewModel extends AbstractViewModel { private final BooleanProperty showBadges = new SimpleBooleanProperty(true); private final ObjectProperty font = new SimpleObjectProperty<>(null); - private final List> subscribers = new ArrayList<>(); - - private TypeSafeNotificationObserver onChatOpened; - private TypeSafeNotificationObserver onKeywordFiltered; - private TypeSafeNotificationObserver onUserFiltered; + ChatRoomContainerViewModel(ChatFilters filters, Callable loader, Executor executor) { + this(() -> new LoadRequest(filters, loader), executor, ignored -> {}); + } - public ChatRoomContainerViewModel() { + /** 要求はFX上の読込開始時に固定し、取得は借用executorで実行する。結果の実解放を終了所有者へ登録する。 */ + public ChatRoomContainerViewModel(Supplier loadRequestFactory, Executor executor, + Consumer> shutdownAwaiter) { + this.loadRequestFactory = Objects.requireNonNull(loadRequestFactory); + this.executor = Objects.requireNonNull(executor); + this.shutdownAwaiter = Objects.requireNonNull(shutdownAwaiter); selectingCount.bind(Bindings.size(selectedList)); // 一つ以上選択されているときは選択モード @@ -99,7 +122,7 @@ public void bindChatPreferences(ChatPreferences chatPreferences) { chatCacheSize.bind(chatPreferences.chatCacheSizeProperty()); showUserName.bind(chatPreferences.showUserNameProperty()); showBadges.bind(chatPreferences.showBadgesProperty()); - font.bind(chatPreferences.fontProperty()); + font.bind(chatPreferences.fontProperty().map(settings -> new ChatFont(settings.family(), settings.size()))); } private void injectionItemListener(ListChangeListener.Change c) { @@ -111,20 +134,20 @@ private void injectionItemListener(ListChangeListener.Change FlowableSubscriber subscriber(Class type, Consumer consumer) { - return new DownCastFXSubscriber<>(type, consumer); + private FlowableSubscriber subscriber(SessionSubscriptions subscriptions, Class type, Consumer consumer) { + return subscriptions.own(new DownCastFXSubscriber<>(type, consumer)); } @Override - public void subscribeEvents(EventSubscribers eventSubscribers) { - var clearedSub = subscriber(ChatClearedEvent.class, this::onChatCleared); - var deleteSub = subscriber(ChatMessageDeletedEvent.class, this::onMessageDeleted); - var stateSub = subscriber(ChatRoomStateUpdatedEvent.class, this::onStateUpdated); - var cheeredSub = subscriber(CheeredEvent.class, this::onCheered); - var raidReceivedSub = subscriber(RaidReceivedEvent.class, this::onRaidReceived); - var giftedSub = subscriber(UserGiftedSubscribeEvent.class, this::onGiftedSubs); - var subsSub = subscriber(UserSubscribedEvent.class, this::onSubs); - var chatSub = new ChatMessageSubscriber(this::onChatPosted); + protected void onSubscribeEvents(EventSubscribers eventSubscribers, SessionSubscriptions subscriptions) { + var clearedSub = subscriber(subscriptions, ChatClearedEvent.class, this::onChatCleared); + var deleteSub = subscriber(subscriptions, ChatMessageDeletedEvent.class, this::onMessageDeleted); + var stateSub = subscriber(subscriptions, ChatRoomStateUpdatedEvent.class, this::onStateUpdated); + var cheeredSub = subscriber(subscriptions, CheeredEvent.class, this::onCheered); + var raidReceivedSub = subscriber(subscriptions, RaidReceivedEvent.class, this::onRaidReceived); + var giftedSub = subscriber(subscriptions, UserGiftedSubscribeEvent.class, this::onGiftedSubs); + var subsSub = subscriber(subscriptions, UserSubscribedEvent.class, this::onSubs); + var chatSub = subscriptions.own(new ChatMessageSubscriber(this::onChatPosted)); eventSubscribers.subscribeChatEvent(clearedSub); eventSubscribers.subscribeChatEvent(deleteSub); @@ -135,24 +158,9 @@ public void subscribeEvents(EventSubscribers eventSubscribers) { eventSubscribers.subscribeChatEvent(subsSub); eventSubscribers.subscribeMessageEvent(chatSub); - subscribers.addAll(List.of( - clearedSub, - deleteSub, - stateSub, - cheeredSub, - raidReceivedSub, - giftedSub, - subsSub, - chatSub - )); - - onChatOpened = this::onChatOpened; - onKeywordFiltered = this::onKeywordFiltered; - onUserFiltered = this::onUserFiltered; - - subscribe(ChatOpeningEvent.class, onChatOpened); - subscribe(KeywordFilteringEvent.class, onKeywordFiltered); - subscribe(UserFilteringEvent.class, onUserFiltered); + subscriptions.subscribe(ChatOpeningEvent.class, this::onChatOpened); + subscriptions.subscribe(KeywordFilteringEvent.class, this::onKeywordFiltered); + subscriptions.subscribe(UserFilteringEvent.class, this::onUserFiltered); } private Optional find(TwitchChannel channel) { @@ -221,6 +229,10 @@ private void onSubs(UserSubscribedEvent e) { } private void onChatOpened(ChatOpeningEvent e) { + if (!loaded.get()) { + pendingChatOpenings.add(e); + return; + } switch (e.getChatOpenType()) { case MERGED -> openChatRooms(e.getChannels()); case SEPARATED -> e.getChannels().forEach(this::openChatRoom); @@ -231,45 +243,175 @@ public ObservableList getChatRoomList() { return chatRoomList; } + /** + * 初期データの取得を開始して結果を FX スレッドで反映する。FX スレッドから呼び出す。 + * 実行中は同じタスクを返す。UI の準備完了は {@link #loadedProperty()}、失敗は {@link #errorProperty()} で確認する。 + * @return データを取得するタスク + * @throws IllegalStateException このモデルが終了している場合 + */ public FXTask loadAsync() { + if (isClosed()) throw new IllegalStateException("chat container is closed"); + if (activeLoad != null) return activeLoad; if (loaded.get()) return FXTask.empty(); - loaded.set(true); - - var helper = AppHelper.getInstance(); - var twitch = helper.getTwitch(); - - chatFilters = helper.getChatFilters(); - + var request = loadRequestFactory.get(); + loading.set(true); + error.set(null); + var token = new Object(); + synchronized (loadLock) { + loadAttempt = token; + } + var drained = new CompletableFuture(); + var executionClaimed = new AtomicBoolean(); var task = FXTask.task(() -> { - var appDir = OS.current().getApplicationDirectory(); - emoji = new Emoji(appDir); - emojiStore = new ChatEmojiStore(emoji); - - var eit = FXTask.task(() -> { - if (!emoji.validateArchive()) { - emoji.extractArchive(); - emoji.validateArchive(); + final ChatResources result; + try { result = request.loader().call(); } + catch (ChatResourcesLoader.CleanupFailure failure) { + drained.completeExceptionally(failure); + throw failure; + } + synchronized (loadLock) { + if (isCurrentLoad(token)) { + pendingResources = result; + return null; } - return null; - }).runAsync(); - - var globalBadges = new GlobalChatBadges(); - var gbt = FXTask.task(() -> globalBadges.load(twitch)).runAsync(); - globalBadgeStore = new GlobalChatBadgeStore(globalBadges); - chatEmoteStore = new ChatEmoteStore(); - - var cft = FXTask.task(() -> chatFilters.loadAll()).runAsync(); - - gbt.waitForDone(); - cft.waitForDone(); - eit.waitForDone(); - + } + try { result.close(); } + catch (RuntimeException | Error failure) { + // 取消済みTaskの例外には残らないため、実解放の所有者にも保持する。 + drained.completeExceptionally(failure); + throw failure; + } return null; }); + activeLoad = task; + task.onDone(() -> adoptResources(token, request.filters())); + task.addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, event -> failLoading(token)); + task.addEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, event -> { + if (isCurrentLoad(token)) resetLoading(); + }); + task.setFinally(() -> { + if (activeLoad == task) { + activeLoad = null; + loading.set(false); + } + }); + task.completion().whenComplete((ignored, failure) -> { + // 未開始の取消とワーカーの開始のどちらかだけが、この実行を引き受ける。 + if (task.isCancelled() && executionClaimed.compareAndSet(false, true)) drained.complete(null); + }); + try { + shutdownAwaiter.accept(drained.minimalCompletionStage()); + executor.execute(() -> { + if (!executionClaimed.compareAndSet(false, true)) return; + try { task.run(); } + finally { drained.complete(null); } + }); + } catch (RuntimeException | Error rejected) { + LOGGER.error("Failed to start chat resource loading", rejected); + failLoading(token); + task.cancel(); + drained.complete(null); + } + return task; + } - task.runAsync(); + private boolean isCurrentLoad(Object token) { + synchronized (loadLock) { + return !isClosed() && loadAttempt == token; + } + } - return task; + private void adoptResources(Object token, ChatFilters filters) { + synchronized (loadLock) { + if (!isCurrentLoad(token)) return; + resources = pendingResources; + pendingResources = null; + } + try { + var result = resources; + filters.applySnapshot(result.filters()); + if (!isCurrentLoad(token)) return; + chatFilters = filters; + globalBadgeStore = result.badgeStore(); + chatEmoteStore = result.emoteStore(); + emojiStore = result.emojiStore(); + loaded.set(true); + } catch (RuntimeException failure) { + LOGGER.error("Failed to apply chat resources", failure); + failLoading(token); + return; + } + var openings = List.copyOf(pendingChatOpenings); + pendingChatOpenings.clear(); + for (var opening : openings) { + if (!isCurrentLoad(token)) break; + onChatOpened(opening); + } + } + + private void failLoading(Object token) { + if (!isCurrentLoad(token)) return; + resetLoading(); + error.set(Resources.getString("chat.load.failed")); + } + + private void resetLoading() { + final ChatResources pending; + final ChatResources adopted; + synchronized (loadLock) { + loadAttempt = null; + pending = pendingResources; + adopted = resources; + pendingResources = null; + resources = null; + } + var task = activeLoad; + activeLoad = null; + if (task != null) task.cancel(); + loading.set(false); + loaded.set(false); + error.set(null); + chatFilters = null; + globalBadgeStore = null; + chatEmoteStore = null; + emojiStore = null; + releaseResources(pending); + if (adopted != pending) releaseResources(adopted); + } + + private void releaseResources(ChatResources owned) { + if (owned == null) return; + var released = new CompletableFuture(); + Runnable release = () -> { + try { + owned.close(); + released.complete(null); + } catch (RuntimeException | Error failure) { + released.completeExceptionally(failure); + throw failure; + } + }; + // 追跡の登録や借用workerの拒否でも実解放を続け、FX上ではI/Oを行わない。 + CloseActions.runAll( + () -> shutdownAwaiter.accept(released.minimalCompletionStage()), + () -> { + try { executor.execute(release); } + catch (RuntimeException | Error rejected) { + LOGGER.warn("Chat resource release worker is unavailable", rejected); + try { + Thread.ofVirtual().name("TCV-Chat-Resources-Close").start(() -> { + try { release.run(); } + catch (RuntimeException | Error failure) { + LOGGER.error("Failed to release chat resources on fallback worker", failure); + } + }); + } catch (RuntimeException | Error fallbackFailure) { + if (fallbackFailure != rejected) rejected.addSuppressed(fallbackFailure); + released.completeExceptionally(rejected); + throw rejected; + } + } + }); } private void openChatRooms(List channels) { @@ -312,7 +454,8 @@ private void openChatRooms(List channels) { chatRooms, emojiStore, this, - chatFilters + chatFilters, + chatCacheSize.get() ); chatRooms.forEach(SingleChatRoomViewModel::joinChatAsync); @@ -382,8 +525,8 @@ public void removeLast() { if (chatRoomList.isEmpty()) return; var last = getChatRoomList().getLast(); - last.leaveChatAsync(); chatRoomList.remove(last); + leaveRooms(List.of(last)); } void popOutAsFloatableStage(ChatRoomViewModel chatRoom) { @@ -415,7 +558,20 @@ public void unselectAll() { */ public void closeAll() { var selectedList = new ArrayList<>(getSelectedList()); - selectedList.forEach(ChatRoomViewModel::leaveChatAsync); + chatRoomList.removeAll(selectedList); + leaveRooms(selectedList); + } + + private void leaveRooms(List rooms) { + if (!rooms.isEmpty()) trackExit(FXTaskGroup.startAll(rooms, ChatRoomViewModel::leaveChatAsync)); + } + + /** 取消可能な UI の task と分離して、全子タスクの終端と失敗をアプリ終了まで所有する。 */ + void trackExit(FXTaskGroup.Batch exits) { + shutdownAwaiter.accept(exits.settled()); + exits.settled().whenComplete((ignored, failure) -> { + if (failure != null) LOGGER.error("Failed to leave chat rooms", failure); + }); } /** @@ -473,7 +629,8 @@ public void mergeSelectedChats() { chatRooms, emojiStore, this, - chatFilters + chatFilters, + chatCacheSize.get() ); bindChatRoomProperties(chatRoomViewModel); @@ -483,62 +640,40 @@ public void mergeSelectedChats() { } @Override - public void onLogout() { - subscribers.forEach(FlowableSubscriber::cancel); - subscribers.clear(); - - var singles = getChatRoomList(); - var floatings = getFloatingChatRoomList(); - - var chatRooms = new ArrayList(); - chatRooms.addAll(singles); - chatRooms.addAll(floatings); - - singles.clear(); - floatings.clear(); - - chatRooms.forEach(ChatRoomViewModel::leaveChatAsync); + protected void onLoggedOut() { + releaseChatRooms(); + } - unsubscribe(onChatOpened); - unsubscribe(onKeywordFiltered); - unsubscribe(onUserFiltered); - onChatOpened = null; - onKeywordFiltered = null; - onUserFiltered = null; + private void releaseChatRooms() { + pendingChatOpenings.clear(); + var chatRooms = new ArrayList<>(chatRoomList); + chatRooms.addAll(floatingChatRoomList); + CloseActions.runAll(chatRoomList::clear, floatingChatRoomList::clear, + this::resetLoading, () -> leaveRooms(chatRooms)); } /** - * コンテナをクリアする。 - * チャットがすべてログアウトされるまでスレッドをブロックする。 + * チャットの退出を開始する。完了待ちはアプリケーションのワーカー終了処理が行う。 */ @Override - public void close() { - subscribers.forEach(FlowableSubscriber::cancel); - - var singles = getChatRoomList(); - var floatings = getFloatingChatRoomList(); - - if (emoji != null) { - emoji.close(); - } - - var chatRooms = new ArrayList(); - chatRooms.addAll(singles); - chatRooms.addAll(floatings); - chatRooms.stream().map(ChatRoomViewModel::leaveChatAsync).forEach(task -> { - try { - task.get(10, TimeUnit.SECONDS); - } catch (InterruptedException | ExecutionException | TimeoutException ignored) { - // no-op - } - }); + protected void onClose() { + CloseActions.runAll(this::releaseChatRooms, + chatCacheSize::unbind, showUserName::unbind, showBadges::unbind, font::unbind); } // ******************** PROPERTIES ******************** + /** すべてのリソースとフィルターを UI に反映し、チャットを開ける状態。 */ public ReadOnlyBooleanProperty loadedProperty() { return loaded.getReadOnlyProperty(); } public boolean isLoaded() { return loaded.get(); } + /** キューでの待機を含む初期ロード中の状態。 */ + public ReadOnlyBooleanProperty loadingProperty() { return loading.getReadOnlyProperty(); } + public boolean isLoading() { return loading.get(); } + + public ReadOnlyStringProperty errorProperty() { return error.getReadOnlyProperty(); } + public String getError() { return error.get(); } + public ReadOnlyBooleanProperty selectModeProperty() { return selectMode.getReadOnlyProperty(); } public boolean isSelectMode() { return selectMode.get(); } diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomViewModel.java b/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomViewModel.java index 04579c1..eda9a7e 100644 --- a/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/chat/ChatRoomViewModel.java @@ -36,6 +36,7 @@ import org.slf4j.LoggerFactory; import java.util.LinkedList; +import java.util.List; public abstract class ChatRoomViewModel { @@ -155,9 +156,7 @@ private ChatDataViewModel createChatDataViewModel(TwitchChannelViewModel channel } public void addChat(ChatDataViewModel chat) { - chat.visibleNameProperty().bind(showName); - chat.visibleBadgeProperty().bind(showBadges); - chat.fontProperty().bind(font); + bindPresentation(chat); // 上限制限 if (getChatCacheSize() <= chatDataList.size()) { @@ -166,11 +165,23 @@ public void addChat(ChatDataViewModel chat) { chatDataList.add(chat); } + /** 呼出元で選択した履歴を、このモデルの表示設定へ接続して置き換える。 */ + protected final void replaceChatHistory(List history) { + var snapshot = List.copyOf(history); + snapshot.forEach(this::bindPresentation); + chatDataList.setAll(snapshot); + } + + private void bindPresentation(ChatDataViewModel chat) { + chat.visibleNameProperty().bind(showName); + chat.visibleBadgeProperty().bind(showBadges); + chat.fontProperty().bind(font); + } + public void deleteChatMessage(String msgId) { for (var item : chatDataList) { if (item.getChatData().msgId().equalsIgnoreCase(msgId)) { item.setDeleted(true); - break; } } } diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/GlobalChatBadgeStore.java b/src/main/java/com/github/k7t3/tcv/app/chat/GlobalChatBadgeStore.java index 82120e7..ba2e5cb 100644 --- a/src/main/java/com/github/k7t3/tcv/app/chat/GlobalChatBadgeStore.java +++ b/src/main/java/com/github/k7t3/tcv/app/chat/GlobalChatBadgeStore.java @@ -17,6 +17,7 @@ package com.github.k7t3.tcv.app.chat; import com.github.k7t3.tcv.app.image.LazyImage; +import com.github.k7t3.tcv.app.image.ImageLoader; import com.github.k7t3.tcv.app.service.CachedImageStore; import com.github.k7t3.tcv.domain.chat.ChatBadge; import com.github.k7t3.tcv.domain.chat.GlobalChatBadges; @@ -26,17 +27,19 @@ public class GlobalChatBadgeStore extends CachedImageStore { private final GlobalChatBadges globalBadges; + private final ImageLoader images; - public GlobalChatBadgeStore(GlobalChatBadges globalChatBadges) { + public GlobalChatBadgeStore(GlobalChatBadges globalChatBadges, ImageLoader images) { super(16, Duration.ofMinutes(5)); this.globalBadges = globalChatBadges; + this.images = images; } @Override protected LazyImage loadImage(ChatBadge key) { var url = globalBadges.getBadgeUrl(key.id(), key.version()).orElse(null); if (url == null) return null; - return new LazyImage(url, 0, 0); + return images.load(url, 0, 0); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/MergedChatRoomViewModel.java b/src/main/java/com/github/k7t3/tcv/app/chat/MergedChatRoomViewModel.java index 76b5970..77ec9fc 100644 --- a/src/main/java/com/github/k7t3/tcv/app/chat/MergedChatRoomViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/chat/MergedChatRoomViewModel.java @@ -20,6 +20,7 @@ import com.github.k7t3.tcv.app.chat.filter.ChatFilters; import com.github.k7t3.tcv.app.emoji.ChatEmojiStore; import com.github.k7t3.tcv.app.service.FXTask; +import com.github.k7t3.tcv.app.service.FXTaskGroup; import com.github.k7t3.tcv.domain.channel.TwitchChannel; import com.github.k7t3.tcv.domain.event.chat.ChatRoomStateUpdatedEvent; import de.saxsys.mvvmfx.ViewModel; @@ -28,10 +29,6 @@ import java.nio.charset.StandardCharsets; import java.util.*; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; public class MergedChatRoomViewModel extends ChatRoomViewModel implements ViewModel { @@ -48,9 +45,23 @@ public class MergedChatRoomViewModel extends ChatRoomViewModel implements ViewMo ChatEmojiStore emojiCache, ChatRoomContainerViewModel containerViewModel, ChatFilters chatFilters + ) { + this(globalChatBadgeStore, emoteStore, definedChatColors, chatRooms, emojiCache, containerViewModel, + chatFilters, DEFAULT_ITEM_COUNT_LIMIT); + } + + MergedChatRoomViewModel( + GlobalChatBadgeStore globalChatBadgeStore, + ChatEmoteStore emoteStore, + DefinedChatColors definedChatColors, + List chatRooms, + ChatEmojiStore emojiCache, + ChatRoomContainerViewModel containerViewModel, + ChatFilters chatFilters, + int initialLimit ) { super(globalChatBadgeStore, emoteStore, definedChatColors, emojiCache, containerViewModel, chatFilters); - setChatCacheSize(DEFAULT_ITEM_COUNT_LIMIT); + setChatCacheSize(initialLimit); initChatRooms(chatRooms); } @@ -72,23 +83,7 @@ public String getIdentity() { public void addChatRoom(SingleChatRoomViewModel chatRoom) { var channel = chatRoom.getChannel(); - - // - // 追加するチャットルームが現在持っているチャットの情報をマージする - // とりあえずすべてマージして最後に制限の個数で切り捨てる - // - var mergedChats = new ArrayList<>(getChatDataList()); - mergedChats.addAll(chatRoom.getChatDataList()); - mergedChats.sort(Comparator.comparing(o -> o.getChatData().firedAt())); - - var limit = getChatCacheSize(); - if (mergedChats.size() <= limit) { - getChatDataList().setAll(mergedChats); - } else { - var subList = mergedChats.subList(mergedChats.size() - limit, mergedChats.size()); - getChatDataList().setAll(subList); - } - + mergeHistory(chatRoom.getChatDataList()); channels.put(channel, chatRoom); } @@ -125,7 +120,7 @@ public void separateChatRoom(SingleChatRoomViewModel chatRoom) { .toList(); // 分離したチャンネルにチャット情報を渡す - chatRoom.getChatDataList().setAll(chatList); + chatRoom.replaceChatHistory(chatList); // 現在のチャットから削除 getChatDataList().removeAll(chatList); @@ -142,38 +137,30 @@ public void closeChatRoom(SingleChatRoomViewModel chatRoom) { channels.remove(channel); + chatRoom.leaveChatAsync(); onChannelRemoved(); } public void aggregate(MergedChatRoomViewModel mergedChatRoom) { if (this == mergedChatRoom) return; - + var incoming = new HashMap(); for (var entry : mergedChatRoom.channels.entrySet()) { - var channel = entry.getKey(); - var chatRoom = entry.getValue(); - - if (channels.containsValue(chatRoom)) continue; - - // - // 追加するチャットルームが現在持っているチャットの情報をマージする - // とりあえずすべてマージして、最後に制限の個数で切り捨てる - // - var mergedChats = new ArrayList<>(getChatDataList()); - mergedChats.addAll(chatRoom.getChatDataList()); - mergedChats.sort(Comparator.comparing(o -> o.getChatData().firedAt())); - - var limit = getChatCacheSize(); - if (mergedChats.size() <= limit) { - chatRoom.getChatDataList().setAll(mergedChats); - } else { - var subList = mergedChats.subList(mergedChats.size() - limit, mergedChats.size()); - chatRoom.getChatDataList().setAll(subList); - } - - channels.put(channel, chatRoom); - containerViewModel.getChatRoomList().remove(mergedChatRoom); + if (!channels.containsKey(entry.getKey())) incoming.put(entry.getKey(), entry.getValue()); } + var incomingHistory = mergedChatRoom.getChatDataList().stream() + .filter(chat -> incoming.containsKey(chat.getChannel())) + .toList(); + mergeHistory(incomingHistory); + channels.putAll(incoming); + containerViewModel.getChatRoomList().remove(mergedChatRoom); + } + private void mergeHistory(List incoming) { + var mergedChats = new ArrayList<>(getChatDataList()); + mergedChats.addAll(incoming); + mergedChats.sort(Comparator.comparing(chat -> chat.getChatData().firedAt())); + var begin = Math.max(0, mergedChats.size() - getChatCacheSize()); + replaceChatHistory(mergedChats.subList(begin, mergedChats.size())); } public ObservableMap getChannels() { @@ -193,11 +180,10 @@ public boolean accept(TwitchChannel channel) { public void onStateUpdated(ChatRoomStateUpdatedEvent e) { var chatRoom = e.getChatRoom(); - // ConcurrentModificationExceptionが内部で起こり得る? channels.entrySet() .stream() - .filter(entry -> entry.getKey().getChannel().isChatJoined()) - .filter(entry -> entry.getKey().getChannel().getOrJoinChatRoom().equals(chatRoom)) + .filter(entry -> entry.getKey().getChannel().getJoinedChatRoom() + .filter(current -> current == chatRoom).isPresent()) .findFirst() .map(Map.Entry::getValue) .ifPresent(chatRoomViewModel -> chatRoomViewModel.onStateUpdated(e)); @@ -221,28 +207,12 @@ public FXTask joinChatAsync() { @Override public FXTask leaveChatAsync() { + List.copyOf(channels.values()).forEach(SingleChatRoomViewModel::stopReceivingState); containerViewModel.onLeft(this); - // FIXME JavaFXのTaskをマージするには? - var latch = new CountDownLatch(channels.size()); - - channels.keySet().parallelStream().map(TwitchChannelViewModel::leaveChatAsync).forEach(task -> { - try { - task.get(30, TimeUnit.SECONDS); - } catch (InterruptedException | ExecutionException | TimeoutException ignored) { - // no-op - } finally { - latch.countDown(); - } - }); - - return FXTask.task(() -> { - try { - latch.await(); - } catch (InterruptedException ignored) { - // no-op - } - }); + var exits = FXTaskGroup.startAll(channels.keySet(), TwitchChannelViewModel::leaveChatAsync); + containerViewModel.trackExit(exits); + return exits.task(); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/SingleChatRoomViewModel.java b/src/main/java/com/github/k7t3/tcv/app/chat/SingleChatRoomViewModel.java index 462b2cc..374f7cc 100644 --- a/src/main/java/com/github/k7t3/tcv/app/chat/SingleChatRoomViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/chat/SingleChatRoomViewModel.java @@ -20,6 +20,7 @@ import com.github.k7t3.tcv.app.chat.filter.ChatFilters; import com.github.k7t3.tcv.app.emoji.ChatEmojiStore; import com.github.k7t3.tcv.app.service.FXTask; +import com.github.k7t3.tcv.app.service.FXTaskGroup; import com.github.k7t3.tcv.domain.channel.TwitchChannel; import com.github.k7t3.tcv.domain.chat.ChatRoomState; import com.github.k7t3.tcv.domain.event.chat.ChatRoomStateUpdatedEvent; @@ -36,6 +37,7 @@ import java.util.Base64; import java.util.HashSet; import java.util.Objects; +import java.util.List; public class SingleChatRoomViewModel extends ChatRoomViewModel implements ViewModel { @@ -44,6 +46,8 @@ public class SingleChatRoomViewModel extends ChatRoomViewModel implements ViewMo private final ReadOnlyObjectWrapper channel; private final ObservableSet roomStates = FXCollections.observableSet(new HashSet<>()); + private boolean left; + private FXTask leaving; SingleChatRoomViewModel( ChatRoomContainerViewModel containerViewModel, @@ -60,21 +64,25 @@ public class SingleChatRoomViewModel extends ChatRoomViewModel implements ViewMo @Override public FXTask joinChatAsync() { + if (left) throw new IllegalStateException("chat room has been left"); var channel = getChannel(); return channel.joinChatAsync(); } @Override public FXTask leaveChatAsync() { + if (leaving != null) return leaving; + stopReceivingState(); var channel = getChannel(); - - if (channel.isChatJoined()) { - containerViewModel.onLeft(this); - } - - return channel.leaveChatAsync(); + containerViewModel.onLeft(this); + var exits = FXTaskGroup.startAll(List.of(channel), TwitchChannelViewModel::leaveChatAsync); + leaving = exits.task(); + containerViewModel.trackExit(exits); + return exits.task(); } + void stopReceivingState() { left = true; } + @Override public boolean accept(TwitchChannel channel) { var viewModel = getChannel(); @@ -103,11 +111,13 @@ public ObservableSet getRoomStates() { @Override public void onStateUpdated(ChatRoomStateUpdatedEvent e) { + if (left) return; var roomState = e.getState(); var active = e.isActive(); LOGGER.info("{} room state updated {}", getChannel().getUserLogin(), roomState); Platform.runLater(() -> { + if (left || getChannel().getChannel().getJoinedChatRoom().orElse(null) != e.getChatRoom()) return; if (active) roomStates.add(roomState); else diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/filter/ChatFilters.java b/src/main/java/com/github/k7t3/tcv/app/chat/filter/ChatFilters.java index 4ad01ec..c96ddda 100644 --- a/src/main/java/com/github/k7t3/tcv/app/chat/filter/ChatFilters.java +++ b/src/main/java/com/github/k7t3/tcv/app/chat/filter/ChatFilters.java @@ -19,30 +19,77 @@ import com.github.k7t3.tcv.app.model.AbstractViewModel; import com.github.k7t3.tcv.app.service.FXTask; import com.github.k7t3.tcv.domain.chat.ChatData; -import com.github.k7t3.tcv.domain.event.EventSubscribers; import com.github.k7t3.tcv.entity.ChatKeywordFilterEntity; import com.github.k7t3.tcv.entity.ChatUserFilterEntity; -import com.github.k7t3.tcv.entity.service.ChatKeywordFilterEntityService; -import com.github.k7t3.tcv.entity.service.ChatUserFilterEntityService; +import com.github.k7t3.tcv.entity.service.ChatFilterEntityStore; +import com.github.k7t3.tcv.app.event.KeywordFilteringEvent; +import com.github.k7t3.tcv.app.event.UserFilteringEvent; +import java.util.Set; +import java.util.HashSet; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicReference; + import javafx.collections.FXCollections; import javafx.collections.ObservableList; +import javafx.application.Platform; import java.util.function.Predicate; +import java.util.function.Consumer; import java.util.regex.Pattern; +import java.util.List; public class ChatFilters extends AbstractViewModel { - private final ChatKeywordFilterEntityService keywordService; - private final ChatUserFilterEntityService userService; + /** + * UI のモデルを含まない、フィルターの読み込み結果。両リストは変更不可のコピーとして保持する。 + * @param keywords キーワードフィルター + * @param users ユーザーフィルター + */ + public record Snapshot(List keywords, List users, long revision) { + public Snapshot(List keywords, List users) { this(keywords, users, 0); } + public static Snapshot from(ChatFilterEntityStore.Snapshot snapshot) { + return new Snapshot(snapshot.keywords(), snapshot.users(), snapshot.revision()); + } + public Snapshot { + keywords = List.copyOf(keywords); + users = List.copyOf(users); + } + } + + private final ChatFilterEntityStore store; + private final Executor executor; + private final Consumer> shutdownAwaiter; + private final Consumer failures; + private final Object writesLock = new Object(); + private final Set pendingWrites = new HashSet<>(); + private long appliedRevision = -1; + private long session; private final ObservableList keywordEntries = FXCollections.observableArrayList(); private final ObservableList userEntries = FXCollections.observableArrayList(); private final Predicate filter; - public ChatFilters(ChatKeywordFilterEntityService keywordService, ChatUserFilterEntityService userService) { - this.keywordService = keywordService; - this.userService = userService; + private static final class Write { + final CompletableFuture settled = new CompletableFuture<>(); + Throwable failure; + boolean ioFinished; + boolean errorObserved; + boolean retired; + } + + /** + * 実行前に保存の終了をshutdownAwaiterへ登録する。executorは借用する。 + * 返すTaskの取消で受付済みの書き込みを取り消さず、終了時は未通知の保存失敗を回収する。 + */ + public ChatFilters(ChatFilterEntityStore store, Executor executor, Consumer> shutdownAwaiter, + Consumer failures) { + this.store = java.util.Objects.requireNonNull(store); + this.executor = java.util.Objects.requireNonNull(executor); + this.shutdownAwaiter = java.util.Objects.requireNonNull(shutdownAwaiter); + this.failures = java.util.Objects.requireNonNull(failures); filter = new KeywordFilter(keywordEntries).or(new UserFilter(userEntries)); } @@ -58,59 +105,140 @@ public ObservableList getUserEntries() { return userEntries; } - public void loadAll() { - var ke = keywordService.retrieveAll().stream().map(this::fromKeywordEntity).toList(); - keywordEntries.setAll(ke); + /** UI 状態を変更せず永続化データを読み込む。バックグラウンドから呼び出せる。 */ + public Snapshot readSnapshot() { + return Snapshot.from(store.read()); + } + + /** + * 読み込み結果から UI の項目を作成し、両一覧を置き換える。変換失敗時はいずれの一覧も変更しない。 + * @param snapshot 読み込み済みのデータ + * @throws IllegalStateException FX スレッド以外から呼び出した場合 + */ + public void applySnapshot(Snapshot snapshot) { + if (!Platform.isFxApplicationThread()) throw new IllegalStateException("use the FX application thread"); + if (isClosed() || snapshot.revision() < appliedRevision) return; + var owner = session; + var ke = snapshot.keywords().stream().map(this::fromKeywordEntity).toList(); - var ue = userService.retrieveAll() + var ue = snapshot.users() .stream() .map(u -> new UserFilterEntry(u.userId(), u.userName(), u.comment())) .toList(); + appliedRevision = snapshot.revision(); + keywordEntries.setAll(ke); + if (isClosed() || session != owner || snapshot.revision() != appliedRevision) return; userEntries.setAll(ue); } - public void saveUserFilter(UserFilterEntry entry) { - FXTask.task(() -> userService.save(toUserEntity(entry))).onDone(e -> { - if (userEntries.stream().noneMatch(e2 -> e2.getUserId().equals(entry.getUserId()))) { - userEntries.add(entry); - } - }).runAsync(); + /** 保存後の全体像を反映してから、既存メッセージにもフィルターを適用する。 */ + public void applyCommittedSnapshot(ChatFilterEntityStore.Snapshot saved) { + if (!Platform.isFxApplicationThread()) throw new IllegalStateException("use the FX application thread"); + if (isClosed() || saved.revision() < appliedRevision) return; + var owner = session; + applySnapshot(Snapshot.from(saved)); + // 通知中に一覧が再入変更されても、列挙を壊さない。 + for (var entry : List.copyOf(keywordEntries)) { + if (isClosed() || session != owner || saved.revision() != appliedRevision) return; + publish(new KeywordFilteringEvent(entry)); + } + for (var entry : List.copyOf(userEntries)) { + if (isClosed() || session != owner || saved.revision() != appliedRevision) return; + publish(new UserFilteringEvent(entry)); + } } - public FXTask deleteUserFilter(UserFilterEntry entry) { - return FXTask.task(() -> userService.delete(toUserEntity(entry))) - .onDone(entity -> userEntries.remove(entry)) - .runAsync(); + /** 現在のセッションで受け付けた保存結果だけを反映する FX 用 callback。保存 I/O 自体は取り消さない。 */ + public Consumer captureCommitHandler() { + if (!Platform.isFxApplicationThread()) throw new IllegalStateException("use the FX application thread"); + var owner = session; + return saved -> { if (!isClosed() && session == owner) applyCommittedSnapshot(saved); }; } - private ChatUserFilterEntity toUserEntity(UserFilterEntry entry) { - return new ChatUserFilterEntity(entry.getUserId(), entry.getUserName(), entry.getComment()); + public FXTask saveUserFilter(UserFilterEntry entry) { + var row = new ChatUserFilterEntity(entry.getUserId(), entry.getUserName(), entry.getComment()); + return submit(new ChatFilterEntityStore.Changes(List.of(), Set.of(), List.of(row), Set.of())); } - public void saveKeywordFilter(KeywordFilterEntry entry) { - if (entry.getFilterId() < 1) { - var t = FXTask.task(() -> keywordService.insert(toKeywordEntity(entry))); - t.onDone(id -> { - entry.setFilterId(id); - keywordEntries.add(entry); - }).runAsync(); - } else { - FXTask.task(() -> keywordService.update(toKeywordEntity(entry))).runAsync(); - } + public FXTask deleteUserFilter(UserFilterEntry entry) { + return submit(new ChatFilterEntityStore.Changes(List.of(), Set.of(), List.of(), Set.of(entry.getUserId()))); + } + + public FXTask saveKeywordFilter(KeywordFilterEntry entry) { + var row = new ChatKeywordFilterEntity(Math.max(0, entry.getFilterId()), entry.getFilterType().getType(), entry.getKeyword()); + return submit(new ChatFilterEntityStore.Changes(List.of(row), Set.of(), List.of(), Set.of())); + } + + public FXTask deleteKeywordFilter(KeywordFilterEntry entry) { + var deleted = entry.getFilterId() > 0 ? Set.of(entry.getFilterId()) : Set.of(); + return submit(new ChatFilterEntityStore.Changes(List.of(), deleted, List.of(), Set.of())); } - public FXTask deleteKeywordFilter(KeywordFilterEntry entry) { - return FXTask.task(() -> keywordService.delete(toKeywordEntity(entry))) - .onDone(entity -> keywordEntries.remove(entry)) - .runAsync(); + private FXTask submit(ChatFilterEntityStore.Changes changes) { + if (!Platform.isFxApplicationThread()) throw new IllegalStateException("use the FX application thread"); + if (isClosed()) throw new IllegalStateException("chat filters are closed"); + var owner = session; + var write = new Write(); + synchronized (writesLock) { pendingWrites.add(write); } + var task = FXTask.task(() -> { + try { return store.save(changes, () -> {}); } + catch (RuntimeException | Error failure) { + synchronized (writesLock) { write.failure = failure; } + throw failure; + } finally { + synchronized (writesLock) { + write.ioFinished = true; + settle(write); + } + } + }); + var applicationFailure = new AtomicReference(); + var observation = FXTask.observation(() -> { + var failure = applicationFailure.get(); + if (failure == null) failure = task.getException(); + if (failure instanceof Exception exception) throw exception; + if (failure instanceof Error error) throw error; + return task.getValue(); + }); + var committed = captureCommitHandler(); + task.onDone(saved -> { + try { committed.accept(saved); } + catch (RuntimeException | Error failure) { + applicationFailure.set(failure); + failures.accept(failure); + } + finally { observation.run(); } + }); + task.onFailure(failure -> { + var visible = !isClosed() && session == owner; + synchronized (writesLock) { + if (visible) write.errorObserved = true; + settle(write); + } + try { if (visible) failures.accept(failure); } + finally { observation.run(); } + }); + try { + shutdownAwaiter.accept(write.settled.minimalCompletionStage()); + executor.execute(task); + } catch (RuntimeException | Error failure) { + synchronized (writesLock) { + write.ioFinished = true; + settle(write); + } + task.cancel(); + observation.cancel(); + throw failure; + } + return observation; } - private ChatKeywordFilterEntity toKeywordEntity(KeywordFilterEntry entry) { - return new ChatKeywordFilterEntity( - entry.getFilterId(), - entry.getFilterType().getType(), - entry.getKeyword() - ); + /** writesLock内で呼び、開いた画面が扱った失敗を終了時に再送出しない。 */ + private void settle(Write write) { + if (!write.ioFinished) return; + if (write.failure == null || write.errorObserved) write.settled.complete(null); + else if (isClosed() || write.retired) write.settled.completeExceptionally(write.failure); + if (write.settled.isDone()) pendingWrites.remove(write); } private KeywordFilterEntry fromKeywordEntity(ChatKeywordFilterEntity entity) { @@ -127,17 +255,24 @@ private KeywordFilterEntry fromKeywordEntity(ChatKeywordFilterEntity entity) { } @Override - public void subscribeEvents(EventSubscribers eventSubscribers) { - // no-op - } - - @Override - public void onLogout() { + protected void onLoggedOut() { + session++; + synchronized (writesLock) { + for (var write : List.copyOf(pendingWrites)) { + write.retired = true; + settle(write); + } + } keywordEntries.clear(); userEntries.clear(); } @Override - public void close() { + protected void onClose() { + synchronized (writesLock) { + for (var write : List.copyOf(pendingWrites)) settle(write); + } + keywordEntries.clear(); + userEntries.clear(); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/chat/filter/KeywordFilterEntry.java b/src/main/java/com/github/k7t3/tcv/app/chat/filter/KeywordFilterEntry.java index 6f91e44..0ea951b 100644 --- a/src/main/java/com/github/k7t3/tcv/app/chat/filter/KeywordFilterEntry.java +++ b/src/main/java/com/github/k7t3/tcv/app/chat/filter/KeywordFilterEntry.java @@ -48,8 +48,13 @@ public static KeywordFilterEntry exactMatch(String keyword) { return new KeywordFilterEntry(KeywordFilterType.EXACT_MATCH, keyword, null); } + /** + * 正規表現のフィルターを作成する。編集・保存用の文字列として元の式も保持する。 + * @param pattern コンパイル済みの正規表現 + * @return 正規表現のフィルター + */ public static KeywordFilterEntry regexMatch(Pattern pattern) { - return new KeywordFilterEntry(KeywordFilterType.REGEXP, null, pattern); + return new KeywordFilterEntry(KeywordFilterType.REGEXP, pattern.pattern(), pattern); } private boolean startsWith(String message) { diff --git a/src/main/java/com/github/k7t3/tcv/app/clip/ClipThumbnailStore.java b/src/main/java/com/github/k7t3/tcv/app/clip/ClipThumbnailStore.java index e936a44..f6e2472 100644 --- a/src/main/java/com/github/k7t3/tcv/app/clip/ClipThumbnailStore.java +++ b/src/main/java/com/github/k7t3/tcv/app/clip/ClipThumbnailStore.java @@ -17,6 +17,7 @@ package com.github.k7t3.tcv.app.clip; import com.github.k7t3.tcv.app.image.LazyImage; +import com.github.k7t3.tcv.app.image.ImageLoader; import com.github.k7t3.tcv.app.service.CachedImageStore; import org.jetbrains.annotations.Nullable; @@ -26,16 +27,18 @@ public class ClipThumbnailStore extends CachedImageStore { private static final double THUMBNAIL_WIDTH = 128; private static final double THUMBNAIL_HEIGHT = 128; + private final ImageLoader images; - public ClipThumbnailStore() { + public ClipThumbnailStore(ImageLoader images) { super(128, Duration.ofMinutes(5)); + this.images = images; } @Override protected @Nullable LazyImage loadImage(PostedClipItem key) { var link = key.getThumbnailLink(); if (link == null) return null; - return new LazyImage(link, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT); + return images.load(link, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipItem.java b/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipItem.java index 84711c5..460aa7d 100644 --- a/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipItem.java +++ b/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipItem.java @@ -16,13 +16,10 @@ package com.github.k7t3.tcv.app.clip; -import com.github.k7t3.tcv.app.core.AppHelper; import com.github.k7t3.tcv.app.core.DesktopUtils; import com.github.k7t3.tcv.app.image.LazyImage; import com.github.k7t3.tcv.app.service.FXTask; import com.github.k7t3.tcv.domain.channel.Broadcaster; -import com.github.k7t3.tcv.domain.chat.ClipChatMessage; -import com.github.k7t3.tcv.domain.chat.ClipFinder; import com.github.k7t3.tcv.domain.clip.VideoClip; import javafx.beans.property.ReadOnlyIntegerProperty; import javafx.beans.property.ReadOnlyIntegerWrapper; @@ -48,10 +45,13 @@ public class PostedClipItem { private ReadOnlyObjectWrapper clip; private final PostedClipRepository repository; + private final long scope; + private boolean retired; public PostedClipItem(PostedClipRepository repository, String id, String url, VideoClip clip) { if (!url.startsWith("https")) throw new IllegalArgumentException("illegal url: " + url); this.repository = repository; + scope = repository.scope(); this.id.set(id); this.url.set(url); @@ -61,27 +61,15 @@ public PostedClipItem(PostedClipRepository repository, String id, String url, Vi } public FXTask retry() { - var helper = AppHelper.getInstance(); - var finder = new ClipFinder(helper.getTwitch()); - var url = getUrl(); - - var task = FXTask.task(() -> finder.findClip(url).flatMap(ClipChatMessage::getClip).orElse(null)); - return task.onDone(c -> { - if (c != null) { - clip().set(c); - } - }).runAsync(); + return repository.retry(this); } public void remove() { - repository.getItems().remove(getId()); + repository.remove(this); } public FXTask browseClipPageAsync() { - return FXTask.task(() -> { - DesktopUtils.browse(getUrl()); - return null; - }).runAsync(); + return repository.browse(this); } public void copyClipURL() { @@ -89,15 +77,20 @@ public void copyClipURL() { } public LazyImage getThumbnailImage() { - return repository.getThumbnailStore().get(this); + return repository.getThumbnailImage(this); } public void onPosted(Broadcaster broadcaster) { + if (!repository.isActive(this)) return; postedChannels.add(broadcaster); lastPostedAt.set(LocalDateTime.now()); - times.set(times.get() + 1); + if (repository.isActive(this)) times.set(times.get() + 1); } + long scope() { return scope; } + boolean isRetired() { return retired; } + void retire() { retired = true; } + public boolean isPosted(Broadcaster broadcaster) { return postedChannels.contains(broadcaster); } @@ -121,7 +114,7 @@ private ReadOnlyObjectWrapper clip() { } public ReadOnlyObjectProperty clipProperty() { return clip().getReadOnlyProperty(); } public VideoClip getClip() { return clip == null ? null : clip.get(); } - private void setClip(VideoClip clip) { clip().set(clip); } + void setClip(VideoClip clip) { clip().set(clip); } public ObservableValue observableThumbnailLink() { return clip().map(VideoClip::thumbnailUrl); } String getThumbnailLink() { return observableThumbnailLink().getValue(); } diff --git a/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipRepository.java b/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipRepository.java index d0fe2fc..d9c9a59 100644 --- a/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipRepository.java +++ b/src/main/java/com/github/k7t3/tcv/app/clip/PostedClipRepository.java @@ -16,96 +16,276 @@ package com.github.k7t3.tcv.app.clip; -import com.github.k7t3.tcv.app.model.AbstractViewModel; +import com.github.k7t3.tcv.app.service.BrowserActions; import com.github.k7t3.tcv.app.event.ClipPostedAppEvent; +import com.github.k7t3.tcv.app.image.ImageLoader; +import com.github.k7t3.tcv.app.image.LazyImage; +import com.github.k7t3.tcv.app.model.AbstractViewModel; import com.github.k7t3.tcv.app.reactive.DownCastFXSubscriber; +import com.github.k7t3.tcv.app.service.CachedImageStore; +import com.github.k7t3.tcv.app.service.FXTask; +import com.github.k7t3.tcv.domain.Twitch; import com.github.k7t3.tcv.domain.channel.Broadcaster; +import com.github.k7t3.tcv.domain.chat.ClipChatMessage; +import com.github.k7t3.tcv.domain.chat.ClipFinder; +import com.github.k7t3.tcv.domain.clip.VideoClip; import com.github.k7t3.tcv.domain.event.EventSubscribers; import com.github.k7t3.tcv.domain.event.chat.ChatRoomEvent; import com.github.k7t3.tcv.domain.event.chat.ClipPostedEvent; -import com.github.k7t3.tcv.reactive.FlowableSubscriber; +import com.github.k7t3.tcv.lifecycle.CloseActions; import javafx.beans.binding.Bindings; import javafx.beans.binding.NumberBinding; import javafx.collections.FXCollections; import javafx.collections.ObservableMap; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import java.time.Duration; +import java.util.IdentityHashMap; import java.util.List; +import java.util.Objects; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.function.BiFunction; +import java.util.function.Consumer; +/** 投稿項目と、そのセッションで開始したクリップ照会・画像を所有する。操作・反映は FX スレッドで行う。 */ public class PostedClipRepository extends AbstractViewModel { - + private static final Logger LOGGER = LoggerFactory.getLogger(PostedClipRepository.class); private final ObservableMap items = FXCollections.observableHashMap(); - + private final ObservableMap readOnlyItems = FXCollections.unmodifiableObservableMap(items); + private final IdentityHashMap requests = new IdentityHashMap<>(); + private final ImageLoader images; + private final Executor executor; + private final BiFunction lookup; + private final Consumer> shutdownAwaiter; + private final Consumer failures; + private final BrowserActions browsers; private ClipThumbnailStore thumbnailStore; + private CachedImageStore broadcasterImages; + private Twitch session; + private long scope; + private boolean imagesAvailable = true; - private FlowableSubscriber subscriber; + public PostedClipRepository(ImageLoader images, Executor executor, Consumer> shutdownAwaiter, + Consumer failures) { + this(images, executor, (client, url) -> new ClipFinder(client).findClip(url) + .flatMap(ClipChatMessage::getClip).orElse(null), shutdownAwaiter, failures); + } + + PostedClipRepository(ImageLoader images, Executor executor, BiFunction lookup, + Consumer> shutdownAwaiter, Consumer failures) { + this.images = Objects.requireNonNull(images); + this.executor = Objects.requireNonNull(executor); + this.lookup = Objects.requireNonNull(lookup); + this.shutdownAwaiter = Objects.requireNonNull(shutdownAwaiter); + this.failures = Objects.requireNonNull(failures); + browsers = new BrowserActions(executor, shutdownAwaiter, failures); + } - public PostedClipRepository() { + public void setSession(Twitch twitch) { + if (isClosed()) throw new IllegalStateException("clip repository is closed"); + Objects.requireNonNull(twitch); + if (session == twitch) return; + onLogout(); + session = twitch; + imagesAvailable = true; } @Override - public void subscribeEvents(EventSubscribers eventSubscribers) { - subscriber = new DownCastFXSubscriber<>(ClipPostedEvent.class, this::onClipPostedEvent); + protected void onSubscribeEvents(EventSubscribers eventSubscribers, SessionSubscriptions subscriptions) { + var subscriber = subscriptions.own(new DownCastFXSubscriber(ClipPostedEvent.class, this::onClipPostedEvent)); eventSubscribers.subscribeChatEvent(subscriber); } - private void onClipPostedEvent(ClipPostedEvent e) { - var chatRoom = e.getChatRoom(); - var broadcaster = chatRoom.getBroadcaster(); - var clipChatMessage = e.getClipChatMessage(); - - var id = clipChatMessage.getId(); - var url = clipChatMessage.getEstimatedURL(); - var clip = clipChatMessage.getClip().orElse(null); - - var item = items.get(id); + private void onClipPostedEvent(ClipPostedEvent event) { + if (isClosed() || !imagesAvailable) return; + if (session != null && !event.getChatRoom().isOwnedBy(session)) return; + var message = event.getClipChatMessage(); + var item = items.get(message.getId()); + boolean created = item == null; if (item == null) { - item = new PostedClipItem(this, id, url, clip); - item.onPosted(broadcaster); - items.put(id, item); + item = new PostedClipItem(this, message.getId(), message.getEstimatedURL(), message.getClip().orElse(null)); + item.onPosted(event.getChatRoom().getBroadcaster()); + items.put(item.getId(), item); } else { - item.onPosted(broadcaster); + item.onPosted(event.getChatRoom().getBroadcaster()); + if (message.getClip().isPresent() && isActive(item) && items.get(item.getId()) == item) { + var previous = requests.remove(item); + if (previous != null) previous.result.cancel(true); + invalidateThumbnail(item); + if (isActive(item) && items.get(item.getId()) == item) item.setClip(message.getClip().orElseThrow()); + } + } + if (created && message.getClip().isEmpty() && session != null && isActive(item) && items.get(item.getId()) == item) { + lookup(item, false); } + if (!isClosed() && imagesAvailable) publish(new ClipPostedAppEvent()); + } - publishEvent(); + public ObservableMap getItems() { return readOnlyItems; } + public NumberBinding getCountBinding() { return Bindings.size(items); } + + public List getPostedBroadcasters() { + return items.values().stream().flatMap(item -> item.getPostedChannels().stream()).distinct().toList(); } - private void publishEvent() { - publish(new ClipPostedAppEvent()); + long scope() { return scope; } + + boolean isActive(PostedClipItem item) { + return !isClosed() && imagesAvailable && !item.isRetired() && item.scope() == scope; } - public ObservableMap getItems() { - return items; + private void requireActive(PostedClipItem item) { + if (!isActive(item)) throw new IllegalStateException("clip item is no longer active"); } - public NumberBinding getCountBinding() { - return Bindings.size(items); + private void requireOwned(PostedClipItem item) { + requireActive(item); + if (items.get(item.getId()) != item) throw new IllegalStateException("clip item is no longer owned"); } - public List getPostedBroadcasters() { - return items.values() - .stream() - .flatMap(p -> p.getPostedChannels().stream()) - .distinct() - .toList(); + FXTask retry(PostedClipItem item) { + return lookup(item, true); } - ClipThumbnailStore getThumbnailStore() { - if (thumbnailStore == null) { - thumbnailStore = new ClipThumbnailStore(); + private FXTask lookup(PostedClipItem item, boolean notifyFailure) { + requireOwned(item); + if (session == null) throw new IllegalStateException("clip session is not available"); + var previous = requests.get(item); + if (previous != null && !previous.result.isDone()) { + previous.notifyFailure |= notifyFailure; + return previous.result; } - return thumbnailStore; + var request = new Request(item, notifyFailure); + requests.put(item, request); + request.worker.cancelWhenCancelled(request.result); + request.result.cancelWhenCancelled(request.worker); + request.result.onFailure(failure -> { + if (!isCurrent(request)) return; + if (request.notifyFailure) failures.accept(failure); + else LOGGER.warn("clip lookup failed for {}", request.url, failure); + }); + request.result.setFinally(() -> { + requests.remove(item, request); + request.worker.cancel(true); + }); + request.worker.onDone(value -> { request.value = value; request.result.run(); }); + request.worker.onFailure(failure -> { request.failure = failure; request.result.run(); }); + try { + shutdownAwaiter.accept(request.drained.minimalCompletionStage()); + executor.execute(() -> { + try { request.worker.run(); } + finally { request.drained.complete(null); } + }); + } catch (RuntimeException | Error failure) { + request.failure = failure; + request.result.run(); + request.worker.cancel(true); + request.drained.complete(null); + } + return request.result; } - @Override - public void onLogout() { - if (subscriber != null) { - subscriber.cancel(); + private boolean isCurrent(Request request) { + return isActive(request.item) && items.get(request.item.getId()) == request.item + && requests.get(request.item) == request && session == request.owner + && !request.result.isCancelled(); + } + + private final class Request { + final PostedClipItem item; + final Twitch owner = session; + final String url; + final CompletableFuture drained = new CompletableFuture<>(); + final FXTask worker; + final FXTask result; + VideoClip value; + Throwable failure; + boolean notifyFailure; + + Request(PostedClipItem item, boolean notifyFailure) { + this.item = item; + this.notifyFailure = notifyFailure; + url = item.getUrl(); + worker = FXTask.task(() -> lookup.apply(owner, url)); + result = FXTask.observation(() -> { + if (!isCurrent(this)) throw new CancellationException("clip lookup is no longer owned"); + if (failure instanceof Error error) throw error; + if (failure instanceof Exception exception) throw exception; + if (value != null) { + invalidateThumbnail(item); + if (!isCurrent(this)) throw new CancellationException("clip lookup was retired during image release"); + item.setClip(value); + } + return value; + }); } - items.clear(); } - @Override - public void close() { - // no-op + FXTask browse(PostedClipItem item) { + requireOwned(item); + return browsers.open(item.getUrl()); + } + + void remove(PostedClipItem item) { + if (items.get(item.getId()) != item) return; + item.retire(); + var request = requests.remove(item); + CloseActions.runAll( + () -> { if (request != null) request.result.cancel(true); }, + () -> items.remove(item.getId(), item), + () -> invalidateThumbnail(item)); + } + + private void invalidateThumbnail(PostedClipItem item) { + if (thumbnailStore != null) thumbnailStore.invalidate(item); + } + + LazyImage getThumbnailImage(PostedClipItem item) { + requireActive(item); + if (thumbnailStore == null) thumbnailStore = new ClipThumbnailStore(images); + return thumbnailStore.get(item); + } + + /** 30px の投稿先プロフィール画像。読込はこのリポジトリが所有する。 */ + public LazyImage getBroadcasterImage(Broadcaster broadcaster) { + if (isClosed() || !imagesAvailable) throw new IllegalStateException("clip image scope is closed"); + if (broadcasterImages == null) { + broadcasterImages = new CachedImageStore<>(64, Duration.ofMinutes(5)) { + @Override protected LazyImage loadImage(Broadcaster key) { + return images.load(key.getProfileImageUrl(), 30, 30); + } + }; + } + return broadcasterImages.get(broadcaster); + } + + @Override protected void onLoggedOut() { endScope(); } + @Override protected void onClose() { CloseActions.runAll(this::endScope, browsers::close); } + + private void endScope() { + scope++; + session = null; + imagesAvailable = false; + items.values().forEach(PostedClipItem::retire); + var pending = List.copyOf(requests.values()); + requests.clear(); + CloseActions.runAll( + () -> CloseActions.runAll(pending.stream().map(request -> (Runnable) () -> request.result.cancel(true)).toArray(Runnable[]::new)), + browsers::cancelAll, + items::clear, + this::releaseImages); + } + + private void releaseImages() { + var thumbnails = thumbnailStore; + var broadcasters = broadcasterImages; + thumbnailStore = null; + broadcasterImages = null; + CloseActions.runAll( + () -> { if (thumbnails != null) thumbnails.close(); }, + () -> { if (broadcasters != null) broadcasters.close(); }); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/core/AppHelper.java b/src/main/java/com/github/k7t3/tcv/app/core/AppHelper.java index c8c6f24..bec5cf7 100644 --- a/src/main/java/com/github/k7t3/tcv/app/core/AppHelper.java +++ b/src/main/java/com/github/k7t3/tcv/app/core/AppHelper.java @@ -16,91 +16,173 @@ package com.github.k7t3.tcv.app.core; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import com.github.k7t3.tcv.app.event.SessionInvalidatedEvent; +import de.saxsys.mvvmfx.MvvmFX; +import javafx.application.Platform; + import com.github.k7t3.tcv.app.chat.filter.ChatFilters; import com.github.k7t3.tcv.app.group.ChannelGroupRepository; +import com.github.k7t3.tcv.app.image.ImageLoader; import com.github.k7t3.tcv.app.keyboard.KeyBindingCombinations; -import com.github.k7t3.tcv.app.service.FXTask; import com.github.k7t3.tcv.app.service.TaskWorker; import com.github.k7t3.tcv.app.service.WindowBoundsService; import com.github.k7t3.tcv.app.user.UserDataFile; +import com.github.k7t3.tcv.app.prefs.SettingsSaveService; +import com.github.k7t3.tcv.prefs.AppPreferences; import com.github.k7t3.tcv.domain.Twitch; +import com.github.k7t3.tcv.domain.channel.ChannelRepository; import com.github.k7t3.tcv.domain.event.EventPublishers; import com.github.k7t3.tcv.domain.event.EventSubscribers; import com.github.k7t3.tcv.entity.service.ChannelGroupEntityService; -import com.github.k7t3.tcv.entity.service.ChatKeywordFilterEntityService; -import com.github.k7t3.tcv.entity.service.ChatUserFilterEntityService; +import com.github.k7t3.tcv.entity.service.ChatFilterEntityStore; + import com.github.k7t3.tcv.entity.service.WindowBoundsEntityService; import javafx.beans.property.*; import javafx.stage.Stage; import java.io.Closeable; import java.util.Objects; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.function.Function; +import java.util.function.Consumer; public class AppHelper implements Closeable { - - private final ReadOnlyStringWrapper userId = new ReadOnlyStringWrapper(); - private final ReadOnlyStringWrapper userName = new ReadOnlyStringWrapper(); - private final ReadOnlyBooleanWrapper authorized = new ReadOnlyBooleanWrapper(); - private final ObjectProperty twitch = new SimpleObjectProperty<>(); - private ObjectProperty primaryStage; - private final EventPublishers publishers = new EventPublishers(); - private final EventSubscribers subscribers = new EventSubscribers(publishers); + private final EventPublishers publishers; + private final EventSubscribers subscribers; + private final TaskWorker worker; + private final Consumer failureHandler; private UserDataFile userDataFile; private ChannelGroupRepository channelGroupRepository; private WindowBoundsService windowBoundsService; private KeyBindingCombinations keyBindingCombinations; + private ChatFilterEntityStore chatFilterStore; private ChatFilters chatFilters; + private final List> lifetimeReleases = new ArrayList<>(); + private final List lifetimeReleaseFailures = new ArrayList<>(); + private final Object lifecycleLock = new Object(); + private ImageLoader imageLoader; + private boolean closed; + private boolean preparingShutdown; + private boolean uiModelsReleased; + private final ClientSessions sessions; + private final CompletableFuture applicationClosed = new CompletableFuture<>(); + private Thread closingThread; + + /** このアプリ専用のワーカーと発行元を新しく所有する。 */ + public AppHelper(Consumer failureHandler) { + this(new TaskWorker(), new EventPublishers(), failureHandler); + } + + /** 注入したワーカーと発行元を、このアプリケーションが終了まで所有する。 */ + public AppHelper(TaskWorker worker, EventPublishers publishers, Consumer failureHandler) { + this(worker, publishers, client -> new ChannelRepository(client, publishers), failureHandler); + } + + AppHelper(TaskWorker worker, EventPublishers publishers, Function channelFactory, + Consumer failureHandler) { + this.worker = Objects.requireNonNull(worker); + this.publishers = Objects.requireNonNull(publishers); + this.failureHandler = Objects.requireNonNull(failureHandler); + this.subscribers = new EventSubscribers(publishers); + this.sessions = new ClientSessions(command -> worker.getExecutor().execute(command), Platform::runLater, + channelFactory, this::publishSessionInvalidated); + } + + private void publishSessionInvalidated() { + var event = new SessionInvalidatedEvent(sessions); + MvvmFX.getNotificationCenter().publish(SessionInvalidatedEvent.class.getName(), event); + } - private AppHelper() { - userId.bind(twitch.map(Twitch::getUserId)); - userName.bind(twitch.map(Twitch::getUserName)); - authorized.bind(twitch.isNotNull()); + /** 現在セッションの操作・状態を借用する。終了はアプリ全体の所有者が行う。 */ + public ClientSessions getClientSessions() { + synchronized (lifecycleLock) { checkOpen(); return sessions; } } public void setUserDataFile(UserDataFile userDataFile) { - this.userDataFile = userDataFile; + synchronized (lifecycleLock) { + checkOpen(); + Objects.requireNonNull(userDataFile); + if (this.userDataFile != null && this.userDataFile != userDataFile) { + throw new IllegalStateException("application already owns a user database"); + } + this.userDataFile = userDataFile; + } } public UserDataFile getUserDataFile() { - return userDataFile; + synchronized (lifecycleLock) { return userDataFile; } } public ChannelGroupRepository getChannelGroupRepository() { - if (channelGroupRepository == null) { - var userDataFile = getUserDataFile(); - var groupService = new ChannelGroupEntityService(userDataFile.getConnector()); - channelGroupRepository = new ChannelGroupRepository(groupService); + synchronized (lifecycleLock) { + checkOpen(); + if (channelGroupRepository == null) { + var userDataFile = Objects.requireNonNull(getUserDataFile()); + var groupService = new ChannelGroupEntityService(userDataFile.getConnector()); + channelGroupRepository = new ChannelGroupRepository(groupService, worker.getExecutor(), this::awaitOnShutdown, + this::reportFailure); + channelGroupRepository.setEventSubscribers(subscribers); + } + return channelGroupRepository; } - return channelGroupRepository; } public WindowBoundsService getWindowBoundsService() { - if (windowBoundsService == null) { - var userDataFile = Objects.requireNonNull(getUserDataFile()); - var entityService = new WindowBoundsEntityService(userDataFile.getConnector()); - windowBoundsService = new WindowBoundsService(entityService); + synchronized (lifecycleLock) { + checkOpen(); + if (windowBoundsService == null) { + var userDataFile = Objects.requireNonNull(getUserDataFile()); + var entityService = new WindowBoundsEntityService(userDataFile.getConnector()); + windowBoundsService = new WindowBoundsService(entityService, worker.getExecutor(), this::awaitOnShutdown); + } + return windowBoundsService; } - return windowBoundsService; } public KeyBindingCombinations getKeyBindingCombinations() { - if (keyBindingCombinations == null) { - keyBindingCombinations = new KeyBindingCombinations(); + synchronized (lifecycleLock) { + checkOpen(); + if (keyBindingCombinations == null) keyBindingCombinations = new KeyBindingCombinations(); + return keyBindingCombinations; } - return keyBindingCombinations; + } + + public ChatFilterEntityStore getChatFilterStore() { + synchronized (lifecycleLock) { + checkOpen(); + if (chatFilterStore == null) chatFilterStore = new ChatFilterEntityStore(Objects.requireNonNull(getUserDataFile()).getConnector()); + return chatFilterStore; + } + } + + /** 設定キャッシュを構築する前に、接続済みDBの未完了投影を背景で復旧する。 */ + public void recoverSettings(AppPreferences preferences) { + new SettingsSaveService(preferences, getChatFilterStore()).recover(); } public ChatFilters getChatFilters() { - if (chatFilters == null) { - var userDataFile = Objects.requireNonNull(getUserDataFile()); - var a = new ChatKeywordFilterEntityService(userDataFile.getConnector()); - var b = new ChatUserFilterEntityService(userDataFile.getConnector()); - chatFilters = new ChatFilters(a, b); + synchronized (lifecycleLock) { + checkOpen(); + if (chatFilters == null) { + chatFilters = new ChatFilters(getChatFilterStore(), worker.getExecutor(), this::awaitOnShutdown, + this::reportFailure); + chatFilters.setEventSubscribers(subscribers); + } + return chatFilters; } - return chatFilters; + } + + private void reportFailure(Throwable failure) { + failureHandler.accept(failure); } public EventPublishers getPublishers() { @@ -111,58 +193,157 @@ public EventSubscribers getSubscribers() { return subscribers; } - public FXTask logoutAsync() { - if (!isAuthorized()) return FXTask.empty(); - - final var twitch = getTwitch(); - setTwitch(null); + /** + * アプリが所有する共有画像サービスを借用する。終了は AppHelper が行う。 + * @return 共有画像サービス + * @throws IllegalStateException アプリが終了している場合 + */ + public ImageLoader getImageLoader() { + synchronized (lifecycleLock) { + checkOpen(); + if (imageLoader == null) imageLoader = new ImageLoader(worker.getExecutor()); + return imageLoader; + } + } - var task = FXTask.task(twitch::logout); - task.runAsync(); - return task; + public ChannelRepository getChannelRepository() { + synchronized (lifecycleLock) { + checkOpen(); + return sessions.getChannelRepository(); + } } - @Override - public void close() { - if (userDataFile != null) { - userDataFile.closeDatabase(); + public Executor getExecutor() { + synchronized (lifecycleLock) { + checkOpen(); + return worker.getExecutor(); } + } - var twitch = getTwitch(); - if (twitch != null) { - twitch.close(); + /** UI が開始前から所有する非同期解放を登録し、アプリ終了時に完了と失敗を回収する。 */ + public void awaitOnShutdown(CompletionStage release) { + Objects.requireNonNull(release); + synchronized (lifecycleLock) { + checkOpen(); + if (lifetimeReleases.contains(release)) return; + lifetimeReleases.add(release); + release.whenComplete((ignored, failure) -> { + synchronized (lifecycleLock) { + lifetimeReleases.remove(release); + if (failure != null) lifetimeReleaseFailures.add(unwrap(failure)); + } + }); } + } - var publishers = getPublishers(); - publishers.close(); + public CompletionStage logoutAsync() { + return logoutAsync(() -> {}); + } - var worker = TaskWorker.getInstance(); - worker.close(); + /** FX 側を切り離してから、捕捉した同じセッションを背景で終了する。観測の取消は解放に作用しない。 */ + public CompletionStage logoutAsync(Runnable detachViews) { + synchronized (lifecycleLock) { checkOpen(); } + return sessions.logoutAsync(detachViews); } - public static AppHelper getInstance() { - return Holder.INSTANCE; + /** FX 側の参照・購読を閉じ、新しいサービス取得を止める。UI 所有者が close の前に呼ぶ。 */ + public void prepareShutdown() { + final ChannelGroupRepository groups; + final ChatFilters filters; + final WindowBoundsService bounds; + synchronized (lifecycleLock) { + preparingShutdown = true; + if (uiModelsReleased) return; + uiModelsReleased = true; + sessions.stopAccepting(); + groups = channelGroupRepository; + filters = chatFilters; + bounds = windowBoundsService; + } + CloseActions.runAll(sessions::freezeCredentials, sessions::detachViews, () -> { if (groups != null) groups.close(); }, + () -> { if (filters != null) filters.close(); }, () -> { if (bounds != null) bounds.close(); }); } - private static class Holder { - private static final AppHelper INSTANCE = new AppHelper(); + @Override + public void close() { + final ImageLoader images; + final List> releases; + final List releaseFailures; + final boolean owner; + synchronized (lifecycleLock) { + if (closingThread == Thread.currentThread()) return; + owner = !closed; + if (owner) { + closed = true; + closingThread = Thread.currentThread(); + sessions.stopAccepting(); + } + images = imageLoader; + releases = List.copyOf(lifetimeReleases); + releaseFailures = List.copyOf(lifetimeReleaseFailures); + } + if (!owner) { + try { applicationClosed.join(); } + catch (CompletionException failure) { rethrow(unwrap(failure)); } + return; + } + try { + CloseActions.runAll( + this::prepareShutdown, + () -> { if (images != null) images.close(); }, + worker::close, + () -> CloseActions.runAll(releases.stream().map(release -> (Runnable) () -> { + try { release.toCompletableFuture().join(); } + catch (CompletionException failure) { rethrow(unwrap(failure)); } + }).toArray(Runnable[]::new)), + () -> CloseActions.runAll(releaseFailures.stream().map(failure -> (Runnable) () -> rethrow(failure)).toArray(Runnable[]::new)), + sessions::close, + publishers::close, + () -> { if (userDataFile != null) userDataFile.closeDatabase(); } + ); + applicationClosed.complete(null); + } catch (RuntimeException | Error failure) { + applicationClosed.completeExceptionally(failure); + throw failure; + } finally { + synchronized (lifecycleLock) { closingThread = null; } + } } + // ######################################## // PROPERTIES - public ReadOnlyStringProperty userIdProperty() { return userId.getReadOnlyProperty(); } - public String getUserId() { return userId.get(); } + public ReadOnlyStringProperty userIdProperty() { return sessions.userIdProperty(); } + public String getUserId() { return sessions.getUserId(); } + + public ReadOnlyStringProperty userNameProperty() { return sessions.userNameProperty(); } + public String getUserName() { return sessions.getUserName(); } + + public ReadOnlyBooleanProperty authorizedProperty() { return sessions.authorizedProperty(); } + public boolean isAuthorized() { return sessions.isAuthorized(); } - public ReadOnlyStringProperty userNameProperty() { return userName.getReadOnlyProperty(); } - public String getUserName() { return userName.get(); } + public ReadOnlyObjectProperty twitchProperty() { return sessions.twitchProperty(); } + public Twitch getTwitch() { return sessions.getTwitch(); } + public void setTwitch(Twitch client) { + synchronized (lifecycleLock) { checkOpen(); } + sessions.adopt(client); + } - public ReadOnlyBooleanProperty authorizedProperty() { return authorized.getReadOnlyProperty(); } - public boolean isAuthorized() { return authorized.get(); } + private void checkOpen() { + if (closed || preparingShutdown) throw new IllegalStateException("application is closed"); + } - public ObjectProperty twitchProperty() { return twitch; } - public Twitch getTwitch() { return twitch.get(); } - public void setTwitch(Twitch twitch) { this.twitch.set(twitch); } + private static Throwable unwrap(Throwable failure) { + while (failure instanceof CompletionException && failure.getCause() != null) failure = failure.getCause(); + return failure; + } + + private static void rethrow(Throwable failure) { + if (failure instanceof RuntimeException exception) throw exception; + if (failure instanceof Error error) throw error; + throw new IllegalStateException(failure); + } public ObjectProperty primaryStageProperty() { if (primaryStage == null) primaryStage = new SimpleObjectProperty<>(); diff --git a/src/main/java/com/github/k7t3/tcv/app/core/ClientSession.java b/src/main/java/com/github/k7t3/tcv/app/core/ClientSession.java new file mode 100644 index 0000000..206d70d --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/core/ClientSession.java @@ -0,0 +1,93 @@ +package com.github.k7t3.tcv.app.core; + +import com.github.k7t3.tcv.domain.Twitch; +import com.github.k7t3.tcv.domain.channel.ChannelRepository; +import com.github.k7t3.tcv.lifecycle.CloseActions; + +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CompletionStage; + +/** 一回のログインで作成したドメインと SDK クライアントを、終了完了まで所有する。 */ +final class ClientSession implements AutoCloseable { + private final Twitch twitch; + private final ChannelRepository channels; + private final Object lifecycleLock = new Object(); + private final CompletableFuture completed = new CompletableFuture<>(); + private final CompletionStage result = completed.minimalCompletionStage(); + private boolean logoutRequested; + private boolean started; + private Thread closingThread; + private CompletionStage beforeEnd = CompletableFuture.completedFuture(null); + + ClientSession(Twitch twitch, ChannelRepository channels) { + this.twitch = Objects.requireNonNull(twitch); + this.channels = Objects.requireNonNull(channels); + } + + Twitch twitch() { return twitch; } + ChannelRepository channels() { return channels; } + CompletionStage completion() { return result; } + + void requestLogout() { + requestLogout(CompletableFuture.completedFuture(null)); + } + + void requestLogout(CompletionStage detached) { + synchronized (lifecycleLock) { + if (started) throw new IllegalStateException("session is already ending"); + logoutRequested = true; + beforeEnd = Objects.requireNonNull(detached); + twitch.freezeCredentials(); + } + } + + void requestClose(CompletionStage detached) { + synchronized (lifecycleLock) { + if (started) throw new IllegalStateException("session is already ending"); + beforeEnd = Objects.requireNonNull(detached); + twitch.freezeCredentials(); + } + } + + @Override + public void close() { + final boolean owner; + final boolean logout; + final CompletionStage prerequisite; + synchronized (lifecycleLock) { + if (closingThread == Thread.currentThread()) return; + owner = !started; + if (owner) { + started = true; + closingThread = Thread.currentThread(); + } + logout = logoutRequested; + prerequisite = beforeEnd; + } + if (!owner) { + try { completed.join(); } + catch (CompletionException failure) { rethrow(failure.getCause()); } + return; + } + try { + CloseActions.runAll(twitch::freezeCredentials, () -> { + try { prerequisite.toCompletableFuture().join(); } + catch (CompletionException failure) { rethrow(failure.getCause()); } + }, channels::clear, logout ? twitch::logout : twitch::close); + completed.complete(null); + } catch (RuntimeException | Error failure) { + completed.completeExceptionally(failure); + throw failure; + } finally { + synchronized (lifecycleLock) { closingThread = null; } + } + } + + private static void rethrow(Throwable failure) { + if (failure instanceof RuntimeException exception) throw exception; + if (failure instanceof Error error) throw error; + throw new IllegalStateException(failure); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/core/ClientSessions.java b/src/main/java/com/github/k7t3/tcv/app/core/ClientSessions.java new file mode 100644 index 0000000..efecfcb --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/core/ClientSessions.java @@ -0,0 +1,251 @@ +package com.github.k7t3.tcv.app.core; + +import com.github.k7t3.tcv.domain.Twitch; +import com.github.k7t3.tcv.domain.channel.ChannelRepository; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import javafx.beans.property.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.function.Function; + +/** + * アプリごとの現在・終了待ちのセッションと、資格情報の再採用制御を所有する。 + * executorは借用し、停止しない。UIを切り離した後、実I/Oの回収後に背景でcloseする。 + */ +public final class ClientSessions implements AutoCloseable { + private static final Logger LOGGER = LoggerFactory.getLogger(ClientSessions.class); + private final Object lifecycleLock = new Object(); + private final Executor executor; + private final Executor ui; + private final Function channelFactory; + private final Runnable invalidated; + private final ReadOnlyStringWrapper userId = new ReadOnlyStringWrapper(); + private final ReadOnlyStringWrapper userName = new ReadOnlyStringWrapper(); + private final ReadOnlyBooleanWrapper authorized = new ReadOnlyBooleanWrapper(); + private final ReadOnlyObjectWrapper twitch = new ReadOnlyObjectWrapper<>(); + private final Set sessions = new HashSet<>(); + private final Set revokedTokens = new HashSet<>(); + private final Set revokingSessions = new HashSet<>(); + private final List sessionFailures = new ArrayList<>(); + private final CompletableFuture completed = new CompletableFuture<>(); + private ClientSession activeSession; + private boolean stopping; + private boolean closed; + private Thread closingThread; + + ClientSessions(Executor executor, Executor ui, Function channelFactory, Runnable invalidated) { + this.executor = Objects.requireNonNull(executor); + this.ui = Objects.requireNonNull(ui); + this.channelFactory = Objects.requireNonNull(channelFactory); + this.invalidated = Objects.requireNonNull(invalidated); + userId.bind(twitch.map(Twitch::getUserId)); + userName.bind(twitch.map(Twitch::getUserName)); + authorized.bind(twitch.isNotNull()); + } + + /** 現在のセッションのリポジトリを借用する。終了後・未ログインでは取得できない。 */ + public ChannelRepository getChannelRepository() { + synchronized (lifecycleLock) { + checkOpen(); + if (activeSession == null) throw new IllegalStateException("no active client session"); + return activeSession.channels(); + } + } + + /** FXで画面を切り離した後に背景で解放する。観測の取消は実解放を取り消さない。 */ + public CompletionStage logoutAsync(Runnable detachViews) { + return endSession(null, true, detachViews); + } + + private CompletionStage endSession(ClientSession expected, boolean revoke, Runnable detachViews) { + final ClientSession session; + var detached = new CompletableFuture(); + Throwable preparationFailure = null; + synchronized (lifecycleLock) { + if (expected != null && (closed || stopping || activeSession != expected)) return CompletableFuture.completedFuture(null); + checkOpen(); + session = activeSession; + if (session != null) { + try { + CloseActions.runAll(() -> { + if (revoke) session.requestLogout(detached); + else session.requestClose(detached); + }, () -> { + revokingSessions.add(session); + revokedTokens.addAll(tokens(session.twitch())); + }); + } catch (RuntimeException | Error failure) { + preparationFailure = failure; + } + } + activeSession = null; + } + Throwable detachFailure = null; + final var beforeDetach = preparationFailure; + try { + CloseActions.runAll(() -> { if (beforeDetach != null) rethrow(beforeDetach); }, + () -> twitch.set(null), detachViews); + } catch (RuntimeException | Error failure) { + detachFailure = failure; + } + if (detachFailure == null) detached.complete(null); + else detached.completeExceptionally(detachFailure); + var result = new CompletableFuture(); + final var previous = detachFailure; + var completion = session == null ? CompletableFuture.completedFuture(null) : session.completion(); + completion.whenComplete((ignored, failure) -> { + var actual = unwrap(failure); + if (previous != null) { + if (actual != null && actual != previous) previous.addSuppressed(actual); + actual = previous; + } + if (actual == null) result.complete(null); + else result.completeExceptionally(actual); + }); + if (session != null) releaseAsync(session); + return result.minimalCompletionStage(); + } + + private void sessionInvalidated(ClientSession session) { + ui.execute(() -> endSession(session, false, invalidated)); + } + + private static Set tokens(Twitch client) { + var result = new HashSet<>(client.credentialTokens()); + var current = client.getAccessToken(); + if (current != null) result.add(current); + return result; + } + + private void releaseAsync(ClientSession session) { + Runnable release = () -> { + try { session.close(); } + catch (RuntimeException | Error failure) { LOGGER.error("client session release failed", failure); } + }; + try { + executor.execute(release); + } catch (RuntimeException | Error rejected) { + // sessions が引き続き所有するため、アプリ停止もこの終了完了を回収する。 + Thread.ofVirtual().name("TCV-Session-End").start(release); + } + } + + ReadOnlyStringProperty userIdProperty() { return userId.getReadOnlyProperty(); } + String getUserId() { return userId.get(); } + + public ReadOnlyStringProperty userNameProperty() { return userName.getReadOnlyProperty(); } + String getUserName() { return userName.get(); } + + public ReadOnlyBooleanProperty authorizedProperty() { return authorized.getReadOnlyProperty(); } + boolean isAuthorized() { return authorized.get(); } + + ReadOnlyObjectProperty twitchProperty() { return twitch.getReadOnlyProperty(); } + public Twitch getTwitch() { return twitch.get(); } + /** FX上でクライアントを採用する。終了・失効済みの資格情報は受け付けない。 */ + public void adopt(Twitch client) { + final ClientSession previous; + synchronized (lifecycleLock) { + checkOpen(); + if (activeSession != null && activeSession.twitch() == client) return; + if (client != null) { + var candidate = tokens(client); + if (client.isClosed() || client.isClosing() || client.hasInvalidCredentials() + || candidate.stream().anyMatch(revokedTokens::contains) + || revokingSessions.stream().anyMatch(session -> tokens(session.twitch()).stream().anyMatch(candidate::contains))) { + throw new IllegalStateException("client credential belongs to an ended session"); + } + } + var next = client == null ? null : new ClientSession(client, channelFactory.apply(client)); + previous = activeSession; + activeSession = next; + if (next != null) { + sessions.add(next); + next.completion().whenComplete((ignored, failure) -> { + synchronized (lifecycleLock) { + sessions.remove(next); + if (revokingSessions.remove(next)) revokedTokens.addAll(tokens(next.twitch())); + if (failure != null) sessionFailures.add(unwrap(failure)); + } + }); + client.onInvalidated(() -> sessionInvalidated(next)); + } + } + CloseActions.runAll(() -> twitch.set(client), () -> { if (previous != null) releaseAsync(previous); }); + } + + /** 新しい採用を止める。状態確定中にクライアント側の処理は呼び出さない。 */ + void stopAccepting() { + synchronized (lifecycleLock) { + stopping = true; + } + } + + /** 停止済みの受付範囲にある全クライアントを試行し、最初の失敗を保持する。 */ + void freezeCredentials() { + final List owned; + synchronized (lifecycleLock) { owned = List.copyOf(sessions); } + CloseActions.runAll(owned.stream().map(session -> (Runnable) session.twitch()::freezeCredentials).toArray(Runnable[]::new)); + } + + /** 所有するプロパティの参照をFX側の終了準備で外す。 */ + void detachViews() { twitch.set(null); } + + @Override + public void close() { + final List owned; + final List failures; + final boolean owner; + synchronized (lifecycleLock) { + if (closingThread == Thread.currentThread()) return; + owner = !closed; + if (owner) { + closed = true; + stopping = true; + closingThread = Thread.currentThread(); + } + owned = List.copyOf(sessions); + failures = List.copyOf(sessionFailures); + } + if (!owner) { + try { completed.join(); } + catch (CompletionException failure) { rethrow(unwrap(failure)); } + return; + } + try { + CloseActions.runAll( + () -> CloseActions.runAll(owned.stream().map(session -> (Runnable) session::close).toArray(Runnable[]::new)), + () -> CloseActions.runAll(failures.stream().map(failure -> (Runnable) () -> rethrow(failure)).toArray(Runnable[]::new))); + completed.complete(null); + } catch (RuntimeException | Error failure) { + completed.completeExceptionally(failure); + throw failure; + } finally { + synchronized (lifecycleLock) { closingThread = null; } + } + } + + private void checkOpen() { + if (closed || stopping) throw new IllegalStateException("application is closed"); + } + + private static Throwable unwrap(Throwable failure) { + while (failure instanceof CompletionException && failure.getCause() != null) failure = failure.getCause(); + return failure; + } + + private static void rethrow(Throwable failure) { + if (failure instanceof RuntimeException exception) throw exception; + if (failure instanceof Error error) throw error; + throw new IllegalStateException(failure); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/core/DesktopUtils.java b/src/main/java/com/github/k7t3/tcv/app/core/DesktopUtils.java index 4bb94ec..c4f2a0d 100644 --- a/src/main/java/com/github/k7t3/tcv/app/core/DesktopUtils.java +++ b/src/main/java/com/github/k7t3/tcv/app/core/DesktopUtils.java @@ -19,37 +19,13 @@ import javafx.scene.input.Clipboard; import javafx.scene.input.DataFormat; -import java.awt.*; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; import java.util.Map; public class DesktopUtils { - public static void browse(String url) throws URISyntaxException, IOException { - var uri = new URI(url); - C.desktop.browse(uri); - } - - public static void clipText(String text) { - var cb = Clipboard.getSystemClipboard(); - cb.setContent(Map.of(DataFormat.PLAIN_TEXT, text)); - } - public static void clipURL(String url) { var cb = Clipboard.getSystemClipboard(); cb.setContent(Map.of(DataFormat.URL, url, DataFormat.PLAIN_TEXT, url)); } - private static class C { - private static final Desktop desktop; - static { - desktop = Desktop.getDesktop(); - if (!desktop.isSupported(Desktop.Action.BROWSE)) { - throw new RuntimeException("browse action not supported"); - } - } - } - } diff --git a/src/main/java/com/github/k7t3/tcv/app/core/ExceptionHandler.java b/src/main/java/com/github/k7t3/tcv/app/core/ExceptionHandler.java index bacb123..ea22ba0 100644 --- a/src/main/java/com/github/k7t3/tcv/app/core/ExceptionHandler.java +++ b/src/main/java/com/github/k7t3/tcv/app/core/ExceptionHandler.java @@ -20,6 +20,8 @@ import javafx.scene.control.Alert; import javafx.scene.control.TextArea; import javafx.stage.Stage; +import javafx.stage.WindowEvent; +import javafx.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,27 +36,26 @@ public class ExceptionHandler { private ExceptionHandler() { } - public static void handle(Throwable e) { - handle(null, e); - } - + /** + * 指定された所有者へ表示する。認証失効では、所有関係の最上位Stageを終了する。 + * 所有者がなければ、別アプリのウインドウを取得・終了しない。 + */ public static void handle(Stage parent, Throwable e) { LOGGER.error(e.getMessage(), e); // 資格情報が無効になったとき if (e instanceof InvalidCredentialException) { - var helper = AppHelper.getInstance(); - var primaryStage = helper.getPrimaryStage(); - + var application = parent; + while (application != null && application.getOwner() instanceof Stage owner) application = owner; var alert = new Alert(Alert.AlertType.ERROR); - alert.initOwner(primaryStage); + if (application != null) alert.initOwner(application); alert.setTitle("Twitch API Error"); alert.setHeaderText(Resources.getString("terminate.header")); alert.setContentText(Resources.getString("terminate.content")); - alert.showAndWait(); + showOwned(application, alert); - primaryStage.close(); + if (application != null) application.close(); return; @@ -80,7 +81,21 @@ public static void handle(Stage parent, Throwable e) { pane.setContent(stacktrace); pane.setExpanded(false); - alert.showAndWait(); + showOwned(parent, alert); + } + + private static void showOwned(Stage owner, Alert alert) { + if (owner == null) { + alert.showAndWait(); + return; + } + EventHandler closed = event -> alert.close(); + owner.addEventHandler(WindowEvent.WINDOW_HIDDEN, closed); + try { + alert.showAndWait(); + } finally { + owner.removeEventHandler(WindowEvent.WINDOW_HIDDEN, closed); + } } } diff --git a/src/main/java/com/github/k7t3/tcv/app/core/LoggerInitializer.java b/src/main/java/com/github/k7t3/tcv/app/core/LoggerInitializer.java index 8ae754a..fa25825 100644 --- a/src/main/java/com/github/k7t3/tcv/app/core/LoggerInitializer.java +++ b/src/main/java/com/github/k7t3/tcv/app/core/LoggerInitializer.java @@ -16,33 +16,151 @@ package com.github.k7t3.tcv.app.core; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import java.io.IOException; import java.io.InputStream; -import java.util.concurrent.Callable; -import java.util.logging.LogManager; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Properties; +import java.util.logging.ConsoleHandler; +import java.util.logging.FileHandler; +import java.util.logging.Formatter; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; public class LoggerInitializer { private LoggerInitializer() { } - public static void initialize() { - initialize(() -> LoggerInitializer.class.getResourceAsStream("/logging.properties")); + public static LoggingSession initialize() { + return initialize(OS.current().getApplicationDirectory(), Logger.getLogger(""), + LoggerInitializer.class.getResourceAsStream("/logging.properties")); } - private static void initialize(Callable callable) { - try (var is = callable.call()) { - LogManager.getLogManager().updateConfiguration(is, k -> ((o, n) -> { - if (k.equals("java.util.logging.FileHandler.pattern")) { - var appDir = OS.current().getApplicationDirectory(); - var logFile = appDir.resolve("log%g.log"); - return logFile.toString(); - } else { - return n; + /** 設定ストリームを消費・解放し、指定した logger のハンドラーだけを管理する。 */ + static LoggingSession initialize(Path directory, Logger target, InputStream source) { + var properties = new Properties(); + try (var input = Objects.requireNonNull(source, "logging configuration is missing")) { + properties.load(input); + } catch (IOException failure) { throw new UncheckedIOException(failure); } + var level = Level.parse(properties.getProperty(".level", "INFO")); + var consoleLevel = Level.parse(properties.getProperty("java.util.logging.ConsoleHandler.level", "INFO")); + var fileLevel = Level.parse(properties.getProperty("java.util.logging.FileHandler.level", "ALL")); + var limit = Long.parseLong(properties.getProperty("java.util.logging.FileHandler.limit", "1073741824")); + var count = Integer.parseInt(properties.getProperty("java.util.logging.FileHandler.count", "10")); + if (limit < 0 || count < 1) throw new IllegalArgumentException("invalid log rotation settings"); + var formatter = new TextLogFormatter(properties.getProperty("java.util.logging.SimpleFormatter.format", + "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$s [%2$s] %5$s %6$s%n")); + var handlers = new ArrayList(); + LoggingSession session = null; + try { + Files.createDirectories(directory); + var console = new ConsoleHandler(); + handlers.add(console); + console.setEncoding("UTF-8"); + console.setFormatter(formatter); + console.setLevel(consoleLevel); + // 明示的に生成し、FileHandler の開始エラーを起動失敗として呼出元へ返す。 + var file = new FileHandler(directory.resolve("log%g.log").toString(), limit, count, false); + handlers.add(file); + file.setEncoding("UTF-8"); + file.setFormatter(formatter); + file.setLevel(fileLevel); + synchronized (target) { + session = new LoggingSession(target, handlers, target.getHandlers(), target.getLevel()); + for (var previous : session.borrowed) target.removeHandler(previous); + for (var handler : handlers) target.addHandler(handler); + target.setLevel(level); + } + return session; + } catch (IOException | RuntimeException | Error failure) { + var primary = failure instanceof IOException io ? new UncheckedIOException(io) : failure; + var installed = session; + CloseActions.runAll(() -> rethrow(primary), () -> { + if (installed != null) installed.close(); + else CloseActions.runAll(handlers.stream().map(handler -> (Runnable) handler::close).toArray(Runnable[]::new)); + }); + throw new AssertionError("unreachable"); + } + } + + /** アプリが導入したハンドラーだけを閉じ、借用した設定を戻す。 */ + public static final class LoggingSession implements AutoCloseable { + private final Logger target; + private final List owned; + private final Handler[] borrowed; + private final Level previousLevel; + private boolean closed; + + private LoggingSession(Logger target, List owned, Handler[] borrowed, Level previousLevel) { + this.target = target; + this.owned = List.copyOf(owned); + this.borrowed = borrowed; + this.previousLevel = previousLevel; + } + + @Override public void close() { + synchronized (target) { + if (closed) return; + closed = true; + var actions = new ArrayList(); + for (var handler : owned) { + actions.add(() -> target.removeHandler(handler)); + actions.add(handler::close); } - })); - } catch (Exception e) { - throw new RuntimeException(e); + for (var handler : borrowed) actions.add(() -> { + if (Arrays.stream(target.getHandlers()).noneMatch(current -> current == handler)) target.addHandler(handler); + }); + actions.add(() -> target.setLevel(previousLevel)); + CloseActions.runAll(actions.toArray(Runnable[]::new)); + } } } + private static final class TextLogFormatter extends Formatter { + private final String pattern; + + private TextLogFormatter(String pattern) { + this.pattern = pattern; + // リソースを作成する前に、6引数の書式が有効か確認する。 + render(ZonedDateTime.now(), "source", "logger", "INFO", "message", ""); + } + + @Override public String format(LogRecord record) { + var source = record.getSourceClassName(); + if (source == null) source = record.getLoggerName(); + else if (record.getSourceMethodName() != null) source += " " + record.getSourceMethodName(); + var trace = new StringWriter(); + if (record.getThrown() != null) { + var writer = new PrintWriter(trace); + writer.println(); + record.getThrown().printStackTrace(writer); + writer.flush(); + } + return render(record.getInstant().atZone(ZoneId.systemDefault()), source, record.getLoggerName(), + record.getLevel().getLocalizedName(), formatMessage(record), trace.toString()); + } + + private String render(ZonedDateTime time, String source, String logger, String level, String message, String trace) { + return String.format(pattern, time, source, logger, level, message, trace); + } + } + + private static void rethrow(Throwable failure) { + if (failure instanceof RuntimeException exception) throw exception; + if (failure instanceof Error error) throw error; + throw new RuntimeException(failure); + } } diff --git a/src/main/java/com/github/k7t3/tcv/app/core/Resources.java b/src/main/java/com/github/k7t3/tcv/app/core/Resources.java index 3669d61..e5e1b26 100644 --- a/src/main/java/com/github/k7t3/tcv/app/core/Resources.java +++ b/src/main/java/com/github/k7t3/tcv/app/core/Resources.java @@ -28,11 +28,13 @@ public class Resources { private static final ResourceBundle RESOURCE_BUNDLE; - private static final TreeMap ICONS; - static { RESOURCE_BUNDLE = ResourceBundle.getBundle("com.github.k7t3.tcv.tcv"); - ICONS = new TreeMap<>( + } + + /** 文字列の参照では画像・描画基盤を初期化しない。 */ + private static class IconsHolder { + private static final TreeMap ICONS = new TreeMap<>( Map.of( 16, smallerIcon(16), 32, smallerIcon(32), @@ -56,7 +58,7 @@ private static Image loadIcon(double size) { } public static List getIcons() { - return ICONS.entrySet().stream() + return IconsHolder.ICONS.entrySet().stream() .sorted(Comparator.comparingInt(Map.Entry::getKey)) .map(Map.Entry::getValue) .toList(); diff --git a/src/main/java/com/github/k7t3/tcv/app/emoji/ChatEmojiStore.java b/src/main/java/com/github/k7t3/tcv/app/emoji/ChatEmojiStore.java index bb8eb9f..ab3b25b 100644 --- a/src/main/java/com/github/k7t3/tcv/app/emoji/ChatEmojiStore.java +++ b/src/main/java/com/github/k7t3/tcv/app/emoji/ChatEmojiStore.java @@ -17,6 +17,7 @@ package com.github.k7t3.tcv.app.emoji; import com.github.k7t3.tcv.app.image.LazyImage; +import com.github.k7t3.tcv.app.image.ImageLoader; import com.github.k7t3.tcv.app.service.CachedImageStore; import org.jetbrains.annotations.Nullable; @@ -25,16 +26,19 @@ public class ChatEmojiStore extends CachedImageStore { private final Emoji emoji; + private final ImageLoader images; - public ChatEmojiStore(Emoji emoji) { + /** アーカイブと画像サービスは借用し、このストアのキャッシュだけを所有する。 */ + public ChatEmojiStore(Emoji emoji, ImageLoader images) { super(64, Duration.ofHours(1)); - this.emoji = emoji; + this.emoji = java.util.Objects.requireNonNull(emoji); + this.images = java.util.Objects.requireNonNull(images); } @Override protected @Nullable LazyImage loadImage(String key) { // 対応する絵文字がないときはnull if (!emoji.contains(key)) return null; - return new LazyImage(() -> emoji.openImageStream(key), 32, 32); + return images.decode(() -> emoji.openImageStream(key), 32, 32); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/emoji/Emoji.java b/src/main/java/com/github/k7t3/tcv/app/emoji/Emoji.java index 09fbce3..cb12902 100644 --- a/src/main/java/com/github/k7t3/tcv/app/emoji/Emoji.java +++ b/src/main/java/com/github/k7t3/tcv/app/emoji/Emoji.java @@ -16,75 +16,172 @@ package com.github.k7t3.tcv.app.emoji; -import javafx.beans.property.ObjectProperty; -import javafx.beans.property.ReadOnlyBooleanProperty; -import javafx.beans.property.ReadOnlyBooleanWrapper; -import javafx.beans.property.SimpleObjectProperty; +import com.github.k7t3.tcv.lifecycle.CloseActions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileTime; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.Collections; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** - * 絵文字イメージをロードするためのクラス。 + * 絵文字アーカイブを所有し、画像の入力 stream を提供する。 + * 検証・配置と終了は直列化する。呼び出し側は返された stream を閉じる。 */ public class Emoji implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(Emoji.class); private static final String FILE_NAME = "openmoji-72x72-color.zip"; - private final Map hexAndName = new HashMap<>(); - private final ObjectProperty archivePath = new SimpleObjectProperty<>(); - private final ReadOnlyBooleanWrapper ready = new ReadOnlyBooleanWrapper(false); - private final AtomicReference properties = new AtomicReference<>(); - private final AtomicReference zipFile = new AtomicReference<>(); + private final Object archiveLock = new Object(); + @FunctionalInterface interface ArchiveInput { InputStream open(Path path) throws IOException; } + @FunctionalInterface interface ArchiveOpener { ZipFile open(Path path) throws IOException; } + @FunctionalInterface interface ArchiveResource { InputStream open() throws IOException; } + @FunctionalInterface interface ArchiveMetadata { BasicFileAttributes read(Path path) throws IOException; } + + private final Path archivePath; + private final ArchiveInput input; + private final ArchiveOpener opener; + private final ArchiveResource resource; + private final ArchiveMetadata metadata; + private EmojiProperties properties; + private OpenArchive archive; + + private record OpenArchive(ZipFile zip, Map entries, FileVersion version, Path copy) {} + + private record FileVersion(Object key, long size, FileTime modified, FileTime created) { + static FileVersion read(BasicFileAttributes attributes) { + return new FileVersion(attributes.fileKey(), attributes.size(), + attributes.lastModifiedTime(), attributes.creationTime()); + } + + } + + /** 識別子がない保存先では、ハッシュを検証した同じbytesをZIPの所有期間中保持する。 */ + private static final class ArchiveCopy implements AutoCloseable { + private final Path path; + private boolean adopted; + + private ArchiveCopy(FileVersion version) throws IOException { + path = version.key() == null ? Files.createTempFile("tcv-emoji-verified-", ".zip") : null; + } + + private String hash(InputStream input) throws IOException { + if (path == null) return computeHash(input); + try (var output = Files.newOutputStream(path)) { return computeHash(input, output); } + } + + private Path adopt() { adopted = true; return path; } + + @Override public void close() throws IOException { + if (!adopted && path != null) Files.deleteIfExists(path); + } + } private boolean closed = false; public Emoji(Path extractDir) { - setArchivePath(extractDir.resolve(FILE_NAME)); + this(extractDir, Files::newInputStream, path -> new ZipFile(path.toFile())); + } + + Emoji(Path extractDir, ArchiveInput input, ArchiveOpener opener) { + this(extractDir, input, opener, Emoji::bundledArchive); + } + + Emoji(Path extractDir, ArchiveInput input, ArchiveOpener opener, ArchiveResource resource) { + this(extractDir, input, opener, resource, path -> Files.readAttributes(path, BasicFileAttributes.class)); + } + + Emoji(Path extractDir, ArchiveInput input, ArchiveOpener opener, ArchiveResource resource, ArchiveMetadata metadata) { + this.archivePath = Objects.requireNonNull(extractDir).resolve(FILE_NAME); + this.input = Objects.requireNonNull(input); + this.opener = Objects.requireNonNull(opener); + this.resource = Objects.requireNonNull(resource); + this.metadata = Objects.requireNonNull(metadata); + } + + private FileVersion readVersion(Path path) throws IOException { return FileVersion.read(metadata.read(path)); } + + private static InputStream bundledArchive() throws IOException { + var input = Emoji.class.getResourceAsStream(FILE_NAME); + if (input == null) throw new IOException("missing bundled emoji archive"); + return input; } public boolean contains(String hex) { - checkReady(); - return hexAndName.containsKey(hex); + synchronized (archiveLock) { + checkReady(); + return archive.entries().containsKey(hex); + } } /** * キーにマッチする絵文字のイメージをロードする{@link InputStream}を返す。 * @param hex 絵文字のHexキー - * @return 絵文字のイメージInputStream - * @throws IOException キーにマッチするイメージがないときにスローされる + * @return 呼び出し側が閉じる入力 stream。アーカイブの置換・終了でも無効になる + * @throws IllegalArgumentException キーに対応する画像がない場合 + * @throws IllegalStateException 検証前または終了済みの場合 + * @throws IOException 画像の入力 stream を開けない場合 */ public InputStream openImageStream(String hex) throws IOException { - checkReady(); - var key = hexAndName.get(hex); - if (key == null) throw new IllegalArgumentException(); + synchronized (archiveLock) { + checkReady(); + var key = archive.entries().get(hex); + if (key == null) throw new IllegalArgumentException(); - var zip = zipFile.get(); - var entry = zip.getEntry(key); - return zip.getInputStream(entry); + var zip = archive.zip(); + var entry = zip.getEntry(key); + return zip.getInputStream(entry); + } } /** - * アーカイブを抽出する + * 配置先の親ディレクトリを作成し、同梱アーカイブを抽出する。 + * @throws IllegalStateException 終了している場合 + * @throws IOException アーカイブの配置に失敗した場合 */ public void extractArchive() throws IOException { - final var archivePath = getArchivePath(); - try (var input = Objects.requireNonNull(getClass().getResourceAsStream(FILE_NAME))) { - Files.copy(input, archivePath, StandardCopyOption.REPLACE_EXISTING); + synchronized (archiveLock) { + checkOpen(); + var target = archivePath.toAbsolutePath(); + Files.createDirectories(target.getParent()); + var temporary = Files.createTempFile(target.getParent(), ".tcv-emoji-", ".tmp"); + Throwable primary = null; + try { + try (var input = resource.open()) { + Files.copy(input, temporary, StandardCopyOption.REPLACE_EXISTING); + } + try (var input = Files.newInputStream(temporary)) { + if (!properties().getHash().equals(computeHash(input))) + throw new IOException("invalid bundled emoji archive"); + } + releaseArchive(); + Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (IOException | RuntimeException | Error failure) { + primary = failure; + throw failure; + } finally { + try { Files.deleteIfExists(temporary); } + catch (IOException cleanup) { + if (primary == null) throw cleanup; + if (primary != cleanup) primary.addSuppressed(cleanup); + } + } } } @@ -92,96 +189,143 @@ public void extractArchive() throws IOException { * 絵文字アーカイブファイルが所定のパスに抽出されているかを判定する。 * * @return 抽出されているファイルが適切なものである場合はtrueを返す。 + * @throws IllegalStateException 終了している場合 + * @throws IOException アーカイブを開けない場合 */ public boolean validateArchive() throws IOException { - var properties = this.properties.get(); - if (properties == null) { - properties = new EmojiProperties(); - properties.loadEmojiProperties(); - LOGGER.info("emoji properties {}", properties); - this.properties.set(properties); - } + synchronized (archiveLock) { + checkOpen(); + try { + var properties = properties(); - var path = getArchivePath(); - if (Files.exists(path)) { - // 存在するファイルのハッシュ値を求める - try (var input = Files.newInputStream(path)) { - var hash = computeHash(input); - if (properties.getHash().equals(hash)) { - final var archivePath = getArchivePath(); - - // コピーしたアーカイブをロード - var zip = new ZipFile(archivePath.toFile()); - zip.stream().map(ZipEntry::getName).forEach(name -> { - var hex = name.toLowerCase(); - var index = hex.indexOf("."); - if (0 < index) { - hex = hex.substring(0, index); + var path = getArchivePath(); + if (Files.exists(path)) { + var version = readVersion(path); + try (var copy = new ArchiveCopy(version)) { + final String hash; + try (var input = this.input.open(path)) { + hash = copy.hash(input); } - hexAndName.put(hex, name); - }); - zipFile.set(zip); - - ready.set(true); - return true; + checkOpen(); + if (properties.getHash().equals(hash)) { + if (!version.equals(readVersion(path))) + throw new IOException("emoji archive changed during validation"); + // 識別子がない場合も、所有コピーは検証済み内容から変更されない。 + if (archive != null && version.equals(archive.version())) return true; + releaseArchive(); + checkOpen(); + var zip = opener.open(copy.path == null ? path : copy.path); + try { + checkOpen(); + if (!version.equals(readVersion(path))) + throw new IOException("emoji archive changed while opening"); + var entries = new HashMap(); + zip.stream().map(ZipEntry::getName).forEach(name -> { + var hex = name.toLowerCase(Locale.ROOT); + var index = hex.indexOf("."); + if (0 < index) { + hex = hex.substring(0, index); + } + entries.put(hex, name); + }); + checkOpen(); + archive = new OpenArchive(zip, Collections.unmodifiableMap(entries), version, copy.adopt()); + return true; + } catch (IOException | RuntimeException | Error failure) { + try { closeZip(zip); } + catch (RuntimeException | Error cleanup) { + if (cleanup != failure) failure.addSuppressed(cleanup); + } + throw failure; + } + } + } + } + releaseArchive(); + return false; + } catch (IOException | RuntimeException | Error failure) { + try { releaseArchive(); } + catch (RuntimeException | Error cleanup) { + if (cleanup != failure) failure.addSuppressed(cleanup); } + throw failure; } } - return false; + } + + private EmojiProperties properties() { + if (properties == null) { + var loaded = new EmojiProperties(); + loaded.loadEmojiProperties(); + LOGGER.info("emoji properties {}", loaded); + properties = loaded; + } + return properties; } private void checkReady() { - if (!isReady()) throw new IllegalStateException("not ready"); + checkOpen(); + if (archive == null) throw new IllegalStateException("not ready"); + } + + private void checkOpen() { if (closed) throw new IllegalStateException("closed"); } + /** 進行中の検証・配置を待ち、アーカイブを一度だけ閉じる。返却済みの stream も無効になる。 */ @Override public void close() { - if (closed) return; - closed = true; - if (zipFile.get() != null) { - try { - zipFile.get().close(); - } catch (IOException e) { - LOGGER.error("error occurred on closing", e); - } + synchronized (archiveLock) { + if (closed) return; + closed = true; + releaseArchive(); } } - public static String computeHash(InputStream input) { - MessageDigest digest; - try { - digest = MessageDigest.getInstance("sha-256"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - - try { - var bytes = new byte[1024]; - int length; - while ((length = input.read(bytes)) != -1) { - digest.update(bytes, 0, length); + private void releaseArchive() { + var previous = archive; + archive = null; + if (previous != null) CloseActions.runAll(() -> closeZip(previous.zip()), () -> { + if (previous.copy() != null) { + try { Files.deleteIfExists(previous.copy()); } + catch (IOException failure) { throw new UncheckedIOException("failed to delete owned emoji archive " + previous.copy(), failure); } } + }); + } - var hashBytes = digest.digest(); - var builder = new StringBuilder(); - // 1文字目の0が消えてしまうのでInteger.toHexStringじゃなくformatで - for (var b : hashBytes) - builder.append("%02x".formatted(Byte.toUnsignedInt(b))); - //builder.append(Integer.toHexString(Byte.toUnsignedInt(b))); - return builder.toString(); + private static void closeZip(ZipFile zip) { + try { zip.close(); } + catch (IOException failure) { throw new UncheckedIOException("failed to close emoji archive", failure); } + } - } catch (IOException e) { - throw new RuntimeException(e); + private static String computeHash(InputStream input) throws IOException { + return computeHash(input, OutputStream.nullOutputStream()); + } + + private static String computeHash(InputStream input, OutputStream output) throws IOException { + final MessageDigest digest; + try { digest = MessageDigest.getInstance("SHA-256"); } + catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException("SHA-256 unavailable", impossible); } + var bytes = new byte[8192]; + int length; + while ((length = input.read(bytes)) != -1) { + digest.update(bytes, 0, length); + output.write(bytes, 0, length); } + return java.util.HexFormat.of().formatHex(digest.digest()); } - public EmojiProperties getProperties() { return properties.get(); } + public EmojiProperties getProperties() { + synchronized (archiveLock) { + return properties; + } + } - public ObjectProperty archivePathProperty() { return archivePath; } - public Path getArchivePath() { return archivePath.get(); } - public void setArchivePath(Path path) { archivePath.set(Objects.requireNonNull(path)); } + public final Path getArchivePath() { return archivePath; } - public ReadOnlyBooleanProperty readyProperty() { return ready.getReadOnlyProperty(); } - public boolean isReady() { return ready.get(); } + public boolean isReady() { + synchronized (archiveLock) { + return archive != null; + } + } } diff --git a/src/main/java/com/github/k7t3/tcv/app/event/ChatOpeningEvent.java b/src/main/java/com/github/k7t3/tcv/app/event/ChatOpeningEvent.java index 43286de..9abb174 100644 --- a/src/main/java/com/github/k7t3/tcv/app/event/ChatOpeningEvent.java +++ b/src/main/java/com/github/k7t3/tcv/app/event/ChatOpeningEvent.java @@ -19,7 +19,6 @@ import com.github.k7t3.tcv.app.channel.MultipleChatOpenType; import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel; -import java.util.Collections; import java.util.List; /** @@ -40,7 +39,7 @@ public ChatOpeningEvent( List channels ) { this.chatOpenType = chatOpenType; - this.channels = Collections.unmodifiableList(channels); + this.channels = List.copyOf(channels); } /** diff --git a/src/main/java/com/github/k7t3/tcv/app/event/SessionInvalidatedEvent.java b/src/main/java/com/github/k7t3/tcv/app/event/SessionInvalidatedEvent.java new file mode 100644 index 0000000..89cfc01 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/event/SessionInvalidatedEvent.java @@ -0,0 +1,6 @@ +package com.github.k7t3.tcv.app.event; + +import com.github.k7t3.tcv.app.core.ClientSessions; + +/** 同じアプリが所有する失効済みセッションの画面を、FX スレッドで切り離す。 */ +public record SessionInvalidatedEvent(ClientSessions source) implements AppEvent {} diff --git a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroup.java b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroup.java index 170821f..1e4cbd6 100644 --- a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroup.java +++ b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroup.java @@ -51,9 +51,9 @@ public UUID getId() { return id; } - public void generateId() { - if (id != null) throw new IllegalStateException(); - id = UUID.randomUUID(); + void assignPersistedId(UUID value) { + if (id != null && !id.equals(value)) throw new IllegalStateException("group id cannot change"); + id = java.util.Objects.requireNonNull(value); } // ******************** PROPERTIES ******************** diff --git a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupListViewModel.java b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupListViewModel.java index 8fc5813..3b7364e 100644 --- a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupListViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupListViewModel.java @@ -18,13 +18,13 @@ import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel; import com.github.k7t3.tcv.app.model.AbstractViewModel; -import com.github.k7t3.tcv.app.core.Resources; import com.github.k7t3.tcv.app.service.FXTask; -import com.github.k7t3.tcv.domain.event.EventSubscribers; import javafx.beans.binding.Bindings; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.ObservableList; +import javafx.collections.FXCollections; +import javafx.beans.Observable; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; @@ -33,13 +33,18 @@ public class ChannelGroupListViewModel extends AbstractViewModel { private final ChannelGroupRepository repository; + private final ObservableList source; + private final ObservableList items = FXCollections.observableArrayList( + group -> new Observable[] { group.pinnedProperty(), group.nameProperty(), group.updatedAtProperty() }); private final SortedList sorted; private final FilteredList filtered; private final StringProperty filter = new SimpleStringProperty(); public ChannelGroupListViewModel(ChannelGroupRepository repository) { this.repository = repository; - sorted = new SortedList<>(repository.getAll()); + source = repository.getAll(); + Bindings.bindContent(items, source); + sorted = new SortedList<>(items); filtered = new FilteredList<>(sorted); filtered.predicateProperty().bind(Bindings.createObjectBinding(() -> this::test, filter)); } @@ -73,7 +78,9 @@ private boolean test(TwitchChannelViewModel channel, String filter) { } public void setComparator(Comparator comparator) { - sorted.setComparator(ChannelGroupPinnedComparator.INSTANCE.thenComparing(comparator)); + checkOpen(); + sorted.setComparator(comparator == null ? ChannelGroupPinnedComparator.INSTANCE + : ChannelGroupPinnedComparator.INSTANCE.thenComparing(comparator)); } public ObservableList getChannelGroups() { @@ -81,16 +88,19 @@ public ObservableList getChannelGroups() { } public FXTask create(String name) { + checkOpen(); var group = new ChannelGroup(); group.setName(name); return repository.saveAsync(group); } public FXTask update(ChannelGroup group) { + checkOpen(); return repository.saveAsync(group); } public FXTask delete(ChannelGroup group) { + checkOpen(); return repository.removeAsync(group); } @@ -98,54 +108,13 @@ public FXTask delete(ChannelGroup group) { public String getFilter() { return filter.get(); } public void setFilter(String filter) { this.filter.set(filter); } - @Override - public void subscribeEvents(EventSubscribers eventSubscribers) { - // no-op - } - - @Override - public void onLogout() { - // no-op - } - - @Override - public void close() { - // no-op - } - - public enum Comparators implements Comparator { - - UPDATED_AT("group.comparator.updated", Comparator.comparing(ChannelGroup::getUpdatedAt)), - - CREATED_AT("group.comparator.created", Comparator.comparing(ChannelGroup::getCreatedAt)), - - LIVE_COUNT("group.comparator.liver", Comparator.comparingLong(g -> g.getChannels() - .stream() - .filter(TwitchChannelViewModel::isLive) - .count() - )), + private void checkOpen() { if (isClosed()) throw new IllegalStateException("group editor is closed"); } - /** 状態の規定値として名前を使用しているので変更しないようにするか別の形で定義したい・・・。*/ - NAME("group.comparator.name", Comparator.comparing(ChannelGroup::getName)); - - private final String display; - - private final Comparator comparator; - - Comparators(String display, Comparator comparator) { - this.display = Resources.getString(display); - this.comparator = comparator; - } - - @Override - public String toString() { - return display; - } - - @Override - public int compare(ChannelGroup o1, ChannelGroup o2) { - return comparator.compare(o1, o2); - } + @Override protected void onClose() { + Bindings.unbindContent(items, source); + filtered.predicateProperty().unbind(); + filter.unbind(); + items.clear(); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupOrder.java b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupOrder.java new file mode 100644 index 0000000..f51085a --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupOrder.java @@ -0,0 +1,40 @@ +package com.github.k7t3.tcv.app.group; + +import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel; +import com.github.k7t3.tcv.app.core.Resources; +import java.util.Comparator; + +public enum ChannelGroupOrder implements Comparator { + + UPDATED_AT("group.comparator.updated", Comparator.comparing(ChannelGroup::getUpdatedAt)), + + CREATED_AT("group.comparator.created", Comparator.comparing(ChannelGroup::getCreatedAt)), + + LIVE_COUNT("group.comparator.liver", Comparator.comparingLong(g -> g.getChannels() + .stream() + .filter(TwitchChannelViewModel::isLive) + .count() + )), + + /** 名前は既存の保存形式として維持する。 */ + NAME("group.comparator.name", Comparator.comparing(ChannelGroup::getName)); + + private final String display; + + private final Comparator comparator; + + ChannelGroupOrder(String display, Comparator comparator) { + this.display = display; + this.comparator = comparator; + } + + @Override + public String toString() { + return Resources.getString(display); + } + + @Override + public int compare(ChannelGroup o1, ChannelGroup o2) { + return comparator.compare(o1, o2); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupRepository.java b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupRepository.java index 1604948..b1601a2 100644 --- a/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupRepository.java +++ b/src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupRepository.java @@ -19,152 +19,288 @@ import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel; import com.github.k7t3.tcv.app.model.AbstractViewModel; import com.github.k7t3.tcv.app.service.FXTask; -import com.github.k7t3.tcv.domain.event.EventSubscribers; +import com.github.k7t3.tcv.app.service.SerialIoQueue; import com.github.k7t3.tcv.entity.ChannelGroupEntity; import com.github.k7t3.tcv.entity.SaveType; import com.github.k7t3.tcv.entity.service.ChannelGroupEntityService; +import javafx.application.Platform; import javafx.beans.Observable; import javafx.collections.FXCollections; import javafx.collections.ObservableList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.time.LocalDateTime; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.function.Consumer; import java.util.stream.Collectors; +/** グループの表示と、受付済みの不変な保存要求を所有する。 */ public class ChannelGroupRepository extends AbstractViewModel { - + private static final Logger LOGGER = LoggerFactory.getLogger(ChannelGroupRepository.class); private final ChannelGroupEntityService service; - + private final SerialIoQueue io; + private final Consumer> shutdownAwaiter; + private final Consumer reportFailure; + private final Map plans = new IdentityHashMap<>(); + private final Map committed = new IdentityHashMap<>(); + private final Map pendingRetention = new IdentityHashMap<>(); + private long scope; + private long sequence; private final ObservableList groups = FXCollections.observableArrayList( - g -> new Observable[] { g.pinnedProperty(), g.nameProperty(), g.updatedAtProperty() } - ); + group -> new Observable[] {group.pinnedProperty(), group.nameProperty(), group.updatedAtProperty()}); - public ChannelGroupRepository(ChannelGroupEntityService service) { - this.service = service; - } + private record State(ChannelGroupEntity entity, Set channels) {} - public List retrieveAllChannelIds() { - return service.retrieveAll().stream() - .flatMap(entity -> entity.channelIds().stream()) - .distinct() - .toList(); + private static final class Plan { + final ChannelGroup group; + final UUID id; + final LocalDateTime created; + boolean persisted; // I/O キュー内だけで更新する。 + State durable; // I/O キュー内だけで更新し、各結果へ捕捉する。 + Object latestRequest; + long publishedSequence; + boolean deleting; + Plan(ChannelGroup group, State baseline) { + this.group = group; + id = group.getId() == null ? UUID.randomUUID() : group.getId(); + created = group.getCreatedAt() == null ? LocalDateTime.now() : group.getCreatedAt(); + persisted = group.getId() != null; + durable = baseline; + } } - /** - * チャンネルグループで使用しているチャンネルを与える - *

- * {@link #retrieveAllChannelIds()}で事前に使用しているチャンネルを取得しておくこと - *

- */ - public void injectChannels(Map channels) { - var entities = service.retrieveAll(); + private record Outcome(Throwable failure, State durable) {} - var groups = new HashSet(); + public ChannelGroupRepository(ChannelGroupEntityService service, Executor executor, + Consumer> shutdownAwaiter, Consumer reportFailure) { + this.service = Objects.requireNonNull(service); + io = new SerialIoQueue(executor); + this.shutdownAwaiter = Objects.requireNonNull(shutdownAwaiter); + this.reportFailure = Objects.requireNonNull(reportFailure); + } + + /** 背景で、先に受付済みの書込を終えてから読む。UI モデルは参照しない。 */ + public List loadSnapshot() { + checkOpen(); + if (Platform.isFxApplicationThread()) throw new IllegalStateException("group loading must run outside FX"); + return io.call(() -> service.retrieveAll().stream().map(entity -> new ChannelGroupEntity( + entity.id(), entity.name(), entity.comment(), entity.pinned(), entity.createdAt(), + entity.updatedAt(), Set.copyOf(entity.channelIds()))).toList()); + } + /** FX 上で一括反映する。読取中に編集・作成・削除した同じ表示モデルを古い一覧で置換しない。 */ + public void applySnapshot(List entities, Map channels) { + checkOpen(); + var local = new HashMap(); + plans.values().forEach(plan -> local.put(plan.id, plan)); + var next = new ArrayList(); for (var entity : entities) { + if (local.containsKey(entity.id())) continue; var group = new ChannelGroup(entity.id()); group.setName(entity.name()); group.setComment(entity.comment()); group.setPinned(entity.pinned()); group.setCreatedAt(entity.createdAt()); group.setUpdatedAt(entity.updatedAt()); - var groupChannels = entity.channelIds().stream().map(channels::get).toList(); - group.getChannels().addAll(groupChannels); - groups.add(group); + group.getChannels().addAll(entity.channelIds().stream().map(channels::get) + .map(Objects::requireNonNull).toList()); + committed.put(group, capture(group, entity.id(), entity.createdAt(), entity.updatedAt())); + next.add(group); } - - this.groups.addAll(groups); + // 保存要求のモデルはこのセッション中の正本。未確定の新規作成は自身の成功時に公開する。 + groups.stream().filter(plans::containsKey).forEach(next::add); + groups.setAll(next); + committed.keySet().removeIf(group -> !groups.contains(group) && !plans.containsKey(group)); } - /** - * リポジトリにロードされているすべてのグループを取得する - * @return リポジトリにロードされているすべてのグループ - */ - public ObservableList getAll() { - return groups; - } + public ObservableList getAll() { return groups; } + + public FXTask saveAsync(ChannelGroup group) { return submit(group, false); } + public FXTask removeAsync(ChannelGroup group) { return submit(group, true); } - /** - * グループを保存する - * @param group 保存するグループ - */ - public FXTask saveAsync(ChannelGroup group) { + private FXTask submit(ChannelGroup group, boolean remove) { + checkOpen(); if (group == null) throw new IllegalArgumentException("group is null"); + if (!Platform.isFxApplicationThread()) throw new IllegalStateException("group edits must run on FX"); + var plan = plans.computeIfAbsent(group, value -> new Plan(value, committed.get(value))); + if (plan.deleting) throw new IllegalStateException("group deletion is pending or complete"); + var updated = group.getId() == null && plan.latestRequest == null ? plan.created : LocalDateTime.now(); + var snapshot = capture(group, plan.id, plan.created, updated); + if (!remove && snapshot.channels().stream().anyMatch(TwitchChannelViewModel::isRetiring)) { + throw new IllegalStateException("cannot save a group with a released channel"); + } + var request = new Object(); + var previousRequest = plan.latestRequest; + plan.latestRequest = request; + if (remove) plan.deleting = true; + var requestScope = scope; + long requestSequence = ++sequence; + var actual = new CompletableFuture(); + var failure = new java.util.concurrent.atomic.AtomicReference(); + var result = FXTask.observation(() -> { + rethrow(failure.get()); + return null; + }); + result.onFailure(error -> { + if (!isClosed() && scope == requestScope) reportFailure.accept(error); + }); + // 実行開始前から所有する。観測の取消・画面終了でも受付済み SQL は実行する。 + try { shutdownAwaiter.accept(actual.minimalCompletionStage()); } + catch (RuntimeException | Error rejected) { + if (plan.latestRequest == request) { + plan.latestRequest = previousRequest; + plan.deleting = false; + } + failure.set(rejected); + actual.completeExceptionally(rejected); + result.run(); + return result; + } + io.submit(() -> { + try { + if (remove) { + if (plan.persisted) service.remove(snapshot.entity()); + plan.persisted = false; + plan.durable = null; + } else { + service.save(plan.persisted ? SaveType.UPDATE : SaveType.INSERT, snapshot.entity()); + plan.persisted = true; + plan.durable = snapshot; + } + return new Outcome(null, plan.durable); + } catch (Throwable error) { + return new Outcome(error, plan.durable); + } + }).whenComplete((outcome, rejected) -> { + var completed = rejected == null ? outcome : new Outcome(unwrap(rejected), plan.durable); + var error = completed.failure(); + failure.set(error); + try { + if (error != null) LOGGER.error("Failed to persist channel group", error); + Platform.runLater(() -> { + if (!isClosed() && scope == requestScope && plans.get(group) == plan) { + finishPublication(plan, request, requestSequence, snapshot, remove, completed, requestScope); + } + }); + } finally { + try { result.run(); } + finally { + if (error == null) actual.complete(null); + else actual.completeExceptionally(error); + } + } + }); + // 監視と実行受付を先に確定する。プロパティ通知から終了処理へ再入しても自己待機しない。 + if (!remove) snapshot.channels().forEach(channel -> { + if (isCurrent(plan, requestScope)) { + pendingRetention.merge(channel, 1, Integer::sum); + reconcileRetention(channel); + } + }); + return result; + } + + private boolean isCurrent(Plan plan, long expectedScope) { + return !isClosed() && scope == expectedScope && plans.get(plan.group) == plan; + } - SaveType saveType; - var now = LocalDateTime.now(); - if (group.getId() == null) { - saveType = SaveType.INSERT; - group.generateId(); - group.setCreatedAt(now); - group.setUpdatedAt(now); - groups.add(group); - } else { - saveType = SaveType.UPDATE; - group.setUpdatedAt(now); + private void finishPublication(Plan plan, Object request, long order, State snapshot, boolean remove, + Outcome outcome, long requestScope) { + var affected = new HashSet<>(snapshot.channels()); + var previous = committed.get(plan.group); + if (previous != null) affected.addAll(previous.channels()); + if (outcome.durable() != null) affected.addAll(outcome.durable().channels()); + try { applyWrite(plan, request, order, snapshot, remove, outcome, requestScope); } + finally { + if (isCurrent(plan, requestScope)) { + if (!remove) snapshot.channels().forEach(channel -> + pendingRetention.computeIfPresent(channel, (key, count) -> count == 1 ? null : count - 1)); + affected.forEach(channel -> { + if (isCurrent(plan, requestScope)) reconcileRetention(channel); + }); + } } + } - var t = FXTask.task(() -> { - var userIds = List.copyOf(group.getChannels()).stream() - .map(c -> c.getBroadcaster().getUserId()) - .collect(Collectors.toSet()); - - var entity = new ChannelGroupEntity( - group.getId(), - group.getName(), - group.getComment(), - group.isPinned(), - group.getCreatedAt(), - group.getUpdatedAt(), - userIds - ); - service.save(saveType, entity); - }); - t.runAsync(); - return t; + private void reconcileRetention(TwitchChannelViewModel channel) { + boolean retained = channel.isFollowing() || pendingRetention.containsKey(channel) + || committed.values().stream().anyMatch(state -> state.channels().contains(channel)); + channel.setPersistent(retained); } - /** - * グループを削除する - * @param group 削除するグループ - */ - public FXTask removeAsync(ChannelGroup group) { - if (group == null) throw new IllegalArgumentException("group is null"); + private void applyWrite(Plan plan, Object request, long order, State snapshot, boolean remove, Outcome outcome, + long requestScope) { + if (order <= plan.publishedSequence) return; + plan.publishedSequence = order; + var group = plan.group; + var durable = outcome.durable(); + if (outcome.failure() != null) { + if (plan.latestRequest == request) { + plan.deleting = false; + if (durable != null) restoreUnchangedFields(group, snapshot, durable); + } + } else if (remove) { + groups.remove(group); + if (isCurrent(plan, requestScope)) committed.remove(group); + return; + } + if (!isCurrent(plan, requestScope)) return; + if (durable != null) { + group.assignPersistedId(durable.entity().id()); + group.setCreatedAt(durable.entity().createdAt()); + if (!isCurrent(plan, requestScope)) return; + group.setUpdatedAt(durable.entity().updatedAt()); + if (!isCurrent(plan, requestScope)) return; + committed.put(group, durable); + if (!plan.deleting && !groups.contains(group)) groups.add(group); + } + } - groups.remove(group); - - var t = FXTask.task(() -> { - var entity = new ChannelGroupEntity( - group.getId(), - group.getName(), - group.getComment(), - group.isPinned(), - group.getCreatedAt(), - group.getUpdatedAt(), - Set.of() - ); - service.remove(entity); - }); - t.runAsync(); - return t; + private static State capture(ChannelGroup group, UUID id, LocalDateTime created, LocalDateTime updated) { + var channels = Set.copyOf(group.getChannels()); + var ids = channels.stream().map(channel -> channel.getBroadcaster().getUserId()).collect(Collectors.toUnmodifiableSet()); + return new State(new ChannelGroupEntity(id, group.getName(), group.getComment(), group.isPinned(), + created, updated, ids), channels); } - @Override - public void subscribeEvents(EventSubscribers eventSubscribers) { - // no-op + private static void restoreUnchangedFields(ChannelGroup group, State requested, State baseline) { + var input = requested.entity(); + var stored = baseline.entity(); + if (Objects.equals(group.getName(), input.name())) group.setName(stored.name()); + if (Objects.equals(group.getComment(), input.comment())) group.setComment(stored.comment()); + if (group.isPinned() == input.pinned()) group.setPinned(stored.pinned()); + if (Set.copyOf(group.getChannels()).equals(requested.channels())) { + group.getChannels().clear(); + group.getChannels().addAll(baseline.channels()); + } } - @Override - public void onLogout() { - groups.clear(); + private static Throwable unwrap(Throwable failure) { + while (failure instanceof CompletionException && failure.getCause() != null) failure = failure.getCause(); + return failure; } - @Override - public void close() { - groups.clear(); + private static void rethrow(Throwable failure) throws Exception { + if (failure instanceof Exception exception) throw exception; + if (failure instanceof Error error) throw error; + if (failure != null) throw new IllegalStateException(failure); } + private void checkOpen() { if (isClosed()) throw new IllegalStateException("group repository is closed"); } + private void endSession() { + scope++; + var pending = List.copyOf(pendingRetention.keySet()); + pendingRetention.clear(); + groups.clear(); + plans.clear(); + pending.forEach(this::reconcileRetention); + committed.clear(); + } + @Override protected void onLoggedOut() { endSession(); } + @Override protected void onClose() { endSession(); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/help/AboutViewModel.java b/src/main/java/com/github/k7t3/tcv/app/help/AboutViewModel.java index 45f1f82..032c9d3 100644 --- a/src/main/java/com/github/k7t3/tcv/app/help/AboutViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/help/AboutViewModel.java @@ -17,8 +17,7 @@ package com.github.k7t3.tcv.app.help; import com.github.k7t3.tcv.app.model.AppViewModel; -import com.github.k7t3.tcv.app.core.DesktopUtils; -import com.github.k7t3.tcv.app.service.FXTask; +import com.github.k7t3.tcv.app.service.BrowserActions; import com.github.k7t3.tcv.domain.event.EventSubscribers; public class AboutViewModel implements AppViewModel { @@ -27,15 +26,11 @@ public class AboutViewModel implements AppViewModel { private static final String LICENSE_LINK = "https://github.com/k7t3/TwitchChatViewer/blob/main/docs/license.md"; private static final String LIBRARIES_LINK = "https://github.com/k7t3/TwitchChatViewer/blob/main/docs/external-libraries.md"; - public AboutViewModel() { - } + private final BrowserActions browsers; - private void browse(String link) { - FXTask.task(() -> { - DesktopUtils.browse(link); - return null; - }).runAsync(); - } + public AboutViewModel(BrowserActions browsers) { this.browsers = browsers; } + + private void browse(String link) { browsers.open(link); } public void browseGitHubPage() { browse(GITHUB_LINK); @@ -55,12 +50,8 @@ public void subscribeEvents(EventSubscribers eventSubscribers) { } @Override - public void onLogout() { - // no-op - } + public void onLogout() { browsers.cancelAll(); } @Override - public void close() { - // no-op - } + public void close() { browsers.close(); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/image/ImageDownloader.java b/src/main/java/com/github/k7t3/tcv/app/image/ImageDownloader.java new file mode 100644 index 0000000..cb61f4c --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/image/ImageDownloader.java @@ -0,0 +1,132 @@ +package com.github.k7t3.tcv.app.image; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpTimeoutException; +import java.nio.ByteBuffer; +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Flow; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** HTTP クライアントを所有し、画像のバイト列を取得する。画像のデコードと UI の反映は呼び出し側が行う。 */ +final class ImageDownloader implements AutoCloseable { + private final Object lifecycle = new Object(); + private HttpClient client; + private boolean closed; + private final Duration timeout; + private final int maxBytes; + + ImageDownloader(Duration timeout) { + this(timeout, 16 * 1024 * 1024); + } + + ImageDownloader(Duration timeout, int maxBytes) { + this.timeout = Objects.requireNonNull(timeout); + if (timeout.isZero() || timeout.isNegative()) throw new IllegalArgumentException("timeout must be positive"); + this.maxBytes = maxBytes; + } + + private HttpClient client() throws IOException { + synchronized (lifecycle) { + if (closed) throw new IOException("image downloader is closed"); + if (client == null) { + client = HttpClient.newBuilder().connectTimeout(timeout) + .followRedirects(HttpClient.Redirect.NORMAL).build(); + } + return client; + } + } + + byte[] download(URI uri) throws IOException, InterruptedException { + var request = HttpRequest.newBuilder(uri).timeout(timeout).GET().build(); + var response = client().sendAsync(request, ignored -> new LimitedBodySubscriber(maxBytes)); + try { + var received = response.get(timeout.toNanos(), TimeUnit.NANOSECONDS); + if (received.statusCode() < 200 || received.statusCode() >= 300) { + throw new IOException("image request failed: HTTP " + received.statusCode()); + } + return received.body(); + } catch (TimeoutException failure) { + var timeout = new HttpTimeoutException("image download timed out"); + timeout.initCause(failure); + throw timeout; + } catch (ExecutionException failure) { + if (failure.getCause() instanceof IOException ioFailure) throw ioFailure; + throw new IOException("image download failed", failure.getCause()); + } finally { + response.cancel(true); + } + } + + @Override + public void close() { + final HttpClient owned; + synchronized (lifecycle) { + if (closed) return; + closed = true; + owned = client; + } + if (owned != null) { + owned.shutdownNow(); + owned.close(); + } + } + + private static final class LimitedBodySubscriber implements HttpResponse.BodySubscriber { + private final int maxBytes; + private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + private final CompletableFuture result = new CompletableFuture<>(); + private Flow.Subscription subscription; + + private LimitedBodySubscriber(int maxBytes) { + this.maxBytes = maxBytes; + } + + @Override + public CompletionStage getBody() { + return result; + } + + @Override + public void onSubscribe(Flow.Subscription subscription) { + this.subscription = subscription; + subscription.request(1); + } + + @Override + public void onNext(List buffers) { + if (result.isDone()) return; + for (var buffer : buffers) { + if (buffer.remaining() > maxBytes - bytes.size()) { + subscription.cancel(); + result.completeExceptionally(new IOException("image exceeds " + maxBytes + " bytes")); + return; + } + var chunk = new byte[buffer.remaining()]; + buffer.get(chunk); + bytes.writeBytes(chunk); + } + subscription.request(1); + } + + @Override + public void onError(Throwable failure) { + result.completeExceptionally(failure); + } + + @Override + public void onComplete() { + if (!result.isDone()) result.complete(bytes.toByteArray()); + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/image/ImageLoader.java b/src/main/java/com/github/k7t3/tcv/app/image/ImageLoader.java new file mode 100644 index 0000000..bdd4b4e --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/image/ImageLoader.java @@ -0,0 +1,81 @@ +package com.github.k7t3.tcv.app.image; + +import com.github.k7t3.tcv.lifecycle.CloseActions; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; + +/** URLと入力streamの画像を読み込み、未完了画像を所有する。executorは所有者から借用する。 */ +public final class ImageLoader implements AutoCloseable { + private final ImageDownloader downloader = new ImageDownloader(Duration.ofSeconds(15)); + private final Executor executor; + private final Object lifecycle = new Object(); + private final Set pending = ConcurrentHashMap.newKeySet(); + private boolean closed; + + /** @param executor FX スレッドとは別のスレッドで画像を処理する executor */ + public ImageLoader(Executor executor) { + this.executor = Objects.requireNonNull(executor); + } + + /** + * HTTP 画像の読み込みを開始する。FX スレッドから呼び出す。 + * @param url 取得する HTTP または HTTPS の URL + * @param width 要求幅。0 の場合は元画像の幅 + * @param height 要求高さ。0 の場合は元画像の高さ + * @return 読み込みの結果を観測する画像 + * @throws IllegalStateException このサービスが終了している場合 + */ + public LazyImage load(String url, double width, double height) { + return decode(() -> new ByteArrayInputStream(downloader.download(URI.create(url))), width, height); + } + + /** + * 借用executorで入力streamを開き、画像をデコードする。FXスレッドから呼び出す。 + * @param input streamの提供元。取得したstreamは成功・失敗によらず閉じる + * @param width 要求幅。0の場合は元画像の幅 + * @param height 要求高さ。0の場合は元画像の高さ + * @return FX上での反映と失敗・取消を観測する画像 + * @throws IllegalStateException このサービスが終了している場合 + */ + public LazyImage decode(Callable input, double width, double height) { + synchronized (lifecycle) { + if (closed) throw new IllegalStateException("image loader is closed"); + var image = new LazyImage(Objects.requireNonNull(input), width, height, executor); + if (closed) { + image.close(); + return image; + } + pending.add(image); + image.completion().whenComplete((value, failure) -> pending.remove(image)); + return image; + } + } + + /** + * 未完了・UI反映待ちの画像を取り消し、HTTPクライアントを終了する。 + * 借用executorは終了しない。入力streamの実処理の終了待ちはexecutorの所有者が行う。 + */ + @Override + public void close() { + final List owned; + synchronized (lifecycle) { + if (closed) return; + closed = true; + owned = List.copyOf(pending); + pending.clear(); + } + CloseActions.runAll( + () -> CloseActions.runAll(owned.stream().map(image -> (Runnable) image::close).toArray(Runnable[]::new)), + downloader::close + ); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/image/LazyImage.java b/src/main/java/com/github/k7t3/tcv/app/image/LazyImage.java index 8e14445..e0df58e 100644 --- a/src/main/java/com/github/k7t3/tcv/app/image/LazyImage.java +++ b/src/main/java/com/github/k7t3/tcv/app/image/LazyImage.java @@ -22,59 +22,104 @@ import javafx.scene.image.Image; import java.io.InputStream; +import java.util.Objects; import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; /** - * 非同期で遅延読み込みするイメージ + * 非同期で遅延読み込みするイメージ。構築とプロパティの参照は FX スレッドで行う。 + * 所有者は不要になった時点で {@link #close()} を呼び、取消と遅延結果の破棄を要求する。 */ -public class LazyImage { +public class LazyImage implements AutoCloseable { private final ReadOnlyObjectWrapper value = new ReadOnlyObjectWrapper<>(); + private final AtomicBoolean closed = new AtomicBoolean(); + private final CompletableFuture completion = new CompletableFuture<>(); + private final LoadImageTask task; + + /** + * 指定したバックグラウンド executor で読み込む。executor は借用し、このインスタンスでは終了しない。 + * 提供元から受け取ったstreamは、デコードの成功・失敗によらず閉じる。 + * @param callable 閉じる責任を移譲する stream の提供元 + * @param requestWidth 要求幅。0 の場合は元画像の幅 + * @param requestHeight 要求高さ。0 の場合は元画像の高さ + * @param executor FX スレッドとは別のスレッドで実行する executor + */ + public LazyImage(Callable callable, double requestWidth, double requestHeight, Executor executor) { + this(new LoadImageTask(callable, requestWidth, requestHeight), executor); + } + + private LazyImage(LoadImageTask task, Executor executor) { + this.task = task; + Objects.requireNonNull(executor); + task.onDone(image -> { + if (!closed.get()) { + value.set(image); + completion.complete(image); + } + }); + task.setOnFailed(event -> { + if (!closed.get()) completion.completeExceptionally(task.getException()); + }); + task.setOnCancelled(event -> completion.cancel(false)); + try { + executor.execute(task); + } catch (RejectedExecutionException failure) { + completion.completeExceptionally(failure); + task.cancel(); + } + } - public LazyImage(String url, double requestWidth, double requestHeight) { - var task = new LoadImageTask(url, requestWidth, requestHeight); - task.onDone(value::set).runAsync(); + /** + * FX 上での反映後に成功し、取得の失敗または終了時の取消も通知する。 + * 返す stage から読込を変更・取消することはできない。 + * 取消の通知は close の呼び出しスレッドでも発生する。 + * @return 画像の反映を観測する stage + */ + public CompletionStage completion() { + return completion.minimalCompletionStage(); } - public LazyImage(Callable callable, double requestWidth, double requestHeight) { - var task = new LoadImageTask(callable, requestWidth, requestHeight); - task.onDone(value::set).runAsync(); + /** 任意のスレッドから読込の取消を要求する。繰り返し呼び出してもよく、表示済み画像は保持する。 */ + @Override + public void close() { + if (closed.compareAndSet(false, true)) { + task.cancel(); + completion.cancel(false); + } } public ReadOnlyObjectProperty valueProperty() { return value.getReadOnlyProperty(); } public Image getValue() { return value.get(); } - private static class LoadImageTask extends FXTask { + private static final class LoadImageTask extends FXTask { - private final String url; private final Callable inputCallable; private final double requestWidth; private final double requestHeight; - public LoadImageTask(String url, double requestWidth, double requestHeight) { - this(url, null, requestWidth, requestHeight); - } - - public LoadImageTask(Callable callable, double requestWidth, double requestHeight) { - this(null, callable, requestWidth, requestHeight); - } - - private LoadImageTask(String url, Callable inputCallable, double requestWidth, double requestHeight) { - this.url = url; - this.inputCallable = inputCallable; + private LoadImageTask(Callable callable, double requestWidth, double requestHeight) { + this.inputCallable = callable; this.requestWidth = requestWidth; this.requestHeight = requestHeight; } @Override protected Image call() throws Exception { - if (url != null) { - return new Image(url, requestWidth, requestHeight, true, true, false); - } else { - return new Image(inputCallable.call(), requestWidth, requestHeight, true, true); + try (var input = inputCallable.call()) { + return decoded(new Image(input, requestWidth, requestHeight, true, true)); } } + private static Image decoded(Image image) throws Exception { + if (image.isError()) throw image.getException(); + return image; + } + } } diff --git a/src/main/java/com/github/k7t3/tcv/app/main/MainViewModel.java b/src/main/java/com/github/k7t3/tcv/app/main/MainViewModel.java index b10adae..38bafcf 100644 --- a/src/main/java/com/github/k7t3/tcv/app/main/MainViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/main/MainViewModel.java @@ -17,24 +17,35 @@ package com.github.k7t3.tcv.app.main; import com.github.k7t3.tcv.app.channel.ChannelViewModelRepository; +import com.github.k7t3.tcv.app.auth.AuthenticatorViewModel; import com.github.k7t3.tcv.app.channel.TwitchChannelListViewModel; import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel; import com.github.k7t3.tcv.app.chat.ChatRoomContainerViewModel; import com.github.k7t3.tcv.app.clip.PostedClipRepository; import com.github.k7t3.tcv.app.model.AbstractViewModel; -import com.github.k7t3.tcv.app.core.AppHelper; +import com.github.k7t3.tcv.app.service.LiveStateNotificator; +import com.github.k7t3.tcv.lifecycle.CloseActions; import com.github.k7t3.tcv.app.event.ClientLoadedEvent; import com.github.k7t3.tcv.app.event.LoginEvent; import com.github.k7t3.tcv.app.event.LogoutEvent; -import com.github.k7t3.tcv.app.group.ChannelGroupRepository; -import com.github.k7t3.tcv.domain.channel.ChannelRepository; -import com.github.k7t3.tcv.domain.event.EventSubscribers; +import com.github.k7t3.tcv.app.event.SessionInvalidatedEvent; +import com.github.k7t3.tcv.domain.auth.CredentialStore; import javafx.beans.property.*; import javafx.collections.ListChangeListener; - import java.util.stream.Collectors; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletionException; +import java.util.function.Consumer; +import java.util.function.Function; +import com.github.k7t3.tcv.app.core.ClientSessions; +import com.github.k7t3.tcv.domain.event.EventSubscribers; +import javafx.application.Platform; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class MainViewModel extends AbstractViewModel { + private static final Logger LOGGER = LoggerFactory.getLogger(MainViewModel.class); private static final int NORM_STREAM_TITLE_LENGTH = 20; @@ -48,12 +59,39 @@ public class MainViewModel extends AbstractViewModel { private final ChatRoomContainerViewModel chatContainer; private final TwitchChannelListViewModel channelList; private final PostedClipRepository clipRepository; + private AuthenticatorViewModel activeAuthenticator; + private final ClientSessions sessions; + private final EventSubscribers source; + private final Function authenticationFactory; + private final Consumer failures; + private final LiveStateNotificator liveNotificator; + private long sessionGeneration; + private long authenticationRequest; + + /** 渡された子モデルを所有する。セッションと発行元は借用し、ここでは閉じない。 */ + public MainViewModel(ClientSessions sessions, EventSubscribers source, ChannelViewModelRepository channelRepository, + ChatRoomContainerViewModel chatContainer, TwitchChannelListViewModel channelList, + PostedClipRepository clipRepository, LiveStateNotificator liveNotificator, + Function authenticationFactory, Consumer failures) { + this.sessions = Objects.requireNonNull(sessions); + this.source = Objects.requireNonNull(source); + this.authenticationFactory = Objects.requireNonNull(authenticationFactory); + this.failures = Objects.requireNonNull(failures); + this.channelRepository = Objects.requireNonNull(channelRepository); + this.chatContainer = Objects.requireNonNull(chatContainer); + this.channelList = Objects.requireNonNull(channelList); + this.clipRepository = Objects.requireNonNull(clipRepository); + this.liveNotificator = Objects.requireNonNull(liveNotificator); + try { initialize(); } + catch (RuntimeException | Error failure) { closeAfterConstructionFailure(failure); throw failure; } + } - public MainViewModel(ChannelGroupRepository groupRepository) { - channelRepository = new ChannelViewModelRepository(groupRepository); - chatContainer = new ChatRoomContainerViewModel(); - channelList = new TwitchChannelListViewModel(); - clipRepository = new PostedClipRepository(); + private void initialize() { + setEventSubscribers(source); + for (var child : List.of(channelRepository, chatContainer, channelList, clipRepository, liveNotificator)) { + child.setEventSubscribers(source); + child.delegateLifecycleToOwner(); + } // 選択しているチャンネルのライブ配信タイトルを正規化してフッターに表示するためのリスナ channelList.getSelectedChannels().addListener(this::onChanged); @@ -62,6 +100,9 @@ public MainViewModel(ChannelGroupRepository groupRepository) { // ログイン時のイベント subscribe(LoginEvent.class, this::onLogin); + subscribe(SessionInvalidatedEvent.class, event -> { + if (event.source() == sessions) detachSessionViews(); + }); } // 選択しているチャンネルの配信タイトルをフッターに表示するためのリスナ @@ -90,38 +131,63 @@ private String normTitle(TwitchChannelViewModel channel) { return title.substring(0, NORM_STREAM_TITLE_LENGTH); } - @Override - public void subscribeEvents(EventSubscribers eventSubscribers) { - // no-op - } - private void onLogin(LoginEvent event) { - var helper = AppHelper.getInstance(); - var twitch = helper.getTwitch(); - var publishers = helper.getPublishers(); - - userName.bind(helper.userNameProperty()); - authorized.bind(helper.authorizedProperty()); - - channelRepository.setRepository(new ChannelRepository(twitch, publishers)); + var generation = ++sessionGeneration; + if (!isCurrentLogin(generation)) return; + userName.bind(sessions.userNameProperty()); + if (!isCurrentLogin(generation)) return; + authorized.bind(sessions.authorizedProperty()); + if (!isCurrentLogin(generation)) return; + + channelRepository.setRepository(sessions.getChannelRepository()); + if (!isCurrentLogin(generation)) return; + clipRepository.setSession(sessions.getTwitch()); + if (!isCurrentLogin(generation)) return; + for (var child : List.of(channelRepository, chatContainer, channelList, clipRepository, liveNotificator)) { + if (!isCurrentLogin(generation)) return; + child.subscribeEvents(source); + } channelRepository.loadAllAsync().onDone(() -> { + if (!isCurrentLogin(generation)) return; var channels = channelRepository.getChannels(); // リポジトリがロードしたチャンネルをリストにバインド channelList.bindChannels(channels); // チャンネルがロードできたら完了イベントを発行 - publish(new ClientLoadedEvent()); + if (isCurrentLogin(generation)) publish(new ClientLoadedEvent()); + }).onFailure(failure -> { + if (isCurrentLogin(generation)) reportFailure(failure); + else LOGGER.debug("discarded initial-load failure from an ended session", failure); }); // チャットに必要な部品をロード - chatContainer.loadAsync(); + if (isCurrentLogin(generation)) chatContainer.loadAsync(); } + private boolean isCurrentLogin(long generation) { return !isClosed() && sessionGeneration == generation; } + public void logout() { - var helper = AppHelper.getInstance(); - helper.logoutAsync(); + if (isClosed()) return; + sessions.logoutAsync(this::detachSessionViews).whenComplete((ignored, failure) -> { + if (failure == null) return; + var cause = failure instanceof CompletionException && failure.getCause() != null ? failure.getCause() : failure; + Platform.runLater(() -> { + if (isClosed()) LOGGER.error("logout failed during shutdown", cause); + else reportFailure(cause); + }); + }); + } + + private void detachSessionViews() { + sessionGeneration++; + CloseActions.runAll(() -> CloseActions.runAll( + () -> { if (activeAuthenticator != null) activeAuthenticator.onLogout(); }, + liveNotificator::onLogout, chatContainer::onLogout, channelList::onLogout, clipRepository::onLogout, channelRepository::onLogout), + () -> publish(new LogoutEvent())); + } - publish(new LogoutEvent()); + private void reportFailure(Throwable failure) { + failures.accept(failure); } public ChannelViewModelRepository getChannelRepository() { @@ -140,14 +206,59 @@ public PostedClipRepository getClipRepository() { return clipRepository; } + public LiveStateNotificator getLiveNotificator() { return liveNotificator; } + + private void closeAfterConstructionFailure(Throwable failure) { + try { close(); } + catch (RuntimeException | Error cleanupFailure) { + if (cleanupFailure != failure) failure.addSuppressed(cleanupFailure); + } + } + + /** 既存の認証画面を閉じ、Main と寿命を共有する認証モデルを作成する。FX スレッドから呼び出す。 */ + public AuthenticatorViewModel createAuthenticator(CredentialStore store) { + if (isClosed()) throw new IllegalStateException("main view model is closed"); + var request = ++authenticationRequest; + var previous = activeAuthenticator; + activeAuthenticator = null; + if (previous != null) previous.close(); + requireCurrentAuthentication(request, null); + var created = authenticationFactory.apply(store); + requireCurrentAuthentication(request, created); + activeAuthenticator = created; + return created; + } + + private void requireCurrentAuthentication(long request, AuthenticatorViewModel created) { + if (isClosed() || request != authenticationRequest) { + var failure = new IllegalStateException(isClosed() + ? "main view model is closed" : "authentication request was superseded"); + try { if (created != null) created.close(); } + catch (RuntimeException | Error cleanup) { if (cleanup != failure) failure.addSuppressed(cleanup); } + throw failure; + } + } + @Override - public void onLogout() { - // ログアウトはlogout()メソッド起点で行うためここでは何もしない + protected void onLoggedOut() { + // 終端済み Task の FX 成功・失敗イベントも、この時点で旧世代にする。 + sessionGeneration++; + authenticationRequest++; } @Override - public void close() { - // no-op + protected void onClose() { + sessionGeneration++; + authenticationRequest++; + var authenticator = activeAuthenticator; + activeAuthenticator = null; + CloseActions.runAll(() -> { + if (authenticator != null) authenticator.close(); + }, () -> { if (liveNotificator != null) liveNotificator.close(); }, + () -> { if (chatContainer != null) chatContainer.close(); }, + () -> { if (channelList != null) channelList.close(); }, + () -> { if (clipRepository != null) clipRepository.close(); }, + () -> { if (channelRepository != null) channelRepository.close(); }); } // ******************** PROPERTIES ******************** diff --git a/src/main/java/com/github/k7t3/tcv/app/model/AbstractViewModel.java b/src/main/java/com/github/k7t3/tcv/app/model/AbstractViewModel.java index b5b4fa3..52e7cfd 100644 --- a/src/main/java/com/github/k7t3/tcv/app/model/AbstractViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/model/AbstractViewModel.java @@ -16,11 +16,19 @@ package com.github.k7t3.tcv.app.model; -import com.github.k7t3.tcv.app.core.AppHelper; +import com.github.k7t3.tcv.app.event.AppEvent; import com.github.k7t3.tcv.app.event.LoginEvent; import com.github.k7t3.tcv.app.event.LogoutEvent; import com.github.k7t3.tcv.app.event.ShutdownEvent; import com.github.k7t3.tcv.domain.event.EventSubscribers; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import com.github.k7t3.tcv.reactive.FlowableSubscriber; + +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; /** * ログイン時、ログアウト時、アプリケーションの終了時に処理が自動でトリガーするベースクラス @@ -31,28 +39,241 @@ */ public abstract class AbstractViewModel implements AppViewModel { + private final AtomicBoolean closed = new AtomicBoolean(); + private final List registrations = new ArrayList<>(); + private SessionSubscriptions session; + private EventSubscribers eventSubscribers; + + private record Registration(Class type, + TypeSafeNotificationObserver observer, + TypeSafeNotificationObserver forwarding, + AtomicBoolean active, + SessionSubscriptions owner) { + } + protected final TypeSafeNotificationObserver onLogin = this::onLogin; protected final TypeSafeNotificationObserver onLogout = this::onLogout; protected final TypeSafeNotificationObserver onShutdown = this::onShutdown; public AbstractViewModel() { - subscribe(LoginEvent.class, onLogin); - subscribe(LogoutEvent.class, onLogout); - subscribe(ShutdownEvent.class, onShutdown); + try { + subscribe(LoginEvent.class, onLogin); + subscribe(LogoutEvent.class, onLogout); + subscribe(ShutdownEvent.class, onShutdown); + } catch (RuntimeException | Error failure) { + closed.set(true); + try { + // 子クラスは未構築なので、共通クラスが登録した通知だけを解放する。 + removeRegistrations(registration -> true); + } catch (RuntimeException | Error cleanup) { + if (cleanup != failure) failure.addSuppressed(cleanup); + } + throw failure; + } } private void onLogin(LoginEvent loginEvent) { - var helper = AppHelper.getInstance(); - var subscribers = helper.getSubscribers(); - subscribeEvents(subscribers); + if (eventSubscribers != null) subscribeEvents(eventSubscribers); + } + + /** + * ログイン通知で Flow を開始するモデルへ、所有者の発行元を渡す。 + * 未設定では Flow を開始しない。購読中の差し替えはログアウト後に行う。 + */ + public final void setEventSubscribers(EventSubscribers source) { + if (closed.get() || session != null) throw new IllegalStateException("cannot replace active event subscriptions"); + eventSubscribers = Objects.requireNonNull(source); + } + + /** 親が開始・ログアウト・終了を一度ずつ呼び出すモデルでは、既定の全体通知への接続を外す。 */ + public final void delegateLifecycleToOwner() { + if (closed.get() || session != null) throw new IllegalStateException("cannot delegate an active lifecycle"); + CloseActions.runAll(() -> unsubscribe(onLogin), () -> unsubscribe(onLogout), () -> unsubscribe(onShutdown)); + } + + @Override + public final void subscribeEvents(EventSubscribers eventSubscribers) { + final SessionSubscriptions opening; + synchronized (registrations) { + if (closed.get() || session != null) return; + opening = new SessionSubscriptions(); + session = opening; + } + try { + onSubscribeEvents(eventSubscribers, opening); + } catch (RuntimeException | Error failure) { + try { + opening.close(); + } catch (RuntimeException | Error cleanup) { + if (cleanup != failure) failure.addSuppressed(cleanup); + } + throw failure; + } + } + + /** + * Flow とセッション中の通知を、渡された購読範囲へ登録する。 + * 再入 logout / close 後も、この呼び出しには終了済みの同じ範囲が渡され続ける。 + */ + protected void onSubscribeEvents(EventSubscribers eventSubscribers, SessionSubscriptions subscriptions) { } private void onLogout(LogoutEvent logoutEvent) { onLogout(); } + @Override + public final void onLogout() { + final SessionSubscriptions previous; + synchronized (registrations) { + if (closed.get()) return; + previous = session; + session = null; + } + CloseActions.runAll(() -> { if (previous != null) previous.close(); }, this::onLoggedOut); + } + + /** セッションの購読を解除した後に実行するログアウト処理。 */ + protected void onLoggedOut() { + } + private void onShutdown(ShutdownEvent shutdownEvent) { close(); } + @Override + public final void subscribe(Class eventType, TypeSafeNotificationObserver observer) { + register(eventType, observer, null); + } + + private void register(Class eventType, TypeSafeNotificationObserver observer, + SessionSubscriptions owner) { + Objects.requireNonNull(eventType); + Objects.requireNonNull(observer); + final Registration registration; + final TypeSafeNotificationObserver forwarding; + synchronized (registrations) { + if (owner != null && (closed.get() || owner.retired)) return; + if (closed.get()) throw new IllegalStateException("view model is closed"); + var active = new AtomicBoolean(true); + forwarding = event -> { + if (!closed.get() && active.get()) observer.receivedNotification(event); + }; + registration = new Registration(eventType, observer, forwarding, active, owner); + registrations.add(registration); + } + try { + AppViewModel.super.subscribe(eventType, forwarding); + // 登録先からの再入終了より後に戻った登録も、その場で解除する。 + if (!registration.active().get()) AppViewModel.super.unsubscribe(forwarding); + } catch (RuntimeException | Error failure) { + synchronized (registrations) { + registration.active().set(false); + registrations.remove(registration); + } + try { + AppViewModel.super.unsubscribe(forwarding); + } catch (RuntimeException | Error cleanup) { + if (cleanup != failure) failure.addSuppressed(cleanup); + } + throw failure; + } + } + + @Override + public final void unsubscribe(TypeSafeNotificationObserver observer) { + removeRegistrations(registration -> registration.observer() == observer); + } + + @Override + public final void unsubscribe(Class eventType, TypeSafeNotificationObserver observer) { + removeRegistrations(registration -> registration.type() == eventType && registration.observer() == observer); + } + + private void removeRegistrations(Predicate predicate) { + final List removed; + synchronized (registrations) { + removed = registrations.stream().filter(predicate).toList(); + registrations.removeAll(removed); + // 通知中のスナップショットに残る登録も、外部の解除処理を始める前に無効にする。 + removed.forEach(registration -> registration.active().set(false)); + } + CloseActions.runAll(removed.stream().map(registration -> (Runnable) () -> + AppViewModel.super.unsubscribe(registration.forwarding())).toArray(Runnable[]::new)); + } + + /** 一回のログインが所有する Flow と通知。終了済みの範囲への遅い登録は採用しない。 */ + protected final class SessionSubscriptions implements AutoCloseable { + private final List> subscribers = new ArrayList<>(); + private boolean retired; + + private SessionSubscriptions() { + } + + /** + * Flow の開始前に所有を登録する。終了後に渡された購読は直ちに取消す。 + * @param subscriber このセッションだけが所有する購読 + * @return 渡された購読。終了済みの場合は取消済み + * @param 購読の型 + */ + public > S own(S subscriber) { + Objects.requireNonNull(subscriber); + synchronized (registrations) { + if (!closed.get() && !retired) { + subscribers.add(subscriber); + return subscriber; + } + } + subscriber.cancel(); + return subscriber; + } + + /** + * logout / close / 登録失敗で解除する通知を登録する。終了済みなら登録しない。 + * @param eventType 購読する通知の型 + * @param observer このセッションの通知処理 + * @param 通知の型 + */ + public void subscribe(Class eventType, TypeSafeNotificationObserver observer) { + register(eventType, observer, this); + } + + /** 通知を無効化してから Flow を取消す。失敗しても全件を試行し、後続の失敗を保持する。 */ + @Override + public void close() { + final List> snapshot; + synchronized (registrations) { + if (retired) return; + retired = true; + if (session == this) session = null; + snapshot = List.copyOf(subscribers); + subscribers.clear(); + } + CloseActions.runAll(() -> removeRegistrations(registration -> registration.owner() == this), + () -> CloseActions.runAll(snapshot.stream().map(subscriber -> (Runnable) subscriber::cancel).toArray(Runnable[]::new))); + } + } + + /** 通知・Flow 購読と画面資源の解放をすべて試行する。失敗を集約し、複数回呼んでも再実行しない。 */ + @Override + public final void close() { + final SessionSubscriptions previous; + synchronized (registrations) { + if (!closed.compareAndSet(false, true)) return; + previous = session; + session = null; + } + CloseActions.runAll(() -> removeRegistrations(registration -> true), + () -> { if (previous != null) previous.close(); }, this::onClose); + } + + /** 終了処理が開始されているかを返す。非同期結果の反映前にも確認できる。 */ + public final boolean isClosed() { + return closed.get(); + } + + /** 通知購読の解除後に実行する画面固有の終了処理。 */ + protected void onClose() { + } + } diff --git a/src/main/java/com/github/k7t3/tcv/app/model/EditableViewModelBase.java b/src/main/java/com/github/k7t3/tcv/app/model/EditableViewModelBase.java index 3872431..c30a187 100644 --- a/src/main/java/com/github/k7t3/tcv/app/model/EditableViewModelBase.java +++ b/src/main/java/com/github/k7t3/tcv/app/model/EditableViewModelBase.java @@ -93,60 +93,4 @@ protected void invalidated() { }; } - protected BooleanProperty booleanProperty() { - return new BooleanPropertyBase() { - @Override - public Object getBean() { - return null; - } - - @Override - public String getName() { - return ""; - } - - @Override - protected void invalidated() { - markDirty(); - } - }; - } - - protected ReadOnlyBooleanWrapper readOnlyBooleanWrapper() { - return new ReadOnlyBooleanWrapper() { - @Override - protected void invalidated() { - markDirty(); - } - }; - } - - protected ObjectProperty objectProperty() { - return new ObjectPropertyBase() { - @Override - public Object getBean() { - return null; - } - - @Override - public String getName() { - return ""; - } - - @Override - protected void invalidated() { - markDirty(); - } - }; - } - - protected ReadOnlyObjectWrapper readOnlyObjectWrapper() { - return new ReadOnlyObjectWrapper<>() { - @Override - protected void invalidated() { - markDirty(); - } - }; - } - } diff --git a/src/main/java/com/github/k7t3/tcv/app/prefs/ChatPreferencesViewModel.java b/src/main/java/com/github/k7t3/tcv/app/prefs/ChatPreferencesViewModel.java index e9163af..913d1a6 100644 --- a/src/main/java/com/github/k7t3/tcv/app/prefs/ChatPreferencesViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/prefs/ChatPreferencesViewModel.java @@ -17,17 +17,19 @@ package com.github.k7t3.tcv.app.prefs; import com.github.k7t3.tcv.app.service.FXTask; -import com.github.k7t3.tcv.prefs.AppPreferences; import com.github.k7t3.tcv.prefs.ChatPreferences; -import com.github.k7t3.tcv.view.chat.ChatFont; -import javafx.application.Platform; +import com.github.k7t3.tcv.prefs.FontSettings; import javafx.beans.property.*; +import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.text.Font; import java.util.List; -import java.util.stream.IntStream; +import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; +import java.util.function.Consumer; +import java.util.function.Supplier; public class ChatPreferencesViewModel implements PreferencesViewModelBase { @@ -47,57 +49,95 @@ public class ChatPreferencesViewModel implements PreferencesViewModelBase { private final ObservableList fontFamilies = FXCollections.observableArrayList(); - private final ChatPreferences prefs; + private final Executor executor; + private final Supplier> fontLookup; + private final Consumer failures; + private FXTask> fontLoad; + private Object fontRequest; + private final ReadOnlyBooleanWrapper fontsReady = new ReadOnlyBooleanWrapper(); + private boolean closed; - public ChatPreferencesViewModel() { - prefs = AppPreferences.getInstance().getChatPreferences(); + public ChatPreferencesViewModel(ChatPreferences prefs, Executor executor, Consumer failures) { + this(prefs, executor, Font::getFamilies, failures); + } + + ChatPreferencesViewModel(ChatPreferences prefs, Executor executor, Supplier> fontLookup, + Consumer failures) { + this.executor = executor; + this.fontLookup = fontLookup; + this.failures = failures; showUserName = new SimpleBooleanProperty(prefs.isShowUserName()); showBadges = new SimpleBooleanProperty(prefs.isShowBadges()); chatCacheSize = new SimpleIntegerProperty(prefs.getChatCacheSize()); var font = prefs.getFont(); - this.font = new SimpleObjectProperty<>(new FontFamily(font.getFamily())); - this.fontSize = new SimpleDoubleProperty(font.getSize()); + this.font = new SimpleObjectProperty<>(new FontFamily(font.family())); + this.fontSize = new SimpleDoubleProperty(font.size()); } - public FXTask loadFontsAsync() { - final var partSize = 100; - return FXTask.task(() -> { - var families = Font.getFamilies(); - var familySize = families.size(); - var div = families.size() / partSize; - var times = families.size() % partSize == 0 ? div : div + 1; - - IntStream.range(0, times) - .mapToObj(i -> families.subList(i * partSize, Math.min(familySize, (i + 1) * partSize))) - .map(chunk -> chunk.stream().map(FontFamily::new).toList()) - .forEach(ff -> Platform.runLater(() -> fontFamilies.addAll(ff))); - }).runAsync(); + public FXTask> loadFontsAsync() { + if (closed) throw new IllegalStateException("chat preferences editor is closed"); + if (fontLoad != null) return fontLoad; + var task = FXTask.task(() -> List.copyOf(fontLookup.get())); + fontLoad = task; + var request = new Object(); + fontRequest = request; + task.onDone(families -> { + if (closed || fontRequest != request) return; + fontFamilies.clear(); + publishFontBatch(families, 0, request); + }); + task.onFailure(failure -> { if (!closed && fontLoad == task) failures.accept(failure); }); + task.setFinally(() -> { + if (fontLoad == task && task.getState() != javafx.concurrent.Worker.State.SUCCEEDED) { + fontLoad = null; + fontRequest = null; + } + }); + try { executor.execute(task); } + catch (RejectedExecutionException closing) { task.cancel(); } + return task; } + private void publishFontBatch(List names, int start, Object request) { + if (closed || fontRequest != request) return; + var end = Math.min(names.size(), start + 100); + fontFamilies.addAll(names.subList(start, end).stream().map(FontFamily::new).toList()); + if (closed || fontRequest != request) return; + if (end < names.size()) Platform.runLater(() -> publishFontBatch(names, end, request)); + else fontsReady.set(true); + } + + public ReadOnlyBooleanProperty fontsReadyProperty() { return fontsReady.getReadOnlyProperty(); } + public ObservableList getFontFamilies() { return fontFamilies; } @Override public boolean canSync() { - return true; + return !closed && getFont() != null && getFont().getFamily() != null && !getFont().getFamily().isBlank() + && Double.isFinite(getFontSize()) && getFontSize() > 0 && getChatCacheSize() > 0; } @Override - public void sync() { - var font = getFont(); - var size = getFontSize(); - - var currentFont = prefs.getFont(); - if (!font.getFamily().equals(currentFont.getFamily()) - || size != currentFont.getSize()) { - prefs.setFont(new ChatFont(font.getFamily(), size)); - } - - prefs.setShowUserName(isShowUserName()); - prefs.setShowBadges(isShowBadges()); - prefs.setChatCacheSize(getChatCacheSize()); + public void prepare(SettingsDraft.Builder target) { + if (!canSync()) throw new IllegalStateException("chat preferences contain an invalid font or cache size"); + target.values(ChatPreferences.editorValues(new FontSettings(getFont().getFamily(), getFontSize()), + isShowUserName(), isShowBadges(), getChatCacheSize())); + } + + public boolean isClosed() { return closed; } + + @Override public void close() { + if (closed) return; + closed = true; + var pending = fontLoad; + fontLoad = null; + fontRequest = null; + if (pending != null) pending.cancel(); + fontFamilies.clear(); + fontsReady.set(false); } // ******************** PROPERTIES ******************** diff --git a/src/main/java/com/github/k7t3/tcv/app/prefs/GeneralPreferencesViewModel.java b/src/main/java/com/github/k7t3/tcv/app/prefs/GeneralPreferencesViewModel.java index 05a955a..b1f4915 100644 --- a/src/main/java/com/github/k7t3/tcv/app/prefs/GeneralPreferencesViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/prefs/GeneralPreferencesViewModel.java @@ -19,76 +19,66 @@ import com.github.k7t3.tcv.app.channel.MultipleChatOpenType; import com.github.k7t3.tcv.app.theme.Theme; import com.github.k7t3.tcv.app.theme.ThemeType; +import com.github.k7t3.tcv.app.theme.ThemeManager; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import javafx.beans.value.ChangeListener; import com.github.k7t3.tcv.prefs.GeneralPreferences; import javafx.beans.property.ObjectProperty; -import javafx.beans.property.ReadOnlyObjectProperty; -import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.beans.property.SimpleObjectProperty; -import javafx.beans.property.SimpleStringProperty; -import javafx.beans.property.StringProperty; -import java.util.Objects; public class GeneralPreferencesViewModel implements PreferencesViewModelBase { private final GeneralPreferences prefs; - - private final ReadOnlyObjectWrapper defaultTheme; - private final ReadOnlyObjectWrapper defaultThemeType; + private final ThemeManager preview; + private boolean closed; + private final ChangeListener themeChanged; + private final ChangeListener typeChanged; private final ObjectProperty theme; private final ObjectProperty themeType; private final ObjectProperty chatOpenType; - private final StringProperty userDataFilePath; - public GeneralPreferencesViewModel(GeneralPreferences prefs) { + this(prefs, null); + } + + public GeneralPreferencesViewModel(GeneralPreferences prefs, ThemeManager preview) { this.prefs = prefs; - defaultTheme = new ReadOnlyObjectWrapper<>(prefs.getTheme()); - defaultThemeType = new ReadOnlyObjectWrapper<>(prefs.getThemeType()); + this.preview = preview; + themeChanged = (observable, previous, next) -> { if (!closed && preview != null) preview.setTheme(next); }; + typeChanged = (observable, previous, next) -> { if (!closed && preview != null) preview.setThemeType(next); }; theme = new SimpleObjectProperty<>(prefs.getTheme()); themeType = new SimpleObjectProperty<>(prefs.getThemeType()); chatOpenType = new SimpleObjectProperty<>(prefs.getMultipleOpenType()); - userDataFilePath = new SimpleStringProperty(prefs.getUserDataFilePath()); + theme.addListener(themeChanged); + themeType.addListener(typeChanged); } @Override public boolean canSync() { - return true; + return !closed && getTheme() != null && getThemeType() != null && getChatOpenType() != null; + } + + @Override public void close() { + if (closed) return; + closed = true; + CloseActions.runAll(() -> { + theme.removeListener(themeChanged); + themeType.removeListener(typeChanged); + }, () -> { if (preview != null) preview.setTheme(prefs.getTheme()); }, + () -> { if (preview != null) preview.setThemeType(prefs.getThemeType()); }); } @Override - public void sync() { - var theme = getTheme(); - if (!Objects.equals(getDefaultTheme(), theme)) { - prefs.setTheme(theme); - } - - var themeType = getThemeType(); - if (!Objects.equals(getDefaultThemeType(), themeType)) { - prefs.setThemeType(themeType); - } - - var openType = getChatOpenType(); - if (openType != prefs.getMultipleOpenType()) { - prefs.setMultipleOpenType(openType); - } - - var userData = getUserDataFilePath(); - if (!Objects.equals(userData, prefs.getUserDataFilePath())) { - prefs.setUserDataFilePath(userData); - } + public void prepare(SettingsDraft.Builder target) { + if (!canSync()) throw new IllegalStateException("general preferences contain an incomplete choice"); + target.values(GeneralPreferences.editorValues(getTheme(), getThemeType(), getChatOpenType())); } // ******************** PROPERTIES ******************** - public ReadOnlyObjectProperty defaultThemeProperty() { return defaultTheme.getReadOnlyProperty(); } - public Theme getDefaultTheme() { return defaultTheme.get(); } - - public ReadOnlyObjectProperty defaultThemeTypeProperty() { return defaultThemeType.getReadOnlyProperty(); } - public ThemeType getDefaultThemeType() { return defaultThemeType.get(); } - public ObjectProperty themeProperty() { return theme; } public Theme getTheme() { return theme.get(); } public void setTheme(Theme theme) { this.theme.set(theme); } @@ -101,8 +91,4 @@ public void sync() { public MultipleChatOpenType getChatOpenType() { return chatOpenType.get(); } public void setChatOpenType(MultipleChatOpenType chatOpenType) { this.chatOpenType.set(chatOpenType); } - public StringProperty userDataFilePathProperty() { return userDataFilePath; } - public String getUserDataFilePath() { return userDataFilePath.get(); } - public void setUserDataFilePath(String userDataFilePath) { userDataFilePathProperty().set(userDataFilePath); } - } diff --git a/src/main/java/com/github/k7t3/tcv/app/prefs/KeyBindingPreferencesViewModel.java b/src/main/java/com/github/k7t3/tcv/app/prefs/KeyBindingPreferencesViewModel.java index e151941..b9eeaed 100644 --- a/src/main/java/com/github/k7t3/tcv/app/prefs/KeyBindingPreferencesViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/prefs/KeyBindingPreferencesViewModel.java @@ -23,21 +23,15 @@ import javafx.collections.ObservableList; import java.util.Objects; -import java.util.stream.Collectors; public class KeyBindingPreferencesViewModel implements PreferencesViewModelBase { - private final KeyBindingPreferences preferences; - - private final KeyBindingCombinations combinations; - private final ObservableList combinationList; - public KeyBindingPreferencesViewModel(KeyBindingPreferences preferences, KeyBindingCombinations combinations) { - this.preferences = preferences; - this.combinations = combinations; + public KeyBindingPreferencesViewModel(KeyBindingCombinations combinations) { this.combinationList = FXCollections.observableList(combinations.getAllBindings()); combinationList.forEach(binding -> binding.combinationProperty().addListener((ob, o, n) -> checkDuplicate())); + checkDuplicate(); } public ObservableList getCombinationList() { @@ -57,6 +51,7 @@ private void checkDuplicate() { for (var check : items) { for (var compare : items) { if (check == compare) continue; + if (check.getCombination() == null || compare.getCombination() == null) continue; if (Objects.equals(check.getCombination().getDisplayText(), compare.getCombination().getDisplayText())) { check.setDuplicated(true); @@ -68,26 +63,17 @@ private void checkDuplicate() { @Override public boolean canSync() { - return combinationList.stream().noneMatch(KeyBindingCombination::isDuplicated); + return combinationList.stream().allMatch(item -> item.getCombination() != null && !item.isDuplicated()); } @Override - public void sync() { - var current = combinations.getAllBindings(); - var currentValues = current.stream().collect( - Collectors.toMap( - KeyBindingCombination::getBinding, - KeyBindingCombination::getCombination - ) - ); + public void prepare(SettingsDraft.Builder target) { + if (!canSync()) throw new IllegalStateException("key bindings are incomplete or duplicated"); + var values = new java.util.HashMap>(); for (var entry : combinationList) { - var currentCombination = currentValues.get(entry.getBinding()); - // 変更されている場合更新 - if (!currentCombination.equals(entry.getCombination())) { - preferences.storeCombination(entry.getBinding(), entry.getCombination()); - combinations.updateCombination(entry.getBinding(), entry.getCombination()); - } + values.put(entry.getBinding().getId(), KeyBindingPreferences.editorValue(entry.getBinding(), entry.getCombination())); } + target.values(values); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/prefs/KeywordFilterViewModel.java b/src/main/java/com/github/k7t3/tcv/app/prefs/KeywordFilterViewModel.java index 2bd0c35..b539aab 100644 --- a/src/main/java/com/github/k7t3/tcv/app/prefs/KeywordFilterViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/prefs/KeywordFilterViewModel.java @@ -19,7 +19,7 @@ import com.github.k7t3.tcv.app.chat.filter.ChatFilters; import com.github.k7t3.tcv.app.chat.filter.KeywordFilterEntry; import com.github.k7t3.tcv.app.chat.filter.KeywordFilterType; -import com.github.k7t3.tcv.app.event.KeywordFilteringEvent; +import com.github.k7t3.tcv.entity.ChatKeywordFilterEntity; import javafx.beans.Observable; import javafx.beans.property.*; import javafx.collections.FXCollections; @@ -34,14 +34,11 @@ public class KeywordFilterViewModel implements PreferencesViewModelBase { private final ObservableList keywordEntries; private final FilteredList filtered; - private final ChatFilters chatFilters; - public KeywordFilterViewModel(ChatFilters filters) { - this.chatFilters = filters; keywordEntries = FXCollections.observableArrayList((w) -> new Observable[] { w.removedProperty() }); keywordEntries.addAll(filters.getKeywordEntries() .stream() - .map(e -> new Wrapper(e, chatFilters)) + .map(e -> new Wrapper(e)) .toList()); filtered = new FilteredList<>(keywordEntries); filtered.setPredicate(w -> !w.isRemoved()); @@ -52,7 +49,7 @@ public ObservableList getKeywordEntries() { } public void addEntry(KeywordFilterEntry entry) { - keywordEntries.add(new Wrapper(entry, chatFilters)); + keywordEntries.add(new Wrapper(entry)); } @Override @@ -61,18 +58,18 @@ public boolean canSync() { } @Override - public void sync() { - keywordEntries.stream().filter(Wrapper::isDirty).forEach(w -> { - w.save(); - var entry = w.entry; - var event = new KeywordFilteringEvent(entry); - publish(event); - }); + public void prepare(SettingsDraft.Builder target) { + if (!canSync()) throw new IllegalStateException("keyword filters contain invalid entries"); + for (var row : keywordEntries) { + if (row.isRemoved()) { target.deleteKeyword(row.entry.getFilterId()); continue; } + if (row.isDirty() || row.entry.getFilterId() < 1) { + target.keyword(new ChatKeywordFilterEntity(Math.max(0, row.entry.getFilterId()), row.getFilterType().getType(), row.getKeyword())); + } + } } public static class Wrapper { private final KeywordFilterEntry entry; - private final ChatFilters chatFilters; private final ObjectProperty filterType = new SimpleObjectProperty<>() { @Override protected void invalidated() { @@ -97,19 +94,19 @@ protected void invalidated() { private final ReadOnlyBooleanWrapper invalid = new ReadOnlyBooleanWrapper(true); private Pattern patternCache; - private Wrapper(KeywordFilterEntry entry, ChatFilters chatFilters) { + private Wrapper(KeywordFilterEntry entry) { this.entry = entry; - this.chatFilters = chatFilters; setKeyword(entry.getKeyword()); setFilterType(entry.getFilterType()); if (entry.getFilterType() == KeywordFilterType.REGEXP) { patternCache = entry.getPattern(); } + dirty.set(false); } private void update(String keyword, KeywordFilterType filterType) { - if (keyword == null || keyword.trim().isEmpty()) { + if (filterType == null || keyword == null || keyword.trim().isEmpty()) { invalid.set(true); return; } @@ -135,28 +132,6 @@ private void markDirty() { dirty.set(true); } - private void save() { - if (!isDirty()) return; - if (isRemoved()) { - chatFilters.deleteKeywordFilter(entry); - return; - } - - var keyword = getKeyword(); - if (getFilterType() == KeywordFilterType.REGEXP) { - if (!isInvalid()) { - entry.setKeyword(keyword); - entry.setPattern(patternCache); - entry.setFilterType(getFilterType()); - chatFilters.saveKeywordFilter(entry); - } - } else { - entry.setKeyword(keyword); - entry.setFilterType(getFilterType()); - chatFilters.saveKeywordFilter(entry); - } - } - public ReadOnlyBooleanProperty dirtyProperty() { return dirty.getReadOnlyProperty(); } public boolean isDirty() { return dirty.get(); } diff --git a/src/main/java/com/github/k7t3/tcv/app/prefs/PreferencesViewModel.java b/src/main/java/com/github/k7t3/tcv/app/prefs/PreferencesViewModel.java index b914bc5..331112d 100644 --- a/src/main/java/com/github/k7t3/tcv/app/prefs/PreferencesViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/prefs/PreferencesViewModel.java @@ -17,36 +17,139 @@ package com.github.k7t3.tcv.app.prefs; import com.github.k7t3.tcv.app.service.FXTask; -import com.github.k7t3.tcv.prefs.AppPreferences; +import com.github.k7t3.tcv.lifecycle.CloseActions; import de.saxsys.mvvmfx.ViewModel; +import java.util.concurrent.Executor; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.atomic.AtomicReference; +import java.util.Objects; +import java.util.function.Consumer; +import javafx.beans.property.ReadOnlyBooleanProperty; +import javafx.beans.property.ReadOnlyBooleanWrapper; +import org.slf4j.LoggerFactory; -import java.nio.file.Path; +public class PreferencesViewModel implements ViewModel, AutoCloseable { + private final SettingsSaveService saves; + private final Executor executor; + private final Consumer> shutdownAwaiter; + private final Consumer failureHandler; + private final ReadOnlyBooleanWrapper busy = new ReadOnlyBooleanWrapper(); + private final ReadOnlyBooleanWrapper savePending = new ReadOnlyBooleanWrapper(); + private final Object lifecycle = new Object(); + private Save activeSave; + private boolean closed; -public class PreferencesViewModel implements ViewModel { + private static final class Save { + final CompletableFuture settled = new CompletableFuture<>(); + Throwable failure; + boolean ioFinished; + boolean errorObserved; + } - private final AppPreferences prefs = AppPreferences.getInstance(); + /** + * 保存の実完了と未通知の失敗を、実行開始前に終了所有者へ登録する。executorは借用する。 + * UI所有者はこのモデルをcloseしてからアプリの終了を待つ。 + * 開いている画面へ引き渡した保存失敗は、終了時には再送出しない。 + */ + public PreferencesViewModel(SettingsSaveService saves, Executor executor, Consumer> shutdownAwaiter, + Consumer failureHandler) { + this.saves = Objects.requireNonNull(saves); + this.executor = Objects.requireNonNull(executor); + this.shutdownAwaiter = Objects.requireNonNull(shutdownAwaiter); + this.failureHandler = Objects.requireNonNull(failureHandler); + } - public void saveAsync() { - var task = FXTask.task(prefs::save); - task.runAsync(); + /** 受付済み保存とFX上の適用を継続する。返す観測Taskの取消や画面終了で保存を取り消さない。 */ + public FXTask saveAsync(SettingsDraft draft, Consumer apply) { + if (closed) throw new IllegalStateException("preferences editor is closed"); + if (isBusy()) throw new IllegalStateException("preferences save is already running"); + Objects.requireNonNull(draft); + Objects.requireNonNull(apply); + busy.set(true); + savePending.set(true); + var save = new Save(); + synchronized (lifecycle) { activeSave = save; } + var task = FXTask.task(() -> { + try { return saves.save(draft); } + catch (RuntimeException | Error failure) { + synchronized (lifecycle) { save.failure = failure; } + throw failure; + } finally { + synchronized (lifecycle) { + save.ioFinished = true; + settle(save); + } + } + }); + var applicationFailure = new AtomicReference(); + var observation = FXTask.observation(() -> { + var failure = applicationFailure.get(); + if (failure == null) failure = task.getException(); + if (failure instanceof Exception exception) throw exception; + if (failure instanceof Error error) throw error; + return task.getValue(); + }); + task.onDone(saved -> { + try { apply.accept(saved); } + catch (RuntimeException | Error failure) { + applicationFailure.set(failure); + reportFailure(failure); + } finally { finishSave(observation); } + }); + task.onFailure(failure -> { + synchronized (lifecycle) { + if (!closed) save.errorObserved = true; + settle(save); + } + try { reportFailure(failure); } + finally { finishSave(observation); } + }); + try { + shutdownAwaiter.accept(save.settled.minimalCompletionStage()); + executor.execute(task); + } + catch (RuntimeException | Error rejected) { + synchronized (lifecycle) { + save.ioFinished = true; + settle(save); + } + task.cancel(); + observation.cancel(false); + busy.set(false); + savePending.set(false); + throw rejected; + } + return observation; } - public FXTask importAsync(Path filePath) { - var task = FXTask.task(() -> prefs.importPreferences(filePath)); - task.runAsync(); - return task; + private void reportFailure(Throwable failure) { + if (closed) LoggerFactory.getLogger(PreferencesViewModel.class).error("preferences save failed after editor closed", failure); + else failureHandler.accept(failure); } - public FXTask exportAsync(Path filePath) { - var task = FXTask.task(() -> prefs.exportPreferences(filePath)); - task.runAsync(); - return task; + private void finishSave(FXTask observation) { + CloseActions.runAll(observation::run, () -> busy.set(false), () -> savePending.set(false)); } - public FXTask clearAsync() { - var task = FXTask.task(prefs::clear); - task.runAsync(); - return task; + /** lifecycle内で、画面へ通知済みの失敗と終了側が回収する未通知の失敗を分ける。 */ + private void settle(Save save) { + if (!save.ioFinished) return; + if (save.failure == null || save.errorObserved) save.settled.complete(null); + else if (closed) save.settled.completeExceptionally(save.failure); } + public ReadOnlyBooleanProperty busyProperty() { return busy.getReadOnlyProperty(); } + public boolean isBusy() { return busy.get(); } + public ReadOnlyBooleanProperty savePendingProperty() { return savePending.getReadOnlyProperty(); } + public boolean isSavePending() { return savePending.get(); } + + /** 受付済みの保存 I/O は借用 executor が所有して完了させる。 */ + @Override public void close() { + synchronized (lifecycle) { + closed = true; + if (activeSave != null) settle(activeSave); + } + busy.set(false); + } } diff --git a/src/main/java/com/github/k7t3/tcv/app/prefs/PreferencesViewModelBase.java b/src/main/java/com/github/k7t3/tcv/app/prefs/PreferencesViewModelBase.java index e9bbfad..9f598b7 100644 --- a/src/main/java/com/github/k7t3/tcv/app/prefs/PreferencesViewModelBase.java +++ b/src/main/java/com/github/k7t3/tcv/app/prefs/PreferencesViewModelBase.java @@ -21,7 +21,7 @@ public interface PreferencesViewModelBase extends AppViewModel { - void sync(); + void prepare(SettingsDraft.Builder target); boolean canSync(); diff --git a/src/main/java/com/github/k7t3/tcv/app/prefs/SettingsDraft.java b/src/main/java/com/github/k7t3/tcv/app/prefs/SettingsDraft.java new file mode 100644 index 0000000..039291b --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/prefs/SettingsDraft.java @@ -0,0 +1,33 @@ +package com.github.k7t3.tcv.app.prefs; + +import com.github.k7t3.tcv.entity.ChatKeywordFilterEntity; +import com.github.k7t3.tcv.entity.ChatUserFilterEntity; +import com.github.k7t3.tcv.entity.service.ChatFilterEntityStore; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** FX スレッドで確定する編集内容。保存中の画面の変更・破棄には影響されない。 */ +public record SettingsDraft(Map> values, ChatFilterEntityStore.Changes filters) { + public SettingsDraft { values = Map.copyOf(values); Objects.requireNonNull(filters); } + + public static final class Builder { + private final Map> values = new HashMap<>(); + private final ArrayList keywords = new ArrayList<>(); + private final HashSet deletedKeywords = new HashSet<>(); + private final ArrayList users = new ArrayList<>(); + private final HashSet deletedUsers = new HashSet<>(); + + public void values(Map> values) { this.values.putAll(values); } + public void keyword(ChatKeywordFilterEntity row) { keywords.add(row); } + public void deleteKeyword(int id) { if (id > 0) deletedKeywords.add(id); } + public void user(ChatUserFilterEntity row) { users.add(row); } + public void deleteUser(String id) { deletedUsers.add(id); } + public SettingsDraft build() { + return new SettingsDraft(values, new ChatFilterEntityStore.Changes(keywords, deletedKeywords, users, deletedUsers)); + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/prefs/SettingsSaveService.java b/src/main/java/com/github/k7t3/tcv/app/prefs/SettingsSaveService.java new file mode 100644 index 0000000..2e6f59d --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/prefs/SettingsSaveService.java @@ -0,0 +1,177 @@ +package com.github.k7t3.tcv.app.prefs; + +import com.github.k7t3.tcv.entity.service.ChatFilterEntityStore; +import com.github.k7t3.tcv.entity.service.SettingsJournal; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import com.github.k7t3.tcv.prefs.AppPreferences; +import com.github.k7t3.tcv.prefs.PreferenceProjection; +import com.github.k7t3.tcv.prefs.PreferenceValuesCodec; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import java.util.prefs.BackingStoreException; +import java.util.prefs.Preferences; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** 編集値とSQLを保存し、起動時・保存前に未完了の設定投影を復旧する。接続は借用する。 */ +public final class SettingsSaveService { + private static final Logger LOGGER = LoggerFactory.getLogger(SettingsSaveService.class); + public record SavedSettings(SettingsDraft draft, ChatFilterEntityStore.Snapshot filters) {} + + private final AppPreferences preferences; + private final ChatFilterEntityStore filters; + private final SettingsJournal journal; + + /** 同じDBに属するフィルターと設定を借用する。構築だけではI/Oしない。 */ + public SettingsSaveService(AppPreferences preferences, ChatFilterEntityStore filters) { + this.preferences = java.util.Objects.requireNonNull(preferences); + this.filters = java.util.Objects.requireNonNull(filters); + journal = filters.settingsJournal(); + } + + /** + * 編集キーの旧値と新値を記録してから保存し、成功後にUIへ渡す不変の結果を返す。 + * 確定済みの保存は、通常の後始末失敗があっても結果を返し、復旧情報とログを残す。 + * @param draft FX側で確定した編集内容。I/Oを行うため背景で渡すこと + * @return 保存した編集内容と確定したフィルター + */ + public SavedSettings save(SettingsDraft draft) { + AppPreferences.validateEditorValues(draft.values()); + var completed = new SavedSettings[1]; + try { + return exclusive(() -> saveLocked(draft, completed)); + } catch (RuntimeException failure) { + if (completed[0] == null) throw failure; + LOGGER.warn("Could not clean up committed settings recovery information", failure); + return completed[0]; + } + } + + /** 保存要求を発行せずに未完了の設定投影を復旧する。背景の起動処理から呼び出す。 */ + public void recover() { + exclusive(() -> { + var node = preferences.getPreferences(); + synchronized (node) { + sync(node); + recoverLocked(node); + } + return null; + }); + } + + private T exclusive(Supplier operation) { + return preferences.exclusive(() -> journal.exclusive(operation)); + } + + private SavedSettings saveLocked(SettingsDraft draft, SavedSettings[] completed) { + var node = preferences.getPreferences(); + synchronized (node) { + sync(node); + recoverLocked(node); + var previous = new HashMap>(); + draft.values().keySet().forEach(key -> previous.put(key, Optional.ofNullable(node.get(key, null)))); + var previousOwners = PreferenceProjection.snapshotOwners(node); + var operation = UUID.randomUUID(); + journal.prepare(new SettingsJournal.Entry(operation, node.absolutePath(), node.isUserNode(), + PreferenceValuesCodec.encode(previous), PreferenceValuesCodec.encode(draft.values()), false, + Optional.of(PreferenceValuesCodec.encode(PreferenceProjection.owners(node))))); + var changed = new boolean[1]; + final ChatFilterEntityStore.Snapshot result; + try { + result = filters.save(draft.filters(), () -> { + changed[0] = true; + PreferenceProjection.beginProjection(node, operation); + PreferenceProjection.claim(node, operation, draft.values()); + write(node, draft.values()); + preferences.save(); + journal.markCommitted(operation); + }); + } catch (RuntimeException | Error failure) { + try { + var committed = journal.pending().filter(entry -> entry.operation().equals(operation)) + .map(SettingsJournal.Entry::committed).orElse(false); + if (!committed) { + // 失敗した編集を、他DBの復旧より新しい確定済み変更として残さない。 + if (changed[0]) restore(node, previous, () -> { + PreferenceProjection.restoreOwners(node, previousOwners); + PreferenceProjection.completeProjection(node, operation); + }); + journal.clear(operation); + } + } catch (RuntimeException | Error restore) { + if (restore != failure) failure.addSuppressed(restore); + } + throw failure; + } + completed[0] = new SavedSettings(draft, result); + preferences.recordCommittedValues(draft.values()); + PreferenceProjection.completeProjection(node, operation); + preferences.save(); + journal.clear(operation); + return completed[0]; + } + } + + private static void sync(Preferences node) { + try { node.sync(); } + catch (BackingStoreException failure) { throw new RuntimeException(failure); } + } + + private void recoverLocked(Preferences node) { + var pending = journal.pending(); + if (pending.isEmpty()) return; + var entry = pending.orElseThrow(); + if (!entry.nodePath().equals(node.absolutePath()) || entry.userNode() != node.isUserNode()) { + throw new IllegalStateException("settings recovery belongs to another preferences node"); + } + PreferenceProjection.isPending(node, entry.operation()); + var before = PreferenceValuesCodec.decode(entry.before()); + var after = PreferenceValuesCodec.decode(entry.after()); + if (!before.keySet().equals(after.keySet())) throw new IllegalArgumentException("settings recovery keys differ"); + var keys = new HashMap>(); + before.keySet().forEach(key -> keys.put(key, Optional.empty())); + // 旧値は型が不正でも補償できるよう、キーだけを検証してrawのまま保持する。 + AppPreferences.validateEditorValues(keys); + AppPreferences.validateEditorValues(after); + var previousOwners = entry.committed() ? Optional.>>empty() + : entry.previousOwners().map(PreferenceProjection::decodeOwners); + var owners = PreferenceProjection.owners(node); + var values = new HashMap<>(entry.committed() ? after : before); + // 後続の確定保存を維持し、未完了の所有者に遮られた復旧記録は破棄しない。 + values.keySet().removeIf(key -> { + var owner = owners.get(key); + // 先行する操作の補償で所有が消えた場合、その操作の古い投影を再び有効にしない。 + if (owner == null) return previousOwners.map(previous -> previous.containsKey(key)).orElse(false); + if (owner.equals(Optional.of(entry.operation().toString()))) return false; + // この投影が始まる前、または補償で既に旧所有へ戻ったキーは書き戻さない。 + if (previousOwners.map(previous -> owner.equals(previous.get(key))).orElse(false)) return true; + if (PreferenceProjection.isPending(node, UUID.fromString(owner.orElseThrow()))) { + throw new IllegalStateException("another pending settings projection must be recovered first"); + } + return true; + }); + restore(node, values, () -> { + previousOwners.ifPresent(previous -> PreferenceProjection.restoreOwners(node, previous, values.keySet())); + PreferenceProjection.completeProjection(node, entry.operation()); + }); + journal.clear(entry.operation()); + } + + private void restore(Preferences node, Map> values, Runnable... additional) { + var actions = new ArrayList(); + values.forEach((key, value) -> actions.add(() -> write(node, Map.of(key, value)))); + CloseActions.runAll(() -> { + CloseActions.runAll(actions.toArray(Runnable[]::new)); + // 値を戻せなければ、この操作の所有を残して次回の復旧対象にする。 + CloseActions.runAll(additional); + }, preferences::save); + } + + private static void write(Preferences node, Map> values) { + values.forEach((key, value) -> { if (value.isPresent()) node.put(key, value.get()); else node.remove(key); }); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/prefs/UserFilterViewModel.java b/src/main/java/com/github/k7t3/tcv/app/prefs/UserFilterViewModel.java index 19505c3..72be4b1 100644 --- a/src/main/java/com/github/k7t3/tcv/app/prefs/UserFilterViewModel.java +++ b/src/main/java/com/github/k7t3/tcv/app/prefs/UserFilterViewModel.java @@ -19,7 +19,7 @@ import com.github.k7t3.tcv.app.chat.filter.ChatFilters; import com.github.k7t3.tcv.app.chat.filter.UserFilterEntry; import com.github.k7t3.tcv.app.model.EditableViewModelBase; -import com.github.k7t3.tcv.app.event.UserFilteringEvent; +import com.github.k7t3.tcv.entity.ChatUserFilterEntity; import javafx.beans.Observable; import javafx.beans.property.ReadOnlyStringProperty; import javafx.beans.property.ReadOnlyStringWrapper; @@ -37,7 +37,7 @@ public UserFilterViewModel(ChatFilters chatFilters) { this.userEntries = FXCollections.observableArrayList(w -> new Observable[] { w.removedProperty() }); userEntries.addAll(chatFilters.getUserEntries() .stream() - .map(e -> new UserFilterViewModel.Wrapper(e, chatFilters)) + .map(e -> new UserFilterViewModel.Wrapper(e)) .toList()); filtered = new FilteredList<>(userEntries); filtered.setPredicate(w -> !w.isRemoved()); @@ -49,48 +49,34 @@ public ObservableList getUsers() { @Override public boolean canSync() { - return userEntries.stream().noneMatch(EditableViewModelBase::isInvalid); + return userEntries.stream().allMatch(row -> row.isRemoved() || (!row.isInvalid() && row.getComment() != null)); } @Override - public void sync() { - userEntries.stream().filter(EditableViewModelBase::isDirty).forEach(w -> { - w.save(); - var entry = w.entry; - var event = new UserFilteringEvent(entry); - publish(event); - }); + public void prepare(SettingsDraft.Builder target) { + if (!canSync()) throw new IllegalStateException("user filters contain invalid entries"); + for (var row : userEntries) { + if (row.isRemoved()) target.deleteUser(row.getUserId()); + else if (!java.util.Objects.equals(row.entry.getComment(), row.getComment())) { + target.user(new ChatUserFilterEntity(row.getUserId(), row.getUserName(), row.getComment())); + } + } } public static class Wrapper extends EditableViewModelBase { private final UserFilterEntry entry; - private final ChatFilters chatFilters; private final ReadOnlyStringWrapper userId = readOnlyStringWrapper(); private final ReadOnlyStringWrapper userName = readOnlyStringWrapper(); private final StringProperty comment = stringProperty(); - public Wrapper(UserFilterEntry entry, ChatFilters chatFilters) { + public Wrapper(UserFilterEntry entry) { this.entry = entry; - this.chatFilters = chatFilters; userId.set(entry.getUserId()); userName.set(entry.getUserName()); comment.set(entry.getComment()); } - private void save() { - if (!isDirty()) return; - if (isRemoved()) { - chatFilters.deleteUserFilter(entry); - return; - } - - if (!isInvalid()) { - entry.setComment(getComment()); - chatFilters.saveUserFilter(entry); - } - } - public ReadOnlyStringProperty userIdProperty() { return userId.getReadOnlyProperty(); } public String getUserId() { return userId.get(); } diff --git a/src/main/java/com/github/k7t3/tcv/app/reactive/ChatMessageSubscriber.java b/src/main/java/com/github/k7t3/tcv/app/reactive/ChatMessageSubscriber.java index 76ca3de..b5c4b26 100644 --- a/src/main/java/com/github/k7t3/tcv/app/reactive/ChatMessageSubscriber.java +++ b/src/main/java/com/github/k7t3/tcv/app/reactive/ChatMessageSubscriber.java @@ -18,12 +18,10 @@ import com.github.k7t3.tcv.domain.event.chat.ChatMessageEvent; import com.github.k7t3.tcv.reactive.AbstractSubscriber; -import com.github.k7t3.tcv.reactive.BackPressurePolicy; import javafx.application.Platform; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.Flow; import java.util.function.Consumer; public class ChatMessageSubscriber extends AbstractSubscriber { @@ -36,11 +34,6 @@ public ChatMessageSubscriber(Consumer consumer) { this.consumer = consumer; } - @Override - public void onSubscribe(Flow.Subscription subscription) { - super.onSubscribe(subscription); - } - @Override protected void handle(ChatMessageEvent item) { consumer.accept(item); @@ -49,30 +42,9 @@ protected void handle(ChatMessageEvent item) { @Override public void onNext(ChatMessageEvent item) { if (Platform.isFxApplicationThread()) { - onNextFX(item); + super.onNext(item); } else { - Platform.runLater(() -> onNextFX(item)); - } - } - - private void onNextFX(ChatMessageEvent item) { - handle(item); - - // 現在設定されているポリシーとリクエスト時点のポリシーを取得 - var policy = backPressurePolicy.get(); - var requested = requestedPolicy.getAndSet(policy); - - // ポリシーが変更されているときは再度リクエスト - if (policy != requested) { - request(policy.getSegmentSize()); - return; - } - - // FULLでないときは処理件数を考慮して適宜リクエストを再発行する - if (policy != BackPressurePolicy.FULL) { - if (segmentCounter.incrementAndGet() == policy.getSegmentSize()) { - request(policy.getSegmentSize()); - } + Platform.runLater(() -> super.onNext(item)); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/reactive/DownCastFXSubscriber.java b/src/main/java/com/github/k7t3/tcv/app/reactive/DownCastFXSubscriber.java index 903b604..b7d6382 100644 --- a/src/main/java/com/github/k7t3/tcv/app/reactive/DownCastFXSubscriber.java +++ b/src/main/java/com/github/k7t3/tcv/app/reactive/DownCastFXSubscriber.java @@ -41,7 +41,9 @@ protected void handleCasted(R item) { if (Platform.isFxApplicationThread()) { consumer.accept(item); } else { - Platform.runLater(() -> consumer.accept(item)); + Platform.runLater(() -> { + if (!isCancelled()) consumer.accept(item); + }); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/AtomicKeyStoreFile.java b/src/main/java/com/github/k7t3/tcv/app/secure/AtomicKeyStoreFile.java new file mode 100644 index 0000000..6a15e36 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/AtomicKeyStoreFile.java @@ -0,0 +1,64 @@ +package com.github.k7t3.tcv.app.secure; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermissions; + +/** 完成して強制書込済みのファイルだけを公開する。非原子的な置換へはフォールバックしない。 */ +final class AtomicKeyStoreFile { + @FunctionalInterface interface Writer { void write(Path path, byte[] bytes) throws IOException; } + @FunctionalInterface interface Commit { void replace(Path temporary, Path target) throws IOException; } + private final Writer writer; + private final Commit commit; + + AtomicKeyStoreFile() { this(AtomicKeyStoreFile::writeAndForce, AtomicKeyStoreFile::replace); } + AtomicKeyStoreFile(Writer writer, Commit commit) { + this.writer = writer; + this.commit = commit; + } + + void write(Path target, byte[] bytes) throws IOException { + var temporary = Files.createTempFile(target.getParent(), ".tcv-keys-", ".tmp", permissions(target, "rw-------")); + Throwable failure = null; + try { + writer.write(temporary, bytes); + commit.replace(temporary, target); + // POSIX では置換先のディレクトリエントリーも強制書込する。 + if (target.getFileSystem().supportedFileAttributeViews().contains("posix")) { + try (var parent = FileChannel.open(target.getParent(), StandardOpenOption.READ)) { parent.force(true); } + } + } catch (IOException | RuntimeException | Error error) { + failure = error; + throw error; + } finally { + try { Files.deleteIfExists(temporary); } + catch (IOException cleanupFailure) { + if (failure != null) failure.addSuppressed(cleanupFailure); + else throw cleanupFailure; + } + } + } + + static void writeAndForce(Path temporary, byte[] bytes) throws IOException { + try (var channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { + var buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) channel.write(buffer); + channel.force(true); + } + } + + static void replace(Path temporary, Path target) throws IOException { + Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } + + static FileAttribute[] permissions(Path path, String mode) { + if (!path.getFileSystem().supportedFileAttributeViews().contains("posix")) return new FileAttribute[0]; + return new FileAttribute[]{PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(mode))}; + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/CipherOperator.java b/src/main/java/com/github/k7t3/tcv/app/secure/CipherOperator.java deleted file mode 100644 index 192c503..0000000 --- a/src/main/java/com/github/k7t3/tcv/app/secure/CipherOperator.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright 2024 k7t3 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.github.k7t3.tcv.app.secure; - -import javax.crypto.*; -import javax.crypto.spec.IvParameterSpec; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; - -/** - * 暗号化に関するユーティリティクラス - *

- * 暗号化・復号に使用しているキー情報は{@link KeyManager}で管理されているため、 - * 必要に応じて{@link KeyManagerFactory}より実装を取得し、永続化すること。 - *

- */ -public class CipherOperator { - - private static final String KEY_ALIAS = "c.o"; - - private static final int IV_LENGTH = 16; - private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; - - private SecretKey secret; - - /** - * プライベートコンストラクタ - */ - private CipherOperator() { - } - - /** - * キーストアから鍵を取得する - */ - private SecretKey getSecret() { - if (secret == null) { - var manager = KeyManagerFactory.getInstance(); - secret = manager.getSecret(KEY_ALIAS); - - if (secret == null) { - secret = generateSecretKey(); - manager.store(KEY_ALIAS, secret); - } - } - return secret; - } - - private static SecretKey generateSecretKey() { - try { - var generator = KeyGenerator.getInstance("AES"); - generator.init(256); - return generator.generateKey(); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } - - /** - * 引数のバイト配列を暗号化して返す。 - *

- * 対称鍵暗号方式によって暗号化され、暗号化に使用した鍵は安全なキーストアに保管される。 - *

- * @param bytes 暗号化するバイト配列 - * @return 暗号かれた配列 - * @throws KeyManagerException キーストアに関するエラー - * @throws NullPointerException 引数がnullのとき - * @throws IllegalArgumentException 引数が空の時 - */ - public static byte[] encrypt(byte[] bytes) { - return Instance.OPERATOR.encrypt0(bytes); - } - - private byte[] encrypt0(byte[] bytes) { - if (bytes == null) - throw new NullPointerException("argument is null"); - if (bytes.length < 1) - throw new IllegalArgumentException("argument is empty"); - - Cipher cipher; - try { - cipher = Cipher.getInstance(ALGORITHM); - } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { - throw new RuntimeException(e); - } - - var secret = getSecret(); - try { - cipher.init(Cipher.ENCRYPT_MODE, secret); - } catch (InvalidKeyException e) { - throw new RuntimeException(e); - } - var iv = cipher.getIV(); - assert iv.length == IV_LENGTH; - - byte[] enc; - try { - enc = cipher.doFinal(bytes); - } catch (IllegalBlockSizeException | BadPaddingException e) { - throw new RuntimeException(e); - } - - // 暗号化配列の先頭に初期化ベクトルを結合して返す - var result = new byte[enc.length + IV_LENGTH]; - System.arraycopy(iv, 0, result, 0, iv.length); - System.arraycopy(enc, 0, result, IV_LENGTH, enc.length); - return result; - } - - /** - * 暗号化されたバイト配列を復号して返す。 - *

- * 復号するためのキーを安全なキーストアから取得して復号する。 - *

- * @param bytes 復号するバイト配列 - * @return 復号されたバイト配列 - * @throws KeyManagerException キーストアに関するエラー - * @throws NullPointerException 引数がnullのとき - * @throws IllegalArgumentException 引数に初期化ベクトルが含まれていないことが疑われるとき - */ - public static byte[] decrypt(byte[] bytes) { - return Instance.OPERATOR.decrypt0(bytes); - } - - private byte[] decrypt0(byte[] bytes) { - if (bytes == null) - throw new NullPointerException("argument is null"); - if (bytes.length < IV_LENGTH + 1) - throw new IllegalArgumentException("argument may not include IV"); - - Cipher cipher; - try { - cipher = Cipher.getInstance(ALGORITHM); - } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { - throw new RuntimeException(e); - } - - var iv = new byte[IV_LENGTH]; - System.arraycopy(bytes, 0, iv, 0, IV_LENGTH); - - var secret = getSecret(); - var ivSpec = new IvParameterSpec(iv); - try { - cipher.init(Cipher.DECRYPT_MODE, secret, ivSpec); - } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { - throw new RuntimeException(e); - } - - byte[] result; - try { - result = cipher.doFinal(bytes, IV_LENGTH, bytes.length - IV_LENGTH); - } catch (IllegalBlockSizeException | BadPaddingException e) { - throw new RuntimeException(e); - } - - return result; - } - - private static final class Instance { - private static final CipherOperator OPERATOR = new CipherOperator(); - } - -} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/CredentialCipher.java b/src/main/java/com/github/k7t3/tcv/app/secure/CredentialCipher.java new file mode 100644 index 0000000..ad3ca42 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/CredentialCipher.java @@ -0,0 +1,89 @@ +package com.github.k7t3.tcv.app.secure; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.IvParameterSpec; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Objects; + +/** 借用した鍵管理サービスを使う。旧 CBC は読取専用とし、新規保存は認証付きの版で行う。 */ +final class CredentialCipher { + private static final byte[] HEADER = {'T', 'C', 'V', 'C', 'R', 'E', 'D', 2}; + private static final int NONCE_BYTES = 12; + private static final int TAG_BITS = 128; + private static final String CURRENT_KEY = "credential.gcm.v2"; + private static final String LEGACY_KEY = "c.o"; + private static final SecureRandom RANDOM = new SecureRandom(); + private final KeyManager keys; + + CredentialCipher(KeyManager keys) { this.keys = Objects.requireNonNull(keys); } + + byte[] encrypt(byte[] plain) { + Objects.requireNonNull(plain); + var key = keys.getOrCreateSecret(CURRENT_KEY, CredentialCipher::generateKey); + var nonce = new byte[NONCE_BYTES]; + RANDOM.nextBytes(nonce); + try { + var cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, nonce)); + cipher.updateAAD(HEADER); + var encrypted = cipher.doFinal(plain); + var result = Arrays.copyOf(HEADER, HEADER.length + nonce.length + encrypted.length); + System.arraycopy(nonce, 0, result, HEADER.length, nonce.length); + System.arraycopy(encrypted, 0, result, HEADER.length + nonce.length, encrypted.length); + return result; + } catch (GeneralSecurityException failure) { + throw new KeyManagerException("failed to encrypt credentials", failure); + } + } + + byte[] decrypt(byte[] encrypted) { + Objects.requireNonNull(encrypted); + try { + if (hasMagic(encrypted)) return decryptCurrent(encrypted); + if (encrypted.length < 32 || encrypted.length % 16 != 0) throw new KeyManagerException("invalid credential format"); + var cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, existingKey(LEGACY_KEY), new IvParameterSpec(encrypted, 0, 16)); + return cipher.doFinal(encrypted, 16, encrypted.length - 16); + } catch (GeneralSecurityException failure) { + throw new KeyManagerException("failed to decrypt credentials", failure); + } + } + + private byte[] decryptCurrent(byte[] encrypted) throws GeneralSecurityException { + var bodyOffset = HEADER.length + NONCE_BYTES; + if (encrypted.length < bodyOffset + TAG_BITS / 8 || encrypted[HEADER.length - 1] != HEADER[HEADER.length - 1]) { + throw new KeyManagerException("unsupported or truncated credential format"); + } + var cipher = Cipher.getInstance("AES/GCM/NoPadding"); + var nonce = Arrays.copyOfRange(encrypted, HEADER.length, bodyOffset); + cipher.init(Cipher.DECRYPT_MODE, existingKey(CURRENT_KEY), new GCMParameterSpec(TAG_BITS, nonce)); + cipher.updateAAD(HEADER); + return cipher.doFinal(encrypted, bodyOffset, encrypted.length - bodyOffset); + } + + private SecretKey existingKey(String alias) { + var key = keys.getSecret(alias); + if (key == null) throw new KeyManagerException("credential decryption key is missing"); + return key; + } + + private static boolean hasMagic(byte[] bytes) { + var length = HEADER.length - 1; + return bytes.length >= length && Arrays.equals(HEADER, 0, length, bytes, 0, length); + } + + private static SecretKey generateKey() { + try { + var generator = KeyGenerator.getInstance("AES"); + generator.init(256); + return generator.generateKey(); + } catch (GeneralSecurityException failure) { + throw new KeyManagerException("failed to generate credential key", failure); + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/CredentialCipherService.java b/src/main/java/com/github/k7t3/tcv/app/secure/CredentialCipherService.java new file mode 100644 index 0000000..76f8a21 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/CredentialCipherService.java @@ -0,0 +1,16 @@ +package com.github.k7t3.tcv.app.secure; + +import java.util.function.Supplier; + +/** 鍵管理を遅延構築して所有する。認証と保存I/Oの実完了後に終了する。 */ +public final class CredentialCipherService implements AutoCloseable { + private final KeyManagerProvider keys; + + CredentialCipherService(Supplier create) { keys = new KeyManagerProvider(create); } + + public byte[] encrypt(byte[] plain) { return new CredentialCipher(keys.get()).encrypt(plain); } + + public byte[] decrypt(byte[] encrypted) { return new CredentialCipher(keys.get()).decrypt(encrypted); } + + @Override public void close() { keys.close(); } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/KeyManager.java b/src/main/java/com/github/k7t3/tcv/app/secure/KeyManager.java index 32bbb73..7ffb467 100644 --- a/src/main/java/com/github/k7t3/tcv/app/secure/KeyManager.java +++ b/src/main/java/com/github/k7t3/tcv/app/secure/KeyManager.java @@ -17,20 +17,18 @@ package com.github.k7t3.tcv.app.secure; import javax.crypto.SecretKey; +import java.util.function.Supplier; /** * 鍵を安全に永続化するためのクラス */ public interface KeyManager extends AutoCloseable { - /** - * バッファリングされる鍵情報を永続化する - * @throws KeyManagerException キーストアに関するエラー - */ - void flush() throws KeyManagerException; + /** 存在する鍵を返す。新規の場合は永続化に成功してから返す。生成と保存は排他的に行う。 */ + SecretKey getOrCreateSecret(String alias, Supplier generator) throws KeyManagerException; /** - * 任意のエイリアスに紐づく鍵を保存する + * 任意のエイリアスに紐づく鍵を永続化し、完了後に戻る。 * @param alias 任意のエイリアス * @param key 保存する鍵 * @throws KeyManagerException キーストアに関するエラー diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/KeyManagerFactory.java b/src/main/java/com/github/k7t3/tcv/app/secure/KeyManagerFactory.java index 3d58a8c..edaaf1c 100644 --- a/src/main/java/com/github/k7t3/tcv/app/secure/KeyManagerFactory.java +++ b/src/main/java/com/github/k7t3/tcv/app/secure/KeyManagerFactory.java @@ -19,27 +19,34 @@ import com.github.k7t3.tcv.app.core.OS; import java.nio.file.Path; +import java.util.function.Supplier; +import java.util.Arrays; +import java.time.Duration; +/** OS保護または明示パスワードの鍵管理を、暗号化サービスの所有範囲へ遅延構築する。 */ public class KeyManagerFactory { static final String DEFAULT_PATH = System.getProperty( "key.manager.path", OS.current().getApplicationDirectory().resolve("keymanager.ks").toString() ); - static final String DEFAULT_PASSWORD = System.getProperty("key.manager.password", "changeit"); private KeyManagerFactory() { } - public static KeyManager getInstance() { - return Holder.KEY_MANAGER; + /** OS保護を既定とし、key.manager.passwordの明示指定だけ従来方式を使用する。 */ + public static CredentialCipherService create() { + return create(Path.of(DEFAULT_PATH), System.getProperty("key.manager.password"), + () -> new ProcessOsSecretStore(SecretStoreCommand::current, Duration.ofSeconds(30))); } - private static final class Holder { - private static final KeyManager KEY_MANAGER; - static { - KEY_MANAGER = new KeyManagerImpl(Path.of(DEFAULT_PATH), DEFAULT_PASSWORD.toCharArray()); - } + static CredentialCipherService create(Path path, String explicitPassword, Supplier osStore) { + return new CredentialCipherService(() -> { + if (explicitPassword == null) return new KeyManagerImpl(path, osStore.get()); + var password = explicitPassword.toCharArray(); + try { return new KeyManagerImpl(path, password); } + finally { Arrays.fill(password, '\0'); } + }); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/KeyManagerImpl.java b/src/main/java/com/github/k7t3/tcv/app/secure/KeyManagerImpl.java index 47f969a..0b3773a 100644 --- a/src/main/java/com/github/k7t3/tcv/app/secure/KeyManagerImpl.java +++ b/src/main/java/com/github/k7t3/tcv/app/secure/KeyManagerImpl.java @@ -16,118 +16,122 @@ package com.github.k7t3.tcv.app.secure; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import com.github.k7t3.tcv.io.InterruptibleFileLocks; import javax.crypto.SecretKey; import javax.security.auth.DestroyFailedException; import java.io.IOException; +import java.io.InterruptedIOException; +import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableEntryException; -import java.security.cert.CertificateException; - +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.Objects; +import java.util.Set; +import java.util.function.Supplier; +import java.util.concurrent.locks.ReentrantLock; + +/** キャッシュした古い KeyStore を書き戻さず、ファイルの読取・変更・置換を一組で行う。 */ class KeyManagerImpl implements KeyManager { - - private static final Logger LOGGER = LoggerFactory.getLogger(KeyManagerImpl.class); - + // FileLock は同じ JVM 内の重複取得を待機しないため、まず JVM 内を直列化する。 + private static final ReentrantLock FILE_LOCK = new ReentrantLock(); + private final ReentrantLock lifecycleLock = new ReentrantLock(); private final Path storePath; + private final char[] password; + private final OsSecretStore secrets; + private final AtomicKeyStoreFile files; + private boolean closed; - private final KeyStore store; - private final KeyStore.PasswordProtection protection; + public KeyManagerImpl(Path path, char[] password) { this(path, password, new AtomicKeyStoreFile()); } - private boolean dirty = false; // 永続化されていない鍵情報があるか - private boolean closed = false; // インスタンスが閉じられているか - - public KeyManagerImpl(Path storePath, char[] password) { - this.storePath = storePath; - this.store = loadKeyStore(storePath, password); - this.protection = new KeyStore.PasswordProtection(password); + KeyManagerImpl(Path path, OsSecretStore secrets) { + this(path, null, Objects.requireNonNull(secrets), new AtomicKeyStoreFile()); } - private static KeyStore loadKeyStore(Path storePath, char[] password) { - if (Files.exists(storePath)) { - try { - LOGGER.info("load key store {}", storePath); - return KeyStore.getInstance(storePath.toFile(), password); - } catch (KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException e) { - throw new KeyManagerException(e); - } - } - - try { - var keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (KeyStoreException | NoSuchAlgorithmException | IOException | CertificateException e) { - throw new KeyManagerException(e); - } + KeyManagerImpl(Path path, char[] password, AtomicKeyStoreFile files) { + this(path, Objects.requireNonNull(password), null, files); } - private void checkClosed() { - if (closed) { - throw new IllegalStateException("already closed"); + private KeyManagerImpl(Path path, char[] password, OsSecretStore secrets, AtomicKeyStoreFile files) { + this.storePath = Objects.requireNonNull(path).toAbsolutePath().normalize(); + this.password = password == null ? null : password.clone(); + this.secrets = secrets; + this.files = Objects.requireNonNull(files); + try { withStore(store -> null); } + catch (RuntimeException | Error failure) { + if (this.password != null) Arrays.fill(this.password, '\0'); + throw failure; } } @Override - public void flush() { - LOGGER.info("flushing key store"); - checkClosed(); - try (var output = Files.newOutputStream(storePath, - StandardOpenOption.CREATE, - StandardOpenOption.WRITE, - StandardOpenOption.TRUNCATE_EXISTING)) { - store.store(output, protection.getPassword()); - dirty = false; - } catch (IOException | NoSuchAlgorithmException | KeyStoreException | CertificateException e) { - throw new KeyManagerException(e); - } + public SecretKey getOrCreateSecret(String alias, Supplier generator) { + Objects.requireNonNull(generator); + return withStore(store -> { + var existing = store.getSecret(Objects.requireNonNull(alias)); + if (existing != null) return existing; + var created = Objects.requireNonNull(generator.get()); + store.put(alias, created); + store.persist(storePath, files); + return created; + }); } @Override public void store(String alias, SecretKey key) { - LOGGER.info("store {} secret", alias); - checkClosed(); - var entry = new KeyStore.SecretKeyEntry(key); - try { - store.setEntry(alias, entry, protection); - dirty = true; - } catch (KeyStoreException e) { - throw new KeyManagerException(e); - } + withStore(store -> { + store.put(Objects.requireNonNull(alias), Objects.requireNonNull(key)); + store.persist(storePath, files); + return null; + }); } @Override - public SecretKey getSecret(String alias) { - LOGGER.info("get {} secret", alias); - checkClosed(); + public SecretKey getSecret(String alias) { return withStore(store -> store.getSecret(Objects.requireNonNull(alias))); } + + @FunctionalInterface + private interface Operation { T apply(KeyStoreSession store) throws IOException, GeneralSecurityException, DestroyFailedException; } + + private T withStore(Operation operation) { try { - var entry = store.getEntry(alias, protection); - if (entry == null) - return null; - return ((KeyStore.SecretKeyEntry) entry).getSecretKey(); - } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) { - throw new KeyManagerException(e); + lifecycleLock.lockInterruptibly(); + try { + if (closed) throw new IllegalStateException("key manager is closed"); + FILE_LOCK.lockInterruptibly(); + try { + var parent = storePath.getParent(); + Files.createDirectories(parent, AtomicKeyStoreFile.permissions(parent, "rwx------")); + var lockPath = storePath.resolveSibling(storePath.getFileName() + ".lock"); + try (var channel = FileChannel.open(lockPath, + Set.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE), + AtomicKeyStoreFile.permissions(lockPath, "rw-------")); var ignored = InterruptibleFileLocks.acquire(channel)) { + try (var store = secrets == null ? KeyStoreSession.passwordProtected(storePath, password) + : KeyStoreSession.osProtected(storePath, secrets, files)) { + return operation.apply(store); + } + } + } finally { FILE_LOCK.unlock(); } + } finally { lifecycleLock.unlock(); } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + var failure = new InterruptedIOException("interrupted while waiting for key storage"); + failure.initCause(interrupted); + throw new KeyManagerException("failed to access key store", failure); + } catch (IOException | GeneralSecurityException | DestroyFailedException failure) { + throw new KeyManagerException("failed to access key store", failure); } } @Override public void close() { - if (closed) return; - LOGGER.info("closing key store"); - // 永続化されていない鍵情報がある場合は閉じる前に書き込む - if (dirty) { - flush(); - } + // closeは受理済みの保存を中断せず、その実完了と秘密消去を待つ。 + lifecycleLock.lock(); try { - protection.destroy(); - } catch (DestroyFailedException ignore) { - } - closed = true; + if (closed) return; + closed = true; + if (password != null) Arrays.fill(password, '\0'); + } finally { lifecycleLock.unlock(); } } } diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/KeyManagerProvider.java b/src/main/java/com/github/k7t3/tcv/app/secure/KeyManagerProvider.java new file mode 100644 index 0000000..ae68666 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/KeyManagerProvider.java @@ -0,0 +1,41 @@ +package com.github.k7t3.tcv.app.secure; + +import java.io.InterruptedIOException; +import java.util.Objects; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Supplier; + +/** 初期化に成功したサービスだけを所有する。初期化失敗は次の呼び出しで再試行できる。 */ +final class KeyManagerProvider implements AutoCloseable { + private final Supplier create; + private final ReentrantLock ownership = new ReentrantLock(); + private KeyManager manager; + private boolean closed; + + KeyManagerProvider(Supplier create) { this.create = Objects.requireNonNull(create); } + + KeyManager get() { + try { ownership.lockInterruptibly(); } + catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + var failure = new InterruptedIOException("interrupted while waiting for key initialization"); + failure.initCause(interrupted); + throw new KeyManagerException("failed to access key service", failure); + } + try { + if (closed) throw new IllegalStateException("key service is closed"); + if (manager == null) manager = Objects.requireNonNull(create.get()); + return manager; + } finally { ownership.unlock(); } + } + + @Override + public void close() { + ownership.lock(); + try { + if (closed) return; + closed = true; + if (manager != null) manager.close(); + } finally { ownership.unlock(); } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/KeyStoreSession.java b/src/main/java/com/github/k7t3/tcv/app/secure/KeyStoreSession.java new file mode 100644 index 0000000..282a354 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/KeyStoreSession.java @@ -0,0 +1,174 @@ +package com.github.k7t3.tcv.app.secure; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.UUID; +import javax.crypto.SecretKey; +import javax.security.auth.DestroyFailedException; + +/** ファイルの排他区間だけ復号用パスワードを所有し、区間終了時に消去する。 */ +final class KeyStoreSession implements AutoCloseable { + private static final byte[] MAGIC = {'T', 'C', 'V', 'K', 'E', 'Y', 'S', 2}; + private static final int HEADER_SIZE = MAGIC.length + 2 * Long.BYTES; + private final KeyStore store; + private final char[] password; + private final OsSecretStore secrets; + private final UUID id; + private final byte[] secret; + private boolean newSecret; + + private KeyStoreSession(KeyStore store, char[] password, OsSecretStore secrets, UUID id, + byte[] secret, boolean newSecret) { + this.store = store; + this.password = password; + this.secrets = secrets; + this.id = id; + this.secret = secret; + this.newSecret = newSecret; + } + + static KeyStoreSession passwordProtected(Path path, char[] password) throws IOException, GeneralSecurityException { + var owned = password.clone(); + try { + var store = Files.exists(path) ? KeyStore.getInstance(path.toFile(), owned) : empty(KeyStore.getDefaultType(), owned); + return new KeyStoreSession(store, owned, null, null, null, false); + } catch (IOException | GeneralSecurityException | RuntimeException | Error failure) { + Arrays.fill(owned, '\0'); + throw failure; + } + } + + static KeyStoreSession osProtected(Path path, OsSecretStore secrets, AtomicKeyStoreFile files) + throws IOException, GeneralSecurityException, DestroyFailedException { + var data = Files.exists(path) ? Files.readAllBytes(path) : null; + KeyStore legacy = null; + var protectedFormat = data != null && data.length >= MAGIC.length - 1 + && Arrays.equals(data, 0, MAGIC.length - 1, MAGIC, 0, MAGIC.length - 1); + if (data != null && !protectedFormat) { + var legacyPassword = "changeit".toCharArray(); + try { legacy = KeyStore.getInstance(path.toFile(), legacyPassword); } + finally { Arrays.fill(legacyPassword, '\0'); } + } + var creating = data == null || legacy != null; + UUID id; + byte[] secret; + if (creating) { + id = UUID.randomUUID(); + secret = new byte[32]; + new SecureRandom().nextBytes(secret); + } else { + if (data.length < HEADER_SIZE || !Arrays.equals(data, 0, MAGIC.length, MAGIC, 0, MAGIC.length)) { + throw new KeyManagerException("unsupported protected key-store format"); + } + var header = ByteBuffer.wrap(data); + header.position(MAGIC.length); + id = new UUID(header.getLong(), header.getLong()); + secret = secrets.read(id.toString()); + if (secret == null) throw new KeyManagerException("OS key-store secret is missing"); + } + char[] password = null; + try { + if (secret.length != 32) throw new KeyManagerException("invalid OS key-store secret"); + password = password(secret); + var store = empty("PKCS12", password); + if (legacy != null) { + copyEntries(legacy, store, password); + } else if (data != null) { + try (var input = new ByteArrayInputStream(data, HEADER_SIZE, data.length - HEADER_SIZE)) { + store.load(input, password); + } + } + var session = new KeyStoreSession(store, password, secrets, id, secret, creating); + if (legacy != null) session.persist(path, files); + return session; + } catch (IOException | GeneralSecurityException | DestroyFailedException | RuntimeException | Error failure) { + Arrays.fill(secret, (byte) 0); + if (password != null) Arrays.fill(password, '\0'); + throw failure; + } + } + + private static void copyEntries(KeyStore source, KeyStore target, char[] password) + throws GeneralSecurityException, DestroyFailedException { + // 固定パスワードは旧形式の読取だけに使用し、新形式へは保存しない。 + var legacyPassword = "changeit".toCharArray(); + var from = new KeyStore.PasswordProtection(legacyPassword); + Arrays.fill(legacyPassword, '\0'); + var to = new KeyStore.PasswordProtection(password); + try { + var aliases = source.aliases(); + while (aliases.hasMoreElements()) { + var alias = aliases.nextElement(); + var entry = source.getEntry(alias, source.isKeyEntry(alias) ? from : null); + target.setEntry(alias, entry, entry instanceof KeyStore.TrustedCertificateEntry ? null : to); + } + } finally { + try { from.destroy(); } + finally { to.destroy(); } + } + } + + private static KeyStore empty(String type, char[] password) throws GeneralSecurityException, IOException { + var store = KeyStore.getInstance(type); + store.load(null, password); + return store; + } + + private static char[] password(byte[] secret) { + var result = new char[secret.length * 2]; + var alphabet = "0123456789abcdef"; + for (var i = 0; i < secret.length; i++) { + result[i * 2] = alphabet.charAt((secret[i] & 0xff) >>> 4); + result[i * 2 + 1] = alphabet.charAt(secret[i] & 0xf); + } + return result; + } + + SecretKey getSecret(String alias) throws GeneralSecurityException, DestroyFailedException { + var protection = new KeyStore.PasswordProtection(password); + try { + var entry = store.getEntry(alias, protection); + if (entry == null) return null; + if (!(entry instanceof KeyStore.SecretKeyEntry key)) throw new KeyManagerException("entry is not a secret key"); + return key.getSecretKey(); + } finally { protection.destroy(); } + } + + void put(String alias, SecretKey key) throws GeneralSecurityException, DestroyFailedException { + var protection = new KeyStore.PasswordProtection(password); + try { store.setEntry(alias, new KeyStore.SecretKeyEntry(key), protection); } + finally { protection.destroy(); } + } + + void persist(Path path, AtomicKeyStoreFile files) throws GeneralSecurityException, IOException { + try (var output = new ByteArrayOutputStream()) { + store.store(output, password); + if (secrets == null) { + files.write(path, output.toByteArray()); + } else { + var payload = output.toByteArray(); + var envelope = ByteBuffer.allocate(HEADER_SIZE + payload.length).put(MAGIC) + .putLong(id.getMostSignificantBits()).putLong(id.getLeastSignificantBits()).put(payload).array(); + // OS側の保存が終わる前に、その秘密を参照するファイルを公開しない。 + if (newSecret) { + secrets.save(id.toString(), secret); + newSecret = false; + } + files.write(path, envelope); + } + } + } + + @Override public void close() { + Arrays.fill(password, '\0'); + if (secret != null) Arrays.fill(secret, (byte) 0); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/LibsecretSecretStore.java b/src/main/java/com/github/k7t3/tcv/app/secure/LibsecretSecretStore.java new file mode 100644 index 0000000..8bf3b1d --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/LibsecretSecretStore.java @@ -0,0 +1,178 @@ +package com.github.k7t3.tcv.app.secure; + +import com.github.k7t3.tcv.lifecycle.CloseActions; +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.util.ArrayList; +import java.util.Objects; +import java.util.UUID; + +import static java.lang.foreign.ValueLayout.*; + +/** Linux Secret Serviceのbinary valueを操作単位で所有する。 */ +final class LibsecretSecretStore implements OsSecretStore { + private final SecretApi api; + /** attributes/value/errorの所有権は呼出元へ移り、dataはvalueからの借用となる。 */ + interface SecretApi { + MemorySegment attributes(MemorySegment application, MemorySegment id); + MemorySegment read(MemorySegment attributes, MemorySegment error); + MemorySegment data(MemorySegment value, MemorySegment length); + MemorySegment value(MemorySegment secret, long length); + int save(MemorySegment attributes, MemorySegment value, MemorySegment error); + void releaseAttributes(MemorySegment attributes); + void releaseValue(MemorySegment value); + void releaseError(MemorySegment error); + } + + LibsecretSecretStore() { + this(new NativeSecretApi(name -> NativeLibraries.SECRET.find(name), name -> NativeLibraries.GLIB.find(name))); + } + + LibsecretSecretStore(SecretApi api) { + this.api = Objects.requireNonNull(api); + if (ADDRESS.byteSize() != 8) throw new KeyManagerException("64-bit libsecret layout required"); + } + + @Override public byte[] read(String id) { + try (var scope = new Scope()) { + var attributes = attributes(scope, id); + var error = scope.arena.allocate(ADDRESS); + var value = api.read(attributes, error); + if (!value.equals(MemorySegment.NULL)) scope.own(value, () -> api.releaseValue(value)); + checkError(scope, error); + if (value.equals(MemorySegment.NULL)) return null; + var length = scope.arena.allocate(JAVA_LONG); + var bytes = api.data(value, length); + if (length.get(JAVA_LONG, 0) != 32 || bytes.equals(MemorySegment.NULL)) + throw new KeyManagerException("invalid libsecret secret length"); + return bytes.reinterpret(32).toArray(JAVA_BYTE); + } + } + @Override public void save(String id, byte[] secret) { + Objects.requireNonNull(secret); + if (secret.length != 32) throw new IllegalArgumentException("32-byte protection secret required"); + try (var scope = new Scope()) { + var attributes = attributes(scope, id); + var bytes = scope.arena.allocateFrom(JAVA_BYTE, secret); + scope.releases.add(() -> bytes.fill((byte) 0)); + var value = api.value(bytes, 32); + scope.own(value, () -> api.releaseValue(value)); + var error = scope.arena.allocate(ADDRESS); + var saved = api.save(attributes, value, error); + checkError(scope, error); + if (saved == 0) throw new NativeSecretStoreException(-1); + } + } + + private MemorySegment attributes(Scope scope, String id) { + var account = UUID.fromString(id).toString(); + var attributes = api.attributes(scope.arena.allocateFrom("com.github.k7t3.tcv"), scope.arena.allocateFrom(account)); + return scope.own(attributes, () -> api.releaseAttributes(attributes)); + } + + private void checkError(Scope scope, MemorySegment result) { + var error = result.get(ADDRESS, 0); + if (error.equals(MemorySegment.NULL)) return; + scope.own(error, () -> api.releaseError(error)); + var code = error.reinterpret(8).get(JAVA_INT, 4); + throw new NativeSecretStoreException(code == 0 ? -1 : code); + } + + private static final class Scope implements AutoCloseable { + private final Arena arena = Arena.ofConfined(); + private final ArrayList releases = new ArrayList<>(); + + private MemorySegment own(MemorySegment value, Runnable release) { + if (value.equals(MemorySegment.NULL)) throw new KeyManagerException("missing libsecret resource"); + releases.add(release); + return value; + } + + @Override public void close() { + var actions = new ArrayList<>(releases.reversed()); + actions.add(arena::close); + CloseActions.runAll(actions.toArray(Runnable[]::new)); + } + } + + static final class NativeSecretApi implements SecretApi { + // HashTableは文字列を借用する。公開固定キーはテーブルより長く保持し、動的な値はScopeが所有する。 + private static final MemorySegment APPLICATION_KEY = Arena.global().allocateFrom("application"); + private static final MemorySegment ID_KEY = Arena.global().allocateFrom("key-id"); + private static final MemorySegment CONTENT_TYPE = Arena.global().allocateFrom("application/octet-stream"); + private static final MemorySegment LABEL = Arena.global().allocateFrom("Twitch Chat Viewer key protection"); + private final SymbolLookup secret; + private final SymbolLookup glib; + + NativeSecretApi(SymbolLookup secret, SymbolLookup glib) { + this.secret = Objects.requireNonNull(secret); + this.glib = Objects.requireNonNull(glib); + } + + @Override public MemorySegment attributes(MemorySegment application, MemorySegment id) { + var table = (MemorySegment) call(glib, "g_hash_table_new", FunctionDescriptor.of(ADDRESS, ADDRESS, ADDRESS), + glib.findOrThrow("g_str_hash"), glib.findOrThrow("g_str_equal")); + if (table.equals(MemorySegment.NULL)) throw new KeyManagerException("missing libsecret attributes"); + var completed = false; + try { + insert(table, APPLICATION_KEY, application); + insert(table, ID_KEY, id); + completed = true; + return table; + } finally { if (!completed) releaseAttributes(table); } + } + + private void insert(MemorySegment table, MemorySegment key, MemorySegment value) { + if ((int) call(glib, "g_hash_table_insert", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS), table, key, value) == 0) + throw new KeyManagerException("libsecret attribute insertion failed"); + } + + @Override public MemorySegment read(MemorySegment attributes, MemorySegment error) { + return (MemorySegment) call(secret, "secret_password_lookupv_binary_sync", + FunctionDescriptor.of(ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS), + MemorySegment.NULL, attributes, MemorySegment.NULL, error); + } + + @Override public MemorySegment data(MemorySegment value, MemorySegment length) { + return (MemorySegment) call(secret, "secret_value_get", FunctionDescriptor.of(ADDRESS, ADDRESS, ADDRESS), value, length); + } + + @Override public MemorySegment value(MemorySegment bytes, long length) { + return (MemorySegment) call(secret, "secret_value_new", FunctionDescriptor.of(ADDRESS, ADDRESS, JAVA_LONG, ADDRESS), + bytes, length, CONTENT_TYPE); + } + + @Override public int save(MemorySegment attributes, MemorySegment value, MemorySegment error) { + // NULL collectionは次のログインにも残る既定保管先。session collectionへ退避しない。 + return (int) call(secret, "secret_password_storev_binary_sync", + FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS, ADDRESS), + MemorySegment.NULL, attributes, MemorySegment.NULL, LABEL, value, MemorySegment.NULL, error); + } + + @Override public void releaseAttributes(MemorySegment attributes) { + call(glib, "g_hash_table_unref", FunctionDescriptor.ofVoid(ADDRESS), attributes); + } + + @Override public void releaseValue(MemorySegment value) { + call(secret, "secret_value_unref", FunctionDescriptor.ofVoid(ADDRESS), value); + } + + @Override public void releaseError(MemorySegment error) { + call(glib, "g_error_free", FunctionDescriptor.ofVoid(ADDRESS), error); + } + + private static Object call(SymbolLookup library, String name, FunctionDescriptor descriptor, Object... arguments) { + try { return Linker.nativeLinker().downcallHandle(library.findOrThrow(name), descriptor).invokeWithArguments(arguments); } + catch (RuntimeException | Error failure) { throw failure; } + catch (Throwable failure) { throw new KeyManagerException("libsecret function failed", failure); } + } + } + + private static final class NativeLibraries { + private static final SymbolLookup SECRET = SymbolLookup.libraryLookup("libsecret-1.so.0", Arena.global()); + private static final SymbolLookup GLIB = SymbolLookup.libraryLookup("libglib-2.0.so.0", Arena.global()); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/MacKeychainSecretStore.java b/src/main/java/com/github/k7t3/tcv/app/secure/MacKeychainSecretStore.java new file mode 100644 index 0000000..cb09fd6 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/MacKeychainSecretStore.java @@ -0,0 +1,158 @@ +package com.github.k7t3.tcv.app.secure; + +import com.github.k7t3.tcv.lifecycle.CloseActions; +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Objects; +import java.util.UUID; + +import static java.lang.foreign.ValueLayout.*; + +/** macOSのSecItem要求とCoreFoundation資源を一回の呼出区間で扱う。 */ +final class MacKeychainSecretStore implements OsSecretStore { + private final String service; + private final Path keychain; + private final SecurityApi api; + + /** 戻り値はOSStatus。成功時に返したCFオブジェクトの所有を呼出元へ移す。 */ + interface SecurityApi { + int open(MemorySegment path, MemorySegment result); + int add(MemorySegment attributes); + int copy(MemorySegment query, MemorySegment result); + } + + MacKeychainSecretStore(String service, Path keychain) { this(service, keychain, new NativeSecurityApi()); } + + MacKeychainSecretStore(String service, Path keychain, SecurityApi api) { + this.service = Objects.requireNonNull(service); + if (service.isBlank() || service.indexOf('\0') >= 0) throw new IllegalArgumentException("invalid keychain service"); + this.keychain = keychain; + this.api = Objects.requireNonNull(api); + } + + @Override public byte[] read(String id) { + try (var scope = new Scope()) { + var query = query(scope, id, true); + put(query, "kSecReturnData", constant(Native.CF, "kCFBooleanTrue")); + var result = scope.arena.allocate(ADDRESS); + var status = api.copy(query, result); + if (status == -25300) return null; + check(status); + var data = scope.own(result.get(ADDRESS, 0)); + var actualType = (long) call(Native.CF, "CFGetTypeID", FunctionDescriptor.of(JAVA_LONG, ADDRESS), data); + var dataType = (long) call(Native.CF, "CFDataGetTypeID", FunctionDescriptor.of(JAVA_LONG)); + if (actualType != dataType) throw new KeyManagerException("invalid keychain secret type"); + var length = (long) call(Native.CF, "CFDataGetLength", FunctionDescriptor.of(JAVA_LONG, ADDRESS), data); + if (length != 32) throw new KeyManagerException("invalid keychain secret length"); + var bytes = (MemorySegment) call(Native.CF, "CFDataGetBytePtr", FunctionDescriptor.of(ADDRESS, ADDRESS), data); + return bytes.reinterpret(length).toArray(JAVA_BYTE); + } + } + + @Override public void save(String id, byte[] secret) { + Objects.requireNonNull(secret); + if (secret.length != 32) throw new IllegalArgumentException("32-byte protection secret required"); + try (var scope = new Scope()) { + var attributes = query(scope, id, false); + var bytes = scope.arena.allocateFrom(JAVA_BYTE, secret); + scope.releases.add(() -> bytes.fill((byte) 0)); + // CFDataに別の秘密コピーを残さず、呼出区間が所有する領域を参照させる。 + var data = scope.own((MemorySegment) call(Native.CF, "CFDataCreateWithBytesNoCopy", + FunctionDescriptor.of(ADDRESS, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS), + MemorySegment.NULL, bytes, (long) secret.length, constant(Native.CF, "kCFAllocatorNull"))); + put(attributes, "kSecValueData", data); + check(api.add(attributes)); + } + } + + private MemorySegment query(Scope scope, String id, boolean read) { + var account = UUID.fromString(id).toString(); + var query = scope.own((MemorySegment) call(Native.CF, "CFDictionaryCreateMutable", + FunctionDescriptor.of(ADDRESS, ADDRESS, JAVA_LONG, ADDRESS, ADDRESS), + MemorySegment.NULL, 0L, Native.CF.findOrThrow("kCFTypeDictionaryKeyCallBacks"), + Native.CF.findOrThrow("kCFTypeDictionaryValueCallBacks"))); + put(query, "kSecClass", constant(Native.SECURITY, "kSecClassGenericPassword")); + put(query, "kSecAttrService", scope.string(service)); + put(query, "kSecAttrAccount", scope.string(account)); + if (keychain != null) { + var result = scope.arena.allocate(ADDRESS); + check(api.open(scope.arena.allocateFrom(keychain.toString()), result)); + var reference = scope.own(result.get(ADDRESS, 0)); + if (read) { + var entries = scope.arena.allocate(ADDRESS); entries.set(ADDRESS, 0, reference); + var array = scope.own((MemorySegment) call(Native.CF, "CFArrayCreate", + FunctionDescriptor.of(ADDRESS, ADDRESS, ADDRESS, JAVA_LONG, ADDRESS), + MemorySegment.NULL, entries, 1L, Native.CF.findOrThrow("kCFTypeArrayCallBacks"))); + put(query, "kSecMatchSearchList", array); + } else put(query, "kSecUseKeychain", reference); + } + return query; + } + + private static void put(MemorySegment dictionary, String name, MemorySegment value) { + call(Native.CF, "CFDictionarySetValue", FunctionDescriptor.ofVoid(ADDRESS, ADDRESS, ADDRESS), + dictionary, constant(Native.SECURITY, name), value); + } + + private static MemorySegment constant(SymbolLookup library, String name) { + return library.findOrThrow(name).reinterpret(ADDRESS.byteSize()).get(ADDRESS, 0); + } + + private static void check(int status) { if (status != 0) throw new NativeSecretStoreException(status); } + + private static Object call(SymbolLookup library, String name, FunctionDescriptor descriptor, Object... arguments) { + try { return Linker.nativeLinker().downcallHandle(library.findOrThrow(name), descriptor).invokeWithArguments(arguments); } + catch (RuntimeException | Error failure) { throw failure; } + catch (Throwable failure) { throw new KeyManagerException("native keychain invocation failed", failure); } + } + + private static final class Scope implements AutoCloseable { + final Arena arena = Arena.ofConfined(); + final ArrayList releases = new ArrayList<>(); + + MemorySegment own(MemorySegment reference) { + if (reference.address() == 0) throw new KeyManagerException("keychain returned no native object"); + releases.add(() -> call(Native.CF, "CFRelease", FunctionDescriptor.ofVoid(ADDRESS), reference)); + return reference; + } + + MemorySegment string(String value) { + return own((MemorySegment) call(Native.CF, "CFStringCreateWithCString", + FunctionDescriptor.of(ADDRESS, ADDRESS, ADDRESS, JAVA_INT), + MemorySegment.NULL, arena.allocateFrom(value), 0x08000100)); + } + + @Override public void close() { + var actions = new ArrayList(releases.reversed()); + releases.clear(); + actions.add(arena::close); + CloseActions.runAll(actions.toArray(Runnable[]::new)); + } + } + + private static final class Native { + static final SymbolLookup CF = SymbolLookup.libraryLookup( + "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", Arena.global()); + static final SymbolLookup SECURITY = SymbolLookup.libraryLookup( + "/System/Library/Frameworks/Security.framework/Security", Arena.global()); + } + + private static final class NativeSecurityApi implements SecurityApi { + @Override public int open(MemorySegment path, MemorySegment result) { + return (int) call(Native.SECURITY, "SecKeychainOpen", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS), path, result); + } + + @Override public int add(MemorySegment attributes) { + return (int) call(Native.SECURITY, "SecItemAdd", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS), attributes, MemorySegment.NULL); + } + + @Override public int copy(MemorySegment query, MemorySegment result) { + return (int) call(Native.SECURITY, "SecItemCopyMatching", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS), query, result); + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/NativeSecretStoreException.java b/src/main/java/com/github/k7t3/tcv/app/secure/NativeSecretStoreException.java new file mode 100644 index 0000000..a88c2b5 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/NativeSecretStoreException.java @@ -0,0 +1,13 @@ +package com.github.k7t3.tcv.app.secure; + +/** 秘密やOS由来の自由文を含めず、拒否・障害の数値コードを保持する。 */ +final class NativeSecretStoreException extends KeyManagerException { + private final int code; + + NativeSecretStoreException(int code) { + super("OS secret store failed with code " + code); + this.code = code; + } + + int code() { return code; } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/OsSecretStore.java b/src/main/java/com/github/k7t3/tcv/app/secure/OsSecretStore.java new file mode 100644 index 0000000..aebcdbf --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/OsSecretStore.java @@ -0,0 +1,10 @@ +package com.github.k7t3.tcv.app.secure; + +/** OSで保護するランダムな秘密を、公開用の識別子で読み書きする境界。 */ +interface OsSecretStore { + /** 呼出元が消去する独立した配列を返す。未登録の場合はnull、利用拒否・読取障害は例外で通知する。 */ + byte[] read(String id); + + /** 保存の完了後に戻る。借用した配列を保持せず、秘密をログやプロセス引数へ公開しない。 */ + void save(String id, byte[] secret); +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/ProcessOsSecretStore.java b/src/main/java/com/github/k7t3/tcv/app/secure/ProcessOsSecretStore.java new file mode 100644 index 0000000..ce10aeb --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/ProcessOsSecretStore.java @@ -0,0 +1,131 @@ +package com.github.k7t3.tcv.app.secure; + +import java.time.Duration; +import java.io.Closeable; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.Set; +import java.util.Locale; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import com.github.k7t3.tcv.lifecycle.CloseActions; + +/** OS保管処理のプロセスを所有し、秘密を私有パイプで交換する。 */ +final class ProcessOsSecretStore implements OsSecretStore { + private static final Set ENVIRONMENT = Set.of("SYSTEMROOT", "WINDIR", "USERPROFILE", + "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES", "APPDATA", + "LOCALAPPDATA", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "DISPLAY", "WAYLAND_DISPLAY", + "XAUTHORITY", "TMPDIR", "TMP", "TEMP"); + private final Supplier helper; + private final Duration timeout; + + ProcessOsSecretStore(Supplier helper, Duration timeout) { + this.helper = Objects.requireNonNull(helper); + this.timeout = Objects.requireNonNull(timeout); + if (timeout.isNegative() || timeout.isZero()) throw new IllegalArgumentException("positive helper timeout required"); + } + + @Override public byte[] read(String id) { return exchange(id, null); } + + @Override public void save(String id, byte[] secret) { + Objects.requireNonNull(secret); + if (secret.length != 32) throw new IllegalArgumentException("32-byte protection secret required"); + exchange(id, secret); + } + + private byte[] exchange(String id, byte[] secret) { + var identifier = UUID.fromString(id); + Process process = null; + Throwable failure = null; + try { + // 子の標準出力はプロトコル専用。診断へ秘密を混ぜない。 + var command = helper.get(); + command.environment().keySet().removeIf(name -> !ENVIRONMENT.contains(name.toUpperCase(Locale.ROOT))); + process = command.redirectError(ProcessBuilder.Redirect.DISCARD).start(); + try (var output = new DataOutputStream(process.getOutputStream())) { + output.writeInt(0x5443564b); + output.writeByte(1); + output.writeByte(secret == null ? 1 : 2); + output.writeLong(identifier.getMostSignificantBits()); + output.writeLong(identifier.getLeastSignificantBits()); + if (secret != null) output.write(secret); + } + // 応答は最大33バイト。子の終了前にreadして期限管理を止めない。 + if (!process.waitFor(timeout.toNanos(), TimeUnit.NANOSECONDS)) { + throw new KeyManagerException("OS secret helper timed out"); + } + if (process.exitValue() != 0) throw new KeyManagerException("OS secret helper exited with code " + process.exitValue()); + try (var input = new DataInputStream(process.getInputStream())) { + return response(input, secret == null); + } + } catch (IOException cause) { + var wrapped = new KeyManagerException("OS secret helper communication failed", cause); + failure = wrapped; + throw wrapped; + } catch (InterruptedException cause) { + Thread.currentThread().interrupt(); + var wrapped = new KeyManagerException("OS secret helper interrupted", cause); + failure = wrapped; + throw wrapped; + } catch (RuntimeException | Error cause) { + failure = cause; + throw cause; + } finally { + if (process != null) { + var owned = process; + try { + CloseActions.runAll(() -> terminate(owned), () -> close(owned.getOutputStream()), + () -> close(owned.getInputStream()), () -> close(owned.getErrorStream())); + } catch (RuntimeException | Error cleanup) { + if (failure != null) failure.addSuppressed(cleanup); + else throw cleanup; + } + } + } + } + + private static byte[] response(DataInputStream input, boolean read) throws IOException { + var status = input.readUnsignedByte(); + if (status == 3) { + var code = input.readInt(); + if (input.read() != -1) throw new IOException("unexpected trailing OS helper error"); + throw new KeyManagerException("OS secret operation failed with code " + code); + } + byte[] secret = null; + var accepted = false; + try { + if (read && status == 1) { + secret = new byte[32]; + input.readFully(secret); + } else if (!(read && status == 0 || !read && status == 2)) { + throw new IOException("unexpected OS helper response"); + } + if (input.read() != -1) throw new IOException("unexpected trailing OS helper response"); + accepted = true; + return secret; + } finally { + if (!accepted && secret != null) Arrays.fill(secret, (byte) 0); + } + } + + private static void terminate(Process process) { + var interrupted = Thread.interrupted(); + try { + if (process.isAlive()) process.destroyForcibly(); + while (true) { + try { process.waitFor(); return; } + catch (InterruptedException ignored) { interrupted = true; } + } + } finally { if (interrupted) Thread.currentThread().interrupt(); } + } + + private static void close(Closeable stream) { + try { stream.close(); } + catch (IOException failure) { throw new UncheckedIOException(failure); } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/SecretStoreCommand.java b/src/main/java/com/github/k7t3/tcv/app/secure/SecretStoreCommand.java new file mode 100644 index 0000000..3b0ea04 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/SecretStoreCommand.java @@ -0,0 +1,33 @@ +package com.github.k7t3.tcv.app.secure; + +import java.nio.file.Path; +import java.nio.file.Files; +import java.net.URISyntaxException; +import java.util.Locale; + +/** 配布済みアプリと開発用JDKのヘルパー起動経路を解決する。 */ +final class SecretStoreCommand { + private SecretStoreCommand() {} + + static ProcessBuilder current() { + try { + var application = Path.of(SecretStoreHelper.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + var launcher = System.getProperty("jpackage.app-path"); + return create(launcher == null ? null : Path.of(launcher), Path.of(System.getProperty("java.home")), application, + System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows")); + } catch (URISyntaxException failure) { throw new KeyManagerException("invalid application code source", failure); } + } + + static ProcessBuilder create(Path launcher, Path javaHome, Path application, boolean windows) { + if (launcher != null) + return new ProcessBuilder(executable(launcher.resolveSibling("Twitch Key Storage" + (windows ? ".exe" : "")))); + return new ProcessBuilder(executable(javaHome.resolve("bin").resolve(windows ? "java.exe" : "java")), + "--enable-native-access=ALL-UNNAMED", "-cp", application.toString(), SecretStoreHelper.class.getName()); + } + + private static String executable(Path path) { + if (!Files.isRegularFile(path) || !Files.isExecutable(path)) + throw new KeyManagerException("missing OS secret helper executable"); + return path.toString(); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/SecretStoreHelper.java b/src/main/java/com/github/k7t3/tcv/app/secure/SecretStoreHelper.java new file mode 100644 index 0000000..3cb94c3 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/SecretStoreHelper.java @@ -0,0 +1,33 @@ +package com.github.k7t3.tcv.app.secure; + +import java.io.IOException; +import java.util.Locale; + +/** JavaFXを起動せず、一回のOS保管要求を処理して終了する。 */ +public final class SecretStoreHelper { + private SecretStoreHelper() {} + + /** 引数から秘密を受け取らず、私有標準入出力だけを使用する。 */ + public static void main(String[] args) { + try { + if (args.length != 0) throw new IOException("unexpected OS helper arguments"); + SecretStoreProtocol.serve(System.in, System.out, () -> nativeStore( + System.getProperty("os.name", ""), System.getenv("DBUS_SESSION_BUS_ADDRESS"))); + } catch (IOException | RuntimeException failure) { + // OSの診断文や入力データを標準出力・標準エラーへ転記しない。 + System.exit(2); + } + } + + static OsSecretStore nativeStore(String name, String sessionBus) { + var os = name.toLowerCase(Locale.ROOT); + if (os.startsWith("mac")) return new MacKeychainSecretStore("com.github.k7t3.tcv.key-protection", null); + if (os.startsWith("windows")) return new WindowsCredentialSecretStore(); + if (os.startsWith("linux")) { + if (sessionBus == null || sessionBus.isBlank() || sessionBus.contains("autolaunch:")) + throw new NativeSecretStoreException(-1); + return new LibsecretSecretStore(); + } + throw new NativeSecretStoreException(-1); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/SecretStoreProtocol.java b/src/main/java/com/github/k7t3/tcv/app/secure/SecretStoreProtocol.java new file mode 100644 index 0000000..09b1548 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/SecretStoreProtocol.java @@ -0,0 +1,47 @@ +package com.github.k7t3.tcv.app.secure; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.UUID; +import java.util.function.Supplier; + +/** 一回限りの私有パイプでOS保管ヘルパーの要求を受け付ける。 */ +final class SecretStoreProtocol { + private SecretStoreProtocol() {} + + static void serve(InputStream input, OutputStream output, Supplier store) throws IOException { + var request = new DataInputStream(input); + var reply = new DataOutputStream(output); + if (request.readInt() != 0x5443564b || request.readUnsignedByte() != 1) + throw new IOException("invalid OS helper request"); + var operation = request.readUnsignedByte(); + if (operation != 1 && operation != 2) throw new IOException("invalid OS helper operation"); + var id = new UUID(request.readLong(), request.readLong()).toString(); + byte[] secret = operation == 2 ? new byte[32] : null; + try { + if (operation == 2) request.readFully(secret); + if (request.read() != -1) throw new IOException("unexpected trailing OS helper request"); + var backend = store.get(); + if (operation == 2) { + backend.save(id, secret); + reply.writeByte(2); + } else { + secret = backend.read(id); + if (secret == null) reply.writeByte(0); + else { + if (secret.length != 32) throw new IOException("invalid OS helper secret length"); + reply.writeByte(1); + reply.write(secret); + } + } + } catch (NativeSecretStoreException failure) { + reply.writeByte(3); + reply.writeInt(failure.code()); + } finally { if (secret != null) Arrays.fill(secret, (byte) 0); } + reply.flush(); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/secure/WindowsCredentialSecretStore.java b/src/main/java/com/github/k7t3/tcv/app/secure/WindowsCredentialSecretStore.java new file mode 100644 index 0000000..fc1dfb5 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/secure/WindowsCredentialSecretStore.java @@ -0,0 +1,152 @@ +package com.github.k7t3.tcv.app.secure; + +import com.github.k7t3.tcv.lifecycle.CloseActions; +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemoryLayout; +import java.lang.invoke.MethodHandle; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; + +import static java.lang.foreign.ValueLayout.*; + +/** Windowsのユーザー別Credential Managerに鍵保護用の秘密を保存する。 */ +final class WindowsCredentialSecretStore implements OsSecretStore { + private final CredentialApi api; + /** 0は成功、非0は呼出直後に捕捉したWin32エラー。成功したreadのbufferは呼出元がfreeする。 */ + interface CredentialApi { + int read(MemorySegment target, MemorySegment result); + int write(MemorySegment credential); + void free(MemorySegment credential); + } + + WindowsCredentialSecretStore() { this(new NativeCredentialApi()); } + + WindowsCredentialSecretStore(CredentialApi api) { + this.api = Objects.requireNonNull(api); + if (ADDRESS.byteSize() != 8) throw new KeyManagerException("64-bit Windows credential layout required"); + } + + @Override public byte[] read(String id) { + try (var arena = Arena.ofConfined()) { + var result = arena.allocate(ADDRESS); + var status = api.read(target(arena, id), result); + if (status == 1168) return null; + if (status != 0) throw new NativeSecretStoreException(status); + var pointer = result.get(ADDRESS, 0); + if (pointer.equals(MemorySegment.NULL)) throw new KeyManagerException("missing native credential buffer"); + try (var owned = new CredentialBuffer(pointer)) { + var bytes = owned.bytes(); + if (owned.value.get(JAVA_INT, 4) != 1 || bytes.byteSize() != 32) + throw new KeyManagerException("invalid native credential type or length"); + return bytes.toArray(JAVA_BYTE); + } + } + } + @Override public void save(String id, byte[] secret) { + Objects.requireNonNull(secret); + if (secret.length != 32) throw new IllegalArgumentException("32-byte protection secret required"); + try (var arena = Arena.ofConfined()) { + var name = target(arena, id); + var bytes = arena.allocateFrom(JAVA_BYTE, secret); + try { + // 64-bit CREDENTIALW。BlobSizeとBlobポインターの間に4バイトのpaddingがある。 + var credential = arena.allocate(80, 8); + credential.set(JAVA_INT, 4, 1); + credential.set(ADDRESS, 8, name); + credential.set(JAVA_INT, 32, 32); + credential.set(ADDRESS, 40, bytes); + credential.set(JAVA_INT, 48, 2); + var status = api.write(credential); + if (status != 0) throw new NativeSecretStoreException(status); + } finally { bytes.fill((byte) 0); } + } + } + + private static MemorySegment target(Arena arena, String id) { + var name = "com.github.k7t3.tcv/key-protection/" + UUID.fromString(id); + return arena.allocateFrom(name, StandardCharsets.UTF_16LE); + } + + private final class CredentialBuffer implements AutoCloseable { + private final MemorySegment value; + + private CredentialBuffer(MemorySegment pointer) { value = pointer.reinterpret(80); } + + private MemorySegment bytes() { + var length = value.get(JAVA_INT, 32); + var pointer = value.get(ADDRESS, 40); + if (length == 0) return MemorySegment.NULL; + if (length < 0 || length > 2560 || pointer.equals(MemorySegment.NULL)) + throw new KeyManagerException("invalid native credential blob"); + return pointer.reinterpret(length); + } + + @Override public void close() { + CloseActions.runAll(() -> bytes().fill((byte) 0), () -> api.free(value)); + } + } + + static final class NativeCredentialApi implements CredentialApi { + private final SymbolLookup symbols; + private final String errorName; + + private NativeCredentialApi() { this(name -> Native.LIBRARY.find(name), "GetLastError"); } + + NativeCredentialApi(SymbolLookup symbols, String errorName) { + this.symbols = Objects.requireNonNull(symbols); + this.errorName = Objects.requireNonNull(errorName); + } + + @Override public int read(MemorySegment target, MemorySegment result) { + return status("CredReadW", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT, JAVA_INT, ADDRESS), target, 1, 0, result); + } + + @Override public int write(MemorySegment credential) { + return status("CredWriteW", FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT), credential, 0); + } + + @Override public void free(MemorySegment credential) { + var handle = Linker.nativeLinker().downcallHandle(symbols.findOrThrow("CredFree"), FunctionDescriptor.ofVoid(ADDRESS)); + invoke(handle, List.of(credential)); + } + + private int status(String name, FunctionDescriptor descriptor, Object... arguments) { + // GetLastErrorを後から別呼出で読むとJVMに上書きされ得るため、downcall直後の状態を捕捉する。 + var handle = Linker.nativeLinker().downcallHandle(symbols.findOrThrow(name), descriptor, Linker.Option.captureCallState(errorName)); + var layout = Linker.Option.captureStateLayout(); + try (var arena = Arena.ofConfined()) { + var state = arena.allocate(layout); + var values = new ArrayList(); + values.add(state); + values.addAll(List.of(arguments)); + if ((int) invoke(handle, values) != 0) return 0; + var code = state.get(JAVA_INT, layout.byteOffset(MemoryLayout.PathElement.groupElement(errorName))); + return code == 0 ? -1 : code; + } + } + + private static Object invoke(MethodHandle handle, List arguments) { + try { return handle.invokeWithArguments(arguments); } + catch (RuntimeException | Error failure) { throw failure; } + catch (Throwable failure) { throw new KeyManagerException("OS credential function failed", failure); } + } + } + + private static final class Native { + private static final SymbolLookup LIBRARY = systemLibrary(); + + private static SymbolLookup systemLibrary() { + var root = System.getenv("SystemRoot"); + if (root == null || root.isBlank()) throw new KeyManagerException("Windows system directory unavailable"); + return SymbolLookup.libraryLookup(Path.of(root, "System32", "Advapi32.dll"), Arena.global()); + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/service/ApplicationShutdown.java b/src/main/java/com/github/k7t3/tcv/app/service/ApplicationShutdown.java new file mode 100644 index 0000000..19c894f --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/service/ApplicationShutdown.java @@ -0,0 +1,90 @@ +package com.github.k7t3.tcv.app.service; + +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; + +/** UI の終了準備、バックグラウンドでの解放、UI の終了通知を順に実行する。 */ +public final class ApplicationShutdown { + + private final Executor worker; + private final Executor ui; + private final Runnable prepare; + private final Runnable release; + private final Runnable exit; + private final CompletableFuture completion = new CompletableFuture<>(); + private final CompletionStage result = completion.minimalCompletionStage(); + private final CompletableFuture released = new CompletableFuture<>(); + private final CompletionStage releasedResult = released.minimalCompletionStage(); + private boolean requested; + + /** + * @param worker 解放処理用。解放対象のワーカーとは別の executor を使用すること + * @param ui UI スレッドへ処理を送る executor + * @param prepare 呼び出し元 UI スレッドで行う終了準備 + * @param release バックグラウンドで行うリソースの解放 + * @param exit 解放後に UI スレッドで行うアプリケーション終了 + */ + public ApplicationShutdown(Executor worker, Executor ui, Runnable prepare, Runnable release, Runnable exit) { + this.worker = Objects.requireNonNull(worker); + this.ui = Objects.requireNonNull(ui); + this.prepare = Objects.requireNonNull(prepare); + this.release = Objects.requireNonNull(release); + this.exit = Objects.requireNonNull(exit); + } + + /** + * UI スレッドから終了を要求する。同じインスタンスへの要求は一度だけ実行する。 + * 処理または executor への投入に失敗した場合、返す stage は例外で完了する。 + */ + public synchronized CompletionStage request() { + if (requested) return result; + requested = true; + var preparationFailure = invoke(prepare, null); + try { + worker.execute(() -> finishOnUi(invoke(release, preparationFailure))); + } catch (RuntimeException | Error failure) { + // 専用スレッドを作成できなくても、所有リソースの解放は省略しない。 + finishOnUi(invoke(release, append(preparationFailure, failure))); + } + return result; + } + + private void finishOnUi(Throwable previous) { + if (previous == null) released.complete(null); + else released.completeExceptionally(previous); + try { + ui.execute(() -> { + complete(invoke(exit, previous)); + }); + } catch (RuntimeException | Error failure) { + complete(append(previous, failure)); + } + } + + /** UI の終了通知を待たず、リソースの解放処理までの完了を返す。 */ + public CompletionStage resourcesReleased() { + return releasedResult; + } + + private void complete(Throwable failure) { + if (failure == null) completion.complete(null); + else completion.completeExceptionally(failure); + } + + private static Throwable invoke(Runnable action, Throwable previous) { + try { + action.run(); + } catch (RuntimeException | Error failure) { + return append(previous, failure); + } + return previous; + } + + private static Throwable append(Throwable previous, Throwable failure) { + if (previous == null) return failure; + if (previous != failure) previous.addSuppressed(failure); + return previous; + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/service/AsyncCommand.java b/src/main/java/com/github/k7t3/tcv/app/service/AsyncCommand.java deleted file mode 100644 index 78b4c43..0000000 --- a/src/main/java/com/github/k7t3/tcv/app/service/AsyncCommand.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2024 k7t3 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.github.k7t3.tcv.app.service; - -import de.saxsys.mvvmfx.utils.commands.Command; -import javafx.beans.property.BooleanProperty; -import javafx.beans.property.ReadOnlyBooleanProperty; -import javafx.beans.property.ReadOnlyBooleanWrapper; -import javafx.beans.property.SimpleBooleanProperty; -import javafx.concurrent.Service; -import javafx.concurrent.Task; - -import java.util.concurrent.Callable; - -public class AsyncCommand extends Service implements Command { - - private final BooleanProperty executable = new SimpleBooleanProperty(false); - private final ReadOnlyBooleanWrapper notExecutable = new ReadOnlyBooleanWrapper(false); - private final ReadOnlyBooleanWrapper notRunning = new ReadOnlyBooleanWrapper(false); - - private final Callable callable; - - public AsyncCommand(Callable callable) { - this.callable = callable; - notExecutable.bind(executable); - notRunning.bind(runningProperty()); - setExecutor(TaskWorker.getInstance().getExecutor()); - } - - @Override - public void execute() { - if (isNotExecutable()) throw new IllegalStateException("not executable"); - if (isRunning()) throw new IllegalStateException("running"); - restart(); - } - - @Override - public boolean isExecutable() { return executable.get(); } - @Override - public ReadOnlyBooleanProperty executableProperty() { return executable; } - @Override - public boolean isNotExecutable() { return notExecutable.get(); } - @Override - public ReadOnlyBooleanProperty notExecutableProperty() { return notExecutable.getReadOnlyProperty(); } - @Override - public boolean isNotRunning() { return super.isRunning(); } - @Override - public ReadOnlyBooleanProperty notRunningProperty() { return notRunning.getReadOnlyProperty(); } - - @Override - protected Task createTask() { - return new FXTask<>() { - @Override - protected T call() throws Exception { - return callable.call(); - } - }; - } -} diff --git a/src/main/java/com/github/k7t3/tcv/app/service/BrowserActions.java b/src/main/java/com/github/k7t3/tcv/app/service/BrowserActions.java new file mode 100644 index 0000000..c963ede --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/service/BrowserActions.java @@ -0,0 +1,111 @@ +package com.github.k7t3.tcv.app.service; + +import com.github.k7t3.tcv.lifecycle.CloseActions; +import java.awt.Desktop; +import java.net.URI; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.function.Consumer; + +/** 一つの画面・モデルが開始するブラウザ操作を所有する。入力は FX 上で固定する。 */ +public final class BrowserActions implements AutoCloseable { + @FunctionalInterface interface Opener { boolean open(URI uri) throws Exception; } + private final Executor executor; + private final Consumer> tracker; + private final Consumer errors; + private final Opener opener; + private final Set pending = new HashSet<>(); + private volatile boolean closed; + private volatile long generation; + + public BrowserActions(Executor executor, Consumer> tracker, Consumer errors) { + this(executor, tracker, errors, uri -> { + var desktop = Desktop.getDesktop(); + if (!desktop.isSupported(Desktop.Action.BROWSE)) return false; + desktop.browse(uri); + return true; + }); + } + + BrowserActions(Executor executor, Consumer> tracker, Consumer errors, Opener opener) { + this.executor = Objects.requireNonNull(executor); + this.tracker = Objects.requireNonNull(tracker); + this.errors = Objects.requireNonNull(errors); + this.opener = Objects.requireNonNull(opener); + } + + public FXTask open(String url) { return openAll(List.of(url)); } + + public FXTask openAll(List urls) { + if (closed) throw new IllegalStateException("browser actions are closed"); + var links = List.copyOf(urls).stream().map(URI::create).toList(); + var opening = new Opening(links); + pending.add(opening); + opening.worker.cancelWhenCancelled(opening.result); + opening.result.cancelWhenCancelled(opening.worker); + opening.result.onFailure(failure -> { if (opening.isCurrent()) errors.accept(failure); }); + opening.result.setFinally(() -> { pending.remove(opening); opening.worker.cancel(true); }); + opening.worker.onDone(value -> { opening.value = value; opening.result.run(); }); + opening.worker.onFailure(failure -> { opening.failure = failure; opening.result.run(); }); + try { + tracker.accept(opening.drained.minimalCompletionStage()); + executor.execute(() -> { + try { opening.worker.run(); } + finally { opening.drained.complete(null); } + }); + } catch (RuntimeException | Error failure) { + opening.failure = failure; + opening.result.run(); + opening.worker.cancel(true); + opening.drained.complete(null); + } + return opening.result; + } + + /** 現在の操作を取り消す。次のログイン等で同じ所有者を再利用できる。 */ + public void cancelAll() { + generation++; + var owned = List.copyOf(pending); + pending.clear(); + CloseActions.runAll(owned.stream().map(opening -> (Runnable) () -> opening.result.cancel(true)).toArray(Runnable[]::new)); + } + + @Override public void close() { + if (closed) return; + closed = true; + cancelAll(); + } + + private final class Opening { + final long token = generation; + final CompletableFuture drained = new CompletableFuture<>(); + final FXTask worker; + final FXTask result; + Boolean value; + Throwable failure; + Opening(List links) { + worker = FXTask.task(() -> { + boolean supported = true; + for (var uri : links) { + if (closed || generation != token || isCancelled() || Thread.currentThread().isInterrupted()) throw new CancellationException("browser scope ended"); + supported &= opener.open(uri); + } + return supported; + }); + result = FXTask.observation(() -> { + if (!isCurrent()) throw new CancellationException("browser opening was retired"); + if (failure instanceof Error error) throw error; + if (failure instanceof Exception exception) throw exception; + return value; + }); + } + boolean isCancelled() { return result.isCancelled(); } + boolean isCurrent() { return !closed && generation == token && pending.contains(this) && !result.isCancelled(); } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/service/CachedImageStore.java b/src/main/java/com/github/k7t3/tcv/app/service/CachedImageStore.java index d2a2710..69dbf7b 100644 --- a/src/main/java/com/github/k7t3/tcv/app/service/CachedImageStore.java +++ b/src/main/java/com/github/k7t3/tcv/app/service/CachedImageStore.java @@ -18,32 +18,99 @@ import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; +import com.github.k7t3.tcv.lifecycle.CloseActions; import com.github.k7t3.tcv.app.image.LazyImage; -import javafx.scene.image.Image; import org.jetbrains.annotations.Nullable; import java.time.Duration; +import java.util.HashSet; import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; -public abstract class CachedImageStore { +/** 画像の再利用を管理する。所有者はセッション終了時に閉じる。 */ +public abstract class CachedImageStore implements AutoCloseable { private final LoadingCache images; + private final ConcurrentHashMap> pendingImages = new ConcurrentHashMap<>(); + private boolean closed; public CachedImageStore(int maxCount, Duration expire) { images = Caffeine.newBuilder() .maximumSize(maxCount) .expireAfterAccess(expire) - .build(this::loadImage); + .build(this::loadOwnedImage); } protected abstract @Nullable LazyImage loadImage(K key); - public LazyImage get(K key) { - return images.get(key); + private @Nullable LazyImage loadOwnedImage(K key) { + var image = loadImage(key); + if (image != null) { + pendingImages.compute(key, (ignored, pending) -> { + if (pending == null) pending = ConcurrentHashMap.newKeySet(); + pending.add(image); + return pending; + }); + image.completion().whenComplete((result, failure) -> pendingImages.computeIfPresent(key, (ignored, pending) -> { + pending.remove(image); + return pending.isEmpty() ? null : pending; + })); + } + return image; + } + + /** + * 画像を取得する。対応する画像がない場合は null。 + * @param key 画像の識別子 + * @return 同じキーで再利用する画像 + * @throws IllegalStateException このストアが終了している場合 + */ + public @Nullable LazyImage get(K key) { + synchronized (images) { + if (closed) throw new IllegalStateException("image store is closed"); + var image = images.get(key); + if (closed) { + invalidate(key); + throw new IllegalStateException("image store is closed"); + } + return image; + } } public Optional getNullable(K key) { - return Optional.ofNullable(images.get(key)); + return Optional.ofNullable(get(key)); + } + + /** 指定したキーの画像を解放し、次回の取得で読み直す。 */ + public void invalidate(K key) { + final Set owned = new HashSet<>(); + synchronized (images) { + var pending = pendingImages.remove(key); + if (pending != null) owned.addAll(pending); + var cached = images.getIfPresent(key); + if (cached != null) owned.add(cached); + images.invalidate(key); + } + CloseActions.runAll(owned.stream().map(image -> (Runnable) image::close).toArray(Runnable[]::new)); + } + + /** キャッシュが所有する画像の読込を一度だけ取り消す。表示済みの画像は保持される。 */ + @Override + public void close() { + final Runnable[] releases; + synchronized (images) { + if (closed) return; + closed = true; + var owned = new HashSet(); + pendingImages.values().forEach(owned::addAll); + owned.addAll(images.asMap().values()); + pendingImages.clear(); + releases = owned.stream() + .map(image -> (Runnable) image::close).toArray(Runnable[]::new); + images.invalidateAll(); + } + CloseActions.runAll(releases); } } diff --git a/src/main/java/com/github/k7t3/tcv/app/service/FXTask.java b/src/main/java/com/github/k7t3/tcv/app/service/FXTask.java index 0869270..7839b72 100644 --- a/src/main/java/com/github/k7t3/tcv/app/service/FXTask.java +++ b/src/main/java/com/github/k7t3/tcv/app/service/FXTask.java @@ -17,17 +17,67 @@ package com.github.k7t3.tcv.app.service; import javafx.concurrent.Task; +import javafx.concurrent.Worker; import javafx.concurrent.WorkerStateEvent; import javafx.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.*; +import java.util.Objects; +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; import java.util.function.Consumer; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; public abstract class FXTask extends Task { private static final Logger LOGGER = LoggerFactory.getLogger(FXTask.class); + private final CompletableFuture completion = new CompletableFuture<>(); + + /** + * FX イベント配送に依存しない Future の終端通知。通知先は FX スレッドとは限らない。 + * 観測側の取消・完了操作はこのタスクに作用しない。タスクの取消は call() 内の + * I/O の終了を意味しないため、実行中の処理の解放には所有 executor の終了待ちも必要。 + */ + public final CompletionStage completion() { + return completion.minimalCompletionStage(); + } + + /** + * 借用タスクの取消だけを、FXイベント配送を待たず自身へ伝える。 + * cancel(true)を要求するが、observationの非割込み方針は維持する。 + * 成功・失敗・逆方向の取消は伝播しない。call内のI/O終了も意味しない。 + * 自身の終端後は、観測元の通知から自身への参照を保持し続けない。 + * @param source 取消を観測するタスク + */ + public final void cancelWhenCancelled(FXTask source) { + Objects.requireNonNull(source); + var target = new AtomicReference>(this); + completion().whenComplete((ignored, failure) -> target.set(null)); + source.completion().whenComplete((ignored, failure) -> { + if (!source.isCancelled()) return; + var observer = target.get(); + if (observer != null) observer.cancel(true); + }); + } + + @Override + protected final void done() { + try { + completion.complete(get()); + } catch (ExecutionException failure) { + completion.completeExceptionally(failure.getCause()); + } catch (CancellationException cancelled) { + completion.completeExceptionally(cancelled); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + completion.completeExceptionally(interrupted); + } + } @Override protected void failed() { @@ -37,54 +87,69 @@ protected void failed() { } public FXTask onDone(Consumer consumer) { - addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, e -> consumer.accept(getValue())); + if (getState() == Worker.State.SUCCEEDED) consumer.accept(getValue()); + else addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, e -> consumer.accept(getValue())); return this; } public FXTask onDone(Runnable runnable) { - addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, e -> runnable.run()); - return this; + return onDone(ignored -> runnable.run()); } - public void waitForDone() { - if (state() != Future.State.RUNNING) - return; - try { - get(20, TimeUnit.SECONDS); - } catch (InterruptedException | ExecutionException | TimeoutException e) { - LOGGER.warn("failed to await for done", e); - } + /** FX スレッドで失敗を受け取る。取消は失敗とせず、完了後の登録にも対応する。 */ + public FXTask onFailure(Consumer consumer) { + if (getState() == Worker.State.FAILED) consumer.accept(getException()); + else addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, event -> consumer.accept(getException())); + return this; } public void setFinally(Runnable runnable) { - EventHandler handler = e -> runnable.run(); + var called = new AtomicBoolean(); + Runnable once = () -> { + if (called.compareAndSet(false, true)) runnable.run(); + }; + EventHandler handler = e -> once.run(); addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, handler); addEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, handler); addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, handler); + var state = getState(); + if (state == Worker.State.SUCCEEDED || state == Worker.State.FAILED || state == Worker.State.CANCELLED) { + once.run(); + } } - public FXTask runAsync() { - TaskWorker.getInstance().submit(this); - return this; + public static FXTask task(Callable callable) { + return create(callable, true); } - public static FXTask task(Callable callable) { + /** + * 別途所有する処理の結果だけを返す。取消は Future を終端にするが、結果を返す + * ワーカーや FX スレッドを割り込まない。実処理の終了は所有者が別途追跡する。 + */ + public static FXTask observation(Callable publication) { + return create(publication, false); + } + + private static FXTask create(Callable callable, boolean interruptible) { return new FXTask<>() { + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return super.cancel(interruptible && mayInterruptIfRunning); + } + @Override protected T call() throws Exception { - return callable.call(); + try { return callable.call(); } + catch (CancellationException cancelled) { + cancel(false); + return null; + } } }; } public static FXTask task(Runnable runnable) { - return new FXTask<>() { - @Override - protected Void call() { - runnable.run(); - return null; - } - }; + return task(() -> { runnable.run(); return null; }); } public static FXTask empty() { diff --git a/src/main/java/com/github/k7t3/tcv/app/service/FXTaskGroup.java b/src/main/java/com/github/k7t3/tcv/app/service/FXTaskGroup.java new file mode 100644 index 0000000..6c25677 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/service/FXTaskGroup.java @@ -0,0 +1,90 @@ +package com.github.k7t3.tcv.app.service; + +import java.util.Collection; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletionException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; + +/** FX で開始する複数の処理について、すべての Future の終端と失敗を回収する。 */ +public final class FXTaskGroup { + private FXTaskGroup() {} + + /** + * task の取消は子の処理へ伝播しない。settled はその取消後も全件の終端を待ち、 + * 実際の失敗を保持する。取消だけの場合の settled は正常完了する。 + * 子が取消された時点で I/O が終了したとは限らないため、executor の終了待ちも必要。 + */ + public record Batch(FXTask task, CompletionStage settled) {} + + /** + * 呼び出しスレッド上で全件の開始を試みる。開始中の失敗でも後続を中断しない。 + * 完了の監視は FX イベントや追加の executor スロットを使わない。 + */ + public static Batch startAll(Collection items, Function> starter) { + var snapshot = List.copyOf(items); + Objects.requireNonNull(starter); + var collector = new Collector(snapshot.size()); + for (int i = 0; i < snapshot.size(); i++) { + int index = i; + try { + var task = Objects.requireNonNull(starter.apply(snapshot.get(i)), "starter returned no task"); + task.completion().whenComplete((ignored, failure) -> collector.completed(index, failure)); + } catch (RuntimeException | Error failure) { + collector.completed(index, failure); + } + } + if (snapshot.isEmpty()) collector.finish(); + return new Batch(collector.task, collector.settled.minimalCompletionStage()); + } + + private static final class Collector { + private final Throwable[] outcomes; + private final AtomicInteger remaining; + private final CompletableFuture settled = new CompletableFuture<>(); + private final FXTask task = FXTask.observation(this::result); + private Throwable failure; + private boolean cancelled; + + Collector(int size) { + outcomes = new Throwable[size]; + remaining = new AtomicInteger(size); + } + + void completed(int index, Throwable error) { + while (error instanceof CompletionException && error.getCause() != null) error = error.getCause(); + outcomes[index] = error; + if (remaining.decrementAndGet() == 0) finish(); + } + + void finish() { + var seen = Collections.newSetFromMap(new IdentityHashMap()); + for (var outcome : outcomes) { + if (outcome instanceof CancellationException) cancelled = true; + else if (outcome != null && seen.add(outcome)) { + if (failure == null) { + failure = outcome; + Collections.addAll(seen, failure.getSuppressed()); + } else failure.addSuppressed(outcome); + } + } + task.run(); + if (failure == null) settled.complete(null); + else settled.completeExceptionally(failure); + } + + private Void result() throws Exception { + if (failure instanceof Exception exception) throw exception; + if (failure instanceof Error error) throw error; + if (failure != null) throw new IllegalStateException(failure); + if (cancelled) throw new CancellationException("a child task was cancelled"); + return null; + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/service/LiveStateNotificator.java b/src/main/java/com/github/k7t3/tcv/app/service/LiveStateNotificator.java index 425ceee..3462e5a 100644 --- a/src/main/java/com/github/k7t3/tcv/app/service/LiveStateNotificator.java +++ b/src/main/java/com/github/k7t3/tcv/app/service/LiveStateNotificator.java @@ -18,92 +18,229 @@ import com.github.k7t3.tcv.app.channel.ChannelViewModelRepository; import com.github.k7t3.tcv.app.channel.TwitchChannelViewModel; -import com.github.k7t3.tcv.app.model.AbstractViewModel; import com.github.k7t3.tcv.app.event.LiveNotificationEvent; +import com.github.k7t3.tcv.app.event.ChatOpeningEvent; +import com.github.k7t3.tcv.app.model.AbstractViewModel; import com.github.k7t3.tcv.app.reactive.DownCastFXSubscriber; +import com.github.k7t3.tcv.domain.channel.ChannelRepository; +import com.github.k7t3.tcv.domain.channel.TwitchChannel; import com.github.k7t3.tcv.domain.event.EventSubscribers; -import com.github.k7t3.tcv.domain.event.channel.ChannelOfflineEvent; -import com.github.k7t3.tcv.domain.event.channel.ChannelOnlineEvent; -import com.github.k7t3.tcv.domain.event.channel.TwitchChannelEvent; -import com.github.k7t3.tcv.reactive.FlowableSubscriber; +import com.github.k7t3.tcv.domain.event.channel.*; +import com.github.k7t3.tcv.lifecycle.CloseActions; import javafx.collections.FXCollections; import javafx.collections.ObservableList; - +import javafx.concurrent.Worker; +import javafx.concurrent.WorkerStateEvent; +import javafx.event.EventHandler; import java.time.LocalTime; import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CancellationException; import java.util.LinkedList; import java.util.List; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +/** 通知の履歴と共有取得の観測を所有する。実際のチャンネル取得はリポジトリが所有する。 */ public class LiveStateNotificator extends AbstractViewModel { - private static final int RECORD_COUNT = 40; - public record LiveStateRecord(TwitchChannelViewModel channel, LocalTime time, boolean live) {} + private record Notice(TwitchChannel source, ChannelRepository owner, long generation, boolean live) {} private final ObservableList records = FXCollections.observableList(new LinkedList<>()); + private final ObservableList readOnlyRecords = FXCollections.unmodifiableObservableList(records); + private final IdentityHashMap, Lookup> lookups = new IdentityHashMap<>(); + private final Map openings = new HashMap<>(); private final ChannelViewModelRepository repository; - private final List> subscribers = new ArrayList<>(); + private final Consumer failures; + private long generation; - public LiveStateNotificator(ChannelViewModelRepository repository) { + public LiveStateNotificator(ChannelViewModelRepository repository, Consumer failures) { this.repository = repository; + this.failures = failures; } - private void push(LiveStateRecord record) { - int over = (records.size() + 1) - RECORD_COUNT; - if (0 < over) { - for (int i = 0; i < over; i++) - records.removeFirst(); - } - records.add(record); + public ObservableList getRecords() { return readOnlyRecords; } - // イベントを発行 - publish(new LiveNotificationEvent(record)); + public boolean canOpen(LiveStateRecord record) { + return !isClosed() && record != null && record.live() && repository.getRepository() != null + && records.stream().anyMatch(current -> current == record); } - public ObservableList getRecords() { - return records; + /** 履歴の旧モデルを使わず、現在の取得元から取得してチャットを開く。 */ + public FXTask openChannelAsync(LiveStateRecord record) { + if (!canOpen(record)) { + var cancelled = FXTask.observation(() -> null); + cancelled.cancel(false); + return cancelled; + } + var broadcaster = record.channel().getBroadcaster(); + var existing = openings.get(broadcaster.getUserId()); + if (existing != null && !existing.result.isDone()) return existing.result; + var opening = new Opening(broadcaster.getUserId(), repository.getRepository(), generation); + openings.put(opening.id, opening); + opening.result.setFinally(opening::detach); + try { + var task = repository.getChannelAsync(broadcaster); + if (!opening.isCurrent()) { opening.result.cancel(false); return opening.result; } + var lookup = lookup(task); + opening.lookup = lookup; + lookup.openings.add(opening); + lookup.attach(); + opening.result.cancelWhenCancelled(task); + } catch (RuntimeException | Error failure) { + opening.complete(null, failure); + if (opening.isCurrent()) failures.accept(failure); + } + return opening.result; } - @Override - public void subscribeEvents(EventSubscribers eventSubscribers) { - var onlineSub = new DownCastFXSubscriber(ChannelOnlineEvent.class, this::onOnlineEvent); - var offlineSub = new DownCastFXSubscriber(ChannelOfflineEvent.class, this::onOfflineEvent); - eventSubscribers.subscribeChannelEvent(onlineSub); - eventSubscribers.subscribeChannelEvent(offlineSub); - subscribers.addAll(List.of(onlineSub, offlineSub)); + private Lookup lookup(FXTask task) { + var lookup = lookups.get(task); + if (lookup == null) { lookup = new Lookup(task); lookups.put(task, lookup); } + return lookup; } - private void onOnlineEvent(ChannelOnlineEvent e) { - var broadcaster = e.getChannel().getBroadcaster(); - repository.getChannelAsync(broadcaster).onDone(channel -> { - var time = LocalTime.now(); - var record = new LiveStateRecord(channel, time, true); - push(record); - }); + @Override protected void onSubscribeEvents(EventSubscribers events, SessionSubscriptions subscriptions) { + generation++; + var online = subscriptions.own(new DownCastFXSubscriber(ChannelOnlineEvent.class, + event -> request(event.getChannel(), true))); + var offline = subscriptions.own(new DownCastFXSubscriber(ChannelOfflineEvent.class, + event -> request(event.getChannel(), false))); + events.subscribeChannelEvent(online); + events.subscribeChannelEvent(offline); } - private void onOfflineEvent(ChannelOfflineEvent e) { - var broadcaster = e.getChannel().getBroadcaster(); - repository.getChannelAsync(broadcaster).onDone(channel -> { - var time = LocalTime.now(); - var record = new LiveStateRecord(channel, time, false); - push(record); - }); + private boolean isCurrent(Notice notice) { + return !isClosed() && generation == notice.generation() && repository.getRepository() == notice.owner() + && notice.source().isActiveIn(notice.owner()); } - @Override - public void onLogout() { - for (var sub : subscribers) - sub.cancel(); - subscribers.clear(); - records.clear(); + private void request(TwitchChannel source, boolean live) { + var notice = new Notice(source, repository.getRepository(), generation, live); + if (!isCurrent(notice)) return; + try { + var task = repository.getChannelAsync(source.getBroadcaster()); + if (!isCurrent(notice)) return; + var lookup = lookup(task); + lookup.notices.add(notice); + lookup.attach(); + } catch (RuntimeException | Error failure) { + if (isCurrent(notice)) failures.accept(failure); + } } - @Override - public void close() { - for (var sub : subscribers) - sub.cancel(); - subscribers.clear(); + private void push(LiveStateRecord record, BooleanSupplier current) { + if (!current.getAsBoolean()) return; + while (records.size() >= RECORD_COUNT) { + if (!current.getAsBoolean()) return; + records.removeFirst(); + } + if (!current.getAsBoolean()) return; + records.add(record); + if (current.getAsBoolean()) publish(new LiveNotificationEvent(record)); } + private void endScope() { + generation++; + var owned = List.copyOf(lookups.values()); + var opening = List.copyOf(openings.values()); + lookups.clear(); + openings.clear(); + CloseActions.runAll(() -> CloseActions.runAll(owned.stream().map(lookup -> (Runnable) lookup::close).toArray(Runnable[]::new)), + () -> CloseActions.runAll(opening.stream().map(request -> (Runnable) () -> request.result.cancel(false)).toArray(Runnable[]::new)), records::clear); + } + @Override protected void onLoggedOut() { endScope(); } + @Override protected void onClose() { endScope(); } + + private final class Lookup implements AutoCloseable { + final FXTask task; + final List notices = new ArrayList<>(); + final List openings = new ArrayList<>(); + boolean attached; + final EventHandler completed = event -> finish(event.getEventType()); + boolean finished; + Lookup(FXTask task) { this.task = task; } + void attach() { + if (attached || finished) return; + attached = true; + task.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, completed); + task.addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, completed); + task.addEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, completed); + var state = task.getState(); + if (state == Worker.State.SUCCEEDED) finish(WorkerStateEvent.WORKER_STATE_SUCCEEDED); + else if (state == Worker.State.FAILED) finish(WorkerStateEvent.WORKER_STATE_FAILED); + else if (state == Worker.State.CANCELLED) finish(WorkerStateEvent.WORKER_STATE_CANCELLED); + } + void finish(javafx.event.EventType type) { + if (finished) return; + var pending = List.copyOf(notices); + var opening = List.copyOf(openings); + close(); + if (type == WorkerStateEvent.WORKER_STATE_FAILED) { + var failure = task.getException(); + opening.forEach(request -> request.complete(null, failure)); + if (pending.stream().anyMatch(LiveStateNotificator.this::isCurrent) || opening.stream().anyMatch(Opening::isCurrent)) failures.accept(failure); + return; + } + if (type != WorkerStateEvent.WORKER_STATE_SUCCEEDED) { + opening.forEach(request -> request.result.cancel(false)); + return; + } + var channel = task.getValue(); + for (var notice : pending) { + BooleanSupplier current = () -> isCurrent(notice) && channel != null + && channel.getChannel() == notice.source() && !channel.isRetiring(); + if (current.getAsBoolean()) push(new LiveStateRecord(channel, LocalTime.now(), notice.live()), current); + } + opening.forEach(request -> request.complete(channel, null)); + } + @Override public void close() { + if (finished) return; + finished = true; + lookups.remove(task, this); + task.removeEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, completed); + task.removeEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, completed); + task.removeEventHandler(WorkerStateEvent.WORKER_STATE_CANCELLED, completed); + notices.clear(); + openings.forEach(request -> request.lookup = null); + openings.clear(); + } + } + + private final class Opening { + final String id; + final ChannelRepository owner; + final long token; + Lookup lookup; + TwitchChannelViewModel channel; + Throwable failure; + final FXTask result = FXTask.observation(() -> publishOpening()); + Opening(String id, ChannelRepository owner, long token) { this.id = id; this.owner = owner; this.token = token; } + boolean isCurrent() { + return !isClosed() && generation == token && repository.getRepository() == owner + && openings.get(id) == this && !result.isCancelled(); + } + TwitchChannelViewModel publishOpening() throws Exception { + if (!isCurrent()) throw new CancellationException("history opening was retired"); + if (failure instanceof Error error) throw error; + if (failure instanceof Exception exception) throw exception; + if (channel == null || channel.isRetiring() || !channel.isLive() || !channel.getChannel().isActiveIn(owner) + || !channel.getBroadcaster().getUserId().equals(id)) return null; + publish(new ChatOpeningEvent(channel)); + return channel; + } + void complete(TwitchChannelViewModel value, Throwable failure) { + channel = value; this.failure = failure; result.run(); + } + void detach() { + openings.remove(id, this); + if (lookup != null) { + var owned = lookup; lookup = null; owned.openings.remove(this); + if (owned.notices.isEmpty() && owned.openings.isEmpty()) owned.close(); + } + } + } } diff --git a/src/main/java/com/github/k7t3/tcv/app/service/SerialIoQueue.java b/src/main/java/com/github/k7t3/tcv/app/service/SerialIoQueue.java new file mode 100644 index 0000000..185487b --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/service/SerialIoQueue.java @@ -0,0 +1,113 @@ +package com.github.k7t3.tcv.app.service; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Objects; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; + +/** + * I/O を受付順に実行する。通常は借用 executor を使い、未開始ポンプを待つ背景読取は + * 独立した仮想スレッドへ引き継ぐ。読取元は実完了まで待ち、書込は返却 stage で追跡する。 + * 観測の取消では受付済み処理を取り消さない。 + */ +public final class SerialIoQueue { + private final Object lock = new Object(); + private final Executor executor; + private final ArrayDeque> jobs = new ArrayDeque<>(); + private Thread drainer; + private boolean scheduled; + private boolean independentScheduled; + + public SerialIoQueue(Executor executor) { this.executor = Objects.requireNonNull(executor); } + + public CompletionStage submit(Callable action) { + var job = new Job<>(action); + final boolean start; + synchronized (lock) { + jobs.add(job); + start = drainer == null && !scheduled; + if (start) scheduled = true; + } + if (start) { + try { executor.execute(this::drainPending); } + catch (RuntimeException | Error failure) { rejectWaiting(failure); } + } + return job.result.minimalCompletionStage(); + } + + /** + * 実行元は専用のポンプ。取消可能な読取タスクのスレッドでは書込を実行しない。 + */ + private void drainPending() { + synchronized (lock) { + if (drainer != null) return; + drainer = Thread.currentThread(); + scheduled = false; + independentScheduled = false; + } + while (true) { + final Job job; + synchronized (lock) { + job = jobs.poll(); + if (job == null) { + drainer = null; + return; + } + } + job.run(); + } + } + + /** FX 以外の読取元から、受付済み書込に続けて読み取る。I/O 処理内からの自己待機は拒否する。 */ + public T call(Callable action) { + var job = new Job<>(action); + final boolean start; + synchronized (lock) { + if (drainer == Thread.currentThread()) throw new IllegalStateException("reentrant serial I/O read"); + jobs.add(job); + start = drainer == null && !independentScheduled; + if (start) { + scheduled = true; + independentScheduled = true; + } + } + if (start) { + // 同じ単一 executor の未開始ポンプを待つ場合も、読取の取消を保存へ伝播させない。 + try { Thread.ofVirtual().name("TCV-Serial-Io-Read").start(this::drainPending); } + catch (RuntimeException | Error failure) { rejectWaiting(failure); } + } + // 取消で戻ると未完了の読取を所有者が見失う。実処理の終端まで待ち、割込状態は保持する。 + try { return job.result.join(); } + catch (CompletionException failure) { + if (failure.getCause() instanceof RuntimeException exception) throw exception; + if (failure.getCause() instanceof Error error) throw error; + throw new IllegalStateException(failure.getCause()); + } + } + + private void rejectWaiting(Throwable failure) { + ArrayList> rejected; + synchronized (lock) { + if (drainer != null) return; + scheduled = false; + independentScheduled = false; + rejected = new ArrayList<>(jobs); + jobs.clear(); + } + rejected.forEach(value -> value.result.completeExceptionally(failure)); + } + + private static final class Job { + final Callable action; + final CompletableFuture result = new CompletableFuture<>(); + Job(Callable action) { this.action = Objects.requireNonNull(action); } + void run() { + try { result.complete(action.call()); } + catch (Throwable failure) { result.completeExceptionally(failure); } + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/service/TaskWorker.java b/src/main/java/com/github/k7t3/tcv/app/service/TaskWorker.java index 26b896c..7ae0515 100644 --- a/src/main/java/com/github/k7t3/tcv/app/service/TaskWorker.java +++ b/src/main/java/com/github/k7t3/tcv/app/service/TaskWorker.java @@ -16,9 +16,6 @@ package com.github.k7t3.tcv.app.service; -import com.github.k7t3.tcv.app.core.ExceptionHandler; -import javafx.concurrent.WorkerStateEvent; - import java.io.Closeable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; @@ -31,12 +28,8 @@ public class TaskWorker implements Closeable { private final ExecutorService executor = Executors.newThreadPerTaskExecutor(factory); - private TaskWorker() { - } - - void submit(FXTask task) { - task.addEventHandler(WorkerStateEvent.WORKER_STATE_FAILED, e -> ExceptionHandler.handle(task.getException())); - executor.submit(task); + /** 独立したワーカーを構築する。所有者が {@link #close()} で終了すること。 */ + public TaskWorker() { } public Executor getExecutor() { @@ -48,12 +41,5 @@ public void close() { executor.close(); } - public static TaskWorker getInstance() { - return Holder.INSTANCE; - } - - private static class Holder { - private static final TaskWorker INSTANCE = new TaskWorker(); - } } diff --git a/src/main/java/com/github/k7t3/tcv/app/service/WindowBoundsService.java b/src/main/java/com/github/k7t3/tcv/app/service/WindowBoundsService.java index bd4d6a3..6d25683 100644 --- a/src/main/java/com/github/k7t3/tcv/app/service/WindowBoundsService.java +++ b/src/main/java/com/github/k7t3/tcv/app/service/WindowBoundsService.java @@ -18,42 +18,155 @@ import com.github.k7t3.tcv.entity.WindowBoundsEntity; import com.github.k7t3.tcv.entity.service.WindowBoundsEntityService; +import com.github.k7t3.tcv.lifecycle.CloseActions; import com.github.k7t3.tcv.view.core.WindowBounds; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executor; +import java.util.function.Consumer; -public class WindowBoundsService { - +/** 確定した座標を受付順に保存する。画面終了や観測取消でも受付済みの書込は完了させる。 */ +public class WindowBoundsService implements AutoCloseable { + private static final Logger LOGGER = LoggerFactory.getLogger(WindowBoundsService.class); + private final Object lifecycle = new Object(); private final WindowBoundsEntityService service; + private final Executor executor; + private final SerialIoQueue io; + private final Consumer> tracker; + private final Consumer failures; + private final Set reads = ConcurrentHashMap.newKeySet(); + private volatile boolean closed; + + public WindowBoundsService(WindowBoundsEntityService service, Executor executor) { + this(service, executor, ignored -> {}); + } - public WindowBoundsService(WindowBoundsEntityService service) { - this.service = service; + public WindowBoundsService(WindowBoundsEntityService service, Executor executor, Consumer> tracker) { + this(service, executor, tracker, failure -> LOGGER.error("window bounds write failed", failure)); } - public FXTask saveBoundsAsync(String identity, WindowBounds bounds) { - var entity = new WindowBoundsEntity(identity, - bounds.x(), bounds.y(), bounds.width(), bounds.height(), bounds.maximized()); - var t = FXTask.task(() -> service.save(entity)); - t.runAsync(); - return t; + WindowBoundsService(WindowBoundsEntityService service, Executor executor, + Consumer> tracker, Consumer failures) { + this.service = Objects.requireNonNull(service); + this.executor = Objects.requireNonNull(executor); + this.tracker = Objects.requireNonNull(tracker); + this.failures = Objects.requireNonNull(failures); + io = new SerialIoQueue(executor); + } + + public FXTask saveBoundsAsync(String identity, WindowBounds bounds) { + var entity = new WindowBoundsEntity(identity, bounds.x(), bounds.y(), bounds.width(), bounds.height(), bounds.maximized()); + var write = new Write(); + synchronized (lifecycle) { + checkOpen(); + try { + tracker.accept(write.drained.minimalCompletionStage()); + io.submit(() -> { service.save(entity); return null; }) + .whenComplete((ignored, failure) -> write.finish(unwrap(failure))); + } catch (RuntimeException | Error failure) { write.finish(failure); } + } + return write.result; } public WindowBounds getBounds(String identity) { - var entity = service.get(identity); - return new WindowBounds(entity.x(), entity.y(), - entity.width(), entity.height(), entity.maximized()); + checkOpen(); + return readBounds(identity); + } + + private WindowBounds readBounds(String identity) { + return io.call(() -> { + var entity = service.get(identity); + return new WindowBounds(entity.x(), entity.y(), entity.width(), entity.height(), entity.maximized()); + }); } + /** 取得失敗の表示は現在の窓が所有する。サービス終了は全ての未採用読取を取り消す。 */ public FXTask getBoundsAsync(String identity) { - var t = FXTask.task(() -> getBounds(identity)); - t.runAsync(); - return t; + final Read read; + synchronized (lifecycle) { + checkOpen(); + read = new Read(identity); + reads.add(read); + read.result.completion().whenComplete((ignored, failure) -> { + reads.remove(read); + if (read.result.isCancelled()) read.worker.cancel(true); + }); + read.worker.completion().whenComplete((value, failure) -> read.finish(value, unwrap(failure))); + } + try { executor.execute(read.worker); } + catch (RuntimeException | Error rejected) { + read.finish(null, rejected); + read.worker.cancel(true); + } + return read.result; } - public void delete(String identity) { - FXTask.task(() -> service.delete(identity)).runAsync(); + private void checkOpen() { + if (closed) throw new IllegalStateException("window bounds service is closed"); } - public void clear() { - FXTask.task(service::clear).runAsync(); + @Override public void close() { + final List owned; + synchronized (lifecycle) { + if (closed) return; + closed = true; + owned = List.copyOf(reads); + reads.clear(); + } + CloseActions.runAll(owned.stream().map(read -> (Runnable) () -> read.result.cancel(true)).toArray(Runnable[]::new)); } + private static Throwable unwrap(Throwable failure) { + while (failure instanceof CompletionException && failure.getCause() != null) failure = failure.getCause(); + return failure; + } + + private static void rethrow(Throwable failure) throws Exception { + if (failure instanceof Error error) throw error; + if (failure instanceof Exception exception) throw exception; + if (failure != null) throw new IllegalStateException(failure); + } + + private final class Write { + final CompletableFuture drained = new CompletableFuture<>(); + Throwable failure; + final FXTask result = FXTask.observation(() -> { rethrow(failure); return null; }); + void finish(Throwable failure) { + this.failure = failure; + try { result.run(); } + finally { + if (failure == null) drained.complete(null); + else { + drained.completeExceptionally(failure); + failures.accept(failure); + } + } + } + } + + private final class Read { + WindowBounds value; + Throwable failure; + final FXTask worker; + final FXTask result = FXTask.observation(() -> { + if (closed) throw new CancellationException("window bounds read was retired"); + rethrow(failure); + return value; + }); + Read(String identity) { worker = FXTask.task(() -> readBounds(identity)); } + void finish(WindowBounds value, Throwable failure) { + if (closed || failure instanceof CancellationException) { result.cancel(false); return; } + this.value = value; + this.failure = failure; + result.run(); + } + } } diff --git a/src/main/java/com/github/k7t3/tcv/app/theme/JapaneseFonts.java b/src/main/java/com/github/k7t3/tcv/app/theme/JapaneseFonts.java new file mode 100644 index 0000000..2a6de09 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/app/theme/JapaneseFonts.java @@ -0,0 +1,39 @@ +package com.github.k7t3.tcv.app.theme; + +import javafx.scene.text.Font; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** 画面とチャットの既定書体を、JavaFX が利用できるフォントから選ぶ。 */ +public final class JapaneseFonts { + + private static final String HIRAGINO = "Hiragino Sans"; + + private JapaneseFonts() {} + + /** ヒラギノ角ゴシックが利用できる場合はそのファミリー名を、それ以外は JavaFX の既定書体名を返す。 */ + public static String defaultDisplayFamily() { + return selectHiragino(Font.getFamilies()).orElseGet(() -> Font.getDefault().getFamily()); + } + + static Optional selectHiragino(List families) { + return families.contains(HIRAGINO) ? Optional.of(HIRAGINO) : Optional.empty(); + } + + static String themeStylesheet(String themeStylesheet) { + var displayFamily = selectHiragino(Font.getFamilies()); + if (displayFamily.isEmpty()) return themeStylesheet; + + var themeUrl = Objects.requireNonNull(JapaneseFonts.class.getResource(themeStylesheet), themeStylesheet); + // JavaFX 27.0.1 ではバイナリ CSS の @import に失敗するため、フラグメントを付けてテキスト版を読む。 + var css = """ + @import "%s#stylesheet"; + .root { -fx-font-family: "%s"; } + """.formatted(themeUrl.toExternalForm(), displayFamily.get()); + return "data:text/css;charset=UTF-8," + URLEncoder.encode(css, StandardCharsets.UTF_8).replace("+", "%20"); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/app/theme/Theme.java b/src/main/java/com/github/k7t3/tcv/app/theme/Theme.java index e75b92a..6adfa4b 100644 --- a/src/main/java/com/github/k7t3/tcv/app/theme/Theme.java +++ b/src/main/java/com/github/k7t3/tcv/app/theme/Theme.java @@ -69,7 +69,8 @@ void applyTheme(Scene scene, ThemeType type, boolean withAnimation) { } var theme = themes.get(type); - Application.setUserAgentStylesheet(Objects.requireNonNull(theme.getUserAgentStylesheet())); + Application.setUserAgentStylesheet(JapaneseFonts.themeStylesheet( + Objects.requireNonNull(theme.getUserAgentStylesheet()))); scene.getRoot().pseudoClassStateChanged(DARK, theme.isDarkMode()); } diff --git a/src/main/java/com/github/k7t3/tcv/app/theme/ThemeManager.java b/src/main/java/com/github/k7t3/tcv/app/theme/ThemeManager.java index c82cdb6..d7c5f50 100644 --- a/src/main/java/com/github/k7t3/tcv/app/theme/ThemeManager.java +++ b/src/main/java/com/github/k7t3/tcv/app/theme/ThemeManager.java @@ -17,17 +17,19 @@ package com.github.k7t3.tcv.app.theme; import com.github.k7t3.tcv.app.core.OS; +import java.util.Objects; import javafx.application.ColorScheme; import javafx.application.Platform; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ObjectPropertyBase; import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; import javafx.scene.Scene; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // AtlantaFX samplerアプリケーションを参照 -public class ThemeManager { +public class ThemeManager implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(ThemeManager.class); @@ -85,35 +87,44 @@ public String getName() { private boolean initialized = false; - private ThemeManager() { + private boolean closed; + private long themeRevision; + private final ObservableValue colorScheme; + + public ThemeManager() { + this(Platform.getPreferences().colorSchemeProperty()); } + ThemeManager(ObservableValue colorScheme) { this.colorScheme = Objects.requireNonNull(colorScheme); } + public void setScene(Scene scene) { + if (closed) throw new IllegalStateException("theme manager is closed"); this.scene = scene; } private void updateTheme(Theme theme, ThemeType type) { - if (theme == null || type == null) return; + if (closed || scene == null || theme == null || type == null) return; + var revision = ++themeRevision; LOGGER.info("updated theme {}:{}", theme, type); if (systemColorSchemeListener != null) { - var preferences = Platform.getPreferences(); - preferences.colorSchemeProperty().removeListener(systemColorSchemeListener); + colorScheme.removeListener(systemColorSchemeListener); systemColorSchemeListener = null; } switch (type) { case LIGHTER, DARKER -> theme.applyTheme(scene, type, initialized); - case SYSTEM -> systemTheme(theme); + case SYSTEM -> systemTheme(theme, revision); } + if (closed || revision != themeRevision) return; initialized = true; } - private void systemTheme(Theme theme) { - var preferences = Platform.getPreferences(); - var colorScheme = preferences.getColorScheme(); - updateSystemColorScheme(theme, colorScheme); + private void systemTheme(Theme theme, long revision) { + updateSystemColorScheme(theme, colorScheme.getValue()); + // 色の反映通知から設定変更や終了へ再入した場合、古い適用から購読を追加しない。 + if (closed || revision != themeRevision) return; systemColorSchemeListener = (ob, o, n) -> updateSystemColorScheme(theme, n); - preferences.colorSchemeProperty().addListener(systemColorSchemeListener); + colorScheme.addListener(systemColorSchemeListener); } private void updateSystemColorScheme(Theme theme, ColorScheme colorScheme) { @@ -131,12 +142,15 @@ private void updateSystemColorScheme(Theme theme, ColorScheme colorScheme) { public Theme getTheme() { return themeProperty().get(); } public void setTheme(Theme theme) { this.theme.set(theme); } - public static ThemeManager getInstance() { - return Holder.INSTANCE; - } - - private static class Holder { - private static final ThemeManager INSTANCE = new ThemeManager(); + @Override public void close() { + if (closed) return; + closed = true; + if (systemColorSchemeListener != null) { + colorScheme.removeListener(systemColorSchemeListener); + systemColorSchemeListener = null; + } + scene = null; + initialized = false; } } diff --git a/src/main/java/com/github/k7t3/tcv/app/user/UserDataFile.java b/src/main/java/com/github/k7t3/tcv/app/user/UserDataFile.java index af22f0b..65b9ccb 100644 --- a/src/main/java/com/github/k7t3/tcv/app/user/UserDataFile.java +++ b/src/main/java/com/github/k7t3/tcv/app/user/UserDataFile.java @@ -27,7 +27,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; /** * ユーザーデータを格納するSQLite形式のファイル @@ -38,20 +37,22 @@ public class UserDataFile { private Path filePath; - private final AtomicReference connectorRef = new AtomicReference<>(); + private SQLiteDBConnector connector; public UserDataFile(String filePath) { this(Path.of(filePath)); } public UserDataFile(Path filePath) { - this.filePath = Objects.requireNonNull(filePath); + this.filePath = Objects.requireNonNull(filePath).toAbsolutePath().normalize(); } - public DatabaseVersion connectDatabase(DatabaseVersion current) throws IOException { - var connector = connectorRef.get(); - if (connector != null && connector.isConnected()) { - return current; + public synchronized DatabaseVersion connectDatabase(DatabaseVersion current) throws IOException { + if (connector != null) { + if (!connector.isConnected()) { + connector.reconnect(getFilePath()); + } + return DatabaseVersion.latest(); } var filePath = getFilePath(); var parent = filePath.getParent(); @@ -70,44 +71,77 @@ public DatabaseVersion connectDatabase(DatabaseVersion current) throws IOExcepti } c.connect(); - connectorRef.set(c); + connector = c; return version; } - public void fileMove(Path moveTo) throws IOException { - var moveFrom = this.filePath; - - boolean exists = Files.exists(moveFrom); - if (exists) { - Files.copy(moveFrom, moveTo); + /** + * DB を閉じてコピーし、同じコネクタを移動先へ接続する。 + * 既存の移動先を上書きせず、失敗時は元ファイルへの接続を復旧する。 + * + * @param moveTo 移動先。同じファイルを指す場合は何もしない + * @throws IOException コピーまたはファイルの同一性確認に失敗した場合 + */ + public synchronized void fileMove(Path moveTo) throws IOException { + var moveFrom = this.filePath.toAbsolutePath().normalize(); + moveTo = Objects.requireNonNull(moveTo).toAbsolutePath().normalize(); + if (moveFrom.equals(moveTo) || (Files.exists(moveFrom) && Files.exists(moveTo) + && Files.isSameFile(moveFrom, moveTo))) return; + if (connector == null) { + moveFile(moveFrom, moveTo, null); + } else { + // 保存タスクが close と reconnect の間に接続を使用しないようにする。 + synchronized (connector) { + moveFile(moveFrom, moveTo, connector); + } } - var connector = connectorRef.get(); + } + + private void moveFile(Path moveFrom, Path moveTo, SQLiteDBConnector connector) throws IOException { if (connector != null) { - connector.reconnect(moveTo); + connector.close(); + } + + boolean exists = Files.exists(moveFrom); + try { + if (exists) { + Files.copy(moveFrom, moveTo); + } + if (connector != null) { + connector.reconnect(moveTo); + } this.filePath = moveTo; + } catch (IOException | RuntimeException | Error failure) { + if (connector != null && !connector.isConnected()) { + try { + connector.reconnect(moveFrom); + } catch (RuntimeException recoveryFailure) { + failure.addSuppressed(recoveryFailure); + } + } + throw failure; } if (exists) { try { Files.delete(moveFrom); - } catch (Exception e) { - LOGGER.warn("failed to delete an older user data file."); + } catch (IOException e) { + LOGGER.warn("failed to delete an older user data file", e); } } } - public void closeDatabase() { - var connector = connectorRef.get(); + public synchronized void closeDatabase() { if (connector == null) return; connector.close(); } - public Path getFilePath() { + public synchronized Path getFilePath() { return filePath; } - public DBConnector getConnector() { - return connectorRef.get(); + public synchronized DBConnector getConnector() { + return connector; } } diff --git a/src/main/java/com/github/k7t3/tcv/database/AbstractDBConnector.java b/src/main/java/com/github/k7t3/tcv/database/AbstractDBConnector.java index ad4a9cd..721550a 100644 --- a/src/main/java/com/github/k7t3/tcv/database/AbstractDBConnector.java +++ b/src/main/java/com/github/k7t3/tcv/database/AbstractDBConnector.java @@ -20,61 +20,71 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.util.Objects; public abstract class AbstractDBConnector implements DBConnector { private Connection connection = null; + private boolean transactionActive; + private boolean manualWork; + private boolean invalid; @Override - public void connect() { + public synchronized void connect() { if (connection != null) throw new IllegalStateException(); this.connection = connectImpl(); + invalid = false; } protected abstract Connection connectImpl(); @Override - public boolean isConnected() { - return connection != null; + public synchronized boolean isConnected() { + return connection != null && !invalid; } private void validConnection() { if (connection == null) throw new IllegalStateException("connection is null"); + if (invalid) throw new IllegalStateException("connection is invalid"); } @Override - public void setAutoCommit(boolean autoCommit) { + public synchronized void setAutoCommit(boolean autoCommit) { validConnection(); try { connection.setAutoCommit(autoCommit); + if (autoCommit) manualWork = false; } catch (SQLException e) { throw new RuntimeException(e); } } @Override - public void commit() { + public synchronized void commit() { validConnection(); try { connection.commit(); + manualWork = false; } catch (SQLException e) { throw new RuntimeException(e); } } @Override - public void rollback() { + public synchronized void rollback() { validConnection(); try { connection.rollback(); + manualWork = false; } catch (SQLException e) { throw new RuntimeException(e); } } @Override - public void execute(String sql) { + public synchronized void execute(String sql) { validConnection(); + markManualWork(); try (var stmt = connection.createStatement()) { stmt.execute(sql); } catch (SQLException e) { @@ -83,8 +93,9 @@ public void execute(String sql) { } @Override - public void query(String query, SQLFunction function) { + public synchronized void query(String query, SQLFunction function) { validConnection(); + markManualWork(); try (var stmt = connection.createStatement(); var rs = stmt.executeQuery(query)) { function.invoke(rs); @@ -94,8 +105,9 @@ public void query(String query, SQLFunction function) { } @Override - public void prepared(String prepared, SQLFunction function) { + public synchronized void prepared(String prepared, SQLFunction function) { validConnection(); + markManualWork(); try (var stmt = connection.prepareStatement(prepared)) { function.invoke(stmt); } catch (SQLException e) { @@ -104,11 +116,88 @@ public void prepared(String prepared, SQLFunction function) { } @Override - public void close() { + public synchronized void readTransaction(Runnable action) { + validConnection(); + Objects.requireNonNull(action); + if (transactionActive || manualWork) { + action.run(); + return; + } + final boolean autoCommit; + try { + autoCommit = connection.getAutoCommit(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + if (autoCommit) setAutoCommit(false); + Throwable failure = null; + try { + transaction(action); + } catch (RuntimeException | Error e) { + failure = e; + throw e; + } finally { + if (autoCommit) { + try { + setAutoCommit(true); + } catch (RuntimeException | Error restoreFailure) { + if (failure == null) throw restoreFailure; + failure.addSuppressed(restoreFailure); + } + } + } + } + + private void markManualWork() { + try { + // 生のSQL APIが開始した範囲は、呼出元のcommit/rollbackまで借用する。 + if (!transactionActive && !connection.getAutoCommit()) manualWork = true; + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + public synchronized void transaction(Runnable action) { + validConnection(); + Objects.requireNonNull(action); + if (transactionActive) throw new IllegalStateException("nested transaction"); + try { + if (connection.getAutoCommit()) throw new IllegalStateException("auto-commit must be disabled"); + } catch (SQLException e) { + throw new RuntimeException(e); + } + transactionActive = true; + try { + action.run(); + commit(); + } catch (RuntimeException | Error failure) { + try { + rollback(); + } catch (RuntimeException | Error rollbackFailure) { + invalid = true; + if (rollbackFailure != failure) failure.addSuppressed(rollbackFailure); + // 結果が不明な接続を再利用すると、後続の読取が未確定更新をcommitできてしまう。 + try { + close(); + } catch (RuntimeException | Error closeFailure) { + if (closeFailure != failure) failure.addSuppressed(closeFailure); + } + } + throw failure; + } finally { + transactionActive = false; + } + } + + @Override + public synchronized void close() { if (connection == null) return; try { connection.close(); connection = null; + manualWork = false; + invalid = false; } catch (SQLException e) { throw new RuntimeException(e); } diff --git a/src/main/java/com/github/k7t3/tcv/database/DBConnector.java b/src/main/java/com/github/k7t3/tcv/database/DBConnector.java index 2d1273a..81f3e43 100644 --- a/src/main/java/com/github/k7t3/tcv/database/DBConnector.java +++ b/src/main/java/com/github/k7t3/tcv/database/DBConnector.java @@ -17,22 +17,47 @@ package com.github.k7t3.tcv.database; import java.io.Closeable; -import java.io.IOException; +import java.nio.file.Path; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.util.Optional; public interface DBConnector extends Closeable { void connect(); + /** @return 操作可能な接続があればtrue。無効化後もcloseによる解放は再試行できる */ boolean isConnected(); + /** @return 現在のファイル保存先。メモリDBはempty。参照だけではI/Oしない */ + Optional storagePath(); + void setAutoCommit(boolean autoCommit); void commit(); void rollback(); + /** + * 自動コミットが無効な接続で更新を実行し、成功時にコミットする。 + * 失敗時はロールバックし、元の例外を再送出する。 + * ロールバックにも失敗した場合は接続を無効化して解放を試み、両方の失敗を元の例外に保持する。 + * 同じ接続の操作は完了まで排他制御される。ネストした呼び出しは拒否する。 + * + * @param action この接続で同期的に実行する更新。自身でコミットしないこと + * @throws IllegalStateException 未接続、自動コミットが有効、またはネストした場合 + */ + void transaction(Runnable action); + + /** + * 結果を複製するまでの読取を一単位で完了し、スナップショットと読取ロックを解放する。 + * 外側のtransaction、または生のSQL APIで開始した手動トランザクション中は + * その範囲を借用し、呼出元の変更を確定しない。借用時の終了は呼出元が担当する。 + * 自身で読取を開始した場合は、成功・失敗後に元の自動コミット設定を復元する。 + * @param action 同期的な読取。ResultSet等を保持せず、更新は行わないこと + */ + void readTransaction(Runnable action); + void execute(String sql); void query(String query, SQLFunction function); diff --git a/src/main/java/com/github/k7t3/tcv/database/SQLiteDBConnector.java b/src/main/java/com/github/k7t3/tcv/database/SQLiteDBConnector.java index fc890ad..1776c20 100644 --- a/src/main/java/com/github/k7t3/tcv/database/SQLiteDBConnector.java +++ b/src/main/java/com/github/k7t3/tcv/database/SQLiteDBConnector.java @@ -16,13 +16,14 @@ package com.github.k7t3.tcv.database; +import com.github.k7t3.tcv.database.table.TableCreatorFactory; import org.sqlite.SQLiteConfig; -import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; +import java.util.Optional; public class SQLiteDBConnector extends AbstractDBConnector { @@ -43,6 +44,11 @@ public class SQLiteDBConnector extends AbstractDBConnector { private final TableCreator tableCreator; + @Override + public synchronized Optional storagePath() { + return Optional.ofNullable(filePath).map(path -> path.toAbsolutePath().normalize()); + } + /** * テスト用のインメモリモードコンストラクタ */ @@ -57,7 +63,8 @@ public SQLiteDBConnector(Path filePath) { public SQLiteDBConnector(Path filePath, TableCreator creator) { this.filePath = filePath; - this.tableCreator = creator; + this.tableCreator = creator != null ? creator + : TableCreatorFactory.create(DatabaseVersion.EMPTY, DatabaseVersion.latest()); } @Override @@ -65,8 +72,9 @@ protected Connection connectImpl() { try { var config = new SQLiteConfig(); config.enforceForeignKeys(true); - config.setJournalMode(SQLiteConfig.JournalMode.MEMORY); - config.setSynchronous(SQLiteConfig.SynchronousMode.OFF); + // ファイル DB はクラッシュ後に復旧できるジャーナルと同期を維持する。 + config.setJournalMode(filePath == null ? SQLiteConfig.JournalMode.MEMORY : SQLiteConfig.JournalMode.DELETE); + config.setSynchronous(filePath == null ? SQLiteConfig.SynchronousMode.OFF : SQLiteConfig.SynchronousMode.FULL); config.setDatePrecision(SQLiteConfig.DatePrecision.MILLISECONDS.getValue()); return DriverManager.getConnection(connectionURL, config.toProperties()); @@ -87,23 +95,33 @@ private void createTable() { this.tableCreator.create(this); } - @Override - public void connect() { - // メモリモードのときか、対象のファイルが存在しないとき - boolean empty = (filePath == null || !Files.exists(filePath)); + private boolean hasTables() { + var exists = new boolean[1]; + query("select 1 from sqlite_master where type = 'table' and name not like 'sqlite_%' limit 1;", + rows -> exists[0] = rows.next()); + return exists[0]; + } + @Override + public synchronized void connect() { constructPath(); super.connect(); - if (empty) { - createTable(); + try { + // スキーマ作成も更新と同じ境界で確定し、途中の DDL を残さない。 + setAutoCommit(false); + transaction(() -> { if (!hasTables()) createTable(); }); + } catch (RuntimeException | Error failure) { + try { + close(); + } catch (RuntimeException closeFailure) { + failure.addSuppressed(closeFailure); + } + throw failure; } - - // デフォルトでAutoCommitはFalse - setAutoCommit(false); } - public void reconnect(Path filePath) { + public synchronized void reconnect(Path filePath) { if (isConnected()) throw new IllegalStateException("connected"); this.filePath = filePath; connect(); diff --git a/src/main/java/com/github/k7t3/tcv/domain/FollowedChannelPager.java b/src/main/java/com/github/k7t3/tcv/domain/FollowedChannelPager.java new file mode 100644 index 0000000..fde6271 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/domain/FollowedChannelPager.java @@ -0,0 +1,27 @@ +package com.github.k7t3.tcv.domain; + +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.function.Function; + +/** フォロー一覧のページ走査。全ページの成功後に、最初の出現順で重複のないIDを返す。 */ +final class FollowedChannelPager { + record Page(List userIds, String nextCursor) { + Page { userIds = List.copyOf(userIds); } + } + + static List load(Function fetch) { + var ids = new LinkedHashSet(); + var seenCursors = new HashSet(); + String cursor = null; + while (true) { + var page = fetch.apply(cursor); + ids.addAll(page.userIds()); + var next = page.nextCursor(); + if (next == null || next.isBlank()) return List.copyOf(ids); + if (!seenCursors.add(next)) throw new IllegalStateException("Repeated followed channels pagination cursor"); + cursor = next; + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/domain/HelixClient.java b/src/main/java/com/github/k7t3/tcv/domain/HelixClient.java new file mode 100644 index 0000000..3ddff99 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/domain/HelixClient.java @@ -0,0 +1,51 @@ +package com.github.k7t3.tcv.domain; + +import com.github.twitch4j.helix.domain.ChannelSearchList; +import com.github.twitch4j.helix.domain.ChatBadgeSetList; +import com.github.twitch4j.helix.domain.ClipList; +import com.github.twitch4j.helix.domain.OutboundFollowing; +import com.github.twitch4j.helix.domain.StreamList; +import com.github.twitch4j.helix.domain.UserList; +import feign.Headers; +import feign.Param; +import feign.RequestLine; +import java.time.Instant; +import java.util.List; + +/** アプリが使用するHelix HTTP契約。実行・再試行・終了の所有はSDKのコマンド型に依存しない。 */ +public interface HelixClient { + @RequestLine("GET /channels/followed?user_id={user_id}&broadcaster_id={broadcaster_id}&first={first}&after={after}") + @Headers("Authorization: Bearer {token}") + OutboundFollowing getFollowedChannels(@Param("token") String token, @Param("user_id") String userId, + @Param("broadcaster_id") String broadcasterId, @Param("first") Integer first, @Param("after") String after); + + @RequestLine("GET /search/channels?after={after}&first={first}&live_only={live_only}&query={query}") + @Headers("Authorization: Bearer {token}") + ChannelSearchList searchChannels(@Param("token") String token, @Param("query") String query, + @Param("first") Integer first, @Param("after") String after, @Param("live_only") Boolean liveOnly); + + @RequestLine("GET /users?id={id}&login={login}") + @Headers("Authorization: Bearer {token}") + UserList getUsers(@Param("token") String token, @Param("id") List ids, @Param("login") List logins); + + @RequestLine("GET /streams?after={after}&before={before}&first={first}&game_id={game_id}&language={language}&user_id={user_id}&user_login={user_login}") + @Headers("Authorization: Bearer {token}") + StreamList getStreams(@Param("token") String token, @Param("after") String after, @Param("before") String before, + @Param("first") Integer first, @Param("game_id") List gameIds, @Param("language") List languages, + @Param("user_id") List userIds, @Param("user_login") List userLogins); + + @RequestLine("GET /chat/badges/global") + @Headers("Authorization: Bearer {token}") + ChatBadgeSetList getGlobalChatBadges(@Param("token") String token); + + @RequestLine("GET /chat/badges?broadcaster_id={broadcaster_id}") + @Headers("Authorization: Bearer {token}") + ChatBadgeSetList getChannelChatBadges(@Param("token") String token, @Param("broadcaster_id") String broadcasterId); + + @RequestLine("GET /clips?broadcaster_id={broadcaster_id}&game_id={game_id}&id={id}&after={after}&before={before}&first={first}&started_at={started_at}&ended_at={ended_at}&is_featured={is_featured}") + @Headers("Authorization: Bearer {token}") + ClipList getClips(@Param("token") String token, @Param("broadcaster_id") String broadcasterId, + @Param("game_id") String gameId, @Param("id") List ids, @Param("after") String after, + @Param("before") String before, @Param("first") Integer first, @Param("started_at") Instant startedAt, + @Param("ended_at") Instant endedAt, @Param("is_featured") Boolean featured); +} diff --git a/src/main/java/com/github/k7t3/tcv/domain/HelixClientFactory.java b/src/main/java/com/github/k7t3/tcv/domain/HelixClientFactory.java new file mode 100644 index 0000000..60e62f4 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/domain/HelixClientFactory.java @@ -0,0 +1,307 @@ +package com.github.k7t3.tcv.domain; + +import com.github.k7t3.tcv.lifecycle.CloseActions; +import com.github.philippheuer.credentialmanager.CredentialManager; +import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; +import com.github.twitch4j.common.config.Twitch4JGlobal; +import com.github.twitch4j.common.util.TypeConvert; +import com.github.twitch4j.helix.TwitchHelixErrorDecoder; +import com.github.twitch4j.helix.domain.CustomReward; +import com.github.twitch4j.helix.interceptor.*; +import feign.Feign; +import feign.Request; +import feign.Retryer; +import feign.RetryableException; +import feign.jackson.JacksonDecoder; +import feign.jackson.JacksonEncoder; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Proxy; +import java.time.Duration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; + +/** SDK の公開 codec / rate limit を使い、再試行は TwitchRequestExecutor が所有する。 */ +final class HelixClientFactory { + static final String OFFICIAL_BASE_URL = "https://api.twitch.tv/helix"; + record Options(String clientId, String clientSecret, String baseUrl, int timeoutMillis) { + Options { + Objects.requireNonNull(baseUrl); + if (timeoutMillis <= 0) throw new IllegalArgumentException("HTTP timeout must be positive"); + } + } + + static final class Handle implements AutoCloseable { + private final HelixClient client; + private final okhttp3.OkHttpClient network; + private final Lifetime lifetime; + + Handle(HelixClient client, okhttp3.OkHttpClient network, Lifetime lifetime) { + this.client = client; this.network = network; this.lifetime = lifetime; + } + HelixClient client() { return client; } + boolean isClosed() { return lifetime.isClosed(); } + @Override public void close() { release(network, lifetime); } + /** 自身の処理からの停止要求後も、外部の所有者は実終了を待てる。 */ + void awaitClosed() { lifetime.awaitDrained(); } + boolean isProcessingOnCurrentThread() { return lifetime.isProcessingOnCurrentThread(); } + } + + static Handle create(CredentialManager credentials, OAuth2Credential token, + ScheduledThreadPoolExecutor scheduler, Options options) { + return create(credentials, token, scheduler, options, Thread::start); + } + + /** 未開始の要求スレッドを開始する境界を指定する。開始できない場合は例外を送出すること。 */ + static Handle create(CredentialManager credentials, OAuth2Credential token, + ScheduledThreadPoolExecutor scheduler, Options options, Consumer requestStarter) { + Objects.requireNonNull(credentials); Objects.requireNonNull(scheduler); + var lifetime = new Lifetime(Objects.requireNonNull(requestStarter)); + var network = new okhttp3.OkHttpClient.Builder().retryOnConnectionFailure(false) + .callTimeout(options.timeoutMillis(), TimeUnit.MILLISECONDS) + .eventListener(lifetime).addInterceptor(chain -> { + if (lifetime.isClosed()) throw new IOException("HTTP client has ended"); + return chain.proceed(chain.request()); + }).build(); + try { + var tokens = new TwitchHelixTokenManager(credentials, options.clientId(), options.clientSecret(), token); + var limits = new TwitchHelixRateLimitTracker( + io.github.bucket4j.BandwidthBuilder.builder().capacity(800) + .refillGreedy(800, Duration.ofMinutes(1)).build(), tokens); + var sdk = new TwitchHelixHttpClient(new feign.okhttp.OkHttpClient(network), scheduler, tokens, limits, options.timeoutMillis()); + feign.Client transport = (request, settings) -> { + lifetime.enter(); + try { + var response = sdk.execute(request, settings); + if (lifetime.isClosed()) { + if (response != null) response.close(); + throw cancelled(null); + } + return response; + } catch (IOException failure) { + if (lifetime.isClosed()) throw cancelled(failure); + throw failure; + } + finally { lifetime.leave(); } + }; + var headers = new TwitchHelixClientIdInterceptor(Twitch4JGlobal.userAgent, tokens); + var mapper = TypeConvert.getObjectMapper(); + var encoder = mapper.copy().addMixIn(CustomReward.class, CustomRewardEncodeMixIn.class); + var errors = new TwitchHelixErrorDecoder(new JacksonDecoder(), limits); + var responses = new TwitchHelixDecoder(mapper, limits); + var client = Feign.builder().client(transport) + .encoder(new JacksonEncoder(encoder)).decoder((response, type) -> { + lifetime.enter(); + try { + var result = responses.decode(response, type); + if (lifetime.isClosed()) throw cancelled(null); + return result; + } catch (IOException | RuntimeException failure) { + if (lifetime.isClosed()) throw cancelled(failure); + throw failure; + } finally { lifetime.leave(); } + }) + .errorDecoder((method, response) -> { + lifetime.enter(); + try { + var failure = errors.decode(method, response); + if (lifetime.isClosed()) return cancelled(null); + if (response.status() == 429) return new RetryableException(429, "Twitch rate limit exceeded", + response.request().httpMethod(), failure, (Long) null, response.request()); + return failure; + } catch (RuntimeException failure) { + if (lifetime.isClosed()) return cancelled(failure); + throw failure; + } finally { lifetime.leave(); } + }) + .requestInterceptor(template -> { + lifetime.enter(); + try { + headers.apply(template); + if (lifetime.isClosed()) throw cancelled(null); + } finally { lifetime.leave(); } + }) + .options(new Request.Options(options.timeoutMillis() / 3, TimeUnit.MILLISECONDS, + options.timeoutMillis(), TimeUnit.MILLISECONDS, true)) + .retryer(Retryer.NEVER_RETRY) + .decodeVoid().target(HelixClient.class, options.baseUrl()); + return new Handle(owned(client, lifetime, options.timeoutMillis()), network, lifetime); + } catch (RuntimeException | Error failure) { + CloseActions.runAll(() -> { + if (failure instanceof RuntimeException exception) throw exception; + throw (Error) failure; + }, () -> release(network, lifetime)); + throw failure; + } + } + + private static HelixClient owned(HelixClient delegate, Lifetime lifetime, int timeoutMillis) { + return (HelixClient) Proxy.newProxyInstance(HelixClient.class.getClassLoader(), new Class[] {HelixClient.class}, + (proxy, method, arguments) -> { + if (method.getDeclaringClass() == Object.class) return switch (method.getName()) { + case "equals" -> proxy == arguments[0]; + case "hashCode" -> System.identityHashCode(proxy); + case "toString" -> delegate.toString(); + default -> throw new IllegalStateException("unknown Object method"); + }; + var request = lifetime.startRequest(() -> method.invoke(delegate, arguments)); + try { return request.get(timeoutMillis, TimeUnit.MILLISECONDS); } + catch (InterruptedException failure) { + request.cancel(true); + Thread.currentThread().interrupt(); + throw cancelled(failure); + } catch (TimeoutException failure) { + request.cancel(true); + throw new CompletionException(failure); + } catch (ExecutionException failure) { + var cause = failure.getCause(); + throw cause instanceof InvocationTargetException invocation ? invocation.getCause() : cause; + } + }); + } + + private static CancellationException cancelled(Throwable cause) { + if (cause instanceof CancellationException cancelled) return cancelled; + var cancelled = new CancellationException("HTTP client has ended"); + if (cause != null) cancelled.initCause(cause); + return cancelled; + } + + /** 受付済みHTTPと本文処理を所有する。外部closeは実終了を待ち、処理自身のcloseは停止だけを要求する。 */ + private static final class Lifetime extends okhttp3.EventListener { + private final Consumer requestStarter; + private final AtomicBoolean closed = new AtomicBoolean(); + private final Object ownership = new Object(); + // 要求全体とcodec等の入れ子を分け、内側のleaveで実行中の所有を失わない。 + private final HashMap executing = new HashMap<>(); + private final Set> requests = new HashSet<>(); + private final Set calls = new HashSet<>(); + private boolean shutdownFinished; + + Lifetime(Consumer requestStarter) { this.requestStarter = requestStarter; } + + boolean isClosed() { return closed.get(); } + boolean isProcessingOnCurrentThread() { + synchronized (ownership) { return executing.containsKey(Thread.currentThread()); } + } + + FutureTask startRequest(Callable work) { + var request = new FutureTask<>(work); + var thread = Thread.ofVirtual().name("TCV-Helix-Request").unstarted(() -> { + try { request.run(); } + finally { + // Futureの取消は先に完了しても、実処理の所有はrunの終了まで維持する。 + synchronized (ownership) { requests.remove(request); } + leave(); + } + }); + synchronized (ownership) { + if (closed.get()) throw cancelled(null); + requests.add(request); + executing.put(thread, 1); + } + try { requestStarter.accept(thread); } + catch (RuntimeException | Error failure) { + synchronized (ownership) { + requests.remove(request); + executing.remove(thread); + ownership.notifyAll(); + } + request.cancel(false); + throw failure; + } + return request; + } + + void enter() { + synchronized (ownership) { + if (closed.get()) throw cancelled(null); + executing.merge(Thread.currentThread(), 1, Integer::sum); + } + } + + void leave() { + synchronized (ownership) { + executing.computeIfPresent(Thread.currentThread(), (thread, depth) -> depth == 1 ? null : depth - 1); + ownership.notifyAll(); + } + } + + @Override public void callStart(okhttp3.Call call) { + final boolean rejected; + synchronized (ownership) { + rejected = closed.get(); + if (!rejected) calls.add(call); + } + if (rejected) call.cancel(); + } + @Override public void callEnd(okhttp3.Call call) { forget(call); } + @Override public void callFailed(okhttp3.Call call, IOException failure) { forget(call); } + private void forget(okhttp3.Call call) { + synchronized (ownership) { + calls.remove(call); + ownership.notifyAll(); + } + } + + void close(Runnable shutdownNetwork) { + final List pending; + final List> pendingRequests; + final boolean owner; + synchronized (ownership) { + owner = closed.compareAndSet(false, true); + // Interrupt before a released worker can move to another owner's work. + if (owner) executing.keySet().forEach(Thread::interrupt); + pending = owner ? List.copyOf(calls) : List.of(); + pendingRequests = owner ? List.copyOf(requests) : List.of(); + } + if (!owner) { + awaitDrained(); + return; + } + try { + CloseActions.runAll(() -> pendingRequests.forEach(request -> request.cancel(true)), + () -> pending.forEach(okhttp3.Call::cancel), shutdownNetwork); + } finally { + synchronized (ownership) { + shutdownFinished = true; + ownership.notifyAll(); + } + awaitDrained(); + } + } + + private void awaitDrained() { + boolean interrupted = false; + try { + synchronized (ownership) { + if (executing.containsKey(Thread.currentThread())) return; + while (!shutdownFinished || !executing.isEmpty() || !calls.isEmpty()) { + try { ownership.wait(); } + catch (InterruptedException cancellation) { interrupted = true; } + } + } + } finally { + if (interrupted) Thread.currentThread().interrupt(); + } + } + } + + private static void release(okhttp3.OkHttpClient network, Lifetime lifetime) { + lifetime.close(() -> CloseActions.runAll(network.dispatcher()::cancelAll, + () -> network.dispatcher().executorService().shutdownNow(), network.connectionPool()::evictAll)); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/domain/StreamEventMonitor.java b/src/main/java/com/github/k7t3/tcv/domain/StreamEventMonitor.java new file mode 100644 index 0000000..164760e --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/domain/StreamEventMonitor.java @@ -0,0 +1,252 @@ +/* + * Copyright 2024 k7t3 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.github.k7t3.tcv.domain; + +import com.github.k7t3.tcv.domain.channel.Broadcaster; +import com.github.twitch4j.common.util.CollectionUtils; +import com.github.twitch4j.common.util.ExponentialBackoffStrategy; +import com.github.k7t3.tcv.domain.channel.StreamInfo; +import com.github.k7t3.tcv.domain.event.stream.StreamStateEvent; +import com.github.k7t3.tcv.lifecycle.OwnedScheduler; +import com.github.twitch4j.helix.domain.Stream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.Closeable; +import java.io.IOException; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Function; + +/** 配信状態の取得・変更通知を、監視の実行世代とチャンネル登録ごとの状態で管理する。 */ +final class StreamEventMonitor implements Closeable { + + private static final Logger LOGGER = LoggerFactory.getLogger(StreamEventMonitor.class); + private static final int MAX_LIMIT = 100; + + private final Function, List> fetchStreams; + private final Consumer eventSink; + private final ScheduledThreadPoolExecutor executor; + private final OwnedScheduler ownedExecutor; + private final Object stateLock = new Object(); + private final Map watched = new LinkedHashMap<>(); + private final ExponentialBackoffStrategy backoff = ExponentialBackoffStrategy.builder() + .immediateFirst(false).baseMillis(1000L).jitter(false).build(); + + private volatile boolean closed; + private long generation; + private ScheduledFuture pending; + + private static final class State { + Boolean live; + String title; + String gameId; + Integer viewers; + } + private record Watch(String userId, State state) {} + private record PendingEvent(Watch watch, StreamStateEvent value) {} + + private static final class PollCycle { + private final long generation; + private final Deque> batches = new ArrayDeque<>(); + + private PollCycle(long generation) { + this.generation = generation; + } + } + + // 未使用の scheduler の所有権を引き受ける。 + StreamEventMonitor(Function, List> fetchStreams, Consumer publishEvent, + ScheduledThreadPoolExecutor executor) { + this.fetchStreams = Objects.requireNonNull(fetchStreams); + this.eventSink = Objects.requireNonNull(publishEvent); + this.executor = Objects.requireNonNull(executor); + this.ownedExecutor = new OwnedScheduler(executor); + executor.setRemoveOnCancelPolicy(true); + } + + /** + * チャンネルを監視対象に追加する。登録済みの場合は現在の状態を維持する。 + * @param broadcaster 監視するチャンネル + * @return 新しい登録を作成した場合は true + * @throws IllegalStateException この監視が終了している場合 + */ + public boolean enableStreamEventListener(Broadcaster broadcaster) { + synchronized (stateLock) { + requireOpen(); + var wasEmpty = watched.isEmpty(); + var added = add(broadcaster); + if (wasEmpty && added) schedule(new PollCycle(++generation), backoff.get()); + return added; + } + } + + /** + * 既存の登録を維持しながら監視対象をまとめて追加する。 + * @param broadcasters 追加するチャンネル + * @throws IllegalStateException この監視が終了している場合 + */ + public void enableStreamEventListeners(Iterable broadcasters) { + synchronized (stateLock) { + requireOpen(); + var wasEmpty = watched.isEmpty(); + broadcasters.forEach(this::add); + if (wasEmpty && !watched.isEmpty()) schedule(new PollCycle(++generation), backoff.get()); + } + } + + private boolean add(Broadcaster broadcaster) { + var id = Objects.requireNonNull(broadcaster.getUserId()); + if (watched.containsKey(id)) return false; + watched.put(id, new Watch(id, new State())); + return true; + } + + /** + * 登録とその状態を破棄し、当該登録の未完了の取得結果を反映対象から外す。 + * @param broadcaster 解除するチャンネル + * @return 登録が存在していた場合は true + */ + public boolean disableStreamEventListenerForId(Broadcaster broadcaster) { + synchronized (stateLock) { + if (watched.remove(broadcaster.getUserId()) == null) return false; + if (watched.isEmpty()) { + generation++; + cancelPending(); + backoff.reset(); + } + return true; + } + } + + private void requireOpen() { + if (closed) throw new IllegalStateException("stream monitor is closed"); + } + + private boolean isCurrent(PollCycle cycle) { + return !closed && generation == cycle.generation && !watched.isEmpty(); + } + + private void schedule(PollCycle cycle, long delayMillis) { + pending = executor.schedule(() -> poll(cycle), delayMillis, TimeUnit.MILLISECONDS); + } + + private void poll(PollCycle cycle) { + final List batch; + synchronized (stateLock) { + if (!isCurrent(cycle)) return; + if (cycle.batches.isEmpty()) { + cycle.batches.addAll(CollectionUtils.chunked(new ArrayList<>(watched.values()), MAX_LIMIT)); + } + batch = cycle.batches.removeFirst().stream() + .filter(watch -> watched.get(watch.userId()) == watch).toList(); + if (batch.isEmpty()) { + schedule(cycle, 0); + return; + } + } + + try { + var response = fetchStreams.apply(batch.stream().map(Watch::userId).toList()); + var streams = new HashMap(); + response.forEach(stream -> streams.put(stream.getUserId(), stream)); + var events = new ArrayList(); + synchronized (stateLock) { + if (!isCurrent(cycle)) return; + for (var watch : batch) { + // 解除後に同じ ID が登録されても、古い応答を新しい状態へ反映しない。 + if (watched.get(watch.userId()) != watch) continue; + eventsFor(watch, streams.get(watch.userId())).forEach(event -> + events.add(new PendingEvent(watch, event))); + } + backoff.reset(); + } + for (var event : events) { + synchronized (stateLock) { + if (!isCurrent(cycle) || watched.get(event.watch().userId()) != event.watch()) continue; + } + eventSink.accept(event.value()); + } + } catch (Exception failure) { + if (!closed) LOGGER.warn("Failed to check stream events", failure); + } finally { + synchronized (stateLock) { + if (isCurrent(cycle)) schedule(cycle, backoff.get()); + } + } + } + + private List eventsFor(Watch watch, Stream stream) { + var events = new ArrayList(); + var state = watch.state(); + if (stream != null && stream.getType().equalsIgnoreCase("live")) { + var wentOnline = Boolean.FALSE.equals(state.live); + var wasAlreadyLive = !wentOnline; + var titleChanged = wasAlreadyLive && state.title != null && !state.title.equals(stream.getTitle()); + var gameChanged = wasAlreadyLive && state.gameId != null && !state.gameId.equals(stream.getGameId()); + var viewersChanged = wasAlreadyLive && !stream.getViewerCount().equals(state.viewers); + if (wentOnline || titleChanged || gameChanged || viewersChanged) { + var info = StreamInfo.of(stream); + if (wentOnline) events.add(new StreamStateEvent.Online(watch.userId(), info)); + if (titleChanged) events.add(new StreamStateEvent.Title(watch.userId(), info)); + if (gameChanged) events.add(new StreamStateEvent.Game(watch.userId(), info)); + if (viewersChanged) events.add(new StreamStateEvent.Viewers(watch.userId(), info)); + } + state.live = true; + state.title = stream.getTitle(); + state.gameId = stream.getGameId(); + state.viewers = stream.getViewerCount(); + } else { + if (Boolean.TRUE.equals(state.live)) events.add(new StreamStateEvent.Offline(watch.userId())); + state.live = false; + state.title = null; + state.gameId = null; + state.viewers = null; + } + return events; + } + + private void cancelPending() { + if (pending != null) pending.cancel(false); + pending = null; + } + + /** + * 新規登録と再予約を止め、所有する scheduler を停止する。複数回呼び出せる。 + * 監視スレッド自身からは停止だけを要求し、その他の呼び出し元は終了完了まで待つ。 + */ + @Override + public void close() throws IOException { + synchronized (stateLock) { + closed = true; + generation++; + watched.clear(); + cancelPending(); + } + ownedExecutor.close(); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/domain/Twitch.java b/src/main/java/com/github/k7t3/tcv/domain/Twitch.java index b9bd3dc..10dd252 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/Twitch.java +++ b/src/main/java/com/github/k7t3/tcv/domain/Twitch.java @@ -18,38 +18,54 @@ import com.github.k7t3.tcv.domain.auth.CredentialController; import com.github.k7t3.tcv.domain.auth.CredentialStore; +import com.github.k7t3.tcv.domain.auth.SessionCredentialStore; import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; -import com.github.twitch4j.TwitchClient; import com.github.twitch4j.chat.TwitchChat; +import com.github.k7t3.tcv.lifecycle.CloseActions; import java.io.Closeable; import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; public class Twitch implements Closeable { - private final OAuth2Credential credential; - private final TwitchClient client; - private final CredentialStore credentialStore; + private final TwitchClients client; + private final Runnable releaseClient; + private final SessionCredentialStore credentialStore; private TwitchAPI twitchAPI; + private final Object lifecycleLock = new Object(); + private boolean closed; + private final AtomicBoolean logoutStarted = new AtomicBoolean(); + private final AtomicBoolean invalidationDelivered = new AtomicBoolean(); + private volatile Runnable invalidated; Twitch( OAuth2Credential credential, CredentialStore credentialStore, - TwitchClient client + TwitchClients client ) { - this.credentialStore = credentialStore; - this.credential = credential; - this.client = client; + this(credential, credentialStore, client, client::close); } - public TwitchAPI getTwitchAPI() { - if (twitchAPI == null) twitchAPI = new TwitchAPI(this); - return twitchAPI; + Twitch(OAuth2Credential credential, CredentialStore credentialStore, TwitchClients client, Runnable releaseClient) { + this.credentialStore = credentialStore instanceof SessionCredentialStore scope ? scope + : new SessionCredentialStore(credentialStore, credential); + this.client = client; + this.releaseClient = Objects.requireNonNull(releaseClient); + this.credentialStore.onUpdated(credential::updateCredential); + this.credentialStore.onInvalidated(this::notifyInvalidation); } - void updateCredential(OAuth2Credential newOne) { - getCredential().updateCredential(newOne); + public TwitchAPI getTwitchAPI() { + synchronized (lifecycleLock) { + checkOpen(); + if (twitchAPI == null) twitchAPI = new TwitchAPI(this); + return twitchAPI; + } } CredentialStore getCredentialStore() { @@ -57,7 +73,25 @@ CredentialStore getCredentialStore() { } private OAuth2Credential getCredential() { - return credential; + return credentialStore.credential(); + } + + public Set credentialTokens() { return credentialStore.tokens(); } + public void freezeCredentials() { credentialStore.retire(); } + public boolean hasInvalidCredentials() { return credentialStore.isInvalid(); } + public boolean isClosing() { return credentialStore.isRetired(); } + public boolean isClosed() { synchronized (lifecycleLock) { return closed; } } + + public void onInvalidated(Runnable listener) { + invalidated = Objects.requireNonNull(listener); + notifyInvalidation(); + } + + public void invalidateCredentials() { credentialStore.invalidate(); } + + private void notifyInvalidation() { + var listener = invalidated; + if (hasInvalidCredentials() && listener != null && invalidationDelivered.compareAndSet(false, true)) listener.run(); } public String getAccessToken() { @@ -75,44 +109,43 @@ public String getUserName() { /** * ドメインパッケージでの使用に限りたい。 */ - public TwitchClient getClient() { - return client; + public TwitchClients getClient() { + synchronized (lifecycleLock) { + checkOpen(); + return client; + } } public TwitchChat getChat() { - return client.getChat(); + return getClient().getChat(); } public void logout() { - if (twitchAPI != null) { - try { - twitchAPI.close(); - } catch (IOException ignored) { - } - twitchAPI = null; - } - client.close(); - - var credentialController = new CredentialController(credentialStore); - try { - credentialController.revokeToken(); - } finally { - credentialController.disposeAuthenticate(); - } - - credentialStore.clearCredentials(); + if (!logoutStarted.compareAndSet(false, true)) return; + CloseActions.runAll(this::close, + () -> CredentialController.revokeToken(getCredential()), + () -> credentialStore.removeCredential(getCredential())); } @Override public void close() { - if (twitchAPI != null) { - try { - twitchAPI.close(); - } catch (IOException ignored) { - } + final TwitchAPI api; + synchronized (lifecycleLock) { + if (closed) return; + closed = true; + api = twitchAPI; } + CloseActions.runAll(this::freezeCredentials, credentialStore::awaitWrites, () -> { + if (api == null) return; + try { api.close(); } + catch (IOException failure) { throw new UncheckedIOException(failure); } + }, releaseClient, () -> { + if (hasInvalidCredentials()) credentialStore.removeCredential(getCredential()); + }); + } - client.close(); + private void checkOpen() { + if (closed) throw new IllegalStateException("twitch client is closed"); } } diff --git a/src/main/java/com/github/k7t3/tcv/domain/TwitchAPI.java b/src/main/java/com/github/k7t3/tcv/domain/TwitchAPI.java index 3b1ffa4..5b286e0 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/TwitchAPI.java +++ b/src/main/java/com/github/k7t3/tcv/domain/TwitchAPI.java @@ -21,20 +21,8 @@ import com.github.k7t3.tcv.domain.channel.FoundChannel; import com.github.k7t3.tcv.domain.channel.StreamInfo; import com.github.k7t3.tcv.domain.exception.InvalidCredentialException; -import com.github.twitch4j.common.events.domain.EventChannel; -import com.github.twitch4j.common.exception.UnauthorizedException; import com.github.twitch4j.common.util.CollectionUtils; -import com.github.twitch4j.common.util.ExponentialBackoffStrategy; -import com.github.twitch4j.domain.ChannelCache; -import com.github.twitch4j.events.*; -import com.github.twitch4j.helix.TwitchHelix; import com.github.twitch4j.helix.domain.*; -import com.netflix.hystrix.HystrixCommand; -import com.netflix.hystrix.exception.HystrixRuntimeException; -import feign.FeignException; -import io.github.xanthic.cache.api.Cache; -import io.github.xanthic.cache.api.domain.ExpiryType; -import io.github.xanthic.cache.core.CacheApi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,14 +30,12 @@ import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; -import java.time.Duration; import java.util.*; -import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.CancellationException; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -import java.util.function.BooleanSupplier; -import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; @@ -59,29 +45,40 @@ public class TwitchAPI implements Closeable { private final Twitch twitch; - // Helix APIの多重アクセス防止用のセマフォ - private final Semaphore semaphore = new Semaphore(4, true); + private final TwitchRequestExecutor requests = new TwitchRequestExecutor(); // トークンのリフレッシュ時のロック private final Lock refreshLock = new ReentrantLock(true); private long refreshTimestamp = Long.MIN_VALUE; - private final ChannelListener channelListener = new ChannelListener(); + private final StreamEventMonitor streamMonitor; + private final AtomicBoolean invalidCredentials = new AtomicBoolean(); public TwitchAPI(Twitch twitch) { + this(twitch, new ScheduledThreadPoolExecutor(2, + Thread.ofPlatform().name("Stream-Watch-Thread").daemon().factory())); + } + + // 未使用の scheduler の所有権を引き受け、API の終了時に停止する。 + TwitchAPI(Twitch twitch, ScheduledThreadPoolExecutor scheduler) { this.twitch = twitch; + this.streamMonitor = new StreamEventMonitor( + ids -> request(helix -> helix.getStreams( + twitch.getAccessToken(), null, null, ids.size(), null, null, ids, null)).getStreams(), + event -> twitch.getClient().getEventManager().publish(event), scheduler); } public List getFollowChannelOwners() { - var broadcasters = getFollowChannelOwners(new ArrayList<>(), null); + var userIds = FollowedChannelPager.load(this::fetchFollowedPage); + var broadcasters = List.copyOf(getBroadcasters(userIds)); LOGGER.info("got broadcasters count {}", broadcasters.size()); return broadcasters; } - private List getFollowChannelOwners(List list, String cursor) { - var set = hystrixCommandWrapper(helix -> helix.getFollowedChannels( + private FollowedChannelPager.Page fetchFollowedPage(String cursor) { + var set = request(helix -> helix.getFollowedChannels( twitch.getAccessToken(), twitch.getUserId(), null, @@ -89,26 +86,24 @@ private List getFollowChannelOwners(List list, String cursor) ); - var follows = set.getFollows(); - if (follows == null) { - return list; + if (set == null || set.getFollows() == null || set.getPagination() == null) { + throw new IllegalStateException("Invalid followed channels response: missing data or pagination"); } - - var userIds = follows.stream().map(OutboundFollow::getBroadcasterId).toList(); - var broadcasters = getBroadcasters(userIds); - list.addAll(broadcasters); - - if (set.getPagination().getCursor() != null) { - return getFollowChannelOwners(list, set.getPagination().getCursor()); + var userIds = new ArrayList(); + for (var follow : set.getFollows()) { + if (follow == null || follow.getBroadcasterId() == null || follow.getBroadcasterId().isBlank()) { + throw new IllegalStateException("Invalid followed channels response: missing broadcaster_id"); + } + userIds.add(follow.getBroadcasterId()); } - - return list; + return new FollowedChannelPager.Page(userIds, set.getPagination().getCursor()); } public List search(String keyword, boolean liveOnly) { - var query = URLEncoder.encode(keyword, StandardCharsets.UTF_8); + // Feign expects URI encoding; form encoding would turn spaces into literal '+'. + var query = URLEncoder.encode(keyword, StandardCharsets.UTF_8).replace("+", "%20"); - var command = hystrixCommandWrapper(helix -> helix.searchChannels( + var command = request(helix -> helix.searchChannels( twitch.getAccessToken(), query, 40, @@ -144,6 +139,7 @@ public List search(String keyword, boolean liveOnly) { var broadcasters = getBroadcasters(userIds).stream().collect(Collectors.toMap(Broadcaster::getUserId, b -> b)); return results.stream() + .filter(r -> broadcasters.containsKey(r.getId())) .map(r -> new FoundChannel(broadcasters.get(r.getId()), r.getIsLive(), r.getGameName())) .toList(); } @@ -157,7 +153,7 @@ public List getBroadcasters(List userIds) { var broadcasters = new ArrayList(); for (var subUserList : subList) { - var set = hystrixCommandWrapper(helix -> helix.getUsers( + var set = request(helix -> helix.getUsers( twitch.getAccessToken(), subUserList, null) @@ -183,7 +179,7 @@ private List getTwitchStreams(List userIds) { for (var subUserIds : subLists) { var limit = Math.min(userIds.size(), 100); - var result = hystrixCommandWrapper(helix -> helix.getStreams( + var result = request(helix -> helix.getStreams( twitch.getAccessToken(), null, null, @@ -211,12 +207,12 @@ public List getStreams(List userIds) { } public List getGlobalBadgeSet() { - var set = hystrixCommandWrapper(helix -> helix.getGlobalChatBadges(twitch.getAccessToken())); + var set = request(helix -> helix.getGlobalChatBadges(twitch.getAccessToken())); return set.getBadgeSets(); } public List getChannelBadgeSet(Broadcaster broadcaster) { - var set = hystrixCommandWrapper(helix -> helix.getChannelChatBadges( + var set = request(helix -> helix.getChannelChatBadges( twitch.getAccessToken(), broadcaster.getUserId()) ); @@ -224,7 +220,7 @@ public List getChannelBadgeSet(Broadcaster broadcaster) { } public List getClips(List clipIds) { - var list = hystrixCommandWrapper(helix -> helix.getClips( + var list = request(helix -> helix.getClips( twitch.getAccessToken(), null, null, @@ -241,73 +237,57 @@ public List getClips(List clipIds) { } public boolean enableStreamEventListener(Broadcaster broadcaster) { - return channelListener.enableStreamEventListener(broadcaster); + return streamMonitor.enableStreamEventListener(broadcaster); } public void enableStreamEventListeners(Iterable broadcasters) { - channelListener.enableStreamEventListeners(broadcasters); + streamMonitor.enableStreamEventListeners(broadcasters); } public boolean disableStreamEventListener(Broadcaster broadcaster) { - return channelListener.disableStreamEventListenerForId(broadcaster); + return streamMonitor.disableStreamEventListenerForId(broadcaster); } - private T hystrixCommandWrapper(Function> function) { - - try { - semaphore.acquire(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - - try { - var helix = twitch.getClient().getHelix(); - var command = function.apply(helix); - return command.execute(); - - } catch (HystrixRuntimeException e) { - - if (e.getCause() instanceof UnauthorizedException) { - // トークンが無効になっていると判断してリフレッシュ - refreshAccessToken(); - return hystrixCommandWrapper(function); - } - - if (e.getCause() instanceof TimeoutException) { - LOGGER.warn(e.getMessage()); - return hystrixCommandWrapper(function); - } - - if (e.getCause() instanceof FeignException fe) { - LOGGER.warn(e.getMessage()); + private T request(Function function) { + return requests.execute(() -> { + checkCredentials(); + return function.apply(twitch.getClient().getHelix()); + }, this::refreshAccessToken); + } - // リトライしてみる - if (500 <= fe.status() && fe.status() <= 599) { - return hystrixCommandWrapper(function); - } - } + private void checkCredentials() { + if (invalidCredentials.get() || twitch.hasInvalidCredentials()) throw new InvalidCredentialException(); + if (twitch.isClosing() || twitch.isClosed()) throw new CancellationException("client session has ended"); + } - if (e.getCause() instanceof InterruptedException) { - LOGGER.info("interrupted current command"); - } else { - LOGGER.error("Hystrix Command Wrapper", e); + private void refreshAccessToken() { + try { refreshCredential(); } + catch (InvalidCredentialException failure) { + invalidCredentials.set(true); + twitch.invalidateCredentials(); + // 監視も更新ロックを使うため、ロックを解放してから終了完了を待つ。 + try { close(); } + catch (IOException | RuntimeException cleanupFailure) { + if (cleanupFailure != failure) failure.addSuppressed(cleanupFailure); } - - throw new RuntimeException(e); - - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - semaphore.release(); + throw failure; } } - private void refreshAccessToken() { - + private void refreshCredential() { var now = System.nanoTime(); - refreshLock.lock(); + try { + // 先行する更新は継続し、取り消された呼出元だけを待機から外す。 + refreshLock.lockInterruptibly(); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + var cancelled = new CancellationException("token refresh wait interrupted"); + cancelled.initCause(failure); + throw cancelled; + } try { + checkCredentials(); if (now < refreshTimestamp) { LOGGER.info("already refreshed"); return; @@ -315,23 +295,19 @@ private void refreshAccessToken() { LOGGER.info("start refresh"); - var controller = new CredentialController(twitch.getCredentialStore()); - var credential = controller.refreshToken(); + try (var controller = new CredentialController(twitch.getCredentialStore())) { + var credential = controller.refreshToken(); - // 資格情報がnullのときはリフレッシュできない何らかの事情があるためログアウトする - if (credential == null) { - twitch.logout(); - // 無効な資格情報をスロー - throw new InvalidCredentialException(); + if (credential == null) { + throw new InvalidCredentialException(); + } } - - twitch.updateCredential(credential); LOGGER.info("done refresh"); refreshTimestamp = System.nanoTime(); - } catch (InvalidCredentialException e) { - throw e; + } catch (InvalidCredentialException | CancellationException failure) { + throw failure; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); @@ -342,352 +318,6 @@ private void refreshAccessToken() { @Override public void close() throws IOException { - channelListener.close(); + streamMonitor.close(); } - - // TwitchClientHelperより - private class ChannelListener implements Closeable { - - private static final int MAX_LIMIT = 100; - - /** - * Holds the channels that are checked for live/offline state changes - */ - private final Set listenForGoLive = ConcurrentHashMap.newKeySet(); - - /** - * Channel Information Cache - */ - private final Cache channelInformation = CacheApi.create(spec -> { - spec.expiryType(ExpiryType.POST_ACCESS); - spec.expiryTime(Duration.ofMinutes(10L)); - spec.maxSize(1_048_576L); - }); - - /** - * Scheduled Thread Pool Executor - */ - private final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor( - 2, Thread.ofPlatform().name("Stream-Watch-Thread").daemon().factory()); - - /** - * Holds the {@link ExponentialBackoffStrategy} used for the stream status listener - */ - private final AtomicReference liveBackoff; - - /** - * The {@link Future} associated with streamStatusEventTask, in an atomic wrapper - */ - private final AtomicReference> streamStatusEventFuture = new AtomicReference<>(); - - /** - * Event Task - Stream Status - *

- * Accepts a list of channel ids not exceeding {@link ChannelListener#MAX_LIMIT} in size as the input - */ - private final Consumer> streamStatusEventTask; - - public ChannelListener() { - var defaultBackoff = ExponentialBackoffStrategy.builder().immediateFirst(false).baseMillis(1000L).jitter(false).build(); - this.liveBackoff = new AtomicReference<>(defaultBackoff); - - // Tasks - this.streamStatusEventTask = channels -> { - try { - Map streams = new HashMap<>(); - channels.forEach(id -> streams.put(id, null)); - - // check go live / stream events - var streamList = hystrixCommandWrapper(helix -> - helix.getStreams(null, null, null, channels.size(), null, null, channels, null)); - - streamList.getStreams().forEach(s -> streams.put(s.getUserId(), s)); - liveBackoff.get().reset(); // API call was successful - - streams.forEach((userId, stream) -> { - // Check if the channel's live status is still desired to be tracked - if (!listenForGoLive.contains(userId)) - return; - - ChannelCache currentChannelCache = channelInformation.computeIfAbsent(userId, s -> new ChannelCache()); - if (stream != null) { - // gracefully support name changes - currentChannelCache.setUserName(stream.getUserLogin()); - } - final EventChannel channel = new EventChannel(userId, currentChannelCache.getUserName()); - - boolean dispatchGoLiveEvent = false; - boolean dispatchGoOfflineEvent = false; - boolean dispatchTitleChangedEvent = false; - boolean dispatchGameChangedEvent = false; - boolean dispatchViewersChangedEvent = false; - - if (stream != null && stream.getType().equalsIgnoreCase("live")) { - // is live - // - live status - if (currentChannelCache.getIsLive() != null && !currentChannelCache.getIsLive()) { - dispatchGoLiveEvent = true; - } - currentChannelCache.setIsLive(true); - boolean wasAlreadyLive = !dispatchGoLiveEvent && currentChannelCache.getIsLive(); - - // - change stream title event - if (wasAlreadyLive && currentChannelCache.getTitle() != null && !currentChannelCache.getTitle().equalsIgnoreCase(stream.getTitle())) { - dispatchTitleChangedEvent = true; - } - currentChannelCache.setTitle(stream.getTitle()); - - // - change game event - if (wasAlreadyLive && currentChannelCache.getGameId() != null && !currentChannelCache.getGameId().equals(stream.getGameId())) { - dispatchGameChangedEvent = true; - } - currentChannelCache.setGameId(stream.getGameId()); - - // - change viewer count event - if (!stream.getViewerCount().equals(currentChannelCache.getViewerCount().getAndSet(stream.getViewerCount())) && wasAlreadyLive) { - dispatchViewersChangedEvent = true; - } - } else { - // was online previously? - if (currentChannelCache.getIsLive() != null && currentChannelCache.getIsLive()) { - dispatchGoOfflineEvent = true; - } - - // is offline - currentChannelCache.setIsLive(false); - currentChannelCache.setTitle(null); - currentChannelCache.setGameId(null); - currentChannelCache.getViewerCount().lazySet(null); - } - - var eventManager = twitch.getClient().getEventManager(); - - // dispatch events - // - go live event - if (dispatchGoLiveEvent) { - eventManager.publish(new ChannelGoLiveEvent(channel, stream)); - } - // - go offline event - if (dispatchGoOfflineEvent) { - eventManager.publish(new ChannelGoOfflineEvent(channel)); - } - // - title changed event - if (dispatchTitleChangedEvent) { - eventManager.publish(new ChannelChangeTitleEvent(channel, stream)); - } - // - game changed event - if (dispatchGameChangedEvent) { - eventManager.publish(new ChannelChangeGameEvent(channel, stream)); - } - // - viewer count changed event - if (dispatchViewersChangedEvent) { - eventManager.publish(new ChannelViewerCountUpdateEvent(channel, stream)); - } - }); - } catch (Exception ex) { - - LOGGER.error("Failed to check for Stream Events (Live/Offline/...): " + ex.getMessage()); - - executor.shutdown(); - - } - }; - } - - @Override - public void close() throws IOException { - cancel(streamStatusEventFuture); - executor.close(); - } - - public void enableStreamEventListeners(Iterable broadcasters) { - broadcasters.forEach(b -> { - if (listenForGoLive.add(b.getUserId())) { - channelInformation.computeIfAbsent(b.getUserId(), c -> new ChannelCache(b.getUserName())); - } - listenForGoLive.add(b.getUserId()); - }); - startOrStopEventGenerationThread(); - } - - public boolean enableStreamEventListener(Broadcaster broadcaster) { - var channelId = broadcaster.getUserId(); - var channelName = broadcaster.getUserLogin(); - - // add to set - final boolean add = listenForGoLive.add(channelId); - if (!add) { - LOGGER.info("Channel {} already added for Stream Events", channelName); - } else { - // initialize cache - channelInformation.computeIfAbsent(channelId, s -> new ChannelCache(channelName)); - } - startOrStopEventGenerationThread(); - return add; - } - - public boolean disableStreamEventListenerForId(Broadcaster broadcaster) { - var channelId = broadcaster.getUserId(); - - // remove from set - boolean remove = listenForGoLive.remove(channelId); - - // invalidate cache - if (remove) { - ChannelCache info = channelInformation.get(channelId); - if (info != null) { - info.setIsLive(null); - info.setGameId(null); - info.setTitle(null); - } - } - - startOrStopEventGenerationThread(); - return remove; - } - - /** - * Start or quit the thread, depending on usage - */ - private void startOrStopEventGenerationThread() { - // stream status event thread - updateListener(listenForGoLive::isEmpty, streamStatusEventFuture, this::runRecursiveStreamStatusCheck, liveBackoff); - } - - /** - * Performs the "heavy lifting" of starting or stopping a listener - * - * @param stopCondition yields whether the listener should be running - * @param futureReference the current listener in an atomic wrapper - * @param startCommand the command to start the listener - * @param backoff the {@link ExponentialBackoffStrategy} for the listener - */ - @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") // Acceptable as futureReference is only streamStatusEventFuture or followerEventFuture - private void updateListener(BooleanSupplier stopCondition, AtomicReference> futureReference, Runnable startCommand, AtomicReference backoff) { - if (stopCondition.getAsBoolean()) { - // Optimization to avoid obtaining an unnecessary lock - if (futureReference.get() != null) { - Future future = null; - synchronized (futureReference) { - if (stopCondition.getAsBoolean()) // Ensure conditions haven't changed in the time it took to acquire this lock - future = futureReference.getAndSet(null); // Clear out the listener future - } - - // Cancel the future - if (future != null) { - future.cancel(false); - backoff.get().reset(); // Ideally we would decrement to zero over time rather than instantly resetting - } - } - } else { - // Optimization to avoid obtaining an unnecessary lock - if (futureReference.get() == null) { - // Must synchronize to prevent race condition where multiple threads could be created - synchronized (futureReference) { - // Start if not already started - if (!stopCondition.getAsBoolean() && futureReference.get() == null) - futureReference.set(executor.schedule(startCommand, backoff.get().get(), TimeUnit.MILLISECONDS)); - } - } - } - } - - /** - * Initiates the stream status listener execution - */ - private void runRecursiveStreamStatusCheck() { - runRecursiveCheck(streamStatusEventFuture, executor, CollectionUtils.chunked(listenForGoLive, MAX_LIMIT), liveBackoff, this::runRecursiveStreamStatusCheck, chunk -> { - streamStatusEventTask.accept(chunk); - return false; // treat as always consuming from the api rate-limit - }); - } - - } - - @SuppressWarnings("SynchronizeOnNonFinalField") - private static class ListenerRunnable implements Runnable { - ScheduledExecutorService executor; - List channels; - AtomicReference> futureReference; - AtomicReference backoff; - Runnable startCommand; - Function executeSingle; - - public ListenerRunnable( - ScheduledExecutorService executor, - List channels, - AtomicReference> futureReference, - AtomicReference backoff, - Runnable startCommand, - Function executeSingle - ) { - this.executor = executor; - this.channels = channels; - this.futureReference = futureReference; - this.backoff = backoff; - this.startCommand = startCommand; - this.executeSingle = executeSingle; - } - - @Override - public void run() { - if (channels.isEmpty()) { - // Try again later if the task wasn't cancelled - if (futureReference.get() != null) - synchronized (futureReference) { - if (cancel(futureReference)) { - backoff.get().reset(); - futureReference.set(executor.schedule(startCommand, backoff.get().get(), TimeUnit.MILLISECONDS)); - } - } - } else { - // Start execution from the first element - run(0); - } - } - - private void run(final int index) { - // If no api call was made by executeSingle, it will return true. Then, we do not need to add any delay before checking the next channel. - Boolean skipDelay = executeSingle.apply(channels.get(index)); - - // Queue up the next check (if the task hasn't been cancelled) - if (futureReference.get() != null) - synchronized (futureReference) { - if (cancel(futureReference)) - futureReference.set( - executor.schedule( - index + 1 < channels.size() ? () -> run(index + 1) : startCommand, - skipDelay ? 0 : backoff.get().get(), - TimeUnit.MILLISECONDS - ) - ); - } - } - } - - private static boolean cancel(AtomicReference> futureRef) { - Future future = futureRef.get(); - return future != null && future.cancel(false); - } - - @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") - private static void runRecursiveCheck(AtomicReference> future, ScheduledExecutorService executor, List units, AtomicReference backoff, Runnable startCommand, Function task) { - if (future.get() != null) - synchronized (future) { - if (cancel(future)) - future.set( - executor.submit( - new ListenerRunnable<>( - executor, - units, - future, - backoff, - startCommand, - task - ) - ) - ); - } - } - } diff --git a/src/main/java/com/github/k7t3/tcv/domain/TwitchClientFactory.java b/src/main/java/com/github/k7t3/tcv/domain/TwitchClientFactory.java new file mode 100644 index 0000000..cf78617 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/domain/TwitchClientFactory.java @@ -0,0 +1,128 @@ +package com.github.k7t3.tcv.domain; + +import com.github.philippheuer.credentialmanager.CredentialManager; +import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; +import com.github.philippheuer.events4j.core.EventManager; +import com.github.twitch4j.chat.TwitchChat; +import com.github.twitch4j.chat.TwitchChatBuilder; +import com.github.twitch4j.common.config.Twitch4JGlobal; +import com.github.twitch4j.common.util.EventManagerUtils; +import com.github.philippheuer.events4j.simple.SimpleEventHandler; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import com.github.k7t3.tcv.lifecycle.OwnedScheduler; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +final class TwitchClientFactory { + record Context(CredentialManager credentials, OAuth2Credential token, EventManager events, ScheduledThreadPoolExecutor scheduler) {} + static final class Resources implements AutoCloseable { + private final TwitchClients client; + private final Context context; + private final HelixClientFactory.Handle http; + private final TwitchChat chat; + private final OwnedScheduler scheduler; + private final AtomicBoolean closed = new AtomicBoolean(); + private final CompletableFuture moduleCloseFinished = new CompletableFuture<>(); + private volatile Thread releasingThread; + Resources(Context context, HelixClientFactory.Handle http, TwitchChat chat, OwnedScheduler scheduler) { + this.context = context; this.http = http; this.chat = chat; + this.scheduler = scheduler; + this.client = new TwitchClients(context.events(), http.client(), chat, this::close); + } + TwitchClients client() { return client; } + @Override public void close() { + if (!closed.compareAndSet(false, true)) { + if (releasingThread == Thread.currentThread() || scheduler.isWorkerThread() + || http.isProcessingOnCurrentThread()) return; + moduleCloseFinished.join(); + CloseActions.runAll(http::awaitClosed, scheduler::close); + return; + } + releasingThread = Thread.currentThread(); + try { + CloseActions.runAll(http::close, chat::close, + context.events()::close, scheduler::close); + } finally { + moduleCloseFinished.complete(null); + releasingThread = null; + } + } + } + + private final Supplier schedulers; + private final Supplier events; + private final Function http; + private final Function chat; + + TwitchClientFactory(Supplier schedulers, Supplier events, + Function http, Function chat) { + this.schedulers = Objects.requireNonNull(schedulers); this.events = Objects.requireNonNull(events); + this.http = Objects.requireNonNull(http); this.chat = Objects.requireNonNull(chat); + } + + static Resources create(CredentialManager credentials, OAuth2Credential token) { + return create(credentials, token, () -> false); + } + + static Resources create(CredentialManager credentials, OAuth2Credential token, BooleanSupplier cancelled) { + var options = new HelixClientFactory.Options(Twitch4JGlobal.clientId, Twitch4JGlobal.clientSecret, + HelixClientFactory.OFFICIAL_BASE_URL, 5000); + var factory = new TwitchClientFactory(() -> { + var pool = new ScheduledThreadPoolExecutor(3, Thread.ofPlatform().daemon().name("tcv-twitch-",0).factory()); + pool.setRemoveOnCancelPolicy(true); + pool.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + return pool; + }, () -> EventManagerUtils.initializeEventManager(SimpleEventHandler.class), + context -> HelixClientFactory.create(context.credentials(), context.token(), context.scheduler(), options), + context -> TwitchChatBuilder.builder().withCredentialManager(context.credentials()).withChatAccount(context.token()) + .withEventManager(context.events()).withScheduledThreadPoolExecutor(context.scheduler()).build()); + return factory.open(credentials, token, cancelled); + } + + Resources open(CredentialManager credentials, OAuth2Credential token) { + return open(credentials, token, () -> false); + } + + Resources open(CredentialManager credentials, OAuth2Credential token, BooleanSupplier cancelled) { + checkCancelled(cancelled); + var pool = Objects.requireNonNull(schedulers.get()); + var ownedScheduler = new OwnedScheduler(pool); + EventManager eventManager = null; + HelixClientFactory.Handle transport = null; + TwitchChat chatClient = null; + try { + checkCancelled(cancelled); + eventManager = Objects.requireNonNull(events.get()); + checkCancelled(cancelled); + var context = new Context(credentials, token, eventManager, pool); + transport = Objects.requireNonNull(http.apply(context)); + checkCancelled(cancelled); + chatClient = Objects.requireNonNull(chat.apply(context)); + checkCancelled(cancelled); + var resources = new Resources(context, transport, chatClient, ownedScheduler); + checkCancelled(cancelled); + return resources; + } catch (RuntimeException | Error failure) { + var ownedEvents = eventManager; var ownedHttp = transport; var ownedChat = chatClient; + CloseActions.runAll(() -> { + if (failure instanceof RuntimeException exception) throw exception; + throw (Error) failure; + }, + () -> { if (ownedChat != null) ownedChat.close(); }, + () -> { if (ownedHttp != null) ownedHttp.close(); }, + () -> { if (ownedEvents != null) ownedEvents.close(); }, ownedScheduler::close); + throw failure; + } + } + + private static void checkCancelled(BooleanSupplier cancelled) { + if (Thread.currentThread().isInterrupted() || cancelled.getAsBoolean()) + throw new CancellationException("Client construction has ended"); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/domain/TwitchClients.java b/src/main/java/com/github/k7t3/tcv/domain/TwitchClients.java new file mode 100644 index 0000000..a40defa --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/domain/TwitchClients.java @@ -0,0 +1,25 @@ +package com.github.k7t3.tcv.domain; + +import com.github.philippheuer.events4j.core.EventManager; +import com.github.twitch4j.chat.TwitchChat; +import java.util.Objects; + +/** このセッションで使うSDKモジュールと、その所有者への終了要求。 */ +public final class TwitchClients implements AutoCloseable { + private final EventManager events; + private final HelixClient helix; + private final TwitchChat chat; + private final Runnable release; + + TwitchClients(EventManager events, HelixClient helix, TwitchChat chat, Runnable release) { + this.events = Objects.requireNonNull(events); + this.helix = Objects.requireNonNull(helix); + this.chat = Objects.requireNonNull(chat); + this.release = Objects.requireNonNull(release); + } + + public EventManager getEventManager() { return events; } + public HelixClient getHelix() { return helix; } + public TwitchChat getChat() { return chat; } + @Override public void close() { release.run(); } +} diff --git a/src/main/java/com/github/k7t3/tcv/domain/TwitchLoader.java b/src/main/java/com/github/k7t3/tcv/domain/TwitchLoader.java index 01187db..9e6c1f9 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/TwitchLoader.java +++ b/src/main/java/com/github/k7t3/tcv/domain/TwitchLoader.java @@ -18,41 +18,102 @@ import com.github.k7t3.tcv.domain.auth.CredentialController; import com.github.k7t3.tcv.domain.auth.CredentialStore; +import com.github.k7t3.tcv.domain.auth.SessionCredentialStore; +import com.github.k7t3.tcv.lifecycle.CloseActions; import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; -import com.github.twitch4j.TwitchClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; import java.util.function.Consumer; +import java.util.function.Function; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; -public class TwitchLoader { +public class TwitchLoader implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(TwitchLoader.class); public record DeviceFlow(String userCode, String verificationURL, String completeURL) {} - private final CredentialStore credentialStore; private final CredentialController controller; + private final Function clientFactory; + private final AtomicBoolean closed = new AtomicBoolean(); + private final AtomicBoolean controllerReleased = new AtomicBoolean(); + private final CompletableFuture controllerReleaseCompleted = new CompletableFuture<>(); + private final SessionCredentialStore scope; + private final Object ownership = new Object(); + private boolean transferred; + private int activeCalls; + private Throwable cleanupFailure; + private final ThreadLocal callDepth = ThreadLocal.withInitial(() -> 0); public TwitchLoader(CredentialStore credentialStore) { - this.credentialStore = credentialStore; - controller = new CredentialController(credentialStore); + this(new SessionCredentialStore(credentialStore)); + } + + private TwitchLoader(SessionCredentialStore scope) { + this(scope, new CredentialController(scope)); + } + + private TwitchLoader(SessionCredentialStore scope, CredentialController controller) { + this(controller, credential -> createAppClient(scope, controller, credential), scope); + } + + TwitchLoader(CredentialController controller, Function clientFactory) { + this(controller, clientFactory, null); + } + + private TwitchLoader(CredentialController controller, Function clientFactory, + SessionCredentialStore scope) { + this.controller = controller; + this.clientFactory = clientFactory; + this.scope = scope; } public DeviceFlow startAuthenticate(Consumer> consumer) { + if (!enterCall()) throw new IllegalStateException("credential loader is closed"); + try { return startOwnedAuthentication(consumer); } + finally { leaveCall(); } + } + + private DeviceFlow startOwnedAuthentication(Consumer> consumer) { var flow = controller.startAuthenticate(result -> { - if (result) { - controller.disposeAuthenticate(); - var twitch = createAppClient(controller.getCredential()); - consumer.accept(Optional.of(twitch)); - } else { - consumer.accept(Optional.empty()); + if (!enterCall()) return; + try { + if (result) { + final Twitch twitch; + try { + twitch = clientFactory.apply(controller.getCredential()); + } catch (RuntimeException failure) { + LOGGER.warn("failed to create authenticated client", failure); + if (!closed.get()) consumer.accept(Optional.empty()); + return; + } + if (!transfer()) { + closeUnacceptedClient(twitch); + return; + } + consumer.accept(Optional.of(twitch)); + } else { + consumer.accept(Optional.empty()); + } + } finally { + try { releaseController(); } + finally { leaveCall(); } } }); return new DeviceFlow(flow.userCode(), flow.verificationURL(), flow.completeURL()); } public Optional load() { + if (!enterCall()) throw new IllegalStateException("credential loader is closed"); + try { return loadOwnedClient(); } + finally { leaveCall(); } + } + + private Optional loadOwnedClient() { + if (closed.get()) throw new IllegalStateException("credential loader is closed"); if (!controller.isAuthorized()) { return Optional.empty(); } @@ -81,19 +142,119 @@ public Optional load() { } } - return Optional.of(createAppClient(credential)); + var twitch = clientFactory.apply(credential); + if (transfer()) return Optional.of(twitch); + closeUnacceptedClient(twitch); + return Optional.empty(); } - private Twitch createAppClient(OAuth2Credential credential) { + private static Twitch createAppClient(SessionCredentialStore credentialStore, CredentialController controller, + OAuth2Credential credential) { + credential = controller.resolveUserIdentity(credential); + credentialStore.bind(credential); var credentialManager = controller.getCredentialManager(); - var client = TwitchClientBuilder.builder() - .withCredentialManager(credentialManager) - .withDefaultAuthToken(credential) - .withEnableHelix(true) - .withChatAccount(credential) - .withEnableChat(true) - .build(); - return new Twitch(credential, credentialStore, client); + credentialManager.getCredentials().clear(); + credentialManager.getCredentials().add(credential); + TwitchClientFactory.Resources resources = null; + try { + resources = TwitchClientFactory.create(credentialManager, credential, credentialStore::isRetired); + var owned = resources; + return new Twitch(credential, credentialStore, owned.client(), owned::close); + } catch (RuntimeException | Error failure) { + var owned = resources; + CloseActions.runAll(() -> { + if (failure instanceof RuntimeException exception) throw exception; + throw (Error) failure; + }, credentialStore::retire, () -> { if (owned != null) owned.close(); }); + throw failure; + } + } + + private boolean transfer() { + synchronized (ownership) { + if (closed.get()) return false; + transferred = true; + return true; + } + } + + @Override + public void close() { + synchronized (ownership) { + closed.set(true); + if (!transferred && scope != null) scope.retire(); + } + releaseController(); + } + + private void releaseController() { + if (!controllerReleased.compareAndSet(false, true)) return; + try { + controller.close(); + controllerReleaseCompleted.complete(null); + } catch (RuntimeException | Error failure) { + controllerReleaseCompleted.completeExceptionally(failure); + throw failure; + } + } + + /** UI の close 要求とは別に、認証 I/O・callback・未採用 client の解放まで背景で待つ。 */ + public void awaitClosed() { + if (callDepth.get() > 0) throw new IllegalStateException("cannot await the current credential operation"); + CloseActions.runAll(this::close, () -> { + try { controllerReleaseCompleted.join(); } + catch (CompletionException failure) { rethrow(failure.getCause()); } + }, controller::awaitAuthenticationStopped, this::awaitCalls, () -> { + synchronized (ownership) { if (cleanupFailure != null) rethrow(cleanupFailure); } + }); + } + + private void closeUnacceptedClient(Twitch client) { + try { client.close(); } + catch (RuntimeException | Error failure) { + synchronized (ownership) { + if (cleanupFailure == null) cleanupFailure = failure; + else if (cleanupFailure != failure) cleanupFailure.addSuppressed(failure); + } + throw failure; + } + } + + private boolean enterCall() { + synchronized (ownership) { + if (closed.get()) return false; + activeCalls++; + callDepth.set(callDepth.get() + 1); + return true; + } + } + + private void leaveCall() { + synchronized (ownership) { + activeCalls--; + var remaining = callDepth.get() - 1; + if (remaining == 0) callDepth.remove(); + else callDepth.set(remaining); + ownership.notifyAll(); + } + } + + private void awaitCalls() { + boolean interrupted = false; + try { + synchronized (ownership) { + while (activeCalls > 0) { + try { ownership.wait(); } + catch (InterruptedException ignored) { interrupted = true; } + } + } + } finally { if (interrupted) Thread.currentThread().interrupt(); } + } + + private static void rethrow(Throwable failure) { + if (failure instanceof RuntimeException exception) throw exception; + if (failure instanceof Error error) throw error; + throw new RuntimeException(failure); } } diff --git a/src/main/java/com/github/k7t3/tcv/domain/TwitchRequestExecutor.java b/src/main/java/com/github/k7t3/tcv/domain/TwitchRequestExecutor.java new file mode 100644 index 0000000..1d02e2b --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/domain/TwitchRequestExecutor.java @@ -0,0 +1,90 @@ +/* + * Copyright 2026 k7t3 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.github.k7t3.tcv.domain; + +import com.github.twitch4j.common.exception.UnauthorizedException; +import feign.FeignException; +import feign.RetryableException; +import feign.codec.DecodeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.Semaphore; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletionException; +import com.github.k7t3.tcv.domain.exception.InvalidCredentialException; +import java.util.concurrent.TimeoutException; +import java.util.function.Supplier; + +/** 呼出元のスレッドで API を実行し、同時実行数・再試行・割り込みを管理する。 */ +final class TwitchRequestExecutor { + + private static final Logger LOGGER = LoggerFactory.getLogger(TwitchRequestExecutor.class); + private static final int MAX_REQUEST_ATTEMPTS = 5; + private static final long RETRY_DELAY_MILLIS = 250; + + private final Semaphore semaphore = new Semaphore(4, true); + + T execute(Supplier request, Runnable refreshAccessToken) { + for (var attempt = 1; ; attempt++) { + try { + if (attempt > 1) Thread.sleep(RETRY_DELAY_MILLIS << (attempt - 2)); + semaphore.acquire(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + + try { + return request.get(); + } catch (CancellationException | InvalidCredentialException e) { + throw e; + } catch (Exception e) { + var cause = e instanceof CompletionException && e.getCause() != null ? e.getCause() : e; + if (cause instanceof CancellationException cancelled) throw cancelled; + if (cause instanceof DecodeException decoded + && decoded.getCause() instanceof CancellationException cancelled) throw cancelled; + if (cause instanceof InterruptedException || cause.getCause() instanceof InterruptedException) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + if (attempt >= MAX_REQUEST_ATTEMPTS) throw new RuntimeException(e); + if (cause instanceof UnauthorizedException) { + refreshAccessToken.run(); + continue; + } + + if (cause instanceof TimeoutException) { + LOGGER.warn("Twitch API request timed out"); + continue; + } + + if (cause instanceof FeignException fe) { + LOGGER.warn("Twitch API request failed with status {}", fe.status()); + if (500 <= fe.status() && fe.status() <= 599) continue; + if (fe.status() == 429 || fe.status() < 0 && fe instanceof RetryableException) continue; + } + + LOGGER.error("Twitch API request failed", e); + throw new RuntimeException(e); + } finally { + // 次の試行と待機の前に通信枠を返し、他のリクエストを妨げない。 + semaphore.release(); + } + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/domain/auth/CredentialController.java b/src/main/java/com/github/k7t3/tcv/domain/auth/CredentialController.java index d40b1f1..917fcea 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/auth/CredentialController.java +++ b/src/main/java/com/github/k7t3/tcv/domain/auth/CredentialController.java @@ -22,39 +22,68 @@ import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; import com.github.twitch4j.auth.domain.TwitchScopes; import com.github.twitch4j.auth.providers.TwitchIdentityProvider; +import com.github.k7t3.tcv.lifecycle.CloseActions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.Executors; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; -public class CredentialController { +public class CredentialController implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(CredentialController.class); private static final String CLIENT_ID = "m2xt95z7dxg78rys5ds3ugc7klxjwn"; private static final String REDIRECT_URL = null; - private final TwitchIdentityProvider identityProvider = new TwitchIdentityProvider(CLIENT_ID, null, REDIRECT_URL); + private final TwitchIdentityProvider identityProvider; private final DeviceFlowController authController; private final CredentialManager credentialManager; + private final ScheduledExecutorService flowExecutor; + private final AtomicBoolean closed = new AtomicBoolean(); + private final CompletableFuture stopRequested = new CompletableFuture<>(); + private final AtomicReference undeliveredPersistenceFailure = new AtomicReference<>(); + private final ThreadLocal callbackDepth = ThreadLocal.withInitial(() -> 0); - private final boolean authorized; - - private OAuth2Credential credential; + private volatile OAuth2Credential credential; public CredentialController(CredentialStore credentialStore) { - var flowExecutor = Executors.newSingleThreadScheduledExecutor(Thread.ofVirtual().factory()); - authController = new DeviceFlowController(flowExecutor, 0); - credentialManager = new CredentialManager(credentialStore, authController); - credentialManager.registerIdentityProvider(identityProvider); - authorized = !credentialManager.getCredentials().isEmpty(); - - if (authorized) { - credential = (OAuth2Credential) credentialManager.getCredentials().getFirst(); + this(credentialStore, Executors.newSingleThreadScheduledExecutor(Thread.ofVirtual().factory())); + } + + private CredentialController(CredentialStore store, ScheduledExecutorService scheduler) { + this(store, new TwitchIdentityProvider(CLIENT_ID, null, REDIRECT_URL), + new DeviceFlowController(scheduler, 0), scheduler); + } + + // scheduler と flow の所有権を引き受ける。 + CredentialController(CredentialStore credentialStore, TwitchIdentityProvider identityProvider, + DeviceFlowController flow, ScheduledExecutorService scheduler) { + this.identityProvider = identityProvider; + this.authController = flow; + this.flowExecutor = scheduler; + try { + credentialManager = new CredentialManager(credentialStore, authController); + credentialManager.registerIdentityProvider(identityProvider); + if (!credentialManager.getCredentials().isEmpty()) { + credential = (OAuth2Credential) credentialManager.getCredentials().getFirst(); + } + } catch (RuntimeException | Error failure) { + try { + close(); + } catch (RuntimeException | Error cleanupFailure) { + if (cleanupFailure != failure) failure.addSuppressed(cleanupFailure); + } + throw failure; } } @@ -63,7 +92,7 @@ public CredentialController(CredentialStore credentialStore) { * @return すでに認可トークンが生成されていた場合はTrue */ public boolean isAuthorized() { - return authorized; + return credential != null; } /** @@ -71,42 +100,68 @@ public boolean isAuthorized() { * @return 生成済みの認可トークンが有効であるかを判定した結果 */ public boolean validateToken() { - if (!authorized) return false; + if (!isAuthorized()) return false; return identityProvider.isCredentialValid(credential).orElse(false); } public OAuth2Credential refreshToken() { + final OAuth2Credential refreshed; try { - var refreshed = identityProvider.refreshCredential(credential).orElse(null); - if (refreshed != null) { - credentialManager.getCredentials().clear(); - credentialManager.addCredential(identityProvider.getProviderName(), refreshed); - credentialManager.save(); - - this.credential = refreshed; - } - return refreshed; + refreshed = identityProvider.refreshCredential(credential).orElse(null); + } catch (CancellationException cancelled) { + throw cancelled; } catch (RuntimeException e) { // リフレッシュに失敗した場合 LOGGER.warn("failed to refresh", e); return null; } + // 保存の失敗は認証失効と区別して返す。元の保存値を削除させない。 + if (refreshed != null) { + var credentials = credentialManager.getCredentials(); + var index = credentials.indexOf(credential); + if (index < 0) throw new IllegalStateException("credential is not managed by this authentication attempt"); + credentialManager.addCredential(identityProvider.getProviderName(), refreshed); + // SDK は追加時に別の補完済み資格情報を作ることがある。 + var saved = (OAuth2Credential) credentials.removeLast(); + credentials.set(index, saved); + credentialManager.save(); + this.credential = saved; + return saved; + } + return null; } - public void revokeToken() { - if (!authorized) return; - identityProvider.revokeCredential(credential); + /** 保存先を読み直さず、呼び出し元のセッションが所有する資格情報だけを失効する。 */ + public static void revokeToken(OAuth2Credential credential) { + if (!new TwitchIdentityProvider(CLIENT_ID, null, REDIRECT_URL).revokeCredential(credential)) { + throw new IllegalStateException("failed to revoke session credential"); + } } public OAuth2Credential getCredential() { return credential; } + public OAuth2Credential resolveUserIdentity(OAuth2Credential current) { + if (current.getUserId() != null && !current.getUserId().isBlank()) return current; + var resolved = identityProvider.getAdditionalCredentialInformation(current) + .filter(value -> value.getUserId() != null && !value.getUserId().isBlank()) + .orElseThrow(() -> new IllegalStateException("Unable to resolve Twitch user identity")); + var credentials = credentialManager.getCredentials(); + var index = credentials.indexOf(current); + if (index < 0) throw new IllegalStateException("credential is not managed by this authentication attempt"); + credentials.set(index, resolved); + credentialManager.save(); + credential = resolved; + return resolved; + } + public CredentialManager getCredentialManager() { return credentialManager; } public DeviceFlow startAuthenticate(Consumer callback) { + if (closed.get()) throw new IllegalStateException("credential controller is closed"); List scopes = List.of( TwitchScopes.HELIX_USER_FOLLOWS_READ, TwitchScopes.CHAT_READ @@ -123,16 +178,85 @@ public DeviceFlow startAuthenticate(Consumer callback) { * @param response レスポンス */ private void callback(DeviceTokenResponse response, Consumer callback) { - var credential = response.getCredential(); + if (closed.get()) return; + callbackDepth.set(callbackDepth.get() + 1); + try { deliver(response, callback); } + finally { + var remaining = callbackDepth.get() - 1; + if (remaining == 0) callbackDepth.remove(); + else callbackDepth.set(remaining); + } + } + + private void deliver(DeviceTokenResponse response, Consumer callback) { + var received = response.getCredential(); + var credential = received == null ? null : credentialManager.getCredentials().stream() + .filter(OAuth2Credential.class::isInstance).map(OAuth2Credential.class::cast) + .filter(candidate -> java.util.Objects.equals(candidate.getIdentityProvider(), received.getIdentityProvider()) + && java.util.Objects.equals(candidate.getAccessToken(), received.getAccessToken())) + .findFirst().orElse(received); if (credential != null) { - credentialManager.save(); + try { credentialManager.save(); } + catch (Error failure) { + retainPersistenceFailure(failure); + throw failure; + } + catch (RuntimeException failure) { + if (!closed.get()) { + LOGGER.warn("failed to persist authenticated credential", failure); + callback.accept(false); + } else if (!(failure instanceof CancellationException)) { + retainPersistenceFailure(failure); + } + return; + } + if (closed.get()) return; this.credential = credential; } - callback.accept(credential != null); + if (!closed.get()) callback.accept(credential != null); + } + + private void retainPersistenceFailure(Throwable failure) { + var previous = undeliveredPersistenceFailure.compareAndExchange(null, failure); + if (previous != null && previous != failure) previous.addSuppressed(failure); } public void disposeAuthenticate() { - authController.close(); + if (!closed.compareAndSet(false, true)) return; + try { + CloseActions.runAll(authController::close, flowExecutor::shutdownNow); + stopRequested.complete(null); + } catch (RuntimeException | Error failure) { + stopRequested.completeExceptionally(failure); + throw failure; + } + } + + /** + * 停止を要求し、所有schedulerの実終了後に未通知の保存失敗も回収する。 + * 終了に伴う保存取消と通知済みの認証失敗は再送出しない。 + * UIと認証callback自身からは待たないこと。 + */ + public void awaitAuthenticationStopped() { + if (callbackDepth.get() > 0) throw new IllegalStateException("cannot await the current authentication callback"); + CloseActions.runAll(this::disposeAuthenticate, () -> { + try { stopRequested.join(); } + catch (CompletionException failure) { rethrow(failure.getCause()); } + }, flowExecutor::close, () -> { + var failure = undeliveredPersistenceFailure.get(); + if (failure != null) rethrow(failure); + }); + } + + private static void rethrow(Throwable failure) { + if (failure instanceof RuntimeException exception) throw exception; + if (failure instanceof Error error) throw error; + throw new RuntimeException(failure); + } + + @Override + public void close() { + disposeAuthenticate(); } public record DeviceFlow(String userCode, String verificationURL, String completeURL) {} diff --git a/src/main/java/com/github/k7t3/tcv/domain/auth/CredentialStore.java b/src/main/java/com/github/k7t3/tcv/domain/auth/CredentialStore.java index a2dd4a2..136a995 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/auth/CredentialStore.java +++ b/src/main/java/com/github/k7t3/tcv/domain/auth/CredentialStore.java @@ -17,12 +17,29 @@ package com.github.k7t3.tcv.domain.auth; import com.github.philippheuer.credentialmanager.api.IStorageBackend; +import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; +import com.github.philippheuer.credentialmanager.domain.Credential; +import java.util.List; +import java.util.Optional; +import java.util.function.BooleanSupplier; public interface CredentialStore extends IStorageBackend { + record Snapshot(String revision, List credentials) { + public Snapshot { credentials = List.copyOf(credentials); } + } + + Snapshot snapshot(); + + /** 比較と許可判定と保存を同じ排他区間で行い、変更した版を返す。 */ + Optional compareAndSet(Snapshot expected, List replacement, BooleanSupplier permitted); + /** * 保存されている資格情報をクリアする */ void clearCredentials(); + /** 現在の保存値に同じ provider / access token がある場合だけ、その資格情報を削除する。 */ + boolean removeCredential(OAuth2Credential expected); + } diff --git a/src/main/java/com/github/k7t3/tcv/domain/auth/SessionCredentialStore.java b/src/main/java/com/github/k7t3/tcv/domain/auth/SessionCredentialStore.java new file mode 100644 index 0000000..2e78be3 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/domain/auth/SessionCredentialStore.java @@ -0,0 +1,201 @@ +package com.github.k7t3.tcv.domain.auth; + +import com.github.k7t3.tcv.domain.exception.InvalidCredentialException; +import com.github.philippheuer.credentialmanager.domain.Credential; +import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; + +/** SDK と API に、その認証試行・セッションだけの資格情報と保存権を渡す。 */ +public final class SessionCredentialStore implements CredentialStore { + private enum State { ACTIVE, RETIRED, INVALID } + private final CredentialStore backing; + private final Object writes = new Object(); + private final AtomicReference state = new AtomicReference<>(State.ACTIVE); + private final AtomicBoolean notified = new AtomicBoolean(); + private final ConcurrentHashMap> tokenHistory = new ConcurrentHashMap<>(); + private volatile Snapshot lease; + private volatile List visible; + private volatile OAuth2Credential own; + private volatile boolean ownsStoredCredential; + private volatile Runnable invalidated; + private volatile Consumer updated = ignored -> {}; + + public SessionCredentialStore(CredentialStore backing) { + this.backing = Objects.requireNonNull(backing); + var initial = backing.snapshot(); + lease = new Snapshot(initial.revision(), copies(initial.credentials())); + visible = copies(initial.credentials()); + remember(visible); + } + + public SessionCredentialStore(CredentialStore backing, OAuth2Credential credential) { + this(backing); + bind(credential); + } + + public void bind(OAuth2Credential credential) { + synchronized (writes) { + checkWritable(); + if (own != null) throw new IllegalStateException("credential scope is already bound"); + own = copy(credential); + ownsStoredCredential = lease.credentials().stream().anyMatch(value -> sameCredential(value, credential)); + visible = List.of(copy(credential)); + remember(visible); + } + } + + public boolean isRetired() { return state.get() == State.RETIRED; } + public boolean isInvalid() { return state.get() == State.INVALID; } + public void retire() { state.compareAndSet(State.ACTIVE, State.RETIRED); } + public void awaitWrites() { synchronized (writes) { /* 保存の確定を背景で待つ。 */ } } + public OAuth2Credential credential() { return copy(Objects.requireNonNull(own)); } + + public Set tokens() { + var selected = own; + if (selected != null) return Set.copyOf(tokenHistory.getOrDefault(key(selected), Set.of())); + return tokenHistory.values().stream().flatMap(Set::stream).collect(java.util.stream.Collectors.toUnmodifiableSet()); + } + + public void onUpdated(Consumer listener) { updated = Objects.requireNonNull(listener); } + public void onInvalidated(Runnable listener) { + invalidated = Objects.requireNonNull(listener); + notifyInvalidation(); + } + + public void invalidate() { + state.compareAndSet(State.ACTIVE, State.INVALID); + notifyInvalidation(); + } + + private void notifyInvalidation() { + var listener = invalidated; + if (state.get() == State.INVALID && listener != null && notified.compareAndSet(false, true)) listener.run(); + } + + @Override public List loadCredentials() { return new ArrayList<>(copies(visible)); } + @Override public Snapshot snapshot() { + synchronized (writes) { return new Snapshot(lease.revision(), copies(visible)); } + } + @Override public Optional getCredentialByUserId(String id) { + return loadCredentials().stream().filter(value -> id != null && id.equalsIgnoreCase(value.getUserId())).findFirst(); + } + + @Override + public void saveCredentials(List credentials) { + try { + synchronized (writes) { + checkWritable(); + if (commit(credentials, () -> true).isEmpty()) { + checkWritable(); + state.compareAndSet(State.ACTIVE, State.INVALID); + throw new InvalidCredentialException(); + } + } + } finally { notifyInvalidation(); } + } + + @Override + public Optional compareAndSet(Snapshot expected, List credentials, BooleanSupplier permitted) { + synchronized (writes) { + if (!expected.revision().equals(lease.revision()) || state.get() != State.ACTIVE) return Optional.empty(); + return commit(credentials, permitted); + } + } + + private Optional commit(List credentials, BooleanSupplier permitted) { + var next = copies(credentials); + var replacement = next; + if (own != null) { + if (!ownsStoredCredential) return Optional.empty(); + if (next.size() > 1 || next.stream().anyMatch(value -> !sameAccount(value, own))) { + throw new IllegalArgumentException("credentials do not belong to this session"); + } + replacement = new ArrayList<>(lease.credentials()); + replacement.removeIf(value -> sameAccount(value, own)); + replacement.addAll(0, next); + } + // 保存の許可判定を通過した更新は、retire と競合しても履歴に残す。 + remember(next); + var result = backing.compareAndSet(lease, replacement, () -> state.get() == State.ACTIVE && permitted.getAsBoolean()); + if (result.isEmpty()) return Optional.empty(); + lease = new Snapshot(result.get().revision(), copies(result.get().credentials())); + visible = next; + if (own != null && !next.isEmpty()) { + own = copy((OAuth2Credential) next.getFirst()); + updated.accept(copy(own)); + } + return Optional.of(new Snapshot(lease.revision(), copies(visible))); + } + + @Override public void clearCredentials() { + var selected = own; + if (selected == null) saveCredentials(List.of()); + else removeCredential(selected); + } + + @Override + public boolean removeCredential(OAuth2Credential expected) { + synchronized (writes) { + if (own == null || !ownsStoredCredential || !sameCredential(own, expected)) return false; + var next = new ArrayList<>(lease.credentials()); + next.removeIf(value -> sameCredential(value, own)); + var result = backing.compareAndSet(lease, next, () -> true); + if (result.isEmpty()) return false; + lease = new Snapshot(result.get().revision(), copies(result.get().credentials())); + visible = List.of(); + ownsStoredCredential = false; + return true; + } + } + + private void checkWritable() { + if (isRetired()) throw new CancellationException("credential session has ended"); + if (isInvalid()) throw new InvalidCredentialException(); + } + + private void remember(List values) { + for (var value : values) { + if (value instanceof OAuth2Credential oauth && oauth.getAccessToken() != null) { + tokenHistory.computeIfAbsent(key(oauth), ignored -> ConcurrentHashMap.newKeySet()).add(oauth.getAccessToken()); + } + } + } + + private static String key(OAuth2Credential value) { return value.getIdentityProvider() + ":" + value.getUserId(); } + private static boolean sameAccount(Credential first, OAuth2Credential second) { + return first instanceof OAuth2Credential oauth + && Objects.equals(oauth.getIdentityProvider(), second.getIdentityProvider()) + && Objects.equals(oauth.getUserId(), second.getUserId()); + } + private static boolean sameCredential(Credential first, OAuth2Credential second) { + return sameAccount(first, second) && first instanceof OAuth2Credential oauth + && Objects.equals(oauth.getAccessToken(), second.getAccessToken()) + && Objects.equals(oauth.getRefreshToken(), second.getRefreshToken()); + } + private static List copies(List values) { + return values.stream().map(value -> { + if (!(value instanceof OAuth2Credential oauth)) throw new IllegalArgumentException("unsupported credential type"); + return (Credential) copy(oauth); + }).toList(); + } + private static OAuth2Credential copy(OAuth2Credential value) { + // SDK updateCredential mutates this list; isolate it without making it unmodifiable. + var result = new OAuth2Credential(value.getIdentityProvider(), value.getAccessToken(), value.getRefreshToken(), + value.getUserId(), value.getUserName(), value.getExpiresIn(), new ArrayList<>(value.getScopes()), + new HashMap<>(value.getContext())); + result.setReceivedAt(value.getReceivedAt()); + return result; + } +} diff --git a/src/main/java/com/github/k7t3/tcv/domain/channel/ChannelRepository.java b/src/main/java/com/github/k7t3/tcv/domain/channel/ChannelRepository.java index 9106473..1683c45 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/channel/ChannelRepository.java +++ b/src/main/java/com/github/k7t3/tcv/domain/channel/ChannelRepository.java @@ -17,8 +17,10 @@ package com.github.k7t3.tcv.domain.channel; import com.github.k7t3.tcv.domain.Twitch; +import com.github.k7t3.tcv.domain.TwitchAPI; import com.github.k7t3.tcv.domain.chat.ChatRoomEventProvider; import com.github.k7t3.tcv.domain.event.EventPublishers; +import com.github.k7t3.tcv.lifecycle.CloseActions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -60,7 +62,7 @@ public ChannelRepository(Twitch twitch, EventPublishers publishers) { public Collection getOrLoadChannels() { channelLock.lock(); try { - return Collections.unmodifiableCollection(channels.values()); + return List.copyOf(channels.values()); } finally { channelLock.unlock(); } @@ -71,12 +73,9 @@ public Collection getOrLoadChannels() { */ public void loadAllRelatedChannels() { LOGGER.info("load all follows"); - if (loaded) return; - - loaded = true; - channelLock.lock(); try { + if (loaded) return; channelEventProvider.listen(); chatEventProvider.listen(); @@ -93,19 +92,16 @@ public void loadAllRelatedChannels() { .findFirst() .orElse(null); - var channel = new TwitchChannel(twitch, broadcaster, stream, chatEventProvider, this); - channel.setFollowing(true); - channel.setPersistent(true); - channels.put(broadcaster.getUserId(), channel); - channelEventProvider.add(channel); + registerChannel(api, broadcaster, stream, true); } - - // Stream GoLive/GoOffline/GameChange/TitleChange - channels.values() - .stream() - .map(TwitchChannel::getBroadcaster) - .forEach(api::enableStreamEventListener); // TODO 一括 - + loaded = true; + } catch (RuntimeException | Error failure) { + try { + clear(); + } catch (RuntimeException | Error cleanup) { + if (cleanup != failure) failure.addSuppressed(cleanup); + } + throw failure; } finally { channelLock.unlock(); } @@ -113,16 +109,13 @@ public void loadAllRelatedChannels() { public List getOrLoadChannels(Collection userIds) { LOGGER.info("load channels ({})", userIds); - if (!loaded) throw new IllegalStateException("not loaded yet"); - if (userIds.isEmpty()) { - return List.of(); - } - var list = new ArrayList(); var loadIds = new ArrayList(); channelLock.lock(); try { + if (!loaded) throw new IllegalStateException("not loaded yet"); + if (userIds.isEmpty()) return List.of(); for (var userId : userIds) { var channel = channels.get(userId); @@ -133,6 +126,7 @@ public List getOrLoadChannels(Collection userIds) { } loadIds.add(userId); } + if (loadIds.isEmpty()) return list; var api = twitch.getTwitchAPI(); var broadcasters = api.getBroadcasters(loadIds); @@ -144,15 +138,7 @@ public List getOrLoadChannels(Collection userIds) { .findFirst() .orElse(null); - var channel = new TwitchChannel(twitch, broadcaster, stream, chatEventProvider, this); - channels.put(broadcaster.getUserId(), channel); - - // Stream 監視イベントを有効化 - api.enableStreamEventListener(channel.getBroadcaster()); - - channelEventProvider.add(channel); - - list.add(channel); + list.add(registerChannel(api, broadcaster, stream, false)); } } finally { channelLock.unlock(); @@ -171,10 +157,9 @@ public List getOrLoadChannels(Collection userIds) { */ public TwitchChannel getOrLoadChannel(Broadcaster broadcaster) { LOGGER.info("load channel ({})", broadcaster); - if (!loaded) throw new IllegalStateException("not loaded yet"); - channelLock.lock(); try { + if (!loaded) throw new IllegalStateException("not loaded yet"); var channel = channels.get(broadcaster.getUserId()); if (channel != null) { @@ -185,18 +170,31 @@ public TwitchChannel getOrLoadChannel(Broadcaster broadcaster) { var api = twitch.getTwitchAPI(); var stream = api.getStream(broadcaster.getUserId()).orElse(null); - channel = new TwitchChannel(twitch, broadcaster, stream, chatEventProvider, this); - channels.put(broadcaster.getUserId(), channel); + return registerChannel(api, broadcaster, stream, false); - // Stream 監視イベントを有効化 - api.enableStreamEventListener(channel.getBroadcaster()); + } finally { + channelLock.unlock(); + } + } + /** channelLock 内で監視登録まで成功したモデルだけを公開する。 */ + private TwitchChannel registerChannel(TwitchAPI api, Broadcaster broadcaster, StreamInfo stream, boolean following) { + var channel = new TwitchChannel(twitch, broadcaster, stream, chatEventProvider, this); + channel.setFollowing(following); + channel.setPersistent(following); + try { + api.enableStreamEventListener(broadcaster); channelEventProvider.add(channel); - + channels.put(broadcaster.getUserId(), channel); return channel; - - } finally { - channelLock.unlock(); + } catch (RuntimeException | Error failure) { + try { + CloseActions.runAll(() -> api.disableStreamEventListener(broadcaster), + () -> channelEventProvider.remove(channel)); + } catch (RuntimeException | Error cleanup) { + if (cleanup != failure) failure.addSuppressed(cleanup); + } + throw failure; } } @@ -210,23 +208,16 @@ public TwitchChannel getOrLoadChannel(Broadcaster broadcaster) { */ public void releaseChannel(TwitchChannel channel) { LOGGER.info("release channel ({})", channel); - if (!loaded) return; - - // 永続化しているチャンネルは開放しない - if (channel.isPersistent()) return; - - var api = twitch.getTwitchAPI(); - channelLock.lock(); try { - channels.remove(channel.getBroadcaster().getUserId()); - - // Stream 監視イベントを無効化 - api.disableStreamEventListener(channel.getBroadcaster()); - - // チャンネルに関するイベントの発行を停止 - channelEventProvider.remove(channel); - + if (!loaded || channel.isPersistent()) return; + var id = channel.getBroadcaster().getUserId(); + if (channels.get(id) != channel) return; + channels.remove(id); + CloseActions.runAll( + channel::dispose, + () -> twitch.getTwitchAPI().disableStreamEventListener(channel.getBroadcaster()), + () -> channelEventProvider.remove(channel)); } finally { channelLock.unlock(); } @@ -236,21 +227,17 @@ public void releaseChannel(TwitchChannel channel) { * ロードしているチャンネルをすべてクリアする */ public void clear() { - var api = twitch.getTwitchAPI(); - channelLock.lock(); try { - for (var channel : channels.values()) { - channel.leaveChat(); - api.disableStreamEventListener(channel.getBroadcaster()); - - // チャンネルに関するイベントの発行を停止 - channelEventProvider.remove(channel); - } - + var owned = List.copyOf(channels.values()); channels.clear(); - channelEventProvider.clean(); - chatEventProvider.clean(); + loaded = false; + var releases = owned.stream().map(channel -> (Runnable) () -> CloseActions.runAll( + channel::dispose, + () -> twitch.getTwitchAPI().disableStreamEventListener(channel.getBroadcaster()) + )).toArray(Runnable[]::new); + CloseActions.runAll(channelEventProvider::clean, chatEventProvider::clean, + () -> CloseActions.runAll(releases)); } finally { channelLock.unlock(); } diff --git a/src/main/java/com/github/k7t3/tcv/domain/channel/TwitchChannel.java b/src/main/java/com/github/k7t3/tcv/domain/channel/TwitchChannel.java index f3099e2..d727275 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/channel/TwitchChannel.java +++ b/src/main/java/com/github/k7t3/tcv/domain/channel/TwitchChannel.java @@ -21,11 +21,11 @@ import com.github.k7t3.tcv.domain.chat.ChatRoom; import com.github.k7t3.tcv.domain.chat.ChatRoomEventProvider; import com.github.twitch4j.helix.domain.ChatBadgeSet; +import com.github.k7t3.tcv.lifecycle.CloseActions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; -import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -43,8 +43,10 @@ public class TwitchChannel { private List badgeSets = null; private final AtomicBoolean badgeLoaded = new AtomicBoolean(false); - private boolean following = false; - private boolean persistent = false; + private volatile boolean following; + private volatile boolean persistent; + private final Object chatLock = new Object(); + private volatile boolean closed; TwitchChannel( Twitch twitch, @@ -67,15 +69,16 @@ public class TwitchChannel { *

*/ public void loadBadgesIfNotLoaded() { - if (badgeLoaded.get()) return; - - var api = twitch.getTwitchAPI(); - badgeSets = api.getChannelBadgeSet(broadcaster); - - badgeLoaded.set(true); + synchronized (chatLock) { + checkOpen(); + if (badgeLoaded.get()) return; + var api = twitch.getTwitchAPI(); + badgeSets = List.copyOf(api.getChannelBadgeSet(broadcaster)); + badgeLoaded.set(true); + } } - private ChatRoom chatRoom; + private volatile ChatRoom chatRoom; /** * このチャンネルのチャットルームに参加しているかを返す @@ -85,6 +88,11 @@ public boolean isChatJoined() { return chatRoom != null; } + /** 通信や参加を行わず、現在のルームの参照だけを取得する。 */ + public Optional getJoinedChatRoom() { + return Optional.ofNullable(chatRoom); + } + /** * チャットルームに参加する *

@@ -93,13 +101,18 @@ public boolean isChatJoined() { * @return チャットルーム */ public ChatRoom getOrJoinChatRoom() { - if (chatRoom != null) return chatRoom; - LOGGER.info("{} chat room created", getChannelName()); - - chatRoom = new ChatRoom(twitch, broadcaster, this); - chatEventProvider.onJoined(chatRoom); + synchronized (chatLock) { + checkOpen(); + if (chatRoom != null) return chatRoom; + LOGGER.info("{} chat room created", getChannelName()); + chatRoom = new ChatRoom(twitch, broadcaster, this); + chatEventProvider.onJoined(chatRoom); + return chatRoom; + } + } - return chatRoom; + private void checkOpen() { + if (closed) throw new IllegalStateException("channel is closed"); } /** @@ -109,17 +122,37 @@ public ChatRoom getOrJoinChatRoom() { *

*/ public void leaveChat() { - if (chatRoom == null) return; - - chatRoom.leave(); - chatEventProvider.onLeft(chatRoom); - - // フォローされていないチャンネルはチャットを使い終わった時点でクリアする - if (!isPersistent()) { - repository.releaseChannel(this); - } + leaveRoom(false); + } + + /** リポジトリによる解放。以後は同じインスタンスから参加しない。 */ + void dispose() { + leaveRoom(true); + } + + private void leaveRoom(boolean dispose) { + var release = new AtomicBoolean(); + CloseActions.runAll(() -> { + synchronized (chatLock) { + if (dispose) closed = true; + var owned = chatRoom; + if (owned == null) return; + if (!isPersistent()) { + closed = true; + release.set(!dispose); + } + chatRoom = null; + CloseActions.runAll(owned::leave, () -> chatEventProvider.onLeft(owned)); + } + }, () -> { + // channelLock を必要とする処理は chatLock の外へ出し、clear とのロック逆転を防ぐ。 + if (release.get()) repository.releaseChannel(this); + }); + } - chatRoom = null; + /** SDK イベントの取得元を、I/O や chatLock の待機なしに判定する。 */ + public boolean isActiveIn(ChannelRepository owner) { + return owner != null && repository == owner && !closed; } public Broadcaster getBroadcaster() { @@ -182,20 +215,6 @@ public Optional getBadgeUrl(ChatBadge badge) { return Optional.empty(); } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof TwitchChannel that)) return false; - return persistent == that.persistent - && Objects.equals(broadcaster, that.broadcaster) - && Objects.equals(chatRoom, that.chatRoom); - } - - @Override - public int hashCode() { - return Objects.hash(broadcaster, persistent, chatRoom); - } - @Override public String toString() { return "TwitchChannel{" + diff --git a/src/main/java/com/github/k7t3/tcv/domain/channel/TwitchChannelEventProvider.java b/src/main/java/com/github/k7t3/tcv/domain/channel/TwitchChannelEventProvider.java index 5104a58..7c7007f 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/channel/TwitchChannelEventProvider.java +++ b/src/main/java/com/github/k7t3/tcv/domain/channel/TwitchChannelEventProvider.java @@ -18,14 +18,11 @@ import com.github.k7t3.tcv.domain.Twitch; import com.github.k7t3.tcv.domain.event.EventPublishers; +import com.github.k7t3.tcv.domain.event.EventSubscriptionScope; import com.github.k7t3.tcv.domain.event.channel.ChannelOfflineEvent; import com.github.k7t3.tcv.domain.event.channel.ChannelOnlineEvent; import com.github.k7t3.tcv.domain.event.channel.StreamStateUpdateEvent; -import com.github.philippheuer.events4j.api.domain.IDisposable; -import com.github.twitch4j.events.*; - -import java.util.ArrayList; -import java.util.List; +import com.github.k7t3.tcv.domain.event.stream.StreamStateEvent; import java.util.concurrent.ConcurrentHashMap; class TwitchChannelEventProvider { @@ -35,7 +32,8 @@ class TwitchChannelEventProvider { private final Twitch twitch; private final EventPublishers eventPublishers; - private List subscriptions; + private final Object lifecycleLock = new Object(); + private EventSubscriptionScope subscriptions; public TwitchChannelEventProvider(Twitch twitch, EventPublishers publishers) { this.twitch = twitch; @@ -49,70 +47,88 @@ public void add(TwitchChannel channel) { public void remove(TwitchChannel channel) { var channelId = channel.getBroadcaster().getUserId(); - channelMap.remove(channelId); + channelMap.computeIfPresent(channelId, (id, current) -> current == channel ? null : current); } public void listen() { - if (subscriptions != null) throw new IllegalStateException(); - - var client = twitch.getClient(); - var eventManager = client.getEventManager(); - - subscriptions = new ArrayList<>(); - subscriptions.add(eventManager.onEvent(ChannelGoLiveEvent.class, this::onChannelGoLiveEvent)); - subscriptions.add(eventManager.onEvent(ChannelGoOfflineEvent.class, this::onChannelGoOfflineEvent)); - subscriptions.add(eventManager.onEvent(ChannelViewerCountUpdateEvent.class, this::onChannelViewerCountUpdateEvent)); - subscriptions.add(eventManager.onEvent(ChannelChangeTitleEvent.class, this::onChannelChangeTitleEvent)); - subscriptions.add(eventManager.onEvent(ChannelChangeGameEvent.class, this::onChannelChangeGameEvent)); + final EventSubscriptionScope opening; + synchronized (lifecycleLock) { + if (subscriptions != null) throw new IllegalStateException("channel events are already registered"); + opening = new EventSubscriptionScope(); + subscriptions = opening; + } + try { + opening.register(scope -> { + var eventManager = twitch.getClient().getEventManager(); + scope.subscribe(eventManager, StreamStateEvent.Online.class, this::onChannelGoLiveEvent); + scope.subscribe(eventManager, StreamStateEvent.Offline.class, this::onChannelGoOfflineEvent); + scope.subscribe(eventManager, StreamStateEvent.Viewers.class, this::onChannelViewerCountUpdateEvent); + scope.subscribe(eventManager, StreamStateEvent.Title.class, this::onChannelChangeTitleEvent); + scope.subscribe(eventManager, StreamStateEvent.Game.class, this::onChannelChangeGameEvent); + }); + } catch (RuntimeException | Error failure) { + synchronized (lifecycleLock) { + if (subscriptions == opening) subscriptions = null; + } + throw failure; + } } public void clean() { - if (subscriptions == null || subscriptions.isEmpty()) return; - for (var sub : subscriptions) - sub.dispose(); - subscriptions.clear(); + final EventSubscriptionScope owned; + synchronized (lifecycleLock) { + owned = subscriptions; + subscriptions = null; + channelMap.clear(); + } + if (owned != null) owned.close(); } - private void onChannelGoLiveEvent(ChannelGoLiveEvent e) { - var channel = channelMap.get(e.getChannel().getId()); + private void onChannelGoLiveEvent(StreamStateEvent.Online e) { + var channel = channelMap.get(e.userId()); if (channel == null) return; - var stream = StreamInfo.of(e.getStream()); + var stream = e.stream(); + channel.setStream(stream); var onlineEvent = new ChannelOnlineEvent(channel, stream); eventPublishers.submit(onlineEvent); } - private void onChannelGoOfflineEvent(ChannelGoOfflineEvent e) { - var channel = channelMap.get(e.getChannel().getId()); + private void onChannelGoOfflineEvent(StreamStateEvent.Offline e) { + var channel = channelMap.get(e.userId()); if (channel == null) return; + channel.setStream(null); var offlineEvent = new ChannelOfflineEvent(channel); eventPublishers.submit(offlineEvent); } - private void onChannelViewerCountUpdateEvent(ChannelViewerCountUpdateEvent e) { - var channel = channelMap.get(e.getChannel().getId()); + private void onChannelViewerCountUpdateEvent(StreamStateEvent.Viewers e) { + var channel = channelMap.get(e.userId()); if (channel == null) return; - var stream = StreamInfo.of(e.getStream()); + var stream = e.stream(); + channel.setStream(stream); var onlineEvent = new StreamStateUpdateEvent(channel, stream); eventPublishers.submit(onlineEvent); } - private void onChannelChangeTitleEvent(ChannelChangeTitleEvent e) { - var channel = channelMap.get(e.getChannel().getId()); + private void onChannelChangeTitleEvent(StreamStateEvent.Title e) { + var channel = channelMap.get(e.userId()); if (channel == null) return; - var stream = StreamInfo.of(e.getStream()); + var stream = e.stream(); + channel.setStream(stream); var onlineEvent = new StreamStateUpdateEvent(channel, stream); eventPublishers.submit(onlineEvent); } - private void onChannelChangeGameEvent(ChannelChangeGameEvent e) { - var channel = channelMap.get(e.getChannel().getId()); + private void onChannelChangeGameEvent(StreamStateEvent.Game e) { + var channel = channelMap.get(e.userId()); if (channel == null) return; - var stream = StreamInfo.of(e.getStream()); + var stream = e.stream(); + channel.setStream(stream); var onlineEvent = new StreamStateUpdateEvent(channel, stream); eventPublishers.submit(onlineEvent); } diff --git a/src/main/java/com/github/k7t3/tcv/domain/channel/TwitchChannelListener.java b/src/main/java/com/github/k7t3/tcv/domain/channel/TwitchChannelListener.java deleted file mode 100644 index b8a5e3d..0000000 --- a/src/main/java/com/github/k7t3/tcv/domain/channel/TwitchChannelListener.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2024 k7t3 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.github.k7t3.tcv.domain.channel; - -public interface TwitchChannelListener { - - void onOnline(TwitchChannel channel, StreamInfo info); - - void onOffline(TwitchChannel channel); - - void onViewerCountUpdated(TwitchChannel channel, StreamInfo info); - - void onTitleChanged(TwitchChannel channel, StreamInfo info); - - void onGameChanged(TwitchChannel channel, StreamInfo info); - -} diff --git a/src/main/java/com/github/k7t3/tcv/domain/chat/ChatMessageFragment.java b/src/main/java/com/github/k7t3/tcv/domain/chat/ChatMessageFragment.java index b5b05d6..bede98d 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/chat/ChatMessageFragment.java +++ b/src/main/java/com/github/k7t3/tcv/domain/chat/ChatMessageFragment.java @@ -19,9 +19,9 @@ /** * チャットメッセージを構成する部品。 * @param type 部品が表す種類 - * @param text メッセージのテキスト - * @param additional 部品に付属する追加情報。 - * エモートの場合は識別子を表し、絵文字のときはHexコードを表す。 + * @param text テキスト・絵文字の表示文字列。エモートでは画像取得に使う識別子 + * @param additional エモートの表示名、または絵文字のコードポイントをハイフンで連結した16進表記。 + * テキストではnull */ public record ChatMessageFragment( Type type, diff --git a/src/main/java/com/github/k7t3/tcv/domain/chat/ChatMessageParser.java b/src/main/java/com/github/k7t3/tcv/domain/chat/ChatMessageParser.java index 9c3e7e9..4b6f376 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/chat/ChatMessageParser.java +++ b/src/main/java/com/github/k7t3/tcv/domain/chat/ChatMessageParser.java @@ -16,33 +16,22 @@ package com.github.k7t3.tcv.domain.chat; -import org.jetbrains.annotations.NotNull; - import java.text.BreakIterator; import java.util.ArrayList; -import java.util.Collections; +import java.util.Comparator; import java.util.List; /** * チャットメッセージのパーサー。 - *

- * エモートの文字位置を正確に検出するためには - * 書記素クラスタを考慮して文字を分解する必要がある。 - *

- *

- * TwitchのIRC実装は標準に基づきUTF-8を使用している。 - * 一方でJavaは文字列の形式にUTF-16を使用するためコードポイントの数に - * 着目して処理する必要がある。 - *

+ *

位置タグをコードポイント単位で検証してから、UTF-16の半開区間へ変換する。 + * 書記素を途中で切る範囲、不正な範囲、重複する範囲は本文を保ったまま除外する。 + * 同じ開始位置では先に記載された範囲を優先する。

+ *

エモート以外の本文は書記素単位でテキストと絵文字へ分割する。

*/ public class ChatMessageParser { - private record Emote(String id, int begin, int end) implements Comparable { - @Override - public int compareTo(@NotNull ChatMessageParser.Emote o) { - return Integer.compare(begin(), o.begin()); - } - } + /** 検証済みエモートのUTF-16半開区間。 */ + private record Emote(String id, int begin, int endExclusive) {} public ChatMessage parse(String message, String emoteInfo) { if (message == null || message.isEmpty()) { @@ -50,72 +39,33 @@ public ChatMessage parse(String message, String emoteInfo) { } var fragments = new ArrayList(); - var emotes = parseEmotes(emoteInfo); - var emote = emotes.isEmpty() ? null : emotes.getFirst(); - var emoteIndex = 0; + var cursor = 0; + for (var emote : parseEmotes(emoteInfo, message)) { + appendText(fragments, message.substring(cursor, emote.begin())); + fragments.add(ChatMessageFragment.emote(emote.id(), message.substring(emote.begin(), emote.endExclusive()))); + cursor = emote.endExclusive(); + } + appendText(fragments, message.substring(cursor)); + return new ChatMessage(message, List.copyOf(fragments)); + } + private void appendText(List fragments, String text) { + if (text.isEmpty()) return; var boundary = BreakIterator.getCharacterInstance(); - boundary.setText(message); - - // 文字位置を指定するカーソル - int cursor = 0; - - // 読み取った文字列を再構成するためのバッファ + boundary.setText(text); var builder = new StringBuilder(); - int start = boundary.first(); for (var end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) { - // 適切な境界で分解された一文字 - var singleChar = message.substring(start, end); - - if (emote == null) { - // 文字を構成する先頭のコードポイントを取得 - var codePoint = singleChar.codePointAt(0); - if (Character.isEmoji(codePoint)) { // 絵文字のとき - builder = cleanBufferAsText(fragments, builder); - handleEmojiChar(fragments, singleChar, codePoint); - } else { - builder.append(singleChar); - } + var singleChar = text.substring(start, end); + var codePoint = singleChar.codePointAt(0); + if (Character.isEmoji(codePoint)) { + builder = cleanBufferAsText(fragments, builder); + handleEmojiChar(fragments, singleChar, codePoint); } else { - if (cursor < emote.begin()) { // エモートに到達していない間はテキスト・絵文字として扱う - // 文字を構成する先頭のコードポイントを取得 - var codePoint = singleChar.codePointAt(0); - if (Character.isEmoji(codePoint)) { // 絵文字のとき - builder = cleanBufferAsText(fragments, builder); - handleEmojiChar(fragments, singleChar, codePoint); - } else { - builder.append(singleChar); - } - } else if (cursor == emote.begin()) { // エモートに到達したときはそれまでのバッファをクリア - builder = cleanBufferAsText(fragments, builder); - builder.append(singleChar); - } else if (cursor < emote.end()) { // エモートの終了まで - builder.append(singleChar); - } else if (cursor == emote.end()) { // エモートが終了したとき - builder.append(singleChar); - var name = builder.toString(); // 名前を取得 - builder = new StringBuilder(); // クリーン - var fragment = ChatMessageFragment.emote(emote.id(), name); - fragments.add(fragment); - // 次のエモートに移動 - if (emoteIndex + 1 < emotes.size()) { - emoteIndex += 1; - emote = emotes.get(emoteIndex); - } else { - emote = null; - } - } + builder.append(singleChar); } - - // コードポイント準拠の文字数 - var charCount = singleChar.codePointCount(0, singleChar.length()); - cursor += charCount; } - cleanBufferAsText(fragments, builder); - - return new ChatMessage(message, fragments); } private void handleEmojiChar(List fragments, String emojiChar, int codePoint) { @@ -144,24 +94,56 @@ private StringBuilder cleanBufferAsText(List fragments, Str return new StringBuilder(); } - private List parseEmotes(String emoteValue) { + private List parseEmotes(String emoteValue, String message) { if (emoteValue == null || emoteValue.isEmpty()) { return List.of(); } + var offsets = codePointOffsets(message); + var codePointCount = offsets.length - 1; + var boundary = BreakIterator.getCharacterInstance(); + boundary.setText(message); var result = new ArrayList(); var emotes = emoteValue.split("/"); for (var emote : emotes) { var emoteSplit = emote.split(":", 2); + if (emoteSplit.length != 2) continue; var id = emoteSplit[0]; + if (id.isBlank()) continue; var ranges = emoteSplit[1].split(","); for (var range : ranges) { var rangeSplit = range.split("-", 2); - var begin = Integer.parseInt(rangeSplit[0]); - var end = Integer.parseInt(rangeSplit[1]); - result.add(new Emote(id, begin, end)); + if (rangeSplit.length != 2) continue; + try { + var begin = Integer.parseInt(rangeSplit[0]); + var end = Integer.parseInt(rangeSplit[1]); + if (begin < 0 || end < begin || end >= codePointCount) continue; + var beginOffset = offsets[begin]; + var endOffset = offsets[end + 1]; + if (!boundary.isBoundary(beginOffset) || !boundary.isBoundary(endOffset)) continue; + result.add(new Emote(id, beginOffset, endOffset)); + } catch (NumberFormatException invalidRange) { + // 不正な位置情報だけを除外し、本文と他の範囲を保つ。 + continue; + } } } - Collections.sort(result); - return result; + result.sort(Comparator.comparingInt(Emote::begin)); + var nonOverlapping = new ArrayList(); + var previousEnd = 0; + for (var emote : result) { + if (emote.begin() < previousEnd) continue; + nonOverlapping.add(emote); + previousEnd = emote.endExclusive(); + } + return List.copyOf(nonOverlapping); + } + + private int[] codePointOffsets(String message) { + var count = message.codePointCount(0, message.length()); + var offsets = new int[count + 1]; + for (var index = 0; index < count; index++) { + offsets[index + 1] = offsets[index] + Character.charCount(message.codePointAt(offsets[index])); + } + return offsets; } } diff --git a/src/main/java/com/github/k7t3/tcv/domain/chat/ChatRoom.java b/src/main/java/com/github/k7t3/tcv/domain/chat/ChatRoom.java index 256a96d..a4ee7c0 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/chat/ChatRoom.java +++ b/src/main/java/com/github/k7t3/tcv/domain/chat/ChatRoom.java @@ -49,6 +49,11 @@ public TwitchChannel getChannel() { return channel; } + /** 遅れて配送されたイベントを、所有するクライアントのセッションに限定する。 */ + public boolean isOwnedBy(Twitch owner) { + return twitch == owner; + } + public void leave() { LOGGER.info("{} leave chat", getBroadcaster().getUserLogin()); diff --git a/src/main/java/com/github/k7t3/tcv/domain/chat/ChatRoomEventProvider.java b/src/main/java/com/github/k7t3/tcv/domain/chat/ChatRoomEventProvider.java index f3f0418..6b6cf2e 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/chat/ChatRoomEventProvider.java +++ b/src/main/java/com/github/k7t3/tcv/domain/chat/ChatRoomEventProvider.java @@ -18,80 +18,93 @@ import com.github.k7t3.tcv.domain.Twitch; import com.github.k7t3.tcv.domain.event.EventPublishers; +import com.github.k7t3.tcv.domain.event.EventSubscriptionScope; import com.github.k7t3.tcv.domain.event.chat.*; -import com.github.philippheuer.events4j.api.domain.IDisposable; import com.github.twitch4j.chat.events.channel.*; import com.github.twitch4j.chat.events.roomstate.EmoteOnlyEvent; import com.github.twitch4j.chat.events.roomstate.FollowersOnlyEvent; import com.github.twitch4j.chat.events.roomstate.SlowModeEvent; import com.github.twitch4j.chat.events.roomstate.SubscribersOnlyEvent; - -import java.util.ArrayList; -import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class ChatRoomEventProvider { - private final ConcurrentHashMap chatRoomMap = new ConcurrentHashMap<>(); - private final ConcurrentHashMap> stateMap = new ConcurrentHashMap<>(); + private record RoomRegistration(ChatRoom room, Set states) {} + private final ConcurrentHashMap rooms = new ConcurrentHashMap<>(); private final Twitch twitch; private final EventPublishers eventPublishers; private final ChatMessageParser parser = new ChatMessageParser(); - private final ClipFinder clipFinder; + private final ClipLinkParser clipLinks = new ClipLinkParser(); - private List subscriptions; + private final Object lifecycleLock = new Object(); + private EventSubscriptionScope subscriptions; public ChatRoomEventProvider(Twitch twitch, EventPublishers eventPublishers) { this.twitch = twitch; this.eventPublishers = eventPublishers; - this.clipFinder = new ClipFinder(twitch); } public void onJoined(ChatRoom chatRoom) { var channelId = chatRoom.getBroadcaster().getUserId(); - chatRoomMap.put(channelId, chatRoom); - stateMap.put(channelId, ConcurrentHashMap.newKeySet()); + rooms.put(channelId, new RoomRegistration(chatRoom, ConcurrentHashMap.newKeySet())); } public void onLeft(ChatRoom chatRoom) { var channelId = chatRoom.getBroadcaster().getUserId(); - chatRoomMap.remove(channelId); - stateMap.remove(channelId); + rooms.computeIfPresent(channelId, (id, current) -> current.room() == chatRoom ? null : current); } public void listen() { - if (subscriptions != null) throw new IllegalStateException(); - - var chat = twitch.getChat(); - var eventManager = chat.getEventManager(); - - subscriptions = new ArrayList<>(); - subscriptions.add(eventManager.onEvent(ChannelMessageEvent.class, this::onChannelMessageEvent)); - subscriptions.add(eventManager.onEvent(SubscriptionEvent.class, this::onSubscriptionEvent)); - subscriptions.add(eventManager.onEvent(ClearChatEvent.class, this::onClearChatEvent)); - subscriptions.add(eventManager.onEvent(DeleteMessageEvent.class, this::onDeleteMessageEvent)); - subscriptions.add(eventManager.onEvent(EmoteOnlyEvent.class, this::onEmoteOnlyEvent)); - subscriptions.add(eventManager.onEvent(FollowersOnlyEvent.class, this::onFollowersOnlyEvent)); - subscriptions.add(eventManager.onEvent(RaidEvent.class, this::onRaidEvent)); - subscriptions.add(eventManager.onEvent(SlowModeEvent.class, this::onSlowModeEvent)); - subscriptions.add(eventManager.onEvent(SubscribersOnlyEvent.class, this::onSubscribersOnlyEvent)); - subscriptions.add(eventManager.onEvent(CheerEvent.class, this::onCheerEvent)); + final EventSubscriptionScope opening; + synchronized (lifecycleLock) { + if (subscriptions != null) throw new IllegalStateException("chat events are already registered"); + opening = new EventSubscriptionScope(); + subscriptions = opening; + } + try { + opening.register(scope -> { + var eventManager = twitch.getChat().getEventManager(); + scope.subscribe(eventManager, ChannelMessageEvent.class, this::onChannelMessageEvent); + scope.subscribe(eventManager, SubscriptionEvent.class, this::onSubscriptionEvent); + scope.subscribe(eventManager, ClearChatEvent.class, this::onClearChatEvent); + scope.subscribe(eventManager, DeleteMessageEvent.class, this::onDeleteMessageEvent); + scope.subscribe(eventManager, EmoteOnlyEvent.class, this::onEmoteOnlyEvent); + scope.subscribe(eventManager, FollowersOnlyEvent.class, this::onFollowersOnlyEvent); + scope.subscribe(eventManager, RaidEvent.class, this::onRaidEvent); + scope.subscribe(eventManager, SlowModeEvent.class, this::onSlowModeEvent); + scope.subscribe(eventManager, SubscribersOnlyEvent.class, this::onSubscribersOnlyEvent); + scope.subscribe(eventManager, CheerEvent.class, this::onCheerEvent); + }); + } catch (RuntimeException | Error failure) { + synchronized (lifecycleLock) { + if (subscriptions == opening) subscriptions = null; + } + throw failure; + } } public void clean() { - if (subscriptions == null || subscriptions.isEmpty()) return; - for (var sub : subscriptions) - sub.dispose(); - subscriptions.clear(); + final EventSubscriptionScope owned; + synchronized (lifecycleLock) { + owned = subscriptions; + subscriptions = null; + rooms.clear(); + } + if (owned != null) owned.close(); + } + + private ChatRoom findRoom(String channelId) { + var registration = rooms.get(channelId); + return registration == null ? null : registration.room(); } private void updateRoomState(String channelId, ChatRoomState roomState, boolean active) { - var chatRoom = chatRoomMap.get(channelId); - if (chatRoom == null) return; - var roomStates = stateMap.get(channelId); - if (roomStates == null) return; + var registration = rooms.get(channelId); + if (registration == null) return; + var chatRoom = registration.room(); + var roomStates = registration.states(); if (active) { roomStates.add(roomState); @@ -139,7 +152,7 @@ private ChatData parseMessageEvent(IRCMessageEvent item) { } private void onChannelMessageEvent(ChannelMessageEvent e) { - var chatRoom = chatRoomMap.get(e.getChannel().getId()); + var chatRoom = findRoom(e.getChannel().getId()); if (chatRoom == null) return; var message = e.getMessage(); @@ -148,7 +161,7 @@ private void onChannelMessageEvent(ChannelMessageEvent e) { var postedEvent = new ChatMessageEvent(chatRoom, chatData); eventPublishers.submitChatMessage(postedEvent); - var clipOp = clipFinder.findClip(message); + var clipOp = clipLinks.parse(message); clipOp.ifPresent(clipChatMessage -> { var clipPostedEvent = new ClipPostedEvent(chatRoom, clipChatMessage); eventPublishers.submit(clipPostedEvent); @@ -156,7 +169,7 @@ private void onChannelMessageEvent(ChannelMessageEvent e) { } private void onSubscriptionEvent(SubscriptionEvent e) { - var chatRoom = chatRoomMap.get(e.getChannel().getId()); + var chatRoom = findRoom(e.getChannel().getId()); if (chatRoom == null) return; var user = e.getUser(); @@ -174,7 +187,7 @@ private void onSubscriptionEvent(SubscriptionEvent e) { } private void onClearChatEvent(ClearChatEvent e) { - var chatRoom = chatRoomMap.get(e.getChannel().getId()); + var chatRoom = findRoom(e.getChannel().getId()); if (chatRoom == null) return; var clearedEvent = new ChatClearedEvent(chatRoom); @@ -182,7 +195,7 @@ private void onClearChatEvent(ClearChatEvent e) { } private void onDeleteMessageEvent(DeleteMessageEvent e) { - var chatRoom = chatRoomMap.get(e.getChannel().getId()); + var chatRoom = findRoom(e.getChannel().getId()); if (chatRoom == null) return; var deletedEvent = new ChatMessageDeletedEvent(chatRoom, e.getMsgId()); @@ -206,7 +219,7 @@ private void onSubscribersOnlyEvent(SubscribersOnlyEvent e) { } private void onRaidEvent(RaidEvent e) { - var chatRoom = chatRoomMap.get(e.getChannel().getId()); + var chatRoom = findRoom(e.getChannel().getId()); if (chatRoom == null) return; var raider = e.getRaider(); @@ -217,7 +230,7 @@ private void onRaidEvent(RaidEvent e) { } private void onCheerEvent(CheerEvent event) { - var chatRoom = chatRoomMap.get(event.getChannel().getId()); + var chatRoom = findRoom(event.getChannel().getId()); if (chatRoom == null) return; var chatData = parseMessageEvent(event.getMessageEvent()); diff --git a/src/main/java/com/github/k7t3/tcv/domain/chat/ChatRoomListener.java b/src/main/java/com/github/k7t3/tcv/domain/chat/ChatRoomListener.java deleted file mode 100644 index 72632a4..0000000 --- a/src/main/java/com/github/k7t3/tcv/domain/chat/ChatRoomListener.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2024 k7t3 - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.github.k7t3.tcv.domain.chat; - -public interface ChatRoomListener { - - void onChatDataPosted(ChatRoom chatRoom, ChatData item); - - void onClipPosted(ChatRoom chatRoom, ClipChatMessage clipChatMessage); - - void onChatCleared(ChatRoom chatRoom); - - void onChatMessageDeleted(ChatRoom chatRoom, String messageId); - - void onStateUpdated(ChatRoom chatRoom, ChatRoomState roomState, boolean active); - - void onRaidReceived(ChatRoom chatRoom, String raiderName, int viewerCount); - - void onUserSubscribed(ChatRoom chatRoom, ChatData chatData); - - void onUserGiftedSubscribe(ChatRoom chatRoom, String giverName, String userName); - - void onCheered(ChatRoom chatRoom, ChatCheer cheer); - -} diff --git a/src/main/java/com/github/k7t3/tcv/domain/chat/ClipFinder.java b/src/main/java/com/github/k7t3/tcv/domain/chat/ClipFinder.java index 0a8531a..60bcde7 100644 --- a/src/main/java/com/github/k7t3/tcv/domain/chat/ClipFinder.java +++ b/src/main/java/com/github/k7t3/tcv/domain/chat/ClipFinder.java @@ -22,18 +22,14 @@ import org.slf4j.LoggerFactory; import java.net.URI; -import java.net.URISyntaxException; import java.util.List; import java.util.Optional; -import java.util.regex.Pattern; public class ClipFinder { private static final Logger LOGGER = LoggerFactory.getLogger(ClipFinder.class); - private static final Pattern CLIP_URL_PATTERN = Pattern.compile( - "https://((www\\.twitch\\.tv|m\\.twitch\\.tv)/[^/]+/clip|clips\\.twitch\\.tv)/[\\p{Alnum}.,%_=?&#\\-+()\\[\\]*$~@!:/{};']+" - ); + private final ClipLinkParser parser = new ClipLinkParser(); private final Twitch twitch; @@ -42,38 +38,18 @@ public ClipFinder(Twitch twitch) { } URI parseClipURI(String chatMessage) { - var matcher = CLIP_URL_PATTERN.matcher(chatMessage); - if (!matcher.find()) { - return null; - } - - try { - return new URI(matcher.group().trim()); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } + return parser.parseClipURI(chatMessage); } /** * チャットに投稿されたクリップのURLをパースしてAPIに投げるメソッド */ public Optional findClip(String message) { - var uri = parseClipURI(message); - if (uri == null) { - return Optional.empty(); - } - - // 0: empty - // 1: ユーザー名 - // 2: clip - // 3: クリップのID - var paths = uri.getPath().split("/"); - if (paths.length != 4 && paths.length != 2) { - LOGGER.error("unexpected clip url {}", message); - return Optional.empty(); - } - - var clipId = paths[paths.length - 1]; + var parsed = parser.parse(message); + if (parsed.isEmpty()) return Optional.empty(); + var link = parsed.orElseThrow(); + var clipId = link.getId(); + var uri = link.getEstimatedURL(); var api = twitch.getTwitchAPI(); var clips = api.getClips(List.of(clipId)); diff --git a/src/main/java/com/github/k7t3/tcv/domain/chat/ClipLinkParser.java b/src/main/java/com/github/k7t3/tcv/domain/chat/ClipLinkParser.java new file mode 100644 index 0000000..759c250 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/domain/chat/ClipLinkParser.java @@ -0,0 +1,50 @@ +/* + * Copyright 2024 k7t3 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.github.k7t3.tcv.domain.chat; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Optional; +import java.util.regex.Pattern; + +/** チャットの URL 検出のみを行う。API やクライアントを必要としない。 */ +public final class ClipLinkParser { + private static final Pattern CLIP_URL_PATTERN = Pattern.compile( + "https://((www\\.twitch\\.tv|m\\.twitch\\.tv)/[^/]+/clip|clips\\.twitch\\.tv)/[\\p{Alnum}.,%_=?&#\\-+()\\[\\]*$~@!:/{};']+" + ); + + URI parseClipURI(String chatMessage) { + var matcher = CLIP_URL_PATTERN.matcher(chatMessage); + if (!matcher.find()) { + return null; + } + + try { + return new URI(matcher.group().trim()); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + public Optional parse(String message) { + var uri = parseClipURI(message); + if (uri == null) return Optional.empty(); + var paths = uri.getPath().split("/"); + if (paths.length != 4 && paths.length != 2) return Optional.empty(); + return Optional.of(ClipChatMessage.of(paths[paths.length - 1], uri.toString(), message)); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/domain/event/EventSubscriptionScope.java b/src/main/java/com/github/k7t3/tcv/domain/event/EventSubscriptionScope.java new file mode 100644 index 0000000..e47f74f --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/domain/event/EventSubscriptionScope.java @@ -0,0 +1,68 @@ +package com.github.k7t3.tcv.domain.event; + +import com.github.k7t3.tcv.lifecycle.CloseActions; +import com.github.philippheuer.events4j.api.IEventManager; +import com.github.philippheuer.events4j.api.domain.IDisposable; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +/** SDK の購読を一つの登録世代として所有し、終了後に開始される通知を抑止する。 */ +public final class EventSubscriptionScope implements AutoCloseable { + private final Object lock = new Object(); + private final List subscriptions = new ArrayList<>(); + private volatile boolean closed; + + /** + * 所有者へ接続済みの範囲に登録する。終了済みなら登録処理自体を実行しない。 + * 失敗した場合は、この範囲だけを閉じて原因を保持する。 + * @param register SDK の購読を追加する処理 + */ + public void register(Consumer register) { + if (closed) return; + try { + register.accept(this); + } catch (RuntimeException | Error failure) { + try { + close(); + } catch (RuntimeException | Error cleanup) { + if (cleanup != failure) failure.addSuppressed(cleanup); + } + throw failure; + } + } + + /** + * 終了時に解除する SDK 購読を追加する。終了後に返った購読も直ちに解除する。 + * @param manager 借用する SDK 発行元 + * @param type イベント型 + * @param consumer この登録世代のイベント処理 + * @param イベントの型 + */ + public void subscribe(IEventManager manager, Class type, Consumer consumer) { + if (closed) return; + var subscription = manager.onEvent(type, event -> { + if (!closed) consumer.accept(event); + }); + synchronized (lock) { + if (!closed) { + subscriptions.add(subscription); + return; + } + } + subscription.dispose(); + } + + @Override + public void close() { + final Runnable[] releases; + synchronized (lock) { + if (closed) return; + closed = true; + releases = subscriptions.stream().map(subscription -> (Runnable) subscription::dispose).toArray(Runnable[]::new); + subscriptions.clear(); + } + CloseActions.runAll(releases); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/domain/event/stream/StreamStateEvent.java b/src/main/java/com/github/k7t3/tcv/domain/event/stream/StreamStateEvent.java new file mode 100644 index 0000000..b0613fb --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/domain/event/stream/StreamStateEvent.java @@ -0,0 +1,14 @@ +package com.github.k7t3.tcv.domain.event.stream; + +import com.github.k7t3.tcv.domain.channel.StreamInfo; + +/** 監視で確定した配信状態。SDKのキャッシュとイベント型を購読側へ渡さない。 */ +public sealed interface StreamStateEvent { + String userId(); + + record Online(String userId, StreamInfo stream) implements StreamStateEvent {} + record Offline(String userId) implements StreamStateEvent {} + record Title(String userId, StreamInfo stream) implements StreamStateEvent {} + record Game(String userId, StreamInfo stream) implements StreamStateEvent {} + record Viewers(String userId, StreamInfo stream) implements StreamStateEvent {} +} diff --git a/src/main/java/com/github/k7t3/tcv/entity/service/ChannelGroupEntityService.java b/src/main/java/com/github/k7t3/tcv/entity/service/ChannelGroupEntityService.java index 5e08a94..7c7ba33 100644 --- a/src/main/java/com/github/k7t3/tcv/entity/service/ChannelGroupEntityService.java +++ b/src/main/java/com/github/k7t3/tcv/entity/service/ChannelGroupEntityService.java @@ -25,6 +25,7 @@ import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.UUID; @@ -55,18 +56,17 @@ public List retrieveAll() { g.updated_at, u.user_id from - group_users u - left join groups g + left join + group_users u on u.group_id = g.id order by g.updated_at desc; """; - var list = new ArrayList(); - connector.query(query, rs -> { - - ChannelGroupEntity entity = null; + // 同じ更新日時の行は別グループの行と混在できる。隣接ではなく親IDで集約する。 + var groups = new LinkedHashMap(); + connector.readTransaction(() -> connector.query(query, rs -> { while (rs.next()) { var id = rs.getString("id"); var name = rs.getString("name"); @@ -78,27 +78,29 @@ public List retrieveAll() { var uuid = UUID.fromString(id); - if (entity == null || !entity.id().equals(uuid)) { + var entity = groups.get(uuid); + if (entity == null) { var ids = new HashSet(); - ids.add(userId); entity = new ChannelGroupEntity(uuid, name, comment, pinned, createdAt, updatedAt, ids); - list.add(entity); - } else { - entity.channelIds().add(userId); + groups.put(uuid, entity); } + if (userId != null) entity.channelIds().add(userId); } - }); + })); - LOGGER.info("{} groups retrieved", list.size()); + LOGGER.info("{} groups retrieved", groups.size()); - return list; + return new ArrayList<>(groups.values()); } public void save(SaveType saveType, ChannelGroupEntity entity) { - switch (saveType) { - case INSERT -> insert(entity); - case UPDATE -> update(entity); - } + connector.transaction(() -> { + switch (saveType) { + case INSERT -> insert(entity); + case UPDATE -> update(entity); + } + }); + LOGGER.info("{} {}", entity, saveType == SaveType.INSERT ? "inserted" : "updated"); } private void insert(ChannelGroupEntity entity) { @@ -126,9 +128,6 @@ private void insert(ChannelGroupEntity entity) { } }); - connector.commit(); - - LOGGER.info("{} inserted", entity); } private void update(ChannelGroupEntity entity) { @@ -171,13 +170,11 @@ private void update(ChannelGroupEntity entity) { } }); - connector.commit(); - - LOGGER.info("{} updated", entity); } public void remove(ChannelGroupEntity entity) { - delete(entity); + connector.transaction(() -> delete(entity)); + LOGGER.info("{} removed", entity); } private void delete(ChannelGroupEntity entity) { @@ -188,9 +185,6 @@ private void delete(ChannelGroupEntity entity) { stmt.executeUpdate(); }); - connector.commit(); - - LOGGER.info("{} removed", entity); } } diff --git a/src/main/java/com/github/k7t3/tcv/entity/service/ChatFilterEntityStore.java b/src/main/java/com/github/k7t3/tcv/entity/service/ChatFilterEntityStore.java new file mode 100644 index 0000000..0cfb4cd --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/entity/service/ChatFilterEntityStore.java @@ -0,0 +1,98 @@ +package com.github.k7t3.tcv.entity.service; + +import com.github.k7t3.tcv.database.DBConnector; +import com.github.k7t3.tcv.entity.ChatKeywordFilterEntity; +import com.github.k7t3.tcv.entity.ChatUserFilterEntity; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; + +/** 両フィルターテーブルを一つの保存単位として扱う。接続は借用する。 */ +public final class ChatFilterEntityStore { + public record Changes(List keywords, Set deletedKeywords, + List users, Set deletedUsers) { + public Changes { + keywords = List.copyOf(keywords); + deletedKeywords = Set.copyOf(deletedKeywords); + users = List.copyOf(users); + deletedUsers = Set.copyOf(deletedUsers); + } + public static Changes empty() { return new Changes(List.of(), Set.of(), List.of(), Set.of()); } + } + + public record Snapshot(List keywords, List users, long revision) { + public Snapshot { keywords = List.copyOf(keywords); users = List.copyOf(users); } + } + + private final DBConnector connector; + private final ChatKeywordFilterEntityService keywords; + private final ChatUserFilterEntityService users; + private final SettingsJournal settingsJournal; + private long revision; + + public ChatFilterEntityStore(DBConnector connector) { + this.connector = Objects.requireNonNull(connector); + keywords = new ChatKeywordFilterEntityService(connector); + users = new ChatUserFilterEntityService(connector); + settingsJournal = new SettingsJournal(connector); + } + + /** @return 同じ接続を借用する設定復旧情報。取得だけではI/Oしない */ + public SettingsJournal settingsJournal() { return settingsJournal; } + + public Snapshot read() { + synchronized (connector) { + var result = new Snapshot[1]; + connector.readTransaction(() -> result[0] = + new Snapshot(keywords.retrieveAll(), users.retrieveAll(), revision)); + return result[0]; + } + } + + /** companion は SQL 変更後、commit 前に実行する。いずれかの失敗で SQL 全体を rollback する。 */ + public Snapshot save(Changes changes, Runnable companion) { + validate(changes); + Objects.requireNonNull(companion); + synchronized (connector) { + var result = new Snapshot[1]; + connector.transaction(() -> { + for (var id : changes.deletedKeywords()) keywords.deleteInTransaction(new ChatKeywordFilterEntity(id, 0, "")); + for (var entity : changes.keywords()) { + if (entity.id() == 0) keywords.insertInTransaction(entity); + else if (keywords.updateInTransaction(entity) != 1) throw new IllegalStateException("keyword filter no longer exists: " + entity.id()); + } + for (var id : changes.deletedUsers()) users.deleteInTransaction(new ChatUserFilterEntity(id, "", "")); + for (var entity : changes.users()) users.saveInTransaction(entity); + result[0] = new Snapshot(keywords.retrieveAll(), users.retrieveAll(), revision + 1); + companion.run(); + }); + revision++; + return result[0]; + } + } + + private static void validate(Changes changes) { + Objects.requireNonNull(changes); + var keywordIds = new HashSet(); + for (var row : changes.keywords()) { + if (row.id() < 0 || row.type() < 0 || row.type() > 3 || row.keyword() == null || row.keyword().isBlank()) { + throw new IllegalArgumentException("invalid keyword filter"); + } + if (row.id() > 0 && (!keywordIds.add(row.id()) || changes.deletedKeywords().contains(row.id()))) { + throw new IllegalArgumentException("conflicting keyword filter changes"); + } + if (row.type() == 3) Pattern.compile(row.keyword()); + } + if (changes.deletedKeywords().stream().anyMatch(id -> id < 1)) throw new IllegalArgumentException("invalid deleted keyword id"); + var userIds = new HashSet(); + for (var row : changes.users()) { + if (row.userId() == null || row.userId().isBlank() || row.userName() == null || row.comment() == null + || !userIds.add(row.userId()) || changes.deletedUsers().contains(row.userId())) { + throw new IllegalArgumentException("invalid or conflicting user filter changes"); + } + } + if (changes.deletedUsers().stream().anyMatch(String::isBlank)) throw new IllegalArgumentException("invalid deleted user id"); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/entity/service/ChatKeywordFilterEntityService.java b/src/main/java/com/github/k7t3/tcv/entity/service/ChatKeywordFilterEntityService.java index 411d89b..3f7c530 100644 --- a/src/main/java/com/github/k7t3/tcv/entity/service/ChatKeywordFilterEntityService.java +++ b/src/main/java/com/github/k7t3/tcv/entity/service/ChatKeywordFilterEntityService.java @@ -39,7 +39,7 @@ public List retrieveAll() { var list = new ArrayList(); var query = "select id, type, keyword from chat_keyword_filter;"; - connector.query(query, rs -> { + connector.readTransaction(() -> connector.query(query, rs -> { while (rs.next()) { var i = 0; @@ -50,12 +50,18 @@ public List retrieveAll() { var entity = new ChatKeywordFilterEntity(id, type, keyword); list.add(entity); } - }); + })); return list; } public int insert(ChatKeywordFilterEntity entity) { + int[] key = new int[1]; + connector.transaction(() -> key[0] = insertInTransaction(entity)); + return key[0]; + } + + int insertInTransaction(ChatKeywordFilterEntity entity) { LOGGER.info("insert entity {}", entity); var sql = "insert into chat_keyword_filter(type, keyword) values(?, ?);"; @@ -70,26 +76,34 @@ public int insert(ChatKeywordFilterEntity entity) { key[0] = rs.getInt(1); } }); - connector.commit(); return key[0]; } public void update(ChatKeywordFilterEntity entity) { + connector.transaction(() -> updateInTransaction(entity)); + } + + int updateInTransaction(ChatKeywordFilterEntity entity) { LOGGER.info("update entity {}", entity); var sql = "update chat_keyword_filter set type = ?, keyword = ? where id = ?;"; + int[] count = new int[1]; connector.prepared(sql, stmt -> { var i = 0; stmt.setInt(++i, entity.type()); stmt.setString(++i, entity.keyword()); stmt.setInt(++i, entity.id()); - stmt.executeUpdate(); + count[0] = stmt.executeUpdate(); }); - connector.commit(); + return count[0]; } public void delete(ChatKeywordFilterEntity entity) { + connector.transaction(() -> deleteInTransaction(entity)); + } + + void deleteInTransaction(ChatKeywordFilterEntity entity) { LOGGER.info("delete entity {}", entity); var sql = "delete from chat_keyword_filter where id = ?;"; @@ -97,7 +111,6 @@ public void delete(ChatKeywordFilterEntity entity) { stmt.setInt(1, entity.id()); stmt.executeUpdate(); }); - connector.commit(); } } diff --git a/src/main/java/com/github/k7t3/tcv/entity/service/ChatUserFilterEntityService.java b/src/main/java/com/github/k7t3/tcv/entity/service/ChatUserFilterEntityService.java index f379174..e219e36 100644 --- a/src/main/java/com/github/k7t3/tcv/entity/service/ChatUserFilterEntityService.java +++ b/src/main/java/com/github/k7t3/tcv/entity/service/ChatUserFilterEntityService.java @@ -40,7 +40,7 @@ public List retrieveAll() { var list = new ArrayList(); - connector.query(query, rs -> { + connector.readTransaction(() -> connector.query(query, rs -> { while (rs.next()) { var i = 0; var userId = rs.getString(++i); @@ -49,12 +49,16 @@ public List retrieveAll() { var entity = new ChatUserFilterEntity(userId, userName, comment); list.add(entity); } - }); + })); return list; } public void save(ChatUserFilterEntity entity) { + connector.transaction(() -> saveInTransaction(entity)); + } + + void saveInTransaction(ChatUserFilterEntity entity) { LOGGER.info("save entity {}", entity); var sql = "insert or replace into chat_user_filter values(?, ?, ?);"; @@ -65,10 +69,13 @@ public void save(ChatUserFilterEntity entity) { stmt.setString(++i, entity.comment()); stmt.executeUpdate(); }); - connector.commit(); } public void delete(ChatUserFilterEntity entity) { + connector.transaction(() -> deleteInTransaction(entity)); + } + + void deleteInTransaction(ChatUserFilterEntity entity) { LOGGER.info("delete entity {}", entity); var sql = "delete from chat_user_filter where user_id = ?;"; @@ -76,7 +83,6 @@ public void delete(ChatUserFilterEntity entity) { stmt.setString(1, entity.userId()); stmt.executeUpdate(); }); - connector.commit(); } } diff --git a/src/main/java/com/github/k7t3/tcv/entity/service/SettingsJournal.java b/src/main/java/com/github/k7t3/tcv/entity/service/SettingsJournal.java new file mode 100644 index 0000000..6a46703 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/entity/service/SettingsJournal.java @@ -0,0 +1,162 @@ +package com.github.k7t3.tcv.entity.service; + +import com.github.k7t3.tcv.database.DBConnector; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.channels.FileChannel; +import java.nio.file.StandardOpenOption; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; + +/** 設定投影の復旧情報をフィルターと同じDBに保存する。接続は借用する。 */ +public final class SettingsJournal { + private static final Object JVM_GUARD = new Object(); + + /** 編集前後の設定とSQLの確定状態。旧記録はpreviousOwnersが空。配列は呼出元と共有しない。 */ + public record Entry(UUID operation, String nodePath, boolean userNode, byte[] before, byte[] after, + boolean committed, Optional previousOwners) { + public Entry { + Objects.requireNonNull(operation); + Objects.requireNonNull(nodePath); + before = before.clone(); + after = after.clone(); + previousOwners = previousOwners.map(bytes -> bytes.clone()); + } + /** 旧記録には更新前の所有情報がなく、従来どおりの復旧を行う。 */ + public Entry(UUID operation, String nodePath, boolean userNode, byte[] before, byte[] after, boolean committed) { + this(operation, nodePath, userNode, before, after, committed, Optional.empty()); + } + @Override public byte[] before() { return before.clone(); } + @Override public byte[] after() { return after.clone(); } + @Override public Optional previousOwners() { return previousOwners.map(bytes -> bytes.clone()); } + } + + private final DBConnector connector; + + SettingsJournal(DBConnector connector) { this.connector = Objects.requireNonNull(connector); } + + /** + * 保存・復旧を排他し、補助テーブルを準備して同期的に実行する。 + * ファイルDBはrealPathに対応するsidecar FileLockを完了まで保持する。 + * コンストラクターではI/Oしない。メモリDBはJVM内だけで排他する。 + * @param operation この接続で実行する保存または復旧 + * @return operationの結果 + */ + public T exclusive(Supplier operation) { + // 接続monitorより先に取得し、同一JVMのFileLock重複とlock用mapの増加を避ける。 + synchronized (JVM_GUARD) { + synchronized (connector) { + var path = connector.storagePath(); + if (path.isEmpty()) return initializeAndRun(operation); + try { + var real = path.orElseThrow().toRealPath(); + var lockPath = real.resolveSibling(real.getFileName() + ".settings.lock"); + try (var channel = FileChannel.open(lockPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE); + var lock = channel.lock()) { + return initializeAndRun(operation); + } + } catch (IOException failure) { throw new UncheckedIOException(failure); } + } + } + } + + private T initializeAndRun(Supplier operation) { + connector.transaction(() -> { + connector.execute(""" + create table if not exists settings_recovery ( + slot integer primary key check (slot = 1), + operation_id text not null, + node_path text not null, + user_node integer not null check (user_node in (0, 1)), + before_values blob not null, + after_values blob not null, + committed integer not null check (committed in (0, 1)) + ); + """); + connector.execute(""" + create table if not exists settings_recovery_owners ( + operation_id text primary key, + before_owners blob not null + ); + """); + }); + return operation.get(); + } + + /** @return 現在の復旧情報。exclusiveの内側で呼び出すこと */ + public Optional pending() { + var entry = new Entry[1]; + connector.readTransaction(() -> connector.query(""" + select recovery.*, owners.before_owners + from settings_recovery recovery + left join settings_recovery_owners owners on recovery.operation_id = owners.operation_id + where recovery.slot = 1; + """, rows -> { + if (rows.next()) entry[0] = new Entry(UUID.fromString(rows.getString("operation_id")), + rows.getString("node_path"), rows.getBoolean("user_node"), rows.getBytes("before_values"), + rows.getBytes("after_values"), rows.getBoolean("committed"), + Optional.ofNullable(rows.getBytes("before_owners"))); + })); + return Optional.ofNullable(entry[0]); + } + + /** + * 未確定の復旧情報を独立してcommitする。既存の情報を上書きしない。 + * @param entry committed=falseの新しい操作。exclusiveの内側で渡すこと + */ + public void prepare(Entry entry) { + if (entry.committed()) throw new IllegalArgumentException("recovery entry is already committed"); + connector.transaction(() -> { + connector.prepared(""" + insert into settings_recovery + (slot, operation_id, node_path, user_node, before_values, after_values, committed) + values (1, ?, ?, ?, ?, ?, 0); + """, statement -> { + statement.setString(1, entry.operation().toString()); + statement.setString(2, entry.nodePath()); + statement.setBoolean(3, entry.userNode()); + statement.setBytes(4, entry.before()); + statement.setBytes(5, entry.after()); + statement.executeUpdate(); + }); + entry.previousOwners().ifPresent(owners -> connector.prepared(""" + insert into settings_recovery_owners (operation_id, before_owners) values (?, ?); + """, statement -> { + statement.setString(1, entry.operation().toString()); + statement.setBytes(2, owners); + statement.executeUpdate(); + })); + }); + } + + /** + * フィルター更新と同じtransactionで確定予定を記す。自身ではcommitしない。 + * @param operation prepareした操作の識別子 + */ + public void markCommitted(UUID operation) { + connector.prepared("update settings_recovery set committed = 1 where slot = 1 and operation_id = ?;", statement -> { + statement.setString(1, operation.toString()); + if (statement.executeUpdate() != 1) throw new IllegalStateException("settings recovery entry is missing"); + }); + } + + /** + * 投影または補償が完了した操作の復旧情報を消す。別操作の情報は消さない。 + * @param operation 終了した操作。exclusiveの内側で渡すこと + */ + public void clear(UUID operation) { + connector.transaction(() -> { + connector.prepared( + "delete from settings_recovery where slot = 1 and operation_id = ?;", statement -> { + statement.setString(1, operation.toString()); + statement.executeUpdate(); + }); + connector.prepared("delete from settings_recovery_owners where operation_id = ?;", statement -> { + statement.setString(1, operation.toString()); + statement.executeUpdate(); + }); + }); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/entity/service/WindowBoundsEntityService.java b/src/main/java/com/github/k7t3/tcv/entity/service/WindowBoundsEntityService.java index 7ba99f0..aa4bc2a 100644 --- a/src/main/java/com/github/k7t3/tcv/entity/service/WindowBoundsEntityService.java +++ b/src/main/java/com/github/k7t3/tcv/entity/service/WindowBoundsEntityService.java @@ -42,36 +42,37 @@ public void save(WindowBoundsEntity entity) { } var sql = "insert or replace into windows values(?, ?, ?, ?, ?, ?);"; - connector.prepared(sql, stmt -> { - var i = 0; - stmt.setString(++i, entity.identity()); - stmt.setDouble(++i, Double.isNaN(entity.x()) ? NaN : entity.x()); - stmt.setDouble(++i, Double.isNaN(entity.y()) ? NaN : entity.y()); - stmt.setDouble(++i, entity.width()); - stmt.setDouble(++i, entity.height()); - stmt.setBoolean(++i, entity.maximized()); - stmt.executeUpdate(); + connector.transaction(() -> { + connector.prepared(sql, stmt -> { + var i = 0; + stmt.setString(++i, entity.identity()); + stmt.setDouble(++i, Double.isNaN(entity.x()) ? NaN : entity.x()); + stmt.setDouble(++i, Double.isNaN(entity.y()) ? NaN : entity.y()); + stmt.setDouble(++i, entity.width()); + stmt.setDouble(++i, entity.height()); + stmt.setBoolean(++i, entity.maximized()); + stmt.executeUpdate(); + }); }); - connector.commit(); } public void delete(String identity) { LOGGER.info("delete window bounds {}", identity); var sql = "delete from windows where id = ?"; - connector.prepared(sql, stmt -> { - stmt.setString(1, identity); - stmt.executeUpdate(); + connector.transaction(() -> { + connector.prepared(sql, stmt -> { + stmt.setString(1, identity); + stmt.executeUpdate(); + }); }); - connector.commit(); } public void clear() { LOGGER.info("clear window bounds"); var sql = "delete from windows;"; - connector.execute(sql); - connector.commit(); + connector.transaction(() -> connector.execute(sql)); } public WindowBoundsEntity get(String identity) { @@ -82,7 +83,7 @@ public WindowBoundsEntity get(String identity) { WindowBoundsEntity[] entities = new WindowBoundsEntity[1]; var query = "select id, x, y, width, height, maximized from windows where id = ?;"; - connector.prepared(query, stmt -> { + connector.readTransaction(() -> connector.prepared(query, stmt -> { stmt.setString(1, identity); try (var rs = stmt.executeQuery()) { if (!rs.next()) { @@ -100,7 +101,7 @@ public WindowBoundsEntity get(String identity) { if (Double.isNaN(y)) y = Double.NaN; entities[0] = new WindowBoundsEntity(id, x, y, width, height, maximized); } - }); + })); LOGGER.info("get window bounds {}({})", entities[0], identity); diff --git a/src/main/java/com/github/k7t3/tcv/io/InterruptibleFileLocks.java b/src/main/java/com/github/k7t3/tcv/io/InterruptibleFileLocks.java new file mode 100644 index 0000000..fa721a6 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/io/InterruptibleFileLocks.java @@ -0,0 +1,31 @@ +package com.github.k7t3.tcv.io; + +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.FileLockInterruptionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; + +/** ネイティブのblocking lockに入らず、割込みで終了できるファイル排他。 */ +public final class InterruptibleFileLocks { + private InterruptibleFileLocks() {} + + /** + * 取得まで待ち、呼出側へロックの解放責任を渡す。channelは借用し、閉じない。 + * 同一JVMでの重複取得は呼出側で直列化する。 + * @param channel 書込可能な開いたchannel + * @return 呼出側が解放する排他ロック + * @throws FileLockInterruptionException 割込み時。割込み状態を保持する + * @throws IOException ファイル排他の取得に失敗した場合 + */ + public static FileLock acquire(FileChannel channel) throws IOException { + // macOSのblocking lockは、割込みを送った側もnative close待ちに巻き込む。 + while (true) { + if (Thread.currentThread().isInterrupted()) throw new FileLockInterruptionException(); + var lock = channel.tryLock(); + if (lock != null) return lock; + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(20)); + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/io/PreferenceFileLock.java b/src/main/java/com/github/k7t3/tcv/io/PreferenceFileLock.java new file mode 100644 index 0000000..6fa0727 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/io/PreferenceFileLock.java @@ -0,0 +1,53 @@ +package com.github.k7t3.tcv.io; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.io.UncheckedIOException; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Supplier; + +/** 設定と資格情報で共有する、JVM内の直列化とプロセス間ファイル排他。 */ +public final class PreferenceFileLock { + private static final ReentrantLock PROCESS_GUARD = new ReentrantLock(); + private static final ScopedValue> HELD_LOCKS = ScopedValue.newInstance(); + + private PreferenceFileLock() {} + + /** + * JVM内の受付、共有ファイル、呼出側のDB/ノードの順で処理する。同じスレッドの再入は同じファイルを再取得しない。 + * @param file 全プロセスが共有するロック。nullはJVM内だけで直列化する + * @param operation DB/ノードの同期と保存を行う処理。ロック取得前にノードのmonitorを保持しないこと + * @return 処理の結果 + * @throws UncheckedIOException 取得・解放のI/O失敗、または割込みの場合。割込み状態は保持する + * @param 処理結果の型 + */ + public static T exclusive(Path file, Supplier operation) { + try { PROCESS_GUARD.lockInterruptibly(); } + catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + var failure = new InterruptedIOException("interrupted while waiting for preference storage"); + failure.initCause(interrupted); + throw new UncheckedIOException(failure); + } + try { + var path = file == null ? null : file.toAbsolutePath().normalize(); + if (path == null || HELD_LOCKS.isBound() && HELD_LOCKS.get().contains(path)) return operation.get(); + try { + Files.createDirectories(path.getParent()); + try (var channel = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE); + var lock = InterruptibleFileLocks.acquire(channel)) { + var held = new HashSet(); + if (HELD_LOCKS.isBound()) held.addAll(HELD_LOCKS.get()); + held.add(path); + return ScopedValue.where(HELD_LOCKS, Set.copyOf(held)).call(operation::get); + } + } catch (IOException failure) { throw new UncheckedIOException(failure); } + } finally { PROCESS_GUARD.unlock(); } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/lifecycle/CloseActions.java b/src/main/java/com/github/k7t3/tcv/lifecycle/CloseActions.java new file mode 100644 index 0000000..baab95a --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/lifecycle/CloseActions.java @@ -0,0 +1,28 @@ +package com.github.k7t3.tcv.lifecycle; + +/** 所有するリソースの解放をすべて試行し、失敗を失わず呼び出し元へ返す。 */ +public final class CloseActions { + + private CloseActions() { + } + + /** + * 指定順にすべての処理を実行し、最初の失敗を再送出する。 + * 後続の失敗は最初の例外の suppressed exceptions に保持する。 + * + * @param actions 同期的な解放処理 + */ + public static void runAll(Runnable... actions) { + Throwable failure = null; + for (var action : actions) { + try { + action.run(); + } catch (RuntimeException | Error error) { + if (failure == null) failure = error; + else if (failure != error) failure.addSuppressed(error); + } + } + if (failure instanceof RuntimeException exception) throw exception; + if (failure instanceof Error error) throw error; + } +} diff --git a/src/main/java/com/github/k7t3/tcv/lifecycle/OwnedScheduler.java b/src/main/java/com/github/k7t3/tcv/lifecycle/OwnedScheduler.java new file mode 100644 index 0000000..eaa924a --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/lifecycle/OwnedScheduler.java @@ -0,0 +1,39 @@ +package com.github.k7t3.tcv.lifecycle; + +import java.util.Objects; +import java.util.ArrayList; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.Future; + +/** 未使用のschedulerを所有し、外部からの終了では実終了を待つ。 */ +public final class OwnedScheduler implements AutoCloseable { + private final ScheduledThreadPoolExecutor scheduler; + private final Set workers = ConcurrentHashMap.newKeySet(); + + /** @param scheduler workerがまだ開始されていない、所有権を移譲するscheduler */ + public OwnedScheduler(ScheduledThreadPoolExecutor scheduler) { + this.scheduler = Objects.requireNonNull(scheduler); + var factory = scheduler.getThreadFactory(); + scheduler.setThreadFactory(task -> factory.newThread(() -> { + var worker = Thread.currentThread(); + workers.add(worker); + try { task.run(); } + finally { workers.remove(worker); } + })); + } + + /** 現在のスレッドが、このscheduler自身のworkerかを返す。 */ + public boolean isWorkerThread() { return workers.contains(Thread.currentThread()); } + + /** 未開始のFutureを取り消す。自分自身は停止要求だけを行い、外部からは実終了を待つ。 */ + @Override public void close() { + var cleanup = new ArrayList(); + for (var task : scheduler.shutdownNow()) { + if (task instanceof Future future) cleanup.add(() -> future.cancel(false)); + } + if (!isWorkerThread()) cleanup.add(scheduler::close); + CloseActions.runAll(cleanup.toArray(Runnable[]::new)); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/prefs/AppPreferences.java b/src/main/java/com/github/k7t3/tcv/prefs/AppPreferences.java index 964025a..e7f9bc4 100644 --- a/src/main/java/com/github/k7t3/tcv/prefs/AppPreferences.java +++ b/src/main/java/com/github/k7t3/tcv/prefs/AppPreferences.java @@ -16,22 +16,22 @@ package com.github.k7t3.tcv.prefs; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; -import java.util.prefs.BackingStoreException; -import java.util.prefs.InvalidPreferencesFormatException; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.prefs.Preferences; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -public class AppPreferences extends PreferencesBase { - - private static final Logger LOGGER = LoggerFactory.getLogger(AppPreferences.class); +public class AppPreferences implements AutoCloseable { private final Preferences preferences; + private final Path settingsLockFile; + private final PreferenceStore store; + + private static final Logger LOGGER = LoggerFactory.getLogger(AppPreferences.class); private final GeneralPreferences generalPreferences; @@ -41,65 +41,107 @@ public class AppPreferences extends PreferencesBase { private StatePreferences statePreferences; - private AppPreferences() { - super(Preferences.userNodeForPackage(AppPreferences.class), new HashMap<>()); + /** アプリ用ノードへの背景書込みを所有する。構築後、背景の起動処理でloadする。 */ + public AppPreferences() { + this(Preferences.userRoot().node("/com/github/k7t3/tcv"), + com.github.k7t3.tcv.app.core.OS.current().getApplicationDirectory().resolve("settings.lock")); + } + + /** 借用ノードを同期的に更新するモデルを構築する。永続化の所有者は呼出側。 */ + public AppPreferences(Preferences preferences) { + this(preferences, null); + } - preferences = Preferences.userRoot().node("/com/github/k7t3/tcv"); - generalPreferences = new GeneralPreferences(preferences, defaults); + /** + * @param preferences 設定ノード。ノード自体の削除・解放は行わない + * @param settingsLockFile 同じノードへ保存する全プロセスで共有するDBと独立したロック。 + * nullは借用ノード用のJVM内排他。構築時にはファイルを作らない + */ + public AppPreferences(Preferences preferences, Path settingsLockFile) { + this.preferences = Objects.requireNonNull(preferences); + this.settingsLockFile = settingsLockFile == null ? null : settingsLockFile.toAbsolutePath().normalize(); + store = new PreferenceStore(preferences, this.settingsLockFile); + generalPreferences = new GeneralPreferences(store); LOGGER.info("preferences initialized"); } - public void clear() { - try { - preferences.clear(); - } catch (BackingStoreException e) { - throw new RuntimeException(e); - } + public Preferences getPreferences() { + return preferences; } - @Override - protected void readFromPreferences() { - if (chatPreferences != null) - chatPreferences.readFromPreferences(); + /** @return DBの移動先から独立した、設定保存用の共有ロック */ + public Optional settingsLockFile() { return Optional.ofNullable(settingsLockFile); } + + /** + * UIで使用する既知の設定だけを背景で同期・読込する。資格情報や未知のキーは列挙しない。 + * FXプロパティの初期化前と起動時の復旧後に呼ぶ。借用ノードは即時読取を維持する。 + * @throws IllegalStateException FXスレッドから呼び出した場合、終了後、または保存先の失敗 + */ + public void load() { + if (javafx.application.Platform.isFxApplicationThread()) throw new IllegalStateException("load preferences outside the FX thread"); + var keys = new java.util.HashSet<>(GeneralPreferences.storedKeys()); + keys.addAll(ChatPreferences.storedKeys()); + keys.addAll(StatePreferences.storedKeys()); + for (var binding : com.github.k7t3.tcv.app.keyboard.KeyBinding.values()) keys.add(binding.getId()); + store.load(java.util.Set.copyOf(keys)); } - @Override - protected void writeToPreferences() { - if (chatPreferences != null) - chatPreferences.writeToPreferences(); + public static void validateEditorValues(Map> values) { + var settings = new HashMap>(GeneralPreferences.editorSettings()); + settings.putAll(ChatPreferences.editorSettings()); + var bindings = new HashMap(); + for (var binding : com.github.k7t3.tcv.app.keyboard.KeyBinding.values()) bindings.put(binding.getId(), binding); + values.forEach((key, value) -> { + if (key.length() > Preferences.MAX_KEY_LENGTH || value.filter(text -> text.length() > Preferences.MAX_VALUE_LENGTH).isPresent()) { + throw new IllegalArgumentException("invalid editor preference: " + key); + } + var setting = settings.get(key); + if (setting != null) value.ifPresent(setting::decode); + else if (bindings.containsKey(key)) value.ifPresent(javafx.scene.input.KeyCombination::keyCombination); + else throw new IllegalArgumentException("invalid editor preference: " + key); + }); } - public void importPreferences(Path filePath) { - try (var input = Files.newInputStream(filePath)) { - Preferences.importPreferences(input); - preferences.sync(); - } catch (IOException | InvalidPreferencesFormatException | BackingStoreException e) { - throw new RuntimeException(e); - } + /** + * SQLも確定した編集値を背景のキャッシュへ記録する。exclusiveの保存処理内で呼ぶ。 + * 保存中に受け付けた後続の通常変更は維持する。FXプロパティは変更しない。 + * @param values 永続化済みの編集値 + */ + public void recordCommittedValues(Map> values) { + validateEditorValues(values); + store.committed(values); } - public void exportPreferences(Path exportFilePath) { - try (var output = Files.newOutputStream(exportFilePath)) { - preferences.exportNode(output); - } catch (IOException | BackingStoreException e) { - throw new RuntimeException(e); - } + /** + * 永続化済みの値をFXのキャッシュに反映する。保存先へは書き戻さない。 + * 所有ノードでは、後続の通常変更や別の保存で置き換わった値を反映しない。 + * @param values 永続化済みの編集値 + * @return 現在も有効で、UIへ適用できる編集値 + */ + public Map> applyCommittedValues(Map> values) { + if (!javafx.application.Platform.isFxApplicationThread()) throw new IllegalStateException("use the FX application thread"); + validateEditorValues(values); + var current = store.currentProjection(values); + generalPreferences.applyCommittedValues(current); + if (chatPreferences != null) chatPreferences.applyCommittedValues(current); + return current; } - public Preferences getPreferences() { - return preferences; - } + /** 背景から受付済み変更の永続化を待ち、書込・flushの失敗を返す。FXプロパティは読み直さない。 */ + public void save() { store.save(); LOGGER.info("save preferences"); } - public void save() { - try { - writeToPreferences(); - preferences.flush(); - LOGGER.info("save preferences"); - } catch (BackingStoreException e) { - throw new RuntimeException(e); - } - } + /** 新規変更を止め、受付済みの保存を背景から待つ。借用ノード自体は削除・解放しない。 */ + @Override public void close() { store.close(this::save); } + + /** + * 設定エディターのDB操作を、受付済みの通常設定変更に続けて実行する。背景から呼ぶ。 + * 同じ保存処理からの再入は同じ排他範囲で実行し、自分自身の完了を待たない。 + * @param operation 保存処理。返るまで共有ファイルを所有する。DB、ノードの順で排他すること + * @return 保存処理の結果 + * @param 結果の型 + */ + public T exclusive(java.util.function.Supplier operation) { return store.exclusive(operation); } public GeneralPreferences getGeneralPreferences() { return generalPreferences; @@ -107,32 +149,25 @@ public GeneralPreferences getGeneralPreferences() { public ChatPreferences getChatPreferences() { if (chatPreferences == null) { - chatPreferences = new ChatPreferences(preferences, defaults); + chatPreferences = new ChatPreferences(store); } return chatPreferences; } public KeyBindingPreferences getKeyBindingPreferences() { if (keyBindingPreferences == null) { - keyBindingPreferences = new KeyBindingPreferences(preferences, defaults); + keyBindingPreferences = new KeyBindingPreferences(store); } return keyBindingPreferences; } public StatePreferences getStatePreferences() { if (statePreferences == null) - statePreferences = new StatePreferences(preferences, defaults); + statePreferences = new StatePreferences(store); return statePreferences; } // ******************** PROPERTIES ******************** - public static AppPreferences getInstance() { - return Holder.INSTANCE; - } - - private static class Holder { - private static final AppPreferences INSTANCE = new AppPreferences(); - } } diff --git a/src/main/java/com/github/k7t3/tcv/prefs/ChatPreferences.java b/src/main/java/com/github/k7t3/tcv/prefs/ChatPreferences.java index cdde2f3..4fe4174 100644 --- a/src/main/java/com/github/k7t3/tcv/prefs/ChatPreferences.java +++ b/src/main/java/com/github/k7t3/tcv/prefs/ChatPreferences.java @@ -16,44 +16,48 @@ package com.github.k7t3.tcv.prefs; -import com.github.k7t3.tcv.view.chat.ChatFont; +import com.github.k7t3.tcv.app.theme.JapaneseFonts; +import javafx.scene.text.Font; import javafx.beans.property.*; import java.util.Map; -import java.util.Objects; +import java.util.Optional; +import java.util.Base64; import java.util.prefs.Preferences; public class ChatPreferences extends PreferencesBase { - private static final int DEFAULT_CHAT_CACHE_SIZE = 256; - - /** - * チャットビューで適用されるフォントファミリ - */ - private static final String CHAT_FONT_FAMILY = "chat.font.family"; - - /** - * チャットビューでユーザー名を表示するか - */ - private static final String CHAT_SHOW_USERNAME = "chat.show.username"; - - /** - * チャットビューでユーザーのバッジを表示するか - */ - private static final String CHAT_SHOW_BADGES = "chat.show.badges"; - - /** 透過ウインドウの透過度*/ - private static final String FLOATABLE_CHAT_OPACITY = "floatable.chat.opacity"; + private static final PreferenceKey CHAT_FONT = new PreferenceKey<>("chat.font.family", + () -> new FontSettings(JapaneseFonts.defaultDisplayFamily(), Font.getDefault().getSize()), + value -> FontSettings.deserialize(Base64.getDecoder().decode(value)), + value -> Base64.getEncoder().encodeToString(value.serialize())); + private static final PreferenceKey CHAT_SHOW_USERNAME = PreferenceKey.bool("chat.show.username", true); + private static final PreferenceKey CHAT_SHOW_BADGES = PreferenceKey.bool("chat.show.badges", true); + private static final PreferenceKey FLOATABLE_CHAT_OPACITY = PreferenceKey.decimal("floatable.chat.opacity", 0.7, + value -> Double.isFinite(value) && value >= 0.1 && value <= 1); + private static final PreferenceKey FLOATABLE_CHAT_TOP = PreferenceKey.bool("floatable.chat.always.top", true); + private static final PreferenceKey CHAT_CACHE_SIZE = PreferenceKey.integer("chat.cache.size", 256, value -> value > 0); + + static Map> editorSettings() { + return Map.of(CHAT_FONT.name(), CHAT_FONT, CHAT_SHOW_USERNAME.name(), CHAT_SHOW_USERNAME, + CHAT_SHOW_BADGES.name(), CHAT_SHOW_BADGES, CHAT_CACHE_SIZE.name(), CHAT_CACHE_SIZE); + } - /** 透過ウインドウを常に最前面に表示するか*/ - private static final String FLOATABLE_CHAT_TOP = "floatable.chat.always.top"; + static java.util.Set storedKeys() { + var keys = new java.util.HashSet<>(editorSettings().keySet()); + keys.add(FLOATABLE_CHAT_OPACITY.name()); + keys.add(FLOATABLE_CHAT_TOP.name()); + return java.util.Set.copyOf(keys); + } - /** - * チャンネルビューごとにチャットをキャッシュする数 - */ - private static final String CHAT_CACHE_SIZE = "chat.cache.size"; + public static Map> editorValues(FontSettings font, boolean names, boolean badges, int cache) { + return Map.of(CHAT_FONT.name(), Optional.of(CHAT_FONT.encode(font)), + CHAT_SHOW_USERNAME.name(), Optional.of(CHAT_SHOW_USERNAME.encode(names)), + CHAT_SHOW_BADGES.name(), Optional.of(CHAT_SHOW_BADGES.encode(badges)), + CHAT_CACHE_SIZE.name(), Optional.of(CHAT_CACHE_SIZE.encode(cache))); + } - private ObjectProperty font; + private ObjectProperty font; private BooleanProperty showUserName; @@ -65,80 +69,19 @@ public class ChatPreferences extends PreferencesBase { private IntegerProperty chatCacheSize; - ChatPreferences(Preferences preferences, Map defaults) { - super(preferences, defaults); - - defaults.put(CHAT_FONT_FAMILY, ChatFont.getDefault().serialize()); - defaults.put(CHAT_SHOW_USERNAME, Boolean.TRUE); - defaults.put(CHAT_SHOW_BADGES, Boolean.TRUE); - defaults.put(FLOATABLE_CHAT_OPACITY, 0.7d); - defaults.put(FLOATABLE_CHAT_TOP, Boolean.TRUE); - defaults.put(CHAT_CACHE_SIZE, DEFAULT_CHAT_CACHE_SIZE); - } - - @Override - protected void readFromPreferences() { - var font = ChatFont.deserialize(getByteArray(CHAT_FONT_FAMILY)); - if (!Objects.equals(getFont(), font)) { - setFont(font); - } - - if (isShowBadges() != getBoolean(CHAT_SHOW_BADGES)) { - setShowBadges(getBoolean(CHAT_SHOW_BADGES)); - } - - if (isShowUserName() != getBoolean(CHAT_SHOW_USERNAME)) { - setShowUserName(getBoolean(CHAT_SHOW_USERNAME)); - } - - if (getFloatingChatAlwaysTop() != getBoolean(FLOATABLE_CHAT_TOP)) { - setFloatingChatAlwaysTop(getBoolean(FLOATABLE_CHAT_TOP)); - } - - if (getFloatingChatOpacity() != getDouble(FLOATABLE_CHAT_OPACITY)) { - setFloatingChatOpacity(getDouble(FLOATABLE_CHAT_OPACITY)); - } - - var chatCacheSize = getInt(CHAT_CACHE_SIZE); - if (chatCacheSize != getChatCacheSize()) { - setChatCacheSize(chatCacheSize); - } - } - - @Override - protected void writeToPreferences() { - if (font != null) { - var bytes = font.get().serialize(); - preferences.putByteArray(CHAT_FONT_FAMILY, bytes); - } - - if (showUserName != null) { - preferences.putBoolean(CHAT_SHOW_USERNAME, showUserName.get()); - } - - if (showBadges != null) { - preferences.putBoolean(CHAT_SHOW_BADGES, showBadges.get()); - } - - if (floatingChatOpacity != null) { - preferences.putDouble(FLOATABLE_CHAT_OPACITY, floatingChatOpacity.get()); - } - - if (floatingChatAlwaysTop != null) { - preferences.putBoolean(FLOATABLE_CHAT_TOP, floatingChatAlwaysTop.get()); - } - } + ChatPreferences(Preferences preferences) { super(preferences, editorSettings().keySet()); } + ChatPreferences(PreferenceStore store) { super(store, editorSettings().keySet()); } // ******************** PROPERTIES ******************** - public ObjectProperty fontProperty() { + public ObjectProperty fontProperty() { if (font == null) { - font = createBytesObjectProperty(CHAT_FONT_FAMILY, ChatFont::deserialize, ChatFont::serialize); + font = createObjectProperty(CHAT_FONT); } return font; } - public ChatFont getFont() { return fontProperty().get(); } - public void setFont(ChatFont font) { this.fontProperty().set(font); } + public FontSettings getFont() { return fontProperty().get(); } + public void setFont(FontSettings font) { this.fontProperty().set(font); } public BooleanProperty showUserNameProperty() { if (showUserName == null) showUserName = createBooleanProperty(CHAT_SHOW_USERNAME); diff --git a/src/main/java/com/github/k7t3/tcv/prefs/FontSettings.java b/src/main/java/com/github/k7t3/tcv/prefs/FontSettings.java new file mode 100644 index 0000000..549655f --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/prefs/FontSettings.java @@ -0,0 +1,33 @@ +package com.github.k7t3.tcv.prefs; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +/** 保存形式は従来の UTF フォント名 + double サイズ。JavaFX の表示状態を持たない。 */ +public record FontSettings(String family, double size) { + public FontSettings { + if (family == null || family.isBlank() || !Double.isFinite(size) || size <= 0) { + throw new IllegalArgumentException("invalid font settings"); + } + } + + public byte[] serialize() { + try (var bytes = new ByteArrayOutputStream(); var out = new DataOutputStream(bytes)) { + out.writeUTF(family); + out.writeDouble(size); + return bytes.toByteArray(); + } catch (IOException failure) { throw new IllegalArgumentException("cannot encode font settings", failure); } + } + + public static FontSettings deserialize(byte[] bytes) { + if (bytes == null) throw new IllegalArgumentException("missing font settings"); + try (var in = new DataInputStream(new ByteArrayInputStream(bytes))) { + var value = new FontSettings(in.readUTF(), in.readDouble()); + if (in.read() != -1) throw new IllegalArgumentException("trailing font settings data"); + return value; + } catch (IOException failure) { throw new IllegalArgumentException("cannot decode font settings", failure); } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/prefs/GeneralPreferences.java b/src/main/java/com/github/k7t3/tcv/prefs/GeneralPreferences.java index 9d5c21e..585c2cc 100644 --- a/src/main/java/com/github/k7t3/tcv/prefs/GeneralPreferences.java +++ b/src/main/java/com/github/k7t3/tcv/prefs/GeneralPreferences.java @@ -26,28 +26,35 @@ import javafx.beans.property.StringProperty; import java.util.Map; +import java.util.Optional; import java.util.prefs.Preferences; public class GeneralPreferences extends PreferencesBase { - /** このアプリケーションに適用されるテーマの名称*/ - private static final String THEME = "theme"; - /** テーマのタイプ*/ - private static final String THEME_TYPE = "theme.type"; - - /** チャンネルを複数選択して開くときの動作*/ - private static final String MULTIPLE_OPEN_TYPE = "multiple.open.type"; + private static final PreferenceKey THEME = PreferenceKey.enumeration("theme", ThemeManager.DEFAULT_THEME, Theme.class); + private static final PreferenceKey THEME_TYPE = PreferenceKey.enumeration("theme.type", ThemeType.SYSTEM, ThemeType.class); + private static final PreferenceKey MULTIPLE_OPEN_TYPE = PreferenceKey.enumeration( + "multiple.open.type", MultipleChatOpenType.SEPARATED, MultipleChatOpenType.class); + private static final String DATABASE_VERSION = "database.version"; + private static final PreferenceKey USER_DATA_FILE_PATH = new PreferenceKey<>("user.data.file", + () -> OS.current().getApplicationDirectory().toAbsolutePath().resolve("userdata.db").toString(), + java.util.function.Function.identity(), java.util.function.Function.identity()); - /** ユーザーデータを格納するファイルのパス*/ - private static final String USER_DATA_FILE_PATH = "user.data.file"; + static Map> editorSettings() { + return Map.of(THEME.name(), THEME, THEME_TYPE.name(), THEME_TYPE, MULTIPLE_OPEN_TYPE.name(), MULTIPLE_OPEN_TYPE); + } - /** - * データベースを構成するためのバージョン。 - * バージョンが異なるときはテーブルを変更する必要があるため現在の値を記録。 - */ - private static final String DATABASE_VERSION = "database.version"; + static java.util.Set storedKeys() { + var keys = new java.util.HashSet<>(editorSettings().keySet()); + keys.add(DATABASE_VERSION); + keys.add(USER_DATA_FILE_PATH.name()); + return java.util.Set.copyOf(keys); + } - private static final String USER_DATA_FILE_NAME = "userdata.db"; + public static Map> editorValues(Theme theme, ThemeType type, MultipleChatOpenType open) { + return Map.of(THEME.name(), Optional.of(THEME.encode(theme)), THEME_TYPE.name(), Optional.of(THEME_TYPE.encode(type)), + MULTIPLE_OPEN_TYPE.name(), Optional.of(MULTIPLE_OPEN_TYPE.encode(open))); + } private ObjectProperty theme; private ObjectProperty themeType; @@ -56,67 +63,27 @@ public class GeneralPreferences extends PreferencesBase { private StringProperty userDataFilePath; - GeneralPreferences(Preferences preferences, Map defaults) { - super(preferences, defaults); - - defaults.put(THEME, ThemeManager.DEFAULT_THEME.name()); - defaults.put(THEME_TYPE, ThemeType.SYSTEM.name()); - defaults.put(MULTIPLE_OPEN_TYPE, MultipleChatOpenType.SEPARATED.name()); - defaults.put(DATABASE_VERSION, DatabaseVersion.EMPTY.name()); - defaults.put(USER_DATA_FILE_PATH, OS.current().getApplicationDirectory() - .toAbsolutePath() - .resolve(USER_DATA_FILE_NAME) - .toString()); - } + GeneralPreferences(Preferences preferences) { super(preferences, editorSettings().keySet()); } + GeneralPreferences(PreferenceStore store) { super(store, editorSettings().keySet()); } public void setDatabaseVersion(DatabaseVersion version) { if (version == DatabaseVersion.EMPTY || version == DatabaseVersion.UNKNOWN) { throw new IllegalArgumentException(); } - preferences.put(DATABASE_VERSION, version.name()); + store.write(DATABASE_VERSION, Optional.of(version.name()), false); } public DatabaseVersion getDatabaseVersion() { - var name = preferences.get(DATABASE_VERSION, (String) defaults.get(DATABASE_VERSION)); + var name = store.read(DATABASE_VERSION).orElse(DatabaseVersion.EMPTY.name()); return DatabaseVersion.valueOf(name); } - @Override - protected void readFromPreferences() { - var themeName = get(THEME); - if (themeName != null) { - var theme = Theme.valueOf(themeName); - setTheme(theme); - } - - try { - var type = MultipleChatOpenType.valueOf(get(MULTIPLE_OPEN_TYPE)); - if (getMultipleOpenType() != type) { - setMultipleOpenType(type); - } - } catch (IllegalArgumentException ignored) { - } - - var userDataFilePath = get(USER_DATA_FILE_PATH); - if (!userDataFilePath.equalsIgnoreCase(getUserDataFilePath())) { - setUserDataFilePath(userDataFilePath); - } - - var databaseVersion = DatabaseVersion.valueOf(get(DATABASE_VERSION)); - if (databaseVersion != getDatabaseVersion()) { - setDatabaseVersion(databaseVersion); - } - } - - @Override - protected void writeToPreferences() { - } // ******************** PROPERTIES ******************** public ObjectProperty themeProperty() { if (theme == null) { - theme = createObjectProperty(THEME, Theme::valueOf, Theme::name); + theme = createObjectProperty(THEME); } return theme; } @@ -125,7 +92,7 @@ public ObjectProperty themeProperty() { public ObjectProperty themeTypeProperty() { if (themeType == null) { - themeType = createObjectProperty(THEME_TYPE, ThemeType::valueOf, ThemeType::name); + themeType = createObjectProperty(THEME_TYPE); } return themeType; } @@ -134,10 +101,7 @@ public ObjectProperty themeTypeProperty() { public ObjectProperty multipleOpenTypeProperty() { if (multipleOpenType == null) { - multipleOpenType = createObjectProperty( - MULTIPLE_OPEN_TYPE, - MultipleChatOpenType::valueOf, - Enum::name); + multipleOpenType = createObjectProperty(MULTIPLE_OPEN_TYPE); } return multipleOpenType; } diff --git a/src/main/java/com/github/k7t3/tcv/prefs/KeyBindingPreferences.java b/src/main/java/com/github/k7t3/tcv/prefs/KeyBindingPreferences.java index 306a7d5..511acb4 100644 --- a/src/main/java/com/github/k7t3/tcv/prefs/KeyBindingPreferences.java +++ b/src/main/java/com/github/k7t3/tcv/prefs/KeyBindingPreferences.java @@ -21,7 +21,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Map; +import java.util.Optional; import java.util.prefs.Preferences; /** @@ -30,47 +30,38 @@ * キーバインドの規定値は{@link KeyBinding}列挙クラスの通り。 *

*/ -public class KeyBindingPreferences extends PreferencesBase { +public class KeyBindingPreferences { + private final PreferenceStore store; private static final Logger LOGGER = LoggerFactory.getLogger(KeyBindingPreferences.class); - KeyBindingPreferences(Preferences preferences, Map defaults) { - super(preferences, defaults); - } + KeyBindingPreferences(Preferences preferences) { this(new PreferenceStore(preferences, null)); } + KeyBindingPreferences(PreferenceStore store) { this.store = java.util.Objects.requireNonNull(store); } public KeyCombination readCustomCombination(KeyBinding binding) { - var code = get(binding.getId()); + var code = store.read(binding.getId()).orElse(null); if (code == null) return KeyCombination.NO_MATCH; try { return KeyCombination.keyCombination(code); - } catch (Exception ignored) { + } catch (IllegalArgumentException ignored) { LOGGER.warn("stored invalid key combination"); return KeyCombination.NO_MATCH; } } public void storeCombination(KeyBinding binding, KeyCombination combination) { - // デフォルトキーが指定されたときは既存のカスタムキーバインドを削除 - if (binding.getDefaultCombination().equals(combination)) { - preferences.remove(binding.getId()); - } else { - preferences.put(binding.getId(), combination.getName()); - } + store.write(binding.getId(), editorValue(binding, combination), true); + } + + public static Optional editorValue(KeyBinding binding, KeyCombination combination) { + return binding.getDefaultCombination().equals(combination) ? Optional.empty() + : Optional.of(combination.getName()); } public void clear() { for (var binding : KeyBinding.values()) { - preferences.remove(binding.getId()); + store.write(binding.getId(), Optional.empty(), true); } } - @Override - protected void readFromPreferences() { - // no-op - } - - @Override - protected void writeToPreferences() { - // no-op - } } diff --git a/src/main/java/com/github/k7t3/tcv/prefs/PreferenceKey.java b/src/main/java/com/github/k7t3/tcv/prefs/PreferenceKey.java new file mode 100644 index 0000000..809fbe7 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/prefs/PreferenceKey.java @@ -0,0 +1,68 @@ +package com.github.k7t3.tcv.prefs; + +import java.util.Optional; +import java.util.function.DoublePredicate; +import java.util.function.Function; +import java.util.function.IntPredicate; +import java.util.function.Supplier; +import java.util.prefs.Preferences; +import org.slf4j.LoggerFactory; + +/** キー、型、既定値、保存形式を一か所に定義する。読取障害を不正な値と混同しない。 */ +record PreferenceKey(String name, Supplier fallback, Function parse, Function format) { + T read(Preferences preferences) { + // 保存先の SecurityException / IllegalStateException 等は既定値に置き換えず呼出元へ返す。 + return read(Optional.ofNullable(preferences.get(name, null))); + } + + T read(Optional stored) { + if (stored.isEmpty()) return fallback.get(); + try { return decode(stored.get()); } + catch (IllegalArgumentException invalid) { + // 値や例外メッセージは記録しない。保存値はそのまま保つ。 + LoggerFactory.getLogger(PreferenceKey.class).warn("invalid preference '{}'; using its default", name); + return fallback.get(); + } + } + + T decode(String value) { + var decoded = parse.apply(value); + if (decoded == null) throw new IllegalArgumentException("invalid preference: " + name); + return decoded; + } + + String encode(T value) { + if (value == null) throw new IllegalArgumentException("invalid preference: " + name); + var encoded = format.apply(value); + decode(encoded); + return encoded; + } + + static PreferenceKey bool(String name, boolean fallback) { + return new PreferenceKey<>(name, () -> fallback, value -> { + if ("true".equalsIgnoreCase(value)) return true; + if ("false".equalsIgnoreCase(value)) return false; + throw new IllegalArgumentException("invalid boolean preference"); + }, Object::toString); + } + + static PreferenceKey integer(String name, int fallback, IntPredicate valid) { + return new PreferenceKey<>(name, () -> fallback, value -> { + var number = Integer.parseInt(value); + if (!valid.test(number)) throw new IllegalArgumentException("invalid integer preference"); + return number; + }, Object::toString); + } + + static PreferenceKey decimal(String name, double fallback, DoublePredicate valid) { + return new PreferenceKey<>(name, () -> fallback, value -> { + var number = Double.parseDouble(value); + if (!valid.test(number)) throw new IllegalArgumentException("invalid decimal preference"); + return number; + }, Object::toString); + } + + static > PreferenceKey enumeration(String name, E fallback, Class type) { + return new PreferenceKey<>(name, () -> fallback, value -> Enum.valueOf(type, value), Enum::name); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/prefs/PreferenceProjection.java b/src/main/java/com/github/k7t3/tcv/prefs/PreferenceProjection.java new file mode 100644 index 0000000..1173c5e --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/prefs/PreferenceProjection.java @@ -0,0 +1,115 @@ +package com.github.k7t3.tcv.prefs; + +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.Set; +import java.util.prefs.Preferences; + +/** 通常プロパティの保存と設定エディターが共有する、キーごとの更新所有情報。 */ +public final class PreferenceProjection { + private static final String OWNERS = "settings.projection.owners"; + private static final String PENDING_PREFIX = "settings.projection.pending."; + + private PreferenceProjection() {} + + /** + * 他DBの復旧が未完了の投影を後続の確定保存と区別できるようにする。 + * @param node monitorと保存用の排他を呼出側で保持するノード + * @param operation これから投影する操作。flushは呼出側が行う + */ + public static void beginProjection(Preferences node, UUID operation) { + node.put(PENDING_PREFIX + operation, "1"); + } + + /** + * @param node monitorと保存用の排他を呼出側で保持するノード + * @param operation 所有情報から得た操作 + * @return 確定または補償の完了が未通知ならtrue。旧記録に印がなければfalse + * @throws IllegalArgumentException 未対応の未完了印の場合 + */ + public static boolean isPending(Preferences node, UUID operation) { + var value = node.get(PENDING_PREFIX + operation, null); + if (value == null) return false; + if (!value.equals("1")) throw new IllegalArgumentException("invalid pending settings projection"); + return true; + } + + /** + * @param node monitorと保存用の排他を呼出側で保持するノード + * @param operation 確定または補償を完了した操作。flushは呼出側が行う + */ + public static void completeProjection(Preferences node, UUID operation) { + node.remove(PENDING_PREFIX + operation); + } + + /** + * @param node monitorと保存用の排他を呼出側で保持するノード + * @return 補償用の所有情報。未作成と空の記録を区別して保持する + */ + public static Optional snapshotOwners(Preferences node) { return Optional.ofNullable(node.get(OWNERS, null)); } + + /** + * 同じ排他範囲の失敗した更新を補償する。flushは呼出側が行う。 + * @param node monitorと保存用の排他を呼出側で保持するノード + * @param previous 更新前に取得した所有情報 + */ + public static void restoreOwners(Preferences node, Optional previous) { + if (previous.isPresent()) node.put(OWNERS, previous.orElseThrow()); + else node.remove(OWNERS); + } + + /** + * 既存の所有情報を検証して読み出す。呼出側がnodeのmonitorを保持する。 + * @param node 借用する設定ノード + * @return キーごとの更新識別子。返したMapの変更はノードへ反映しない + */ + public static Map> owners(Preferences node) { + var encoded = node.get(OWNERS, null); + if (encoded == null) return new HashMap<>(); + return decodeOwners(Base64.getDecoder().decode(encoded)); + } + + /** + * @param encoded 既存の版1形式で保存された所有情報 + * @return UUIDまで検証済みの所有情報。返したMapは変更しても保存先に作用しない + */ + public static Map> decodeOwners(byte[] encoded) { + var result = new HashMap<>(PreferenceValuesCodec.decode(encoded)); + result.values().forEach(value -> UUID.fromString(value.orElseThrow( + () -> new IllegalArgumentException("missing settings projection owner")))); + return result; + } + + /** + * 復旧したキーだけを以前の所有へ戻す。後続保存が所有する他のキーを維持する。 + * @param node monitorと保存用の排他を呼出側で保持するノード + * @param previous 検証済みの更新前所有情報 + * @param keys 値の補償に成功したキー。flushは呼出側が行う + */ + public static void restoreOwners(Preferences node, Map> previous, Set keys) { + var owners = owners(node); + keys.forEach(key -> { + if (previous.containsKey(key)) owners.put(key, previous.get(key)); + else owners.remove(key); + }); + if (owners.isEmpty()) node.remove(OWNERS); + else node.put(OWNERS, Base64.getEncoder().encodeToString(PreferenceValuesCodec.encode(owners))); + } + + /** + * 更新するキーの所有を記録する。値の保存とflushは呼出側が行う。 + * 呼出側がnodeのmonitorを保持し、プロセス間の排他も必要に応じて確保する。 + * @param node 借用する設定ノード + * @param operation この更新だけを識別するUUID + * @param values 更新するキー。既存の他キーの所有は維持する + */ + public static void claim(Preferences node, UUID operation, Map> values) { + if (values.isEmpty()) return; + var owners = owners(node); + values.keySet().forEach(key -> owners.put(key, Optional.of(operation.toString()))); + node.put(OWNERS, Base64.getEncoder().encodeToString(PreferenceValuesCodec.encode(owners))); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/prefs/PreferenceStore.java b/src/main/java/com/github/k7t3/tcv/prefs/PreferenceStore.java new file mode 100644 index 0000000..2d5f96b --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/prefs/PreferenceStore.java @@ -0,0 +1,249 @@ +package com.github.k7t3.tcv.prefs; + +import com.github.k7t3.tcv.app.service.SerialIoQueue; +import com.github.k7t3.tcv.io.PreferenceFileLock; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import java.util.prefs.BackingStoreException; +import java.util.prefs.Preferences; + +/** 所有ノードへの変更を受付順に永続化する。借用ノードは呼出元で直ちに変更する。 */ +final class PreferenceStore { + private static final ScopedValue ACTIVE = ScopedValue.newInstance(); + private final Preferences node; + private final Path file; + private final SerialIoQueue queue; + private final Object admission = new Object(); + private final List failures = new ArrayList<>(); + private final Map pending = new HashMap<>(); + private final Map> cached = new HashMap<>(); + private CompletableFuture closed; + + PreferenceStore(Preferences node, Path file) { + this(node, file, task -> Thread.ofVirtual().name("TCV-Preferences").start(task)); + } + + PreferenceStore(Preferences node, Path file, Executor executor) { + this.node = java.util.Objects.requireNonNull(node); + this.file = file; + queue = file == null ? null : new SerialIoQueue(executor); + } + + Optional read(String key) { + synchronized (admission) { + if (cached.containsKey(key)) return cached.get(key); + } + return Optional.ofNullable(node.get(key, null)); + } + + void load(Set keys) { + if (queue == null) return; + exclusive(() -> { + var loaded = new HashMap>(); + synchronized (node) { + sync(); + keys.forEach(key -> loaded.put(key, Optional.ofNullable(node.get(key, null)))); + } + synchronized (admission) { + loaded.forEach((key, value) -> { if (!pending.containsKey(key)) cached.put(key, value); }); + } + return null; + }); + } + + void committed(Map> values) { + if (queue == null) return; + synchronized (admission) { + values.forEach((key, value) -> { if (!pending.containsKey(key)) cached.put(key, value); }); + } + } + + Map> currentProjection(Map> values) { + if (queue == null) return Map.copyOf(values); + var current = new HashMap>(); + synchronized (admission) { + values.forEach((key, value) -> { if (value.equals(cached.get(key))) current.put(key, value); }); + } + return Map.copyOf(current); + } + + void write(String key, Optional value, boolean recoveryKey) { + Runnable change = () -> { + if (recoveryKey) PreferenceProjection.claim(node, UUID.randomUUID(), Map.of(key, value)); + if (value.isPresent()) node.put(key, value.orElseThrow()); + else node.remove(key); + }; + if (queue == null) { + synchronized (admission) { ensureOpen(); } + if (recoveryKey) { synchronized (node) { change.run(); } } + else change.run(); + return; + } + synchronized (admission) { + ensureOpen(); + var accepted = new Object(); + pending.put(key, accepted); + cached.put(key, value); + var started = new AtomicBoolean(); + queue.submit(() -> { + started.set(true); + try { + locked(() -> { + synchronized (node) { + sync(); + var previous = Optional.ofNullable(node.get(key, null)); + var owners = recoveryKey ? PreferenceProjection.snapshotOwners(node) : Optional.empty(); + try { change.run(); flush(); } + catch (RuntimeException | Error failure) { + // 失敗した通常変更を、古いSQL投影より新しい確定済み変更として残さない。 + try { + CloseActions.runAll(() -> { + if (previous.isPresent()) node.put(key, previous.orElseThrow()); + else node.remove(key); + }, () -> { + if (recoveryKey) PreferenceProjection.restoreOwners(node, owners); + }, this::flush); + } catch (RuntimeException | Error restore) { + if (restore != failure) failure.addSuppressed(restore); + } + throw failure; + } + } + return null; + }); + synchronized (admission) { + // 同じキーへの後続変更を、古い書込の完了で消さない。 + if (pending.get(key) == accepted) pending.remove(key); + } + return null; + } catch (RuntimeException | Error failure) { + synchronized (admission) { failures.add(failure); } + throw failure; + } + }).whenComplete((ignored, failure) -> { + if (failure != null && !started.get()) { + var cause = failure instanceof CompletionException && failure.getCause() != null + ? failure.getCause() : failure; + // 本体が記録する失敗と分け、未開始の書込だけを所有する。 + synchronized (admission) { failures.add(cause); } + } + }); + } + } + + T exclusive(Supplier operation) { + if (ACTIVE.isBound() && ACTIVE.get() == this) return operation.get(); + return call(operation, false); + } + + private T call(Supplier operation, boolean finishing) { + if (queue == null) { + synchronized (admission) { if (!finishing) ensureOpen(); } + return PreferenceFileLock.exclusive(null, operation); + } + final CompletionStage accepted; + var started = new AtomicBoolean(); + synchronized (admission) { + if (!finishing) ensureOpen(); + accepted = queue.submit(() -> { + started.set(true); + if (!finishing) { reportFailures(null); return locked(operation); } + T result = null; + Throwable finalFailure = null; + try { result = locked(operation); } + catch (RuntimeException | Error failure) { finalFailure = failure; } + // ファイル取得に失敗しても、先行する書込の失敗を失わない。 + reportFailures(finalFailure); + return result; + }); + } + try { return await(accepted); } + catch (RuntimeException | Error failure) { + // 終了要求自体の投入拒否でも、先行書込みの失敗を回収する。 + if (finishing && !started.get()) reportFailures(failure); + throw failure; + } + } + + private static T await(CompletionStage accepted) { + try { return accepted.toCompletableFuture().join(); } + catch (CompletionException failure) { + if (failure.getCause() instanceof RuntimeException exception) throw exception; + if (failure.getCause() instanceof Error error) throw error; + throw new IllegalStateException(failure.getCause()); + } + } + + void save() { + if (queue == null || ACTIVE.isBound() && ACTIVE.get() == this) { flush(); return; } + call(() -> { + synchronized (node) { sync(); flush(); } + return null; + }, true); + } + + private void reportFailures(Throwable finalFailure) { + final List previous; + synchronized (admission) { previous = List.copyOf(failures); } + if (!previous.isEmpty()) { + var failure = new IllegalStateException("preference writes failed", previous.getFirst()); + previous.stream().skip(1).forEach(failure::addSuppressed); + if (finalFailure != null) failure.addSuppressed(finalFailure); + throw failure; + } + if (finalFailure instanceof RuntimeException failure) throw failure; + if (finalFailure instanceof Error failure) throw failure; + } + + void close(Runnable finish) { + if (ACTIVE.isBound() && ACTIVE.get() == this) throw new IllegalStateException("cannot close active preference storage"); + final boolean owner; + final CompletableFuture completion; + synchronized (admission) { + owner = closed == null; + if (owner) closed = new CompletableFuture<>(); + completion = closed; + } + if (owner) { + try { finish.run(); completion.complete(null); } + catch (RuntimeException | Error failure) { completion.completeExceptionally(failure); } + } + await(completion); + } + + private void ensureOpen() { + if (closed != null) throw new IllegalStateException("preference storage is closed"); + } + + void checkOpen() { synchronized (admission) { ensureOpen(); } } + + private T locked(Supplier operation) { + // DBを使う処理では、共有ファイル→DB→ノードの取得順を呼出側に維持させる。 + return PreferenceFileLock.exclusive(file, () -> ScopedValue.where(ACTIVE, this).call(operation::get)); + } + + private void sync() { + try { node.sync(); } + catch (BackingStoreException failure) { throw new IllegalStateException(failure); } + } + + private void flush() { + synchronized (node) { + try { node.flush(); } + catch (BackingStoreException failure) { throw new IllegalStateException(failure); } + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/prefs/PreferenceValuesCodec.java b/src/main/java/com/github/k7t3/tcv/prefs/PreferenceValuesCodec.java new file mode 100644 index 0000000..1b7652d --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/prefs/PreferenceValuesCodec.java @@ -0,0 +1,69 @@ +package com.github.k7t3.tcv.prefs; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.TreeMap; +import java.util.prefs.Preferences; + +/** 設定の復旧記録とキー所有情報が共有する、既存の版付きバイナリ形式。 */ +public final class PreferenceValuesCodec { + private PreferenceValuesCodec() {} + + /** + * キー順の版1形式へ変換する。emptyは値の削除を表す。 + * @param values Preferencesの長さ制約に収まるキーとraw値 + * @return 既存の復旧記録と互換のバイト列 + */ + public static byte[] encode(Map> values) { + try { + var bytes = new ByteArrayOutputStream(); + try (var output = new DataOutputStream(bytes)) { + output.writeInt(1); + output.writeInt(values.size()); + for (var entry : new TreeMap<>(values).entrySet()) { + validateLength(entry.getKey(), entry.getValue()); + output.writeUTF(entry.getKey()); + output.writeBoolean(entry.getValue().isPresent()); + if (entry.getValue().isPresent()) output.writeUTF(entry.getValue().orElseThrow()); + } + } + return bytes.toByteArray(); + } catch (IOException failure) { throw new UncheckedIOException(failure); } + } + + /** + * 版・件数・重複・長さ・末尾を検証して読み戻す。 + * @param bytes 版1形式の記録 + * @return 不変のraw値。型ごとの妥当性は利用側で検証する + * @throws IllegalArgumentException 記録が不正、または未対応の版の場合 + */ + public static Map> decode(byte[] bytes) { + try (var input = new DataInputStream(new ByteArrayInputStream(bytes))) { + if (input.readInt() != 1) throw new IllegalArgumentException("unknown settings recovery format"); + var count = input.readInt(); + if (count < 0 || count > bytes.length / 3) throw new IllegalArgumentException("invalid settings recovery size"); + var result = new HashMap>(); + for (var index = 0; index < count; index++) { + var key = input.readUTF(); + var value = input.readBoolean() ? Optional.of(input.readUTF()) : Optional.empty(); + validateLength(key, value); + if (result.putIfAbsent(key, value) != null) throw new IllegalArgumentException("duplicate recovery key"); + } + if (input.read() != -1) throw new IllegalArgumentException("trailing settings recovery data"); + return Map.copyOf(result); + } catch (IOException failure) { throw new IllegalArgumentException("invalid settings recovery record", failure); } + } + + private static void validateLength(String key, Optional value) { + if (key.length() > Preferences.MAX_KEY_LENGTH || value.filter(s -> s.length() > Preferences.MAX_VALUE_LENGTH).isPresent()) { + throw new IllegalArgumentException("invalid settings recovery value length"); + } + } +} diff --git a/src/main/java/com/github/k7t3/tcv/prefs/PreferencesBase.java b/src/main/java/com/github/k7t3/tcv/prefs/PreferencesBase.java index 86a18a0..d64e58f 100644 --- a/src/main/java/com/github/k7t3/tcv/prefs/PreferencesBase.java +++ b/src/main/java/com/github/k7t3/tcv/prefs/PreferencesBase.java @@ -17,127 +17,87 @@ package com.github.k7t3.tcv.prefs; import javafx.beans.property.*; -import org.slf4j.LoggerFactory; - +import java.util.HashMap; import java.util.Map; -import java.util.function.Function; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; import java.util.prefs.Preferences; public abstract class PreferencesBase { + protected final PreferenceStore store; + private final Map>> updates = new HashMap<>(); + private boolean applying; + private final Set recoveryKeys; - protected final Preferences preferences; - - protected final Map defaults; + PreferencesBase(Preferences preferences) { this(preferences, Set.of()); } - PreferencesBase(Preferences preferences, Map defaults) { - this.preferences = preferences; - this.defaults = defaults; + PreferencesBase(Preferences preferences, Set recoveryKeys) { + this(new PreferenceStore(preferences, null), recoveryKeys); } - /** - * ストアに保存される内容を明示的に読み込む - */ - protected abstract void readFromPreferences(); - - /** - * バッファリングされる設定内容を明示的にバッキングストアに書き込む - */ - protected abstract void writeToPreferences(); - - protected BooleanProperty createBooleanProperty(String key) { - var property = new SimpleBooleanProperty(getBoolean(key)); - property.addListener((ob, o, n) -> preferences.putBoolean(key, n)); - return property; + PreferencesBase(PreferenceStore store, Set recoveryKeys) { + this.store = java.util.Objects.requireNonNull(store); + this.recoveryKeys = Set.copyOf(recoveryKeys); } - protected IntegerProperty createIntegerProperty(String key) { - var property = new SimpleIntegerProperty(getInt(key)); - property.addListener((ob, o, n) -> preferences.putInt(key, n.intValue())); - return property; + final void applyCommittedValues(Map> values) { + var previous = applying; + applying = true; + try { values.forEach((key, value) -> { var update = updates.get(key); if (update != null) update.accept(value); }); } + finally { applying = previous; } } - protected DoubleProperty createDoubleProperty(String key) { - var property = new SimpleDoubleProperty(getDouble(key)); - property.addListener((ob, o, n) -> preferences.putDouble(key, n.doubleValue())); + protected BooleanProperty createBooleanProperty(PreferenceKey key) { + var property = new SimpleBooleanProperty(key.read(store.read(key.name()))) { + @Override public void set(boolean value) { checkWritable(); super.set(value); } + }; + updates.put(key.name(), value -> property.set(key.read(value))); + property.addListener((ob, old, next) -> write(key, next)); return property; } - protected StringProperty createStringProperty(String key) { - var property = new SimpleStringProperty(get(key)); - property.addListener((ob, o, n) -> preferences.put(key, n)); + protected IntegerProperty createIntegerProperty(PreferenceKey key) { + var property = new SimpleIntegerProperty(key.read(store.read(key.name()))) { + @Override public void set(int value) { checkWritable(); key.encode(value); super.set(value); } + }; + updates.put(key.name(), value -> property.set(key.read(value))); + property.addListener((ob, old, next) -> write(key, next.intValue())); return property; } - protected ObjectProperty createBytesObjectProperty( - String key, - Function fromBytes, - Function toBytes) { - var property = new SimpleObjectProperty<>(fromBytes.apply(getByteArray(key))); - property.addListener((ob, o, n) -> preferences.putByteArray(key, toBytes.apply(n))); + protected DoubleProperty createDoubleProperty(PreferenceKey key) { + var property = new SimpleDoubleProperty(key.read(store.read(key.name()))) { + @Override public void set(double value) { checkWritable(); key.encode(value); super.set(value); } + }; + updates.put(key.name(), value -> property.set(key.read(value))); + property.addListener((ob, old, next) -> write(key, next.doubleValue())); return property; } - protected ObjectProperty createObjectProperty( - String key, - Function fromString, - Function toString - ) { - Function f = s -> { - try { - return fromString.apply(s); - } catch (Exception e) { - LoggerFactory.getLogger(getClass()).warn(e.getMessage()); - return fromString.apply((String) defaults.get(key)); - } + protected StringProperty createStringProperty(PreferenceKey key) { + var property = new SimpleStringProperty(key.read(store.read(key.name()))) { + @Override public void set(String value) { checkWritable(); key.encode(value); super.set(value); } }; - var property = new SimpleObjectProperty<>(f.apply(get(key))); - property.addListener((ob, o, n) -> preferences.put(key, toString.apply(n))); + updates.put(key.name(), value -> property.set(key.read(value))); + property.addListener((ob, old, next) -> write(key, next)); return property; } - protected String get(String key) { - try { - return preferences.get(key, (String) defaults.get(key)); - } catch (Exception e) { - LoggerFactory.getLogger(getClass()).warn(e.getMessage(), e); - return (String) defaults.get(key); - } - } - - protected int getInt(String key) { - try { - return preferences.getInt(key, (Integer) defaults.get(key)); - } catch (Exception e) { - LoggerFactory.getLogger(getClass()).warn(e.getMessage(), e); - return (Integer) defaults.get(key); - } - } - - protected double getDouble(String key) { - try { - return preferences.getDouble(key, (Double) defaults.get(key)); - } catch (Exception e) { - LoggerFactory.getLogger(getClass()).warn(e.getMessage(), e); - return (Double) defaults.get(key); - } - } - - protected boolean getBoolean(String key) { - try { - return preferences.getBoolean(key, (Boolean) defaults.get(key)); - } catch (Exception e) { - LoggerFactory.getLogger(getClass()).warn(e.getMessage(), e); - return (Boolean) defaults.get(key); - } + protected ObjectProperty createObjectProperty(PreferenceKey key) { + var property = new SimpleObjectProperty(key.read(store.read(key.name()))) { + @Override public void set(T value) { checkWritable(); key.encode(value); super.set(value); } + }; + updates.put(key.name(), value -> property.set(key.read(value))); + property.addListener((ob, old, next) -> write(key, next)); + return property; } - protected byte[] getByteArray(String key) { - try { - return preferences.getByteArray(key, (byte[]) defaults.get(key)); - } catch (Exception e) { - LoggerFactory.getLogger(getClass()).warn(e.getMessage(), e); - return (byte[]) defaults.get(key); - } + private void write(PreferenceKey key, T value) { + if (applying) return; + var encoded = key.encode(value); + store.write(key.name(), Optional.of(encoded), recoveryKeys.contains(key.name())); } + private void checkWritable() { if (!applying) store.checkOpen(); } } diff --git a/src/main/java/com/github/k7t3/tcv/prefs/StatePreferences.java b/src/main/java/com/github/k7t3/tcv/prefs/StatePreferences.java index efee783..c327436 100644 --- a/src/main/java/com/github/k7t3/tcv/prefs/StatePreferences.java +++ b/src/main/java/com/github/k7t3/tcv/prefs/StatePreferences.java @@ -19,16 +19,22 @@ import javafx.beans.property.BooleanProperty; import javafx.beans.property.StringProperty; -import java.util.Map; +import com.github.k7t3.tcv.app.group.ChannelGroupOrder; import java.util.prefs.Preferences; public class StatePreferences extends PreferencesBase { - private static final String TOGGLE_CHANNELS = "toggle.channels"; - private static final String ONLY_LIVE = "only.live"; - private static final String ONLY_FOLLOWS = "only.follows"; - private static final String GROUP_ORDER_DESCENDING = "group.order.descending"; - private static final String GROUP_ORDER_ITEM = "group.order.item"; + private static final PreferenceKey TOGGLE_CHANNELS = PreferenceKey.bool("toggle.channels", true); + private static final PreferenceKey ONLY_LIVE = PreferenceKey.bool("only.live", false); + private static final PreferenceKey ONLY_FOLLOWS = PreferenceKey.bool("only.follows", false); + private static final PreferenceKey GROUP_ORDER_DESCENDING = PreferenceKey.bool("group.order.descending", false); + private static final PreferenceKey GROUP_ORDER_ITEM = new PreferenceKey<>("group.order.item", + () -> ChannelGroupOrder.NAME.name(), value -> ChannelGroupOrder.valueOf(value).name(), value -> value); + + static java.util.Set storedKeys() { + return java.util.Set.of(TOGGLE_CHANNELS.name(), ONLY_LIVE.name(), ONLY_FOLLOWS.name(), + GROUP_ORDER_DESCENDING.name(), GROUP_ORDER_ITEM.name()); + } private BooleanProperty toggleChannels; private BooleanProperty onlyLive; @@ -36,43 +42,14 @@ public class StatePreferences extends PreferencesBase { private BooleanProperty groupOrderDescending; private StringProperty groupOrderItem; - StatePreferences(Preferences preferences, Map defaults) { - super(preferences, defaults); - - defaults.put(TOGGLE_CHANNELS, Boolean.TRUE); - defaults.put(ONLY_LIVE, Boolean.FALSE); - defaults.put(ONLY_FOLLOWS, Boolean.FALSE); - defaults.put(GROUP_ORDER_DESCENDING, Boolean.FALSE); - defaults.put(GROUP_ORDER_ITEM, "NAME"); // ChannelGroupListViewを参照 - } - - @Override - protected void readFromPreferences() { - boolean v; - if ((v = getBoolean(TOGGLE_CHANNELS)) != isToggleChannels()) - setToggleChannels(v); - if ((v = getBoolean(ONLY_LIVE)) != isOnlyLive()) - setOnlyLive(v); - if ((v = getBoolean(ONLY_FOLLOWS)) != isOnlyFollows()) - setOnlyFollows(v); - if ((v = getBoolean(GROUP_ORDER_DESCENDING)) != isGroupOrderDescending()) - setGroupOrderDescending(v); - - String item; - if (!(item = get(GROUP_ORDER_ITEM)).equals(getGroupOrderItem())) - setGroupOrderItem(item); - } - - @Override - protected void writeToPreferences() { - // no-op - } + StatePreferences(Preferences preferences) { super(preferences); } + StatePreferences(PreferenceStore store) { super(store, java.util.Set.of()); } public BooleanProperty toggleChannelsProperty() { if (toggleChannels == null) toggleChannels = createBooleanProperty(TOGGLE_CHANNELS); return toggleChannels; } - public boolean isToggleChannels() { return toggleChannels == null ? (boolean) defaults.get(TOGGLE_CHANNELS) : toggleChannels.get(); } + public boolean isToggleChannels() { return toggleChannelsProperty().get(); } public void setToggleChannels(boolean toggleChannels) { toggleChannelsProperty().set(toggleChannels); } public BooleanProperty onlyLiveProperty() { @@ -80,27 +57,27 @@ public BooleanProperty onlyLiveProperty() { return onlyLive; } public void setOnlyLive(boolean onlyLive) { onlyLiveProperty().set(onlyLive); } - public boolean isOnlyLive() { return onlyLive == null ? (boolean) defaults.get(ONLY_LIVE) : onlyLive.get(); } + public boolean isOnlyLive() { return onlyLiveProperty().get(); } public BooleanProperty onlyFollowsProperty() { if (onlyFollows == null) onlyFollows = createBooleanProperty(ONLY_FOLLOWS); return onlyFollows; } - public boolean isOnlyFollows() { return onlyFollows == null ? (boolean) defaults.get(ONLY_FOLLOWS) : onlyFollows.get(); } + public boolean isOnlyFollows() { return onlyFollowsProperty().get(); } public void setOnlyFollows(boolean onlyFollows) { onlyFollowsProperty().set(onlyFollows); } public BooleanProperty groupOrderDescendingProperty() { if (groupOrderDescending == null) groupOrderDescending = createBooleanProperty(GROUP_ORDER_DESCENDING); return groupOrderDescending; } - public boolean isGroupOrderDescending() { return groupOrderDescending == null ? (boolean) defaults.get(GROUP_ORDER_DESCENDING) : groupOrderDescending.get(); } + public boolean isGroupOrderDescending() { return groupOrderDescendingProperty().get(); } public void setGroupOrderDescending(boolean groupOrderDescending) { groupOrderDescendingProperty().set(groupOrderDescending); } public StringProperty groupOrderItemProperty() { if (groupOrderItem == null) groupOrderItem = createStringProperty(GROUP_ORDER_ITEM); return groupOrderItem; } - public String getGroupOrderItem() { return groupOrderItem == null ? (String) defaults.get(GROUP_ORDER_ITEM) : groupOrderItem.get(); } + public String getGroupOrderItem() { return groupOrderItemProperty().get(); } public void setGroupOrderItem(String groupOrderItem) { groupOrderItemProperty().set(groupOrderItem); } } diff --git a/src/main/java/com/github/k7t3/tcv/reactive/AbstractSubscriber.java b/src/main/java/com/github/k7t3/tcv/reactive/AbstractSubscriber.java index f2abe8b..6df1531 100644 --- a/src/main/java/com/github/k7t3/tcv/reactive/AbstractSubscriber.java +++ b/src/main/java/com/github/k7t3/tcv/reactive/AbstractSubscriber.java @@ -17,6 +17,7 @@ package com.github.k7t3.tcv.reactive; import java.util.concurrent.Flow; +import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; @@ -30,11 +31,21 @@ */ public abstract class AbstractSubscriber implements FlowableSubscriber { - protected final AtomicReference backPressurePolicy = new AtomicReference<>(BackPressurePolicy.FULL); - protected final AtomicReference requestedPolicy = new AtomicReference<>(BackPressurePolicy.FULL); - protected final AtomicLong segmentCounter = new AtomicLong(0); + private static final Flow.Subscription CANCELLED = new Flow.Subscription() { + @Override + public void request(long n) { + } + + @Override + public void cancel() { + } + }; - private Flow.Subscription subscription; + private final AtomicReference backPressurePolicy = new AtomicReference<>(BackPressurePolicy.FULL); + private final AtomicReference requestedPolicy = new AtomicReference<>(BackPressurePolicy.FULL); + private final AtomicLong segmentCounter = new AtomicLong(0); + + private final AtomicReference subscription = new AtomicReference<>(); /** * 流量制限を指定する。 @@ -46,7 +57,11 @@ public void setBackPressurePolicy(BackPressurePolicy policy) { @Override public void onSubscribe(Flow.Subscription subscription) { - this.subscription = subscription; + Objects.requireNonNull(subscription); + if (!this.subscription.compareAndSet(null, subscription)) { + subscription.cancel(); + return; + } var policy = backPressurePolicy.get(); requestedPolicy.set(policy); @@ -55,13 +70,15 @@ public void onSubscribe(Flow.Subscription subscription) { protected abstract void handle(T item); - protected void request(long requestSize) { + private void request(long requestSize) { segmentCounter.set(0); - subscription.request(requestSize); + var current = subscription.get(); + if (current != null) current.request(requestSize); } @Override public void onNext(T item) { + if (isCancelled()) return; handle(item); // 現在設定されているポリシーとリクエスト時点のポリシーを取得 @@ -82,11 +99,14 @@ public void onNext(T item) { } } + /** 解除後にキューから届いた通知を破棄するための状態。 */ + protected final boolean isCancelled() { + return subscription.get() == CANCELLED; + } + @Override public void cancel() { - if (subscription != null) { - subscription.cancel(); - subscription = null; - } + var current = subscription.getAndSet(CANCELLED); + if (current != null) current.cancel(); } } diff --git a/src/main/java/com/github/k7t3/tcv/reactive/FlowableSubscriber.java b/src/main/java/com/github/k7t3/tcv/reactive/FlowableSubscriber.java index 32eac46..d5651bf 100644 --- a/src/main/java/com/github/k7t3/tcv/reactive/FlowableSubscriber.java +++ b/src/main/java/com/github/k7t3/tcv/reactive/FlowableSubscriber.java @@ -27,8 +27,8 @@ public interface FlowableSubscriber extends Flow.Subscriber { /** * 購読を解除する。 *

- * まだ購読が開始されていない({@link #onSubscribe(Flow.Subscription)}がコールされていない) - * ときは何も実行されない。 + * 登録前に呼び出した場合も、後から届く購読を解除する。 + * 解除は冪等であり、このサブスクライバーを再利用して購読を開始することはできない。 *

*/ void cancel(); diff --git a/src/main/java/com/github/k7t3/tcv/view/ApplicationWindow.java b/src/main/java/com/github/k7t3/tcv/view/ApplicationWindow.java new file mode 100644 index 0000000..54a3289 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/view/ApplicationWindow.java @@ -0,0 +1,7 @@ +package com.github.k7t3.tcv.view; + +/** 生成直後から所有し、画面構築の途中失敗でも解放できるウインドウ。 */ +interface ApplicationWindow extends AutoCloseable { + void show(); + @Override void close(); +} diff --git a/src/main/java/com/github/k7t3/tcv/view/Launcher.java b/src/main/java/com/github/k7t3/tcv/view/Launcher.java index 63ee7c2..0506505 100644 --- a/src/main/java/com/github/k7t3/tcv/view/Launcher.java +++ b/src/main/java/com/github/k7t3/tcv/view/Launcher.java @@ -19,154 +19,253 @@ import com.github.k7t3.tcv.app.core.AppHelper; import com.github.k7t3.tcv.app.core.ExceptionHandler; import com.github.k7t3.tcv.app.core.LoggerInitializer; -import com.github.k7t3.tcv.app.core.Resources; import com.github.k7t3.tcv.app.main.MainViewModel; +import com.github.k7t3.tcv.app.auth.PreferencesCredentialStorage; +import com.github.k7t3.tcv.app.secure.CredentialCipherService; import com.github.k7t3.tcv.app.secure.KeyManagerFactory; +import com.github.k7t3.tcv.app.service.ApplicationShutdown; import com.github.k7t3.tcv.app.user.UserDataFile; +import com.github.k7t3.tcv.lifecycle.CloseActions; import com.github.k7t3.tcv.prefs.AppPreferences; -import com.github.k7t3.tcv.view.core.JavaFXHelper; -import com.github.k7t3.tcv.app.theme.ThemeManager; -import com.github.k7t3.tcv.view.core.WindowBoundsListener; -import com.github.k7t3.tcv.view.main.MainView; -import de.saxsys.mvvmfx.FluentViewLoader; +import com.github.k7t3.tcv.view.core.WindowBounds; import javafx.application.Application; import javafx.application.Platform; -import javafx.scene.Scene; import javafx.stage.Stage; -import javafx.stage.WindowEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CompletionStage; +import java.util.function.Consumer; +import java.util.function.Function; public class Launcher extends Application { - - private Logger log; - + private final Logger log = LoggerFactory.getLogger(Launcher.class); private AppPreferences preferences; - + private AppHelper helper; private MainViewModel viewModel; + private ApplicationWindow window; + private final Runnable closeKeyManager; + private final Consumer startupError; + private final Runnable exit; + private final Function modelFactory; + private final WindowFactory windowFactory; + private ApplicationShutdown shutdown; + private LoggerInitializer.LoggingSession logging; + private CredentialCipherService credentialCipher; + private Throwable preparationFailure; + private volatile Throwable startupFailure; + private volatile Throwable startupException; + private final CompletableFuture initializationCompleted = new CompletableFuture<>(); + private final CompletableFuture startupCompleted = new CompletableFuture<>(); + private volatile boolean initializationStarted; + private volatile boolean initialized; + private WindowBounds savedBounds; + private boolean forcedShutdown; + private volatile boolean started; + private volatile Thread startingThread; + + @FunctionalInterface + interface WindowFactory { + ApplicationWindow create(Stage stage, MainViewModel model, AppHelper helper, AppPreferences preferences, WindowBounds savedBounds, + Runnable hidden, Consumer failed); + } - @Override - public void init() throws Exception { - super.init(); - - // 暗黙的な終了を無効化 - // アプリケーションは明示的に終了する。 - Platform.setImplicitExit(false); - - // ロガーの初期化 - LoggerInitializer.initialize(); + public Launcher() { this(null, null, () -> {}, + failure -> ExceptionHandler.handle(null, failure), Platform::exit); } - log = LoggerFactory.getLogger(Launcher.class); - log.info("logger initialized"); + Launcher(AppPreferences preferences, AppHelper helper, Runnable closeKeyManager, + Consumer startupError, Runnable exit) { + this(preferences, helper, closeKeyManager, startupError, exit, null, null); + } - preferences = AppPreferences.getInstance(); + Launcher(AppPreferences preferences, AppHelper helper, Runnable closeKeyManager, Consumer startupError, + Runnable exit, Function modelFactory, WindowFactory windowFactory) { + this.preferences = preferences; + this.helper = helper; + this.closeKeyManager = closeKeyManager; + this.startupError = startupError; + this.exit = exit; + this.modelFactory = modelFactory != null ? modelFactory : this::createModel; + this.windowFactory = windowFactory != null ? windowFactory : this::createWindow; } - @Override - public void start(Stage primaryStage) { + private MainViewModel createModel(AppHelper owner) { + return MainModelFactory.create(owner, this::reportOperationFailure); + } - log.info("start application"); + private void reportOperationFailure(Throwable failure) { + ExceptionHandler.handle(helper.getPrimaryStage(), failure); + } - var helper = AppHelper.getInstance(); - helper.setPrimaryStage(primaryStage); + private ApplicationWindow createWindow(Stage stage, MainViewModel model, AppHelper owner, AppPreferences settings, + WindowBounds bounds, Runnable hidden, Consumer failed) { + credentialCipher = KeyManagerFactory.create(); + var credentials = new PreferencesCredentialStorage(settings.getPreferences(), + credentialCipher::encrypt, credentialCipher::decrypt, + com.github.k7t3.tcv.app.core.OS.current().getApplicationDirectory().resolve("credentials.lock"), + settings.settingsLockFile().orElse(null)); + return new MainWindow(stage, model, owner, settings, bounds, hidden, failed, credentials); + } + @Override + public void init() { + synchronized (this) { + if (initializationStarted || shutdown != null) throw new IllegalStateException("application initialization already ended"); + initializationStarted = true; + } try { - // ユーザーファイルを接続 - var generalPrefs = preferences.getGeneralPreferences(); - var userDataFile = new UserDataFile(generalPrefs.getUserDataFilePath()); - var current = generalPrefs.getDatabaseVersion(); - var version = userDataFile.connectDatabase(current); - generalPrefs.setDatabaseVersion(version); - helper.setUserDataFile(userDataFile); - } catch (IOException e) { - ExceptionHandler.handle(e); - Platform.exit(); + if (Platform.isFxApplicationThread()) throw new IllegalStateException("initialize storage outside the FX thread"); + Platform.setImplicitExit(false); + logging = LoggerInitializer.initialize(); + if (preferences == null) preferences = new AppPreferences(); + if (helper == null) helper = new AppHelper(this::reportOperationFailure); + preferences.load(); + var general = preferences.getGeneralPreferences(); + var file = new UserDataFile(general.getUserDataFilePath()); + helper.setUserDataFile(file); + var version = file.connectDatabase(general.getDatabaseVersion()); + helper.recoverSettings(preferences); + preferences.load(); + general.setDatabaseVersion(version); + // 画面を構築する前に、背景起動で受け付けた版更新の実保存・失敗を確認する。 + if (preferences.settingsLockFile().isPresent()) preferences.save(); + savedBounds = helper.getWindowBoundsService().getBounds("main"); + } catch (IOException | RuntimeException | Error failure) { + recordStartupFailure(failure); + } finally { + // stop が待つ間に同じ monitor を要求しない。 + initialized = true; + initializationCompleted.complete(null); } + } - // ViewModel - viewModel = new MainViewModel(helper.getChannelGroupRepository()); - - // チャンネルリストに関する設定のバインド - var channelList = viewModel.getChannelListViewModel(); - channelList.bindGeneralPreferences(preferences.getGeneralPreferences()); - - // チャットに関する設定のバインド - var chatContainer = viewModel.getChatContainer(); - chatContainer.bindChatPreferences(preferences.getChatPreferences()); - - // Viewのロード - var tuple = FluentViewLoader.fxmlView(MainView.class) - .viewModel(viewModel) - .resourceBundle(Resources.getResourceBundle()) - .load(); - var view = tuple.getView(); - var codeBehind = tuple.getCodeBehind(); - - // メインシーンの作成 - var scene = new Scene(view); - - // テーマを適用 - var themePrefs = preferences.getGeneralPreferences(); - var tm = ThemeManager.getInstance(); - tm.setScene(scene); - tm.setTheme(themePrefs.getTheme()); - tm.setThemeType(themePrefs.getThemeType()); - - // 画面が表示されたら認証画面を表示する(おそらくModalPaneの仕様的に - // シーングラフが表示されてからじゃないと動作しないため) - JavaFXHelper.shownOnce(primaryStage, e -> codeBehind.startMainView()); - - // ウインドウを閉じるときのイベント - primaryStage.setOnHidden(this::onHidden); - - // ウインドウの情報 - primaryStage.titleProperty().bind(viewModel.titleProperty()); - primaryStage.getIcons().setAll(Resources.getIcons()); - - // ウインドウの境界を追跡 - var boundsListener = new WindowBoundsListener(); - boundsListener.install(primaryStage); + @Override + public void start(Stage stage) { + if (!initialized) throw new IllegalStateException("application is not initialized"); + if (started || shutdown != null) throw new IllegalStateException("application startup already ended"); + started = true; + startingThread = Thread.currentThread(); + try { + if (startupFailure != null) { requestShutdown(); return; } + helper.setPrimaryStage(stage); + var general = preferences.getGeneralPreferences(); + var createdModel = modelFactory.apply(helper); + if (shutdown != null) { createdModel.close(); return; } + viewModel = createdModel; + viewModel.getChannelListViewModel().bindGeneralPreferences(general); + if (shutdown != null) return; + viewModel.getChatContainer().bindChatPreferences(preferences.getChatPreferences()); + if (shutdown != null) return; + // show より先に所有し、FXML やテーマ適用の途中失敗も回収する。 + var createdWindow = windowFactory.create(stage, viewModel, helper, preferences, savedBounds, this::requestShutdown, this::failStartup); + if (shutdown != null) { createdWindow.close(); return; } + window = createdWindow; + window.show(); + } catch (RuntimeException | Error failure) { failStartup(failure); } + finally { + startingThread = null; + startupCompleted.complete(null); + } + } - // ウインドウ境界を復元 - var windowBoundsService = helper.getWindowBoundsService(); - var windowBounds = windowBoundsService.getBounds("main"); - log.info("fetch window bounds {}", windowBounds); - windowBounds.apply(primaryStage); + private void failStartup(Throwable failure) { + recordStartupFailure(failure); + requestShutdown(); + } - // ウインドウを閉じるときに境界を記録 - primaryStage.addEventHandler(WindowEvent.WINDOW_HIDING, e -> { - var t = windowBoundsService.saveBoundsAsync("main", boundsListener.getCurrent()); - t.waitForDone(); - }); + private void recordStartupFailure(Throwable failure) { + if (startupFailure == null) { + startupFailure = failure; + startupException = failure instanceof IOException io ? new UncheckedIOException(io) : failure; + } else if (startupException != failure) startupException.addSuppressed(failure); + } - primaryStage.setScene(scene); - primaryStage.show(); + /** FX スレッドからの終了要求。部分起動の終了も同じ完了を共有する。 */ + public synchronized CompletionStage requestShutdown() { return shutdown(false).request(); } + + private ApplicationShutdown shutdown(boolean forced) { + if (shutdown == null) { + forcedShutdown = forced; + shutdown = new ApplicationShutdown( + command -> Thread.ofVirtual().name("TCV-Shutdown").start(command), + forced ? Runnable::run : Platform::runLater, + this::prepareShutdown, this::releaseResources, forced ? () -> {} : () -> CloseActions.runAll( + () -> { if (startupFailure != null) startupError.accept(startupFailure); }, exit)); + shutdown.request().whenComplete((ignored, failure) -> { + if (failure != null) log.error("application shutdown failed", failure); + }); + } + return shutdown; } @Override public void stop() { - log.info("application closing ..."); - - // 設定のSave - var prefs = AppPreferences.getInstance(); - prefs.save(); + final ApplicationShutdown current; + synchronized (this) { current = shutdown(true); } + // 構築の中から再入したstopは、同じスレッドで戻る生成処理を待たない。 + if (startingThread == Thread.currentThread()) return; + try { current.resourcesReleased().toCompletableFuture().join(); } + catch (CompletionException failure) { + if (forcedShutdown) rethrow(failure.getCause()); + } + } - // キーストアの終了 - KeyManagerFactory.getInstance().close(); + private void prepareShutdown() { + var ownedWindow = window; + var ownedModel = viewModel; + window = null; + viewModel = null; + var failure = startupException; + try { + CloseActions.runAll(() -> { if (failure != null) rethrow(failure); }, + () -> { if (ownedWindow != null) ownedWindow.close(); }, + () -> { if (ownedModel != null) ownedModel.close(); }, + () -> { if (helper != null && (!initializationStarted || initialized)) helper.prepareShutdown(); }); + } catch (RuntimeException | Error error) { + preparationFailure = error; + throw error; + } + } - // ViewModelのクローズ - viewModel.close(); + private void releaseResources() { + try { + CloseActions.runAll(() -> { + if (initializationStarted) initializationCompleted.join(); + if (started) startupCompleted.join(); + }, () -> { + if (preparationFailure != null) rethrow(preparationFailure); + }, () -> { + if (startupException != null) rethrow(startupException); + }, () -> { if (helper != null) helper.close(); }, + () -> { if (preferences != null) preferences.close(); }, this::closeCredentialCipher, closeKeyManager); + } catch (RuntimeException | Error failure) { + // 起動・解放の診断をログへ書いてから、最後にログ自身を解放する。 + CloseActions.runAll(() -> rethrow(failure), + () -> log.error("application resource release failed", failure), this::closeLogging); + } + closeLogging(); + } - // アプリケーションの終了 - var helper = AppHelper.getInstance(); - helper.close(); + private void closeLogging() { + var owned = logging; + logging = null; + if (owned != null) owned.close(); } - private void onHidden(WindowEvent e) { - // JavaFX Applicationの終了 - Platform.exit(); + private void closeCredentialCipher() { + var owned = credentialCipher; + credentialCipher = null; + if (owned != null) owned.close(); } + private static void rethrow(Throwable failure) { + if (failure instanceof RuntimeException error) throw error; + if (failure instanceof Error error) throw error; + if (failure instanceof IOException error) throw new UncheckedIOException(error); + throw new RuntimeException(failure); + } } diff --git a/src/main/java/com/github/k7t3/tcv/view/MainModelFactory.java b/src/main/java/com/github/k7t3/tcv/view/MainModelFactory.java new file mode 100644 index 0000000..ac4f8a5 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/view/MainModelFactory.java @@ -0,0 +1,95 @@ +package com.github.k7t3.tcv.view; + +import com.github.k7t3.tcv.app.auth.AuthenticatorViewModel; +import com.github.k7t3.tcv.app.channel.ChannelViewModelRepository; +import com.github.k7t3.tcv.app.channel.TwitchChannelListViewModel; +import com.github.k7t3.tcv.app.chat.ChatResourcesLoader; +import com.github.k7t3.tcv.app.chat.ChatRoomContainerViewModel; +import com.github.k7t3.tcv.app.clip.PostedClipRepository; +import com.github.k7t3.tcv.app.core.AppHelper; +import com.github.k7t3.tcv.app.core.OS; +import com.github.k7t3.tcv.app.group.ChannelGroupRepository; +import com.github.k7t3.tcv.app.image.ImageLoader; +import com.github.k7t3.tcv.app.main.MainViewModel; +import com.github.k7t3.tcv.app.model.AbstractViewModel; +import com.github.k7t3.tcv.app.service.BrowserActions; +import com.github.k7t3.tcv.app.service.LiveStateNotificator; +import com.github.k7t3.tcv.domain.auth.CredentialStore; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.Function; + +/** 起動単位の共有サービスからMainのモデルを構成し、途中失敗の資源も回収する。 */ +public final class MainModelFactory { + private MainModelFactory() {} + + /** 標準の共有サービスと認証処理でMainを構築する。返したモデルが子を所有する。 */ + public static MainViewModel create(AppHelper helper, Consumer failures) { + return create(helper, helper.getChannelGroupRepository(), helper.getImageLoader(), failures); + } + + /** 借用するグループ・画像を明示して、標準の認証処理でMainを構築する。 */ + public static MainViewModel create(AppHelper helper, ChannelGroupRepository groups, ImageLoader images, + Consumer failures) { + return create(helper, groups, images, failures, store -> new AuthenticatorViewModel(store, + helper.getClientSessions()::adopt, helper.getExecutor(), failures)); + } + + /** 認証の生成先を指定する。生成関数は未開始のモデルを返し、開始は画面の所有後に行う。 */ + public static MainViewModel create(AppHelper helper, Consumer failures, + Function authentication) { + return create(helper, helper.getChannelGroupRepository(), helper.getImageLoader(), failures, authentication); + } + + private static MainViewModel create(AppHelper helper, ChannelGroupRepository groups, ImageLoader images, + Consumer failures, Function authentication) { + Objects.requireNonNull(failures); + Objects.requireNonNull(authentication); + var owned = new ArrayList(); + try { + var executor = helper.getExecutor(); + var source = helper.getSubscribers(); + var sessions = helper.getClientSessions(); + var channels = own(owned, new ChannelViewModelRepository(groups, images, executor, helper::awaitOnShutdown, failures)); + var chats = own(owned, createChat(helper, images)); + var list = own(owned, new TwitchChannelListViewModel(new BrowserActions(executor, helper::awaitOnShutdown, failures))); + var clips = own(owned, new PostedClipRepository(images, executor, helper::awaitOnShutdown, failures)); + var notifications = own(owned, new LiveStateNotificator(channels, failures)); + return new MainViewModel(sessions, source, channels, chats, list, clips, notifications, store -> { + var model = authentication.apply(store); + try { + helper.awaitOnShutdown(model.resourcesReleased()); + model.setEventSubscribers(source); + model.delegateLifecycleToOwner(); + return model; + } catch (RuntimeException | Error failure) { + try { model.close(); } + catch (RuntimeException | Error cleanup) { if (cleanup != failure) failure.addSuppressed(cleanup); } + throw failure; + } + }, failures); + } catch (RuntimeException | Error failure) { + try { CloseActions.runAll(owned.reversed().stream().map(model -> (Runnable) model::close).toArray(Runnable[]::new)); } + catch (RuntimeException | Error cleanup) { if (cleanup != failure) failure.addSuppressed(cleanup); } + throw failure; + } + } + + /** 読込開始時のFXスレッドで現在のセッションとフィルターを固定する。 */ + public static ChatRoomContainerViewModel createChat(AppHelper helper, ImageLoader images) { + return new ChatRoomContainerViewModel(() -> { + var filters = helper.getChatFilters(); + var loader = new ChatResourcesLoader(OS.current().getApplicationDirectory(), + Objects.requireNonNull(helper.getTwitch()), filters::readSnapshot, images); + return new ChatRoomContainerViewModel.LoadRequest(filters, loader::load); + }, helper.getExecutor(), helper::awaitOnShutdown); + } + + private static T own(List owner, T model) { + owner.add(model); + return model; + } +} diff --git a/src/main/java/com/github/k7t3/tcv/view/MainViewFactory.java b/src/main/java/com/github/k7t3/tcv/view/MainViewFactory.java new file mode 100644 index 0000000..108d5f6 --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/view/MainViewFactory.java @@ -0,0 +1,107 @@ +package com.github.k7t3.tcv.view; + +import atlantafx.base.controls.ModalPane; +import com.github.k7t3.tcv.app.channel.ChannelViewModelRepository; +import com.github.k7t3.tcv.app.channel.SearchChannelViewModel; +import com.github.k7t3.tcv.app.core.AppHelper; +import com.github.k7t3.tcv.app.core.ExceptionHandler; +import com.github.k7t3.tcv.app.help.AboutViewModel; +import com.github.k7t3.tcv.app.keyboard.KeyBinding; +import com.github.k7t3.tcv.app.main.MainViewModel; +import com.github.k7t3.tcv.app.prefs.*; +import com.github.k7t3.tcv.app.service.BrowserActions; +import com.github.k7t3.tcv.app.theme.ThemeManager; +import com.github.k7t3.tcv.domain.auth.CredentialStore; +import com.github.k7t3.tcv.prefs.AppPreferences; +import com.github.k7t3.tcv.view.channel.TwitchChannelListView; +import com.github.k7t3.tcv.view.chat.ChatContainerView; +import com.github.k7t3.tcv.view.command.*; +import com.github.k7t3.tcv.view.help.AboutView; +import com.github.k7t3.tcv.view.main.MainView; +import com.github.k7t3.tcv.view.prefs.PreferencesView; +import javafx.beans.value.ObservableValue; +import javafx.scene.input.KeyCombination; +import javafx.stage.Stage; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +/** 起動側でViewとコマンドの依存を接続する。返した部品の所有は画面へ渡す。 */ +public final class MainViewFactory { + private MainViewFactory() {} + + /** 共有サービスの取得と子の生成は、以前と同じFX上の利用時点まで遅延させる。 */ + public static MainView create(Stage owner, MainViewModel model, AppHelper helper, AppPreferences preferences, + ThemeManager theme, CredentialStore credentials) { + return new MainView(preferences, credentials, new MainView.Components( + helper::getKeyBindingCombinations, + pane -> new OpenChannelGroupCommand(pane, helper.getChannelGroupRepository(), preferences, model.authorizedProperty()), + pane -> new OpenClipCommand(pane, model.getClipRepository(), model.authorizedProperty().and(model.clipCountProperty().greaterThan(0))), + () -> preferences(helper, preferences, stage -> new PreferencesView(preferencesPages(helper, preferences, theme, stage)), Stage::new), + pane -> search(pane, model.getChannelRepository(), helper, model.authorizedProperty()), + () -> about(helper, AboutView::new, Stage::new), + () -> new BrowserActions(helper.getExecutor(), helper::awaitOnShutdown, failure -> ExceptionHandler.handle(owner, failure)), + () -> new TwitchChannelListView(helper::getChannelGroupRepository, preferences, () -> owner), + () -> new ChatContainerView(helper.getChannelGroupRepository(), preferences.getChatPreferences(), helper::getWindowBoundsService))); + } + + /** Aboutの子Stageを通知先にしたモデルを、そのStageの生成後に構築する。 */ + public static OpenAboutCommand about(AppHelper helper, Supplier views, Supplier stages) { + return new OpenAboutCommand(helper::getPrimaryStage, stage -> new AboutViewModel(new BrowserActions( + helper.getExecutor(), helper::awaitOnShutdown, failure -> ExceptionHandler.handle(stage, failure))), views, stages); + } + + /** 検索モデルの生成と現在セッションへの接続を、モーダルの所有処理へ渡す。 */ + public static OpenSearchChannelCommand search(ModalPane pane, ChannelViewModelRepository repository, AppHelper helper, + ObservableValue condition) { + return search(pane, helper, condition, () -> new SearchChannelViewModel(repository, helper.getImageLoader(), + helper.getExecutor(), failure -> ExceptionHandler.handle(helper.getPrimaryStage(), failure))); + } + + /** 検索のセッション接続は、コマンドがモデルとViewを所有した後に行う。 */ + public static OpenSearchChannelCommand search(ModalPane pane, AppHelper helper, ObservableValue condition, + Supplier models) { + return new OpenSearchChannelCommand(pane, condition, models, model -> { + model.setEventSubscribers(helper.getSubscribers()); + model.twitchProperty().bind(helper.twitchProperty()); + }); + } + + /** 設定Stageを先に所有してから、同じStageへ通知するモデルとViewを構成する。 */ + public static OpenPreferencesCommand preferences(AppHelper helper, AppPreferences preferences, + Function views, Supplier stages) { + return new OpenPreferencesCommand(helper::getPrimaryStage, stage -> new PreferencesViewModel( + new SettingsSaveService(preferences, helper.getChatFilterStore()), helper.getExecutor(), + helper::awaitOnShutdown, + failure -> ExceptionHandler.handle(stage, failure)), views, stages); + } + + /** ページはFXML初期化中に順に生成し、設定Viewがそれぞれを所有する。 */ + public static PreferencesView.Pages preferencesPages(AppHelper helper, AppPreferences preferences, ThemeManager theme, Stage owner) { + return new PreferencesView.Pages( + () -> new GeneralPreferencesViewModel(preferences.getGeneralPreferences(), theme), + () -> new ChatPreferencesViewModel(preferences.getChatPreferences(), helper.getExecutor(), + failure -> ExceptionHandler.handle(owner, failure)), + () -> new KeywordFilterViewModel(helper.getChatFilters()), + () -> new UserFilterViewModel(helper.getChatFilters()), + () -> new KeyBindingPreferencesViewModel(helper.getKeyBindingCombinations()), + () -> prepareCommit(helper, preferences, theme)); + } + + private static Consumer prepareCommit(AppHelper helper, AppPreferences preferences, ThemeManager theme) { + // 保存受付時の対象を固定し、画面終了後の成功でも共有サービスを再取得しない。 + var applyFilters = helper.getChatFilters().captureCommitHandler(); + var keys = helper.getKeyBindingCombinations(); + return saved -> { + var current = preferences.applyCommittedValues(saved.draft().values()); + for (var binding : KeyBinding.values()) { + var value = current.get(binding.getId()); + if (value != null) keys.updateCombination(binding, value.map(KeyCombination::keyCombination) + .orElseGet(binding::getDefaultCombination)); + } + theme.setTheme(preferences.getGeneralPreferences().getTheme()); + theme.setThemeType(preferences.getGeneralPreferences().getThemeType()); + applyFilters.accept(saved.filters()); + }; + } +} diff --git a/src/main/java/com/github/k7t3/tcv/view/MainWindow.java b/src/main/java/com/github/k7t3/tcv/view/MainWindow.java new file mode 100644 index 0000000..a40414a --- /dev/null +++ b/src/main/java/com/github/k7t3/tcv/view/MainWindow.java @@ -0,0 +1,120 @@ +package com.github.k7t3.tcv.view; + +import com.github.k7t3.tcv.domain.auth.CredentialStore; + +import com.github.k7t3.tcv.app.core.AppHelper; +import com.github.k7t3.tcv.app.core.Resources; +import com.github.k7t3.tcv.app.main.MainViewModel; +import com.github.k7t3.tcv.app.service.WindowBoundsService; +import com.github.k7t3.tcv.app.theme.ThemeManager; +import com.github.k7t3.tcv.lifecycle.CloseActions; +import com.github.k7t3.tcv.prefs.AppPreferences; +import com.github.k7t3.tcv.view.core.WindowBounds; +import com.github.k7t3.tcv.view.core.WindowBoundsListener; +import com.github.k7t3.tcv.view.main.MainView; +import de.saxsys.mvvmfx.FluentViewLoader; +import javafx.event.EventHandler; +import javafx.scene.Scene; +import javafx.stage.Stage; +import javafx.stage.WindowEvent; + +import java.util.function.Consumer; + +/** FX 側の画面、テーマ、ウインドウ購読を、ロードの開始前から所有する。 */ +final class MainWindow implements ApplicationWindow { + private final Stage stage; + private final MainViewModel model; + private final AppHelper helper; + private final AppPreferences preferences; + private final WindowBounds savedBounds; + private final MainView controller; + private final ThemeManager theme; + private final Runnable hidden; + private final Consumer failed; + private final WindowBoundsListener bounds = new WindowBoundsListener(); + private WindowBoundsService boundsService; + private EventHandler onShown; + private EventHandler onHiding; + private EventHandler onHidden; + private boolean shown; + private boolean closed; + + MainWindow(Stage stage, MainViewModel model, AppHelper helper, AppPreferences preferences, WindowBounds savedBounds, + Runnable hidden, Consumer failed, CredentialStore credentials) { + this(stage, model, helper, preferences, savedBounds, hidden, failed, credentials, new ThemeManager()); + } + + private MainWindow(Stage stage, MainViewModel model, AppHelper helper, AppPreferences preferences, WindowBounds savedBounds, + Runnable hidden, Consumer failed, CredentialStore credentials, ThemeManager theme) { + this(stage, model, helper, preferences, savedBounds, hidden, failed, + MainViewFactory.create(stage, model, helper, preferences, theme, credentials), theme); + } + + MainWindow(Stage stage, MainViewModel model, AppHelper helper, AppPreferences preferences, WindowBounds savedBounds, Runnable hidden, + Consumer failed, MainView controller, ThemeManager theme) { + this.stage = stage; + this.model = model; + this.helper = helper; + this.preferences = preferences; + this.savedBounds = savedBounds; + this.hidden = hidden; + this.failed = failed; + this.controller = controller; + this.theme = theme; + } + + @Override public void show() { + if (closed || shown) throw new IllegalStateException("window is already opened or closed"); + var tuple = FluentViewLoader.fxmlView(MainView.class).codeBehind(controller).viewModel(model) + .resourceBundle(Resources.getResourceBundle()).load(); + if (closed) return; + var scene = new Scene(tuple.getView()); + theme.setScene(scene); + theme.setTheme(preferences.getGeneralPreferences().getTheme()); + if (closed) return; + theme.setThemeType(preferences.getGeneralPreferences().getThemeType()); + if (closed) return; + stage.titleProperty().bind(model.titleProperty()); + if (closed) return; + stage.getIcons().setAll(Resources.getIcons()); + if (closed) return; + bounds.install(stage); + var service = helper.getWindowBoundsService(); + boundsService = service; + savedBounds.apply(stage, () -> !closed); + if (closed) return; + onShown = event -> { + stage.removeEventHandler(WindowEvent.WINDOW_SHOWN, onShown); + if (closed) return; + try { controller.startMainView(); } + catch (RuntimeException | Error failure) { failed.accept(failure); } + }; + onHiding = event -> { if (shown && !closed) service.saveBoundsAsync("main", bounds.getCurrent()); }; + onHidden = event -> hidden.run(); + stage.addEventHandler(WindowEvent.WINDOW_SHOWN, onShown); + stage.addEventHandler(WindowEvent.WINDOW_HIDING, onHiding); + stage.addEventHandler(WindowEvent.WINDOW_HIDDEN, onHidden); + stage.setScene(scene); + if (closed) return; + stage.show(); + if (!closed) shown = true; + } + + @Override public void close() { + if (closed) return; + closed = true; + CloseActions.runAll(() -> { + // onHidden より先に終了要求が来た場合も、最後の境界を排出対象へ入れる。 + if (shown && stage.isShowing()) boundsService.saveBoundsAsync("main", bounds.getCurrent()); + }, () -> { + if (onShown != null) stage.removeEventHandler(WindowEvent.WINDOW_SHOWN, onShown); + if (onHiding != null) stage.removeEventHandler(WindowEvent.WINDOW_HIDING, onHiding); + if (onHidden != null) stage.removeEventHandler(WindowEvent.WINDOW_HIDDEN, onHidden); + }, bounds::uninstall, controller::close, theme::close, () -> { + stage.titleProperty().unbind(); + stage.hide(); + stage.setScene(null); + if (helper.getPrimaryStage() == stage) helper.setPrimaryStage(null); + }); + } +} diff --git a/src/main/java/com/github/k7t3/tcv/view/auth/AuthenticatorView.java b/src/main/java/com/github/k7t3/tcv/view/auth/AuthenticatorView.java index 689c541..84092e7 100644 --- a/src/main/java/com/github/k7t3/tcv/view/auth/AuthenticatorView.java +++ b/src/main/java/com/github/k7t3/tcv/view/auth/AuthenticatorView.java @@ -19,7 +19,7 @@ import atlantafx.base.controls.CustomTextField; import atlantafx.base.layout.InputGroup; import com.github.k7t3.tcv.app.auth.AuthenticatorViewModel; -import com.github.k7t3.tcv.app.event.LoginEvent; +import com.github.k7t3.tcv.view.core.ViewResources; import de.saxsys.mvvmfx.FxmlView; import de.saxsys.mvvmfx.InjectViewModel; import javafx.application.Platform; @@ -35,7 +35,21 @@ import java.net.URL; import java.util.ResourceBundle; -public class AuthenticatorView implements FxmlView, Initializable { +public class AuthenticatorView implements FxmlView, Initializable, AutoCloseable { + private final ViewResources owned = new ViewResources(); + private final Runnable endModel; + + public AuthenticatorView() { this(null); } + + /** 外側の所有者がある場合は、その一回限りの解放を取り外し時にも要求する。 */ + public AuthenticatorView(Runnable endModel) { this.endModel = endModel; } + + private void releaseModel() { + if (endModel != null) endModel.run(); + else if (viewModel != null) viewModel.close(); + } + + @Override public void close() { owned.close(); } @FXML private Pane root; @@ -64,32 +78,69 @@ public class AuthenticatorView implements FxmlView, Init @FXML private ProgressBar progressBar; + @FXML + private Label errorLabel; + + @FXML + private Button retryButton; + @InjectViewModel private AuthenticatorViewModel viewModel; @Override public void initialize(URL url, ResourceBundle resourceBundle) { + if (owned.isClosed()) { releaseModel(); return; } + owned.add(this::releaseModel); + owned.add(this::detachControls); + javafx.beans.value.ChangeListener parentChanged = (observable, oldParent, newParent) -> { + if (oldParent != null && newParent == null) close(); + }; + root.parentProperty().addListener(parentChanged); + owned.add(() -> root.parentProperty().removeListener(parentChanged)); authUriLink.disableProperty().bind(viewModel.initializedProperty().not()); authUriLink.textProperty().bind(viewModel.authUriProperty()); - authUriLink.setOnAction(e -> viewModel.openAuthUri()); + authUriLink.setOnAction(e -> { if (!owned.isClosed()) viewModel.openAuthUri(); }); userCodeGroup.visibleProperty().bind(viewModel.initializedProperty()); userCodeField.textProperty().bind(viewModel.userCodeProperty()); - userCodeField.focusedProperty().addListener((ob, o, n) -> { - if (n) { - Platform.runLater(() -> userCodeField.selectAll()); + javafx.beans.value.ChangeListener focused = (ob, o, n) -> { + if (n && !owned.isClosed()) { + Platform.runLater(() -> { if (!owned.isClosed() && userCodeField.isFocused()) userCodeField.selectAll(); }); } - }); + }; + userCodeField.focusedProperty().addListener(focused); + owned.add(() -> userCodeField.focusedProperty().removeListener(focused)); openLinkButton.visibleProperty().bind(viewModel.initializedProperty()); - openLinkButton.setOnAction(e -> viewModel.openAuthUri()); + openLinkButton.setOnAction(e -> { if (!owned.isClosed()) viewModel.openAuthUri(); }); clipAuthUriButton.visibleProperty().bind(viewModel.initializedProperty()); - clipAuthUriButton.setOnAction(e -> viewModel.clipAuthUri()); + clipAuthUriButton.setOnAction(e -> { if (!owned.isClosed()) viewModel.clipAuthUri(); }); qrcodeImageView.imageProperty().bind(viewModel.qrcodeProperty()); - viewModel.subscribe(LoginEvent.class, e -> progressBar.setProgress(1d)); + progressBar.progressProperty().bind(viewModel.busyProperty().map(busy -> busy ? -1d : 0d)); + errorLabel.textProperty().bind(viewModel.errorProperty()); + errorLabel.visibleProperty().bind(viewModel.errorProperty().isNotEmpty()); + errorLabel.managedProperty().bind(errorLabel.visibleProperty()); + retryButton.visibleProperty().bind(errorLabel.visibleProperty()); + retryButton.managedProperty().bind(retryButton.visibleProperty()); + retryButton.setOnAction(event -> { if (!owned.isClosed()) viewModel.beginAuthentication(); }); } + private void detachControls() { + if (authUriLink != null) { + authUriLink.disableProperty().unbind(); authUriLink.textProperty().unbind(); authUriLink.setOnAction(null); + } + if (userCodeGroup != null) userCodeGroup.visibleProperty().unbind(); + if (userCodeField != null) userCodeField.textProperty().unbind(); + for (var button : new Button[] {openLinkButton, clipAuthUriButton, retryButton}) { + if (button != null) { button.visibleProperty().unbind(); button.managedProperty().unbind(); button.setOnAction(null); } + } + if (qrcodeImageView != null) { qrcodeImageView.imageProperty().unbind(); qrcodeImageView.setImage(null); } + if (progressBar != null) { progressBar.progressProperty().unbind(); progressBar.setProgress(0); } + if (errorLabel != null) { + errorLabel.textProperty().unbind(); errorLabel.visibleProperty().unbind(); errorLabel.managedProperty().unbind(); + } + } } diff --git a/src/main/java/com/github/k7t3/tcv/view/channel/FoundChannelListCell.java b/src/main/java/com/github/k7t3/tcv/view/channel/FoundChannelListCell.java index 0ff0c87..893ac88 100644 --- a/src/main/java/com/github/k7t3/tcv/view/channel/FoundChannelListCell.java +++ b/src/main/java/com/github/k7t3/tcv/view/channel/FoundChannelListCell.java @@ -20,6 +20,10 @@ import atlantafx.base.theme.Styles; import com.github.k7t3.tcv.app.channel.FoundChannelViewModel; import com.github.k7t3.tcv.app.core.Resources; +import com.github.k7t3.tcv.app.service.FXTask; +import javafx.concurrent.Worker; +import javafx.concurrent.WorkerStateEvent; +import javafx.event.EventHandler; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.geometry.Insets; @@ -35,7 +39,13 @@ import org.kordamp.ikonli.fontawesome5.FontAwesomeSolid; import org.kordamp.ikonli.javafx.FontIcon; -public class FoundChannelListCell extends ListCell { +public class FoundChannelListCell extends ListCell implements AutoCloseable { + private final java.util.function.Supplier alerts; + private boolean closed; + private BrowserWatch browserWatch; + private Alert activeAlert; + private final java.util.List