|
| 1 | +// Copyright 2024 LiveKit, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import 'dart:async'; |
| 16 | + |
| 17 | +import '../support/reusable_completer.dart'; |
| 18 | +import 'jwt.dart'; |
| 19 | +import 'token_source.dart'; |
| 20 | + |
| 21 | +/// A validator function that determines if cached credentials are still valid. |
| 22 | +/// |
| 23 | +/// The validator receives the original request options and cached response, and should |
| 24 | +/// return `true` if the cached credentials are still valid for the given request. |
| 25 | +/// |
| 26 | +/// The default validator checks JWT expiration using [isResponseExpired]. |
| 27 | +typedef TokenValidator = bool Function(TokenRequestOptions options, TokenSourceResponse response); |
| 28 | + |
| 29 | +/// A tuple containing the request options and response that were cached. |
| 30 | +class TokenStoreItem { |
| 31 | + final TokenRequestOptions options; |
| 32 | + final TokenSourceResponse response; |
| 33 | + |
| 34 | + const TokenStoreItem({ |
| 35 | + required this.options, |
| 36 | + required this.response, |
| 37 | + }); |
| 38 | +} |
| 39 | + |
| 40 | +/// Protocol for storing and retrieving cached token credentials. |
| 41 | +/// |
| 42 | +/// Implement this abstract class to create custom storage solutions like |
| 43 | +/// SharedPreferences or secure storage for token caching. |
| 44 | +abstract class TokenStore { |
| 45 | + /// Store credentials in the store. |
| 46 | + /// |
| 47 | + /// This replaces any existing cached credentials with the new ones. |
| 48 | + Future<void> store(TokenRequestOptions options, TokenSourceResponse response); |
| 49 | + |
| 50 | + /// Retrieve the cached credentials. |
| 51 | + /// |
| 52 | + /// Returns the cached credentials if found, null otherwise. |
| 53 | + Future<TokenStoreItem?> retrieve(); |
| 54 | + |
| 55 | + /// Clear all stored credentials. |
| 56 | + Future<void> clear(); |
| 57 | +} |
| 58 | + |
| 59 | +/// A simple in-memory store implementation for token caching. |
| 60 | +/// |
| 61 | +/// This store keeps credentials in memory and is lost when the app is terminated. |
| 62 | +/// Suitable for development and testing. |
| 63 | +class InMemoryTokenStore implements TokenStore { |
| 64 | + TokenStoreItem? _cached; |
| 65 | + |
| 66 | + @override |
| 67 | + Future<void> store(TokenRequestOptions options, TokenSourceResponse response) async { |
| 68 | + _cached = TokenStoreItem(options: options, response: response); |
| 69 | + } |
| 70 | + |
| 71 | + @override |
| 72 | + Future<TokenStoreItem?> retrieve() async { |
| 73 | + return _cached; |
| 74 | + } |
| 75 | + |
| 76 | + @override |
| 77 | + Future<void> clear() async { |
| 78 | + _cached = null; |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +/// Default validator that checks JWT expiration using [isResponseExpired]. |
| 83 | +bool _defaultValidator(TokenRequestOptions options, TokenSourceResponse response) { |
| 84 | + return !isResponseExpired(response); |
| 85 | +} |
| 86 | + |
| 87 | +/// A token source that caches credentials from any [TokenSourceConfigurable] using a configurable store. |
| 88 | +/// |
| 89 | +/// This wrapper improves performance by avoiding redundant token requests when credentials are still valid. |
| 90 | +/// It automatically validates cached tokens and fetches new ones when needed. |
| 91 | +/// |
| 92 | +/// The cache will refetch credentials when: |
| 93 | +/// - The cached token has expired (validated via [TokenValidator]) |
| 94 | +/// - The request options have changed |
| 95 | +/// - The cache has been explicitly invalidated via [invalidate] |
| 96 | +class CachingTokenSource implements TokenSourceConfigurable { |
| 97 | + final TokenSourceConfigurable _wrapped; |
| 98 | + final TokenStore _store; |
| 99 | + final TokenValidator _validator; |
| 100 | + final Map<TokenRequestOptions, ReusableCompleter<TokenSourceResponse>> _inflightRequests = {}; |
| 101 | + |
| 102 | + /// Initialize a caching wrapper around any token source. |
| 103 | + /// |
| 104 | + /// - Parameters: |
| 105 | + /// - wrapped: The underlying token source to wrap and cache |
| 106 | + /// - store: The store implementation to use for caching (defaults to in-memory store) |
| 107 | + /// - validator: A function to determine if cached credentials are still valid (defaults to JWT expiration check) |
| 108 | + CachingTokenSource( |
| 109 | + this._wrapped, { |
| 110 | + TokenStore? store, |
| 111 | + TokenValidator? validator, |
| 112 | + }) : _store = store ?? InMemoryTokenStore(), |
| 113 | + _validator = validator ?? _defaultValidator; |
| 114 | + |
| 115 | + @override |
| 116 | + Future<TokenSourceResponse> fetch(TokenRequestOptions options) async { |
| 117 | + final existingCompleter = _inflightRequests[options]; |
| 118 | + if (existingCompleter != null && existingCompleter.isActive) { |
| 119 | + return existingCompleter.future; |
| 120 | + } |
| 121 | + |
| 122 | + final completer = existingCompleter ?? ReusableCompleter<TokenSourceResponse>(); |
| 123 | + _inflightRequests[options] = completer; |
| 124 | + final resultFuture = completer.future; |
| 125 | + |
| 126 | + try { |
| 127 | + final cached = await _store.retrieve(); |
| 128 | + if (cached != null && cached.options == options && _validator(cached.options, cached.response)) { |
| 129 | + completer.complete(cached.response); |
| 130 | + return resultFuture; |
| 131 | + } |
| 132 | + |
| 133 | + final response = await _wrapped.fetch(options); |
| 134 | + await _store.store(options, response); |
| 135 | + completer.complete(response); |
| 136 | + return resultFuture; |
| 137 | + } catch (e, stackTrace) { |
| 138 | + completer.completeError(e, stackTrace); |
| 139 | + rethrow; |
| 140 | + } finally { |
| 141 | + _inflightRequests.remove(options); |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + /// Invalidate the cached credentials, forcing a fresh fetch on the next request. |
| 146 | + Future<void> invalidate() async { |
| 147 | + await _store.clear(); |
| 148 | + } |
| 149 | + |
| 150 | + /// Get the cached credentials if one exists. |
| 151 | + Future<TokenSourceResponse?> cachedResponse() async { |
| 152 | + final cached = await _store.retrieve(); |
| 153 | + return cached?.response; |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +/// Extension to add caching capabilities to any [TokenSourceConfigurable]. |
| 158 | +extension CachedTokenSource on TokenSourceConfigurable { |
| 159 | + /// Wraps this token source with caching capabilities. |
| 160 | + /// |
| 161 | + /// The returned token source will reuse valid tokens and only fetch new ones when needed. |
| 162 | + /// |
| 163 | + /// - Parameters: |
| 164 | + /// - store: The store implementation to use for caching (defaults to in-memory store) |
| 165 | + /// - validator: A function to determine if cached credentials are still valid (defaults to JWT expiration check) |
| 166 | + /// - Returns: A caching token source that wraps this token source |
| 167 | + CachingTokenSource cached({ |
| 168 | + TokenStore? store, |
| 169 | + TokenValidator? validator, |
| 170 | + }) => |
| 171 | + CachingTokenSource( |
| 172 | + this, |
| 173 | + store: store, |
| 174 | + validator: validator, |
| 175 | + ); |
| 176 | +} |
0 commit comments