Slide 1

Slide 1 text

CONNECTING THE DOTS BUILDING AND STRUCTURING A FUNCTIONAL APPLICATION IN SCALA JAKUB KOZŁOWSKI, DISNEY STREAMING YOW! LAMBDA JAM 2021 Photo by Kumiko SHIMIZU on Unsplash

Slide 2

Slide 2 text

PROBLEM STATEMENT

Slide 3

Slide 3 text

PROBLEM STATEMENT We want to build an application

Slide 4

Slide 4 text

PROBLEM STATEMENT We want to build an application There are some sources of data (databases, APIs, event streams)

Slide 5

Slide 5 text

PROBLEM STATEMENT We want to build an application There are some sources of data (databases, APIs, event streams) We need to serve HTTP traffic

Slide 6

Slide 6 text

PROBLEM STATEMENT We want to build an application There are some sources of data (databases, APIs, event streams) We need to serve HTTP traffic Some things need to run in the background additionally

Slide 7

Slide 7 text

PROBLEM STATEMENT We want to build an application There are some sources of data (databases, APIs, event streams) We need to serve HTTP traffic Some things need to run in the background additionally We want to do it with FP

Slide 8

Slide 8 text

DEPENDENCY GRAPH TYPICAL APPLICATION

Slide 9

Slide 9 text

DEPENDENCY GRAPH def database: Database def businessLogic(db: Database): BusinessLogic def server(logic: BusinessLogic): Server def backgroundProcesses(logic: BusinessLogic): Processes

Slide 10

Slide 10 text

DEPENDENCY GRAPH def database: Database def businessLogic(db: Database): BusinessLogic def server(logic: BusinessLogic): Server def backgroundProcesses(logic: BusinessLogic): Processes def build: (Server, Processes) = { val logic = businessLogic(database) (server(logic), backgroundProcesses(logic)) }

Slide 11

Slide 11 text

DEPENDENCY GRAPH This could be us, but the real world exists... def database: Database def businessLogic(db: Database): BusinessLogic def server(logic: BusinessLogic): Server def backgroundProcesses(logic: BusinessLogic): Processes def build: (Server, Processes) = { val logic = businessLogic(database) (server(logic), backgroundProcesses(logic)) }

Slide 12

Slide 12 text

RESOURCES.

Slide 13

Slide 13 text

RESOURCES. But we can just kill our application when it quits, right?

Slide 14

Slide 14 text

CONNECTION POOLS?

Slide 15

Slide 15 text

CONNECTION POOLS? But we can use try-finally, right?

Slide 16

Slide 16 text

def getConnection(db: Database): Connection def returnConnection(conn: Connection): Unit def doWork(conn: Connection): Result TRY-FINALLY

Slide 17

Slide 17 text

def getConnection(db: Database): Connection def returnConnection(conn: Connection): Unit def doWork(conn: Connection): Result TRY-FINALLY val result = { val c = getConnection(db) try doWork(c) finally returnConnection(c) }

Slide 18

Slide 18 text

def getConnection(db: Database): IO[Connection] def returnConnection(conn: Connection): IO[Unit] def doWork(conn: Connection): IO[Result] TRY-FINALLY IN FP val result: IO[Result] = getConnection(db).bracket { c !=> doWork(c) }(returnConnection)

Slide 19

Slide 19 text

MORE RESOURCES? Can't keep nesting bracket forever

Slide 20

Slide 20 text

MORE RESOURCES? Can't keep nesting bracket forever ABSTRACTION? How to hide details?

Slide 21

Slide 21 text

RESOURCE DATA STRUCTURE

Slide 22

Slide 22 text

RUNNING A RESOURCE?

Slide 23

Slide 23 text

RUNNING A RESOURCE?

Slide 24

Slide 24 text

COMPOSITION?

Slide 25

Slide 25 text

WHY AM I TALKING ABOUT THIS? def database: Database def businessLogic(db: Database): BusinessLogic def server(logic: BusinessLogic): Server def backgroundProcesses(logic: BusinessLogic): Processes

Slide 26

Slide 26 text

WHY AM I TALKING ABOUT THIS? def database: Resource[Database] def businessLogic(db: Database): BusinessLogic def server(logic: BusinessLogic): Resource[Server] def backgroundProcesses(logic: BusinessLogic): Resource[Processes]

Slide 27

Slide 27 text

WHY AM I TALKING ABOUT THIS? def database: Resource[Database] def businessLogic(db: Database): BusinessLogic def server(logic: BusinessLogic): Resource[Server] def backgroundProcesses(logic: BusinessLogic): Resource[Processes] def build: Resource[(Server, Processes)] = database.flatMap { db !=> val logic = businessLogic(db) server(logic).flatMap { srv !=> backgroundProcesses(logic).map(p !=> (srv, p)) } }

Slide 28

Slide 28 text

WHY AM I TALKING ABOUT THIS? def database: Resource[Database] def businessLogic(db: Database): BusinessLogic def server(logic: BusinessLogic): Resource[Server] def backgroundProcesses(logic: BusinessLogic): Resource[Processes] def build: Resource[(Server, Processes)] = for { db !<- database logic = businessLogic(db) srv !<- server(logic) processes !<- backgroundProcesses(logic) } yield (srv, processes)

Slide 29

Slide 29 text

HOW IS A BACKGROUND PROCESS A RESOURCE? Watch this space: yt.kubukoz.com -> "Background processing in functional Scala" playlist

Slide 30

Slide 30 text

DEPENDENCY GRAPH AS A RESOURCE

Slide 31

Slide 31 text

ALGEBRAS / CAPABILITY TRAITS

Slide 32

Slide 32 text

ALGEBRAS / CAPABILITY TRAITS Tagless Final style

Slide 33

Slide 33 text

ALGEBRAS / CAPABILITY TRAITS Tagless Final style Interfaces parameterised by an effect

Slide 34

Slide 34 text

ALGEBRAS / CAPABILITY TRAITS Tagless Final style Interfaces parameterised by an effect Capability traits - lawless type classes

Slide 35

Slide 35 text

RULES OF THUMB

Slide 36

Slide 36 text

RULES OF THUMB Prefer capability traits (Files[F], Network[F], Console[F]) over Sync/Async

Slide 37

Slide 37 text

RULES OF THUMB Prefer capability traits (Files[F], Network[F], Console[F]) over Sync/Async Implicit or explicit?

Slide 38

Slide 38 text

RULES OF THUMB Prefer capability traits (Files[F], Network[F], Console[F]) over Sync/Async Implicit or explicit? - 1 instance per type: implicit definition, pass implicitly

Slide 39

Slide 39 text

RULES OF THUMB Prefer capability traits (Files[F], Network[F], Console[F]) over Sync/Async Implicit or explicit? - 1 instance per type: implicit definition, pass implicitly - has possible test instance: explicit definition, pass implicitly

Slide 40

Slide 40 text

RULES OF THUMB Prefer capability traits (Files[F], Network[F], Console[F]) over Sync/Async Implicit or explicit? - 1 instance per type: implicit definition, pass implicitly - has possible test instance: explicit definition, pass implicitly - multiple instances in app: all explicit

Slide 41

Slide 41 text

IMAGE PROCESSING APP CASE STUDY

Slide 42

Slide 42 text

IMAGE PROCESSING APP CASE STUDY Project Goals

Slide 43

Slide 43 text

IMAGE PROCESSING APP CASE STUDY Project Goals Search images from a datasource by the text on them (OCR)

Slide 44

Slide 44 text

IMAGE PROCESSING APP CASE STUDY Project Goals Search images from a datasource by the text on them (OCR) Live OCR is too slow, so we'll index ahead of time

Slide 45

Slide 45 text

IMAGE PROCESSING APP CASE STUDY Project Goals Search images from a datasource by the text on them (OCR) Live OCR is too slow, so we'll index ahead of time github.com/kubukoz/dropbox-demo

Slide 46

Slide 46 text

DATA FLOW (LINEAR)

Slide 47

Slide 47 text

TANGENT: HEXAGONAL ARCHITECTURE Hexagonal Architecture by Cth027, licensed under CC BY-SA 4.0

Slide 48

Slide 48 text

TANGENT: HEXAGONAL ARCHITECTURE Hexagonal Architecture by Cth027, licensed under CC BY-SA 4.0 Or... just sensible architecture.

Slide 49

Slide 49 text

TANGENT: HEXAGONAL ARCHITECTURE Hexagonal Architecture by Cth027, licensed under CC BY-SA 4.0 Or... just sensible architecture. Keep vendor/implementation-specific details hidden and away from core logic

Slide 50

Slide 50 text

TANGENT: HEXAGONAL ARCHITECTURE Hexagonal Architecture by Cth027, licensed under CC BY-SA 4.0 Or... just sensible architecture. Keep vendor/implementation-specific details hidden and away from core logic Only talk to these via adapters with a simple API

Slide 51

Slide 51 text

TANGENT: HEXAGONAL ARCHITECTURE Hexagonal Architecture by Cth027, licensed under CC BY-SA 4.0 Jakub Nabrdalik - Hexagonal Architecture in practice https://www.youtube.com/watch?v=sOaS83Ir8Ck Or... just sensible architecture. Keep vendor/implementation-specific details hidden and away from core logic Only talk to these via adapters with a simple API

Slide 52

Slide 52 text

DEPENDENCY GRAPH

Slide 53

Slide 53 text

PROJECT STRUCTURE shared - contains common vocabulary Used by adapters and core logic imagesource, ocr, indexer - modules root - contains core logic + http module Standard sbt pattern for "main" sources

Slide 54

Slide 54 text

OCR MODULE

Slide 55

Slide 55 text

OCR MODULE ProcessRunner - capability trait for running system processes

Slide 56

Slide 56 text

OCR MODULE ProcessRunner - capability trait for running system processes Tesseract - runs a Tesseract process

Slide 57

Slide 57 text

OCR MODULE ProcessRunner - capability trait for running system processes Tesseract - runs a Tesseract process OCR - wraps Tesseract and specifies config options (languages)

Slide 58

Slide 58 text

OCR MODULE ProcessRunner - capability trait for running system processes Tesseract - runs a Tesseract process OCR - wraps Tesseract and specifies config options (languages) TestOCRInstances - contains test fakes for OCR for usage in tests of higher-level components (processes)

Slide 59

Slide 59 text

PROCESS RUNNER package com.kubukoz.process trait ProcessRunner[F[_]] { def run(program: List[String]): Resource[F, ProcessRunner.Running[F]] } object ProcessRunner { def apply[F[_]](implicit F: ProcessRunner[F]): ProcessRunner[F] = F implicit def instance[F[_]: Async]: ProcessRunner[F] = !!... }

Slide 60

Slide 60 text

TESSERACT package com.kubukoz.ocr.tesseract private[ocr] trait Tesseract[F[_]] { def decode(input: fs2.Stream[F, Byte], languages: List[String]): F[String] } object Tesseract { def apply[F[_]](implicit F: Tesseract[F]): Tesseract[F] = F def instance[F[_]: ProcessRunner: Logger: Concurrent](implicit SC: fs2.Compiler[F, F]): Tesseract[F] = !!... }

Slide 61

Slide 61 text

OCR

Slide 62

Slide 62 text

package com.kubukoz.ocr trait OCR[F[_]] { def decodeText(file: fs2.Stream[F, Byte]): F[DecodedText] } object OCR { def apply[F[_]](implicit F: OCR[F]): OCR[F] = F } OCR

Slide 63

Slide 63 text

package com.kubukoz.ocr trait OCR[F[_]] { def decodeText(file: fs2.Stream[F, Byte]): F[DecodedText] } object OCR { def apply[F[_]](implicit F: OCR[F]): OCR[F] = F } OCR final case class Config(languages: List[String]) def config[F[_]]: ConfigValue[F, Config] = !!...

Slide 64

Slide 64 text

package com.kubukoz.ocr trait OCR[F[_]] { def decodeText(file: fs2.Stream[F, Byte]): F[DecodedText] } object OCR { def apply[F[_]](implicit F: OCR[F]): OCR[F] = F } OCR final case class Config(languages: List[String]) def config[F[_]]: ConfigValue[F, Config] = !!... private[ocr] def tesseractInstance[F[_]: Tesseract: Functor](config: Config): OCR[F] = new OCR[F] { def decodeText(file: fs2.Stream[F, Byte]): F[DecodedText] = Tesseract[F].decode(file, config.languages).map(DecodedText(_)) }

Slide 65

Slide 65 text

package com.kubukoz.ocr trait OCR[F[_]] { def decodeText(file: fs2.Stream[F, Byte]): F[DecodedText] } object OCR { def apply[F[_]](implicit F: OCR[F]): OCR[F] = F } OCR final case class Config(languages: List[String]) def config[F[_]]: ConfigValue[F, Config] = !!... private[ocr] def tesseractInstance[F[_]: Tesseract: Functor](config: Config): OCR[F] = new OCR[F] { def decodeText(file: fs2.Stream[F, Byte]): F[DecodedText] = Tesseract[F].decode(file, config.languages).map(DecodedText(_)) } def module[F[_]: Concurrent: ProcessRunner: Logger](config: Config): OCR[F] = { implicit val tesseract = Tesseract.instance[F] OCR.tesseractInstance[F](config) }

Slide 66

Slide 66 text

package com.kubukoz.ocr object TestOCRInstances { !// decodeText("hello".getBytes) !== "hello" def simple[F[_]: Functor](implicit SC: fs2.Compiler[F, F]): OCR[F] = _.through(fs2.text.utf8Decode[F]).compile.string.map(DecodedText(_)) } TEST INSTANCE

Slide 67

Slide 67 text

WIRING IT ALL UP

Slide 68

Slide 68 text

WIRING IT ALL UP

Slide 69

Slide 69 text

object Application { final case class Config( indexer: Indexer.Config, imageSource: ImageSource.Config, processQueue: ProcessQueue.Config, ocr: OCR.Config, http: HttpServer.Config, ) }

Slide 70

Slide 70 text

object Application { final case class Config( indexer: Indexer.Config, imageSource: ImageSource.Config, processQueue: ProcessQueue.Config, ocr: OCR.Config, http: HttpServer.Config, ) } def config[F[_]: ApplicativeThrow]: ConfigValue[F, Config] = ( Indexer.config[F], ImageSource.config[F], ProcessQueue.config[F], OCR.config[F], HttpServer.config[F], ).parMapN(Config)

Slide 71

Slide 71 text

object Application { final case class Config( indexer: Indexer.Config, imageSource: ImageSource.Config, processQueue: ProcessQueue.Config, ocr: OCR.Config, http: HttpServer.Config, ) } def config[F[_]: ApplicativeThrow]: ConfigValue[F, Config] = ( Indexer.config[F], ImageSource.config[F], ProcessQueue.config[F], OCR.config[F], HttpServer.config[F], ).parMapN(Config) def run[F[_]: Async: Logger](config: Config): Resource[F, Server] = for { implicit0(client: Client[F]) !<- HttpClient.instance[F] }

Slide 72

Slide 72 text

object Application { final case class Config( indexer: Indexer.Config, imageSource: ImageSource.Config, processQueue: ProcessQueue.Config, ocr: OCR.Config, http: HttpServer.Config, ) } def config[F[_]: ApplicativeThrow]: ConfigValue[F, Config] = ( Indexer.config[F], ImageSource.config[F], ProcessQueue.config[F], OCR.config[F], HttpServer.config[F], ).parMapN(Config) def run[F[_]: Async: Logger](config: Config): Resource[F, Server] = for { implicit0(client: Client[F]) !<- HttpClient.instance[F] } implicit0(imageSource: ImageSource[F]) !<- ImageSource.module[F](config.imageSource).toResource implicit0(indexer: Indexer[F]) !<- Indexer.module[F](config.indexer) implicit0(ocr: OCR[F]) !<- OCR.module[F](config.ocr).pure[Resource[F, *]]

Slide 73

Slide 73 text

object Application { final case class Config( indexer: Indexer.Config, imageSource: ImageSource.Config, processQueue: ProcessQueue.Config, ocr: OCR.Config, http: HttpServer.Config, ) } def config[F[_]: ApplicativeThrow]: ConfigValue[F, Config] = ( Indexer.config[F], ImageSource.config[F], ProcessQueue.config[F], OCR.config[F], HttpServer.config[F], ).parMapN(Config) def run[F[_]: Async: Logger](config: Config): Resource[F, Server] = for { implicit0(client: Client[F]) !<- HttpClient.instance[F] } implicit0(imageSource: ImageSource[F]) !<- ImageSource.module[F](config.imageSource).toResource implicit0(indexer: Indexer[F]) !<- Indexer.module[F](config.indexer) implicit0(ocr: OCR[F]) !<- OCR.module[F](config.ocr).pure[Resource[F, *]] processQueue !<- ProcessQueue.instance(config.processQueue)

Slide 74

Slide 74 text

object Application { final case class Config( indexer: Indexer.Config, imageSource: ImageSource.Config, processQueue: ProcessQueue.Config, ocr: OCR.Config, http: HttpServer.Config, ) } def config[F[_]: ApplicativeThrow]: ConfigValue[F, Config] = ( Indexer.config[F], ImageSource.config[F], ProcessQueue.config[F], OCR.config[F], HttpServer.config[F], ).parMapN(Config) def run[F[_]: Async: Logger](config: Config): Resource[F, Server] = for { implicit0(client: Client[F]) !<- HttpClient.instance[F] } implicit0(imageSource: ImageSource[F]) !<- ImageSource.module[F](config.imageSource).toResource implicit0(indexer: Indexer[F]) !<- Indexer.module[F](config.indexer) implicit0(ocr: OCR[F]) !<- OCR.module[F](config.ocr).pure[Resource[F, *]] processQueue !<- ProcessQueue.instance(config.processQueue) implicit0(index: Index[F]) !<- Index.instance[F](processQueue).pure[Resource[F, *]] implicit0(download: Download[F]) !<- Download.instance[F].pure[Resource[F, *]] implicit0(search: Search[F]) !<- Search.instance[F](serverInfo.get).pure[Resource[F, *]]

Slide 75

Slide 75 text

object Application { final case class Config( indexer: Indexer.Config, imageSource: ImageSource.Config, processQueue: ProcessQueue.Config, ocr: OCR.Config, http: HttpServer.Config, ) } def config[F[_]: ApplicativeThrow]: ConfigValue[F, Config] = ( Indexer.config[F], ImageSource.config[F], ProcessQueue.config[F], OCR.config[F], HttpServer.config[F], ).parMapN(Config) def run[F[_]: Async: Logger](config: Config): Resource[F, Server] = for { implicit0(client: Client[F]) !<- HttpClient.instance[F] } implicit0(imageSource: ImageSource[F]) !<- ImageSource.module[F](config.imageSource).toResource implicit0(indexer: Indexer[F]) !<- Indexer.module[F](config.indexer) implicit0(ocr: OCR[F]) !<- OCR.module[F](config.ocr).pure[Resource[F, *]] processQueue !<- ProcessQueue.instance(config.processQueue) implicit0(index: Index[F]) !<- Index.instance[F](processQueue).pure[Resource[F, *]] implicit0(download: Download[F]) !<- Download.instance[F].pure[Resource[F, *]] implicit0(search: Search[F]) !<- Search.instance[F](serverInfo.get).pure[Resource[F, *]] server !<- HttpServer.instance[F](config.http) yield server

Slide 76

Slide 76 text

A COUPLE GUIDELINES TESTING

Slide 77

Slide 77 text

A COUPLE GUIDELINES TESTING Test the contract, not the implementation

Slide 78

Slide 78 text

A COUPLE GUIDELINES TESTING Test the contract, not the implementation Prefer fakes over mocks/stubs

Slide 79

Slide 79 text

A COUPLE GUIDELINES TESTING Test the contract, not the implementation Prefer fakes over mocks/stubs Test your fakes with the same suite as the real things

Slide 80

Slide 80 text

TESTING

Slide 81

Slide 81 text

TESTING index.schedule(Path("/hello"))

Slide 82

Slide 82 text

TESTING index.schedule(Path("/hello")) val file = fakeFile("hello world", "/hello/world") imageSource.uploadFile(file.fileData) !*>

Slide 83

Slide 83 text

TESTING index.schedule(Path("/hello")) val file = fakeFile("hello world", "/hello/world") imageSource.uploadFile(file.fileData) !*> !*> indexer.search("hello").compile.toList

Slide 84

Slide 84 text

TESTING index.schedule(Path("/hello")) val file = fakeFile("hello world", "/hello/world") imageSource.uploadFile(file.fileData) !*> !*> indexer.search("hello").compile.toList { }.map { results !=> expect(results !== List(file.fileDocument)) }

Slide 85

Slide 85 text

TESTING Await blogpost for more ;) index.schedule(Path("/hello")) val file = fakeFile("hello world", "/hello/world") imageSource.uploadFile(file.fileData) !*> !*> indexer.search("hello").compile.toList { }.map { results !=> expect(results !== List(file.fileDocument)) }

Slide 86

Slide 86 text

SUMMARY

Slide 87

Slide 87 text

TIPS

Slide 88

Slide 88 text

TIPS Use Resource + IO for stateful dependencies

Slide 89

Slide 89 text

TIPS Use Resource + IO for stateful dependencies Define clear responsibilities for modules

Slide 90

Slide 90 text

TIPS Use Resource + IO for stateful dependencies Define clear responsibilities for modules Design for replacement

Slide 91

Slide 91 text

TIPS Use Resource + IO for stateful dependencies Define clear responsibilities for modules Design for replacement Look for abstractions

Slide 92

Slide 92 text

TIPS Use Resource + IO for stateful dependencies Define clear responsibilities for modules Design for replacement Look for abstractions Prototype early

Slide 93

Slide 93 text

TIPS Use Resource + IO for stateful dependencies Define clear responsibilities for modules Design for replacement Look for abstractions Prototype early Draw some diagrams, see if you have too many arrows ;)

Slide 94

Slide 94 text

LEARN MORE Check out the sources: github.com/kubukoz/dropbox-demo Read "Practical FP in Scala" by Gabriel Volpe github.com/scala-steward-org/scala-steward github.com/branchtalk-io/backend github.com/kubukoz/spotify-next github.com/pitgull/pitgull leanpub.com/pfp-scala

Slide 95

Slide 95 text

THANK YOU 📰 blog.kubukoz.com 🐦 @kubukoz Slides: speakerdeck.com/kubukoz Code: git.io/JONEj Find me on YouTube! (yt.kubukoz.com)