LazyMagic

Service Project Documentation

Overview

The Service project is the backend foundation of the MagicPets multi-tenant SaaS platform, built as a serverless microservices architecture on AWS. Using the LazyMagic framework, it implements an OpenAPI-first development approach where all APIs are defined in YAML specifications and code is generated automatically. The Service provides four distinct APIs (Admin, Store, Consumer, Public) through AWS Lambda functions and generates strongly-typed client SDKs consumed by the frontend applications.

Project Structure

Service/
├── Schemas/                # Domain data models and repositories
│   ├── AdminSchema/        # Administrative entities
│   ├── ConsumerSchema/     # Consumer-specific entities  
│   ├── SharedSchema/       # Core business entities
│   ├── StoreSchema/        # Store management entities
│   └── PublicSchema/       # Public/unauthenticated entities
├── Modules/                # Business logic implementations
│   ├── AdminModule/        # Administrative operations
│   ├── StoreModule/        # Store management operations
│   ├── ConsumerModule/     # Consumer-facing operations
│   └── PublicModule/       # Public/unauthenticated operations
├── Containers/             # Lambda function containers
│   ├── AdminLambda/        # Admin + Store + Consumer + Public APIs
│   ├── StoreLambda/        # Store + Consumer + Public APIs
│   ├── ConsumerLambda/     # Consumer + Public APIs
│   └── PublicLambda/       # Public API only
├── ClientSDKs/             # Generated client libraries
│   ├── AdminApi/           # Full-access admin client
│   ├── StoreApi/           # Store operations client
│   ├── ConsumerApi/        # Consumer operations client
│   ├── PublicApi/          # Public access client
│   └── *ModuleClientInterface/ # Module-specific interfaces
├── AWSTemplates/           # Infrastructure as Code
├── LocalWebService/        # Local development server
├── ProjectTemplates/       # Code generation templates
└── openapi.*.yaml         # API specifications

Architecture

Serverless AWS Architecture

  • AWS Lambda: Serverless compute for each container
  • API Gateway: HTTP APIs with Cognito authorization
  • DynamoDB: NoSQL database with auto-scaling
  • Cognito: Dual authentication systems (TenantAuth + ConsumerAuth)
  • CloudFront: Content delivery network
  • S3: Static asset storage
  • SAM: Infrastructure as Code deployment

OpenAPI-First Development

  1. Define: APIs specified in OpenAPI YAML files
  2. Generate: LazyMagic generates DTOs, controllers, and repositories
  3. Implement: Custom business logic in partial classes
  4. Deploy: Automated AWS infrastructure provisioning
  5. Consume: Generated client SDKs for frontend applications

Multi-Tenant Design

  • Tenant Isolation: Data segregation by tenant ID
  • Subtenant Support: Hierarchical tenant organization
  • Authentication Isolation: Separate Cognito pools for different user types
  • Resource Isolation: Per-tenant AWS resource allocation

Schema Projects

AdminSchema

Purpose: Administrative entities for system management.

Key Models:

  • TenantUser: Administrative users with role-based permissions
  • Subtenant: Hierarchical tenant organization
  • TenantUserStatus: User lifecycle state management

Generated Components:

  • DTOs with FluentValidation rules
  • Models for client-side consumption
  • DynamoDB repository implementations
  • Service registration for dependency injection

ConsumerSchema

Purpose: Consumer-specific entities and preferences.

Key Models:

  • Preferences: User preferences including locale and theme settings
  • Consumer profile and personalization data

SharedSchema

Purpose: Core business entities shared across all modules.

Key Models:

  • Pet: Central pet entity with comprehensive attributes
  • Category: Hierarchical pet categorization
  • Tag: Flexible tagging system for pets
  • PetStatus: Pet availability and lifecycle states

Repository Pattern:

public partial interface IPetRepo : IDocumentRepo<Pet> 
{
    // Auto-generated CRUD operations
    // Custom query methods can be added
}

public partial class PetRepo : DYDBRepository<Pet>, IPetRepo
{
    // DynamoDB-specific implementation
    // Tenant-aware data access
}

StoreSchema

Purpose: Store management and operations.

Key Models:

  • Order: Order management and processing
  • Store-specific inventory and operations data

PublicSchema

Purpose: Public/unauthenticated access entities.

Key Models:

  • Fingerprint: Browser fingerprinting for analytics
  • Bada: Public data entities

Module Architecture

Module Hierarchy and Access Levels

┌─────────────┬─────────────┬─────────────┬─────────────┐
│ AdminModule │ StoreModule │ ConsumerMod │ PublicModule│
├─────────────┼─────────────┼─────────────┼─────────────┤
│             │             │             │             │
│ AdminLambda │ StoreLambda │ ConsumerLam │ PublicLambda│
│   (All)     │  (S+C+P)    │   (C+P)     │    (P)      │
└─────────────┴─────────────┴─────────────┴─────────────┘

AdminModule

Purpose: System administration and tenant management.

Key Classes:

  • AdminModuleController.cs: Custom business logic implementation
  • AdminModuleControllerBase.g.cs: Generated from OpenAPI specification
  • IAdminModuleController.g.cs: Generated interface
  • AdminModuleAuthorization.cs: TenantAuth authentication logic
  • AdminModuleRegistrations.g.cs: Dependency injection setup

Operations:

  • Tenant user CRUD operations
  • Subtenant management
  • System configuration
  • Administrative reporting

StoreModule

Purpose: Store operations and inventory management.

Key Classes:

  • StoreModuleController.cs: Store-specific business logic
  • StoreModuleAuthorization.cs: Store employee authentication
  • Generated base classes and interfaces

Operations:

  • Pet inventory management
  • Store-specific operations
  • Employee workflow support
  • Order processing

ConsumerModule

Purpose: Consumer-facing operations and personalization.

Key Classes:

  • ConsumerModuleController.g.cs: Generated consumer operations
  • ConsumerModuleAuthorization.g.cs: ConsumerAuth authentication
  • Generated interfaces and registrations

Operations:

  • Consumer preferences management
  • Pet browsing and discovery
  • User profile operations
  • Personalization features

PublicModule

Purpose: Unauthenticated public access operations.

Key Classes:

  • PublicModuleController.cs: Public API implementation
  • PublicModuleAuthorization.cs: No authentication required
  • Generated base classes and interfaces

Operations:

  • Public pet information
  • Anonymous browsing
  • Fingerprinting and analytics
  • Public content delivery

Container Architecture

Lambda Container Design

Each container hosts a specific combination of modules based on access requirements:

AdminLambda

Access Level: Full system access Hosted Modules: Public + Consumer + Store + Admin Authentication: TenantAuth (administrative users) Use Cases: System administration, tenant management, full backend access

StoreLambda

Access Level: Store operations Hosted Modules: Public + Consumer + Store Authentication: TenantAuth (store employees) Use Cases: Store management, inventory operations, customer service

ConsumerLambda

Access Level: Consumer operations Hosted Modules: Public + Consumer Authentication: ConsumerAuth (end consumers) Use Cases: Consumer app backend, personalization, pet browsing

PublicLambda

Access Level: Public only Hosted Modules: Public Authentication: None required Use Cases: Anonymous access, public content, SEO

Container Implementation

Key Generated Files:

  • LambdaEntryPoint.g.cs: AWS Lambda entry point with middleware setup
  • LocalEntryPoint.g.cs: Local development ASP.NET Core entry point
  • Startup.g.cs: Service configuration and middleware pipeline
  • ConfigureSvcs.g.cs: Dependency injection container setup

Features:

  • Cognito JWT token processing
  • Multi-tenant request context
  • Error handling and logging
  • Performance monitoring

Client SDK Generation

SDK Architecture

Generated client SDKs provide strongly-typed access to backend APIs:

API Hierarchy

