0:02 This is a checkout endpoint. It's normal TypeScript, 0:06 async/await, try catch, and Postgres. 0:10 It would totally pass code review, and I would've approved it, 0:14 but let's watch what happens when a customer's phone loses signal 0:18 halfway through paying. 0:21 The customer saw an error page, and then 0:25 three keyboards left the warehouse, an order got written, 0:30 and their card got charged, but they're gonna hit buy 0:34 again. Now, this is the same API, the same 0:38 database, and the same fake payment provider 0:41 rewritten 0:42 with Effect. 0:44 Let's go ahead and invoke this just the same. 0:47 Now, as we can see, nothing was charged, 0:51 nothing was reserved, and nothing was written. 0:55 By the end of this video, you'll know exactly why. 0:59 Not just the hangup, but typed errors, 1:03 retries, timeouts that actually cancel things, and 1:07 dependency injection without decorators. 1:10 And one of my favorite features is writing tests without a 1:14 single mock. It all sounds too good to be true, 1:17 but with Effect, it 1:18 makes it possible with ease. It's all in one small repro, 1:22 linked below. And in this lecture, I'm gonna show you the same 1:26 API before and after, rewritten inside of 1:30 Effect. By doing so, you'll see the major benefits of 1:34 Effect, the core concepts you need to understand, 1:37 and why you might wanna 1:38 use it for your next project. So before we touch any code, 1:42 a quick word on what Effect actually is, because the 1:46 name doesn't tell you much. 1:49 So Effect is an open source TypeScript library. 1:52 The simplest way I can put it is that it's the standard library 1:56 TypeScript never shipped with, 1:59 aimed at the boring, hard parts of production code: 2:03 errors, retries, timeouts, concurrency, 2:07 cancellation, dependency injection, config, 2:11 logging, and tracing. Every real backend ends up needing 2:15 all of these. Normally, you get them from a dozen different 2:17 packages, or you 2:19 hand roll them, and none of them know about each other. 2:22 Effect gives you one model for all of them. 2:25 The retry knows about the timeout, the timeout knows how to 2:29 cancel, cancellation knows how to run your 2:31 cleanup, and the 2:33 type system tracks all of it. The core idea fits in 2:37 one sentence: an Effect is a description of a program, 2:41 not a program that's already running. 2:43 A promise starts the moment you create it, and from then on, you can 2:47 only wait for it. An Effect is a value, like a recipe. 2:52 Because nothing has run yet, the runtime can add retries, 2:56 time it out, race it, cancel it, or swap out what it 3:00 depends on before and while it runs. 3:03 So why use it for this video on a checkout endpoint? 3:07 Because checkout is exactly where plain async/await gets 3:10 quietly dangerous. You're touching money and inventory, 3:14 talking to a flaky third party, doing things in parallel, 3:18 and a client can vanish at any moment. 3:21 Most of the bugs there aren't in the happy path. 3:24 They're in the what if this fails halfway paths, and those 3:28 are the 3:28 paths TypeScript types don't see at all. 3:31 So let's go ahead and start with the code most of us would 3:34 actually write. 3:34 I'll show you the before of this TypeScript API, 3:38 and then after, we're gonna rewrite this in Effect 3:41 and learn how to implement all 3:42 of these great features that Effect gives us out of the box. 3:46 I'll see you there. 3:48 Now, before we start, a quick word about my site. 3:51 If you like how I teach, I've put all my courses and lectures in 3:55 one place at learn.michaelguay.dev. 3:58 I'll leave a link to it below. Every course that I have on this site 4:02 builds from a real project from git init all the way to 4:06 deploying to production. My current course is NestJS 4:10 Durable Workflows, and it's about business processes 4:13 that survive 4:13 crashes. All of my future content and courses will only be available 4:17 on this site, and you get access to tons of extra 4:21 content through video lectures covering all advanced full 4:25 stack material. And even in the future, I'm thinking of doing a 4:29 brand-new course now on Effect that you can get access to as part of this 4:33 site. 4:34 So thanks so much for checking it out. I'll leave a link below. 4:37 Let's go ahead and jump right in. All right, so to go ahead and get started, 4:40 I've 4:41 pushed the completed repository for this lecture to 4:44 GitHub, and I'll leave a link to this below. 4:47 However, on here, I've also pushed another branch called 4:50 starting point, 4:51 and this is where we're gonna start the project from. 4:54 Here will only contain the starting repository and the 4:57 code before we refactor it in Effect, so it allows you to start off 5:01 at the same point as me. I'm gonna go ahead and copy 5:05 this repository URL, 5:08 and then simply go ahead and run git clone to clone the repository 5:12 to 5:12 your local repo. Once you've cloned it, you can then run git 5:16 checkout starting point to get onto that starting 5:19 point branch. Now, here, we're also gonna be using 5:23 Bun as our dependency manager and runtime. 5:27 So if you don't have Bun installed on your machine, I'll leave another link below 5:31 where you can get access to it, which is the fastest runtime and package 5:35 manager to execute our TypeScript code. 5:38 Now, importantly, Effect is not a compiler, and 5:42 it's not a dependency manager. We still need 5:46 a compiler, a runtime like Bun, to actually execute our 5:49 TypeScript, and Effect is essentially a 5:52 intermediate layer between the application and the 5:56 runtime. So with Bun available, make sure you also run Bun 6:00 install to get the latest dependencies, and then go ahead and open 6:04 up the code in your code editor so we can go ahead and take a look at it. 6:09 So this is the starting project inside of VS Code. 6:13 Now I'm not gonna jump through everything here, as I'll leave you to do 6:17 so. We wanna focus on Effect in this short 6:20 lecture. 6:20 We have a starting package JSON with some commands to bring 6:24 up our PostgreSQL database and also execute 6:28 a demo script. 6:31 So we have the DB up and some demo commands 6:33 which we'll run later on. 6:35 We have a Docker Compose file which just simply declares a single 6:38 PostgreSQL 6:39 service which is our database that the application connects to. 6:43 We also have a .env.example file in 6:47 here, and this is gonna provide our BUN 6:50 application 6:51 with any environment variables it needs to run. 6:54 Here we have the database URL which is the connection string to the 6:58 Docker container which is our PostgreSQL database. 7:01 And a couple more like the ports for our before and after 7:05 applications and some further configuration values that 7:09 we will use later on. 7:11 Now, to make sure that we actually have this environment 7:14 file available, 7:15 go ahead and run this command to copy the example into the 7:19 root application.env. This will make sure we have this 7:23 .env and this is what the application will read. 7:26 By default, BUN reads in .env files and all the environment 7:29 variables inside automatically without us having to do anything 7:33 else, which is another great advantage. 7:37 So now that we have 7:39 this set up here, we have the environment variables our 7:42 application will need. 7:44 We also have a test folder which is empty. 7:47 We're gonna set up tests later on and see how Effect makes testing our 7:50 TypeScript code a lot easier. 7:53 We also have our scripts folder which is gonna contain a demo 7:57 script that walks through our application's API and 8:01 essentially demonstrates the concepts that we want to see in 8:05 this application. Now, we're gonna jump further into this demo 8:08 script once 8:09 we're ready to actually execute it. 8:11 For now, just know that this will allow us to test the 8:13 application and the 8:15 concepts that we'll review in this lecture. 8:18 Finally, I just have a DB folder which contains our migration 8:21 scripts to get the database schema in 8:25 line with the 8:28 same expectation that the code expects. 8:30 So we have a table for our underlying products, 8:34 orders, 8:36 and also a seed command to actually insert some 8:40 dummy data into the database. So here I'm inserting into 8:43 products with a few columns and the orders. 8:47 And so in here we're inserting in some dummy products like a keyboard, mouse, and 8:51 monitor. The product contains these following 8:54 columns to store the 8:55 data and then we have orders that we're actually gonna create by 8:59 simply referencing the products that already exist by their ID. 9:03 So we'll walk through this in the application on how to actually create 9:07 these 9:07 orders inside of both APIs 9:11 and this starting data will allow us to reference these products 9:15 later on inside of the demo script. 9:18 Now in our package JSON we have a command to DB up, 9:22 start up the PostgreSQL container with Docker Compose and bring it 9:26 down. 9:28 And then the rest of the commands here are to invoke the demo script which we'll 9:32 see later on. Part of that is to reference and use this 9:35 SQL migration file and apply it against our database so the 9:39 demo script takes care of that for us. 9:43 Now finally, this migration file, this init.sql, 9:47 is actually loaded in from our Docker Compose through a volume. 9:51 So we're actually hosting this init SQL file and 9:55 mounting it onto this Docker entry point folder and this 9:59 essentially means that this SQL migration file will get 10:02 executed 10:03 when the PostgreSQL container starts up and automatically get our 10:06 database in line with this desired schema including 10:10 the dummy products which is great. 10:12 So we have the application and the dependencies all 10:16 available and ready to run. Finally, let's go ahead and now 10:19 see inside of the source directory we have the before and after 10:23 folders. After is empty as we're gonna be writing 10:26 this 10:26 ourselves and before is gonna contain the existing 10:30 application API. 10:33 So let's go ahead and jump into this next. 10:36 So looking at our API as it exists today, let's go ahead and 10:39 start off with the main.ts file. This is the entry point to the 10:43 application. In our package JSON, the before command 10:47 here actually invokes the main.ts file directly by 10:51 running BUN run. Another key benefit to using BUN 10:54 is we can execute 10:54 TypeScript directly without having to transpile it to... 10:58 from JavaScript. And now if we look at this main.ts, let's go 11:02 ahead and 11:04 dive into this a bit more. 11:07 So the first thing that we have here is a global database 11:11 client. This will allow every function in here to 11:14 reach out, 11:15 grab it, and interact with the database. 11:19 So we simply just are using the PostgreSQL driver from... 11:24 for BUN and Node and notice in our package JS this is 11:28 part of our dependencies. So PostgreSQL driver is 11:31 automatically included as well as Effect. 11:34 Effect is just another dependency. 11:37 We also have a couple of other Effect dependencies that we'll see how they're 11:41 used later. One is actually a platform BUN 11:44 adapter 11:46 and an SQL PostgreSQL dependency and both of these 11:50 will come into play later on. So we have our dependencies. 11:53 We've already installed these, so we have the PostgreSQL driver 11:57 available and like I said, BUN will automatically read in 12:00 .env environment variables to the application. 12:04 So since we have the .env and we are including the database URL, 12:08 we can directly read this from the env now using 12:11 process.env database URL and BUN takes care of this for 12:15 us. So now we have the connection string to 12:18 the database, we've established 12:19 the connection, and we can run SQL against it directly 12:23 thanks to this database connection that has been established. 12:27 Next up, we have a function 12:29 chargeWithRetry. Payments are flaky, so we 12:33 want to retry, and that's exactly what this function 12:36 does. 12:36 It is going to charge our payment provider, 12:40 in this case coming from a separate file, 12:44 and we simply call .charge on it. It exposes this charge 12:48 function. 12:49 And to implement our retry, we are keeping track of our current 12:53 attempt iteration and have a while loop where we say 12:57 while true with a try catch inside. 13:00 We are going to call chargeWithAmount Cents that's passed 13:04 in and the cardToken, which represents a Stripe 13:08 card token or any other payment provider will have some sort of a 13:12 card token to reference the card that we are charging. 13:16 And by calling return await, we now create this promise and dispatch 13:20 it to payments and tell it to charge. 13:23 And thanks to the catch block, any errors that now occur, we are going to 13:27 enter here. We are going to firstly iterate the 13:29 attempt that we are on, 13:31 and then we are catching this error type. 13:34 Notice this error type is of type Any. 13:37 This is one of the major flaws with TypeScript out of the box, 13:41 which Effect is going to make so much better. 13:44 We have no idea what this error is. We have no idea what it 13:47 caught. So line 23 here, this is a common pattern. 13:51 We have to decide whether to retry this error 13:55 by checking the error message 13:59 and comparing a string directly. In this case, we are 14:02 relying on payments.charge, dispatching to 14:06 an underlying payment SDK. And now here inside of the 14:10 calling function, we sort of have a leaky abstraction. 14:13 We have to know that the payment provider is 14:17 gonna return us this error message type, and we are relying on 14:21 this to catch the error. Now, if someone in the payments 14:25 module renames this error message at any point, this will 14:29 still compile and silently fail at runtime. 14:33 This is one of the first real issues with TypeScript that Effect 14:37 makes so much better. It essentially is this type safety around our 14:40 errors, because here we have no idea what this 14:43 error type is and we don't 14:44 have any type safety around the error handling. 14:48 If this changes at runtime, we essentially are going 14:52 to break, and that is not great. So the rest of this is basic. 14:55 We just have a delay that we are increasing by the 14:59 attempts number, sleeping a little bit of time before we 15:02 try again. 15:04 And so this does implement a chargeWithRetry. It does do that. 15:08 But again, it's flaky, it's not type safe, and this 15:12 pattern here is very common if you've worked with 15:16 legacy or even modern TypeScript codebases, error type Any. 15:21 And so we'll see how to improve upon this in the Effect 15:25 implementation. Let's keep moving on to the next function. 15:30 All right, next up, we're moving on to withTimeout. 15:35 This is gonna be just a very basic timeout implementation. 15:39 Now, this is gonna look very similar to the way 15:42 you would see it 15:43 inside of a normal TypeScript codebase. 15:45 Essentially, we have a race where we are 15:49 using Promise.race. As you can see here, we're taking in the 15:53 promise itself as a parameter and then the milliseconds, which is 15:57 the timeout value. Now, Promise.race allows you, as we can 16:01 see here, to create a promise that is resolved or rejected when 16:05 any of the provided promises resolve or reject. 16:08 And so here what we're gonna do is race the promise 16:13 against 16:14 another promise that we create directly inside. 16:17 And here we are using setTimeout and rejecting at the 16:21 very end of the provided millisecond value. 16:25 So at the end of this millisecond value, setTimeout will trigger, 16:29 we will reject the promise, and what that means is 16:33 if we got to this point and we rejected the promise, then the 16:37 promise here will reject because we rejected the second 16:41 parameter here in this array. But if the first promise we passed 16:44 in completes first, then the Promise.race, whichever 16:48 one completes first or rejects first, will be returned, and that's 16:52 exactly what happens here. Now, there's two problems with this 16:56 implementation. The first is that this timer that we set with 17:00 setTimeout never actually gets cleared. 17:03 So when the timeout wins, the charge 17:06 just will keep going. In other words, Promise.race 17:11 doesn't cancel anything. It just stops listening. 17:15 So a timed out payment, in this case when we use 17:19 withTimeout, can still succeed after we've told the 17:22 customer that it failed, and we'll see why in the next function. 17:27 But essentially what you wanna take away here is that Promise.race, 17:31 it's not canceling 17:33 either of these when they complete or reject. 17:37 They keep on running, and that is sometimes an undesirable 17:41 effect. In this case, the next function will see exactly why. 17:45 So this next function here, createOrder, is the actual 17:48 business logic. We have to take in the 17:52 HTTP request body and create the order inside 17:56 of our database. Now, this is the main workflow, and 18:00 there's a lot going on in here that we typically see inside of some 18:04 TypeScript codebases. The first of which is we receive this 18:08 request body and we wanna validate that it is, well, 18:11 valid for our system. We need to do some sort of validation. 18:15 So we can see typically this sort of pattern where we have if statements to 18:19 check All of the data on the incoming body, make 18:23 sure it matches the incoming type as we'd expect. 18:27 So here we have this runtime validation. 18:30 Now, a downside to this is that even after we do these checks, the 18:34 type for the body is still type any, which is not ideal. 18:38 We don't have type safety, and in general, this is just 18:42 kind of messy. This won't scale well. 18:44 When we have tons of other validations we have to make, this is gonna keep on 18:48 bloating and just be really hard to maintain. 18:51 So that's the first thing that's not great that Effect gives a solution 18:55 for. And of course, in case I didn't mention it, Effect 18:59 has in a solution for this with timeout race as well, which we'll see. 19:04 Essentially everything in here that we're doing now will be 19:07 replaced by a better variant using Effect. 19:10 And so after the validation, we are now looking up the 19:14 product inside of the database using our SQL 19:18 Postgres connection. So we're using that to execute 19:22 a select statement where ID is equal to the 19:25 body.productID. So we check to see if the product 19:29 already exists. If it doesn't, we throw an error, and then we 19:32 are doing a reserve stock with a conditional 19:36 update. So two buyers can't grab the last unit, 19:41 which is good. So here we're doing this atomic operation 19:44 where we 19:45 reserve the stock first before doing anything else with it, 19:49 and that's exactly what we do. We update the product stock and set it 19:53 equal to the existing stock minus the body.quantity, 19:56 so the new stock from the incoming request. 20:00 We subtract it where the ID is equal to the product ID from the 20:04 body and stock is greater than or equal to body.quantity, meaning 20:08 we still have a quantity we can work with. 20:10 And if this is equal to zero, then we don't proceed because we 20:13 are out of 20:14 stock already. So at this point, we've done our validation. 20:17 We know we have a valid product to actually order. 20:21 And then finally, that's what we do next in this try catch, 20:25 where we calculate the total by 20:28 multiplying the product price cents by the incoming 20:32 body.quantity. And then we execute Promise.all to execute 20:36 both of these promises. The first is gonna be with our 20:40 withTimeout function, which as we know, takes in a 20:43 promise or a timeout value, and that's exactly 20:47 what we do here. So we are using our 20:50 chargeWithRetry to essentially implement the charge 20:53 functionality with our retry, as well as wrapping it inside of a 20:57 timeout. So we retry our failed charges 21:01 up to this timeout value, three thousand milliseconds. 21:05 And then the second promise that we execute at the same time is this 21:09 fastestQuote function, which is coming from the shipping 21:12 file, which we'll take a look at in a second. 21:15 Both of these promises execute at the same time. 21:18 So at the end of this, we will have charged the user 21:22 appropriately or timed out, and we also are 21:26 executing this fastestQuote function. 21:28 Finally, we have the catch block where we catch any 21:32 errors that 21:32 occur. So depending on any errors that occur inside 21:36 of our try, we now want to do the compensating action 21:40 here. Because remember, before we executed this 21:44 charge statement and fastestQuote, we reserved the stock. 21:49 Now we have to undo that. If any errors occurred, 21:51 we wanna reset the stock 21:52 back to where it was so users can continue to order this 21:56 product because it failed the first time, and that's exactly what we do, 22:01 putting the stock back essentially. 22:03 Now, this fastestQuote function that we set up is essentially just 22:07 another Promise.race, a single promise file where we 22:11 call carriers.map. And the final thing we do here 22:14 is generate a new 22:15 random ID, and then we insert into 22:19 orders all of the details from this new order, 22:23 including from the incoming request body, the existing 22:26 price information itself, and details from the 22:30 charge and shipping operation that we did up above. 22:34 All of this is going into the new order that is inserted into the 22:38 database. So just to summarize, we do our validation, 22:42 reserve the stock on the product, issue the 22:45 charge, and 22:48 ask three carriers for a quote and takes the fastest. 22:51 And with the result of this, we now insert the new order into the 22:54 database. 22:55 So just taking a quick look at this fastestQuote, as I said before, this 22:59 is gonna ask three carriers for a quote and take the fastest with 23:03 Promise.race. And that's exactly what this quote 23:06 function is 23:07 doing. It is using the static carriers array 23:11 and this fake dummy delayMillisecond value to indicate how long 23:15 each carrier lookup takes. So that's what we do inside a quote. 23:19 We wait for that delayMillisecond value and then return 23:23 back the carrier. So this Promise.race will give us the 23:26 fastest 23:27 carrier. In this case, 23:29 we know that's always gonna be FedEx because it has the shortest delay. 23:33 So we get the fastest quote along with charging the user at the same 23:37 time. All this information is then returned back to us in terms of 23:41 the charge and shipping object, which are used inside of the 23:45 new order that's inserted into the database. 23:47 Last but not least, we have this toResponse function, 23:51 which takes in any error object and converts it 23:55 into an appropriate JSON response. 23:59 So here, errors essentially become HTTP statuses 24:03 by looking up the error.message inside of an 24:07 object. We are looking at the error.message, 24:10 and that 24:11 maps to the object key inside of this map, and 24:15 that will translate to the appropriate status code. 24:17 And that status code is what we send back on the JSON response 24:21 with 24:21 response.json. Now, when we make a typo 24:25 to our error types in the application, for example, if 24:29 we return back a response that is invalid body 24:32 something else that no longer exists in this map, well, 24:36 that means that our application will again stop f- working properly at 24:40 runtime. We don't get type safety around these 24:43 errors. 24:44 That's a clear gap that we have at the moment in our types of 24:47 critical 24:48 code, and hopefully that is clear. 24:50 And now the final logic in here is simply starting the 24:54 HTTP server using BUN.serve, where we pass through the 24:58 H- HTTP port and all the routes inside of the 25:01 app. 25:01 So we have one for /products, a GET route that returns 25:05 back the response.json with a simple select statement. 25:10 We have a post route for /orders, which calls our 25:13 createOrder function and returns back, which passes in the 25:17 request body using request.json. 25:20 And we know this is gonna return back our return object from createOrder, 25:25 which in this case is just a newly created order that's 25:27 inserted in the d- 25:28 database. And then finally, we have an HTTP GET 25:32 route that will extract a path parameter to pull off the incoming 25:37 order ID, and we extract that inside of this database query 25:41 to pull back the order from the database 25:44 and return that back as a JSON response. 25:47 And notice that each of these are wrapped inside of the try-catch, 25:50 where we are formatting and catching the incoming error. 25:54 Again, this type is totally unknown. 25:56 It's a runtime error that we pass into ToResponse and map to 26:00 httpStatus code. And so this is a gap that we are trying to 26:04 fill, but hopefully all this code in this short 26:06 main.ts should be 26:08 clear as to what we are doing. Essentially, a small orders 26:11 API where we can charge the user and insert a new order, as 26:15 well as updating the product quantity. 26:18 Now, with all of this in place, let's go ahead and run a 26:22 short example. We're gonna place one order and watch the 26:25 application logs. So to start our application server, 26:30 again, remember from the package.json, we can run the before command. 26:34 So run BUN before, and we can see that we're now listening on this 26:38 port, and we can send requests. So let's do this. 26:43 Now, the first thing we wanna do is run BUN DB:up. 26:48 This is gonna use Docker Compose to run and start up our Postgres 26:52 container that we defined so the database is running. 26:55 Make sure you have Docker Desktop installed and running. 26:58 If you don't, I'll leave a link to that below where you can get access to it. 27:02 And now with the database up and running, make sure we run BUN reset. 27:06 This is gonna invoke the demo script, which we'll walk through later, and 27:09 essentially just resets the database back to the starting state. 27:14 So in case you run this multiple times, you can reset the state at any 27:18 point with that command. 27:20 And then I'm gonna copy and paste this curl command, which I'll 27:24 leave in the lecture description so you can easily copy this. 27:28 Essentially, we're just launching a post request, 27:31 that /orders 27:32 API, and passing through a JSON object, 27:36 where now we are passing through product ID of keyboard, 27:40 quantity one, and card token with an example value. 27:44 Now, this all matches from the DB schema, 27:48 where remember we inserted this dummy product. 27:50 So if keyboard is a product ID that I can actually reference, 27:55 and the rest of this is coming from the request body 27:59 payload that we expect inside of the API. 28:02 And so now if I go off and send this, you can see here 28:05 we get the newly created order returned back to us. 28:09 So this is showing us the API is working as expected, 28:12 and we can even see some console logging here inside of that 28:16 Promise.race, where we looked up all of the carriers 28:20 for our shipping at the same time. 28:23 Now, there's a key thing we wanna understand 28:26 here, is that FedEx 28:27 won the race, right? However, we already sent the 28:31 response back to the caller through the API, 28:35 and these kept running. The promise kept running even after 28:39 FedEx was looked up and we returned the HTTP response. 28:43 The other promises inside a promise race, in this case for 28:47 UPS and DHL, kept on running anyways. 28:52 This is coming directly from our shipping.ts file, where if you 28:56 remember, we are running this set timeout 28:59 and using the carrier 29:00 delay. So this runs again for up to six hundred 29:03 milliseconds, but our 29:04 response came back much quicker than that. 29:06 And that's because Promise.race will return as soon as one of these 29:10 completes. But again, as this point as I'm trying to make clear 29:13 as 29:14 possible, the other promises that we've executed keep on running in the 29:18 background. They don't just stop. 29:20 And this is a problem that Effect will fix for us. 29:24 We get control over the asynchronous 29:27 execution of our application, because we don't want 29:31 these functions to keep on running in the background even after we exit. 29:35 We don't care about them. They could be potentially really 29:38 expensive, 29:39 or even worse, they could have side effects 29:41 and keep our application 29:43 in an inconsistent state. And that's the power of Effect that will 29:47 allow us to have more control over this asynchronous execution. 29:51 Because in production, these are gonna be three HTTP calls, 29:55 three HTTP sockets, which take up valuable resources in our 29:59 application, and three bills from the carrier's 30:02 API. We don't want that. That's wasted work and wasted money. 30:06 We need a better way, and that's what we're gonna get inside of 30:09 this 30:10 application with Effect. So again, hopefully this is clear as possible. 30:13 When the client hangs up and we return back from our API as 30:17 we just did, BUN.serve doesn't cancel our 30:21 underlying handler, and it isn't an error, so 30:25 nothing is thrown. The catch never runs. 30:28 The function just carries to-- on to completion with nobody listening. 30:32 Charge insert done. So three questions to keep in mind after 30:36 reviewing this demo. How would you know from a function's type 30:40 how it can fail? How do you cancel work you no longer 30:44 need? And how would you test this createOrder 30:47 function that we've 30:48 implemented without a real database? 30:50 These are all great questions to ask, and they're all questions that we will be 30:54 able to answer from using Effect. So let's go ahead and jump 30:58 in to see what is Effect, what can we learn from it, and 31:02 actually build the same API and application using Effect 31:06 concepts and take more control over our application. 31:10 All right, so next up, I've gone ahead and checked out back to the main 31:14 branch for the repository, which is gonna give us access to the 31:18 fully rewritten application with Effect inside of the 31:22 after folder. Now, don't worry, we are going to walk through each and 31:26 every file here and explain what is going on so we can learn 31:29 Effect's concepts and compare them to the existing 31:33 application. 31:36 So before we jump into this new application, 31:41 I wanna walk through a bit of vocabulary. 31:44 So remember before when we talked about Effect and its 31:48 type, 31:49 an Effect is a description of a program, not a 31:53 running one. Its type carries three things. 31:56 We'll see this in this application. 31:58 An Effect will have success, 32:01 error, and requirements. 32:05 So in other words, what it succeeds with, how it can fail, and what it 32:09 needs from the outside world before it can run. 32:12 When you see in our application, for example, we'll have an Effect 32:16 with an OrderSuccess and OutOfStock 32:20 type here. What this means is it's a program that 32:24 produces an order or fails with OutOfStock and 32:27 needs nothing. When the third slot is filled, for 32:31 example, we have a requirement, this will look 32:34 something like this, an Effect with a Product 32:39 never an SQL Client, for example. Here, this means 32:43 it's a program that produces a product, can't fail in any 32:47 way that I need to handle, and needs a database client to run. 32:51 Never in the error slot means can't fail. 32:54 Never in the requirement slot means needs nothing. 32:57 Now, compare this to Promise with an 33:01 Order 33:03 inside. What this means is, well, not much actually. 33:06 It's a promise and it tells you the first thing and nothing else, and 33:10 that's the gap that Effect essentially allows us to fill 33:14 with this type safety. Now, the next concept we need to look at is 33:18 generator functions and how we write Effect code. 33:25 So I wanna compare two snippets of code, 33:29 one in the format of standard TypeScript that we would see. 33:33 So here is a total function which looks what we'd expect, takes in 33:37 an ID parameter, uses async await to await a 33:41 find method call, and simply returns back a result. 33:44 So when we call this, we can simply await this function 33:48 using promises and async await. This looks as we remember and as 33:52 we'd expect. However, over here, we can see the same 33:56 code written inside of Effect. This is how we write Effect 34:00 code that reads top to bottom. Effect.gen 34:04 is the Effect version of an async function. 34:08 Inside of it, yield is the Effect version of await. 34:12 Run this Effect and give me its success value. 34:15 If it fails, the rest of the function doesn't run, 34:18 exactly 34:19 like an async await that throws, right? 34:21 If we throw an error here, we don't run the rest of the function, 34:25 and same 34:25 thing here inside of the generator. 34:27 So although this syntax may look a lot different than we're used to, 34:32 async generator functions are a normal part of 34:35 JavaScript and TypeScript, and Effect makes use of them to control 34:39 the 34:39 execution flow of asynchronous code as we'll see. 34:43 So this Effect.gen we're gonna see a lot of as it's how we write asynchronous 34:47 code, and then yield* is how we then wait for a 34:50 value. The function star 34:53 with a star is a generator. You don't need to know how generators 34:56 work. 34:57 Just read yield* as await. 34:59 Now, critically, error types add up automatically. 35:03 If you yield* one thing that can fail with A and 35:07 another thing that can fail with B, the whole generator block can fail 35:11 with A or B. You never have to write these TypeScript 35:14 union by 35:15 hand. The compiler collects it for us, which is an amazing 35:19 benefit. Now, another concept we wanna review is 35:23 .pipe. 35:25 Every Effect has a .pipe method, and it worked kinda 35:29 similar to RxJS pipe method. We give it 35:32 function and each one takes the Effect and returns a new modified 35:36 Effect, essentially using read it top to bottom. 35:40 In this case, take findById. By 35:43 piping this Effect.retry and 35:46 Effect.timeout, we are adding retry and timeout 35:50 functionality. Now, critically, nothing runs directly 35:54 here as we write this at runtime. We're just building a bigger 35:58 description out of a smaller one, essentially a recipe for how Effect is 36:02 gonna execute this code. Very g-- and again, very similar to 36:05 RxJS, we are combining these inner 36:09 Effects, in this case, retry and timeout, which come directly from 36:13 Effect out of the box. Now, the last concept I want to review is 36:16 Effect.function. You'll see this everywhere. 36:19 It's essentially Effect.gen that we saw earlier for functions that 36:23 take arguments. Effect.function 36:26 inventory.find gives you a normal function. 36:30 We can call it with an ID 36:32 and get back an Effect. The string is a name. 36:36 And Effect uses it to create a tracing span. 36:39 Every call gets timed and labeled automatically, which is what 36:43 you'd want in production for a service method anyway. 36:46 You can also leave this name out, but the fact that we get this 36:50 observability and tracing as a first-class citizen of 36:54 our application is so nice, and it makes 36:57 debugging and making our code faster so much easier 'cause we can see 37:01 when we eventually trace how much time these functions are taking 37:05 up. 37:07 All right, so now we've reviewed these core concepts 37:09 from Effect. 37:10 Let's take a look at how they've been applied to our new application to 37:14 understand the benefits of Effect. 37:16 All right, so the first thing we're gonna review 37:18 is this domain.ts file. 37:20 This is going to be the underlying data and the errors that 37:24 it can throw. 37:25 This file has no Effect logic in it at all. 37:30 It's the data that our API deals with described with 37:34 schema, which is Effect's validation library. 37:37 It plays the role Zod plays in a lot of code bases, but it also 37:41 knows how to encode, decode, and generate API 37:44 documentation all out of the box for us, which is all 37:48 functionality you commonly want when you have a schema library, 37:52 and we get this out of the box. Next up, we have 37:55 branded IDs. Each of these is two lines, and 37:59 you'll see this two-line pattern through all the file. 38:02 The first line is the schema itself, a runtime 38:06 value that can check data. The second line 38:10 pulls the TypeScript type out of the schema with type of 38:13 product ID.type. You write the shape once and get both. 38:18 Now, what's with brand here? 38:20 At runtime, a product ID is just a string, but at the 38:24 type level it's tagged. A product ID and an order 38:27 ID aren't interchangeable even though both are 38:31 strings underneath. We'll see this catch a real bug in a few 38:35 minutes. So to make one from a raw string, you just write product 38:39 ID. So essentially, this brand allows us to create a unique 38:43 type for a given underlying value like a 38:47 product ID or order ID, and now these are two distinct TypeScript 38:50 types. And again, notice we're using this .pipe 38:54 functionality to provide Effect with more 38:57 information. Now, of course, schema comes with all of the different 39:01 types you'd expect under it. So for example, 39:04 we have all of the different types 39:05 it offers to get as specific as we need. 39:08 So if we need a number, a string, or any other type, we have that available. 39:12 And so next up for this cents value, we have a reusable rule, 39:16 in this case an integer, and it has to be more than zero. 39:21 So we use an integer type and pipe through this 39:25 schema.check. It essentially adds a runtime check to 39:29 a schema. That's how we can get runtime 39:30 functionality. 39:31 And this is gonna mirror our SQL table rule that 39:35 says a price cents has to be greater than zero. 39:38 So we have this runtime validation as well as compile time with 39:42 a static schema, and this is how we can apply this runtime using 39:46 schema.check and then using schema.is Greater than. 39:49 And of course, this comes with cus- tons of custom validators 39:54 out of the box, and we can build our own if we need to. 39:57 So this is very nice because we are building the shape of the data 40:01 through schemas but then also enforcing the business logic 40:04 rules directly in one spot so that when we supply 40:08 these values to our API later on, it's automatically gonna 40:12 enforce this schema for us without us having to do anything. 40:15 We always know that the data we have working in our 40:19 APIs does match the schema we defined because we have this 40:23 schema validation out of the box. 40:26 So then we finally declare the product and 40:30 order types. And so notice these are actual classes 40:34 that are now extending schema.class 40:38 where we t- provide the TypeScript type 40:41 that we just created. 40:42 Schema.class gives us a real class and a schema in one. 40:46 We can instantiate new instances of it using new, and the fields are 40:50 validated when we do, which is incredible. 40:52 It allows us to essentially have really nice object-oriented code if 40:56 we want. And this is super valuable because it 40:59 means that for now when we 41:00 instantiate a product or an order, 41:02 the values are automatically validated. We... 41:05 Which is a huge deal for catching runtime bugs. 41:07 Now of course, inside we have the fields 41:09 that make up the class, 41:11 and here these fields are simply reusing what we've already 41:15 defined. So the ID references the product ID type. 41:19 Name and stock are created on the fly 41:23 as generic types. And cents points to cents, which again 41:27 builds from the 41:29 schema and has this runtime check. 41:31 And I just can't stress how cool this is, the fact that we now have this 41:35 validation whenever we, for example, create a new product. 41:39 If we don't supply these properly, of course that's gonna throw an error. 41:43 And we get the runtime validation now. 41:49 When we instantiate this, since it's less than zero, this 41:53 is going to be 41:53 a problem. 41:56 And down here we have the same idea for an order. 41:59 Now, one field here is worth taking another look at. 42:02 All these other fields are just coming f- straight from the schema. 42:05 Here we have Schema.DateTimeFromUTCFromString. 42:09 Now, schemas have two sides. There's the encoded side which 42:13 travels over the wire. Here, an ISO date string in 42:17 JSON. And then there's the decoded side, what your code 42:21 actually works with. That's gonna be a proper DateTime value. 42:25 So the schema actually converts in both directions. 42:28 When a request comes in, strings get decoded into dates 42:32 automatically. When a response goes out, dates get encoded 42:36 into strings. We never have to call a new date or to ISO 42:40 string by hand Which is really convenient. 42:43 And that's what we're indicating here with this 42:46 DateTimeUTCFromString. So again, this is just another example of 42:49 functionality that Effect is taking care for us without us having to 42:52 manually 42:53 implement it. Next up, we have CreateOrder. 42:58 This essentially is the request body for our post orders 43:02 route. Now notice here, this is actually called a 43:05 struct, not a class, because it's just a plain 43:10 object coming in. We never expect to actually directly 43:13 instantiate this CreateOrder type with new. 43:17 So that's a difference in how we can declare those two different types, 43:21 where as better known as a plain old JavaScript object, a 43:25 POJO, this is how we'd reference that, versus a 43:29 real class that contains data and potentially functionality as we've 43:32 provided up above. The difference is we will instantiate instances of these 43:37 versus a struct, not really so. 43:40 And here we're providing properties just the same as in the class with the 43:43 types directly or creating new types on the fly. 43:47 For example, here, a new integer for quantity, 43:50 where we have a runtime 43:51 check to make sure it's be- in between a minimum and 43:55 maximum. We also have a non-empty string defined 43:58 for card 43:58 token. And so compare this approach with this 44:02 declarative 44:02 schema-driven back to what we were doing before 44:06 inside of our main.ts in CreateOrder. 44:08 And remember, when we got the request body, 44:11 we're doing this ugly 44:13 manual validation over every property by checking 44:16 its type manually with three if statements. 44:20 And even after this, the type of the body that we've just 44:24 checked is still any, not great. This approach here with Effect 44:28 replaces all three. We know that quantity 44:32 must be an integer between one and ten, card token can't be empty, 44:36 and once a request has passed through this schema, its type is 44:39 CreateOrder, fully typed, with product ID 44:43 already branded as a product ID, which is incredible. 44:47 So let's go ahead and actually prove this out. 44:50 I wanna show you this in action. So to do this, I simply go ahead 44:54 and run bun 44:56 after, which is gonna start up that new after server, invoking 45:00 our new main.ts, which uses this domain.ts schema. 45:04 Of course, we'll walk through all this other code 45:05 later on, but just to show you 45:07 this in action, I'm going to copy the same curl 45:11 request from before or very similar to launch it at 45:15 our API at this post endpoint /orders. 45:19 And notice here we are passing in a quantity of 45:23 zero in the body, which as we would expect, should be 45:27 violating this schema check because we've defined this to be 45:30 between one and ten. So now if we send the request to the server, 45:35 we get back a four hundred bad request error, which is incredible. 45:38 It means our validation was caught. 45:41 And even better, if we go back to the application server, 45:45 we can actually see the request that hit the API. 45:49 We have an info log telling us, which is really nice, how long it 45:53 actually took, giving us the HTTP span of five 45:56 milliseconds, 45:57 and then we see the underlying error that caused the client to get the four 46:01 hundred 46:01 here, an API schema error with the 46:05 schema rule that was violated, in this case, our 46:09 quantity 46:10 validation, even telling us details about the request. 46:13 So this is super nice out of the box. 46:15 You don't even need any sort of logger or 46:19 filter. We just get this great developer 46:21 experience telling us what 46:23 the problem was, 46:25 and this validation is working just as we'd expect coming from 46:29 the 46:29 source of truth, which is the schema itself. So nice to see. 46:34 All right, so the last thing we're gonna look at in 46:36 this file is these 46:38 errors that we have now defined. And essentially, 46:40 it might be the most important 46:42 idea in it. In the before code, errors were 46:46 throw new error out of stock, for example, inside of our main.ts. 46:50 We're throwing these generic errors, which is a 46:54 string inside of a generic error. And the only way to tell them 46:57 apart was comparing these strings. 47:01 It's brittle, not type-safe, and just smells 47:05 ugly in all. However, in Effect, errors are 47:09 values with their own classes. That's exactly what we're 47:12 defining here. So in this case, this product not found error, 47:16 which is extending Schema.TaggedError, 47:21 takes in three arguments. The first is the tag. 47:25 In this case, a string, product not found. 47:28 Every one of these errors gets an underscored tag field with that string, 47:32 and it's how the code tells errors apart. 47:35 The compiler knows every possible tag. 47:38 So if we misspell one in comparison, it's a type error and 47:42 not a silent runtime bug. Second, the fields. 47:46 A product not found carries which product wasn't found, 47:49 and it's a typed product ID, not a string buried in a message. 47:54 So we can directly build the 47:57 error details with type safety. Third is annotations, and 48:01 here it's an HTTP API status of four hundred and four. 48:05 The error carries its own HTTP status. 48:08 Remember, toResponse in the before code 48:11 was a big object 48:12 mapping message string to status codes. 48:15 Well, that doesn't exist in this version. 48:17 The error here is the mapping. And because this is a 48:21 schema tagged error, it can be serialized to 48:25 JSON. That's how it'll travel to the client as a 48:28 response 48:29 body, and how a typed client can decode it back 48:32 into a real 48:32 product not found on the other side. Very nice. 48:37 Now, the rest of these errors follows the same 48:39 pattern, and each of these is 48:41 gonna define its own tag. Its own details of what it 48:45 includes in the error and its own HTTP status. 48:49 Essentially, it's a whole vocabulary of things 48:51 that can go wrong, up in one place, 48:53 and every one of them will show up in a type signature somewhere. 48:56 This is something we've never really gotten with standard TypeScript, and 49:00 in my opinion, there's been a real gap up until now, 49:03 and Effect handles 49:04 this really nicely. So now we've looked at the domain 49:08 schemas, the data itself, the validation, and our error types, 49:12 which is amazing. Let's go ahead and move on to our first 49:16 service. 49:17 I want to now take a look at our first service, and that's gonna 49:21 be the payment gateway. Now, the services in the 49:25 before code, every function reached for globals. 49:28 If you remember, the SQL client, the charge function imported from 49:32 payments TS. And that's what made it really hard to 49:36 test. In Effect, each dependency is a service, 49:40 an interface plus a way to build it. 49:43 Now, this is a fake payment provider, so it's the smallest real one, but it's 49:47 gonna show us exactly how this works. 49:49 So everything we need here is imported from Effect plus two payment 49:53 errors from the domain file. Let's take a look at the 49:57 service definition. 49:59 This shape is going to repeat for every service, 50:04 so let's take it apart once carefully. 50:06 Context, we have the payment gateway that's 50:09 extending 50:09 context.service. This is gonna take two 50:13 type arguments. 50:16 The first is the class itself. The second is the 50:20 interface, the methods that this service will 50:23 implement. And finally, the string at the end, 50:28 here effectdemo/PaymentGateway. 50:31 This is the service's unique key. At runtime, Effect 50:34 keeps a map of keyed implementation, and this is gonna be the key, 50:38 similar to an injection token inside of NestJS. 50:42 So one class here is giving us two things. 50:45 It's a type, the interface as we are describing it, and 50:49 at runtime Effect... and it's a tag you can 50:53 look the implementation up with. No decorators, no reflect 50:57 metadata, no container configuration. 51:00 Everything we need in this one definition. 51:02 Now, taking a look at this interface itself, 51:05 charge is going to 51:06 return an Effect that succeeds with the 51:10 charge ID or fails with payment declined or 51:14 payment unavailable. That's the contract. 51:18 Any code that calls charge will see these two errors in its 51:22 own type, and it has to either handle them 51:24 or pass them 51:25 on explicitly, which is gonna be critical. 51:28 Remember, this is the same Effect shape we saw in 51:31 the intro, 51:32 and we are returning the error types that the clients must now handle 51:36 appropriately, keeping everything fully safe at 51:40 runtime and at compile time. We also have refund 51:43 takes in the charge ID and returns back in essentially an empty 51:47 Effect, which is going to be as close to nothing 51:50 as possible. 51:51 Now, inside of this class, the first thing that we 51:55 are doing is declaring this static read-only layer 52:00 using layer.Effect. Now, the way we can think about this 52:04 is that an interface, in this case up above, the interface 52:07 that we defined, 52:08 it's already telling us what a payment gateway is. 52:12 Now, the layer here is saying how to 52:16 actually build one. So this is the implementation itself. 52:20 By convention, it's a static property on the service 52:23 class 52:23 called layer. So layer.Effect that we're 52:27 calling here means to build a payment gateway, run this Effect, 52:31 and whatever returns is the implementation. 52:34 The Effect.gen that we provide as the implementation, 52:38 and here we reference Payment Gateway to specify what we're providing 52:41 for, this Effect.gen runs once when the app starts up, 52:46 not once per request. It's reused. 52:49 It's essentially the constructor. 52:51 It's where we're gonna read config, open up a connection pool, warm a cache, 52:55 anything we need to do to get this dependency ready to use at runtime. 52:59 And so we're calling Effect.gen, which remember, allows us to 53:03 create an async function and await things inside 53:07 using that yield syntax. And so that's exactly what we do at the 53:11 start. We are getting the configuration 53:15 from the environment. 53:18 So in this case, we're pulling off failure rate 53:20 and latency as 53:22 environment variables from the .env at the root, which remember, 53:25 we've set here as some dummy values, 53:29 and this is gonna allow us to introduce some randomness and key failures 53:33 to our app. 53:34 And so now to read these in, in the payment gateway, we use 53:38 config directly from Effect to read in environment variables, 53:43 and this also allows us to do validation on them, which is really nice 53:47 as well. Config.number here is reading the environment 53:51 variable, parsing it as a number, and even providing a default 53:55 of zero point five. We do the same thing with the latency, 53:58 except making 53:59 sure that it is an integer. And so this is really nice because 54:03 if an environment variable is set to something that isn't a number, 54:06 the startup 54:07 will fail with a clear config error naming the variable, whereas in the 54:10 before code, we would not find out until runtime 54:14 with a crash, and that's the difference here. 54:18 Now importantly, also notice we are using this yield star 54:22 syntax to yield the config. Config here is 54:26 just another Effect, and where it reads from environment 54:29 variables 54:30 by default is swappable. So tests are gonna be able to supply their own 54:34 config without touching process.env, which is very nice. 54:37 So now we have the configuration we need. 54:40 Let's move on to the actual implementation of the 54:44 payment gateway so we can implement charge and 54:48 refund. 54:49 All right, so next up we have the actual charge 54:52 effect 54:53 itself. And here notice we're using 54:55 Effect.function 54:56 instead of Effect.gen, which lets us take in 55:00 parameters to the effect. 55:03 So here we're specifying amountCents and cardToken as input 55:07 parameters, and again, we're giving this a string name here, 55:11 which is going to make sure that every charge automatically gets a 55:14 tracing 55:15 span. 55:16 Now, in this next call where we call 55:18 Effect.annotateCurrentSpan, 55:21 that attaches the amount that we're passing in here 55:26 to that span. So in a tracing tool, we can see how much this charge 55:30 actually was for. Essentially, we can correlate any data we want inside 55:34 of this effect now to the trace that we set up at the beginning, which 55:38 is very convenient. Next up, instead of awaiting a 55:42 new promise with setTimeout, the analogous format here is to 55:46 yield Effect.sleep, which provides this out of the box, 55:50 and we are sleeping for this latency milliseconds, which is configured via the 55:54 environment variable. And here, this is gonna represent our fake 55:58 network latency. Now again, the key benefit to this 56:01 sleep through an effect versus the promise approach is that 56:05 this sleep is actually interruptible. 56:08 If this request gets canceled while we're sleeping, 56:12 the sleep just stops and the rest of this function never 56:16 runs. In the real world, that's an HTTP call to 56:20 Stripe getting aborted, and that's gonna matter a lot in the hang 56:23 up demo. 56:24 But even beyond Stripe, if we had some expensive calculations 56:27 going on here, 56:29 resources being obtained, those are all still gonna be taken up 56:33 versus here when we interrupt this sleep with Effect, we 56:36 are essentially interrupting the flow of execution now. 56:40 And this is a big deal because we essentially have the way 56:44 to cancel a request and any subsequent work, whereas in 56:47 normal TypeScript, this is not possible. 56:50 Next up here, 56:53 we are doing a check on the cardToken. 56:56 If it's passed in as tokDeclined, this is gonna represent the declined 57:00 token flow, essentially a test card that always gets declined. 57:04 And look at how we are now failing here. 57:06 Instead of throwing a new error, we return 57:09 yield new PaymentDeclined. And this is a key 57:13 concept in Effect, errors can be yielded directly. 57:17 Yielding one fails the effect with this error, a bit like 57:21 throw. The difference is that the compiler now sees this. 57:25 PaymentDeclined is now part of the function's error type, which remember 57:29 we specified up above, and the compiler will check it against the 57:32 interface we declared. So if I yielded some error that's not in the 57:36 interface, that would not compile. 57:39 Instead, we now have this type safety. 57:43 Next up we have this 57:46 chaos section where we're implementing a random 57:50 chaos. Here, Random.next is Effect's 57:54 random number. It's a value between zero and one. 57:59 Now, you might be thinking, "Why not use Math.random?" We could, but 58:03 a big benefit of Effect.random and all of the different 58:06 functionality from Effect is that random here 58:10 is itself an Effect service, and that means a test 58:14 can swap in a seeded one and get the same random failures 58:18 every run, which is really cool and useful opposed to just 58:22 using Math.random. 58:24 We also are using Effect's built-in logger here, logWarning, 58:28 and automatically attaches context to every line, 58:33 like how far into the request we are, request details, and we're gonna 58:37 see this in the server logs in a minute. So this is very useful. 58:41 We have this out of the box without any external dependencies. 58:45 And then the last thing we do here is if we did 58:48 trigger a random failure via our chaos check, where we are 58:52 checking the failure rate that we passed in from the environment, 58:55 well, just 58:56 like we did for PaymentDeclined, we are now failing with 58:59 PaymentUnavailable 59:03 and yielding in the same format. 59:07 Finally, if we did succeed, then we are returning 59:11 a fake charge ID. 59:14 And then finally, we have the refund implemented as well, 59:17 which is 59:18 another Effect function that takes in the charge ID, implements a 59:21 similar sleep, and logs out. 59:29 Now notice at the very end here, we're returning 59:31 PaymentGateway.of with the charge and refund. 59:35 This is the implementation that we specified in the interface up 59:39 above. .of is a small helper 59:43 that checks this object matches the service's interface. 59:47 If charge, for example, returned the wrong shape 59:50 or could fail with 59:50 an error the interface doesn't list, this is where we would get 59:54 a compile time warning, which is incredible. 59:57 Now, the last thing I want to show you is back on line 14. 1:00:01 If we now hover over this layer, just look at the type inference 1:00:05 that's happening here. We can actually see the three type 1:00:08 parameters the layer has, which looks a lot like an Effect. 1:00:13 It provides the PaymentGateway, building it can fail 1:00:17 with a ConfigError because of our environment variables that 1:00:21 we're reading, 1:00:22 and it requires nothing, so it has the never type here. 1:00:26 Now, this is the power of Effect. We never 1:00:29 specified this Config.ConfigError. 1:00:32 Effect is automatically picking this up because it knows of the 1:00:36 other effects that we call inside, in this case Config, and it knows the 1:00:40 failure types of Config because Config itself is 1:00:44 just yet another Effect. And so the compiler figures all of 1:00:48 this out, and in the end, we just get this one 1:00:52 Type that tells us all the ways that this can fail, 1:00:55 keeping our application 1:00:56 type safe both at runtime and build time, which is so cool. 1:01:00 So now we've seen the payment gateway, how to set 1:01:03 up an external dependency, a service, in other words, 1:01:07 we call it an effect, 1:01:09 and provide both its interface and implementation 1:01:13 by creating 1:01:15 a new layer. 1:01:18 Now we're gonna see how this is then plugged into the application 1:01:21 and used later 1:01:22 on. But for now, let's go ahead and head over to the 1:01:26 next service, shipping TS, which is gonna be a 1:01:29 service that actually has no setup. 1:01:34 All right, so now inside of shipping TS, this is the 1:01:38 same job as the before version, where we are gonna ask three 1:01:42 carriers for a quote and take whichever answers first. 1:01:46 But now we're gonna see how we do this more effectively inside of Effect. 1:01:51 Now here we have a plain TypeScript interface for the 1:01:55 quote and a carriers array. Now you might be wondering, 1:01:59 why do we have a plain TypeScript interface here and not a 1:02:03 schema like we saw before inside of Effect? 1:02:06 And the reason why is because this interface here never 1:02:10 crosses the HTTP boundary on its own. 1:02:13 It doesn't need to be a schema. Plain TypeScript is fine, and that's an 1:02:17 important distinction to make. The Effect schemas really 1:02:20 are only valuable 1:02:21 if we are crossing across the boundary. 1:02:24 We want that validation, deserialization, and serialization, 1:02:29 as well as automatic documentation and so on. 1:02:31 We still have internal types declared 1:02:34 as we would in TypeScript. 1:02:37 We also have our three fake carriers here with a response 1:02:40 time, which we know FedEx will always succeed in 1:02:43 because it is the 1:02:44 quickest with the lowest delay. And then we have the shipping 1:02:48 service defined. Now this is the same service shape we saw with 1:02:51 payments, but now look at the interface. 1:02:56 Fastest quote here is no longer a function. 1:03:00 It's actually a property holding an Effect. 1:03:04 Since it takes no arguments, it doesn't need to be a function. 1:03:08 An Effect is a description of the work, not the work itself. 1:03:12 So one value can be run once per request a 1:03:16 thousand times, and each run is fresh. 1:03:22 With promises, you couldn't do that. 1:03:24 A promise stored in a property would run once and cache the 1:03:28 result forever. Not so with an Effect. 1:03:31 And so we're seeing both of these approaches, right? 1:03:33 In Payment Gateway, we had functions that took parameters, and here 1:03:37 we simply just have the property itself, which is set to the Effect that 1:03:41 we can run once per request a thousand times, and each run 1:03:45 is fresh. And so we can see the type of the Effect 1:03:48 is 1:03:49 the quote which we defined up above. 1:03:52 So that's what we're gonna be returning back from it. 1:03:55 And it has no error type, so we don't need to include that 1:03:59 because getting a quote can't fail. 1:04:01 And so now we can see, just as we saw before in the other Effect, 1:04:05 we are 1:04:05 declaring the read-only layer, and now we're calling 1:04:09 layer.succeed instead of Effect. 1:04:13 Now, this is for when there's nothing to set up, 1:04:15 no asynchronous code to run, 1:04:16 right? There's no config, no connections, nothing really for anything to 1:04:20 fail. We just hand over the implementation 1:04:23 object directly, 1:04:24 and that is key. So succeed allows us to do this. 1:04:28 So just as we did before, we're now providing this shipping 1:04:32 dependency. And for this, we're not using a function 1:04:36 anymore because remember, the interface is just the property itself. 1:04:40 We are using this shipping dot of syntax. 1:04:44 And so let's take a look at this and read it from the inside out. 1:04:48 For each carrier that we have, we are calling 1:04:51 Effect.sleep on that carrier's delay, 1:04:55 which stands in for an HTTP call. Then we have 1:04:59 Effect.as, which says when that 1:05:03 finishes, succeed with this value instead. 1:05:06 So each one is wait hundred and fifty milliseconds, 1:05:09 then produce the FedEx 1:05:10 quote, essentially because we know FedEx will 1:05:12 succeed first. 1:05:14 We also pass an Effect.onInterrupt. 1:05:17 That's a hook that only runs if this Effect gets canceled 1:05:21 before it finishes. Effect's word for cancellation 1:05:24 is interruption, and you'll hear me say 1:05:26 that a lot from here on. 1:05:28 I added this hook purely so we can see cancellation happen in the logs. 1:05:33 Finally, we wrap this all inside of 1:05:35 Effect.raceAll. It starts all 1:05:39 three at the same time because we are iterating over each 1:05:43 carrier, so all three of these are going to execute at once, 1:05:46 similar to how 1:05:47 Promise.race would work. But however, the main difference though 1:05:51 with Promise.race is, yes, it is starting all three of 1:05:54 these at the same time, all this asynchronous work at once. 1:05:58 However, the moment that one of these succeeds and we 1:06:02 execute the Effect.as and we issue back this response, the 1:06:05 moment that we do that, it interrupts the rest of the 1:06:09 executions, not just stop listening to them like 1:06:13 Promise.race. It actually stops them, and that is 1:06:17 the key that we need to understand. 1:06:19 Just as we saw before inside of Payment Gateway, Effect allows us to 1:06:23 interrupt the flow of execution here because we said as soon as the 1:06:27 first one of these succeeds, in this case raceAll, we want to 1:06:31 stop. And this is critical again because as soon 1:06:34 as we got the 1:06:35 FedEx response, that means we don't have to reach out to 1:06:38 DHL or UPS if we already haven't done that, and we can 1:06:42 clean up these resources quicker and overall just stop 1:06:46 doing wasted work when we don't need to, right? 1:06:48 Because once the first one succeeds, we can move on. 1:06:51 Now the last thing we see here is calling Effect.withSpan 1:06:55 This is added on using .pipe to the .of 1:06:59 call, which remember allows us to add on 1:07:02 additional functionality 1:07:03 when this is actually invoked. And h- here, what we are doing with 1:07:07 withSpan is essentially naming the span on a plain effect. 1:07:11 Essentially, this is the same thing that we did for the functional approach. 1:07:15 Remember, we pass in toEffect.function. 1:07:18 Well, there's nowhere to do that here, so we need to set the span at the end like 1:07:22 this. And so this will record 1:07:24 shipping.fastestQuote and the 1:07:26 execution inside with our observability. 1:07:29 And so when we run this, we are actually going to see the two other 1:07:33 carriers that got interrupted, thanks to the onInterrupt 1:07:37 effect that's passed in here. As soon as FedEx finishes, the other two 1:07:41 will be canceled, and we will see this onInterrupt get 1:07:44 called, and this is commonly 1:07:45 a place where we could do any resource cleanup. 1:07:48 It's an amazing benefit of Effect, allows us to clean things up effectively. 1:07:53 Finally, if we hover over this layer, we can see the re- return type is 1:07:57 a, a layer that has the shipping dependency, 1:08:00 no 1:08:01 failures, and no dependencies. So great. 1:08:03 We now have shipping service complete. 1:08:05 Let's move on to inventory.ts, the inventory service. 1:08:09 This is gonna be a bit more complex because here we actually have 1:08:13 two different implementations instead of just one, and we're 1:08:17 gonna see what this looks like next. 1:08:21 So our inventory service here should look sort of 1:08:24 similar to the other services we've already gone over. 1:08:28 It's going to manage inventory, the products, and their stock. 1:08:32 And here, as we can see in this comment at the top, 1:08:35 this tells us something 1:08:36 interesting about this file. There's actually gonna be two different 1:08:39 implementations of the same interface that we define for this 1:08:43 service. One is going to use a direct Postgres 1:08:46 connection for this 1:08:47 data, and the other is a plain in-memory map, 1:08:50 which can be used for 1:08:51 testing. And a key benefit is that we can swap out these 1:08:55 runtime dependencies and use them for testing much more easily, 1:08:58 and that's 1:08:59 what we'll see in this service. The other thing I wanna point out is 1:09:02 that we're now 1:09:03 importing this SQL client and SQL schema from 1:09:06 effect/sql. In effect, for SQL ships 1:09:10 inside the Effect package as a subpath. 1:09:13 This gives us a database agnostic SQL client. 1:09:17 Notice there's nothing Postgres specific in this file at all. 1:09:21 The actual Postgres driver gets chosen in the main.ts later on, 1:09:25 and this is incredible. It means we don't have to code to a 1:09:29 specific driver implementation. 1:09:30 We can swap that out at any point in time without having to change the 1:09:34 code, which is so nice. It makes swapping our database 1:09:38 of choice so much easier in the future and encap- encapsulates 1:09:42 us from this implementation detail. 1:09:46 So the first thing we'll review here is the 1:09:51 definition of our inventory class. 1:09:53 Now again, this looks very similar to the payment 1:09:56 gateway. 1:09:56 We're extending the contact service, passing in the class type 1:10:00 itself, and then we define the interface for the 1:10:03 methods that we're gonna 1:10:04 implement on the actual implementation choice. 1:10:07 This is gonna be for operations. 1:10:12 And we can see the return types for each of these is listing, 1:10:16 again, what we are returning, any errors, and 1:10:19 dependencies. So for example, find, which takes in the product 1:10:23 ID, can return back a product or a ProductNotFound 1:10:27 Error. Much more descriptive. 1:10:31 Now note what's not in these error types that we define, like OutOfStock. 1:10:35 We don't have any database errors directly, and we'll see why in 1:10:39 a moment. 1:10:40 So the next thing we do is create our layer once again using 1:10:43 Layer.effect, 1:10:45 and then we pass in for the inventory implementation, a new 1:10:48 Effect.genFunction. 1:10:51 Now in here, the first thing that we do is get access 1:10:55 to the SQL client. Now, this is a very 1:10:58 important pattern here. What we're doing is we're getting access 1:11:02 to the 1:11:02 SQL client using this yield* and accessing it from the 1:11:06 SQL client global import here directly. 1:11:09 This is how you ask for a dependency. 1:11:12 In the before code, there was a global at the top of the file. 1:11:15 Here, we're not using a global. I was mistaken the first time. 1:11:19 We are using the SQL client .SQL client. 1:11:23 This is the layer saying, "To build me, someone has to give 1:11:27 me a SQL client." 1:11:29 Yield* 1:11:31 on a service gets you its implementation, whichever one got 1:11:34 plugged in at runtime. So essentially, this is how we're 1:11:38 injecting a dependency into this 1:11:42 implementation. We're not using globals anymore. 1:11:45 Instead, we're simply pointing at this generic 1:11:49 SQL client service interface, and Effect will take care 1:11:53 of, of providing the correct implementation 1:11:56 based off of what we 1:11:57 wire up later on. And this is a similar pattern on how to 1:12:01 ask for a dependency inside of Effect. 1:12:04 So next up, we have the actual database queries. 1:12:08 And so to build this, we use the SQL schema import. 1:12:11 And on it, like any driver or SDK, we'll have our 1:12:15 methods to interact with the database. 1:12:17 Here we have a findAll. Now, the way this works is that we give it a 1:12:21 schema for the input, a schema for each row, 1:12:25 and the SQL to run. The really cool thing about what this does 1:12:29 is it actually validates what goes in, decodes every 1:12:33 row from the database that comes out through the 1:12:37 product schema. So this is automatically gonna turn it 1:12:40 into a JavaScript class and apply the same 1:12:44 validations. Now, why is that important? Well, think about it. 1:12:47 If someone puts a negative price in the database for some reason, which 1:12:51 does not match our runtime validation we specified on the product schema, 1:12:56 that's gonna get a loud decode error, not a broken object 1:13:00 wandering through our app at runtime, and this is such a 1:13:03 powerful pattern. I can't stress it enough. 1:13:06 This runtime safety at all levels, including the database level 1:13:09 here, where because we're providing it with this 1:13:12 result, which is what we expect 1:13:14 the schema of the response to be from the database, we always know what we're 1:13:17 pulling back does match the exact shape. 1:13:21 And this prevents so many hard to track runtime bugs, of course, where 1:13:25 information or objects in the application or runtime get mutated in some 1:13:29 way. And here we are validating that just like on the HTTP 1:13:32 API, we do it on the database as well, always ensuring our data 1:13:36 is in the correct shape. So we have the requests, which 1:13:39 is what we pass in 1:13:40 as well. In this case, we don't need to pass anything in, 1:13:45 so we use the schema void type, and then execute is the raw 1:13:48 SQL that we execute against the database. 1:13:52 Now importantly, this SQL template tag is 1:13:55 completely type safe. In find by ID, for example, 1:13:59 we are passing in the product ID as a request, getting back the 1:14:03 product again and, and execute now it ex- expects 1:14:07 the parameter here to be the ID of type string because 1:14:11 we pointed it at our product ID schema type. 1:14:15 And now inside of select star, we can provide it in the select 1:14:19 statement. ID here becomes a bound parameter, 1:14:22 not string 1:14:23 concatenation, no SQL injection, which is nice. 1:14:26 We get this safety out of the box too. 1:14:31 And so finally, as we have both of these queries ready to 1:14:34 use, 1:14:36 so find all here is gonna return us back an array as we'd expect. 1:14:41 Find one option returns an option. 1:14:45 Effect's way of saying maybe a value. 1:14:47 So that's a key concept as well. This return type is 1:14:51 going to either be a product or a special none 1:14:55 type, and this is gonna enforce us to handle 1:14:58 both 1:14:59 scenarios in our code. It's essentially a null we can't forget 1:15:03 to check, and again, keeping our app safe because we know this 1:15:07 query may fail to select something, and if that happens, we want to tell 1:15:10 our app that it could be empty. So we're forced to do validation on 1:15:14 it. 1:15:16 And again, this also helps us to avoid more runtime 1:15:18 issues, which is really 1:15:20 nice. Next up, we're moving on to this list 1:15:23 const that we see here, 1:15:26 and this is how we're actually now using the queries we set up 1:15:30 above. Now let's walk through this. 1:15:33 This comment that we specify here is introducing one of the 1:15:37 most important ideas inside of Effect. 1:15:40 So we'll take this slow. Effect splits failures into two 1:15:44 kinds. The first are errors, which are the expected ones. 1:15:48 They're in the type that we define, for example, out of 1:15:51 stock or card declined, right? These are the types we're 1:15:55 using inside of the interface. So we have these 1:15:59 well-defined errors. 1:16:01 Callers are expected to handle them, and they get listed. 1:16:05 However, we also have defects, which are the unexpected ones. 1:16:09 These are bugs, crashes, the database falling over. 1:16:12 They're not in the type because there's nothing reasonable a caller 1:16:16 can do about them. However, they still get caught and logged, 1:16:20 and the request still returns a five hundred. 1:16:23 They just don't clutter every signature in the app. 1:16:26 And so Effect or die, this statement we see here, 1:16:30 turns errors into defects. The query can fail with 1:16:34 a SQL error, and we're saying if the database is 1:16:37 broken, that's a defect, not a business case. 1:16:41 That's why list's type is Effect read-only array 1:16:45 product, no errors. Without this, SQL error would 1:16:49 leak into every function in the app all the way up to the HTTP 1:16:52 handlers, and that's not what we wanna do. 1:16:54 We want to catch this earlier and react to it, and that's 1:16:58 exactly what we are doing. Now, this is a judgment call, not a rule. 1:17:02 If you wanted to retry on connection errors, you'd keep it as a typed 1:17:06 error and deal with it later on. Effects let you make that 1:17:10 decision based on your application's needs, which are really nice. 1:17:15 So again, just to show you this in action, right? 1:17:17 If we hover over list, you can see the return type for this 1:17:20 Effect, right? 1:17:21 It's a product array, and we have never for the failure 1:17:25 types that can happen. If we comment out or die, let's see what 1:17:29 happens. Now you can see the SQL error is 1:17:33 now part of the definition of the type, and we're essentially 1:17:37 now forcing all of the callers of this to handle this 1:17:40 appropriately. But that's not what we want to do because 1:17:44 there's nothing really useful that callers can do with this. 1:17:47 You can't recover from the database is gone at the checkout level, so the 1:17:51 inventory service here is drawing a line. 1:17:53 Domain errors like product not found or out of stock stay in the 1:17:57 error channel because callers can handle these. 1:18:01 Infrastructure errors like SQL error become defects. 1:18:04 They bubble up and crash the fiber, which is just like the execution 1:18:08 context in Effect and resolve to an uncaught exception. 1:18:12 Another way of thinking about this 1:18:14 is that it's Effect equivalent of saying, "If the database is broken, just 1:18:18 throw. That's not my caller's problem to solve." 1:18:21 Essentially failing 1:18:22 fast, and that's what or die allows us to do. 1:18:24 We don't wanna pollute the error type chain with a bunch of errors that we don't 1:18:28 care about handling up above. We just want them to propagate to the 1:18:32 caller. In this case, the HTTP handler. 1:18:36 So important concept to understand there as well, and like I said, there's a 1:18:40 bit of judgment here, right? You don't have to necessarily agree with 1:18:43 this line of 1:18:43 thinking, but it's nice to know that you have the tool in your 1:18:46 toolbox to use it. So we're also piping a span on 1:18:50 this, calling it inventory.list. 1:18:55 So we have better observability around the execution of the 1:18:58 database query. So we have list find by ID. 1:19:02 Next up, we're gonna implement find, which is an Effect function. 1:19:06 Where we are essentially running the query and database errors are then 1:19:10 now becoming defects. So let's take a look at this in 1:19:13 detail. We are creating the new Effect function, 1:19:16 giving it its observability 1:19:17 tracing span name, and we're taking in a generator function 1:19:21 with 1:19:21 the product ID as a parameter. And the first thing we're doing is 1:19:25 using our findById query Effect we have above, yielding on 1:19:29 it and piping through, again, an Effect.orDie. 1:19:33 Just like we did for list all, we want these database errors to become 1:19:37 defects, so that's what we do here. 1:19:39 And then we see this Option.match. 1:19:43 Now, remember, in, an Option in Effect is the idea of 1:19:47 a value representing maybe there's a value and maybe there isn't, or 1:19:51 T or null in TypeScript. And so Option.match 1:19:55 here is taking in the product 1:19:59 Effect itself, and then we pass in this second parameter 1:20:02 that's 1:20:03 handling both of these cases. It allows you to run 1:20:07 some different code depending on the Option result, right? 1:20:10 If it did resolve to some value, we can execute a different Effect. 1:20:14 If it doesn't, we can do something different, 1:20:16 and that's what Option.match allows 1:20:17 us to do, handling both of these cases. 1:20:20 In this case, no rows means we want to fail with the 1:20:23 product 1:20:24 not found error, and that's exactly what we do. 1:20:27 We call Effect.fail, pass through the product not found 1:20:31 typed error with our extra product ID context, 1:20:35 versus onSome is the parameter we pass for success, 1:20:39 and here we just pass through Effect.succeeded, the explicit 1:20:43 way to create a successful one. And what this does is it means the 1:20:46 missing row scenario here becomes a typed 1:20:50 domain-level error with a four oh four attached, no matter how 1:20:54 we call it, which is very nice. Next up, we have reserve 1:20:57 functionality, which really is not doing anything different from what 1:21:00 we've already 1:21:01 seen, just another Effect function where 1:21:05 we're doing a conditional update. 1:21:07 Only subtract if there's enough stock in one atomic statement, so two 1:21:11 buyers can't both grab the last unit. 1:21:14 If no rows come back, there wasn't enough, so we fail with the out of 1:21:18 stock error using the same syntax we've seen so far. 1:21:22 Then we move on to release. This puts the stock back and 1:21:26 logs it. This log here is what we'll be looking at inside of our 1:21:29 demo, 1:21:30 "Released 3X keyboard" in our hang-up scenario. 1:21:34 Finally, we call inventory.of and provide the interface with all of the 1:21:38 implementations here. 1:21:40 So now we have the Postgres implementation fully reviewed. 1:21:44 Let's look at this layer memory down below. 1:21:47 And again, this is a separate implementation 1:21:48 that adheres to the same interface, 1:21:50 and we're just calling it layer memory. We can call it whatever we want. 1:21:54 We're gonna reference this when we actually wire together this 1:21:57 dependency at runtime and choose which implementation we wanna use. 1:22:02 By default, that will be this Postgres layer. 1:22:04 But when we do tests, we can now plug in this memory 1:22:08 layer. And what this means is we'll have a way to test all the 1:22:12 functionality 1:22:12 inside of this service without using a real database, which is very 1:22:16 nice. So this second implementation is the same interface, but we're 1:22:20 using an in-memory map. This syntax here, 1:22:23 layer.sync, is when we want to build a service 1:22:27 that is fully synchronous. No config, no awaiting. 1:22:32 Just run this function with no generator or yield functionality. 1:22:36 And that's exactly what we do, all in... 1:22:38 essentially implementing all of these methods once again with an in-memory 1:22:42 map now. 1:22:44 So now we have this in-memory implementation as well. 1:22:47 We have the inventory service and our SQL 1:22:51 client connection all reviewed. Now we can see the amazing 1:22:55 benefits of using Effect for our database work 1:22:59 because of this type safety and runtime validation of all the data 1:23:03 that's read in, which is very nice to have, as well as 1:23:07 type-safe CRUD functionality, both in the success and 1:23:11 error cases. So very nice inventory service fully 1:23:15 reviewed. 1:23:16 Let's now move on to the final orders service, 1:23:20 which is going to be the same patterns we've already seen s- 1:23:24 before, where we have a Postgres and memory layer. 1:23:27 So we'll go over this a bit quicker as these are the same patterns. 1:23:31 So here in line six, we have the new order type, and when 1:23:35 we pass in to create an order, we have everything except 1:23:39 the created_at timestamp, because that's what the database 1:23:42 is going to 1:23:43 set. So we want to make sure we have a type 1:23:46 that represents a new 1:23:47 incoming order, which is the same order we've already declared 1:23:50 on the schema 1:23:51 without the created_at timestamp value. 1:23:53 Next up, we have something that is a bit different from our previous 1:23:57 implementation, and it's a real problem that I hit 1:23:59 when building this demo. 1:24:01 Remember, created_at on order decodes from an ISO 1:24:05 string, because that's what JSON has. 1:24:08 But the Postgres driver hands back a timestamp Z column 1:24:12 as a JavaScript date, not a string. 1:24:15 Same field, different format at each boundary. 1:24:18 So instead of writing a second near-identical schema for database rows, 1:24:23 mapFields derives one from order. 1:24:26 Take every field as is, except for 1:24:30 created_at. Decodes from a date. If someone adds 1:24:34 a field to order later, the row schema picks it up automatically. 1:24:38 ToOrder turns a decoded row into a proper order 1:24:42 instance. Next up, we have the interface for the orders 1:24:45 class, 1:24:46 where we define the create and find method for orders. 1:24:50 Importantly, find here is failing with order not 1:24:54 found in some cases, whereas create will not fail. 1:24:58 Again, any database failure is gonna be thrown as a defect. 1:25:02 And then we have the layer implementation set up as the static read-only 1:25:06 layer. For this orders interface with our 1:25:09 generator function, 1:25:10 with our effect gen function, and just like we did previously, we 1:25:14 are using this injected SQL client, and we're using the 1:25:18 SQL schema find one and find one option 1:25:22 to implement our insert and find by ID. 1:25:27 Now let's dive a bit deeper into both of these calls. 1:25:30 So let's start with the insert. The request schema is 1:25:34 derived again. 1:25:36 Here we have the order schema that we've already defined, 1:25:41 essentially without the created at field as we've done before. 1:25:44 So for this, we use the map fields function where we 1:25:47 are not 1:25:48 setting created at, but spreading everything else that already 1:25:52 exists to give us the schema that the request to this 1:25:56 database operation will then expect. 1:25:58 And that's reflected here as well in the execute parameter type, right? 1:26:02 This is everything the order schema already declares minus 1:26:06 created at. Now, notice in the execute operation, we 1:26:10 have this SQL.insert. This is a helper that 1:26:13 expands an object into the column list and values for you, 1:26:18 which is incredibly useful. 1:26:21 Essentially, it's translating this JavaScript object 1:26:25 into 1:26:25 the raw SQL needed to actually create this record in the database, which 1:26:29 is very convenient. We're also returning back everything 1:26:33 from the row, including the created at timestamp the 1:26:35 database filled in, 1:26:37 and it's decoded through the order row result. 1:26:41 We pass through the 1:26:43 result schema, which as we know up above, 1:26:47 is taking in the record and now setting created at to this 1:26:51 date time UTC from date schema value. 1:26:55 And this matches the shape coming back from the database. 1:26:58 Now, find one here. We're using find one because we are 1:27:02 saying exactly one row comes back from this insert operation. 1:27:07 So we have the insert query. Create and find 1:27:11 are the same patterns as inventory. 1:27:14 We have the expected schema we've set up here. 1:27:18 And notice we're using the or die 1:27:22 pattern where any database errors are thrown early 1:27:27 instead of passing that up to callers on their type chain. 1:27:31 And for find, we're also using option.match to 1:27:34 specify the option path. So for on none, if we 1:27:38 find no matching orders, we throw that order not found and fail 1:27:42 the effect. Otherwise, we succeed and pass through. 1:27:46 And this is to make sure as we can hover over find, we have the correct 1:27:50 effect 1:27:51 type where we return an order. Order not found error can be thrown and 1:27:55 it takes no dependencies. So again, just building up this context for the 1:27:59 effect compiler to do all this work for us. 1:28:02 And then finally, we return back orders.of with the 1:28:05 implementations. 1:28:06 Now, just like we did for the previous service, 1:28:10 we also 1:28:10 have a memory implementation that we're gonna use for 1:28:14 testing. And so that just implements create 1:28:16 and find, again 1:28:17 using this in memory map. Now, we've covered every single service 1:28:21 that checkout itself depends on. Now it's time to go to the 1:28:25 workflow itself inside of the checkout service. 1:28:29 Let's go ahead and dig in. 1:28:32 So in this file, we're essentially replacing what 1:28:35 create order was doing inside of the before code. 1:28:39 And everything we've read so far is essentially building up to 1:28:42 this. So let's start from the beginning with our 1:28:45 imports at the 1:28:46 top. There's two small things I wanna point 1:28:48 out. 1:28:49 The first is this schedule import 1:28:52 coming from effect. This is new, and that's how we'll describe 1:28:56 retries. And most of the domain of imports have 1:29:00 type in front, 1:29:01 as you'll also see as well. We only need them as types here. 1:29:06 So let's move on down below to a contract that we 1:29:10 have defined. Essentially, this new type and our 1:29:14 checkout service class definition. 1:29:17 This should look familiar as we've seen before. 1:29:20 Checkout is a service too with one method. Read the signature. 1:29:23 We have place order. It takes in a validated 1:29:27 create order and returns an order, or 1:29:31 fails with one of the exactly five error types from above, 1:29:35 and that's what we're defining in this checkout error type, all of the different 1:29:39 kinds of errors, the domain errors that can come from this 1:29:42 service. Now, remember, this was one of the first questions from the 1:29:46 before section. How would we know how a function can fail? 1:29:51 Well, now it's answered in the type before we've 1:29:53 read a line of the implementation. 1:29:55 Here's all of the different domain errors that the clients and consumers of this 1:29:58 service have to now handle, which is very nice. 1:30:02 And we know under the hood where these errors are coming from. 1:30:05 For example, well, remember, this comes from our 1:30:08 inventory service. Here, we are throwing 1:30:12 the product not found error. 1:30:15 And same thing goes for the rest of these errors. 1:30:17 These are coming from other services that are re-throwing to us. 1:30:20 And so let's prove the compiler is actually watching. 1:30:24 If I go ahead and delete payment declined, for 1:30:27 example, from this list, you'll now see if we scroll 1:30:31 down, we get a type error around our final 1:30:35 return 1:30:35 statement where we're trying to provide an implementation of 1:30:39 place order. If we hover over it, 1:30:42 we will see that type payment declined is not 1:30:46 assignable to type checkout error. 1:30:48 The implementation can still fail with a declined card. 1:30:52 Just because we commented out the type here, the code doesn't change. 1:30:55 This is still a possibility coming from the payment gateway, and this is 1:30:59 because the payment gateway says it can from the types that it returns, and 1:31:03 I just claimed that it couldn't. The compiler won't let me lie about it. 1:31:07 Errors flow up through yield automatically, and the signature has to 1:31:11 account for every one. This is runtime type safety 1:31:15 of errors inside of effect. 1:31:18 And so we have the definition of the checkout service complete here. 1:31:22 We're returning an order or this checkout error. 1:31:24 Inside of the implementation, we 1:31:28 create a first layer here, layer no deps, 1:31:32 or dependencies. It's called layer no deps for a reason 1:31:36 we'll see at the 1:31:36 bottom of this file. And here it asks for all four 1:31:40 services with yield. Remember, we saw this pattern earlier when we wanted 1:31:44 to inject the SQL client. Well, look how we're doing it in the same 1:31:48 way to inject the other services our app has, has 1:31:52 created. We're just following the same syntax. 1:31:54 We just use yield star and provide the name of the service, 1:31:58 and that's all we have to do. Now, importantly, 1:32:02 this is not choosing implementation. 1:32:04 It's just choosing the class itself. 1:32:07 So we're yielding inventory, and this just means 1:32:11 that we will ensure that this interface is implemented on this type, 1:32:15 but we don't know the actual implementation details. 1:32:17 That is still abstracted away from us and provided at runtime. 1:32:21 And again, this is a major benefit because we can 1:32:24 swap out the implementation at 1:32:25 any time and keep our code 1:32:28 flexible 1:32:30 because we're gonna be programming to an abstraction what the interface 1:32:33 says these services do and not an implementation, which is very 1:32:37 clean code. So now we have the services themself. 1:32:41 This is the same concept around the SQL client. 1:32:44 It doesn't know or care whether the inventory is Postgres or a 1:32:48 map. So let's move on now. 1:32:51 If we hover over layer no deps, we'll see 1:32:58 that it's automatically picked up all four of these dependencies 1:33:01 automatically inside of the effect. 1:33:05 Checkout needs all of these services to actually run, and the compiler 1:33:09 worked this all out just from writing the yield statements, which is really 1:33:12 incredible. So now we have the dependencies. 1:33:15 Let's move on to the retry policy. So this 1:33:19 is how we're implementing our retries inside of effect. 1:33:23 Here we have a new const called charge with retry. 1:33:28 Now, this is just a simple function that we are creating. 1:33:32 Remember, previously, we implemented this using a while 1:33:36 true loop from the before code. Now, instead of a while 1:33:40 loop, we are describing it as a value. 1:33:44 Essentially, take payments.charge, 1:33:48 the method that we know that this service will implement, and 1:33:52 pipe on additional functionality to it, just as we've done before 1:33:56 to these effects where we can add additional functionality with pipe. 1:34:00 Now, we still pass through the parameters 1:34:02 that it expects, and this is fully type 1:34:04 safe. And now inside of pipe, we can implement 1:34:07 effect.retry, which is how we can implement retries inside 1:34:11 of effect. Now, effect.retry takes a schedule, which is 1:34:15 a description of when to try again. 1:34:19 The dollar sign here is a small helper. 1:34:21 It plugs in the error type from charge, so the rest of the schedule knows 1:34:25 exactly what errors it'll be looking at. 1:34:28 Now, let's read the rest of it like a sentence. 1:34:30 We schedule.exponential a hundred milliseconds, which 1:34:34 means wait a hundred milliseconds, then two hundred, then four hundred, 1:34:39 doubling each time. So we have an exponential back off with 1:34:42 this one line 1:34:43 of code. We also add schedule.jittered, which is a 1:34:47 nice technique to add some randomness to each wait. 1:34:50 So if we have a thousand clients that fail at the same moment, we 1:34:54 don't all retry at the same moment and knock the provider over again. 1:34:58 We also tell it to schedule up to times three, 1:35:02 which just means at most three retries, which means at most 1:35:06 four calls total. Finally, we have this 1:35:09 schedule.while where we pass in this callback with 1:35:13 the input. As we can see, that's either payment declined or payment 1:35:17 unavailable, and we check to see if this 1:35:20 input._tag is equal to payment unavailable. 1:35:24 Now, what does this mean? Well, this is saying only keep going 1:35:28 while the error is the transient one. 1:35:31 A declined card will stop immediately. 1:35:34 That's the string compare from line twenty-three of the before code. 1:35:38 But input here is typed as a payment declined 1:35:42 or a payment unavailable. That is the big benefit we 1:35:46 get. We actually know the type of this error 1:35:49 that can be thrown. 1:35:50 So when we do this comparison of checking the error string, this 1:35:54 is now type safe. If I misspell this tag name, 1:35:59 it's going to be a compilation error, right? 1:36:02 If I'm trying to check for an error that doesn't exist, we will know about it, 1:36:05 and 1:36:05 that is the type safety we get, which is incredible. 1:36:08 Finally, we have schedule.tap, which allows us to run some arbitrary 1:36:12 code on each retry. Here, we're just using the effect 1:36:16 logger to log out a warning message and let the user know that we 1:36:20 are retrying with the current attempt number, which we can pull off 1:36:24 of the schedule.tap input. And so each piece is 1:36:28 one line. It's totally reusable. You could pull this schedule 1:36:32 out into a constant and share it across every service 1:36:35 that calls a 1:36:36 flaky API, and you'd have the same functionality in 1:36:40 all of your calls, which is an amazing benefit here. 1:36:43 It's this composition of description of runtime 1:36:47 logic, in this case, like a retry loop, that is so 1:36:51 nice. Finally, you can see we have one more bit of code. 1:36:55 This is effect.timeout or else. 1:36:59 Now, essentially, this is the timeout that's wrapped around the 1:37:03 whole 1:37:03 thing with retries included. So here we're saying three seconds 1:37:07 total for everything in here to be running. 1:37:10 And we specify that with the duration. 1:37:13 Remember, the before code with timeout was a race against a 1:37:16 timer, and the charge keeps running after you've 1:37:20 given up on 1:37:20 it. Timeout or else works just like the or 1:37:24 die from earlier, where we will actually 1:37:28 stop early. We will interrupt the in-flight attempt. 1:37:32 In this case, remember, that's gonna be Effect.sleep 1:37:37 in the gateway, which is our fake HTTP call. 1:37:40 That will actually be interrupted. 1:37:42 In a real provider SDK, the HTTP request itself 1:37:46 will get aborted. And on timeout, we fail with our own 1:37:50 custom error, payment timeout, which already knows it's a 1:37:53 504. That's where our last error type comes 1:37:57 into play 1:37:57 here, and this is great. We now have such a better way to 1:38:01 describe the timeout functionality and a way to actually 1:38:04 abort it so that... Imagine if this call here we're making 1:38:08 and this retry loop is really expensive, it's taking up 1:38:12 resources. 1:38:13 Well, now we can actually stop it once we know 1:38:16 that we are finished. 1:38:18 So now we have the charge with retry described. 1:38:22 We know how to actually do this work with our retries. 1:38:26 Let's move on to the actual place order 1:38:30 implementation. This is the real meat of the application, the 1:38:34 workflow itself. Now, I want you to put this next to the 1:38:38 before code, and it's the same steps in the same order. 1:38:42 We are finding the product, as you can see, in Effect.function. 1:38:46 We're passing in the span name, the input, which is going to 1:38:50 be create order. And here, the first thing that we do is 1:38:55 yield this asynchronous bit of code where we reach out to 1:38:58 inventory.find, pass through the input.productID, 1:39:03 and get the product back. 1:39:05 So we have the product, and now we are calculating the total cents by 1:39:09 multiplying the price cents times input times quantity, and 1:39:13 then we reach out to the inventory service and call reserved and 1:39:16 pass in these details. So now at this point, we've found the 1:39:20 product, work out the total, reserve the stock. 1:39:24 And of course, we know this can throw out of stock error 1:39:26 if it... 1:39:27 Which maps up to our out of stock checkout error type. 1:39:31 And so now we've reserved the stock. 1:39:33 So everything after this point of time that we've reserved the 1:39:37 stock, this might need undoing. And importantly, 1:39:41 that's why the next bit of code is wrapped in its own 1:39:45 inner Effect.gen. We'll see what's attached to it 1:39:49 in a second. So inside of this second 1:39:52 Effect.gen, we are charging the card and getting a shipping 1:39:56 quote at the same exact time. That is what we are doing 1:40:00 with Effect.all. It's the Promise.all equivalent. 1:40:04 By default, it runs things one after another. 1:40:08 However, we can configure it with this concurrency 1:40:10 option of 1:40:11 unbounded. This means we're gonna run them all at 1:40:14 once. 1:40:15 Or you could set concurrency to a string, a number value 1:40:19 like five, and that gets us a bounded pool for free. 1:40:23 However, the big difference here from Promise.all 1:40:25 is if either 1:40:27 one of these fails, we don't just keep on running the other 1:40:31 promises. The other asynchronous code is 1:40:34 interrupted. With Promise.all, if the charge fails, the 1:40:38 shipping quote keeps running in the background with nobody waiting for it. 1:40:42 Here, it actually gets canceled, and that is the big 1:40:47 benefit that we need to understand. 1:40:49 So we are calling our charge with retry, which remember is 1:40:53 just charge on the payment service with this retry 1:40:56 functionality built in and the timeout. 1:40:59 So that's gonna be one bit of asynchronous work, and then the fastest quote 1:41:03 effect from the shipping service. 1:41:05 So both of these are executed the same time. 1:41:07 If either of them fails, then we stop the execution. 1:41:11 And think about what this means, right? 1:41:12 If this fastest quote API is expensive, but for some reason 1:41:16 the charge fails first, we don't need to keep on doing this 1:41:20 expensive work, and that's the power we gain with Effect 1:41:23 in this 1:41:23 scenario. 1:41:26 And so finally, we'll move on to after doing this work, 1:41:30 you can see we are returning orders.create. 1:41:34 And here we are saving the order. We're calling create on the order 1:41:38 service to persist this into the database. 1:41:41 However, look at the extra functionality 1:41:43 that we're adding onto with pipe since 1:41:45 this is just another effect. Here you can see we're using our first 1:41:49 onError where we do some logic if an error occurs. 1:41:53 Well, in this case, think about it. 1:41:55 If we know an error occurs in the order creation, we wanna be able to roll 1:41:59 back the work we've done previously. 1:42:02 In other words, if saving the order fails, well, we wanna refund the 1:42:05 user's card. And so Effect.onerror means 1:42:08 if this effect ends without 1:42:09 succeeding, run this cleanup code, and then keep failing with the 1:42:13 original error. It doesn't do any swallowing of the error. 1:42:17 And so remember, refund is just another method on the 1:42:21 payment service, so that will take care of refunding the 1:42:24 user if an error occurs. And so we get this out of the box, 1:42:28 which is 1:42:28 nice. Now, the next bit of code we have here is 1:42:32 another pipe, the second onError, and this might just 1:42:36 be the most important bit of code in this whole video, so 1:42:40 give it some time to actually sink in. 1:42:43 This second onError is wrapped around the whole inner block. 1:42:48 Everything after the reservation, if anything in there 1:42:52 fails, we are wanting to release the stock. 1:42:55 And we can see this. If we trace this back up to where it's 1:42:58 called, 1:42:59 this is the inner generator function that we created, 1:43:01 and that's why we created it, 1:43:02 so that we can add this error handling at the end. 1:43:07 And as we can see in this comment, this is the whole reason this 1:43:11 video exists. A try catch runs when something is 1:43:15 thrown. On error runs on every way an effect 1:43:18 can end without succeeding. There are three. 1:43:22 The first is a typed error, a declined card, a 1:43:25 timeout. A catch handles these two. 1:43:29 A defect, something unexpected like the database 1:43:32 dying mid 1:43:33 insert. Remember, those on dies turn database errors into 1:43:37 defects. They're not in the types, but on error, we'll 1:43:40 still see them. And finally, interruption. 1:43:44 If the work was canceled, for example, the client hung up and the server 1:43:48 canceled the request. A catch only ever sees the first 1:43:52 one. In the before code, a hangup isn't thrown at your code at 1:43:56 all, so the catch never runs. In effect, all 1:44:00 three of these different error types go through this same 1:44:04 exit, so the same cleanup runs. There are two layers of 1:44:08 rollback, each exactly where they belong. 1:44:10 The inner one refunds the charge if saving fails. 1:44:14 The outer one releases stock if anything after the reservation 1:44:18 fails. And this is the power of effect. 1:44:21 We can attach the error handling right alongside where it 1:44:25 belongs best, and we get this error handling over these 1:44:28 different types of errors, not just the typed errors, 1:44:31 which keeps our application 1:44:32 even more resilient and our business in line, 1:44:36 because we won't have angry users of our system that have 1:44:40 inventory out of line because the order to sell failed and we never 1:44:43 released it. So this is excellent, and I hope this is very clear. 1:44:48 The last thing that we do inside of this class 1:44:52 is wiring up the defaults. Now here, 1:44:54 checkout.of is the same as every other service. 1:44:58 Now critically, this layer with no depths cons 1:45:01 that we created 1:45:02 at the top, this layer is checkout with all 1:45:06 four dependencies still open. Layer takes 1:45:10 that and plugs in two of them, the real payment 1:45:14 gateway and the real shipping. So we're providing these 1:45:17 two layers that we need. 1:45:20 Layer.provide means build these first and feed them 1:45:24 into this layer. Why only two? Because payments and 1:45:28 shipping are the same everywhere this app runs. 1:45:31 But inventory and orders needs Postgres in production and a map 1:45:35 in tests. So we wanna let the caller decide those. 1:45:39 So if we hover over layer, we can see we have all the types now 1:45:43 tracked from this. Payment gateway and shipping are now gone from the 1:45:47 requirements, so only inventory and orders are left. 1:45:51 And we can also see config error is popping up in the error type 1:45:55 because the payment gateway reads config when built. 1:45:57 So this is really cool seeing how we can compose our layers 1:46:01 in this way, where in this service, we know we always 1:46:05 want the payment gateway and the shipping layers, and we 1:46:09 can tell other providers, the ones that will be higher up, to 1:46:13 finish the implementation wiring to give us the 1:46:16 database and order service that we will need. 1:46:20 Next up, let's go ahead and see all of this in action. 1:46:24 All right, so I wanna show you a quick demo of the 1:46:27 checkout service in 1:46:28 action w- now that we've wired everything together. 1:46:31 Now, of course, this is gonna be using the HTTP side yet, 1:46:35 which we haven't read or gone over, but we'll tackle this later 1:46:39 on. I wanna show you this workflow that will actually do things, and we'll 1:46:43 come back to see how it's actually wired. 1:46:45 Now, before starting the server, remember, we've added our .env, and 1:46:49 in here, we actually have these two environment 1:46:52 variables, the payment 1:46:53 failure rate and the payment latency milliseconds. 1:46:57 So if you recall, if we look for the payment failure rate, 1:47:00 for example, 1:47:02 and look inside of our gateway, remember, the failure rate and the 1:47:05 latency milliseconds are both used 1:47:09 inside of our payment gateway service. 1:47:12 So remember, the latency here is just an artificial sleep to 1:47:16 represent an HTTP call that will take time. 1:47:19 And then the failure rate is essentially some chaos 1:47:22 that we're introducing 1:47:23 to show what happens when the payment fails. 1:47:27 And as we know, since we've hooked into effects on error 1:47:31 mechanism, we should see 1:47:34 our error handling in action, and that's exactly what we're gonna 1:47:37 demonstrate. 1:47:38 So what we wanna do is make sure we have one terminal running, 1:47:42 and make sure you run bun after at the root 1:47:46 of the monorepo. Here, this is gonna start up the 1:47:50 after bun server. 1:47:52 And then what we're gonna do is make sure you open up a 1:47:56 different terminal window and go into the same 1:48:00 project where you already are running the server in. 1:48:03 And then we can simply run the command bun demo 1:48:07 after declined. Now, this is gonna invoke the demo 1:48:11 script that we have introduced to actually walk through our server with some 1:48:14 examples. And so if we go ahead and execute this, you'll 1:48:18 see that we get back the HTTP status code of a 1:48:22 four O two. That's the HTTP API status that we 1:48:26 configured from our domain TS file. 1:48:29 Remember, inside of here, we have our four 1:48:33 O two status code associated with the payment declined error. 1:48:36 So this was automatically handled for us. 1:48:39 What's also nice, if we look over to the server logs, 1:48:43 look what actually got logged out here. 1:48:45 We can see the HTTP span, how long it took, 1:48:47 but look at this important message, 1:48:49 "Released one X keyboard." This is our stock 1:48:53 being released by the outer on error that we 1:48:56 configured and no retry payment warning. 1:49:00 Instead, 1:49:02 schedule.while saw payment decline and stopped immediately. 1:49:06 So these are both amazing findings coming from effects implementation that we 1:49:10 didn't get with the before server. 1:49:13 So remember, from our checkout workflow, we have our on error, where 1:49:17 we know if any errors occur from the payment gateway. 1:49:22 Which we wrapped inside of the generator function. 1:49:26 Then we have our effect on error where we release the inventories. 1:49:29 That is happening, and this is amazing because the payment failed, 1:49:33 we are doing 1:49:33 this cleanup work appropriately. 1:49:36 And importantly, we didn't retry payment because we know 1:49:39 that we don't 1:49:39 wanna retry payment for a payment declined error. 1:49:42 That doesn't make any sense. 1:49:45 And this comes directly from our charge with retry function. 1:49:47 Remember in here, we did implement retry functionality using 1:49:51 our 1:49:52 pipe effect syntax, but also we told it using 1:49:55 schedule.while, we don't wanna enter this loop if we have 1:50:00 the error tag as payment unavailable as we do now. 1:50:03 So both of this is working as expected. Very nice. 1:50:06 The next demo we're going to do, we're going to make sure we 1:50:10 keep the server running. And notice we also have this nice HTTP 1:50:14 logging too, so we can even see on the server side the 1:50:16 request failed. 1:50:18 So that's nice too. And so now what we're gonna do 1:50:20 is run bun reset, which 1:50:22 puts the application back at the original state. 1:50:25 I wanna run bun demo after burst. And so this 1:50:29 is gonna run ten orders against a flaky shipping provider. 1:50:33 And let's see what happens here. So we got back this response, 1:50:37 and we can see in the application logs now. 1:50:41 Ten concurrent orders against a provider that fails half 1:50:45 the time. If we scroll up here, we can see the retries in 1:50:49 action. So these warnings that we see 1:50:53 are from our log warning in the gateway in schedule.tap in the 1:50:56 checkout. Notice we see this number, this 1:51:00 hashtag number. That's actually a fiber ID. 1:51:04 That is... A fiber is Effect's lightweight thread. 1:51:08 Every request runs in its own one, and each one gets an 1:51:12 ID. So you can follow one's request retries 1:51:15 through interleave logs, 1:51:16 which is really useful. Now notice we also see, we saw earlier 1:51:20 up above, we see DHL and UPS quote canceled here. 1:51:24 And here's our race all from shipping. 1:51:26 FedEx won, so UPS and DHL get interrupted, and their 1:51:30 on to interrupt hooks ran. Compare with the before server where all 1:51:34 three carriers finish on every single request. 1:51:37 This is structured concurrency. No piece of work outlives the thing that 1:51:41 asked for it. 1:51:43 So hopefully it's a bit more clear now on the benefits of using 1:51:47 Effect as we've walked through this demo. 1:51:51 The last things I wanna touch on are the final pieces of our 1:51:55 Effect API. So more specifically, the API itself, 1:51:59 how we've actually wired up our endpoints. 1:52:02 So let's take a quick look here on the HTTP side. 1:52:05 Now, Effect splits it into two files on 1:52:07 purpose: the contract, what 1:52:09 the API looks like, and the handlers, what it does. 1:52:13 This is the contract, and it's pure data, no server code, 1:52:17 no handlers, and no database. We can notice up top 1:52:21 we're importing from Effect/HTTP API, another 1:52:25 subpath of the main package in Effect four. 1:52:28 Now, an API is made up of groups, 1:52:32 and groups are made up of endpoints. 1:52:36 The products group has one endpoint, 1:52:40 get/products named list, 1:52:43 which succeeds with an array of products. 1:52:46 The name list is how we'll refer to it in the handlers and in the type 1:52:50 client. 1:52:51 The orders group has two endpoints, post/orders named create. 1:52:56 The payload is our create order schema. 1:52:58 That's how the four hundred we saw earlier happened. 1:53:00 The request body gets decoded through this schema before any of 1:53:04 our code runs. Success is an order with the status 1:53:08 set to two zero one created. An error lists every error 1:53:12 this endpoint can return. Each one already carries its status code 1:53:16 from domain TS, so there's no mapping to write, 1:53:19 and it's the 1:53:20 same five as checkout error. 1:53:23 Get/orders/ID named get. Prams 1:53:27 says the ID in the path is an order ID. 1:53:30 So it arrives already branded from our schema. 1:53:33 Succeeds with an order or fails with order not found, 1:53:36 a four zero four. 1:53:38 And the whole API is two groups together with a title for 1:53:42 docs. 1:53:45 Because this file is only data, the same definition drives three things 1:53:49 for us automatically: the server, a fully typed client, 1:53:53 and the OpenAPI docs. Really cool. 1:53:56 Let's see the docs in action. 1:53:59 So make sure your development server is still running. 1:54:02 And you can go to localhost three four six zero, where your server should be 1:54:06 running, /docs. And you get this really nice 1:54:10 looking documentation out of the box. 1:54:13 We can click here to expand our post/orders 1:54:17 and actually see the underlying responses returned from 1:54:21 this API, each with its body schema. 1:54:24 I didn't write a single doc annotation, and these can't drift from the code 1:54:28 because 1:54:28 they are the code. Really, really cool. 1:54:31 It comes with this AI agent and even a test request directly in the 1:54:34 browser. 1:54:35 So this is so cool to see. It makes it so useful for 1:54:39 clients. Now, the next file I wanna look at is our 1:54:43 http.ts. 1:54:46 And here we have the actual handlers for our 1:54:49 HTTP routes. 1:54:51 These are thin adapters from the contract to the services. 1:54:55 And so here, HTTP API builder.group with 1:54:59 API and products passed in says, "Here's the 1:55:02 implementation of the products group of this API." 1:55:06 This function gets a handler's builder. 1:55:10 It asks for inventory with yield the same as any other service, 1:55:14 and then handlers.handle list with the 1:55:18 actual implementation. When get/products comes in, it will 1:55:22 run inventory.list. And as you'd expect, everything is fully type 1:55:25 safe, checked against the contract. 1:55:28 If we misspell list here, for example 1:55:32 Autocomplete won't offer it, and it won't compile. 1:55:35 Return something that isn't an array of products and, 1:55:38 you guessed it, it 1:55:39 will not compile. We also see next up the orders 1:55:43 group. Handle all takes every endpoint at 1:55:47 once. 1:55:50 And it's a compile error if you forget one. 1:55:52 It's just convenient instead of having to list them all. 1:55:55 Create gets payload already validated and typed as create 1:55:58 order and hands it straight to place order. 1:56:01 Get also gets params.id, a branded order 1:56:05 ID, 1:56:06 and hands it to orders.find. And here's the check 1:56:09 that ties it together. 1:56:11 Place order can fail with the checkout error, and the contract 1:56:15 lists exactly those errors for create. 1:56:18 If checkout could fail with something the contract doesn't list, the line wouldn't 1:56:21 compile. The API docs, the handler, and the workflow, they 1:56:25 all agree. It's impossible for them not to, which is 1:56:30 amazing. 1:56:31 And we can see this back in the docs. 1:56:33 If I open up the /post orders, 1:56:37 you can see all of the different response codes that can be returned from 1:56:41 this API, not just the success with the expected 1:56:44 schema, but all 1:56:45 of these other responses that can come back from our domain model, 1:56:49 right? A payment declined. The reason, the underlying error 1:56:53 code comes directly from the source of truth, the code, which is 1:56:56 incredible. We know as a client of the application, 1:56:59 we can code against this 1:57:01 and keep our clients just as safe in the error path as they do with the 1:57:05 success path. 1:57:07 Lastly, we have this API routes. This turns the API plus 1:57:11 its handlers into routes, also serving the raw 1:57:14 OpenAPI spec at openapi.json, 1:57:18 so every handler group must be provided, or the type tells you one's missing. 1:57:22 And this means that we have this accessible for clients and 1:57:26 consumers, which is the source of truth for what our 1:57:29 API is returning, 1:57:30 both in the success and error path. 1:57:33 And notice this API routes is just yet another layer, and it still 1:57:37 needs things, right? We only provided three services. 1:57:40 It knows that it still needs the other services plus some 1:57:44 platform pieces, and that's what we're gonna wire in next 1:57:47 in the final file, the 1:57:48 main.ts. So the main.ts here is where we plug everything 1:57:52 together. 1:57:54 This decides which implementations we run for all of our 1:57:58 abstract interfaces so far. Everything else just declared what it 1:58:02 needs, and so here we can wire it in. 1:58:05 So the only two imports from outside of Effect in the whole app are in here. 1:58:09 We have an import from Effect/platform, platform 1:58:13 bun, 1:58:15 and this is the bun specific HTTP server and runtime. 1:58:19 There are Node and Deno equivalents, and you can swap these two names, 1:58:22 and the app 1:58:22 runs on Node just like that. And we also have 1:58:25 Effect/sequel pg, the Postgres driver 1:58:29 behind the generic SQL client that we've used so far. 1:58:32 These stay as separate packages because they're tied to specific runtimes and 1:58:36 databases, which we know we can swap out without 1:58:39 having to change any of 1:58:40 our service code. 1:58:44 So first up, we have this SQL live const. 1:58:48 This is the Postgres layer. This is what provides the SQL 1:58:52 client. The URL comes from database URL 1:58:56 read as config.redacted, a secret. 1:59:00 This means it doesn't end up in logs or error messages, which is very nice. 1:59:04 And these are a couple of transformers we're using to transform 1:59:08 and map our column names. For example, the database has 1:59:12 price_cents, but our schemas have price cents camel 1:59:16 cased. So difference in snake versus camel 1:59:18 casing. 1:59:19 And so if we want to make sure we don't have to code with snake case in this 1:59:23 example, we can use these transformers 1:59:27 to essentially translate and map the database to our 1:59:31 code schemas and make them the same and in line, which is nice. 1:59:35 We don't have to sacrifice readability to keep these the same. 1:59:40 Now, from here on, we build the app up in layers, and that 1:59:44 is literal. So first up, repos. This 1:59:47 uses layer.mergeall. It combines the Postgres 1:59:51 inventory and the Postgres orders 1:59:56 into one layer that provides both. 1:59:59 They both need a SQL client, so 2:00:02 layer.provide is what does that. It feeds it 2:00:05 in. And one important detail, a layer is built once and 2:00:09 shared. Both repositories here are gonna get the same connection 2:00:13 pool and not one each. 2:00:15 Next up, we have the services. So take 2:00:18 checkout.layer, 2:00:22 which needed inventory and orders, if you remember. 2:00:26 As we can see here, it needs inventory and orders. 2:00:32 And so we provide it with repos. It's provide 2:00:36 merge instead of provide, and the difference here 2:00:39 matters. Provide feeds repos into checkout 2:00:43 and hides 2:00:43 them. Only checkout comes out. Provide merge feeds 2:00:47 them and keeps them in the output. We need that because the handlers use 2:00:51 inventory and orders directly for get/product and 2:00:55 get/orders ID. So essentially just a way to 2:00:58 return back the output from doing this, whereas we didn't need to 2:01:02 do that for repos. For services, we want that, so our handlers have the 2:01:06 same. Next up, we have routes. This is our API routes 2:01:11 merged with HTTP API scaler. This is the docs 2:01:15 page that we opened up at /docs generated from that same API 2:01:18 value. 2:01:20 Then provide services so the handlers get checkout, inventory, 2:01:24 and orders. Next up, we have server live. 2:01:27 These serve those routes on a bun HTTP server. 2:01:31 The port is config.port. with defaulting to 2:01:34 3460. And the Bun server layer also supplies the 2:01:37 platform 2:01:38 pieces that we need, like the router, file system, and so on. 2:01:41 And so that API routes, which was asking for. 2:01:45 And the final line here, 2:01:47 it's the one line that actually runs everything. 2:01:50 Everything before this line was a description. 2:01:53 Layer.launch turns the whole layer into an effect that builds 2:01:57 everything and then waits forever. 2:01:59 Bunruntime.runmain runs it 2:02:02 and handles Control C, it interrupts the app, 2:02:05 and every layer gets shut 2:02:06 down in reverse order. The server stops taking requests first, 2:02:10 in-flight requests get interrupted, and yes, their on error cleanup runs 2:02:14 too, and then the database pool closes. 2:02:17 You get a fully graceful shutdown without writing a single line. 2:02:21 How cool is that? So I hope you've thoroughly enjoyed this 2:02:24 walkthrough 2:02:25 over migrating a traditional TypeScript API into 2:02:28 Effect and seeing not only the syntax, what Effect is made up 2:02:32 of and how to use it, but also the core concepts that 2:02:36 hopefully you can use to, to try and building your own apps and 2:02:40 APIs with Effect. I think as you've seen here, the developer 2:02:43 experience is quite simply unmatched in terms of what it's doing 2:02:47 for us, as well as the combined runtime type 2:02:51 safety 2:02:51 we get, both in the success and error routes. 2:02:55 So I hope you've enjoyed this video. 2:02:57 Thank you so much for watching, and I'll see you in the next one. 2:03:01 Now, if you enjoyed this lecture and you wanna see more content like it, 2:03:05 make sure you head down to my website below, 2:03:07 learn.michaelguay.dev, where you get access to all my 2:03:11 best-selling 2:03:11 Udemy courses, hundreds of hours of exclusive developer 2:03:15 content covering advanced full stack development that you can't really 2:03:19 get anywhere else in my opinion. My current course is NestJS Durable 2:03:23 Workflows, How to Build Business Processes 2:03:25 that Survive Crashes in the 2:03:27 Real World. 2:03:29 We walk through distributed workflows using the outbox pattern and 2:03:32 Apache Pulsar. My next course will be on Effect, so if 2:03:36 you've enjoyed this deep dive, you're gonna wanna subscribe and stick 2:03:40 around for the upcoming course. Thanks so much for watching, 2:03:44 and I'll see you in the next one.