Skip to content

Instantly share code, notes, and snippets.

@rcook
Last active April 7, 2023 09:46
Show Gist options
  • Save rcook/67c81760dd046d21fd496ab6ae8e404a to your computer and use it in GitHub Desktop.
Save rcook/67c81760dd046d21fd496ab6ae8e404a to your computer and use it in GitHub Desktop.
AWS via Haskell Part 2 (S3)
name: aws-via-haskell
version: 0.1.0.0
homepage: https://github.com/rcook/aws-via-haskell#readme
license: MIT
license-file: LICENSE
author: Richard Cook
maintainer: [email protected]
copyright: 2017 Richard Cook
category: Command Line
build-type: Simple
cabal-version: >= 1.10
extra-source-files: README.md
source-repository head
type: git
location: https://github.com/rcook/aws-via-haskell.git
library
default-language: Haskell2010
if os(darwin)
cpp-options: -DOS_MACOS
if os(linux)
cpp-options: -DOS_LINUX
if os(windows)
cpp-options: -DOS_WINDOWS
hs-source-dirs: lib
ghc-options: -W -Wall -fwarn-incomplete-patterns -fwarn-unused-imports
build-depends: amazonka
, base >= 4.7 && < 5
, bytestring
, lens
, resourcet
, text
exposed-modules: AWSViaHaskell
, AWSViaHaskell.AWSInfo
, AWSViaHaskell.Util
executable dynamodb-app
default-language: Haskell2010
if os(darwin)
cpp-options: -DOS_MACOS
if os(linux)
cpp-options: -DOS_LINUX
if os(windows)
cpp-options: -DOS_WINDOWS
hs-source-dirs: dynamodb
main-is: Main.hs
ghc-options: -threaded -rtsopts -with-rtsopts=-N -W -Wall -fwarn-incomplete-patterns -fwarn-unused-imports
build-depends: amazonka
, amazonka-dynamodb
, aws-via-haskell
, base >= 4.7 && < 5
, lens
, text
, unordered-containers
executable s3-app
default-language: Haskell2010
if os(darwin)
cpp-options: -DOS_MACOS
if os(linux)
cpp-options: -DOS_LINUX
if os(windows)
cpp-options: -DOS_WINDOWS
hs-source-dirs: s3
main-is: Main.hs
ghc-options: -threaded -rtsopts -with-rtsopts=-N -W -Wall -fwarn-incomplete-patterns -fwarn-unused-imports
build-depends: amazonka
, amazonka-s3
, aws-via-haskell
, base >= 4.7 && < 5
, bytestring
, conduit-extra
, lens
, resourcet
, text
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
module AWSViaHaskell.AWSInfo
( AWSInfo(..)
, LoggingState(..)
, ServiceEndpoint(..)
, getAWSInfo
, withAWS
, withAWS'
) where
import Control.Lens ((<&>), set)
import Control.Monad.Trans.AWS
( AWST'
, runAWST
)
import Control.Monad.Trans.Resource
( MonadBaseControl
, ResourceT
)
import Data.ByteString (ByteString)
import Control.Monad.Trans.AWS
( Credentials(..)
, Env
, LogLevel(..)
, Region(..)
, Service
, envLogger
, newEnv
, newLogger
, reconfigure
, runResourceT
, setEndpoint
, within
)
import System.IO (stdout)
type HostName = ByteString
type Port = Int
data AWSInfo = AWSInfo
{ env :: Env
, region :: Region
, service :: Service
}
data LoggingState = LoggingEnabled | LoggingDisabled
data ServiceEndpoint = AWS Region | Local HostName Port
getAWSInfo :: LoggingState -> ServiceEndpoint -> Service -> IO AWSInfo
getAWSInfo loggingState serviceEndpoint service = do
e <- getEnv loggingState
let (r, s) = regionService serviceEndpoint service
return $ AWSInfo e r s
where
-- Standard discovery mechanism for credentials, log to standard output
getEnv LoggingEnabled = do
logger <- newLogger Debug stdout
newEnv Discover <&> set envLogger logger
-- Standard discovery mechanism for credentials, no logging
getEnv LoggingDisabled = newEnv Discover
-- Run against a DynamoDB instance running on AWS in specified region
regionService (AWS region) s = (region, s)
-- Run against a local DynamoDB instance on a given host and port
regionService (Local hostName port) s = (NorthVirginia, setEndpoint False hostName port s)
withAWS :: MonadBaseControl IO m =>
AWST' Env (ResourceT m) a
-> AWSInfo
-> m a
withAWS action AWSInfo{..} =
runResourceT . runAWST env . within region $ do
reconfigure service action
withAWS' :: MonadBaseControl IO m =>
AWSInfo
-> AWST' Env (ResourceT m) a
-> m a
withAWS' = flip withAWS
The MIT License (MIT)
Copyright (c) 2017 Richard Cook
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main (main) where
import AWSViaHaskell
import Control.Exception.Lens (handling)
import Control.Lens ((^.), (.~), (&))
import Control.Monad (forM_, void, when)
import Data.ByteString.Lazy.Char8 (ByteString)
import qualified Data.ByteString.Lazy.Char8 as ByteString
import Data.Conduit.Binary (sinkLbs)
import Data.Monoid ((<>))
import qualified Data.Text.IO as Text (putStrLn)
import Network.AWS
( Region(..)
, await
, send
, sinkBody
)
import Network.AWS.Data (toText)
import Network.AWS.S3
( _BucketAlreadyOwnedByYou
, BucketName(..)
, LocationConstraint(..)
, ObjectKey(..)
, bucketExists
, cbCreateBucketConfiguration
, cbcLocationConstraint
, createBucketConfiguration
, bName
, createBucket
, getObject
, gorsBody
, headBucket
, lbrsBuckets
, listBuckets
, listObjectsV
, lrsContents
, oKey
, putObject
, s3
)
data S3Info = S3Info
{ aws :: AWSInfo
, bucketName :: BucketName
}
getS3Info :: LoggingState -> ServiceEndpoint -> IO S3Info
getS3Info loggingState serviceEndpoint = do
aws <- getAWSInfo loggingState serviceEndpoint s3
return $ S3Info aws "rcook456dac3a5a0e4aeba1b3238306916a31"
doCreateBucketIfNotExists :: S3Info -> IO ()
doCreateBucketIfNotExists S3Info{..} = withAWS' aws $ do
let cbc = createBucketConfiguration
& cbcLocationConstraint .~ Just (LocationConstraint (region aws))
newlyCreated <- handling _BucketAlreadyOwnedByYou (const (pure False)) $ do
void $ send $ createBucket bucketName
& cbCreateBucketConfiguration .~ Just cbc
return True
when newlyCreated (void $ await bucketExists (headBucket bucketName))
doListBuckets :: S3Info -> IO [BucketName]
doListBuckets S3Info{..} = withAWS' aws $ do
result <- send $ listBuckets
return $ [ x ^. bName | x <- result ^. lbrsBuckets ]
doPutObject :: S3Info -> IO ()
doPutObject S3Info{..} = withAWS' aws $ do
void $ send $ putObject bucketName "object-key" "object-bytes"
doListObjects :: S3Info -> IO [ObjectKey]
doListObjects S3Info{..} = withAWS' aws $ do
result <- send $ listObjectsV bucketName
return $ [ x ^. oKey | x <- result ^. lrsContents ]
doGetObject :: S3Info -> IO ByteString
doGetObject S3Info{..} = withAWS' aws $ do
result <- send $ getObject bucketName "object-key"
(result ^. gorsBody) `sinkBody` sinkLbs
main :: IO ()
main = do
-- Use the real thing
s3Info <- getS3Info LoggingDisabled (AWS Ohio)
-- localstack by default exposes its S3 service on port 4572
--s3Info <- getS3Info LoggingDisabled (Local "localhost" 4572)
putStrLn "CreateBucket"
doCreateBucketIfNotExists s3Info
putStrLn "ListBuckets"
bucketNames <- doListBuckets s3Info
forM_ bucketNames $ \n ->
Text.putStrLn $ " " <> toText n
putStrLn "PutObject"
doPutObject s3Info
putStrLn "ListObjects"
objectKeys <- doListObjects s3Info
forM_ objectKeys $ \k ->
Text.putStrLn $ " " <> toText k
putStrLn "GetObject"
content <- doGetObject s3Info
ByteString.putStrLn $ " " <> content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment