Header image

Xử Lý Lỗi Theo Phong Cách Lập Trình Hàm Trong Kotlin Với Arrow-kt

07/04/2022

630

Xử Lý Lỗi Theo Phong Cách Lập Trình Hàm Trong Kotlin Với Arrow-kt

Bài viết này sẽ giới thiệu một số cách để xử lý lỗi trong Kotlin theo phong cách lập trình hàm sử dụng thư viện Arrow-kt. Những ví dụ được đưa ra sẽ theo thứ tự từ đơn giản đến phức tạp nhưng mạnh mẽ hơn.

Kotlin là gì?

Kotlin là một ngôn ngữ lập trình kiểu tĩnh, ban đầu được thiết kế để chạy trên máy ảo Java (JVM), sau này có thể biên dịch sang JavaScript và Native binaries sử dụng công nghệ LLVM. Kotlin có cú pháp hiện đại, ngắn gọn, an toàn và hỗ trợ cả lập trình hướng đối tượng (OOP)lập trình hàm (FP).

Arrow-kt là gì?

Arrow-kt (https://arrow-kt.io/) là một thư viện Typed Functional Programming trong Kotlin. Arrow cung cấp một ngôn ngữ chung của các interface và sự trừu tượng hóa trên các thư viện Kotlin. Nó bao gồm các kiểu dữ liệu phổ biến nhất như Option, Either, Validated, v.v … và các functional operator như traversecomputation blocks giúp cho người dùng viết các ứng dụng và thư viện pure FP dễ dàng hơn.

Setup

Trong file build.gradle.kts của root project, thêm mavenCentral vào danh sách:

allprojects {
    repositories {
        mavenCentral()
    }
}

Thêm dependency vào file build.gradle.kts của project:

val arrow_version = "1.0.1"
dependencies {
    implementation("io.arrow-kt:arrow-core:$arrow_version")
}

Pure function và exceptions

Pure function

Trong lập trình hàm, pure function là những function có hai tính chất:

  • Giá trị trả về chỉ phụ thuộc vào tham số truyền vào nó (tức là nếu cùng input thì cùng output).
  • Không tạo ra các side effect.

Side effect là những tác dụng xảy ra khi thực hiện một function mà không phải công dụng chính của nó. Ví dụ: ngoài việc trả về các giá trị, nó gây ra những tương tác thay đổi môi trường, thay đổi các biến toàn cục, thực hiện các hoạt động I/O như HTTP request, in dữ liệu ra console, đọc và ghi files Trong Kotlin, tất cả các function trả về Unit rất có thể tạo ra side effect. Đó là bởi vì giá trị trả về là Unit biểu thị “không có giá trị hữu ích được trả về”, điều này ngụ ý rằng function không làm gì khác ngoài việc thực hiện các side effect.

Một số ví dụ pure function trong Kotlin là những hàm toán học như sin, cos, max, …

Lợi ích của pure functions: dễ dàng combine, dễ dàng test, dễ dàng debug, dễ dàng parallelize, … Vì thế trong lập trình hàm, chúng ta sẽ cố gắng sử dụng nhiều pure functions nhất có thể, và tách biệt các phần pure và impure.

Exceptions

Kotlin có thể throwcatch các Exception tương tự như ngôn ngữ Java, JavaScript, C++,… Sử dụngtry { } catch(e) { } finally { } là cách xử lý lỗi phổ biến trong các ngôn ngữ lập trình mệnh lệnh.

Tuy nhiên việc throw và catch các Exception, chúng ta có thể thay đổi hành vi của function, khiến cho các function không còn pure nữa (catch Exception là một side effect). Ví dụ, một function catch hai Exception là ex1ex2 từ một function khác và tính toán kết quả, lúc đó kết quả đó sẽ phụ thuộc vào thứ tự thực thi của các câu lệnh, thậm chí có thể thay đổi giữa hai lần thực thi khác nhau của cùng một hệ thống.

Partial function

Ngoài ra, việc throw các Exception khiến cho các function trở thành một Partial function, tức là một function không hoàn toàn – không được xác định cho tất cả các giá trị input có thể có, bởi vì trong một số trường hợp, nó có thể không bao giờ trả về bất cứ thứ gì. Ví dụ, trong trường hợp một vòng lặp vô hạn hoặc nếu một Exception được throw.

Ví dụ: findUserById ở ví dụ dưới là một partial function.

@JvmInline
value class UserId(val value: String)

@JvmInline
value class Username(val value: String)

@JvmInline
value class PostId(val value: String)

data class User(
    val id: UserId,
    val username: Username,
    val postIds: List<PostId>
)

class UserException(message: String?, cause: Throwable?) : Exception(message, cause)

/**
 * @return an [User] if found or `null` otherwise.
 * @throws UserException if there is any error (eg. database error, connection error, ...)
 */
suspend fun findUserById(id: UserId): User? = TODO()

Đề làm cho findUserById trở thành một total function, chúng ta thay vì throw UserException, chúng ta có thể return nó như một giá trị, thay return type của findUserById thành UserResult.

sealed interface UserResult {
    data class Success(val user: User?) : UserResult
    data class Failure(val error: UserException) : UserResult
}

suspend fun findUserById(id: UserId): UserResult = TODO()

Các vấn đề với Exceptions

Exception có thể được xem như là những câu lệnh GOTO như trong C/C++, vì chúng làm gián đoạn luồng chương trình bằng cách quay lại nơi gọi nó. Các Exception không nhất quán, đặc biệt là khi trong lập trình Multithread, chúngta try...catch một function nhưng Exception được throw ở một Thread khác mà không thể catch nó được.

Một vấn đề khác là việc lạm dụng catch Exception: catch nhiều hơn những gì cần thiết và cả những Exception từ hệ thống như VirtualMachineError, OutOfMemoryError,…

try {
    doExceptionalStuff() //throws IllegalArgumentException
} catch (e: Throwable) {
    // too broad, `Throwable` matches a set of fatal exceptions and errors
    // a user may be unable to recover from:
    /*
    VirtualMachineError
    OutOfMemoryError
    ThreadDeath
    LinkageError
    InterruptedException
    ControlThrowable
    NotImplementedError
    */
}

Và cuối cùng, nhìn vào một signature của một function, chúng ta không thể biết được, nó sẽ throw ra Exception nào, ngoài việc đọc docs hay là đọc source code của nó, thay vào đó, chúng ta hay để signature của function đó biểu hiện rõ ràng những lỗi nào có thể xảy ra khi gọi function đó.

Vì vậy, để xử lý lỗi, chúng ta cần một type có thể được compose với nhau, và biểu thị một kết quả hợp lệ hoặc một lỗi. Những type đó là Discriminated union/ tagged union, trong Kotlin đó được triển khai thông qua sealed class/sealed interface/enum class. Chúng ta sẽ cùng tìm hiểu kotlin.Result được cung cấp bởi Kotlin Sdtlib từ version 1.3 , và sau đó là arrow.core.Either đến từ thư viện Arrow-kt.

Sử dụng kotlin.Result để xử lý lỗi

Chúng ta có thể sử dụng Result<T> như là một type để biểu thị: hoặc là giá trị thành công với type là T, hoặc là là một lỗi xảy ra với một một Throwable. Nếu theo cách hiểu đơn giản, Result<T> = T | Throwable.

Để tạo ra giá trị Result, ta có thể dụng các function có sẵn như

  • Result.success
  • Result.failure
  • runCatching (tương tự như try { } catch { }
    nhưng trả về Result).
suspend fun findUserByIdFromDb(id: String): UserDb? = TODO()

fun UserDb.toUser(): User = TODO()

suspend fun findUserById(id: UserId): Result<User?> = runCatching { findUserByIdFromDb(id.value)?.toUser() }

Chúng ta có thể kiểm tra Result là giá trị thành công hay không, thông qua hai property là isSuccessisFailure. Để thực hiện các hành động ứng với mỗi trường hợp của Result thông qua function onSuccessonFailure.

val userResult: Result<User?> = findUserById(UserId("#id"))
userResult.isSuccess
userResult.isFailure
userResult.onSuccess { u: User? -> println(u) }
userResult.onFailure { e: Throwable -> println(e) }

Để có thể lấy giá trị bên trong Result, chúng ta sử dụng các function getOr__. Sử dụng exceptionOrNull để truy cập giá trị Throwable bên trong nếu Result đại diện cho giá trị thất bại. Ngoài ra, còn có function fold có thể handle một trong hai case dễ dàng.

val userResult: Result<User?> = findUserById(UserId("#id"))

// Access value
userResult.getOrNull()
userResult.getOrThrow()
userResult.getOrDefault(defaultValue)
userResult.getOrElse { e: Throwable -> defaultValue(e) }

// Access Throwable
userResult.exceptionOrNull()

fun handleUser(u: User?) {}
fun handleError(e: Throwable) {
    when (e) {
        is UserException -> {
            // handle UserException
        }
        else -> {
            // handle other cases
        }
    }
}

userResult.fold(
    onSuccess = { handleUser(it) },
    onFailure = { handleError(it) }
)

Tuy nhiên, sức mạnh thực sự của Result nằm ở việc chain các hoạt động trên nó. Ví dụ: nếu bạn muốn truy cập một property của User:

val userResult: Result<User?> = findUserById(UserId("#id"))
val usernameNullableResult: Result<Username?> = userResult.map { it?.username }

Chú ý rằng, nếu việc gọi lambda truyền vào function map throw Exception, thì Exception đó sẽ bị throw ra ngoài. Nếu muốn Exception đó được catch và chuyển thành giá trị Result, sử dụng mapCatching để vừa map vừa catching.

val usernameResult: Result<Username> = userResult.map {
    checkNotNull(it?.username) { "user is null!" }
}

Một vấn đề đặt ra là làm sao để chain các Result mà phụ thuộc lẫn nhau

// (UserId) -> Result<User?>
suspend fun findUserById(id: UserId): Result<User?> = TODO()

// User -> List<Post>
suspend fun getPostsByUser(user: User): Result<List<Post>> = TODO()

// List<Post> -> Result<Unit>
suspend fun doSomethingWithPosts(posts: List<Post>): Result<Unit> = TODO()

Chúng ta tạo một function flatMap (mapflatten).

// Map and flatten
inline fun <T, R> Result<T>.flatMap(transform: (T) -> Result<R>): Result<R> = mapCatching { transform(it).getOrThrow() }

// or
inline fun <T, R> Result<T>.flatMap(transform: (T) -> Result<R>): Result<R> = map(transform).flatten()
inline fun <T> Result<Result<T>>.flatten(): Result<T> = getOrElse { Result.failure(it) }

Bằng việc sử dụng flatMap, chúng ta có thể chain các Result với nhau

val unitResult: Result<Unit> = findUserById(UserId("#id"))
    .flatMap { user: User? -> runCatching { checkNotNull(user) { "user is null!" } } }
    .flatMap { getPostsByUser(it) }
    .flatMap { doSomethingWithPosts(it) }

Thư viện Arrow-kt cũng cung cấp block result { ... } để có thể handle việc chain các Result với nhau, tránh một số trường hợp sử dụng quá nhiều các nested flatMap. Trong block result { ... }, sử dụng function bind() để lấy giá trị T từ Result<T>. Nếu bind được gọi trên một Result đại diện một lỗi, thì phần code ở phía dưới nó trong block result { ... } sẽ bị bỏ qua (cơ chế short-circuits).

import arrow.core.*

val unitResult: Result<Unit> = result { /*this: ResultEffect*/
    val userNullable: User? = findUserById(UserId("#id")).bind()
    val user: User = checkNotNull(userNullable) { "user is null!" }
    val posts: List<Post> = getPostsByUser(user).bind()
    doSomethingWithPosts(posts).bind()
}

Một số tình huống khác có thể yêu cầu các chiến lược xử lý lỗi phức tạp có thể bao gồm khôi phục hoặc báo cáo lỗi. Ví dụ, chúng ta fetch data từ remote server, nếu bị lỗi thì sẽ lấy data từ cache. Chúng ta có thể sử dụng 2 function recoverrecoverCatching,

class MyData(...)

fun getFromRemote(): MyData = TODO()
fun getFromCache(): MyData = TODO()

val result: Result<MyData> = runCatching { getFromRemote() }
    .recoverCatching { e: Throwable ->
        logger.error(e, "getFromRemote")
        getFromCache()
    }

Sử dụng Result là một cách tiếp cận này tốt hơn, tuy nhiên vấn đề là lỗi luôn luôn là một Throwable, ta phải đọc docs hoặc đọc source code của nó. Một vấn đề nữa là runCatching khi kết hợp với suspend function, nó sẽ catch mọi Throwable, kể cả kotlinx.coroutines.CancellationException, CancellationException là một Exception đặc biệt, được coroutines sử dụng để đảm bảo cơ chế cooperative cancellation (xem issues 1814 Kotlin/kotlinx.coroutines).

Một cách tiếp cận tốt hơn là sử dụng arrow.core.Either, khắc phục các nhược điểm của Result.

Sử dụng arrow.core.Either để xử lý lỗi

Chúng ta có thể sử dụng Either<L, R> như là một type để biểu thị: hoặc là giá trị Left(value: L) , hoặc là giá trị Right(value: R). Nếu theo cách hiểu đơn giản, Either<L, R> = L | R.

public sealed class Either<out A, out B> {
    public data class Left<out A> constructor(val value: A) : Either<A, Nothing>()
    public data class Right<out B> constructor(val value: B) : Either<Nothing, B>()
}

Trong đó, Left thường đại diện cho các giá trị lỗi, giá trị không mong muốn, và Right thường đại diện cho các giá trị thành công, giá trị mong muốn. Nhìn chung Either<L, R> tương tự với Result<T>, Result<T> chỉ tập trung vào type của giá trị thành công mà không quan tâm đến type của giá trị lỗi, và chúng ta có thể xem Result<R> ~= Either<Throwable, R>. Eitherright-biased, tức là các function như map, filter, flatMap, … sẽ theo nhánh Right, nhánh Left bị bỏ qua (được return trực tiếp mà không có hành động nào trên nó cả).

Để tạo ra giá trị Either, ta có thể dụng các function có sẵn như:

  • Left constructor, ví dụ: val e: Either<Int, Nothing> = Left(1)
  • Right constructor, ví dụ: val e: Either<Nothing, Int> = Right(1)
  • left extension function, ví dụ val e: Either<Int, Nothing> = 1.left().
  • right extension function, ví dụ val e: Either<Nothing, Int> = 1.right().
  • Either.catch functions, catch các Exceptions nhưng nó sẽ bỏ qua các fatal Exception
    như kotlinx.coroutines.CancellationException, VirtualMachineError, OutOfMemoryError,…
  • Và nhiều cách được cung cấp bởi arrow.core.Either.Companion.
suspend fun findUserByIdFromDb(id: String): UserDb? = TODO()

fun UserDb.toUser(): User = TODO()

fun Throwable.toUserException(): UserException = TODO()

suspend fun findUserById(id: UserId): Either<UserException, User?> =
    Either
        .catch { findUserByIdFromDb(id.value)?.toUser() } // Either<Throwable, User?>
        .mapLeft { it.toUserException() }                 // Either<UserException, User?>

Chúng ta có thể kiểm tra Either là giá trị Left hay Right, thông qua hai function là isLeft()isLeft(). Either cũng cung cấp hai function tap (tương tự onSucesscủa Result) và tapLeft (tương tự onFailure của Result).

val result: Either<UserException, User?> = findUserById(UserId("#id"))
result.isLeft()
result.isRight()
result.tap { u: User? -> println(u) }
result.tapLeft { e: UserException -> println(e) }

Tương tự như Result, chúng ta sử dụng các function getOrElse, orNull, getOrHandle để lấy giá trị mà Right chứa nếu nó là Right. Một số function hữu ích nữa là fold, bimap, mapError, filter,…

val result: Either<UserException, User?> = findUserById(UserId("#id"))

// Access value
result.getOrElse { defaultValue }
result.orNull()
result.getOrHandle { e: UserException -> defaultValue(e) }

fun handleUser(u: User?) {}
fun handleError(e: UserException) {
    // handle UserException
}

result.fold(
    ifRight = { handleUser(it) },
    ifLeft = { handleError(it) }
)

Tương tự ví dụ khi sử dụng Result, chúng ta cũng muốn chain nhiều giá trị Either với nhau

// (UserId) -> Either<UserException, User?>
suspend fun findUserById(id: UserId): Either<UserException, User?> = TODO()

// User -> Either<UserException, List<Post>>
suspend fun getPostsByUser(user: User): Either<UserException, List<Post>> = TODO()

// List<Post> -> Either<UserException, Unit>
suspend fun doSomethingWithPosts(posts: List<Post>): Either<UserException, Unit> = TODO()

Thư viện Arrow-kt đã cung cấp sẵn function flatMap và block either { ... } để có thể chain các Either với nhau dễ dàng. Trong either { ... } block, sử dụng function bind() để lấy giá trị R từ Either<L, R>. Nếu bind được gọi trên một Either chứa giá trị Left, thì phần code ở phía dưới nó trong block either { ... } sẽ bị bỏ qua (cơ chế short-circuits).

import arrow.core.*

class UserNotFoundException() : UserException("User is null", null)

val result: Either<UserException, Unit> = findUserById(UserId("#id"))
    .flatMap { user: User? ->
        if (user == null) UserNotFoundException().left()
        else user.right()
    }
    .flatMap { getPostsByUser(it) }
    .flatMap { doSomethingWithPosts(it) }

// or either block

val result: Either<UserException, Unit> = either { /*this: EitherEffect*/
    val userNullable: User? = findUserById(UserId("#id")).bind()
    val user: User = ensureNotNull(userNullable) { UserNotFoundException() }
    val posts: List<Post> = getPostsByUser(user).bind()
    doSomethingWithPosts(posts).bind()
}

Cuối cùng là cách khôi phục lỗi. Tương tự như recoverrecoverCatching của Result, chúng ta có thể sử dụng hai function handleErrorhandleErrorWith (giống như flatMap nhưng theo nhánh Left).

class MyData(...)

suspend fun getFromRemote(): MyData = TODO()
suspend fun getFromCache(): MyData = TODO()

val result: Either<Throwable, MyData> =
    Either
        .catch { getFromRemote() }
        .handleErrorWith { e: Throwable ->
            Either.catch {
                logger.error(e, "getFromRemote")
                getFromCache()
            }
        }

Kết luận

Chúng ta đã cùng tìm hiểu Result và sau đó là Either, cả hai type giúp xử lý lỗi và làm giảm side effect. Either còn chỉ rõ về những lỗi có thể xảy ra mà chỉ cần nhìn vào signature của một function. Ngoài ra, Either hỗ trợ cho suspend function mà không làm mất đi cơ chế cancellation, và Arrow-kt cũng có module Fx (https://arrow-kt.io/docs/fx/) giúp cho việc sử dụng Kotlin Coroutines dễ dàng hơn, khi viết các chương trình asyncconcurrent.

Hy vọng bạn thích bài viết này và hôm nay bạn đã học được điều gì đó hữu ích!

Tài liệu tham khảo

  • Arrow-kt – Either docs
  • Arrow-kt – Error handlding
  • Arrow-kt – Monad comprehension
  • Ciocîrlan, D. (2021) Idiomatic error handling in scala, Rock the JVM Blog. Available at: https://blog.rockthejvm.com/idiomatic-error-handling-in-scala/ (Accessed: 04 October 2024).

Author: st-hocnguyen

Related Blog

Knowledge

Software Development

+0

    Mastering AWS Lambda: An Introduction to Serverless Computing

    Imagine this: you have a system that sends emails to users to notify them about certain events at specific times of the day or week. During peak hours, the system demands a lot of resources, but it barely uses any for the rest of the time. If you were to dedicate a server just for this task, managing resources efficiently and maintaining the system would be incredibly complex. This is where AWS Lambda comes in as a solution to these challenges. Its ability to automatically scale, eliminate server management, and, most importantly, charge you only for the resources you use simplifies everything. Hello everyone! I’m Đang Đo Quang Bao, a Software Engineer at SupremeTech. Today, I’m excited to introduce the series' first episode, “Mastering AWS Lambda: An Introduction to Serverless Computing.” In this episode, we’ll explore: The definition of AWS Lambda and how it works.The benefits of serverless computing.Real-world use cases. Let’s dive in! What is AWS Lambda? AWS Lambda is a serverless computing service that Amazon Web Services (AWS) provides. It executes your code in response to specific triggers and scales automatically, charging you only for the compute time you use. How Does AWS Lambda Work? AWS Lambda operates on an event-driven model, reacting to specific actions or events. In simple terms, it executes code in response to particular triggers. Let’s explore this model further to gain a more comprehensive understanding. The above is a simplified workflow for sending emails to many users simultaneously, designed to give you a general understanding of how AWS Lambda works. The workflow includes: Amazon EventBridge:Role: EventBridge acts as the starting point of the workflow. It triggers the first AWS Lambda function at a specific time each day based on a cron schedule.How It Works:Configured to run automatically at 00:00 UTC or any desired time.Ensures the workflow begins consistently without manual intervention.Amazon DynamoDB:Role: DynamoDB is the primary database for user information. It holds the email addresses and other relevant metadata for all registered users.How It Works:The first Lambda function queries DynamoDB to fetch the list of users who need to receive emails.AWS Lambda (1st Function):Role: This Lambda function prepares the user data for email sending by fetching it from DynamoDB, batching it, and sending it to Amazon SQS.How It Works:Triggered by EventBridge at the scheduled time.Retrieves user data from DynamoDB in a single query or multiple paginated queries.Split the data into smaller batches (e.g., 100 users per batch) for efficient processing.Pushes each batch as a separate message into Amazon SQS.Amazon SQS (Simple Queue Service).Role: SQS serves as a message queue, temporarily storing user batches and decoupling the data preparation process from email-sending.How It Works:Each message in SQS represents one batch of users (e.g., 100 users).Messages are stored reliably and are processed independently by the second Lambda function.AWS Lambda (2nd Function):Role: This Lambda function processes each user batch from SQS and sends emails to the users in that batch.How It Works:Triggered by SQS for every new message in the queue.Reads the batch data (e.g., 100 users) from the message.Sends individual emails to each user in the batch using Amazon SES.Amazon SES (Simple Email Service).Role: SES handles the actual email delivery, reliably ensuring messages reach users’ inboxes.How It Works:Receives the email content (recipient address, subject, body) from the second Lambda function.Delivers emails to the specified users.Provides feedback on delivery status, including successful deliveries, bounces, and complaints. As you can see, AWS Lambda is triggered by external events or actions (AWS EventBridge schedule) and only "lives" for the duration of its execution. >>> Maybe you are interested: The Rise of Serverless CMS Solutions Benefits of AWS Lambda No Server Management:Eliminate the need to provision, configure, and maintain servers. AWS handles the underlying infrastructure, allowing developers to focus on writing code.Cost Efficiency:Pay only for the compute time used (measured in milliseconds). There are no charges when the function isn’t running.Scalability:AWS Lambda automatically scales horizontally to handle thousands of requests per second.Integration with AWS Services:Lambda integrates seamlessly with services like S3, DynamoDB, and SQS, enabling event-driven workflows.Improved Time-to-Market:Developers can deploy and iterate applications quickly without worrying about managing infrastructure. Real-World Use Cases for AWS Lambda AWS Lambda is versatile and can be applied in various scenarios. Here are some of the most common and impactful use cases: Real-Time File ProcessingExample: Automatically resizing images uploaded to an Amazon S3 bucket.How It Works:An upload to S3 triggered a Lambda function.The function processes the file (e.g., resizing or compressing an image).The processed file is stored back in S3 or another storage system.Why It’s Useful:Eliminates the need for a dedicated server to process files.Automatically scales based on the number of uploads.Building RESTful APIsExample: Creating a scalable backend for a web or mobile application.How It Works:Amazon API Gateway triggers AWS Lambda in response to HTTP requests.Lambda handles the request, performs necessary logic (e.g., CRUD operations), and returns a response.Why It’s Useful:Enables fully serverless APIs.Simplifies backend management and scaling.IoT ApplicationsExample: Processing data from IoT devices.How It Works:IoT devices publish data to AWS IoT Core, which triggers Lambda.Lambda processes the data (e.g., analyzing sensor readings) and stores results in DynamoDB or ElasticSearch.Why It’s Useful:Handles bursts of incoming data without requiring a dedicated server.Integrates seamlessly with other AWS IoT services.Real-Time Streaming and AnalyticsExample: Analyzing streaming data for fraud detection or stock market trends.How It Works:Events from Amazon Kinesis or Kafka trigger AWS Lambda.Lambda processes each data stream in real time and outputs results to an analytics service like ElasticSearch.Why It’s Useful:Allows real-time data insights without managing complex infrastructure.Scheduled TasksExample: Running daily tasks/reports or cleaning up expired data.How It Works:Amazon EventBridge triggers Lambda at scheduled intervals (e.g., midnight daily).Lambda performs tasks like querying a database, generating reports, or deleting old records.Why It’s Useful:Replaces traditional cron jobs with a scalable, serverless solution. Conclusion AWS Lambda is a powerful service that enables developers to build highly scalable, event-driven applications without managing infrastructure. Lambda simplifies workflows and accelerates time-to-market by automating tasks and seamlessly integrating with other AWS services like EventBridge, DynamoDB, SQS, and SEStime to market. We’ve explored the fundamentals of AWS Lambda, including its definition, how it works, its benefits, and its application in real-world use cases. It offers an optimized and cost-effective solution for many scenarios, making it a vital tool in modern development. At SupremeTech, we’re committed to harnessing innovative technologies to deliver impactful solutions. This is just the beginning of our journey with AWS Lambda. In upcoming episodes, we’ll explore implementing AWS Lambda in different programming languages and uncover best practices for building efficient serverless applications. Stay tuned, and let’s continue mastering AWS Lambda together!

    25/12/2024

    27

    Bao Dang D. Q.

    Knowledge

    +1

    • Software Development

    Mastering AWS Lambda: An Introduction to Serverless Computing

    25/12/2024

    27

    Bao Dang D. Q.

    Automate your git flow with git hooks

    Knowledge

    +0

      Automate Your Git Workflow with Git Hooks for Efficiency

      Have you ever wondered how you can make your Git workflow smarter and more efficient? What if repetitive tasks like validating commit messages, enforcing branch naming conventions, or preventing sensitive data leaks could happen automatically? Enter Git Hooks—a powerful feature in Git that enables automation at every step of your development process. If you’ve worked with webhooks, the concept of Git Hooks might already feel familiar. Like API events trigger webhooks, Git Hooks are scripts triggered by Git actions such as committing, pushing, or merging. These hooks allow developers to automate tasks, enforce standards, and improve the overall quality of their Git workflows. By integrating Git Hooks into your project, you can gain numerous benefits, including clearer commit histories, fewer human errors, and smoother team collaboration. Developers can also define custom rules tailored to their Git flow, ensuring consistency and boosting productivity. In this SupremeTech blog, I, Đang Đo Quang Bao, will introduce you to Git Hooks, explain how they work, and guide you through implementing them to transform your Git workflow. Let’s dive in! What Are Git Hooks? Git Hooks are customizable scripts that automatically execute when specific events occur in a Git repository. These events might include committing code, pushing changes, or merging branches. By leveraging Git Hooks, you can tailor Git's behavior to your project's requirements, automate repetitive tasks, and reduce the likelihood of human errors. Imagine validating commit messages, running tests before a push, or preventing large file uploads—all without manual intervention. Git Hooks makes this possible, enabling developers to integrate useful automation directly into their workflows. Type of Git Hooks Git Hooks come in two main categories, each serving distinct purposes: Client-Side Hooks These hooks run on the user’s local machine and are triggered by actions like committing or pushing changes. They are perfect for automating tasks like linting, testing, or enforcing commit message standards. Examples:pre-commit: Runs before a commit is finalized.pre-push: Executes before pushing changes to a remote repository.post-merge: Triggers after merging branches. Server-Side Hooks These hooks operate on the server hosting the repository and are used to enforce project-wide policies. They are ideal for ensuring consistent workflows across teams by validating changes before they’re accepted into the central repository. Examples: pre-receive: Runs before changes are accepted by the remote repository.update: Executes when a branch or tag is updated on the server. My Journey to Git Hooks When I was working on personal projects, Git management was fairly straightforward. There were no complex workflows, and mistakes were easy to spot and fix. However, everything changed when I joined SupremeTech and started collaborating on larger projects. Adhering to established Git flows across a team introduced new challenges. Minor missteps—like inconsistent commit messages, improper branch naming, accidental force pushes, or forgetting to run unit tests—quickly led to inefficiencies and avoidable errors. That’s when I discovered the power of Git Hooks. By combining client-side Git Hooks with tools like Husky, ESLint, Jest, and commitlint, I could automate and streamline our Git processes. Some of the tasks I automated include: Enforcing consistent commit message formats.Validating branch naming conventions.Automating testing and linting.Preventing accidental force pushes and large file uploads.Monitoring and blocking sensitive data in commits. This level of automation was a game-changer. It improved productivity, reduced human errors, and allowed developers to focus on their core tasks while Git Hooks quietly enforced the rules in the background. It transformed Git from a version control tool into a seamless system for maintaining best practices. Getting Started with Git Hooks Setting up Git Hooks manually can be dull, especially in team environments where consistency is critical. Tools like Husky simplify the process, allowing you to manage Git Hooks and integrate them into your workflows easily. By leveraging Husky, you can unlock the full potential of Git Hooks with minimal setup effort. I’ll use Bun as the JavaScript runtime and package manager in this example. If you’re using npm or yarn, replace Bun-specific commands with their equivalents. Setup Steps 1. Initialize Git: Start by initializing a Git repository if one doesn’t already exist git init 2. Install Husky: Use Bun to add Husky as a development dependency bun add -D husky 3. Enable Husky Hooks: Initialize Husky to set up Git Hooks for your project bunx husky init 4. Verify the Setup: At this point, a folder named .husky will be created, which already includes a sample of pre-commit hook. With this, the setup for Git Hooks is complete. Now, let’s customize it to optimize some simple processes. Examples of Git Hook Automation Git Hooks empowers you to automate tedious yet essential tasks and enforce team-wide best practices. Below are four practical examples of how you can leverage Git Hooks to improve your workflow: Commit Message Validation Ensuring consistent and clear commit messages improves collaboration and makes Git history easier to understand. For example, enforce the following format: pbi-203 - refactor - [description…] [task-name] - [scope] - [changes] Setup: Install Commitlint: bun add -D husky @commitlint/{config-conventional,cli} Configure rules in commitlint.config.cjs: module.exports = {     rules: {         'task-name-format': [2, 'always', /^pbi-\d+ -/],         'scope-type-format': [2, 'always', /-\s(refactor|fix|feat|docs|test|chore|style)\s-\s[[^\]]+\]$/]     },     plugins: [         {             rules: {                 'task-name-format': ({ raw }) => {                     const regex = /^pbi-\d+ -/;                     return [regex.test(raw),                         `❌ Commit message must start with "pbi-<number> -". Example: "pbi-1234 - refactor - [optimize function]"`                     ];                 },                 'scope-type-format': ({ raw}) => {                     const regex = /-\s(refactor|fix|feat|docs|test|chore|style)\s-\s[[^\]]+\]$/;                     return [regex.test(raw),                         `❌ Commit message must include a valid scope and description. Example: "pbi-1234 - refactor - [optimize function]".                         \nValid scopes: refactor, fix, feat, docs, test, chore, style`                     ];                 }             }         }     ] } Add Commitlint to the commit-msg hook: echo "bunx commitlint --edit \$1" >> .husky/commit-msg With this, we have completed the commit message validation setup. Now, let’s test it to see how it works. Now, developers will be forced to follow this committing rule, which increases the readability of the Git History. Automate Branch Naming Conventions Enforce branch names like feature/pbi-199/add-validation. First, we will create a script in the project directory named scripts/check-branch-name.sh. #!/bin/bash # Define allowed branch naming pattern branch_pattern="^(feature|bugfix|hotfix|release)/pbi-[0-9]+/[a-zA-Z0-9._-]+$" # Get the current branch name current_branch=$(git symbolic-ref --short HEAD) # Check if the branch name matches the pattern if [[ ! "$current_branch" =~ $branch_pattern ]]; then   echo "❌ Branch name '$current_branch' is invalid!"   echo "✅ Branch names must follow this pattern:"   echo "   - feature/pbi-<number>/<description>"   echo "   - bugfix/pbi-<number>/<description>"   echo "   - hotfix/pbi-<number>/<description>"   echo "   - release/pbi-<number>/<description>"   exit 1 fi echo "✅ Branch name '$current_branch' is valid." Add the above script execution command into the pre-push hook. echo "bash ./scripts/check-branch-name.sh" >> .husky/pre-push Grant execute permissions to the check-branch-name.sh file. chmod +x ./scripts/check-branch-name.sh Let’s test the result by pushing our code to the server. Invalid case: git checkout main git push Output: ❌ Branch name 'main' is invalid! ✅ Branch names must follow this pattern:   - feature/pbi-<number>/<description>   - bugfix/pbi-<number>/<description>   - hotfix/pbi-<number>/<description>   - release/pbi-<number>/<description> husky - pre-push script failed (code 1) Valid case: git checkout -b feature/pbi-100/add-new-feature git push Output: ✅ Branch name 'feature/pbi-100/add-new-feature' is valid. Prevent Accidental Force Pushes Force pushes can overwrite shared branch history, causing significant problems in collaborative projects. We will implement validation for the prior pre-push hook to prevent accidental force pushes to critical branches like main or develop. Create a script named scripts/prevent-force-push.sh. #!/bin/bash # Define the protected branches protected_branches=("main" "develop") # Get the current branch name current_branch=$(git symbolic-ref --short HEAD) # Check if the current branch is in the list of protected branches if [[ " ${protected_branches[@]} " =~ " ${current_branch} " ]]; then # Check if the push is a force push for arg in "$@"; do   if [[ "$arg" == "--force" || "$arg" == "-f" ]]; then     echo "❌ Force pushing to the protected branch '${current_branch}' is not allowed!"     exit 1   fi done fi echo "✅ Push to '${current_branch}' is valid." Add the above script execution command into the pre-push hook. echo "bash ./scripts/prevent-force-push.sh" >> .husky/pre-push Grant execute permissions to the check-branch-name.sh file. chmod +x ./scripts/prevent-force-push.sh Result: Invalid case: git checkout main git push -f Output: ❌ Force pushing to the protected branch 'main' is not allowed! husky - pre-push script failed (code 1) Valid case: git checkout main git push Output: ✅ Push is valid. Monitor for Secrets in Commits Developers sometimes unexpectedly include sensitive data in commits. We will set up a pre-commit hook to scan files for sensitive patterns before committing to prevent accidental commits containing sensitive information (such as API keys, passwords, or other secrets). Create a script named scripts/monitor-secrets-with-values.sh. #!/bin/bash # Define sensitive value patterns patterns=( # Base64-encoded strings "([A-Za-z0-9+/]{40,})={0,2}" # PEM-style private keys "-----BEGIN RSA PRIVATE KEY-----" "-----BEGIN OPENSSH PRIVATE KEY-----" "-----BEGIN PRIVATE KEY-----" # AWS Access Key ID "AKIA[0-9A-Z]{16}" # AWS Secret Key "[a-zA-Z0-9/+=]{40}" # Email addresses (optional) "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" # Others (e.g., passwords, tokens) ) # Scan staged files for sensitive patterns echo "🔍 Scanning staged files for sensitive values..." # Get the list of staged files staged_files=$(git diff --cached --name-only) # Initialize a flag to track if any sensitive data is found found_sensitive_data=false # Loop through each file and pattern for file in $staged_files; do # Skip binary files if [[ $(file --mime-type -b "$file") == "application/octet-stream" ]]; then   continue fi # Scan each pattern using grep -E (extended regex) for pattern in "${patterns[@]}"; do   if grep -E -- "$pattern" "$file"; then     echo "❌ Sensitive value detected in file '$file': Pattern '$pattern'"     found_sensitive_data=true     break   fi done done # If sensitive data is found, prevent the commit if $found_sensitive_data; then echo "❌ Commit aborted. Please remove sensitive values before committing." exit 1 fi echo "✅ No sensitive values detected. Proceeding with committing." Add the above script execution command into the pre-commit hook. echo "bash ./scripts/monitor-secrets-with-values.sh" >> .husky/pre-commit Grant execute permissions to the monitor-secrets-with-values.sh file. chmod +x ./scripts/monitor-secrets-with-values.sh Result: Invalid case: git add private git commit -m “pbi-002 - chore - add unexpected private file” Result: 🔍 Scanning staged files for sensitive values... -----BEGIN OPENSSH PRIVATE KEY----- ❌ Sensitive value detected in file 'private': Pattern '-----BEGIN OPENSSH PRIVATE KEY-----' ❌ Commit aborted. Please remove sensitive values before committing. husky - pre-commit script failed (code 1) Valid case: git reset private git commit -m “pbi-002 - chore - remove unexpected private file” Result: 🔍 Scanning staged files for sensitive values... ✅ No sensitive values detected. Proceeding with commit. [main c575028] pbi-002 - chore - remove unexpected private file 4 files changed, 5 insertions(+) create mode 100644 .env.example create mode 100644 .husky/commit-msg create mode 100644 .husky/pre-commit create mode 100644 .husky/pre-push Conclusion "Humans make mistakes" in software development; even minor errors can disrupt workflows or create inefficiencies. That’s where Git Hooks come in. By automating essential checks and enforcing best practices, Git Hooks reduces the chances of errors slipping through and ensures a smoother, more consistent workflow. Tools like Husky make it easier to set up Git Hooks, allowing developers to focus on writing code instead of worrying about process compliance. Whether it’s validating commit messages, enforcing branch naming conventions, or preventing sensitive data from being committed, Git Hooks acts as a safety net that ensures quality at every step. If you want to optimize your Git workflow, now is the time to start integrating Git Hooks. With the proper setup, you can make your development process reliable but also effortless and efficient. Let automation handle the rules so your team can focus on building great software.

      24/12/2024

      36

      Bao Dang D. Q.

      Knowledge

      +0

        Automate Your Git Workflow with Git Hooks for Efficiency

        24/12/2024

        36

        Bao Dang D. Q.

        Knowledge

        Software Development

        +0

           Exploring API Performance Testing with Postman

          Hello, tech enthusiasts and creative developers! I’m Vu, the author of SupremeTech’s performance testing series. In the article “The Ultimate Guide to JMeter Performance Testing Tool,” we explored JMeter's strengths and critical role in performance testing. Today, I’m introducing an exciting and straightforward way to do API performance testing using Postman. What is Postman? Postman is a robust API (Application Programming Interface) platform that empowers developers to quickly design, test, document, and interact with APIs. It is a widely used tool for testing APIs, which is valuable in software development, primarily web or mobile app development. Why Use Postman for API Testing? Postman is favored by software developers, testers, and API specialists because of its many advantages: User-Friendly Interface: Postman’s intuitive design makes it easy to use.Supports Diverse HTTP Methods: It handles requests such as GET, POST, PUT, DELETE, PATCH, OPTIONS, and more.Flexible Configuration: Easily manage API request headers, parameters, and body settings.Test Automation with Scripts: Write JavaScript code within the Tests tab to automate API response validation.Integration with CI/CD: Postman's CLI tool, Newman, seamlessly integrates with CI/CD pipelines, enabling automated API testing in development workflows.API Documentation and Sharing: Create and share API documentation with team members or clients effortlessly. Performance API Testing on Postman As of mid-2024, Postman introduced a new feature allowing users to perform API performance testing quickly and conveniently. With just a few simple steps, you can evaluate your API’s performance under high load and ensure its strength. Step 1: Select the Collection for Performance Testing Open Postman and navigate to the Collections tab on the left sidebar.Choose the Collection or Folder you want to test. Step 2: Launch the Collection Runner After selecting your desired Collection or Folder, click Run Collection to open the Collection Runner window.In the Runner, select the APIs you want to include in the performance test.Switch to the Performance tab and choose a simulation method:Fixed: Simulates a fixed number of users.Ramp Up: Starts with a few users and gradually increases.Spike: Introduces a sudden surge in traffic followed by a reduction.Peak: Increases traffic to a high level and sustains it for a period. Step 3: Adjust Virtual Users and Test Duration Configure the Virtual Users and Test Duration settings to simulate the desired load.Start with smaller values, then gradually increase them to gain a clear understanding of your API's performance under varying conditions. Step 4: Run the Test Click Run to start the performance test.During the test, Postman will send API requests and provide real-time data on:Response Time: The API's duration to respond to a request.Error Rate: The percentage of failed requests.Throughput: The number of API requests the system can handle per second. Step 5: Analyze the Report Once the test is complete, Postman generates a detailed report, including: Response Time: Tracks the duration it takes for APIs to process requests.Error Rate: Highlights any issues encountered during testing.Throughput: Measures the system's capacity to process requests under load. Use these metrics to evaluate whether your API performs efficiently under heavy traffic. These insights will guide you in optimizing your API for better performance. Leverage Customization for Realistic User Simulation Postman allows you to customize request data for each virtual user. You can upload a CSV or JSON file with unique datasets if you want different data for each user. This feature enables a more accurate simulation of real-world user behavior. After each test run, Postman provides an easy-to-understand report highlighting the areas for improvement. You can track performance changes and compare test results to identify weaknesses and refine your API. Test and Optimize Your API with Postman With Postman’s new performance testing feature, API optimization has never been easier. It helps you quickly identify and address potential issues to ensure your system is always ready to handle user demands effectively and reliably.   For more details and step-by-step guidance, check out the following resources on the Postman website:   OverviewRun a performance testView performance test metricsDebug performance test errorsInject data into virtual users Start your API performance optimization journey with Postman and prepare your system to meet every demand seamlessly. >>> Explore more articles about performance testing: SupremeTech’s Expertise in the Process of Performance Testing

          23/12/2024

          29

          Vu Nguyen Q.

          Knowledge

          +1

          • Software Development

           Exploring API Performance Testing with Postman

          23/12/2024

          29

          Vu Nguyen Q.

          Knowledge

          Software Development

          +0

            From Raw Data to Perfect API Responses: Serialization in NestJS

            Hello, My name is Dzung. I am a developer who has been in this game for approximately 6 years. I've just started exploring NestJS and am excited about this framework's capabilities. In this blog, I want to share the knowledge I’ve gathered and practiced in NestJS. Today's topic is serialization! As you know, APIs are like the messengers of your application, delivering data from the backend to the client side. Without proper control, they might spill too much information, such as passwords or internal settings. This is where serialization in NestJS steps in, turning messy, raw data into polished, purposeful API responses. With the power of serialization, you can control exactly what your users see, hide sensitive fields, format nested objects, and deliver secure, efficient, and downright beautiful responses. In this blog, we’ll explore how serialization in NestJS works, why it’s a must-have skill for any developer, and how to implement it step by step. Your APIs will go from raw and unrefined to clean and professional by the end. Let’s dive in! What Happens Without Serialization? Let’s look at what happens when you don’t use serialization in your NestJS application. Imagine you’re building a user management system, and you create an API endpoint to fetch user details. Here’s your User entity: Now, you write a simple endpoint to fetch a user: What happens when you call this endpoint? The API sends the entire user object straight to the client—every single field included: The consequences of lacking Serialization in the NestJS application Security Risks: Sensitive data, like passwords, should never be exposed in API responses.Data Overload: Users and clients don’t need internal flags or timestamps—they just add noise.Lack of Professionalism: Messy, unfiltered responses make your API look unpolished and unreliable. Next, we’ll see how to clean up this mess and craft polished API responses using NestJS serialization techniques. The Differences in Applying Serialization By implementing serialization in your NestJS application, you can take full control over what data is exposed in your API responses. Let’s revisit the previous example and clean it up. Step 1: Install class-transformer To get started with serialization, you need the class-transformer package. Install it with: Step 2: Update the User Entity with Exposed or Excluded Decorator Use class-transformer decorators to specify which fields should be exposed or excluded. Only the ID and email fields will be included in the response. Step 3: Apply the Serializer Interceptor NestJS provides a built-in ClassSerializerInterceptor to handle serialization. You can apply it at different levels: Per-Controller Globally To apply serialization to all controllers, add the interceptor to the application setup: When the Get User Endpoint is called, this is what your API will now return: Why Serialization Makes a Difference Security: Sensitive fields are automatically excluded, keeping your data safe.Clarity: Only the necessary fields are sent, reducing noise and improving usability.Professionalism: Clean and consistent responses give your API a polished look. Dynamic Serialization with Group What if you want to show different data to users, such as admins versus regular users? The class-transformer package supports groups, allowing you to expose fields based on context. Example: In the controller, specify the group for the transformation: When the Get User Endpoint is called, this is what your API will now return: By incorporating serialization into your NestJS application, you not only improve security but also enhance the user experience by providing streamlined, predictable, and professional API responses. Now that you know how serialization works in NestJS, you can apply these techniques to your projects, creating safer, cleaner, and more maintainable APIs. SupremeTech has lots of experience and produces web or app services. Let’s schedule a call now if you want to work with us. Also, now we are hiring! Please check open positions for career opportunities.

            20/12/2024

            38

            Dung Nguyen Q.

            Knowledge

            +1

            • Software Development

            From Raw Data to Perfect API Responses: Serialization in NestJS

            20/12/2024

            38

            Dung Nguyen Q.

            Customize software background

            Want to customize a software for your business?

            Meet with us! Schedule a meeting with us!