RegionalClientSupplier clientFactory()

in src/main/java/com/amazonaws/encryptionsdk/kms/KmsMasterKeyProvider.java [292:331]


    RegionalClientSupplier clientFactory() {
      if (regionalClientSupplier_ != null) {
        return regionalClientSupplier_;
      }

      // Clone again; this MKP builder might be reused to build a second MKP with different creds.
      AWSKMSClientBuilder builder =
          templateBuilder_ != null
              ? cloneClientBuilder(templateBuilder_)
              : AWSKMSClientBuilder.standard();

      ConcurrentHashMap<String, AWSKMS> clientCache = new ConcurrentHashMap<>();
      snoopClientCache(clientCache);

      return region -> {
        AWSKMS kms = clientCache.get(region);

        if (kms != null) return kms;

        // We can't just use computeIfAbsent as we need to avoid leaking KMS clients if we're asked
        // to decrypt
        // an EDK with a bogus region in its ARN. So we'll install a request handler to identify the
        // first
        // successful call, and cache it when we see that.
        SuccessfulRequestCacher cacher = new SuccessfulRequestCacher(clientCache, region);
        ArrayList<RequestHandler2> handlers = new ArrayList<>();
        if (builder.getRequestHandlers() != null) {
          handlers.addAll(builder.getRequestHandlers());
        }
        handlers.add(cacher);

        kms =
            cloneClientBuilder(builder)
                .withRegion(region)
                .withRequestHandlers(handlers.toArray(new RequestHandler2[handlers.size()]))
                .build();

        return cacher.setClient(kms);
      };
    }