// AdminApi - Full access to all modules
public partial interface IAdminApi : 
    IPublicModuleClient, 
    IConsumerModuleClient, 
    IStoreModuleClient, 
    IAdminModuleClient
{
    // Generated HTTP client methods
    // Full API surface area
}

// StoreApi - Store + Consumer + Public access
public partial interface IStoreApi : 
    IPublicModuleClient, 
    IConsumerModuleClient, 
    IStoreModuleClient
{
    // Store-level operations
}

// ConsumerApi - Consumer + Public access
public partial interface IConsumerApi : 
    IPublicModuleClient, 
    IConsumerModuleClient
{
    // Consumer-level operations
}

// PublicApi - Public access only
public partial interface IPublicApi : 
    IPublicModuleClient
{
    // Unauthenticated operations
}

Module Client Interfaces

Purpose: Interface segregation for specific module operations.

Examples:

  • IAdminModuleClient: Administrative operations only
  • IStoreModuleClient: Store operations only
  • IConsumerModuleClient: Consumer operations only
  • IPublicModuleClient: Public operations only

Benefits:

  • Dependency injection with specific access levels
  • Testability with interface mocking
  • Clear separation of concerns
  • Type-safe API consumption

Local Development

LocalWebService

Purpose: Local development server that emulates AWS API Gateway.

Key Features:

  • Multi-API Hosting: All four APIs on https://localhost:5001
  • Swagger Documentation: Interactive API documentation at /swagger
  • AWS Integration: Uses local AWS credentials for DynamoDB access
  • Hot Reload: Supports development-time code changes
  • Request Logging: Comprehensive request/response logging

Configuration:

// launchSettings.json
{
  "https": {
    "commandName": "Project",
    "launchBrowser": true,
    "launchUrl": "swagger",
    "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Development",
      "AWS_PROFILE": "default",
      "AWS_REGION": "us-east-1"
    },
    "applicationUrl": "https://localhost:5001"
  }
}

Service Registration:

  • Automatic AWS credential detection
  • STS caller identity verification
  • Multi-region support
  • Development vs. production environment switching

Authentication Systems

Dual Authentication Architecture

The Service implements two separate Cognito-based authentication systems:

TenantAuth

Purpose: Administrative and store employee authentication User Pool: Tenant-specific Cognito User Pool Consumers: AdminApi, StoreApi Features:

  • Tenant-scoped user management
  • Role-based access control
  • Administrative permissions
  • Store employee access

ConsumerAuth

Purpose: End consumer authentication User Pool: Separate Cognito User Pool for consumers Consumers: ConsumerApi Features:

  • Self-service registration
  • Consumer-specific permissions
  • Personal data management
  • Isolated from business operations

Authentication Flow

  1. JWT Token Validation: API Gateway validates Cognito tokens
  2. Header Extraction: Lambda middleware extracts user claims
  3. CallerInfo Generation: User context for data access
  4. Repository Integration: Tenant-aware data operations
public class CallerInfo
{
    public string UserId { get; set; }
    public string TenantId { get; set; }
    public string SubtenantId { get; set; }
    public Dictionary<string, string> Claims { get; set; }
}

Code Generation Framework

LazyMagic MDD Tool

Purpose: Model-Driven Development with OpenAPI specifications.

Generation Pipeline:

  1. OpenAPI Specs → Parse YAML definitions
  2. Schema Generation → DTOs, Models, Validators, Repositories
  3. Controller Generation → Base classes, interfaces, implementations
  4. Container Generation → Lambda entry points, startup configuration
  5. SDK Generation → Client libraries with full type safety
  6. Infrastructure Generation → AWS SAM templates

.NET Source Generators

Integrated Analyzers:

  • LazyMagic.LzItemViewModelGenerator: Generates ViewModels from DTOs
  • LazyMagic.DIHelper: Auto-registers services with dependency injection
  • LazyMagic.FactoryGenerator: Creates factory classes for object creation

Template System

