𝗣𝗿𝗼𝗹𝗼𝗴𝘂𝗲 𝗮𝗻𝗱 𝗘𝗽𝗶𝗹𝗼𝗴𝘂𝗲 𝗠𝗮𝗰𝗿𝗼𝘀 𝗶𝗻 𝗛𝘆𝗽𝗲𝗿𝗹𝗮𝗻𝗲

Middleware is the backbone of request processing in Hyperlane. Most people use standard request and response middleware. However, Hyperlane offers specialized prologue and epilogue macros for extra control.

These macros run at the very start and very end of the request lifecycle. They allow you to control exactly when data reaches the client.

The Request Lifecycle:

• Request arrives: The server receives the HTTP request. • Prologue phase: You send initial data like headers or status codes. • Middleware chain: Functions process the request. • Route handler: The system builds the response. • Response middleware: Functions process the response. • Epilogue phase: Final data flushes to the client and connections close.

Use these macros to manage steps 2 and 6.

The Send Macros:

Use #[try_send] for non-critical data. If a connection breaks, it handles the error without crashing. This is good for streaming where losing one chunk is fine.

Use #[send] for critical data. This ensures the data goes through.

The Flush Macros:

Use #[try_flush] to attempt to clear the buffer and handle errors gracefully.

Use #[flush] to force all buffered data to the client. Use this to prevent data loss before closing a connection.

Best Practices:

  • Use #[try_send] for streaming data to avoid crashes on broken connections.
  • Use #[send] when data delivery is mandatory.
  • Always flush your buffer before closing a connection.
  • Check stream.is_keep_alive() in your epilogue to manage connection reuse.
  • Use these macros for Server-Sent Events (SSE) to push real-time updates.
  • Handle all send and flush errors to prevent system failures.

These tools give you precise control over data flow and response timing.

Source: https://dev.to/tengxgfyrz67s/prologue-and-epilogue-macros-1n29 Project Code: https://github.com/hyperlane-dev/hyperlane