|
| 1 | +using Restate.Sdk; |
| 2 | + |
| 3 | +namespace NativeAotSaga; |
| 4 | + |
| 5 | +/// <summary> |
| 6 | +/// Demonstrates the Saga pattern (compensating transactions) using Restate, |
| 7 | +/// compiled with NativeAOT. |
| 8 | +/// </summary> |
| 9 | +[Service] |
| 10 | +public sealed class TripBookingService |
| 11 | +{ |
| 12 | + [Handler] |
| 13 | + public async Task<TripBookingResult> Book(Context ctx, TripBookingRequest request) |
| 14 | + { |
| 15 | + var compensations = new List<Func<Context, Task>>(); |
| 16 | + |
| 17 | + try |
| 18 | + { |
| 19 | + // Step 1: Book flight |
| 20 | + ctx.Console.Log($"Booking flight for trip {request.TripId}..."); |
| 21 | + var flightConfirmation = await ctx.Run( |
| 22 | + "book-flight", |
| 23 | + () => BookingApi.BookFlight(request.Flight) |
| 24 | + ); |
| 25 | + |
| 26 | + compensations.Add( |
| 27 | + async (c) => |
| 28 | + { |
| 29 | + c.Console.Log($"Compensating: cancelling flight {flightConfirmation}"); |
| 30 | + await c.Run("cancel-flight", () => BookingApi.CancelFlight(flightConfirmation)); |
| 31 | + } |
| 32 | + ); |
| 33 | + |
| 34 | + // Step 2: Book hotel |
| 35 | + ctx.Console.Log($"Booking hotel for trip {request.TripId}..."); |
| 36 | + var hotelConfirmation = await ctx.Run( |
| 37 | + "book-hotel", |
| 38 | + () => BookingApi.BookHotel(request.Hotel) |
| 39 | + ); |
| 40 | + |
| 41 | + compensations.Add( |
| 42 | + async (c) => |
| 43 | + { |
| 44 | + c.Console.Log($"Compensating: cancelling hotel {hotelConfirmation}"); |
| 45 | + await c.Run("cancel-hotel", () => BookingApi.CancelHotel(hotelConfirmation)); |
| 46 | + } |
| 47 | + ); |
| 48 | + |
| 49 | + // Step 3: Book car rental (may fail — demonstrates compensation) |
| 50 | + ctx.Console.Log($"Booking car rental for trip {request.TripId}..."); |
| 51 | + var carConfirmation = await ctx.Run( |
| 52 | + "book-car-rental", |
| 53 | + () => BookingApi.BookCarRental(request.CarRental), |
| 54 | + RetryPolicy.FixedAttempts(3) |
| 55 | + ); |
| 56 | + |
| 57 | + ctx.Console.Log($"Trip {request.TripId} booked successfully!"); |
| 58 | + return new TripBookingResult( |
| 59 | + request.TripId, |
| 60 | + flightConfirmation, |
| 61 | + hotelConfirmation, |
| 62 | + carConfirmation |
| 63 | + ); |
| 64 | + } |
| 65 | + catch (TerminalException) |
| 66 | + { |
| 67 | + ctx.Console.Log( |
| 68 | + $"Trip {request.TripId} failed. Running {compensations.Count} compensation(s)..." |
| 69 | + ); |
| 70 | + |
| 71 | + for (var i = compensations.Count - 1; i >= 0; i--) |
| 72 | + await compensations[i](ctx); |
| 73 | + |
| 74 | + ctx.Console.Log($"Trip {request.TripId} fully compensated."); |
| 75 | + throw; |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments