Skip to content

Instantly share code, notes, and snippets.

@kailuowang
Last active March 27, 2021 03:08
Show Gist options
  • Save kailuowang/d58f57f4d273b40645e3a475e1ef4065 to your computer and use it in GitHub Desktop.
Save kailuowang/d58f57f4d273b40645e3a475e1ef4065 to your computer and use it in GitHub Desktop.
Create Google Cloud Client from key file stored on S3
import cats.effect.{Resource, Sync}
import cats.implicits._
import com.google.api.gax.core.FixedCredentialsProvider
import com.google.auth.oauth2.GoogleCredentials
import com.google.cloud.language.v1.{LanguageServiceClient, LanguageServiceSettings}
object GoogleClient {
case object S3ObjectNotFound extends RuntimeException
def s3GoogleCredential[F[_]](
cfg: S3Config
)(implicit F: Sync[F]
): F[GoogleCredentials] = {
import awscala._
import s3._
import cfg._
F.defer {
implicit val s3 = S3(accessKeyId, secretKey)(Region(region))
s3.bucket(bucketName)
.flatMap(_.getObject(objectName))
.liftTo[F](S3ObjectNotFound)
.flatMap { obj =>
F.delay(
GoogleCredentials
.fromStream(obj.content)
)
}
}
}
def languageClientFrom[F[_]](cred: GoogleCredentials)(implicit F: Sync[F]) =
Resource.make {
F.delay(
LanguageServiceClient.create(
LanguageServiceSettings
.newBuilder()
.setCredentialsProvider(
FixedCredentialsProvider.create(cred)
)
.build()
)
)
}(c => F.delay(c.shutdown()))
def languageClient[F[_]: Sync]: Resource[F, LanguageServiceClient] =
Resource
.liftF(loadConfig[F])
.evalMap(s3GoogleCredential(_))
.flatMap(languageClientFrom(_))
case class S3Config(
accessKeyId: String,
secretKey: String,
region: String,
bucketName: String,
objectName: String)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment