Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

User management task #46

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,9 @@ TAGS
tests.iml
# Auto-copied by sbt-microsites
docs/src/main/tut/contributing.md
.sdkmanrc
.bloop
.vscode
.metals
metals.sbt
logs/
70 changes: 58 additions & 12 deletions users/.scalafmt.conf
Original file line number Diff line number Diff line change
@@ -1,18 +1,64 @@
version = "3.7.12"
runner.dialect = scala3
style = defaultWithAlign
maxColumn = 120
danglingParentheses = true
align.openParenCallSite = false
spaces.inImportCurlyBraces = true
rewrite.rules = [PreferCurlyFors, RedundantBraces, SortImports]
binPack.parentConstructors = false
unindentTopLevelOperators = true
newlines.afterImplicitKWInVerticalMultiline = true
newlines.beforeImplicitKWInVerticalMultiline = true
rewriteTokens {
"=>" = "⇒"
"->" = "→"
"<-" = "←"
align = most

continuationIndent.defnSite = 2
align.arrowEnumeratorGenerator = true
align.openParenCallSite = false
align.openParenDefnSite = false

assumeStandardLibraryStripMargin = true
align.stripMargin = true

danglingParentheses.defnSite = true
danglingParentheses.callSite = true
danglingParentheses.exclude = [class, trait, enum, def]

docstrings.style = Asterisk
docstrings.wrap = "no"
docstrings.forceBlankLineBefore = true

rewrite.rules = [RedundantBraces, RedundantParens, SortImports, PreferCurlyFors, SortModifiers]
rewrite.redundantBraces.includeUnitMethods = true
rewrite.redundantBraces.stringInterpolation = true
rewrite.redundantBraces.methodBodies = false

rewrite.imports.sort = ascii
rewrite.imports.groups = [
["javax?\\..*"]
["akka\\..*"]
["org\\..*"]
["com\\..*"]
["scala\\..*"]
["io\\..*", "cats\\..*"]
["scala\\.concurrent\\..*"]
]

rewrite.sortModifiers {
order = [
override
private
protected
final
sealed
abstract
lazy
implicit
]
}

rewrite.trailingCommas.style = "never"

newlines.topLevelStatementBlankLines = [
{
blanks { before = 1 }
}
]

# removed tokens because they are deprecated

align.tokens = ["%", "%%", {code = "⇒", owner = "Case"}, ]
project.excludeFilters = [
.scalafmt.conf
Expand Down
30 changes: 15 additions & 15 deletions users/build.sbt
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
name := "users"
version := "1.0.0"
import sbt._

scalaVersion := "2.12.3"
scalacOptions ++= Seq(
"-deprecation",
"-encoding",
"UTF-8",
"-feature",
"-language:existentials",
"-language:higherKinds",
"-Ypartial-unification"
inThisBuild(
List(
scalaVersion := "3.3.0",
semanticdbEnabled := true,
name := "users",
version := "1.0.0"
)
)

resolvers +=
"Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"

libraryDependencies ++= Seq(
"com.softwaremill.quicklens" %% "quicklens" % "1.4.11",
"org.typelevel" %% "cats-core" % "1.0.0-MF",
compilerPlugin("org.spire-math" %% "kind-projector" % "0.9.4")
)
Dependencies.CatsCore,
Dependencies.CatsEffect,
Dependencies.QuickLens,
Dependencies.Logback
) ++ Dependencies.Http4s ++
Dependencies.Circe ++
Dependencies.Tests
39 changes: 39 additions & 0 deletions users/project/Dependencies.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import sbt._

object Dependencies {

object Versions {
val catsCore = "2.9.0"
val catsEffect = "3.5.1"
val quckLens = "1.9.6"
val http4sVersion = "1.0.0-M40"
val logback = "1.2.3"
val circe = "0.14.5"

val catsEffectScalatest = "1.5.0"
val scalatest = "3.2.16"
}

lazy val CatsCore = "org.typelevel" %% "cats-core" % Versions.catsCore
lazy val CatsEffect = "org.typelevel" %% "cats-effect" % Versions.catsEffect
lazy val QuickLens = "com.softwaremill.quicklens" %% "quicklens" % Versions.quckLens
lazy val Logback = "ch.qos.logback" % "logback-classic" % Versions.logback

lazy val Http4s = Seq(
"org.http4s" %% "http4s-ember-client",
"org.http4s" %% "http4s-ember-server",
"org.http4s" %% "http4s-dsl",
"org.http4s" %% "http4s-circe"
).map(_ % Versions.http4sVersion)

lazy val Circe = Seq(
"io.circe" %% "circe-generic",
"io.circe" %% "circe-core",
"io.circe" %% "circe-literal"
).map(_ % Versions.circe)

lazy val Tests = Seq(
"org.typelevel" %% "cats-effect-testing-scalatest" % Versions.catsEffectScalatest,
"org.scalatest" %% "scalatest" % Versions.scalatest
).map(_ % Test)
}
2 changes: 1 addition & 1 deletion users/project/build.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
sbt.version=1.0.1
sbt.version=1.9.2
9 changes: 8 additions & 1 deletion users/project/plugins.sbt
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "1.3.0")

addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.7")
addSbtPlugin("io.github.davidgregory084" % "sbt-tpolecat" % "0.4.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6")
addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "1.0.2")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.1.1")
addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.10.4")
27 changes: 27 additions & 0 deletions users/src/main/resources/logback.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">

