unkai-0.1.0.1: src/Unkai.hs
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Unkai
-- Copyright : (c) 2015-2022 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Nadeem Bitar <nadeem@gmail.com>
-- Stability : provisional
-- Portability : non-portable (GHC extensions)
--
-- This module provides a common set of operations which can be performed against
-- the remote Google Service APIs. Typically you will import this module qualified
-- along with modules from the various @unkai-*@ libraries for services you wish
-- to communicate with.
module Unkai
( -- * Usage
-- $usage
-- * Environment
Env,
HasEnv (..),
newEnv,
newEnvWith,
-- ** Credentials
-- $credentials
Credentials (..),
AuthorizedUser (..),
ServiceAccount (..),
getApplicationDefault,
fromFilePath,
saveAuthorizedUser,
saveAuthorizedUserToWellKnownPath,
-- ** Authorization
-- $authorization
type AllowRequest,
KnownScopes,
allow,
forbid,
(!),
-- * Sending Requests
send,
sendEither,
-- ** Streaming Media
download,
downloadEither,
upload,
uploadEither,
GBody (..),
bodyContentType,
sourceBody,
getMIMEType,
-- * Service Configuration
-- $configuration
-- ** Overriding Defaults
configure,
override,
timeout,
-- ** Lenses
serviceHost,
servicePort,
servicePath,
serviceSecure,
serviceTimeout,
-- * Handling Errors
Error (..),
AuthError (..),
SerializeError (..),
ServiceError (..),
AsError (..),
AsAuthError (..),
-- * Logging
-- $logging
Logger,
LogLevel (..),
-- ** Constructing a Logger
newLogger,
-- * Constructing a HTTP Manager
newManager,
tlsManagerSettings,
-- * Running Asynchronous Actions
-- $async
-- * Compute Metadata
-- $metadata
-- * Re-exported Types
GoogleRequest (Rs, Scopes),
MediaUpload,
MediaDownload,
ServiceConfig,
Stream,
sinkLBS,
FieldMask (..),
PatchField (..),
Seconds (..),
seconds,
microseconds,
AccessToken (..),
RefreshToken (..),
OAuthScope (..),
ClientId (..),
ServiceId (..),
GSecret (..),
Base64 (..),
DateTime (..),
Date (..),
Time (..),
Duration (..),
AsText (..),
-- * Re-exported Utilities
runResourceT,
)
where
import Control.Exception.Lens
import Control.Monad
import Control.Monad.IO.Class (MonadIO (..))
import Control.Monad.Trans.Resource (MonadResource, runResourceT)
import Network.HTTP.Client (newManager)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Unkai.Auth
import Unkai.Env
import Unkai.Internal.Body
import Unkai.Internal.HTTP
import Unkai.Internal.Logger
import Unkai.Prelude
-- | Send a request, returning authentication, transport, serialization and
-- service failures in 'Left'.
sendEither ::
( MonadResource m,
AllowRequest a scopes
) =>
Env scopes ->
a ->
m (Either Error (Rs a))
sendEither =
unsafeRequest
-- | Send a request, returning the associated response if successful.
--
-- Throws 'Error' during request setup and eager response handling.
send ::
( MonadResource m,
AllowRequest a scopes
) =>
Env scopes ->
a ->
m (Rs a)
send env =
sendEither env
>=> hoistEither
-- | Send a request returning the associated streaming media response if successful.
--
-- Some request data types have two possible responses, the JSON metadata and
-- a streaming media response. Use 'send' to retrieve the metadata and 'download'
-- to retrieve the streaming media.
--
-- Consume the single-pass Streamly stream inside the same 'runResourceT' scope.
-- Once this function returns 'Right', subsequent body-read failures are raised
-- during consumption.
downloadEither ::
( MonadResource m,
AllowRequest (MediaDownload a) scopes
) =>
Env scopes ->
a ->
m (Either Error (Rs (MediaDownload a)))
downloadEither env =
sendEither env
. MediaDownload
-- | Send a request returning the associated streaming media response if successful.
--
-- Some request data types have two possible responses, the JSON metadata and
-- a streaming media response. Use 'send' to retrieve the metadata and 'download'
-- to retrieve the streaming media.
--
-- Equivalent to:
--
-- @
-- 'send' . 'MediaDownload'
-- @
--
-- Write each strict byte chunk to a binary file as it arrives.
--
-- > {-# LANGUAGE OverloadedStrings #-}
-- >
-- > import Control.Monad.IO.Class (liftIO)
-- > import qualified Data.ByteString as BS
-- > import qualified Streamly.Data.Fold as Fold
-- > import qualified Streamly.Data.Stream as Stream
-- > import System.IO (IOMode (WriteMode), withBinaryFile)
-- > import Unkai (Env, download, runResourceT)
-- > import qualified Unkai.Storage as Storage
-- >
-- > downloadFile :: Env '[Storage.Devstorage'ReadOnly] -> FilePath -> IO ()
-- > downloadFile env output = withBinaryFile output WriteMode $ \handle ->
-- > runResourceT $ do
-- > stream <- download env (Storage.newStorageObjectsGet "bucket" "reports/q1.csv")
-- > Stream.fold (Fold.drainMapM (liftIO . BS.hPut handle)) stream
--
-- Throws 'Error' during request setup and eager response handling.
download ::
( MonadResource m,
AllowRequest (MediaDownload a) scopes
) =>
Env scopes ->
a ->
m (Rs (MediaDownload a))
download env =
downloadEither env
>=> hoistEither
-- | Send a request with an attached <https://tools.ietf.org/html/rfc2387 multipart/related media> upload.
--
-- Equivalent to:
--
-- @
-- 'sendEither' . 'MediaUpload'
-- @
--
-- For example:
--
-- > {-# LANGUAGE OverloadedLabels #-}
-- > {-# LANGUAGE OverloadedStrings #-}
-- >
-- > import Control.Lens ((&), (?~))
-- > import Data.Generics.Labels ()
-- > import Unkai (Env, Error, runResourceT, sourceBody, uploadEither)
-- > import qualified Unkai.Storage as Storage
-- >
-- > uploadFile :: Env '[Storage.Devstorage'ReadWrite] -> FilePath -> IO (Either Error Storage.Object)
-- > uploadFile env path = do
-- > let metadata = Storage.newObject & #name ?~ "reports/q1.csv"
-- > body <- sourceBody path
-- > runResourceT (uploadEither env (Storage.newStorageObjectsInsert "bucket" metadata) body)
uploadEither ::
( MonadResource m,
AllowRequest (MediaUpload a) scopes
) =>
Env scopes ->
a ->
GBody ->
m (Either Error (Rs (MediaUpload a)))
uploadEither env x =
sendEither env
. MediaUpload x
-- | Send a request with an attached <https://tools.ietf.org/html/rfc2387 multipart/related media> upload.
--
-- Equivalent to:
--
-- @
-- 'send' . 'MediaUpload'
-- @
--
-- Throws 'Error' during request setup and eager response handling.
upload ::
( MonadResource m,
AllowRequest (MediaUpload a) scopes
) =>
Env scopes ->
a ->
GBody ->
m (Rs (MediaUpload a))
upload env x =
uploadEither env x
>=> hoistEither
hoistEither :: (MonadIO m) => Either Error a -> m a
hoistEither = either (liftIO . throwingM _Error) pure
-- $usage
--
-- The request and response types provided by the various @unkai-*@ libraries can
-- be used with either 'send', 'upload', or 'download', depending upon the
-- request's purpose. Namely, 'send' is the function you will most commonly use to
-- send requests, with 'upload' and 'download' as convenience when dealing with
-- streaming requests and responses respectively.
--
-- To get started we will need to specify our Google Service credentials and
-- create an 'Env' environment containing configuration which will be used by
-- calling functions to perform any actions. Your Google 'Credentials' can be supplied
-- in a number of ways, by having Unkai retrieve
-- <https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials>
-- for use on Google App Engine and Google Compute Engine, or by explicitly
-- supplying your credentials. See the <#credentials Credentials> section for
-- information about supported credential mechanisms.
--
-- The following example demonstrates uploading a file to Google
-- <https://cloud.google.com/storage/ Cloud Storage> using 'ObjectsInsert' from
-- <http://hackage.haskell.org/package/unkai-storage unkai-storage>:
--
--
-- > {-# LANGUAGE DataKinds #-}
-- > {-# LANGUAGE FlexibleContexts #-}
-- > {-# LANGUAGE OverloadedLabels #-}
-- > {-# LANGUAGE OverloadedStrings #-}
-- > {-# LANGUAGE ScopedTypeVariables #-}
-- >
-- > import Control.Lens ((.~), (<&>), (?~))
-- > import Data.Function ((&))
-- > import Data.Generics.Labels ()
-- > import Data.Proxy (Proxy (..))
-- > import System.IO (stdout)
-- > import Unkai (HasEnv (envLogger, envScopes), LogLevel (Debug), newEnv, newLogger, runResourceT, sourceBody, upload)
-- > import qualified Unkai.Storage as Storage
-- >
-- > example :: IO Storage.Object
-- > example = do
-- > lgr <- newLogger Debug stdout -- (1)
-- > env <- newEnv <&> (envLogger .~ lgr) . (envScopes .~ (Proxy :: Proxy '[Storage.Devstorage'ReadWrite])) -- (2) (3)
-- > body <- sourceBody "/path/to/image.jpg" -- (4)
-- > let key = "image.jpg"
-- > bucket = "my-storage-bucket"
-- >
-- > runResourceT $ -- (5)
-- > upload env (Storage.newStorageObjectsInsert bucket (Storage.newObject & #name ?~ key)) body
--
-- Breaking down the above example, we have the following points of interest:
--
-- 1. A new 'Logger' to replace the default noop logger is created, set to print
-- debug information and errors to 'stdout'.
--
-- 2. The 'Env' is created using 'newEnv'. This creates a new HTTP 'Manager' and
-- retrieves the application default 'Credentials'.
--
-- 3. The lenses 'envLogger' and 'envScopes' are used to set the newly created
-- 'Logger' and authorised OAuth2 scopes, respectively. Explicitly annotating the
-- 'Env' with the scopes ensures that any mismatch between the remote
-- operations performed in 'upload' and the credential scopes are raised as
-- errors at compile time.
-- See the <#authorization Authorization> section for more information.
--
-- 4. The streaming 'body' for the object is retrieved from a 'FilePath', and the
-- MIME type is calculated from the file extension.
-- The MIME type is used as the object's @Content-Type@ in Cloud Storage, and
-- can be overriden using the 'bodyContentType' lens as follows:
--
-- > import Network.HTTP.Media ((//))
-- >
-- > body <- sourceBody f <&> bodyContentType .~ "application" // "json"
--
-- 5. Finally, we run the 'Google' computation using @'runResourceT'@
-- which serialises the 'StorageObjectsInsert' type to a HTTP request and sets the streaming 'Body'.
-- The resulting 'Storage.Object' metadata is then parsed from a successful HTTP response.
-- 1
-- Additional examples can be found can be found in the
-- <https://github.com/shinzui/unkai/tree/develop/examples Unkai> project's
-- source control.
-- $authorization #authorization#
-- Each request within a particular 'send', 'upload' or 'download' context requires specific
-- OAuth2 scopes to be have been authorized for the given credentials.
--
-- For example, the Google Storage 'StorageObjectsInsert' has the associated scopes of:
--
-- > type Scopes ObjectsInsert =
-- > '["https://www.googleapis.com/auth/cloud-platform",
-- > "https://www.googleapis.com/auth/devstorage.full_control",
-- > "https://www.googleapis.com/auth/devstorage.read_write"]
--
-- Multiple differing requests within a given function call context will then require
-- the credentials to have a minimal set of these associated request scopes.
-- This authorization information is represented as a type-level set,
-- the 's' type parameter of 'Env'. A mismatch of the sent request scopes and the 'Env' credential scopes results in a informative
-- compile error.
--
-- You can use 'allow' or the 'envScopes' lens to specify the 'Env's set of scopes.
-- The various @unkai-*@ libraries export their individual scopes from @Unkai.*"
-- and you can use the '(!)' combinator to combine these into a larger set.
--
-- For example:
--
-- > import Control.Lens ((<&>), (.~))
-- > import Unkai
-- > import Unkai.Monitoring
-- > import Unkai.Compute
-- >
-- > main :: IO ()
-- > main = do
-- > env <- newEnv <&> envScopes .~ (Proxy :: Proxy '[Monitoring'Read, Monitoring'Write, Compute'ReadOnly])
-- > ...
--
-- >>> :type env
-- Env '["https://www.googleapis.com/auth/monitoring.read", "https://www.googleapis.com/auth/monitoring.write", "https://www.googleapis.com/auth/compute.readonly"]
-- $configuration
-- Each service has its own configuration such as host, port, path prefix, and timeout
-- which can be customized independent of other services.
-- It can be desirable to customize this when mocking service endpoints or adjusting
-- HTTP response timeouts for a specific request.
--
-- For example, to point all calls to Google Compute to @https://localhost@ instead
-- of the actual remote endpoint, we can use @Control.Monad.Reader.local@ in conjunction
-- with 'override':
--
-- > import Control.Lens ((&), (.~))
-- > import Control.Monad.Reader (local)
-- > import Unkai
-- > import Unkai.Compute
-- >
-- > local (override (computeService & serviceHost .~ "localhost")) $ do
-- > _ <- send $ instancesGet "project" "zone" "instance-id"
-- > ...
-- $credentials #credentials#
-- By default 'newEnv' uses 'getApplicationDefault' to discover credentials
-- from the underlying, following Google's official library behaviour.
-- If you wish to manually specify 'Credentials' via 'newEnvWith', you can use one
-- of the following supported credential mechanisms:
--
-- * "Unkai.Auth.ServiceAccount" - Applications deployed to custom environments.
-- * "Unkai.Auth.ApplicationDefault" - Applications deployed to App Engine (GAE) or Compute Engine (GCE).
--
-- For local development, run @gcloud auth application-default login@ to
-- create an authorized-user ADC file. See "Unkai.Auth" for direct credential operations.
-- $async
-- Requests can be sent asynchronously, but due to guarantees about resource closure
-- require the use of <http://hackage.haskell.org/package/lifted-async lifted-async>.
-- $metadata
--
-- Google Compute metadata can be retrieve when running on GCE instances.
-- See the documentation in "Unkai.Compute.Metadata" for the available
-- functions.
-- $logging
-- The exposed logging interface is a primitive 'Logger' function which gets
-- threaded through service calls and serialisation routines. This allows the
-- consuming library to output useful information and diagnostics. Unkai sends
-- method, status and request summaries to callbacks. Token exchange bodies
-- and credential-bearing request and response data are omitted at every level.
--
-- The 'newLogger' function can be used to construct a simple logger which writes
-- output to a 'Handle', but in most production code you should probably consider
-- using a more robust logging library such as
-- <http://hackage.haskell.org/package/tinylog tinylog> or
-- <http://hackage.haskell.org/package/fast-logger fast-logger>.