From 328c70728ce05710b86c76a1175eadff6491ddae Mon Sep 17 00:00:00 2001 From: k7t3 Date: Tue, 22 Sep 2026 17:17:43 +0900 Subject: [PATCH 01/11] =?UTF-8?q?chore(gitignore):=20AI=20=E3=83=84?= =?UTF-8?q?=E3=83=BC=E3=83=AB=E9=96=A2=E9=80=A3=E3=81=AE=E3=83=95=E3=82=A1?= =?UTF-8?q?=E3=82=A4=E3=83=AB=E3=82=92=E7=84=A1=E8=A6=96=E5=AF=BE=E8=B1=A1?= =?UTF-8?q?=E3=81=AB=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit .agents / .opencode / AGENTS.md はローカル開発用の AI エージェント設定であり、リポジトリで管理する必要が ないため無視対象に追加。 --- .gitignore | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index d3ed74e..4b915c5 100644 --- a/.gitignore +++ b/.gitignore @@ -38,4 +38,9 @@ bin/ ### Mac OS ### .DS_Store -userinfo \ No newline at end of file +userinfo + +# AI +.agents +.opencode +AGENTS.md \ No newline at end of file From 511e55f66cae57479bb75597dcdf6d8f08b08295 Mon Sep 17 00:00:00 2001 From: k7t3 Date: Wed, 28 Oct 2026 21:20:52 +0900 Subject: [PATCH 02/11] =?UTF-8?q?refactor(core):=20=E3=82=A2=E3=83=97?= =?UTF-8?q?=E3=83=AA=E5=85=A8=E4=BD=93=E3=81=AE=E8=B3=87=E6=BA=90=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E3=81=A8=E6=B0=B8=E7=B6=9A=E5=8C=96=E3=82=92=E6=94=B9?= =?UTF-8?q?=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit セッション、非同期処理、画像と画面の所有・終了を整理し、 SQLite と設定の保存・復旧を強化する。 認証と API、ビルド環境、テストおよび技術的負債の記録も更新する。 --- .gitattributes | 2 + .github/workflows/deploy.yaml | 63 +- .github/workflows/test.yaml | 15 +- .java-version | 1 + README.md | 51 +- build.gradle | 272 +++--- buildSrc/build.gradle | 21 + buildSrc/settings.gradle | 7 + .../k7t3/tcv/build/JdkModulesTask.groovy | 48 + .../github/k7t3/tcv/build/JdkToolTask.groovy | 32 + .../k7t3/tcv/build/NativePackageTask.groovy | 64 ++ .../k7t3/tcv/build/LinuxGlibcRequirement.java | 135 +++ .../github/k7t3/tcv/build/PackageOutput.java | 111 +++ .../github/k7t3/tcv/build/PackagePlan.java | 115 +++ .../tcv/build/LinuxGlibcRequirementTest.java | 170 ++++ .../k7t3/tcv/build/PackageOutputTest.java | 125 +++ .../k7t3/tcv/build/PackagePlanTest.java | 153 +++ docs/external-libraries.md | 91 +- docs/licenses/jai-imageio.txt | 92 ++ gradle/libs.versions.toml | 49 + gradle/wrapper/gradle-wrapper.jar | Bin 60756 -> 48749 bytes gradle/wrapper/gradle-wrapper.properties | 8 +- gradlew | 54 +- gradlew.bat | 201 ++-- settings.gradle | 1 - .../tcv/app/auth/AuthenticatorViewModel.java | 341 +++++-- .../auth/PreferencesCredentialStorage.java | 321 +++--- .../app/channel/ChannelChatConnection.java | 208 ++++ .../channel/ChannelViewModelRepository.java | 300 ++++-- .../app/channel/FoundChannelViewModel.java | 140 ++- .../app/channel/SearchChannelViewModel.java | 149 ++- .../channel/TwitchChannelListViewModel.java | 60 +- .../app/channel/TwitchChannelViewModel.java | 132 ++- .../tcv/app/chat/ChannelChatBadgeStore.java | 7 +- .../k7t3/tcv/app/chat/ChatDataViewModel.java | 7 - .../k7t3/tcv/app/chat/ChatEmoteStore.java | 7 +- .../k7t3/tcv/app/chat/ChatResources.java | 46 + .../tcv/app/chat/ChatResourcesLoader.java | 69 ++ .../app/chat/ChatRoomContainerViewModel.java | 381 +++++--- .../k7t3/tcv/app/chat/ChatRoomViewModel.java | 19 +- .../tcv/app/chat/GlobalChatBadgeStore.java | 7 +- .../tcv/app/chat/MergedChatRoomViewModel.java | 110 +-- .../tcv/app/chat/SingleChatRoomViewModel.java | 22 +- .../k7t3/tcv/app/chat/filter/ChatFilters.java | 237 ++++- .../app/chat/filter/KeywordFilterEntry.java | 7 +- .../k7t3/tcv/app/clip/ClipThumbnailStore.java | 7 +- .../k7t3/tcv/app/clip/PostedClipItem.java | 35 +- .../tcv/app/clip/PostedClipRepository.java | 276 +++++- .../github/k7t3/tcv/app/core/AppHelper.java | 317 ++++-- .../k7t3/tcv/app/core/ClientSession.java | 93 ++ .../k7t3/tcv/app/core/ClientSessions.java | 251 +++++ .../k7t3/tcv/app/core/DesktopUtils.java | 19 - .../k7t3/tcv/app/core/ExceptionHandler.java | 37 +- .../k7t3/tcv/app/core/LoggerInitializer.java | 150 ++- .../github/k7t3/tcv/app/core/Resources.java | 10 +- .../k7t3/tcv/app/emoji/ChatEmojiStore.java | 10 +- .../com/github/k7t3/tcv/app/emoji/Emoji.java | 328 +++++-- .../k7t3/tcv/app/event/ChatOpeningEvent.java | 3 +- .../app/event/SessionInvalidatedEvent.java | 6 + .../k7t3/tcv/app/group/ChannelGroup.java | 6 +- .../app/group/ChannelGroupListViewModel.java | 71 +- .../k7t3/tcv/app/group/ChannelGroupOrder.java | 40 + .../tcv/app/group/ChannelGroupRepository.java | 342 +++++-- .../k7t3/tcv/app/help/AboutViewModel.java | 23 +- .../k7t3/tcv/app/image/ImageDownloader.java | 132 +++ .../k7t3/tcv/app/image/ImageLoader.java | 81 ++ .../github/k7t3/tcv/app/image/LazyImage.java | 95 +- .../k7t3/tcv/app/main/MainViewModel.java | 175 +++- .../k7t3/tcv/app/model/AbstractViewModel.java | 235 ++++- .../app/prefs/ChatPreferencesViewModel.java | 112 ++- .../prefs/GeneralPreferencesViewModel.java | 74 +- .../prefs/KeyBindingPreferencesViewModel.java | 32 +- .../tcv/app/prefs/KeywordFilterViewModel.java | 53 +- .../tcv/app/prefs/PreferencesViewModel.java | 141 ++- .../app/prefs/PreferencesViewModelBase.java | 2 +- .../k7t3/tcv/app/prefs/SettingsDraft.java | 33 + .../tcv/app/prefs/SettingsSaveService.java | 177 ++++ .../tcv/app/prefs/UserFilterViewModel.java | 38 +- .../app/reactive/ChatMessageSubscriber.java | 32 +- .../app/reactive/DownCastFXSubscriber.java | 4 +- .../tcv/app/secure/AtomicKeyStoreFile.java | 64 ++ .../k7t3/tcv/app/secure/CipherOperator.java | 177 ---- .../k7t3/tcv/app/secure/CredentialCipher.java | 89 ++ .../app/secure/CredentialCipherService.java | 16 + .../k7t3/tcv/app/secure/KeyManager.java | 10 +- .../tcv/app/secure/KeyManagerFactory.java | 23 +- .../k7t3/tcv/app/secure/KeyManagerImpl.java | 164 ++-- .../tcv/app/secure/KeyManagerProvider.java | 41 + .../k7t3/tcv/app/secure/KeyStoreSession.java | 174 ++++ .../tcv/app/secure/LibsecretSecretStore.java | 178 ++++ .../app/secure/MacKeychainSecretStore.java | 158 +++ .../secure/NativeSecretStoreException.java | 13 + .../k7t3/tcv/app/secure/OsSecretStore.java | 10 + .../tcv/app/secure/ProcessOsSecretStore.java | 131 +++ .../tcv/app/secure/SecretStoreCommand.java | 33 + .../tcv/app/secure/SecretStoreHelper.java | 33 + .../tcv/app/secure/SecretStoreProtocol.java | 47 + .../secure/WindowsCredentialSecretStore.java | 152 +++ .../tcv/app/service/ApplicationShutdown.java | 90 ++ .../k7t3/tcv/app/service/AsyncCommand.java | 73 -- .../k7t3/tcv/app/service/BrowserActions.java | 111 +++ .../tcv/app/service/CachedImageStore.java | 79 +- .../github/k7t3/tcv/app/service/FXTask.java | 115 ++- .../k7t3/tcv/app/service/FXTaskGroup.java | 90 ++ .../tcv/app/service/LiveStateNotificator.java | 243 ++++- .../k7t3/tcv/app/service/SerialIoQueue.java | 113 +++ .../k7t3/tcv/app/service/TaskWorker.java | 18 +- .../tcv/app/service/WindowBoundsService.java | 153 ++- .../k7t3/tcv/app/theme/ThemeManager.java | 48 +- .../k7t3/tcv/app/user/UserDataFile.java | 80 +- .../tcv/database/AbstractDBConnector.java | 109 ++- .../github/k7t3/tcv/database/DBConnector.java | 27 +- .../k7t3/tcv/database/SQLiteDBConnector.java | 46 +- .../k7t3/tcv/domain/FollowedChannelPager.java | 27 + .../github/k7t3/tcv/domain/HelixClient.java | 51 + .../k7t3/tcv/domain/HelixClientFactory.java | 307 ++++++ .../k7t3/tcv/domain/StreamEventMonitor.java | 252 +++++ .../com/github/k7t3/tcv/domain/Twitch.java | 113 ++- .../com/github/k7t3/tcv/domain/TwitchAPI.java | 530 ++-------- .../k7t3/tcv/domain/TwitchClientFactory.java | 128 +++ .../github/k7t3/tcv/domain/TwitchClients.java | 25 + .../github/k7t3/tcv/domain/TwitchLoader.java | 202 +++- .../tcv/domain/TwitchRequestExecutor.java | 90 ++ .../tcv/domain/auth/CredentialController.java | 166 +++- .../k7t3/tcv/domain/auth/CredentialStore.java | 17 + .../domain/auth/SessionCredentialStore.java | 201 ++++ .../tcv/domain/channel/ChannelRepository.java | 123 ++- .../tcv/domain/channel/TwitchChannel.java | 99 +- .../channel/TwitchChannelEventProvider.java | 83 +- .../tcv/domain/chat/ChatMessageFragment.java | 6 +- .../tcv/domain/chat/ChatMessageParser.java | 144 ++- .../github/k7t3/tcv/domain/chat/ChatRoom.java | 5 + .../domain/chat/ChatRoomEventProvider.java | 101 +- .../k7t3/tcv/domain/chat/ClipFinder.java | 38 +- .../k7t3/tcv/domain/chat/ClipLinkParser.java | 50 + .../domain/event/EventSubscriptionScope.java | 68 ++ .../domain/event/stream/StreamStateEvent.java | 14 + .../service/ChannelGroupEntityService.java | 50 +- .../entity/service/ChatFilterEntityStore.java | 98 ++ .../ChatKeywordFilterEntityService.java | 25 +- .../service/ChatUserFilterEntityService.java | 14 +- .../tcv/entity/service/SettingsJournal.java | 162 ++++ .../service/WindowBoundsEntityService.java | 37 +- .../k7t3/tcv/io/InterruptibleFileLocks.java | 31 + .../k7t3/tcv/io/PreferenceFileLock.java | 53 + .../k7t3/tcv/lifecycle/CloseActions.java | 28 + .../k7t3/tcv/lifecycle/OwnedScheduler.java | 39 + .../github/k7t3/tcv/prefs/AppPreferences.java | 161 ++-- .../k7t3/tcv/prefs/ChatPreferences.java | 132 +-- .../github/k7t3/tcv/prefs/FontSettings.java | 33 + .../k7t3/tcv/prefs/GeneralPreferences.java | 94 +- .../k7t3/tcv/prefs/KeyBindingPreferences.java | 37 +- .../github/k7t3/tcv/prefs/PreferenceKey.java | 68 ++ .../k7t3/tcv/prefs/PreferenceProjection.java | 115 +++ .../k7t3/tcv/prefs/PreferenceStore.java | 249 +++++ .../k7t3/tcv/prefs/PreferenceValuesCodec.java | 69 ++ .../k7t3/tcv/prefs/PreferencesBase.java | 148 ++- .../k7t3/tcv/prefs/StatePreferences.java | 61 +- .../k7t3/tcv/reactive/AbstractSubscriber.java | 42 +- .../k7t3/tcv/reactive/FlowableSubscriber.java | 4 +- .../k7t3/tcv/view/ApplicationWindow.java | 7 + .../com/github/k7t3/tcv/view/Launcher.java | 319 +++--- .../k7t3/tcv/view/MainModelFactory.java | 95 ++ .../github/k7t3/tcv/view/MainViewFactory.java | 107 ++ .../com/github/k7t3/tcv/view/MainWindow.java | 120 +++ .../k7t3/tcv/view/auth/AuthenticatorView.java | 71 +- .../view/channel/FoundChannelListCell.java | 103 +- .../k7t3/tcv/view/channel/LiveInfoPopup.java | 18 +- .../channel/LiveStateNotificatorView.java | 51 +- .../tcv/view/channel/SearchChannelView.java | 81 +- .../view/channel/TwitchChannelListCell.java | 51 +- .../view/channel/TwitchChannelListView.java | 161 +++- .../channel/menu/OpenBrowserMenuItem.java | 18 +- .../view/channel/menu/OpenChatMenuItem.java | 15 +- .../tcv/view/chat/ChannelProfileView.java | 33 + .../k7t3/tcv/view/chat/ChatContainerView.java | 304 +++--- .../k7t3/tcv/view/chat/ChatDataCell.java | 178 ++-- .../tcv/view/chat/ChatDataContextMenu.java | 49 +- .../github/k7t3/tcv/view/chat/ChatFont.java | 32 +- .../k7t3/tcv/view/chat/ChatRoomViewUtils.java | 141 ++- .../chat/FloatableMergedChatRoomView.java | 154 +-- .../chat/FloatableSingleChatRoomView.java | 127 +-- .../tcv/view/chat/MergedChatRoomView.java | 134 +-- .../tcv/view/chat/SingleChatRoomView.java | 106 +- .../view/clip/PostedClipRepositoryView.java | 72 +- .../tcv/view/clip/PostedClipViewCell.java | 59 +- .../view/command/LoadCredentialCommand.java | 97 +- .../tcv/view/command/OpenAboutCommand.java | 103 +- .../view/command/OpenChannelGroupCommand.java | 45 +- .../tcv/view/command/OpenClipCommand.java | 36 +- .../OpenCommunityGuidelineCommand.java | 16 +- .../view/command/OpenPreferencesCommand.java | 121 ++- .../command/OpenSearchChannelCommand.java | 60 +- .../tcv/view/command/OpenTermsCommand.java | 16 +- .../tcv/view/command/OwnedModalCommand.java | 100 ++ .../tcv/view/control/EditableLabelSkin.java | 17 +- .../github/k7t3/tcv/view/core/BasicPopup.java | 27 +- .../view/core/DeleteButtonTableColumn.java | 22 +- .../k7t3/tcv/view/core/FloatableStage.java | 21 + .../k7t3/tcv/view/core/JavaFXHelper.java | 100 +- .../k7t3/tcv/view/core/OwnedDialog.java | 65 ++ .../k7t3/tcv/view/core/ViewResources.java | 28 + .../k7t3/tcv/view/core/WindowBounds.java | 13 +- .../k7t3/tcv/view/core/WindowBoundsScope.java | 86 ++ .../k7t3/tcv/view/core/cell/TextListCell.java | 111 --- .../tcv/view/group/ChannelGroupListCell.java | 107 +- .../tcv/view/group/ChannelGroupListView.java | 72 +- .../menu/ChannelGroupCreateMenuItem.java | 51 +- .../tcv/view/group/menu/ChannelGroupMenu.java | 100 +- .../view/group/menu/ChannelGroupMenuItem.java | 39 +- .../github/k7t3/tcv/view/help/AboutView.java | 20 +- .../tcv/view/keyboard/KeyCombinationCell.java | 74 +- .../tcv/view/main/AuthenticationMenuItem.java | 146 ++- .../github/k7t3/tcv/view/main/MainView.java | 249 ++++- .../tcv/view/prefs/ChatPreferencesView.java | 37 +- .../view/prefs/GeneralPreferencesView.java | 10 +- .../view/prefs/KeyBindingPreferencesView.java | 55 +- .../tcv/view/prefs/KeywordFilterCell.java | 44 + .../tcv/view/prefs/KeywordFilterView.java | 46 +- .../k7t3/tcv/view/prefs/PreferencesPage.java | 4 +- .../k7t3/tcv/view/prefs/PreferencesView.java | 167 ++-- .../k7t3/tcv/view/prefs/UserFilterView.java | 26 +- src/main/packaging/key-storage.properties | 6 + .../com/github/k7t3/tcv/tcv.properties | 13 +- .../com/github/k7t3/tcv/tcv_ja.properties | 13 +- .../k7t3/tcv/view/auth/AuthenticatorView.fxml | 4 +- .../tcv/view/channel/SearchChannelView.fxml | 2 +- .../view/channel/TwitchChannelListView.fxml | 4 +- .../k7t3/tcv/view/chat/ChatContainerView.fxml | 18 +- .../chat/FloatableMergedChatRoomView.fxml | 4 +- .../chat/FloatableSingleChatRoomView.fxml | 4 +- .../tcv/view/chat/MergedChatRoomView.fxml | 6 +- .../tcv/view/chat/SingleChatRoomView.fxml | 6 +- .../view/clip/PostedClipRepositoryView.fxml | 2 +- .../tcv/view/group/ChannelGroupListView.fxml | 2 +- .../github/k7t3/tcv/view/help/AboutView.fxml | 4 +- .../github/k7t3/tcv/view/main/MainView.fxml | 6 +- .../tcv/view/prefs/ChatPreferencesView.fxml | 2 +- .../view/prefs/GeneralPreferencesView.fxml | 2 +- .../view/prefs/KeyBindingPreferencesView.fxml | 2 +- .../tcv/view/prefs/KeywordFilterView.fxml | 2 +- .../k7t3/tcv/view/prefs/PreferencesView.fxml | 4 +- .../k7t3/tcv/view/prefs/UserFilterView.fxml | 2 +- src/main/resources/logging.properties | 13 +- .../AuthenticatorBrowserLifetimeTest.java | 64 ++ .../app/auth/AuthenticatorLifecycleTest.java | 403 ++++++++ .../app/auth/AuthenticatorShutdownTest.java | 162 ++++ .../auth/CredentialReadProbeViewModel.java | 40 + .../PreferencesCredentialPersistenceTest.java | 310 ++++++ .../PreferencesCredentialProcessTest.java | 223 +++++ .../PreferencesCredentialStorageTest.java | 239 +++++ .../channel/ChannelBorrowedLifecycleTest.java | 37 + .../app/channel/ChannelChatLifecycleTest.java | 369 +++++++ .../ChannelChatRegistrationOwnershipTest.java | 177 ++++ .../ChannelChatSessionIntegrationTest.java | 115 +++ .../channel/ChannelImageLifecycleTest.java | 150 +++ .../app/channel/ChannelListBrowserTest.java | 87 ++ .../app/channel/ChannelListFilterTest.java | 121 +++ .../ChannelLoadingCancellationTest.java | 86 ++ .../channel/ChannelLoadingLifecycleTest.java | 218 +++++ .../app/channel/ChannelLoadingQueueTest.java | 229 +++++ .../tcv/app/channel/ChannelReleaseTest.java | 146 +++ .../tcv/app/channel/ChannelReopenTest.java | 118 +++ .../app/channel/FoundChannelImageTest.java | 91 ++ .../tcv/app/channel/FoundChannelJoinTest.java | 38 + .../FoundChannelRequestOwnershipTest.java | 161 ++++ .../channel/SearchChannelViewModelTest.java | 232 +++++ .../channel/SearchRequestLifecycleTest.java | 293 ++++++ .../app/channel/TwitchChannelImageTest.java | 48 + .../app/chat/ChatContainerLoadingTest.java | 679 +++++++++++++ .../app/chat/ChatContainerShutdownTest.java | 57 ++ .../k7t3/tcv/app/chat/ChatDataBadgesTest.java | 49 + .../tcv/app/chat/ChatExitAggregationTest.java | 229 +++++ .../tcv/app/chat/ChatHistoryMergingTest.java | 247 +++++ ...ChatResourceRegistrationOwnershipTest.java | 257 +++++ .../ChatResourceReleaseOwnershipTest.java | 282 ++++++ .../tcv/app/chat/ChatResourcesLoaderTest.java | 103 ++ .../app/chat/ChatRoomStateOwnershipTest.java | 49 + .../chat/ChatSessionSubscriptionsTest.java | 135 +++ .../tcv/app/chat/MergedChatShutdownTest.java | 125 +++ .../app/chat/MergedRoomStateRoutingTest.java | 45 + .../chat/filter/ChatFilterMatchingTest.java | 47 + .../app/chat/filter/ChatFilterSavingTest.java | 98 ++ .../filter/ChatFilterWriteOwnershipTest.java | 378 ++++++++ .../chat/filter/ChatFiltersLoadingTest.java | 98 ++ .../app/clip/PostedClipCancellationTest.java | 74 ++ .../clip/PostedClipImageLifecycleTest.java | 51 + .../tcv/app/clip/PostedClipOwnershipTest.java | 43 + .../tcv/app/clip/PostedClipRetryTest.java | 338 +++++++ .../tcv/app/core/AppHelperErrorOwnerTest.java | 150 +++ .../app/core/AppHelperModelLifetimeTest.java | 105 ++ .../tcv/app/core/AppHelperReleaseTest.java | 49 + .../tcv/app/core/AppHelperSessionTest.java | 440 +++++++++ .../tcv/app/core/AppHelperShutdownTest.java | 190 ++++ .../core/ApplicationImageShutdownTest.java | 80 ++ .../core/ClientSessionReleaseStartupTest.java | 179 ++++ .../k7t3/tcv/app/core/ClientSessionTest.java | 137 +++ .../app/core/ExceptionHandlerOwnerTest.java | 171 ++++ .../tcv/app/core/LoggerInitializerTest.java | 133 +++ .../app/core/MainSessionIntegrationTest.java | 179 ++++ .../tcv/app/emoji/ChatEmojiStoreTest.java | 127 ++- .../tcv/app/emoji/EmojiLifecycleTest.java | 504 ++++++++++ .../group/ChannelGroupEditorLifetimeTest.java | 55 ++ ...ChannelGroupRegistrationOwnershipTest.java | 226 +++++ .../app/group/ChannelGroupShutdownTest.java | 120 +++ .../group/ChannelGroupWriteOwnershipTest.java | 370 +++++++ .../app/group/GroupChannelRetentionTest.java | 184 ++++ .../tcv/app/image/ImageDownloaderTest.java | 306 ++++++ .../k7t3/tcv/app/image/ImageLoaderTest.java | 125 +++ .../k7t3/tcv/app/image/ImageStoresTest.java | 79 ++ .../k7t3/tcv/app/image/ImageTestDoubles.java | 24 + .../k7t3/tcv/app/image/LazyImageTest.java | 212 ++++ .../app/main/MainBrowserErrorOwnerTest.java | 87 ++ .../k7t3/tcv/app/main/MainErrorFixture.java | 93 ++ .../main/MainInitialLoadOwnershipTest.java | 160 +++ .../app/main/MainOperationErrorOwnerTest.java | 124 +++ .../app/main/MainViewModelLifecycleTest.java | 278 ++++++ .../ViewModelConstructionFailureTest.java | 48 + .../app/model/ViewModelEventSourceTest.java | 88 ++ .../tcv/app/model/ViewModelLifecycleTest.java | 130 +++ .../model/ViewModelReleaseFailureTest.java | 183 ++++ .../app/model/ViewModelSessionScopeTest.java | 143 +++ .../app/model/ViewModelSubscriptionTest.java | 85 ++ .../prefs/OwnedSettingsProjectionTest.java | 89 ++ .../tcv/app/prefs/PreferencesDraftTest.java | 90 ++ .../prefs/PreferencesSaveOwnershipTest.java | 262 +++++ .../tcv/app/prefs/PreferencesSaveTest.java | 104 ++ .../app/prefs/SettingsCrashRecoveryTest.java | 583 +++++++++++ .../SettingsCredentialCoordinationTest.java | 64 ++ .../app/prefs/SettingsDraftCaptureTest.java | 90 ++ .../prefs/SettingsEditorLifecycleTest.java | 175 ++++ .../app/prefs/SettingsProfileProcessTest.java | 210 ++++ .../prefs/SettingsProfileRecoveryTest.java | 519 ++++++++++ .../app/prefs/SettingsSaveServiceTest.java | 282 ++++++ .../tcv/app/reactive/FXSubscriberTest.java | 54 ++ ....java => CredentialCipherServiceTest.java} | 49 +- .../tcv/app/secure/CredentialCipherTest.java | 154 +++ .../CredentialStorageEncryptionTest.java | 103 ++ .../secure/KeyManagerCancellationTest.java | 273 ++++++ .../app/secure/KeyManagerDurabilityTest.java | 207 ++++ .../tcv/app/secure/KeyManagerFactoryTest.java | 68 ++ .../tcv/app/secure/KeyManagerImplTest.java | 19 +- .../app/secure/KeyManagerProviderTest.java | 134 +++ .../tcv/app/secure/KeyStoreProcessProbe.java | 32 + .../app/secure/LibsecretSecretStoreTest.java | 307 ++++++ .../app/secure/MacKeychainProcessProbe.java | 83 ++ .../app/secure/MacKeychainRequestTest.java | 198 ++++ .../secure/MacKeychainSecretStoreTest.java | 69 ++ .../app/secure/OsProtectedKeyStoreTest.java | 303 ++++++ .../tcv/app/secure/PackagedOsKeyProbe.java | 44 + .../app/secure/ProcessOsSecretStoreTest.java | 143 +++ .../app/secure/SecretStoreCommandTest.java | 96 ++ .../tcv/app/secure/SecretStoreHelperTest.java | 69 ++ .../app/secure/SecretStoreProcessProbe.java | 51 + .../app/secure/SecretStoreProtocolTest.java | 144 +++ .../WindowsCredentialSecretStoreTest.java | 217 +++++ .../app/service/ApplicationShutdownTest.java | 87 ++ .../tcv/app/service/BrowserActionsTest.java | 148 +++ .../tcv/app/service/CachedImageStoreTest.java | 170 ++++ .../service/FXTaskCancellationLinkTest.java | 53 + .../tcv/app/service/FXTaskCompletionTest.java | 109 +++ .../k7t3/tcv/app/service/FXTaskGroupTest.java | 167 ++++ .../k7t3/tcv/app/service/FXTaskTest.java | 82 +- .../LiveStateNotificatorOwnershipTest.java | 424 ++++++++ .../tcv/app/service/SerialIoQueueTest.java | 111 +++ .../WindowBoundsServiceOwnershipTest.java | 94 ++ .../app/service/WindowBoundsShutdownTest.java | 114 +++ .../app/theme/ThemeManagerLifecycleTest.java | 131 +++ .../k7t3/tcv/app/user/UserDataFileTest.java | 138 +++ .../tcv/build/BuildRuntimeContractTest.java | 39 + .../ProductionRuntimeDependenciesTest.java | 20 + .../k7t3/tcv/chat/ChatMessageParserTest.java | 156 ++- .../tcv/database/SQLiteDBConnectorTest.java | 87 ++ .../tcv/database/SQLiteReadLifetimeTest.java | 196 ++++ .../database/SQLiteRollbackFailureTest.java | 80 ++ .../tcv/database/SQLiteTransactionTest.java | 104 ++ .../tcv/domain/FollowedChannelPagerTest.java | 31 + .../tcv/domain/FollowedChannelsHttpTest.java | 910 ++++++++++++++++++ .../tcv/domain/HelixRuntimeLinkageTest.java | 423 ++++++++ .../tcv/domain/StreamEventMonitorTest.java | 343 +++++++ .../github/k7t3/tcv/domain/TwitchAPITest.java | 384 ++++++++ .../tcv/domain/TwitchClientFactoryTest.java | 246 +++++ .../tcv/domain/TwitchEndpointHttpTest.java | 272 ++++++ .../k7t3/tcv/domain/TwitchLifecycleTest.java | 285 ++++++ .../tcv/domain/TwitchLoaderShutdownTest.java | 196 ++++ .../k7t3/tcv/domain/TwitchLoaderTest.java | 272 ++++++ .../domain/TwitchRefreshCancellationTest.java | 84 ++ .../domain/TwitchSchedulerOwnershipTest.java | 366 +++++++ .../CredentialControllerShutdownTest.java | 293 ++++++ .../domain/auth/CredentialControllerTest.java | 200 ++++ .../auth/SessionCredentialStoreTest.java | 240 +++++ .../channel/ChannelEventOwnershipTest.java | 43 + .../ChannelRepositoryLifecycleTest.java | 428 ++++++++ .../channel/EventProviderLifecycleTest.java | 346 +++++++ .../domain/chat/ChatRoomClipEventTest.java | 55 ++ .../domain/chat/ChatRoomMessageEventTest.java | 75 ++ .../chat/ChatRoomModerationEventTest.java | 72 ++ .../event/EventSubscriptionScopeTest.java | 63 ++ .../ChannelGroupEntityServiceTest.java | 58 +- .../ChannelGroupResultMappingTest.java | 58 ++ .../service/ChatFilterEntityStoreTest.java | 105 ++ .../service/ChatFilterSnapshotTest.java | 95 ++ .../SettingsJournalPersistenceTest.java | 85 ++ .../tcv/io/InterruptibleFileLocksTest.java | 39 + .../prefs/AppPreferencesPersistenceTest.java | 46 + .../k7t3/tcv/prefs/FontSettingsTest.java | 31 + .../prefs/InvalidStoredPreferencesTest.java | 134 +++ .../prefs/KeyBindingWriteOwnershipTest.java | 59 ++ .../OwnedPreferenceWriteRecoveryTest.java | 83 ++ .../PreferenceBackendWriteOwnershipTest.java | 51 + .../prefs/PreferenceClosedPropertyTest.java | 32 + ...eInteractionDuringCredentialWriteTest.java | 75 ++ .../tcv/prefs/PreferenceLoadSnapshotTest.java | 52 + .../tcv/prefs/PreferencePendingValueTest.java | 37 + .../tcv/prefs/PreferenceProcessProbe.java | 25 + ...referenceValuesCodecCompatibilityTest.java | 21 + .../tcv/prefs/PreferenceWriteFailureTest.java | 128 +++ .../prefs/PreferenceWriteLifecycleTest.java | 53 + .../prefs/PreferencesWithoutToolkitTest.java | 27 + .../tcv/prefs/StatePreferencesReadTest.java | 34 + .../tcv/reactive/AbstractSubscriberTest.java | 114 +++ .../k7t3/tcv/support/ClipEventSource.java | 46 + .../k7t3/tcv/support/MemoryPreferences.java | 22 + .../com/github/k7t3/tcv/support/TestJvm.java | 18 + .../github/k7t3/tcv/support/TestJvmTest.java | 39 + .../LauncherCredentialOwnershipProbe.java | 325 +++++++ .../view/LauncherCredentialOwnershipTest.java | 66 ++ .../tcv/view/LauncherDefaultErrorProbe.java | 64 ++ .../tcv/view/LauncherDefaultErrorTest.java | 40 + .../k7t3/tcv/view/LauncherLifecycleTest.java | 189 ++++ .../view/LauncherPreferenceWriterTest.java | 81 ++ .../view/LauncherServiceOwnershipProbe.java | 64 ++ .../view/LauncherServiceOwnershipTest.java | 41 + .../k7t3/tcv/view/LauncherStartupTest.java | 615 ++++++++++++ .../tcv/view/MainAccessibleControlsTest.java | 123 +++ .../k7t3/tcv/view/MainModelFactoryTest.java | 52 + .../github/k7t3/tcv/view/MainWindowTest.java | 824 ++++++++++++++++ .../view/MainWindowThemeOwnershipTest.java | 65 ++ .../auth/AuthenticatorViewLifecycleTest.java | 80 ++ .../channel/ChannelListCellLifetimeTest.java | 133 +++ .../channel/ChannelListViewLifetimeTest.java | 238 +++++ .../channel/FoundChannelCellLifetimeTest.java | 101 ++ .../LiveNotificationViewLifetimeTest.java | 82 ++ .../view/channel/MenuItemLifetimeTest.java | 38 + .../tcv/view/channel/PopupLifetimeTest.java | 47 + .../SearchChannelViewLifecycleTest.java | 76 ++ .../view/chat/ChatContainerOwnershipTest.java | 138 +++ .../view/chat/ChatDataCellLifetimeTest.java | 284 ++++++ .../chat/ChatDataContextMenuLifetimeTest.java | 113 +++ .../view/chat/ChatRoomViewLifetimeTest.java | 341 +++++++ .../view/chat/ChatViewSubscriptionsTest.java | 76 ++ .../chat/FloatableBoundsOwnershipTest.java | 46 + .../tcv/view/chat/OfflineBackgroundTest.java | 78 ++ .../view/clip/PostedClipCellLifetimeTest.java | 102 ++ .../view/clip/PostedClipImageViewTest.java | 68 ++ .../view/clip/PostedClipViewLifetimeTest.java | 37 + .../LoadCredentialCommandLifetimeTest.java | 138 +++ .../view/command/OpenAboutCommandTest.java | 174 ++++ .../command/OpenPreferencesCommandTest.java | 378 ++++++++ .../command/OpenSearchChannelCommandTest.java | 214 ++++ .../view/command/OwnedModalCommandTest.java | 80 ++ .../EditableLabelSkinLifetimeTest.java | 152 +++ ...eteButtonTableColumnAccessibilityTest.java | 51 + .../core/JavaFXHelperPseudoClassTest.java | 43 + .../k7t3/tcv/view/core/OwnedDialogTest.java | 119 +++ .../k7t3/tcv/view/core/ViewResourcesTest.java | 28 + .../tcv/view/core/WindowBoundsScopeTest.java | 131 +++ .../group/ChannelGroupViewLifetimeTest.java | 216 +++++ .../menu/ChannelGroupCreateLifetimeTest.java | 117 +++ .../menu/ChannelGroupMenuLifetimeTest.java | 149 +++ .../view/keyboard/KeyCombinationCellTest.java | 79 ++ .../AuthenticationMenuItemLifetimeTest.java | 156 +++ .../tcv/view/prefs/KeyBindingEditorTest.java | 142 +++ .../tcv/view/prefs/KeywordFilterCellTest.java | 42 + .../prefs/SettingsTablePageLifetimeTest.java | 137 +++ 475 files changed, 50381 insertions(+), 5333 deletions(-) create mode 100644 .gitattributes create mode 100644 .java-version create mode 100644 buildSrc/build.gradle create mode 100644 buildSrc/settings.gradle create mode 100644 buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkModulesTask.groovy create mode 100644 buildSrc/src/main/groovy/com/github/k7t3/tcv/build/JdkToolTask.groovy create mode 100644 buildSrc/src/main/groovy/com/github/k7t3/tcv/build/NativePackageTask.groovy create mode 100644 buildSrc/src/main/java/com/github/k7t3/tcv/build/LinuxGlibcRequirement.java create mode 100644 buildSrc/src/main/java/com/github/k7t3/tcv/build/PackageOutput.java create mode 100644 buildSrc/src/main/java/com/github/k7t3/tcv/build/PackagePlan.java create mode 100644 buildSrc/src/test/java/com/github/k7t3/tcv/build/LinuxGlibcRequirementTest.java create mode 100644 buildSrc/src/test/java/com/github/k7t3/tcv/build/PackageOutputTest.java create mode 100644 buildSrc/src/test/java/com/github/k7t3/tcv/build/PackagePlanTest.java create mode 100644 docs/licenses/jai-imageio.txt create mode 100644 gradle/libs.versions.toml create mode 100644 src/main/java/com/github/k7t3/tcv/app/channel/ChannelChatConnection.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/chat/ChatResources.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/chat/ChatResourcesLoader.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/core/ClientSession.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/core/ClientSessions.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/event/SessionInvalidatedEvent.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/group/ChannelGroupOrder.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/image/ImageDownloader.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/image/ImageLoader.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/prefs/SettingsDraft.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/prefs/SettingsSaveService.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/AtomicKeyStoreFile.java delete mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/CipherOperator.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/CredentialCipher.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/CredentialCipherService.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/KeyManagerProvider.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/KeyStoreSession.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/LibsecretSecretStore.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/MacKeychainSecretStore.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/NativeSecretStoreException.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/OsSecretStore.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/ProcessOsSecretStore.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/SecretStoreCommand.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/SecretStoreHelper.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/SecretStoreProtocol.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/secure/WindowsCredentialSecretStore.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/service/ApplicationShutdown.java delete mode 100644 src/main/java/com/github/k7t3/tcv/app/service/AsyncCommand.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/service/BrowserActions.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/service/FXTaskGroup.java create mode 100644 src/main/java/com/github/k7t3/tcv/app/service/SerialIoQueue.java create mode 100644 src/main/java/com/github/k7t3/tcv/domain/FollowedChannelPager.java create mode 100644 src/main/java/com/github/k7t3/tcv/domain/HelixClient.java create mode 100644 src/main/java/com/github/k7t3/tcv/domain/HelixClientFactory.java create mode 100644 src/main/java/com/github/k7t3/tcv/domain/StreamEventMonitor.java create mode 100644 src/main/java/com/github/k7t3/tcv/domain/TwitchClientFactory.java create mode 100644 src/main/java/com/github/k7t3/tcv/domain/TwitchClients.java create mode 100644 src/main/java/com/github/k7t3/tcv/domain/TwitchRequestExecutor.java create mode 100644 src/main/java/com/github/k7t3/tcv/domain/auth/SessionCredentialStore.java create mode 100644 src/main/java/com/github/k7t3/tcv/domain/chat/ClipLinkParser.java create mode 100644 src/main/java/com/github/k7t3/tcv/domain/event/EventSubscriptionScope.java create mode 100644 src/main/java/com/github/k7t3/tcv/domain/event/stream/StreamStateEvent.java create mode 100644 src/main/java/com/github/k7t3/tcv/entity/service/ChatFilterEntityStore.java create mode 100644 src/main/java/com/github/k7t3/tcv/entity/service/SettingsJournal.java create mode 100644 src/main/java/com/github/k7t3/tcv/io/InterruptibleFileLocks.java create mode 100644 src/main/java/com/github/k7t3/tcv/io/PreferenceFileLock.java create mode 100644 src/main/java/com/github/k7t3/tcv/lifecycle/CloseActions.java create mode 100644 src/main/java/com/github/k7t3/tcv/lifecycle/OwnedScheduler.java create mode 100644 src/main/java/com/github/k7t3/tcv/prefs/FontSettings.java create mode 100644 src/main/java/com/github/k7t3/tcv/prefs/PreferenceKey.java create mode 100644 src/main/java/com/github/k7t3/tcv/prefs/PreferenceProjection.java create mode 100644 src/main/java/com/github/k7t3/tcv/prefs/PreferenceStore.java create mode 100644 src/main/java/com/github/k7t3/tcv/prefs/PreferenceValuesCodec.java create mode 100644 src/main/java/com/github/k7t3/tcv/view/ApplicationWindow.java create mode 100644 src/main/java/com/github/k7t3/tcv/view/MainModelFactory.java create mode 100644 src/main/java/com/github/k7t3/tcv/view/MainViewFactory.java create mode 100644 src/main/java/com/github/k7t3/tcv/view/MainWindow.java create mode 100644 src/main/java/com/github/k7t3/tcv/view/chat/ChannelProfileView.java create mode 100644 src/main/java/com/github/k7t3/tcv/view/command/OwnedModalCommand.java create mode 100644 src/main/java/com/github/k7t3/tcv/view/core/OwnedDialog.java create mode 100644 src/main/java/com/github/k7t3/tcv/view/core/ViewResources.java create mode 100644 src/main/java/com/github/k7t3/tcv/view/core/WindowBoundsScope.java delete mode 100644 src/main/java/com/github/k7t3/tcv/view/core/cell/TextListCell.java create mode 100644 src/main/java/com/github/k7t3/tcv/view/prefs/KeywordFilterCell.java create mode 100644 src/main/packaging/key-storage.properties create mode 100644 src/test/java/com/github/k7t3/tcv/app/auth/AuthenticatorBrowserLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/auth/AuthenticatorLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/auth/AuthenticatorShutdownTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/auth/CredentialReadProbeViewModel.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/auth/PreferencesCredentialPersistenceTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/auth/PreferencesCredentialProcessTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/auth/PreferencesCredentialStorageTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/ChannelBorrowedLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/ChannelChatLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/ChannelChatRegistrationOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/ChannelChatSessionIntegrationTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/ChannelImageLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/ChannelListBrowserTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/ChannelListFilterTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/ChannelLoadingCancellationTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/ChannelLoadingLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/ChannelLoadingQueueTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/ChannelReleaseTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/ChannelReopenTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/FoundChannelImageTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/FoundChannelJoinTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/FoundChannelRequestOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/SearchChannelViewModelTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/SearchRequestLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/channel/TwitchChannelImageTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/ChatContainerLoadingTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/ChatContainerShutdownTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/ChatDataBadgesTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/ChatExitAggregationTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/ChatHistoryMergingTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/ChatResourceRegistrationOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/ChatResourceReleaseOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/ChatResourcesLoaderTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/ChatRoomStateOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/ChatSessionSubscriptionsTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/MergedChatShutdownTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/MergedRoomStateRoutingTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/filter/ChatFilterMatchingTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/filter/ChatFilterSavingTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/filter/ChatFilterWriteOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/chat/filter/ChatFiltersLoadingTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/clip/PostedClipCancellationTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/clip/PostedClipImageLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/clip/PostedClipOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/clip/PostedClipRetryTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/core/AppHelperErrorOwnerTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/core/AppHelperModelLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/core/AppHelperReleaseTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/core/AppHelperSessionTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/core/AppHelperShutdownTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/core/ApplicationImageShutdownTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/core/ClientSessionReleaseStartupTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/core/ClientSessionTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/core/ExceptionHandlerOwnerTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/core/LoggerInitializerTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/core/MainSessionIntegrationTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/emoji/EmojiLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/group/ChannelGroupEditorLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/group/ChannelGroupRegistrationOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/group/ChannelGroupShutdownTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/group/ChannelGroupWriteOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/group/GroupChannelRetentionTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/image/ImageDownloaderTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/image/ImageLoaderTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/image/ImageStoresTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/image/ImageTestDoubles.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/image/LazyImageTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/main/MainBrowserErrorOwnerTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/main/MainErrorFixture.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/main/MainInitialLoadOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/main/MainOperationErrorOwnerTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/main/MainViewModelLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/model/ViewModelConstructionFailureTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/model/ViewModelEventSourceTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/model/ViewModelLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/model/ViewModelReleaseFailureTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/model/ViewModelSessionScopeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/model/ViewModelSubscriptionTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/prefs/OwnedSettingsProjectionTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/prefs/PreferencesDraftTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/prefs/PreferencesSaveOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/prefs/PreferencesSaveTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/prefs/SettingsCrashRecoveryTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/prefs/SettingsCredentialCoordinationTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/prefs/SettingsDraftCaptureTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/prefs/SettingsEditorLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/prefs/SettingsProfileProcessTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/prefs/SettingsProfileRecoveryTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/prefs/SettingsSaveServiceTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/reactive/FXSubscriberTest.java rename src/test/java/com/github/k7t3/tcv/app/secure/{CipherOperatorTest.java => CredentialCipherServiceTest.java} (56%) create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/CredentialCipherTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/CredentialStorageEncryptionTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/KeyManagerCancellationTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/KeyManagerDurabilityTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/KeyManagerFactoryTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/KeyManagerProviderTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/KeyStoreProcessProbe.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/LibsecretSecretStoreTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/MacKeychainProcessProbe.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/MacKeychainRequestTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/MacKeychainSecretStoreTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/OsProtectedKeyStoreTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/PackagedOsKeyProbe.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/ProcessOsSecretStoreTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/SecretStoreCommandTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/SecretStoreHelperTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/SecretStoreProcessProbe.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/SecretStoreProtocolTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/secure/WindowsCredentialSecretStoreTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/service/ApplicationShutdownTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/service/BrowserActionsTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/service/CachedImageStoreTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/service/FXTaskCancellationLinkTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/service/FXTaskCompletionTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/service/FXTaskGroupTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/service/LiveStateNotificatorOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/service/SerialIoQueueTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/service/WindowBoundsServiceOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/service/WindowBoundsShutdownTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/theme/ThemeManagerLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/app/user/UserDataFileTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/build/BuildRuntimeContractTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/build/ProductionRuntimeDependenciesTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/database/SQLiteDBConnectorTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/database/SQLiteReadLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/database/SQLiteRollbackFailureTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/database/SQLiteTransactionTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/FollowedChannelPagerTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/FollowedChannelsHttpTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/HelixRuntimeLinkageTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/StreamEventMonitorTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/TwitchAPITest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/TwitchClientFactoryTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/TwitchEndpointHttpTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/TwitchLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/TwitchLoaderShutdownTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/TwitchLoaderTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/TwitchRefreshCancellationTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/TwitchSchedulerOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/auth/CredentialControllerShutdownTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/auth/CredentialControllerTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/auth/SessionCredentialStoreTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/channel/ChannelEventOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/channel/ChannelRepositoryLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/channel/EventProviderLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/chat/ChatRoomClipEventTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/chat/ChatRoomMessageEventTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/chat/ChatRoomModerationEventTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/domain/event/EventSubscriptionScopeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/entity/service/ChannelGroupResultMappingTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/entity/service/ChatFilterEntityStoreTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/entity/service/ChatFilterSnapshotTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/entity/service/SettingsJournalPersistenceTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/io/InterruptibleFileLocksTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/AppPreferencesPersistenceTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/FontSettingsTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/InvalidStoredPreferencesTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/KeyBindingWriteOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/OwnedPreferenceWriteRecoveryTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/PreferenceBackendWriteOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/PreferenceClosedPropertyTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/PreferenceInteractionDuringCredentialWriteTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/PreferenceLoadSnapshotTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/PreferencePendingValueTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/PreferenceProcessProbe.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/PreferenceValuesCodecCompatibilityTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/PreferenceWriteFailureTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/PreferenceWriteLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/PreferencesWithoutToolkitTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/prefs/StatePreferencesReadTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/reactive/AbstractSubscriberTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/support/ClipEventSource.java create mode 100644 src/test/java/com/github/k7t3/tcv/support/MemoryPreferences.java create mode 100644 src/test/java/com/github/k7t3/tcv/support/TestJvm.java create mode 100644 src/test/java/com/github/k7t3/tcv/support/TestJvmTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/LauncherCredentialOwnershipProbe.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/LauncherCredentialOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/LauncherDefaultErrorProbe.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/LauncherDefaultErrorTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/LauncherLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/LauncherPreferenceWriterTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/LauncherServiceOwnershipProbe.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/LauncherServiceOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/LauncherStartupTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/MainAccessibleControlsTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/MainModelFactoryTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/MainWindowTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/MainWindowThemeOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/auth/AuthenticatorViewLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/channel/ChannelListCellLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/channel/ChannelListViewLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/channel/FoundChannelCellLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/channel/LiveNotificationViewLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/channel/MenuItemLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/channel/PopupLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/channel/SearchChannelViewLifecycleTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/chat/ChatContainerOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/chat/ChatDataCellLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/chat/ChatDataContextMenuLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/chat/ChatRoomViewLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/chat/ChatViewSubscriptionsTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/chat/FloatableBoundsOwnershipTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/chat/OfflineBackgroundTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/clip/PostedClipCellLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/clip/PostedClipImageViewTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/clip/PostedClipViewLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/command/LoadCredentialCommandLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/command/OpenAboutCommandTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/command/OpenPreferencesCommandTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/command/OpenSearchChannelCommandTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/command/OwnedModalCommandTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/control/EditableLabelSkinLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/core/DeleteButtonTableColumnAccessibilityTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/core/JavaFXHelperPseudoClassTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/core/OwnedDialogTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/core/ViewResourcesTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/core/WindowBoundsScopeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/group/ChannelGroupViewLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/group/menu/ChannelGroupCreateLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/group/menu/ChannelGroupMenuLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/keyboard/KeyCombinationCellTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/main/AuthenticationMenuItemLifetimeTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/prefs/KeyBindingEditorTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/prefs/KeywordFilterCellTest.java create mode 100644 src/test/java/com/github/k7t3/tcv/view/prefs/SettingsTablePageLifetimeTest.java 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..fdcd755 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -6,11 +6,17 @@ on: # ドットをエスケープしなくていい(正規表現でない) - 'v[0-9]+.[0-9]+.[0-9]+*' workflow_dispatch: + inputs: + tag: + description: 'ビルドする既存のタグ(例: v1.2.3-rc.1)' + required: true + type: string jobs: parse_version: # プッシュされたタグの文字列からバージョンをパースする runs-on: ubuntu-latest outputs: + tag: ${{ steps.parse.outputs.tag }} full_version: ${{ steps.parse.outputs.full_version }} version: ${{ steps.parse.outputs.version }} major: ${{ steps.parse.outputs.major }} @@ -20,35 +26,51 @@ jobs: steps: - name: Parse version from tag id: parse + env: + DISPATCH_TAG: ${{ inputs.tag }} 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 + 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; } + MAJOR=${BASH_REMATCH[1]} + MINOR=${BASH_REMATCH[2]} + PATCH=${BASH_REMATCH[3]} + VERSION=$MAJOR.$MINOR.$PATCH + FULL_VERSION=${TAG#v} + SUFFIX=${FULL_VERSION#"$VERSION"} + SUFFIX=${SUFFIX#-} + printf '%s\n' "tag=$TAG" "full_version=$FULL_VERSION" "version=$VERSION" \ + "major=$MAJOR" "minor=$MINOR" "patch=$PATCH" "suffix=$SUFFIX" >> "$GITHUB_OUTPUT" make: # タグから識別したバージョン情報に基づくアプリケーションを生成する strategy: matrix: # WindowsランナーはWiX Toolset 3.14.1.8722入り - # MacOSはIntel CPU(macos-13)とApple Silicon CPU(macos-14) + # MacOSはIntel CPU(macos-15-intel)とApple Silicon CPU(macos-15) # 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] + os: [windows-latest, macos-15-intel, macos-15] runs-on: ${{ matrix.os }} needs: parse_version steps: - name: Checkout source - uses: actions/checkout@v4 + uses: actions/checkout@v7.0.1 + with: + ref: refs/tags/${{ needs.parse_version.outputs.tag }} - name: Setup JDK - uses: actions/setup-java@v4 + uses: actions/setup-java@v6 with: - java-version: 21.0.1 + java-version: '25' distribution: 'temurin' + check-latest: true - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 + uses: gradle/actions/setup-gradle@v6.4.0 + with: + cache-provider: basic - name: Make an application for Windows if: (matrix.os == 'windows-latest') run: .\gradlew.bat "-Papp.version=${{ needs.parse_version.outputs.full_version }}" make @@ -61,12 +83,12 @@ jobs: 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') + if: (matrix.os == 'macos-15-intel') 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') + if: (matrix.os == 'macos-15') 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" @@ -83,17 +105,17 @@ jobs: 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 + uses: actions/upload-artifact@v7.0.2 # https://github.com/actions/upload-artifact with: name: ${{ env.asset_name }} path: ${{ env.asset_path }} compression-level: 0 release: runs-on: ubuntu-latest - needs: make + needs: [make, parse_version] steps: - name: Download Artifacts - uses: actions/download-artifact@v4.1.8 + uses: actions/download-artifact@v8.0.2 with: path: build/distribution/ - name: Create Release @@ -101,5 +123,6 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token with: + tag_name: ${{ needs.parse_version.outputs.tag }} draft: true # ドラフトリリースとし、公開は手動で行う files: build/distribution/** diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index a5c8a09..5dfb495 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -12,13 +12,18 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout source - uses: actions/checkout@v4 + uses: actions/checkout@v7.0.1 - name: Setup JDK - uses: actions/setup-java@v4 + uses: actions/setup-java@v6 with: - java-version: 21.0.1 + java-version: '25' distribution: 'temurin' + check-latest: true - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 + uses: gradle/actions/setup-gradle@v6.4.0 + with: + cache-provider: basic - name: Test with Gradle - run: ./gradlew test \ No newline at end of file + run: | + ./gradlew -p buildSrc test + ./gradlew test 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..ad813ea 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,55 @@ ### チャットメッセージのフィルタリング * 特定のユーザーのメッセージを非表示にしたり、正規表現を使用してフィルタリングできます。 +## 資格情報の保存 + +資格情報の暗号化鍵は、macOSではキーチェーン、WindowsではCredential Manager、LinuxではSecret Serviceを使って保護します。 +Linuxではlibsecret 0.19.0以上と、ログイン中のセッションD-Busで利用できるSecret Serviceが必要です。 +画面表示にはGTK 3.20以上とXTestライブラリも必要です。DEBはこれらに加え、対象JavaFXのネイティブ資源から読み取ったglibcの最小版を宣言します。現在のJavaFX 27.0.1ではARM64版がglibc 2.38以上を要求します。 +OSの保管先を利用できない場合は保存・復号を失敗として扱い、共通パスワードへ切り替えません。 + +旧既定パスワード形式の鍵ファイルは、初回の鍵利用時にOS保護形式へ移行します。 +鍵ファイルだけを別環境へコピーしても復号できません。JVMプロパティ`key.manager.password`を明示した場合は、従来のパスワード方式を維持します。 + +## 開発とビルド + +JDK 25 をインストールしてください。コンパイル・テスト・`jdeps`・`jpackage` は、 +Gradle の Java toolchain で同じ Java 25 を選択します。Gradle Wrapper は 9.8.2 です。 +Java・JavaFX・テストライブラリのバージョンは `gradle/libs.versions.toml` で管理します。 +ヘッドレステストは JavaFX 27 の描画基盤を使います。 + +構築・所有・終了順は[アーキテクチャ](docs/architecture.md)、改善の進捗と検証範囲は[技術的負債の監査](docs/technical-debt.md)を参照してください。 + +```bash +./gradlew -p buildSrc test # パッケージ生成ロジックのテスト +./gradlew test # ヘッドレスで全アプリテスト +./gradlew -Pheadless=false test # デスクトップ上の実ウインドウを使うテスト +./gradlew run # アプリの起動 +``` + +実macOSの連携テストは、専用の一時キーチェーンへ合成データを書き込み、最後に削除します。通常のテストからは除外し、明示指定した場合だけ実行します。 + +```bash +./gradlew -PosKeychainTests=true test --tests '*MacKeychainSecretStoreTest' +``` + +配布物は生成する OS 上でビルドします。`make` は Windows では EXE、macOS では DMG、 +Linux では DEB を生成します。OS ごとの外部ツールは [JDK 25 の jpackage 仕様](https://docs.oracle.com/en/java/javase/25/docs/specs/man/jpackage.html)を参照してください。 + +```bash +./gradlew "-Papp.version=1.2.3-rc.1" appImage # build/app-image に実行イメージを生成 +./gradlew "-Papp.version=1.2.3-rc.1" make # build/app にインストーラーを生成 +``` + +版番号は `major.minor.patch` と任意の `-suffix` / `+metadata` です。 +ネイティブの版番号には数値3要素を使い、アプリには完全な版番号を渡します。 +配布入力は専用ディレクトリへ同期し、生成成功後に直前の出力を置換します。 +生成失敗時には直前の出力を保持し、置換の復旧にも失敗した場合はバックアップの場所を報告します。 +公開・署名証明書による署名・公証は別途行います。 + +GitHub Actions の手動配布ビルドでは、既存の `v1.2.3` 形式のタグを指定します。 +指定タグからビルドし、同じタグのドラフトリリースを作成します。 + ## License -詳細は [LICENSE](LICENSE.md) を参照してください。 \ No newline at end of file +詳細は [LICENSE](LICENSE.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..bc04fb2 100644 --- a/docs/external-libraries.md +++ b/docs/external-libraries.md @@ -12,19 +12,15 @@ URL: https://github.com/hfg-gmuend/openmoji License: CC BY-SA 4.0 ``` -## License +## OS-provided secret storage -```yaml -Name: Apollo GraphQL Java libraries -URL: https://github.com/apollographql/apollo-kotlin -License: MIT -``` +The application uses OS-provided native services through the JDK Foreign Function and Memory API. These native libraries are not bundled in the application image. -```yaml -Name: UUID (com.benasher44) -URL: https://github.com/benasher44/uuid -License: MIT -``` +- macOS: Security and CoreFoundation frameworks for Keychain access. +- Windows: [Credential Manager](https://learn.microsoft.com/en-us/windows/win32/api/wincred/nf-wincred-credreadw), provided by Advapi32.dll. +- Linux: [libsecret binary API](https://gnome.pages.gitlab.gnome.org/libsecret/func.password_storev_binary_sync.html) (0.19.0 or later), GLib, and a Secret Service available on the existing session D-Bus. The DEB declares a dependency on [libsecret-1-0](https://packages.debian.org/trixie/libsecret-1-0). + +## License ```yaml Name: JCommander @@ -92,18 +88,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 +100,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 +130,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 +142,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 +185,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 249e5832f090a2944b7473328c07c9755baa3196..9fa7f288283f81eec4952784c271abd7e0938dee 100644 GIT binary patch literal 48749 zcma&OWmH_-wk?cn;V!}5-QC?ScmajGYe;Z+3GVI$cX#&$ClK7-AN!ow?)Tol@9ytZ zYpZ@#TYu)5WA;9JA7hq^JR}q*7#tiN7#JAo$MgSvP{H8A6eTr88D*8Em=$EjC6&}A zH8r5Y!2fz>U02U#l?(gJbWM+?xy1>dlx+LyS(BfdX^AFxGJ8U2nvfU;4Nx4NK}2`y z?MV=4jb>Eo&P_0FDL*_g(B*N;1NlbI_t0W?+_`1|)}VZc+)j4pR8fmNBBH1e`Df0JO} zzN@#As4%03;W^B;Jq|jdQ%$el(ah)4ic-SrE8j@BX1H|PmfUVnb`M-!Maw}vlnB-< zm$QvEDUidyLK07uE?e{4r)LTR<@y7Eh*0FjjSZseKnaESu`YKnef+9^i z40Nb`Lpj~w)7ND^*&{KY&q}VXU7eNRKu&|OrY3Nb&!0}h06X_) zg)zK9u-@~uVL32XREM+De3*%wgU*J@i7|j4mz!@YzD{_F+{q0U9N$LT-|4I?lotNA zAu>QwAr%TsJlT7>wy8bIx)yb|> z-nF9tw;6zSL}|%D=J?WmKrXGotgP(_$c5cB=;{A@gO3yIo?be z3yrViT1>n}n1AnnkK^hb3SukF6#j!u20jHAOAR|Ui>UN8a&W4Gyl-DY$2jPCa&79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! z(2!VjP&{Z1w+%eUq^ /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..4f0bd19 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,19 +19,10 @@ 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)); @@ -42,14 +33,4 @@ public static void clipURL(String url) { 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/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/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..706aef4 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,118 @@ 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) { + 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..2e55981 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,31 +100,36 @@ 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) { + credentialManager.getCredentials().clear(); + credentialManager.addCredential(identityProvider.getProviderName(), refreshed); + credentialManager.save(); + this.credential = refreshed; + } + return refreshed; } - 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() { @@ -107,6 +141,7 @@ public CredentialManager getCredentialManager() { } 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 +158,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..71358b7 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,83 @@ 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(); 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; 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(); 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(); 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(); var onlineEvent = new StreamStateUpdateEvent(channel, stream); eventPublishers.submit(onlineEvent); } 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/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..92a8b30 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,47 @@ package com.github.k7t3.tcv.prefs; -import com.github.k7t3.tcv.view.chat.ChatFont; +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(Font.getDefault().getFamily(), 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 +68,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