-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
ConnectionStream.scala
77 lines (67 loc) · 2.7 KB
/
ConnectionStream.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* Copyright 2017-2019 Fs2 Rabbit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.gvolpe.fs2rabbit.interpreter
import javax.net.ssl.SSLContext
import cats.effect.Sync
import cats.syntax.apply._
import cats.syntax.flatMap._
import cats.syntax.functor._
import com.github.gvolpe.fs2rabbit.algebra.Connection
import com.github.gvolpe.fs2rabbit.config.Fs2RabbitConfig
import com.github.gvolpe.fs2rabbit.model.{AMQPChannel, RabbitChannel}
import com.github.gvolpe.fs2rabbit.effects.Log
import com.rabbitmq.client.{ConnectionFactory, Connection => RabbitMQConnection}
import fs2.Stream
class ConnectionStream[F[_]](factory: ConnectionFactory)(implicit F: Sync[F], L: Log[F])
extends Connection[Stream[F, ?]] {
private[fs2rabbit] val acquireConnection: F[(RabbitMQConnection, AMQPChannel)] =
for {
conn <- F.delay(factory.newConnection)
channel <- F.delay(conn.createChannel)
} yield (conn, RabbitChannel(channel))
/**
* Creates a connection and a channel in a safe way using Stream.bracket.
* In case of failure, the resources will be cleaned up properly.
**/
override def createConnectionChannel: Stream[F, AMQPChannel] =
Stream
.bracket(acquireConnection) {
case (conn, RabbitChannel(channel)) =>
L.info(s"Releasing connection: $conn previously acquired.") *>
F.delay { if (channel.isOpen) channel.close() } *> F.delay { if (conn.isOpen) conn.close() }
case (_, _) => F.raiseError[Unit](new Exception("Unreachable"))
}
.map { case (_, channel) => channel }
}
object ConnectionStream {
private[fs2rabbit] def mkConnectionFactory[F[_]: Sync](
config: Fs2RabbitConfig,
sslContext: Option[SSLContext]
): F[ConnectionFactory] =
Sync[F].delay {
val factory = new ConnectionFactory()
factory.setHost(config.host)
factory.setPort(config.port)
factory.setVirtualHost(config.virtualHost)
factory.setConnectionTimeout(config.connectionTimeout)
if (config.ssl) {
sslContext.fold(factory.useSslProtocol())(factory.useSslProtocol)
}
config.username.foreach(factory.setUsername)
config.password.foreach(factory.setPassword)
factory
}
}