|
| 1 | +/* |
| 2 | + * Copyright 2022-2023 Optimizely |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +using System; |
| 18 | +using System.Collections.Generic; |
| 19 | +using System.Linq; |
| 20 | +using OptimizelySDK.Logger; |
| 21 | + |
| 22 | +namespace OptimizelySDK.Odp |
| 23 | +{ |
| 24 | + /// <summary> |
| 25 | + /// Concrete implementation that schedules connections to ODP for audience segmentation |
| 26 | + /// and caches the results. |
| 27 | + /// </summary> |
| 28 | + public class OdpSegmentManager : IOdpSegmentManager |
| 29 | + { |
| 30 | + /// <summary> |
| 31 | + /// Logger used to record messages that occur within the ODP client |
| 32 | + /// </summary> |
| 33 | + private readonly ILogger _logger; |
| 34 | + |
| 35 | + /// <summary> |
| 36 | + /// ODP segment API manager to communicate with ODP |
| 37 | + /// </summary> |
| 38 | + private readonly IOdpSegmentApiManager _apiManager; |
| 39 | + |
| 40 | + /// <summary> |
| 41 | + /// ODP configuration containing the connection parameters |
| 42 | + /// </summary> |
| 43 | + private volatile OdpConfig _odpConfig; |
| 44 | + |
| 45 | + /// <summary> |
| 46 | + /// Cached segments |
| 47 | + /// </summary> |
| 48 | + private readonly ICache<List<string>> _segmentsCache; |
| 49 | + |
| 50 | + public OdpSegmentManager(IOdpSegmentApiManager apiManager, |
| 51 | + ICache<List<string>> cache = null, |
| 52 | + ILogger logger = null |
| 53 | + ) |
| 54 | + { |
| 55 | + _apiManager = apiManager; |
| 56 | + _logger = logger ?? new DefaultLogger(); |
| 57 | + |
| 58 | + _segmentsCache = |
| 59 | + cache ?? new LruCache<List<string>>(Constants.DEFAULT_MAX_CACHE_SIZE, |
| 60 | + TimeSpan.FromSeconds(Constants.DEFAULT_CACHE_SECONDS), logger); |
| 61 | + } |
| 62 | + |
| 63 | + public OdpSegmentManager(IOdpSegmentApiManager apiManager, |
| 64 | + int? cacheSize = null, |
| 65 | + TimeSpan? itemTimeout = null, |
| 66 | + ILogger logger = null |
| 67 | + ) |
| 68 | + { |
| 69 | + _apiManager = apiManager; |
| 70 | + _logger = logger ?? new DefaultLogger(); |
| 71 | + |
| 72 | + _segmentsCache = new LruCache<List<string>>(cacheSize, itemTimeout, logger); |
| 73 | + } |
| 74 | + |
| 75 | + /// <summary> |
| 76 | + /// Attempts to fetch and return a list of a user's qualified segments from the local segments cache. |
| 77 | + /// If no cached data exists for the target user, this fetches and caches data from the ODP server instead. |
| 78 | + /// </summary> |
| 79 | + /// <param name="fsUserId">The FS User ID identifying the user</param> |
| 80 | + /// <param name="options">An array of OptimizelySegmentOption used to ignore and/or reset the cache.</param> |
| 81 | + /// <returns>Qualified segments for the user from the cache or the ODP server if the cache is empty.</returns> |
| 82 | + public List<string> FetchQualifiedSegments(string fsUserId, |
| 83 | + List<OdpSegmentOption> options = null |
| 84 | + ) |
| 85 | + { |
| 86 | + if (_odpConfig == null || !_odpConfig.IsReady()) |
| 87 | + { |
| 88 | + _logger.Log(LogLevel.WARN, Constants.ODP_NOT_INTEGRATED_MESSAGE); |
| 89 | + return null; |
| 90 | + } |
| 91 | + |
| 92 | + if (!_odpConfig.HasSegments()) |
| 93 | + { |
| 94 | + _logger.Log(LogLevel.DEBUG, |
| 95 | + "No Segments are used in the project, Not Fetching segments. Returning empty list."); |
| 96 | + return new List<string>(); |
| 97 | + } |
| 98 | + |
| 99 | + options = options ?? new List<OdpSegmentOption>(); |
| 100 | + |
| 101 | + List<string> qualifiedSegments; |
| 102 | + var cacheKey = GetCacheKey(OdpUserKeyType.FS_USER_ID.ToString().ToLower(), fsUserId); |
| 103 | + |
| 104 | + if (options.Contains(OdpSegmentOption.RESET_CACHE)) |
| 105 | + { |
| 106 | + _segmentsCache.Reset(); |
| 107 | + } |
| 108 | + |
| 109 | + if (!options.Contains(OdpSegmentOption.IGNORE_CACHE)) |
| 110 | + { |
| 111 | + qualifiedSegments = _segmentsCache.Lookup(cacheKey); |
| 112 | + if (qualifiedSegments != null) |
| 113 | + { |
| 114 | + _logger.Log(LogLevel.DEBUG, "ODP Cache Hit. Returning segments from Cache."); |
| 115 | + return qualifiedSegments; |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + _logger.Log(LogLevel.DEBUG, "ODP Cache Miss. Making a call to ODP Server."); |
| 120 | + |
| 121 | + qualifiedSegments = _apiManager.FetchSegments( |
| 122 | + _odpConfig.ApiKey, |
| 123 | + _odpConfig.ApiHost, |
| 124 | + OdpUserKeyType.FS_USER_ID, |
| 125 | + fsUserId, |
| 126 | + _odpConfig.SegmentsToCheck)?. |
| 127 | + ToList(); |
| 128 | + |
| 129 | + if (qualifiedSegments != null && !options.Contains(OdpSegmentOption.IGNORE_CACHE)) |
| 130 | + { |
| 131 | + _segmentsCache.Save(cacheKey, qualifiedSegments); |
| 132 | + } |
| 133 | + |
| 134 | + return qualifiedSegments; |
| 135 | + } |
| 136 | + |
| 137 | + /// <summary> |
| 138 | + /// Creates a key used to identify which user fetchQualifiedSegments should lookup and save to in the segments cache |
| 139 | + /// </summary> |
| 140 | + /// <param name="userKey">Always 'fs_user_id' (parameter for consistency with other SDKs)</param> |
| 141 | + /// <param name="userValue">Arbitrary string representing the Optimizely Feature Experimentation user ID</param> |
| 142 | + /// <returns>Concatenates inputs and returns the string "{userKey}-$-{userValue}"</returns> |
| 143 | + private static string GetCacheKey(string userKey, string userValue) |
| 144 | + { |
| 145 | + return $"{userKey}-$-{userValue}"; |
| 146 | + } |
| 147 | + |
| 148 | + /// <summary> |
| 149 | + /// Update the ODP configuration settings being used by the Segment Manager |
| 150 | + /// </summary> |
| 151 | + /// <param name="odpConfig">New ODP Configuration to apply</param> |
| 152 | + public void UpdateSettings(OdpConfig odpConfig) |
| 153 | + { |
| 154 | + _odpConfig = odpConfig; |
| 155 | + } |
| 156 | + |
| 157 | + /// <summary> |
| 158 | + /// Reset/clear the segments cache |
| 159 | + /// </summary> |
| 160 | + public void ResetCache() |
| 161 | + { |
| 162 | + _segmentsCache.Reset(); |
| 163 | + } |
| 164 | + |
| 165 | + /// <summary> |
| 166 | + /// For Testing Only: Retrieve the current segment cache |
| 167 | + /// </summary> |
| 168 | + internal ICache<List<string>> SegmentsCacheForTesting => _segmentsCache; |
| 169 | + } |
| 170 | +} |
0 commit comments