All Downloads are FREE. Search and download functionalities are using the official Maven repository.

gcp4zio.gcs.GCSClient.scala Maven / Gradle / Ivy

The newest version!
package gcp4zio.gcs

import com.google.auth.oauth2.{GoogleCredentials, ServiceAccountCredentials}
import com.google.cloud.storage.{Storage, StorageOptions}
import zio.{RIO, Scope, Task, ZIO}
import java.io.FileInputStream

object GCSClient {

  private def getStorage(path: String): Storage = {
    val credentials: GoogleCredentials = ServiceAccountCredentials.fromStream(new FileInputStream(path))
    StorageOptions.newBuilder().setCredentials(credentials).build().getService
  }

  /** @param url
    *   Host url of mock GCS server
    * @param project
    *   GCP Project Id for mock GCS server
    * @return
    *   Task[Storage]
    */
  def testClient(url: String, project: String): Task[Storage] =
    ZIO.attempt(StorageOptions.newBuilder().setProjectId(project).setHost(url).build().getService)

  /** Returns AutoCloseable Storage object wrapped in ZIO
    * @param path
    *   Optional path to Service Account Credentials file
    * @return
    *   RIO[Scope, Storage]
    */
  def apply(path: Option[String]): RIO[Scope, Storage] = ZIO.fromAutoCloseable(ZIO.attempt {
    val envPath: String = sys.env.getOrElse("GOOGLE_APPLICATION_CREDENTIALS", "NOT_SET_IN_ENV")

    path match {
      case Some(p) =>
        logger.info("Using credentials from values passed in function for GCS Client")
        getStorage(p)
      case None =>
        if (envPath == "NOT_SET_IN_ENV") {
          logger.info("Using credentials from local sdk for GCS Client")
          StorageOptions.newBuilder().build().getService
        } else {
          logger.info("Using credentials from GOOGLE_APPLICATION_CREDENTIALS for GCS Client")
          getStorage(envPath)
        }
    }
  })
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy