|
| 1 | +package jenkins.plugins.slack.cache; |
| 2 | + |
| 3 | +import com.github.benmanes.caffeine.cache.Caffeine; |
| 4 | +import com.github.benmanes.caffeine.cache.LoadingCache; |
| 5 | +import hudson.AbortException; |
| 6 | +import java.io.IOException; |
| 7 | +import java.time.Duration; |
| 8 | +import java.util.HashMap; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.concurrent.CompletableFuture; |
| 11 | +import java.util.concurrent.CompletionException; |
| 12 | +import java.util.concurrent.ExecutionException; |
| 13 | +import java.util.logging.Logger; |
| 14 | +import jenkins.model.Jenkins; |
| 15 | +import jenkins.plugins.slack.HttpClient; |
| 16 | +import org.apache.http.Header; |
| 17 | +import org.apache.http.HttpEntity; |
| 18 | +import org.apache.http.HttpResponse; |
| 19 | +import org.apache.http.HttpStatus; |
| 20 | +import org.apache.http.client.ResponseHandler; |
| 21 | +import org.apache.http.client.ServiceUnavailableRetryStrategy; |
| 22 | +import org.apache.http.client.methods.RequestBuilder; |
| 23 | +import org.apache.http.impl.client.CloseableHttpClient; |
| 24 | +import org.apache.http.impl.client.HttpClientBuilder; |
| 25 | +import org.apache.http.protocol.HttpContext; |
| 26 | +import org.apache.http.util.EntityUtils; |
| 27 | +import org.json.JSONArray; |
| 28 | +import org.json.JSONObject; |
| 29 | + |
| 30 | +public class SlackChannelIdCache { |
| 31 | + |
| 32 | + private static final String UPLOAD_FAILED_TEMPLATE = "Failed to retrieve channel names. Response: "; |
| 33 | + private static final Logger logger = Logger.getLogger(SlackChannelIdCache.class.getName()); |
| 34 | + |
| 35 | + // cache that includes all channel names and IDs for each workspace used |
| 36 | + private static final LoadingCache<String, Map<String, String>> CHANNEL_METADATA_CACHE = Caffeine.newBuilder() |
| 37 | + .maximumSize(100) |
| 38 | + .refreshAfterWrite(Duration.ofHours(24)) |
| 39 | + .build(SlackChannelIdCache::populateCache); |
| 40 | + private static final int MAX_RETRIES = 10; |
| 41 | + |
| 42 | + private static Map<String, String> populateCache(String token) { |
| 43 | + HttpClientBuilder closeableHttpClientBuilder = HttpClient.getCloseableHttpClientBuilder(Jenkins.get().getProxy()) |
| 44 | + .setRetryHandler((exception, executionCount, context) -> executionCount <= MAX_RETRIES) |
| 45 | + .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() { |
| 46 | + |
| 47 | + long retryInterval; |
| 48 | + |
| 49 | + @Override |
| 50 | + public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) { |
| 51 | + boolean shouldRetry = executionCount <= MAX_RETRIES && |
| 52 | + response.getStatusLine().getStatusCode() == HttpStatus.SC_TOO_MANY_REQUESTS; |
| 53 | + if (shouldRetry) { |
| 54 | + Header firstHeader = response.getFirstHeader("Retry-After"); |
| 55 | + if (firstHeader != null) { |
| 56 | + retryInterval = Long.parseLong(firstHeader.getValue()) * 1000L; |
| 57 | + logger.info(String.format("Rate limited by Slack, retrying in %dms", retryInterval)); |
| 58 | + } |
| 59 | + } |
| 60 | + return shouldRetry; |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public long getRetryInterval() { |
| 65 | + return retryInterval; |
| 66 | + } |
| 67 | + }); |
| 68 | + try (CloseableHttpClient client = closeableHttpClientBuilder.build()) { |
| 69 | + return convertChannelNameToId(client, token, new HashMap<>(), null); |
| 70 | + } catch (IOException e) { |
| 71 | + throw new RuntimeException(e); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + public static String getChannelId(String botUserToken, String channelName) throws ExecutionException, InterruptedException, AbortException { |
| 76 | + Map<String, String> channelNameToIdMap = CHANNEL_METADATA_CACHE.get(botUserToken); |
| 77 | + String channelId = channelNameToIdMap.get(channelName); |
| 78 | + |
| 79 | + // most likely is that a new channel has been created since the last cache refresh |
| 80 | + // or a typo in the channel name, a bit risky in larger workspaces but shouldn't happen too often |
| 81 | + if (channelId == null) { |
| 82 | + try { |
| 83 | + CompletableFuture<Map<String, String>> newResult = CHANNEL_METADATA_CACHE.refresh(botUserToken); |
| 84 | + channelNameToIdMap = newResult.get(); |
| 85 | + } catch (CompletionException e) { |
| 86 | + throw new AbortException("Failed uploading file to slack, channel not found: " + channelName + ", error: " + e.getMessage()); |
| 87 | + } |
| 88 | + |
| 89 | + channelId = channelNameToIdMap.get(channelName); |
| 90 | + } |
| 91 | + |
| 92 | + return channelId; |
| 93 | + } |
| 94 | + |
| 95 | + private static Map<String, String> convertChannelNameToId(CloseableHttpClient client, String token, Map<String, String> channels, String cursor) throws IOException { |
| 96 | + RequestBuilder requestBuilder = RequestBuilder.get("https://slack.com/api/conversations.list") |
| 97 | + .addHeader("Authorization", "Bearer " + token) |
| 98 | + .addParameter("exclude_archived", "true") |
| 99 | + .addParameter("types", "public_channel,private_channel"); |
| 100 | + |
| 101 | + if (cursor != null) { |
| 102 | + requestBuilder.addParameter("cursor", cursor); |
| 103 | + } |
| 104 | + ResponseHandler<JSONObject> standardResponseHandler = getStandardResponseHandler(); |
| 105 | + JSONObject result = client.execute(requestBuilder.build(), standardResponseHandler); |
| 106 | + |
| 107 | + if (!result.getBoolean("ok")) { |
| 108 | + logger.warning("Couldn't convert channel name to ID in Slack: " + result); |
| 109 | + return channels; |
| 110 | + } |
| 111 | + |
| 112 | + JSONArray channelsArray = result.getJSONArray("channels"); |
| 113 | + for (int i = 0; i < channelsArray.length(); i++) { |
| 114 | + JSONObject channel = channelsArray.getJSONObject(i); |
| 115 | + |
| 116 | + String channelName = channel.getString("name"); |
| 117 | + String channelId = channel.getString("id"); |
| 118 | + |
| 119 | + channels.put(channelName, channelId); |
| 120 | + } |
| 121 | + |
| 122 | + cursor = result.getJSONObject("response_metadata").getString("next_cursor"); |
| 123 | + if (cursor != null && !cursor.isEmpty()) { |
| 124 | + return convertChannelNameToId(client, token, channels, cursor); |
| 125 | + } |
| 126 | + |
| 127 | + return channels; |
| 128 | + } |
| 129 | + |
| 130 | + private static ResponseHandler<JSONObject> getStandardResponseHandler() { |
| 131 | + return response -> { |
| 132 | + int status = response.getStatusLine().getStatusCode(); |
| 133 | + if (status >= 200 && status < 300) { |
| 134 | + HttpEntity entity = response.getEntity(); |
| 135 | + return entity != null ? new JSONObject(EntityUtils.toString(entity)) : null; |
| 136 | + } else { |
| 137 | + String errorMessage = UPLOAD_FAILED_TEMPLATE + status + " " + EntityUtils.toString(response.getEntity()); |
| 138 | + throw new HttpStatusCodeException(response.getStatusLine().getStatusCode(), errorMessage); |
| 139 | + } |
| 140 | + }; |
| 141 | + } |
| 142 | + |
| 143 | + public static class HttpStatusCodeException extends RuntimeException { |
| 144 | + private final int statusCode; |
| 145 | + |
| 146 | + public HttpStatusCodeException(int statusCode, String message) { |
| 147 | + super(message); |
| 148 | + this.statusCode = statusCode; |
| 149 | + } |
| 150 | + |
| 151 | + public int getStatusCode() { |
| 152 | + return statusCode; |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + public static void clearCache() { |
| 157 | + CHANNEL_METADATA_CACHE.invalidateAll(); |
| 158 | + } |
| 159 | +} |
0 commit comments