How floor114/mysql2-aws_rds_iam works
Project type and purpose
• Type: An open-source Ruby gem (library) that patches the mysql2 client to support AWS RDS IAM authentication.
• Purpose: When you call Mysql2::Client.new with aws_rds_iam_auth: true, the gem intercepts the connection, generates a short-lived auth token via AWS SDK, and then connects to MySQL on RDS using that token.
Main components
a. Consumer (Ruby application or script)
• Your Rails or Ruby code that does require 'mysql2/aws_rds_iam' and Mysql2::Client.new(...).
b. mysql2-aws_rds_iam gem
• ClientExtension – monkey-patches Mysql2::Client to detect aws_rds_iam_auth.
• AuthToken Registry – holds token generators keyed by name.
• Default Generator – uses Aws::RDS::AuthTokenGenerator (from aws-sdk-rds) to build tokens.
• ExpirableToken – wraps the raw token with expiry logic.
• Factory – orchestrates creation of ExpirableToken via selected generator.
• Errors – custom exception types.
c. External dependency
• aws-sdk-rds – the AWS Ruby SDK that actually talks to AWS STS/RDS to retrieve a signed auth token.
d. External service
• Amazon RDS MySQL instance with IAM authentication enabled.
Relationships and interactions
1) Application invokes Mysql2::Client.new with aws_rds_iam_auth: true.
2) ClientExtension intercepts initialization and calls AuthTokenFactory.build(host, port, username).
3) Factory looks up the chosen generator in AuthTokenRegistry.
4) DefaultGenerator (or custom) calls into aws-sdk-rds’s AuthTokenGenerator.generate to retrieve a presigned URL/token.
5) The raw token is wrapped into an ExpirableToken object.
6) ClientExtension supplies the token as the password parameter to the underlying mysql2 C extension.
7) mysql2 C extension makes the TCP handshake to the Amazon RDS endpoint using the token, returning a client connection.
Architectural patterns and principles
• Monkey-patch / extension pattern: Patches Mysql2::Client at runtime.
• Registry pattern: AuthTokenRegistry for pluggable token generators.
• Factory pattern: AuthTokenFactory to decouple generator lookup and invocation.
• Single Responsibility: Each module (Errors, Version, ClientExtension, Registry, Generator) has a well-defined role.
• Open-Source best practice: clear separation of core logic vs. extension points for customization.
Putting it all together
• Layout left to right or top to bottom: Application → Gem internals → AWS SDK → RDS.