<!--
NOTE: the logback-test.xml takes precedence over logback-test.xml when running the
app with "scala:run". It is an issue with maven scala plugin's classpath handling.
As this page says: http://scala-tools.org/mvnsites/maven-scala-plugin/usage_run.html
"scala:run" uses the test classpath.
-->

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %highlight([%level]) %logger - %msg%n</pattern>
</encoder>
</appender>

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>logs/api.log</file>
<encoder>
<pattern>%d [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>

<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
64 changes: 57 additions & 7 deletions users/src/main/scala/users/Main.scala
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
package users

import cats.data._
import cats.implicits._
import java.time.OffsetDateTime

import users.config._
import users.main._
import org.http4s.server.Server
import org.typelevel.log4cats.slf4j.Slf4jFactory
import org.typelevel.log4cats.syntax._
import org.typelevel.log4cats.Logger
import org.typelevel.log4cats.LoggerFactory
import org.typelevel.log4cats.SelfAwareStructuredLogger

object Main extends App {
import cats.*
import cats.effect.*
import cats.implicits.*

import fs2.io.net.Network
import users.config.*
import users.domain.*
import users.main.*

object Main extends IOApp:

private val adminUsername = UserName("admin")

val config = ApplicationConfig(
executors = ExecutorsConfig(
Expand All @@ -22,6 +36,42 @@ object Main extends App {
)
)

val application = Application.fromApplicationConfig.run(config)
override def run(args: List[String]): IO[ExitCode] = {
implicit val loggerFactory: LoggerFactory[IO] = Slf4jFactory.create[IO]
implicit val logger: SelfAwareStructuredLogger[IO] = loggerFactory.getLogger
(for
app <- appBuilder[IO](config)
server <- program[IO](app)
admin <- Resource.eval(generateAdmin[IO](app))
yield server)
.use(_ => IO.never)
.as(ExitCode.Success)

}

private def appBuilder[F[_]: Async](config: ApplicationConfig): Resource[F, Application[F]] =
Resource.eval(Application.fromApplicationConfig[F].run(config))

private def program[F[_]: Async: Network: LoggerFactory: Logger](app: Application[F]): Resource[F, Server] =
app.services.httpService.server[F](app.services.userManagement)

}
private def generateAdmin[F[_]: Monad: Logger](app: Application[F]): F[User] =
app.services.repositories.userRepository.getByUserName(adminUsername).flatMap {
case Some(u) => u.pure[F]
case None =>
for {
_ <- info"Creating admin"
id <- app.services.userManagement.generateId()
now = OffsetDateTime.now
u = User(
id,
UserName("admin"),
EmailAddress("[email protected]"),
Some(Password("admin")),
User.Metadata(1, now, now, None, None),
isAdmin = true
)
_ <- app.services.repositories.userRepository.insert(u)
_ <- info"Admin auth info header: Token: ${id.value}"
} yield u
}
34 changes: 22 additions & 12 deletions users/src/main/scala/users/config/config.scala
Original file line number Diff line number Diff line change
@@ -1,35 +1,45 @@
package users.config

import cats.data._
import cats.*
import cats.data.*
import cats.implicits.*

case class ApplicationConfig(
executors: ExecutorsConfig,
services: ServicesConfig
executors: ExecutorsConfig,
services: ServicesConfig,
httpConfig: HttpConfig = HttpConfig.default
)

case class ExecutorsConfig(
services: ExecutorsConfig.ServicesConfig
services: ExecutorsConfig.ServicesConfig
)

object ExecutorsConfig {
val fromApplicationConfig: Reader[ApplicationConfig, ExecutorsConfig] =
Reader(_.executors)

def fromApplicationConfig[F[_]: Applicative]: ReaderT[F, ApplicationConfig, ExecutorsConfig] =
ReaderT(_.executors.pure)

case class ServicesConfig(
parallellism: Int
parallellism: Int
)
}

case class ServicesConfig(
users: ServicesConfig.UsersConfig
users: ServicesConfig.UsersConfig
)

object ServicesConfig {
val fromApplicationConfig: Reader[ApplicationConfig, ServicesConfig] =
Reader(_.services)

def fromApplicationConfig[F[_]: Applicative]: ReaderT[F, ApplicationConfig, ServicesConfig] =
ReaderT(_.services.pure)

case class UsersConfig(
failureProbability: Double,
timeoutProbability: Double
failureProbability: Double,
timeoutProbability: Double
)
}

object HttpConfig:
val default = HttpConfig(host = "localhost", port = 8080)

case class HttpConfig(host: String, port: Int)
2 changes: 1 addition & 1 deletion users/src/main/scala/users/domain/Done.scala
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package users.domain

final case object Done
case object Done
30 changes: 30 additions & 0 deletions users/src/main/scala/users/domain/Protocol.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package users.domain

import io.circe.*
import io.circe.derivation.*
import io.circe.generic.semiauto.*

object Protocol:

implicit val idCodec: Codec[User.Id] = Codec.from(
Decoder.decodeString.map(User.Id.apply),
Encoder.encodeString.contramap(_.value)
)

implicit val userNameCodec: Codec[UserName] = Codec.from(
Decoder.decodeString.map(UserName.apply),
Encoder.encodeString.contramap(_.value)
)

implicit val emailAddressCodec: Codec[EmailAddress] = Codec.from(
Decoder.decodeString.map(EmailAddress.apply),
Encoder.encodeString.contramap(_.value)
)

implicit val passwordCodec: Codec[Password] = Codec.from(
Decoder.decodeString.map(Password.apply),
Encoder.encodeString.contramap(_.value)
)
implicit val metadataCodec: Codec[User.Metadata] = deriveCodec[User.Metadata]

implicit val userCodec: Codec[User] = deriveCodec[User]
Loading