module Config ( AppConfig , S3Config , SmtpConfig , UserConfig , UserEntry , defaultUserConfig , fillUserConfigFromEnv , loadConfig , s3ConfigFromUser ) where import Prelude import Control.Monad.Error.Class (throwError) import Data.Argonaut (decodeJson, (.:), (.:?)) import Data.Argonaut.Core (Json) import Data.Either (Either(..)) import Data.Function.Uncurried (Fn3, runFn3) import Data.Int (fromString) as Data.Int import Data.Maybe (Maybe(..), fromMaybe, isJust, isNothing) import Data.String (joinWith) import Data.Traversable (traverse) import Effect (Effect) import Effect.Aff (Aff, makeAff, nonCanceler) import Effect.Class (liftEffect) import Effect.Exception (error) import Node.Process (cwd, lookupEnv) -- | Per-user runtime configuration after environment values are resolved. type UserConfig = { listenbrainzUser :: Maybe String , lastfmUser :: Maybe String , lastfmApiKey :: Maybe String , discogsToken :: Maybe String , cosineApiKey :: Maybe String , databaseFile :: String , s3Bucket :: Maybe String , s3Region :: String , awsAccessKeyId :: Maybe String , awsSecretAccessKey :: Maybe String , awsEndpointUrl :: Maybe String , awsS3AddressingStyle :: Maybe String , coverCacheEnabled :: Boolean , backupEnabled :: Boolean , backupIntervalHours :: Int } -- | A configured user and their URL slug. type UserEntry = { slug :: String , name :: Maybe String , config :: UserConfig } -- | Process-wide configuration and configured users. type AppConfig = { port :: Int , host :: String , metricsEnabled :: Boolean , corsOrigin :: String , adminToken :: Maybe String , adminEmail :: Maybe String , registrationEnabled :: Boolean , registrationsDb :: String , smtp :: SmtpConfig , users :: Array UserEntry } -- | SMTP settings for notification email. type SmtpConfig = { host :: Maybe String , port :: Int , user :: Maybe String , pass :: Maybe String , from :: Maybe String } -- | S3-compatible object storage settings. type S3Config = { bucket :: Maybe String , region :: String , accessKeyId :: Maybe String , secretAccessKey :: Maybe String , endpointUrl :: Maybe String , addressingStyle :: Maybe String } -- | Extract object-storage settings from a user configuration. s3ConfigFromUser :: UserConfig -> S3Config s3ConfigFromUser cfg = { bucket: cfg.s3Bucket , region: cfg.s3Region , accessKeyId: cfg.awsAccessKeyId , secretAccessKey: cfg.awsSecretAccessKey , endpointUrl: cfg.awsEndpointUrl , addressingStyle: cfg.awsS3AddressingStyle } -- Defaults for a self-registered user; creds and DB path are filled by fillUserConfigFromEnv. -- | Create defaults for a newly self-registered user. defaultUserConfig :: String -> Maybe String -> Maybe String -> UserConfig defaultUserConfig databaseFile listenbrainzUser lastfmUser = { listenbrainzUser , lastfmUser , lastfmApiKey: Nothing , discogsToken: Nothing , cosineApiKey: Nothing , databaseFile , s3Bucket: Nothing , s3Region: "us-east-1" , awsAccessKeyId: Nothing , awsSecretAccessKey: Nothing , awsEndpointUrl: Nothing , awsS3AddressingStyle: Nothing , coverCacheEnabled: false , backupEnabled: false , backupIntervalHours: 24 } foreign import loadConfigImpl :: Fn3 String (String -> Effect Unit) (Json -> Effect Unit) (Effect Unit) -- | Load, resolve, and validate application configuration. loadConfig :: String -> Aff AppConfig loadConfig path = do json <- makeAff \cb -> runFn3 loadConfigImpl path (\msg -> cb (Left (error msg))) (\j -> cb (Right j)) *> pure nonCanceler rawUsers <- case decodeUsersJson json of Left msg -> throwError (error msg) Right users -> pure users portStr <- liftEffect $ lookupEnv "PORT" hostStr <- liftEffect $ lookupEnv "HOST" metricsEnabledStr <- liftEffect $ lookupEnv "METRICS_ENABLED" corsOriginStr <- liftEffect $ lookupEnv "CORS_ORIGIN" adminToken <- liftEffect $ lookupEnv "ADMIN_TOKEN" adminEmail <- liftEffect $ lookupEnv "ADMIN_EMAIL" registrationEnabledStr <- liftEffect $ lookupEnv "REGISTRATION_ENABLED" registrationsDbEnv <- liftEffect $ lookupEnv "CORPUS_REGISTRATIONS_DB" smtpHost <- liftEffect $ lookupEnv "SMTP_HOST" smtpPortStr <- liftEffect $ lookupEnv "SMTP_PORT" smtpUser <- liftEffect $ lookupEnv "SMTP_USER" smtpPass <- liftEffect $ lookupEnv "SMTP_PASS" smtpFrom <- liftEffect $ lookupEnv "SMTP_FROM" databasePath <- liftEffect $ lookupEnv "DATABASE_PATH" defaultPath <- liftEffect cwd filledUsers <- traverse ( \u -> do c <- fillUserConfigFromEnv u.config pure (u { config = c }) ) rawUsers let resolvePath file = case databasePath of Nothing -> defaultPath <> "/" <> file Just dir -> dir <> "/" <> file port = fromMaybe 8000 (portStr >>= Data.Int.fromString) host = fromMaybe "127.0.0.1" hostStr metricsEnabled = metricsEnabledStr == Just "true" corsOrigin = fromMaybe "*" corsOriginStr registrationEnabled = registrationEnabledStr == Just "true" registrationsDb = resolvePath (fromMaybe "registrations.db" registrationsDbEnv) smtp = { host: smtpHost , port: fromMaybe 587 (smtpPortStr >>= Data.Int.fromString) , user: smtpUser , pass: smtpPass , from: smtpFrom } fullConfig = { port , host , metricsEnabled , corsOrigin , adminToken , adminEmail , registrationEnabled , registrationsDb , smtp , users: filledUsers } case validateConfig fullConfig of Left msg -> throwError (error msg) Right cfg -> pure cfg -- Fills shared credentials and resolves the database path from the environment. -- | Fill shared credentials and resolve the database path from the environment. fillUserConfigFromEnv :: UserConfig -> Aff UserConfig fillUserConfigFromEnv cfg = do lastfmApiKey <- liftEffect $ lookupEnv "LASTFM_API_KEY" discogsToken <- liftEffect $ lookupEnv "DISCOGS_TOKEN" cosineApiKey <- liftEffect $ lookupEnv "COSINE_API_KEY" s3Bucket <- liftEffect $ lookupEnv "S3_BUCKET" s3Region <- liftEffect $ map (fromMaybe "us-east-1") $ lookupEnv "S3_REGION" awsAccessKeyId <- liftEffect $ lookupEnv "AWS_ACCESS_KEY_ID" awsSecretAccessKey <- liftEffect $ lookupEnv "AWS_SECRET_ACCESS_KEY" awsEndpointUrl <- liftEffect $ lookupEnv "AWS_ENDPOINT_URL" awsS3AddressingStyle <- liftEffect $ lookupEnv "AWS_S3_ADDRESSING_STYLE" databasePath <- liftEffect $ lookupEnv "DATABASE_PATH" defaultPath <- liftEffect cwd let resolvePath file = case databasePath of Nothing -> defaultPath <> "/" <> file Just dir -> dir <> "/" <> file pure cfg { lastfmApiKey = lastfmApiKey , discogsToken = discogsToken , cosineApiKey = cosineApiKey , s3Bucket = s3Bucket , s3Region = s3Region , awsAccessKeyId = awsAccessKeyId , awsSecretAccessKey = awsSecretAccessKey , awsEndpointUrl = awsEndpointUrl , awsS3AddressingStyle = awsS3AddressingStyle , databaseFile = resolvePath cfg.databaseFile } validateConfig :: AppConfig -> Either String AppConfig validateConfig cfg = do _ <- traverse validateUserEntry cfg.users pure cfg validateUserEntry :: UserEntry -> Either String UserEntry validateUserEntry entry = let c = entry.config label = if entry.slug == "" then "root" else entry.slug lfmMissing = if isJust c.lastfmUser && isNothing c.lastfmApiKey then [ "LASTFM_API_KEY" ] else [] s3Missing = if c.coverCacheEnabled || c.backupEnabled then (if isNothing c.s3Bucket then [ "S3_BUCKET" ] else []) <> (if isNothing c.awsAccessKeyId then [ "AWS_ACCESS_KEY_ID" ] else []) <> ( if isNothing c.awsSecretAccessKey then [ "AWS_SECRET_ACCESS_KEY" ] else [] ) <> (if isNothing c.awsEndpointUrl then [ "AWS_ENDPOINT_URL" ] else []) else [] missing = lfmMissing <> s3Missing in if missing == [] then Right entry else Left ( "User '" <> label <> "': missing required env vars: " <> joinWith ", " missing ) mapLeft :: forall a b c. (a -> c) -> Either a b -> Either c b mapLeft f (Left a) = Left (f a) mapLeft _ (Right b) = Right b decodeUsersJson :: Json -> Either String (Array UserEntry) decodeUsersJson json = do obj <- mapLeft show $ decodeJson json usersArr <- mapLeft show (obj .: "users" :: Either _ (Array Json)) traverse decodeUserEntry usersArr decodeUserEntry :: Json -> Either String UserEntry decodeUserEntry json = do obj <- mapLeft show $ decodeJson json slug <- mapLeft show $ obj .: "slug" name <- mapLeft show $ obj .:? "name" configJson <- mapLeft show (obj .: "config" :: Either _ Json) config <- decodeUserConfig configJson pure { slug, name, config } -- Decodes only the non-sensitive, per-user fields from users.json. -- Shared credentials are injected from environment variables in loadConfig. decodeUserConfig :: Json -> Either String UserConfig decodeUserConfig json = do obj <- mapLeft show $ decodeJson json listenbrainzUser <- mapLeft show $ obj .:? "listenbrainzUser" lastfmUser <- mapLeft show $ obj .:? "lastfmUser" databaseFile <- mapLeft show $ obj .: "databaseFile" coverCacheEnabled <- mapLeft show $ obj .: "coverCacheEnabled" backupEnabled <- mapLeft show $ obj .: "backupEnabled" backupIntervalHours <- mapLeft show $ obj .: "backupIntervalHours" pure { listenbrainzUser , lastfmUser , lastfmApiKey: Nothing , discogsToken: Nothing , cosineApiKey: Nothing , databaseFile , s3Bucket: Nothing , s3Region: "us-east-1" , awsAccessKeyId: Nothing , awsSecretAccessKey: Nothing , awsEndpointUrl: Nothing , awsS3AddressingStyle: Nothing , coverCacheEnabled , backupEnabled , backupIntervalHours }