ProjectTemplates: Reusable templates for new components

  • ApiLambda: Template for new Lambda containers
  • Controller: Template for new module controllers
  • Schema: Template for new data schemas
  • ClientSDK: Template for new API clients

Benefits:

  • Consistency: All generated code follows same patterns
  • Type Safety: Strongly-typed throughout the entire stack
  • Rapid Development: New APIs can be created in minutes
  • Maintainability: Generated code reduces manual maintenance

AWS Deployment

Infrastructure as Code

SAM Templates: Complete AWS infrastructure defined as code

Generated Infrastructure:

  • Lambda Functions: One per container with appropriate permissions
  • API Gateways: HTTP APIs with Cognito authorizers
  • DynamoDB Tables: Auto-generated from schema definitions
  • IAM Roles: Least-privilege access for each Lambda
  • Cognito User Pools: Separate pools for tenants and consumers
  • CloudFront Distributions: CDN for frontend applications
  • S3 Buckets: Static assets and deployment artifacts

Multi-Environment Support

  • Parameter-driven: Environment-specific configurations
  • Stack isolation: Separate AWS stacks per environment
  • Resource naming: Consistent naming with environment suffixes
  • Configuration management: Environment-specific settings

Data Flow

Request Processing Flow

Client App → Client SDK → API Gateway → Lambda Container → Module → Repository → DynamoDB
    ↑                                                                                    ↓
JSON/HTTP ← Generated Client ← HTTP Response ← Lambda Response ← Business Logic ← Data Access

Code Generation Flow

OpenAPI Specs → LazyMagic Tool → Generated Code → Manual Implementation → Deployment
     ↓               ↓              ↓                    ↓                  ↓
  API Def → Schema/Controller → DTOs/Models/Repos → Custom Logic → AWS Resources

Authentication Flow

Client Login → Cognito → JWT Token → API Gateway → Lambda Middleware → CallerInfo → Repository
      ↓                                                     ↓                        ↓
  User Creds → Auth Pool → Claims/Token → Validation → User Context → Tenant Data

Integration with Frontend Applications

AdminApp Integration

  • Consumes: AdminApi (full access)
  • Authentication: TenantAuth
  • Operations: User management, tenant administration, system configuration

StoreApp Integration

  • Consumes: StoreApi (store + consumer + public)
  • Authentication: TenantAuth
  • Operations: Pet management, store operations, inventory

ConsumerApp Integration

  • Consumes: ConsumerApi + PublicApi
  • Authentication: ConsumerAuth
  • Operations: Pet browsing, preferences, consumer features

BaseAppLib Integration

  • SDK Distribution: Generated SDKs consumed as NuGet packages
  • ViewModel Generation: Automatic ViewModel generation from DTOs
  • Authentication: Unified auth patterns across all apps

Development Workflow

Building the Service

cd Service
dotnet build MagicPetsService.sln

Running Local Development

cd LocalWebService
dotnet run
# Access Swagger UI at https://localhost:5001/swagger

Deploying to AWS

cd AWSTemplates
sam build
sam deploy --guided

Generating Code

# LazyMagic tool automatically generates:
# - DTOs and Models from OpenAPI schemas
# - Controllers and repositories
# - Client SDKs
# - AWS SAM templates

Architectural Strengths

  1. OpenAPI-First: All APIs defined before implementation ensures consistency
  2. Code Generation: Massive reduction in boilerplate code
  3. Type Safety: End-to-end type safety from database to client
  4. Serverless: Auto-scaling, pay-per-use AWS infrastructure
  5. Multi-Tenant: Built-in tenant isolation and security
  6. Modular: Clean separation of concerns with module architecture
  7. Dual Auth: Separate authentication systems for different user types
  8. Local Development: Full local development experience with AWS integration
  9. Infrastructure as Code: Repeatable, version-controlled deployments
  10. SDK Generation: Strongly-typed client libraries for all APIs

The Service project represents a sophisticated, production-ready serverless backend that leverages modern cloud architecture patterns while maintaining developer productivity through extensive code generation and tooling automation.