|
| 1 | +package gg.grounds.permissions.invalidation |
| 2 | + |
| 3 | +import io.nats.client.Connection |
| 4 | +import io.nats.client.Dispatcher |
| 5 | +import io.nats.client.Nats |
| 6 | +import io.nats.client.Options |
| 7 | +import java.nio.file.Files |
| 8 | +import java.nio.file.Path |
| 9 | +import java.time.Duration |
| 10 | +import java.util.UUID |
| 11 | +import java.util.concurrent.Executors |
| 12 | +import java.util.concurrent.ScheduledExecutorService |
| 13 | +import java.util.concurrent.TimeUnit |
| 14 | +import java.util.concurrent.atomic.AtomicBoolean |
| 15 | +import org.slf4j.Logger |
| 16 | + |
| 17 | +class NatsPermissionSnapshotInvalidationSubscriber |
| 18 | +private constructor( |
| 19 | + private val config: PermissionSnapshotInvalidationConfig, |
| 20 | + private val logger: Logger, |
| 21 | + private val codec: PermissionSnapshotInvalidationCodec, |
| 22 | + private val connectionFactory: PermissionSnapshotInvalidationConnectionFactory = |
| 23 | + JnatsPermissionSnapshotInvalidationConnectionFactory(), |
| 24 | + private val retryScheduler: PermissionSnapshotInvalidationRetryScheduler = |
| 25 | + ExecutorPermissionSnapshotInvalidationRetryScheduler(), |
| 26 | + @Suppress("UNUSED_PARAMETER") marker: Unit, |
| 27 | +) : AutoCloseable { |
| 28 | + constructor( |
| 29 | + config: PermissionSnapshotInvalidationConfig, |
| 30 | + logger: Logger, |
| 31 | + codec: PermissionSnapshotInvalidationCodec = PermissionSnapshotInvalidationCodec(), |
| 32 | + ) : this(config, logger, codec, marker = Unit) |
| 33 | + |
| 34 | + internal constructor( |
| 35 | + config: PermissionSnapshotInvalidationConfig, |
| 36 | + connectionFactory: PermissionSnapshotInvalidationConnectionFactory, |
| 37 | + retryScheduler: PermissionSnapshotInvalidationRetryScheduler, |
| 38 | + logger: Logger, |
| 39 | + codec: PermissionSnapshotInvalidationCodec = PermissionSnapshotInvalidationCodec(), |
| 40 | + ) : this(config, logger, codec, connectionFactory, retryScheduler, Unit) |
| 41 | + |
| 42 | + private val started = AtomicBoolean() |
| 43 | + private val closed = AtomicBoolean() |
| 44 | + private val lifecycleLock = Any() |
| 45 | + |
| 46 | + @Volatile private var connection: PermissionSnapshotInvalidationConnection? = null |
| 47 | + |
| 48 | + fun start(handler: (UUID) -> Unit) { |
| 49 | + synchronized(lifecycleLock) { |
| 50 | + if (closed.get() || !started.compareAndSet(false, true)) return |
| 51 | + try { |
| 52 | + retryScheduler.execute { connect(handler) } |
| 53 | + } catch (_: RuntimeException) { |
| 54 | + if (!closed.get()) { |
| 55 | + logger.warn( |
| 56 | + "Failed to schedule permission snapshot invalidation subscription " + |
| 57 | + "(subject={}, reason=subscription_scheduling_failed)", |
| 58 | + config.subject, |
| 59 | + ) |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + private fun connect(handler: (UUID) -> Unit) { |
| 66 | + if (closed.get()) return |
| 67 | + |
| 68 | + var openedConnection: PermissionSnapshotInvalidationConnection? = null |
| 69 | + try { |
| 70 | + val tokenSupplier = |
| 71 | + when (val credentials = config.credentials) { |
| 72 | + PermissionSnapshotInvalidationCredentials.Anonymous -> null |
| 73 | + PermissionSnapshotInvalidationCredentials.InvalidTokenFile -> |
| 74 | + throw PermissionSnapshotNatsTokenException( |
| 75 | + "invalid_token_file_configuration" |
| 76 | + ) |
| 77 | + is PermissionSnapshotInvalidationCredentials.TokenFile -> |
| 78 | + FileNatsTokenSupplier(credentials.path) |
| 79 | + } |
| 80 | + tokenSupplier?.get()?.fill('\u0000') |
| 81 | + openedConnection = connectionFactory.connect(config, tokenSupplier) |
| 82 | + openedConnection.subscribe(config.subject) { payload -> consume(payload, handler) } |
| 83 | + val subscribed = |
| 84 | + synchronized(lifecycleLock) { |
| 85 | + if (closed.get()) { |
| 86 | + false |
| 87 | + } else { |
| 88 | + connection = openedConnection |
| 89 | + logger.debug( |
| 90 | + "Subscribed to permission snapshot invalidations successfully " + |
| 91 | + "(subject={})", |
| 92 | + config.subject, |
| 93 | + ) |
| 94 | + true |
| 95 | + } |
| 96 | + } |
| 97 | + if (!subscribed) { |
| 98 | + closeQuietly(openedConnection) |
| 99 | + return |
| 100 | + } |
| 101 | + } catch (exception: PermissionSnapshotNatsTokenException) { |
| 102 | + subscriptionFailed(openedConnection, handler, exception.reason) |
| 103 | + } catch (_: Exception) { |
| 104 | + subscriptionFailed(openedConnection, handler, "nats_connection_failed") |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + private fun subscriptionFailed( |
| 109 | + openedConnection: PermissionSnapshotInvalidationConnection?, |
| 110 | + handler: (UUID) -> Unit, |
| 111 | + reason: String, |
| 112 | + ) { |
| 113 | + closeQuietly(openedConnection) |
| 114 | + logger.warn( |
| 115 | + "Failed to subscribe to permission snapshot invalidations " + "(subject={}, reason={})", |
| 116 | + config.subject, |
| 117 | + reason, |
| 118 | + ) |
| 119 | + retry(handler) |
| 120 | + } |
| 121 | + |
| 122 | + private fun consume(payload: ByteArray, handler: (UUID) -> Unit) { |
| 123 | + val decoded = codec.decodeResult(payload) |
| 124 | + val event = decoded.event |
| 125 | + if (event == null) { |
| 126 | + logger.debug( |
| 127 | + "Rejected permission snapshot invalidation " + |
| 128 | + "(reason=${decoded.reason ?: "malformed_event"})" |
| 129 | + ) |
| 130 | + return |
| 131 | + } |
| 132 | + |
| 133 | + try { |
| 134 | + handler(event.playerId) |
| 135 | + } catch (_: RuntimeException) { |
| 136 | + logger.warn( |
| 137 | + "Failed to handle permission snapshot invalidation " + |
| 138 | + "(playerId={}, reason=handler_failed)", |
| 139 | + event.playerId, |
| 140 | + ) |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + private fun retry(handler: (UUID) -> Unit) { |
| 145 | + synchronized(lifecycleLock) { |
| 146 | + if (closed.get()) return |
| 147 | + try { |
| 148 | + retryScheduler.schedule(INITIAL_RETRY_DELAY) { connect(handler) } |
| 149 | + } catch (_: RuntimeException) { |
| 150 | + if (!closed.get()) { |
| 151 | + logger.warn( |
| 152 | + "Failed to schedule permission snapshot invalidation retry " + |
| 153 | + "(subject={}, reason=retry_scheduling_failed)", |
| 154 | + config.subject, |
| 155 | + ) |
| 156 | + } |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + override fun close() { |
| 162 | + val activeConnection = |
| 163 | + synchronized(lifecycleLock) { |
| 164 | + if (!closed.compareAndSet(false, true)) return |
| 165 | + connection.also { connection = null } |
| 166 | + } |
| 167 | + try { |
| 168 | + retryScheduler.close() |
| 169 | + } catch (_: RuntimeException) { |
| 170 | + logger.warn( |
| 171 | + "Failed to close permission snapshot invalidation scheduler " + |
| 172 | + "(subject={}, reason=scheduler_close_failed)", |
| 173 | + config.subject, |
| 174 | + ) |
| 175 | + } |
| 176 | + closeQuietly(activeConnection) |
| 177 | + } |
| 178 | + |
| 179 | + private fun closeQuietly(connection: PermissionSnapshotInvalidationConnection?) { |
| 180 | + try { |
| 181 | + connection?.close() |
| 182 | + } catch (_: Exception) { |
| 183 | + logger.warn( |
| 184 | + "Failed to close permission snapshot invalidation connection " + |
| 185 | + "(subject={}, reason=nats_close_failed)", |
| 186 | + config.subject, |
| 187 | + ) |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + private companion object { |
| 192 | + val INITIAL_RETRY_DELAY: Duration = Duration.ofSeconds(5) |
| 193 | + } |
| 194 | +} |
| 195 | + |
| 196 | +internal fun interface NatsTokenSupplier { |
| 197 | + fun get(): CharArray |
| 198 | +} |
| 199 | + |
| 200 | +internal class FileNatsTokenSupplier(private val tokenFile: Path) : NatsTokenSupplier { |
| 201 | + override fun get(): CharArray { |
| 202 | + val token = |
| 203 | + try { |
| 204 | + Files.readString(tokenFile).trim() |
| 205 | + } catch (_: Exception) { |
| 206 | + throw PermissionSnapshotNatsTokenException("token_file_unavailable") |
| 207 | + } |
| 208 | + if (token.isEmpty()) { |
| 209 | + throw PermissionSnapshotNatsTokenException("token_file_empty") |
| 210 | + } |
| 211 | + return token.toCharArray() |
| 212 | + } |
| 213 | +} |
| 214 | + |
| 215 | +private class PermissionSnapshotNatsTokenException(val reason: String) : RuntimeException() |
| 216 | + |
| 217 | +internal interface PermissionSnapshotInvalidationConnectionFactory { |
| 218 | + fun connect( |
| 219 | + config: PermissionSnapshotInvalidationConfig, |
| 220 | + tokenSupplier: NatsTokenSupplier?, |
| 221 | + ): PermissionSnapshotInvalidationConnection |
| 222 | +} |
| 223 | + |
| 224 | +internal interface PermissionSnapshotInvalidationConnection : AutoCloseable { |
| 225 | + fun subscribe(subject: String, handler: (ByteArray) -> Unit) |
| 226 | +} |
| 227 | + |
| 228 | +internal class JnatsPermissionSnapshotInvalidationConnectionFactory : |
| 229 | + PermissionSnapshotInvalidationConnectionFactory { |
| 230 | + override fun connect( |
| 231 | + config: PermissionSnapshotInvalidationConfig, |
| 232 | + tokenSupplier: NatsTokenSupplier?, |
| 233 | + ): PermissionSnapshotInvalidationConnection { |
| 234 | + return JnatsPermissionSnapshotInvalidationConnection( |
| 235 | + Nats.connect(buildOptions(config, tokenSupplier)) |
| 236 | + ) |
| 237 | + } |
| 238 | + |
| 239 | + internal fun buildOptions( |
| 240 | + config: PermissionSnapshotInvalidationConfig, |
| 241 | + tokenSupplier: NatsTokenSupplier?, |
| 242 | + ): Options = |
| 243 | + Options.Builder() |
| 244 | + .server(config.natsUrl) |
| 245 | + .maxReconnects(-1) |
| 246 | + .apply { tokenSupplier?.let { supplier -> tokenSupplier(supplier::get) } } |
| 247 | + .build() |
| 248 | +} |
| 249 | + |
| 250 | +private class JnatsPermissionSnapshotInvalidationConnection(private val connection: Connection) : |
| 251 | + PermissionSnapshotInvalidationConnection { |
| 252 | + @Volatile private var dispatcher: Dispatcher? = null |
| 253 | + |
| 254 | + override fun subscribe(subject: String, handler: (ByteArray) -> Unit) { |
| 255 | + check(dispatcher == null) { "Permission snapshot invalidation subscription already exists" } |
| 256 | + dispatcher = |
| 257 | + connection |
| 258 | + .createDispatcher { message -> handler(message.data) } |
| 259 | + .apply { subscribe(subject) } |
| 260 | + } |
| 261 | + |
| 262 | + override fun close() { |
| 263 | + dispatcher?.let(connection::closeDispatcher) |
| 264 | + connection.close() |
| 265 | + } |
| 266 | +} |
| 267 | + |
| 268 | +internal interface PermissionSnapshotInvalidationRetryScheduler : AutoCloseable { |
| 269 | + fun execute(task: () -> Unit) |
| 270 | + |
| 271 | + fun schedule(delay: Duration, task: () -> Unit) |
| 272 | +} |
| 273 | + |
| 274 | +private class ExecutorPermissionSnapshotInvalidationRetryScheduler( |
| 275 | + private val executor: ScheduledExecutorService = |
| 276 | + Executors.newSingleThreadScheduledExecutor { runnable -> |
| 277 | + Thread(runnable, "permission-snapshot-invalidation").apply { isDaemon = true } |
| 278 | + } |
| 279 | +) : PermissionSnapshotInvalidationRetryScheduler { |
| 280 | + override fun execute(task: () -> Unit) { |
| 281 | + executor.execute(task) |
| 282 | + } |
| 283 | + |
| 284 | + override fun schedule(delay: Duration, task: () -> Unit) { |
| 285 | + executor.schedule(task, delay.toMillis(), TimeUnit.MILLISECONDS) |
| 286 | + } |
| 287 | + |
| 288 | + override fun close() { |
| 289 | + executor.shutdownNow() |
| 290 | + } |
| 291 | +} |
0 commit comments