Private
Public Access
feat: primera iteracion del servicio de comunicaciones externas
This commit is contained in:
1 parent
73f9cef8ce
commit
4c0dbaa91c
15 files changed
+429
No files matched your search
@@ -0,0 +1,6 @@
|
||||
SMTP_HOST=smtp.gmail.com
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=tu-usuario@gmail.com
|
||||
SMTP_PASSWORD=tu-app-password
|
||||
SMTP_FROM=tu-usuario@gmail.com
|
||||
SMTP_TO=destinatario@example.com
|
||||
@@ -0,0 +1,84 @@
|
||||
# comms
|
||||
|
||||
Servicio de comunicaciones. Expone un endpoint HTTP que recibe un JSON y lo envía por email vía SMTP.
|
||||
|
||||
## Requisitos
|
||||
|
||||
- Java 21+
|
||||
- sbt 1.x
|
||||
|
||||
## Configuración
|
||||
|
||||
Crear un `.env` en esta carpeta (basado en `.env.example`):
|
||||
|
||||
```
|
||||
SMTP_HOST=smtp.gmail.com
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=tu-usuario@gmail.com
|
||||
SMTP_PASSWORD=tu-app-password
|
||||
SMTP_FROM=tu-usuario@gmail.com
|
||||
SMTP_TO=destinatario@example.com(solo se usa en testint `sbt test`)
|
||||
```
|
||||
|
||||
- `SMTP_PORT`: `587` (STARTTLS) o `465` (SSL). Por defecto `587`.
|
||||
|
||||
## Correr
|
||||
|
||||
```sh
|
||||
sbt run
|
||||
```
|
||||
|
||||
El servidor escucha en `http://localhost:8088`.
|
||||
|
||||
## Endpoint
|
||||
|
||||
### `POST /email`
|
||||
|
||||
Envía un email. `to` es el destinatario (viene en la request, no en el `.env`).
|
||||
|
||||
```sh
|
||||
curl -X POST http://localhost:8088/email \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"titulo": "Pedido #123",
|
||||
"descripcion": "<p><strong>Nuevo pedido</strong></p>",
|
||||
"items": ["Bujía", "Filtro de aceite", "Pastillas de freno"],
|
||||
"to": "cliente@example.com"
|
||||
}'
|
||||
```
|
||||
|
||||
- `titulo`: asunto del email (string).
|
||||
- `descripcion`: cuerpo del email, se trata como HTML.
|
||||
- `items`: lista de strings, se renderiza como tabla en el email.
|
||||
- `to`: destinatario (string).
|
||||
|
||||
Respuestas:
|
||||
|
||||
- `200 OK` si se envió.
|
||||
- `400 Bad Request` si el JSON no es válido.
|
||||
|
||||
## Test de envío real
|
||||
|
||||
Manda un email de verdad usando las credenciales del `.env` (el destinatario sale de `SMTP_TO`, o de `SMTP_FROM` si la variable no está):
|
||||
|
||||
```sh
|
||||
sbt "testOnly com.fede.comms.SmtpEmailSpec"
|
||||
```
|
||||
|
||||
## Estructura
|
||||
|
||||
```
|
||||
src/main/scala/com/fede/comms/
|
||||
├── Main.scala # entrypoint
|
||||
├── CommsServer.scala # wiring del servidor
|
||||
├── CommsRoutes.scala # rutas HTTP
|
||||
├── config/
|
||||
│ └── SmtpConfig.scala # config SMTP + parser de .env
|
||||
└── emails/
|
||||
├── Emails.scala # modelo Mensaje + trait Email
|
||||
└── SmtpEmail.scala # envío vía SMTP
|
||||
```
|
||||
|
||||
## Futuro
|
||||
|
||||
Pensado para agregar un webhook que también reciba el mismo JSON y lo envíe por otros canales. Basta con definir un trait por canal (como `Email[F]`) y encadenarlo en `CommsRoutes`.
|
||||
@@ -0,0 +1,31 @@
|
||||
val Http4sVersion = "0.23.36"
|
||||
val CirceVersion = "0.14.16"
|
||||
val MunitVersion = "1.3.4"
|
||||
val LogbackVersion = "1.6.1"
|
||||
val MunitCatsEffectVersion = "2.2.0"
|
||||
val JakartaMailVersion = "2.0.2"
|
||||
|
||||
lazy val root = (project in file("."))
|
||||
.settings(
|
||||
organization := "com.fede.comms",
|
||||
name := "comms",
|
||||
version := "0.0.1-SNAPSHOT",
|
||||
scalaVersion := "2.13.18",
|
||||
libraryDependencies ++= Seq(
|
||||
"org.http4s" %% "http4s-ember-server" % Http4sVersion,
|
||||
"org.http4s" %% "http4s-ember-client" % Http4sVersion,
|
||||
"org.http4s" %% "http4s-circe" % Http4sVersion,
|
||||
"org.http4s" %% "http4s-dsl" % Http4sVersion,
|
||||
"io.circe" %% "circe-generic" % CirceVersion,
|
||||
"org.scalameta" %% "munit" % MunitVersion % Test,
|
||||
"org.typelevel" %% "munit-cats-effect" % MunitCatsEffectVersion % Test,
|
||||
"com.sun.mail" % "jakarta.mail" % JakartaMailVersion,
|
||||
"ch.qos.logback" % "logback-classic" % LogbackVersion % Runtime,
|
||||
),
|
||||
addCompilerPlugin("org.typelevel" %% "kind-projector" % "0.13.4" cross CrossVersion.full),
|
||||
addCompilerPlugin("com.olegpy" %% "better-monadic-for" % "0.3.1"),
|
||||
assembly / assemblyMergeStrategy := {
|
||||
case "module-info.class" => MergeStrategy.discard
|
||||
case x => (assembly / assemblyMergeStrategy).value.apply(x)
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
sbt.version=1.12.14
|
||||
@@ -0,0 +1,3 @@
|
||||
addSbtPlugin("org.typelevel" % "sbt-tpolecat" % "0.5.7")
|
||||
addSbtPlugin("io.spray" % "sbt-revolver" % "0.10.0")
|
||||
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.4.1")
|
||||
@@ -0,0 +1,16 @@
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<!-- On Windows machines setting withJansi to true enables ANSI
|
||||
color code interpretation by the Jansi library. This requires
|
||||
org.fusesource.jansi:jansi:1.8 on the class path. Note that
|
||||
Unix-based operating systems such as Linux and Mac OS X
|
||||
support ANSI color codes by default. -->
|
||||
<withJansi>true</withJansi>
|
||||
<encoder>
|
||||
<pattern>[%thread] %highlight(%-5level) %cyan(%logger{15}) - %msg %n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.fede.comms
|
||||
|
||||
import cats.effect.Concurrent
|
||||
import cats.syntax.all._
|
||||
import com.fede.comms.emails.{Email, Mensaje}
|
||||
import org.http4s.HttpRoutes
|
||||
import org.http4s.circe.CirceEntityDecoder._
|
||||
import org.http4s.dsl.Http4sDsl
|
||||
|
||||
object CommsRoutes {
|
||||
|
||||
def emailRoutes[F[_]: Concurrent](email: Email[F]): HttpRoutes[F] = {
|
||||
val dsl = new Http4sDsl[F] {}
|
||||
import dsl._
|
||||
HttpRoutes.of[F] {
|
||||
case req @ POST -> Root / "email" =>
|
||||
req.attemptAs[Mensaje].foldF(
|
||||
_ => BadRequest(),
|
||||
mensaje => email.enviar(mensaje) *> Ok()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.fede.comms
|
||||
|
||||
import cats.effect.{Async, Resource}
|
||||
import com.comcast.ip4s._
|
||||
import com.fede.comms.config.SmtpConfig
|
||||
import com.fede.comms.emails.SmtpEmail
|
||||
import fs2.io.net.Network
|
||||
import org.http4s.ember.server.EmberServerBuilder
|
||||
import org.http4s.implicits._
|
||||
import org.http4s.server.middleware.Logger
|
||||
|
||||
object CommsServer {
|
||||
|
||||
def run[F[_]: Async: Network]: F[Nothing] = {
|
||||
for {
|
||||
smtpConfig <- Resource.eval(SmtpConfig.load[F]())
|
||||
email = new SmtpEmail[F](smtpConfig)
|
||||
|
||||
httpApp = CommsRoutes.emailRoutes[F](email).orNotFound
|
||||
|
||||
finalHttpApp = Logger.httpApp(true, true)(httpApp)
|
||||
|
||||
_ <-
|
||||
EmberServerBuilder.default[F]
|
||||
.withHost(ipv4"0.0.0.0")
|
||||
.withPort(port"8088")
|
||||
.withHttpApp(finalHttpApp)
|
||||
.build
|
||||
} yield ()
|
||||
}.useForever
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.fede.comms
|
||||
|
||||
import cats.effect.{IO, IOApp}
|
||||
|
||||
object Main extends IOApp.Simple {
|
||||
val run = CommsServer.run[IO]
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.fede.comms.config
|
||||
|
||||
import cats.effect.Sync
|
||||
|
||||
import java.io.File
|
||||
import scala.io.Source
|
||||
|
||||
final case class SmtpConfig(
|
||||
host: String,
|
||||
port: Int,
|
||||
user: String,
|
||||
password: String,
|
||||
from: String,
|
||||
to: String
|
||||
)
|
||||
|
||||
object SmtpConfig {
|
||||
|
||||
def load[F[_]: Sync](envFile: String = ".env"): F[SmtpConfig] =
|
||||
Sync[F].delay {
|
||||
val env = EnvFile.load(envFile)
|
||||
|
||||
def required(key: String): String =
|
||||
env.getOrElse(key, sys.error(s"Falta $key en $envFile"))
|
||||
|
||||
SmtpConfig(
|
||||
host = required("SMTP_HOST"),
|
||||
port = env.get("SMTP_PORT").flatMap(_.toIntOption).getOrElse(587),
|
||||
user = required("SMTP_USER"),
|
||||
password = required("SMTP_PASSWORD"),
|
||||
from = required("SMTP_FROM"),
|
||||
to = required("SMTP_TO")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
object EnvFile {
|
||||
|
||||
def load(path: String): Map[String, String] = {
|
||||
val file = new File(path)
|
||||
if (!file.exists()) Map.empty
|
||||
else {
|
||||
val lines = Source.fromFile(file).getLines().toList
|
||||
lines.flatMap(parseLine).toMap
|
||||
}
|
||||
}
|
||||
|
||||
private def parseLine(line: String): Option[(String, String)] = {
|
||||
val trimmed = line.trim
|
||||
if (trimmed.isEmpty || trimmed.startsWith("#")) None
|
||||
else {
|
||||
val withoutExport = trimmed.stripPrefix("export").trim
|
||||
val idx = withoutExport.indexOf('=')
|
||||
if (idx <= 0) None
|
||||
else {
|
||||
val key = withoutExport.substring(0, idx).trim
|
||||
val raw = withoutExport.substring(idx + 1).trim
|
||||
val value = raw match {
|
||||
case q if q.length >= 2 && q.head == '"' && q.last == '"' =>
|
||||
q.substring(1, q.length - 1)
|
||||
case q if q.length >= 2 && q.head == '\'' && q.last == '\'' =>
|
||||
q.substring(1, q.length - 1)
|
||||
case other => other
|
||||
}
|
||||
Some(key -> value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.fede.comms.emails
|
||||
|
||||
import cats.effect.Concurrent
|
||||
import io.circe.{Decoder, Encoder}
|
||||
import io.circe.generic.semiauto._
|
||||
import org.http4s.{EntityDecoder, EntityEncoder}
|
||||
import org.http4s.circe._
|
||||
|
||||
final case class Mensaje(titulo: String, descripcion: String, items: List[String], to: String)
|
||||
|
||||
object Mensaje {
|
||||
implicit val mensajeDecoder: Decoder[Mensaje] = deriveDecoder
|
||||
implicit def mensajeEntityDecoder[F[_]: Concurrent]: EntityDecoder[F, Mensaje] = jsonOf
|
||||
|
||||
implicit val mensajeEncoder: Encoder[Mensaje] = deriveEncoder
|
||||
implicit def mensajeEntityEncoder[F[_]]: EntityEncoder[F, Mensaje] = jsonEncoderOf
|
||||
}
|
||||
|
||||
trait Email[F[_]] {
|
||||
def enviar(m: Mensaje): F[Unit]
|
||||
}
|
||||
|
||||
object Email {
|
||||
def apply[F[_]](implicit ev: Email[F]): Email[F] = ev
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.fede.comms.emails
|
||||
|
||||
import cats.effect.Sync
|
||||
import jakarta.mail.internet.{InternetAddress, MimeMessage}
|
||||
import jakarta.mail.{Authenticator, Message, PasswordAuthentication, Session, Transport}
|
||||
|
||||
import java.util.Properties
|
||||
|
||||
final class SmtpEmail[F[_]: Sync](config: com.fede.comms.config.SmtpConfig) extends Email[F] {
|
||||
|
||||
def enviar(m: Mensaje): F[Unit] =
|
||||
Sync[F].blocking {
|
||||
val props = new Properties()
|
||||
props.put("mail.transport.protocol", "smtp")
|
||||
props.put("mail.smtp.host", config.host)
|
||||
props.put("mail.smtp.port", config.port.toString)
|
||||
props.put("mail.smtp.auth", "true")
|
||||
if (config.port == 465) {
|
||||
props.put("mail.smtp.ssl.enable", "true")
|
||||
} else {
|
||||
props.put("mail.smtp.starttls.enable", "true")
|
||||
}
|
||||
|
||||
val session = Session.getInstance(props, new Authenticator {
|
||||
override def getPasswordAuthentication: PasswordAuthentication =
|
||||
new PasswordAuthentication(config.user, config.password)
|
||||
})
|
||||
|
||||
val message = new MimeMessage(session)
|
||||
message.setFrom(new InternetAddress(config.from))
|
||||
message.setRecipients(Message.RecipientType.TO, m.to)
|
||||
message.setSubject(m.titulo, "UTF-8")
|
||||
message.setContent(htmlBody(m), "text/html; charset=utf-8")
|
||||
Transport.send(message)
|
||||
}
|
||||
|
||||
private def htmlBody(m: Mensaje): String = {
|
||||
val itemsHtml =
|
||||
if (m.items.isEmpty) ""
|
||||
else
|
||||
m.items.zipWithIndex
|
||||
.map { case (item, i) =>
|
||||
s"""<tr><td>${i + 1}</td><td>${escape(item)}</td></tr>"""
|
||||
}
|
||||
.mkString(
|
||||
"""<table border="1" cellpadding="6" cellspacing="0" style="border-collapse: collapse;">
|
||||
|<thead><tr><th>#</th><th>Item</th></tr></thead>
|
||||
|<tbody>""".stripMargin,
|
||||
"",
|
||||
"</tbody></table>"
|
||||
)
|
||||
s"""<html><body>
|
||||
|${m.descripcion}
|
||||
|$itemsHtml
|
||||
|</body></html>""".stripMargin
|
||||
}
|
||||
|
||||
private def escape(s: String): String =
|
||||
s.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.fede.comms
|
||||
|
||||
import cats.effect.IO
|
||||
import cats.effect.kernel.Ref
|
||||
import com.fede.comms.emails.{Email, Mensaje}
|
||||
import org.http4s._
|
||||
import org.http4s.implicits._
|
||||
import munit.CatsEffectSuite
|
||||
|
||||
class CommsRoutesSpec extends CatsEffectSuite {
|
||||
|
||||
test("POST /email returns 200 and calls enviar") {
|
||||
val testIO = for {
|
||||
ref <- Ref.of[IO, List[Mensaje]](Nil)
|
||||
email = new Email[IO] {
|
||||
def enviar(m: Mensaje): IO[Unit] = ref.update(_ :+ m)
|
||||
}
|
||||
req = Request[IO](Method.POST, uri"/email")
|
||||
.withEntity(Mensaje("Titulo", "Descripcion", List("a", "b"), "a@b.com"))
|
||||
resp <- CommsRoutes.emailRoutes[IO](email).orNotFound(req)
|
||||
sent <- ref.get
|
||||
} yield (resp.status, sent)
|
||||
|
||||
for {
|
||||
r <- testIO
|
||||
_ <- assertIO(IO.pure(r._1), Status.Ok)
|
||||
_ <- assertIO(IO.pure(r._2), List(Mensaje("Titulo", "Descripcion", List("a", "b"), "a@b.com")))
|
||||
} yield ()
|
||||
}
|
||||
|
||||
test("POST /email with invalid json returns 400") {
|
||||
val email = new Email[IO] {
|
||||
def enviar(m: Mensaje): IO[Unit] = IO.unit
|
||||
}
|
||||
val req = Request[IO](Method.POST, uri"/email").withEntity("{}")
|
||||
assertIO(
|
||||
CommsRoutes.emailRoutes[IO](email).orNotFound(req).map(_.status),
|
||||
Status.BadRequest
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.fede.comms
|
||||
|
||||
import cats.effect.IO
|
||||
import com.fede.comms.config.SmtpConfig
|
||||
import com.fede.comms.emails.{Mensaje, SmtpEmail}
|
||||
import munit.CatsEffectSuite
|
||||
|
||||
class SmtpEmailSpec extends CatsEffectSuite {
|
||||
|
||||
test("envia un email real usando el .env") {
|
||||
for {
|
||||
config <- SmtpConfig.load[IO]()
|
||||
email = new SmtpEmail[IO](config)
|
||||
to = sys.env.getOrElse("SMTP_TO", config.from)
|
||||
_ <- email.enviar(
|
||||
Mensaje(
|
||||
titulo = "[comms] prueba",
|
||||
descripcion = "Email de prueba desde el servicio comms",
|
||||
items = List("item 1", "item 2"),
|
||||
to = to
|
||||
)
|
||||
)
|
||||
} yield ()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user