### Start Local Development Server Source: https://github.com/archman-dev/website/blob/main/README.md Starts a local development server for the Archman website. Changes are reflected live without needing to restart the server. ```bash pnpm start ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/archman-dev/website/blob/main/README.md Installs project dependencies using the pnpm package manager. This is the first step before running any other commands. ```bash pnpm install ``` -------------------------------- ### Deploy to Vercel Source: https://github.com/archman-dev/website/blob/main/README.md Commands for deploying the Archman website to Vercel. Includes installing the Vercel CLI and performing production deployments. ```bash npm i -g vercel vercel vercel --prod ``` -------------------------------- ### Initialize SDK Client (Python, Go, Node.js) Source: https://github.com/archman-dev/website/blob/main/editing/widgets/code.mdx Demonstrates how to initialize an SDK client for an API service, specifying the base URL. Requires the respective SDK to be installed. ```python from sdk import Client client = Client(base_url='https://api.example.com') ``` ```go package main import "example.com/sdk" func main() { client := sdk.NewClient("https://api.example.com") _ = client } ``` ```javascript import { Client } from '@example/sdk' const client = new Client({ baseUrl: 'https://api.example.com' }) ``` -------------------------------- ### Procedural Flowchart Example Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/programming-paradigms/procedural-structured.mdx Illustrates a typical procedural flow for processing a payment, demonstrating sequence, selection, and process steps. ```mermaid flowchart TB S["Start"] --> V{"Validate Input?"} V -- No --> E["Fail Fast & Return Error"] V -- Yes --> P1["Transform Data"] P1 --> P2["Call External API"] P2 --> P3["Persist Result"] P3 --> D["Done"] ``` -------------------------------- ### E-Commerce Platform Entity-Relationship Diagram (Mermaid) Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/data-fundamentals/data-modeling/conceptual.mdx Illustrates the structure of a simplified e-commerce platform, defining key entities, their attributes, and relationships. This diagram serves as a practical example for conceptual modeling. ```mermaid %%{init: {"flowchart": {"useMaxWidth": false, "htmlLabels": true, "nodeSpacing": 40, "rankSpacing": 35, "padding": 8, "wrap": true}, "themeVariables": {"fontSize": "14px"}} }%% erDiagram CUSTOMER { string customer_id PK string name string email date registration_date string status } ADDRESS { string address_id PK string street string city string postal_code string country string address_type } PRODUCT { string product_id PK string name string description decimal price string category string status } ORDER { string order_id PK date order_date string status decimal total_amount string payment_status } ORDER_ITEM { string order_item_id PK int quantity decimal unit_price decimal line_total } PAYMENT { string payment_id PK decimal amount string payment_method string status date payment_date } CUSTOMER ||--o{ ADDRESS : "has" CUSTOMER ||--o{ ORDER : "places" ORDER ||--o{ ORDER_ITEM : "contains" PRODUCT ||--o{ ORDER_ITEM : "included_in" ORDER ||--|| PAYMENT : "paid_by" ``` -------------------------------- ### OOP Call Flow: Order Placement Example (Mermaid) Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/programming-paradigms/object-oriented.mdx Visualizes the call flow for placing an order, demonstrating how the OrderService delegates authorization to a gateway and handles potential errors. This highlights the interaction between objects in an OOP system. ```mermaid flowchart TB A["OrderService.place(order)"] --> B{"order.total_cents > 0?"} B --|No|--> C["Raise ValueError / error"] B --|Yes|--> D["gateway.authorize(order.total_cents)"] D --> E{"res.ok?"} E --|No|--> F["Raise payment failed error"] E --|Yes|--> G["Return PAID, auth_code"] ``` -------------------------------- ### ConfigTabs with YAML and JSON Source: https://github.com/archman-dev/website/blob/main/editing/widgets/config-tabs.mdx Displays configuration examples for a connector policy using both YAML and JSON formats. The component handles the display of different file types within tabs. ```yaml timeouts: request: 2s retries: attempts: 3 ``` ```json { "timeouts": { "request": "2s" }, "retries": { "attempts": 3 } } ``` -------------------------------- ### Mermaid Diagram: Abstraction and Encapsulation Example Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/system-thinking-basics/abstractions-and-encapsulation.mdx Visualizes a client interacting with a public API that abstracts internal components like a database, queue, and workers, demonstrating encapsulation. ```mermaid flowchart TB subgraph api["Public API (Interface)"] I[OrderService] end subgraph internals["Internals (Hidden)"] D[(DB)] Q[(Queue)] W[Worker] end C[Client] --> I I --> D I --> Q Q --> W W --> D ``` -------------------------------- ### Go Actor Example (Goroutine) Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/programming-paradigms/actor-model.mdx Implements an actor using Go's goroutines and channels. The actor processes messages from a channel, updating its state or responding to 'get' requests. It uses a WaitGroup to manage termination. ```go package main import ( "fmt" "sync" ) // An Actor is a goroutine that processes messages from a channel. type Actor struct { mailbox chan interface{} wg *sync.WaitGroup state int } func NewActor(wg *sync.WaitGroup) *Actor { return &Actor{ mailbox: make(chan interface{}, 100), // Bounded mailbox wg: wg, state: 0, } } // Run starts the actor's message processing loop. func (a *Actor) Run() { defer a.wg.Done() for msg := range a.mailbox { switch m := msg.(type) { case int: a.state += m case string: if m == "get" { fmt.Printf("State is: %d\n", a.state) } } } } // Send posts a message to the actor's mailbox. func (a *Actor) Send(msg interface{}) { a.mailbox <- msg } func main() { var wg sync.WaitGroup actor := NewActor(&wg) wg.Add(1) go actor.Run() actor.Send(1) actor.Send(1) actor.Send("get") close(actor.mailbox) // Signal actor to terminate wg.Wait() // Wait for actor to finish } ``` -------------------------------- ### Terraform AWS Instance Configuration Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/programming-paradigms/declarative-and-logic.mdx An example of Terraform HCL defining an AWS EC2 instance. This showcases how infrastructure is declared declaratively. ```hcl # Declare the desired state of the infrastructure. # Terraform's engine figures out how to create/update it. resource "aws_instance" "web" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" tags = { Name = "HelloWorld" } } ``` -------------------------------- ### Mermaid Flowchart for PSP Authorization Retries Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/what-is-software-architecture/architecture-vs-design-vs-implementation.mdx A Mermaid flowchart visualizing the retry logic for PSP authorization. It details the steps from starting an attempt, making the POST call, handling success or failure, and implementing backoff with jitter for subsequent attempts. ```mermaid flowchart TB S["Start"] --> A["Attempt 1..N"] A --> T["POST authorize()"] T -->|Success| R["Return result"] T -->|Error/Timeout| C{"More attempts left?"} C -- Yes --> B["Backoff with jitter"] B --> A C -- No --> E["Raise/propagate error"] ``` -------------------------------- ### Node.js gRPC Client for Orders Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/system-thinking-basics/interfaces-and-contracts.mdx A Node.js client example for interacting with the Orders gRPC service. It utilizes `@grpc/grpc-js` and `@grpc/proto-loader` to load the protobuf definitions, create a client, and make a `CreateOrder` call, handling potential errors. ```javascript const grpc = require('@grpc/grpc-js'); const protoLoader = require('@grpc/proto-loader'); const { v4: uuidv4 } = require('uuid'); const PROTO_PATH = './orders.proto'; const packageDefinition = protoLoader.loadSync(PROTO_PATH); const orders_proto = grpc.loadPackageDefinition(packageDefinition).orders.v1; function main() { const client = new orders_proto.Orders('localhost:50051', grpc.credentials.createInsecure()); const idempotencyKey = uuidv4(); client.createOrder({ idempotency_key: idempotencyKey, order_id: "ord-123", item_ids: ["item-abc", "item-def"] }, (err, response) => { if (err) { console.error('Error: ', err); return; } console.log('Order created with ETag:', response.etag); }); } main(); ``` -------------------------------- ### Mermaid Diagram: API Gateway Abstraction Example Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/system-thinking-basics/abstractions-and-encapsulation.mdx Illustrates how an API Gateway acts as an abstraction layer, providing a single interface for clients to interact with multiple backend microservices while encapsulating internal complexities. ```mermaid flowchart TB subgraph client_domain["Client Domain"] client["Mobile/Web Client"] end subgraph system_boundary["System Boundary"] gateway["API Gateway"] end subgraph backend_services["Backend Services (Internal)"] service_a["Orders Service"] service_b["Users Service"] service_c["Payments Service"] end client --> gateway gateway --> service_a gateway --> service_b gateway --> service_c ``` -------------------------------- ### Make Simple API Request (Python, Go, Node.js) Source: https://github.com/archman-dev/website/blob/main/editing/widgets/code.mdx Shows how to make a simple GET request to an API endpoint ('https://api.example.com/health') and print the response status code. Works with standard HTTP libraries/fetch API. ```python import requests resp = requests.get('https://api.example.com/health') print(resp.status_code) ``` ```go package main import ( "fmt" "net/http" ) func main() { resp, err := http.Get("https://api.example.com/health") if err != nil { panic(err) } fmt.Println(resp.StatusCode) } ``` ```javascript async function main() { const resp = await fetch('https://api.example.com/health') console.log(resp.status) } main() ``` -------------------------------- ### Mermaid Diagram: Bounded Contexts and ACL Example Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/system-thinking-basics/abstractions-and-encapsulation.mdx Depicts two Bounded Contexts (Sales and Shipping) interacting through public APIs and an Anti-Corruption Layer (ACL), showcasing encapsulation and abstraction. ```mermaid flowchart TB subgraph sales_ctx["Sales Context"] sales_api["Public API"] sales_logic["Business Logic"] sales_db[("Sales DB")] sales_api --> sales_logic --> sales_db end subgraph shipping_ctx["Shipping Context"] shipping_svc["Shipping Service"] acl["Anti-Corruption Layer"] shipping_logic["Business Logic"] shipping_db[("Shipping DB")] shipping_svc --> acl --> shipping_logic --> shipping_db end sales_api -- "OrderPlaced Event" --> shipping_svc ``` -------------------------------- ### OOP Design: Dependency Inversion Example (Mermaid) Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/programming-paradigms/object-oriented.mdx Illustrates dependency inversion in an order service using a PaymentGateway interface. This pattern promotes loose coupling by having the service depend on an abstraction rather than a concrete implementation. ```mermaid classDiagram class PaymentGateway { <> +authorize(amount: Money): AuthResult } class StripeGateway { +authorize(amount: Money): AuthResult } class OrderService { -gateway: PaymentGateway +place(order: Order): Receipt } PaymentGateway <|.. StripeGateway OrderService --> PaymentGateway ``` -------------------------------- ### Conceptual Windowed Sum in Go Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/programming-paradigms/dataflow-stream-processing.mdx Demonstrates a conceptual Go implementation of a windowed sum aggregation. It processes incoming events and groups them into time-based buckets for summation. This example uses channels for event input and string formatting for bucket keys. ```go package main import "fmt" type Event struct { Timestamp int64 Key string Value int } // WindowedSum aggregates events into time-based windows. func WindowedSum(events <-chan Event, windowSeconds int64) map[string]int { buckets := make(map[string]int) for e := range events { bucketTimestamp := (e.Timestamp / windowSeconds) * windowSeconds key := fmt.Sprintf("%s:%d", e.Key, bucketTimestamp) buckets[key] += e.Value } return buckets } func main() { // In a real app, events would come from a source like Kafka. eventChan := make(chan Event, 2) eventChan <- Event{1672531205, "A", 10} eventChan <- Event{1672531215, "A", 5} close(eventChan) results := WindowedSum(eventChan, 300) fmt.Println(results) // map[A:1672531200:15] } ``` -------------------------------- ### Conceptual Data Modeling Process Flow Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/data-fundamentals/data-modeling/conceptual.mdx Visualizes the steps involved in conceptual data modeling, from gathering business requirements and domain knowledge to identifying entities, defining attributes, modeling relationships, capturing business rules, and validating the conceptual model with stakeholders. It also shows the transition to a logical model. ```mermaid %%{init: {"flowchart": {"useMaxWidth": false, "htmlLabels": true, "nodeSpacing": 40, "rankSpacing": 35, "padding": 8, "wrap": true}, "themeVariables": {"fontSize": "14px"}} }%% flowchart TB Start["Business Requirements
& Domain Knowledge"] --> Gather["Gather Information
• Stakeholder interviews
• Business documents
• Process analysis"] Gather --> Identify["Identify Entities
• People, places, things
• Business concepts
• Key objects"] Identify --> Attributes["Define Attributes
• Entity properties
• Business characteristics
• Descriptive data"] Attributes --> Relationships["Model Relationships
• Entity connections
• Business associations
• Cardinalities"] Relationships --> Rules["Capture Business Rules
• Constraints
• Validation rules
• Business logic"] Rules --> Validate["Validate with Stakeholders
• Review accuracy
• Confirm completeness
• Refine model"] Validate -->|"Needs changes"| Gather Validate -->|"Approved"| Complete["Conceptual Model
Complete"] Complete --> Next["Transition to
Logical Model"] ``` -------------------------------- ### Programming Paradigm Decision Aid (Mermaid) Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/programming-paradigms/index.mdx This Mermaid diagram visualizes a decision-making process for selecting a dominant programming paradigm for a software component. It guides users through primary drivers like data mutation, domain behavior, concurrency safety, asynchronous events, rules, and isolation to recommend suitable paradigms such as Procedural, Object-Oriented, Functional, Event-Driven/Reactive, Declarative/Logic, or Actor Model. ```mermaid flowchart TB Start["Choose dominant paradigm for a component"] C1{"Primary driver?"} P1["Data mutation and I/O orchestration"] P2["Rich domain behavior and invariants"] P3["Deterministic transforms / concurrency safety"] P4["Event streams and async boundaries"] P5["Rules / queries over facts"] P6["Message isolation and supervision"] Start --> C1 C1 -- "Throughput/IO" --> P1 C1 -- "Encapsulation" --> P2 C1 -- "Correctness" --> P3 C1 -- "Asynchrony" --> P4 C1 -- "Declarative" --> P5 C1 -- "Isolation" --> P6 P1 --> R1["Prefer Procedural/Structured"] P2 --> R2["Prefer Object‑Oriented"] P3 --> R3["Prefer Functional"] P4 --> R4["Prefer Event‑Driven/Reactive"] P5 --> R5["Prefer Declarative/Logic"] P6 --> R6["Prefer Actor Model"] R1 --> Note["Mix paradigms at boundaries; keep APIs small"] R2 --> Note R3 --> Note R4 --> Note R5 --> Note R6 --> Note ``` -------------------------------- ### Mermaid: E-commerce Logical Model Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/data-fundamentals/data-modeling/logical.mdx Visualizes a logical database schema for an e-commerce platform using Mermaid syntax. This diagram illustrates normalized tables and their relationships, including CUSTOMERS, ADDRESSES, CATEGORIES, PRODUCTS, ORDERS, ORDER_ITEMS, and PAYMENTS. It serves as a practical example of a well-structured database design. ```mermaid %%{init: {"flowchart": {"useMaxWidth": false, "htmlLabels": true, "nodeSpacing": 40, "rankSpacing": 35, "padding": 8, "wrap": true}, "themeVariables": {"fontSize": "14px"}} }%% erDiagram CUSTOMERS { int customer_id PK varchar email UK varchar first_name varchar last_name date registration_date varchar status timestamp created_at timestamp updated_at } ADDRESSES { int address_id PK int customer_id FK varchar address_type varchar street varchar city varchar state varchar postal_code varchar country boolean is_default timestamp created_at } CATEGORIES { int category_id PK varchar name UK varchar description int parent_category_id FK boolean is_active } PRODUCTS { int product_id PK varchar sku UK varchar name text description decimal price int category_id FK varchar status int stock_quantity timestamp created_at timestamp updated_at } ORDERS { int order_id PK int customer_id FK int shipping_address_id FK int billing_address_id FK date order_date varchar status decimal subtotal decimal tax_amount decimal shipping_amount decimal total_amount timestamp created_at timestamp updated_at } ORDER_ITEMS { int order_item_id PK int order_id FK int product_id FK int quantity decimal unit_price decimal line_total } PAYMENTS { int payment_id PK int order_id FK decimal amount varchar payment_method varchar status varchar transaction_id date payment_date timestamp created_at } CUSTOMERS ||--o{ ADDRESSES : "has" CUSTOMERS ||--o{ ORDERS : "places" CATEGORIES ||--o{ CATEGORIES : "parent_of" CATEGORIES ||--o{ PRODUCTS : "contains" ORDERS ||--o{ ORDER_ITEMS : "contains" PRODUCTS ||--o{ ORDER_ITEMS : "included_in" ORDERS ||--o{ PAYMENTS : "paid_by" ADDRESSES ||--o{ ORDERS : "shipping_address" ADDRESSES ||--o{ ORDERS : "billing_address" ``` -------------------------------- ### Node.js AOP: Proxy for Performance Measurement Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/programming-paradigms/aspect-oriented.mdx This Node.js example utilizes the `Proxy` object to implement an aspect that measures the performance of a function. The `performanceAspect` intercepts function calls, starts a timer, executes the original function, and ends the timer. ```javascript const performanceAspect = { apply(target, thisArg, args) { console.time(target.name); const result = Reflect.apply(target, thisArg, args); console.timeEnd(target.name); return result; } }; function someBusinessLogic(a, b) { // complex calculation return a + b; } // Weave the aspect using a Proxy const proxiedLogic = new Proxy(someBusinessLogic, performanceAspect); proxiedLogic(10, 20); // Logs execution time to the console ``` -------------------------------- ### Docker Compose Configuration for Services Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/system-thinking-basics/components-connectors-configurations.mdx A minimal docker-compose.yml file to set up a distributed system including a product service, order service, PostgreSQL database, Zookeeper, and Kafka. It defines service images, environment variables, port mappings, and dependencies. ```yaml version: "3.9" services: product: image: ghcr.io/example/product-service:latest environment: - GRPC_PORT=50051 ports: - "50051:50051" order: image: ghcr.io/example/order-service:latest depends_on: - product - postgres - kafka environment: - PRODUCT_GRPC_ADDR=product:50051 - DATABASE_URL=postgres://postgres:postgres@postgres:5432/orders?sslmode=disable - KAFKA_BROKERS=kafka:9092 ports: - "8080:8080" postgres: image: postgres:15 environment: - POSTGRES_PASSWORD=postgres - POSTGRES_DB=orders ports: - "5432:5432" zookeeper: image: confluentinc/cp-zookeeper:7.6.1 environment: ZOOKEEPER_CLIENT_PORT: 2181 kafka: image: confluentinc/cp-kafka:7.6.1 depends_on: - zookeeper environment: KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092 KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 ports: - "9092:9092" ``` -------------------------------- ### Conceptual Modeling Decision Flow (Mermaid) Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/data-fundamentals/data-modeling/conceptual.mdx Visualizes the decision process for creating conceptual models based on project scope and stakeholder needs. It guides users through selecting the appropriate model focus (business, technical, or balanced) and validation steps. ```mermaid %%{init: {"flowchart": {"useMaxWidth": false, "htmlLabels": true, "nodeSpacing": 40, "rankSpacing": 35, "padding": 8, "wrap": true}, "themeVariables": {"fontSize": "14px"}} }%% flowchart TB Start["Starting Conceptual Modeling"] --> Scope{"What's your scope?" Scope -->||"New system"| New["Greenfield Project
• Start from scratch
• Gather all requirements
• Build comprehensive model"] Scope -->||"Existing system"| Existing["Legacy System
• Document current state
• Identify gaps
• Plan improvements"] Scope -->||"Integration"| Integration["System Integration
• Map shared concepts
• Identify conflicts
• Design common model"] New --> Stakeholders{"Who are your
stakeholders?" Existing --> Stakeholders Integration --> Stakeholders Stakeholders -->||"Business users"| Business["Business-Focused Model
• Use domain language
• Focus on processes
• Validate with users"] Stakeholders -->||"Technical teams"| Technical["Technical-Focused Model
• Include implementation hints
• Consider constraints
• Plan for logical model"] Stakeholders -->||"Mixed audience"| Mixed["Balanced Model
• Clear business concepts
• Technical considerations
• Multiple validation cycles"] Business --> Validate["Validate & Refine"] Technical --> Validate Mixed --> Validate Validate --> Complete["Conceptual Model
Ready for Logical Design"] ``` -------------------------------- ### Mermaid Diagram: Client-Server Configuration Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/system-thinking-basics/components-connectors-configurations.mdx Visualizes a basic client-server architecture using Mermaid syntax. It shows a 'Client' component communicating with a 'Server' component via a 'REST API' connector. ```mermaid flowchart TB subgraph sys["System Configuration"] Client["Client"] -->|REST| Server["Server"] end classDef component fill:#f9f,stroke:#333,stroke-width:2px,color:#333; class Client,Server component; ``` -------------------------------- ### Deploy to GitHub Pages Source: https://github.com/archman-dev/website/blob/main/README.md Commands for deploying the Archman website to GitHub Pages. Supports deployment using SSH or without SSH, pushing to the 'gh-pages' branch. ```bash USE_SSH=true pnpm deploy ``` ```bash GIT_USER= pnpm deploy ``` -------------------------------- ### Mermaid Diagram: E-commerce Order Processing Flow Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/system-thinking-basics/components-connectors-configurations.mdx Illustrates a more complex e-commerce order processing flow using Mermaid syntax. It depicts interactions between an 'OrderService', 'ProductService', 'PostgreSQL DB', and a 'Kafka Topic'. ```mermaid flowchart TB A["Client"] -->|"HTTP POST /orders"| B["OrderService"] B -->|"gRPC GetProduct"| C["ProductService"] B -->|"SQL INSERT"| D["PostgreSQL DB"] B -->|"Publish Event"| E["Kafka Topic: order-events"] classDef service fill:#D6EAF8,stroke:#2E86C1,stroke-width:2px,color:#000; classDef db fill:#E8DAEF,stroke:#8E44AD,stroke-width:2px,color:#000; classDef topic fill:#D5F5E3,stroke:#28B463,stroke-width:2px,color:#000; class B,C service; class D db; class E topic; ``` -------------------------------- ### Create products table with full-text search and indexes Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/data-fundamentals/data-modeling/physical.mdx Establishes the 'products' table using the InnoDB engine, incorporating a primary key, unique SKU constraint, foreign key to categories, and check constraints for price and stock. It includes standard indexes for category, status, price, stock quantity, and creation date, along with full-text indexes on name and description for enhanced search capabilities. A composite index is also provided for filtering by category and status. ```sql -- Products table with full-text search capabilities CREATE TABLE products ( product_id INT AUTO_INCREMENT PRIMARY KEY, sku VARCHAR(100) NOT NULL, name VARCHAR(255) NOT NULL, description TEXT, price DECIMAL(10,2) NOT NULL, category_id INT NOT NULL, status ENUM('active', 'inactive', 'discontinued') NOT NULL DEFAULT 'active', stock_quantity INT NOT NULL DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Constraints UNIQUE KEY uk_products_sku (sku), FOREIGN KEY (category_id) REFERENCES categories(category_id) ON DELETE RESTRICT, CONSTRAINT chk_price_positive CHECK (price >= 0), CONSTRAINT chk_stock_non_negative CHECK (stock_quantity >= 0) ) ENGINE=InnoDB; -- Standard indexes for common queries CREATE INDEX idx_products_category_id ON products(category_id); CREATE INDEX idx_products_status ON products(status); CREATE INDEX idx_products_price ON products(price); CREATE INDEX idx_products_stock_quantity ON products(stock_quantity); CREATE INDEX idx_products_created_at ON products(created_at); -- Full-text indexes for search functionality CREATE FULLTEXT INDEX ft_products_name ON products(name); CREATE FULLTEXT INDEX ft_products_description ON products(description); CREATE FULLTEXT INDEX ft_products_name_description ON products(name, description); -- Composite index for product filtering CREATE INDEX idx_products_category_status ON products(category_id, status); ``` -------------------------------- ### Connector Selection Decision Flow Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/system-thinking-basics/components-connectors-configurations.mdx A Mermaid diagram illustrating a decision flow for selecting the appropriate communication connector based on factors like synchronous/asynchronous communication, internal/external context, and specific guarantees like point-to-point or pub/sub. ```mermaid flowchart TB A[Start] --> B{Sync or Async Communication?}; B -- Sync --> C{Internal or External?}; B -- Async --> G{Point-to-Point or Pub/Sub?}; C -- Internal --> D{Performance critical?}; C -- External --> E["Use HTTP/REST (or GraphQL)"]; D -- Yes --> F["Use gRPC (or other binary RPC)"]; D -- No --> E; G -- "Point-to-Point" --> H["Use a Message Queue (e.g., RabbitMQ, SQS)"]; G -- "Pub/Sub" --> I{Real-time or Event Log?}; I -- "Real-time" --> J["Use a Message Broker (e.g., RabbitMQ, NATS)"]; I -- "Event Log" --> K["Use a Streaming Platform (e.g., Kafka, Pulsar)"] ``` -------------------------------- ### Build Static Website Content Source: https://github.com/archman-dev/website/blob/main/README.md Generates the static content for the Archman website into the 'build' directory. This content can then be hosted on any static hosting service. ```bash pnpm build ``` -------------------------------- ### Mermaid Data Modeling Levels Diagram Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/data-fundamentals/data-modeling/index.mdx Visualizes the progression of data modeling from business requirements to physical implementation, illustrating the conceptual, logical, and physical models with their key characteristics and examples. ```mermaid %%{init: {"flowchart": {"useMaxWidth": false, "htmlLabels": true, "nodeSpacing": 40, "rankSpacing": 35, "padding": 8, "wrap": true}, "themeVariables": {"fontSize": "14px"}} }%% flowchart TB Business["Business Requirements
& Domain Knowledge"] --> Conceptual["Conceptual Model
(What exists?)"] Conceptual --> Logical["Logical Model
(How to structure?)"] Logical --> Physical["Physical Model
(Where to implement?)"] Conceptual -.->|"Entities &
Relationships"| ConceptualDetail["• Customer
• Order
• Product
• Relationships"] Logical -.->|"Tables &
Constraints"| LogicalDetail["• customers table
• orders table
• products table
• Foreign keys"] Physical -.->|"Storage &
Performance"| PhysicalDetail["• Indexes
• Partitions
• Storage engines
• Hardware"] ``` -------------------------------- ### System Thinking Basics Overview (Mermaid) Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/system-thinking-basics/index.mdx A mind map illustrating the fundamental concepts of systems thinking, including components, connectors, configurations, interfaces, abstractions, and system properties. ```mermaid mindmap root((System Thinking Basics)) Components Deployable units Single responsibility Clear boundaries Independent evolution Connectors Synchronous Asynchronous Protocols Reliability patterns Configurations Topology Environment mapping Runtime behavior Failure modes Interfaces & Contracts API design Versioning strategy Compatibility rules Error handling Abstractions & Encapsulation Information hiding Stable boundaries Implementation isolation Complexity management System Properties Emergent behavior Change propagation Risk accumulation Evolution patterns ``` -------------------------------- ### ConfigTabs without Title (YAML) Source: https://github.com/archman-dev/website/blob/main/editing/widgets/config-tabs.mdx Shows the ConfigTabs component used without a specific title, displaying a simple YAML configuration. This example focuses on the core functionality of presenting code snippets. ```yaml key: value list: - a - b ``` -------------------------------- ### Go Order Service with Payment Gateway Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/programming-paradigms/object-oriented.mdx Provides a Go implementation of an order service utilizing an interface for PaymentGateway. It demonstrates dependency injection and the structure for placing orders and authorizing payments. ```go package orders import "fmt" type PaymentGateway interface { Authorize(amountCents int) (authCode string, ok bool) } type Order struct { UserID string TotalCents int } type Service struct { gateway PaymentGateway } func NewService(g PaymentGateway) *Service { return &Service{gateway: g} } func (s *Service) Place(o Order) (string, error) { if o.TotalCents <= 0 { return "", fmt.Errorf("invalid total") } code, ok := s.gateway.Authorize(o.TotalCents) if !ok { return "", fmt.Errorf("payment failed") } return code, nil } ``` -------------------------------- ### Checklist Component Rich Content (React) Source: https://github.com/archman-dev/website/blob/main/editing/widgets/checklist.mdx Demonstrates incorporating rich content, including HTML tags and code elements, within the items of the Checklist component. This example shows API review criteria. ```jsx import Checklist from "@site/src/components/Checklist"; Naming follows REST conventions , { label: <>Error model, items: [ <> Consistent problem+json , <> Documented retryable codes , ], }, ]} /> ``` -------------------------------- ### Declarative System Workflow (Mermaid) Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/programming-paradigms/declarative-and-logic.mdx Visualizes the step-by-step sequence of how a declarative system operates, from user submission of the desired state to the engine's planning, execution, and the system's reporting of the actual state. It highlights the ongoing reconciliation loop for drift detection. ```mermaid sequenceDiagram participant User participant Engine participant System User->>Engine: Submit desired state Engine->>System: Plan & apply changes System-->>Engine: Report actual state Engine-->>User: Show plan/results Note over Engine,System: Loop: detect drift, re-apply as needed ``` -------------------------------- ### Conceptual Windowed Aggregation (Python) Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/programming-paradigms/dataflow-stream-processing.mdx Demonstrates a conceptual windowed aggregation in Python. It processes events with timestamps and keys, summing values within defined time windows. This example is illustrative and not production-ready. ```python # Conceptual example of windowed aggregation from collections import defaultdict def windowed_sum(events, window_seconds): """ Aggregates event values into time-based windows. `events` is an iterator of dictionaries like {'ts': 1672531205, 'key': 'A', 'value': 10} """ buckets = defaultdict(int) for event in events: # Integer division creates discrete time buckets bucket_timestamp = (event["ts"] // window_seconds) * window_seconds key = (event["key"], bucket_timestamp) buckets[key] += event["value"] return buckets # Example usage: # stream = get_event_stream() ``` -------------------------------- ### Python PSP Client with Retry Logic Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/what-is-software-architecture/architecture-vs-design-vs-implementation.mdx Python code demonstrating a client function to call an external Payment Service Provider (PSP). It includes a loop for retries with exponential backoff and jitter, handling potential exceptions and HTTP errors. ```python import requests, time, random def call_psp(payload, retries=3): for attempt in range(1, retries + 1): try: resp = requests.post('https://psp.example/authorize', json=payload, timeout=2) resp.raise_for_status() return resp.json() except Exception as e: if attempt == retries: raise time.sleep(min(0.25 * (2 ** attempt) + random.uniform(0, 0.1), 2.0)) ``` -------------------------------- ### Physical Data Modeling Process Flow Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/data-fundamentals/data-modeling/physical.mdx Visualizes the iterative process of physical data modeling, starting from a logical model, analyzing requirements, optimizing the design, implementing the database, and finally monitoring and tuning. ```Mermaid %%{init: {"flowchart": {"useMaxWidth": false, "htmlLabels": true, "nodeSpacing": 40, "rankSpacing": 35, "padding": 8, "wrap": true}, "themeVariables": {"fontSize": "14px"}} }%% flowchart TB Logical["Logical Model
• Tables & Columns
• Relationships
• Constraints"] --> Analyze["Analyze Requirements
• Query patterns
• Data volumes
• Performance targets
• Operational needs"] Analyze --> Optimize["Optimize Design
• Add indexes
• Plan partitions
• Choose storage engines
• Configure features"] Optimize --> Implement["Implement Database
• Create tables
• Add indexes
• Set up partitions
• Configure storage"] Implement --> Monitor["Monitor & Tune
• Query performance
• Storage usage
• Maintenance overhead
• Scalability metrics"] Monitor -->|"Needs optimization"| Analyze Monitor -->|"Performing well"| Production["Production System
Optimized"] Analyze -.->|"Considerations"| Considerations["• Database system
• Hardware constraints
• Access patterns
• Growth projections"] Optimize -.->|"Techniques"| Techniques["• Indexing strategies
• Partitioning schemes
• Storage optimization
• Performance tuning"] ``` -------------------------------- ### Vs Component: Basic Usage with Items Source: https://github.com/archman-dev/website/blob/main/editing/widgets/vs.mdx Demonstrates the fundamental usage of the Vs component by passing an array of items. Each item has a label and an array of points. The 'highlight' prop is used to specify which item(s) should be visually emphasized. ```jsx import Vs from "@site/src/components/Vs"; ``` -------------------------------- ### Mermaid Diagram for Decision Flow Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/what-is-software-architecture/architectural-decision-impact-and-cost-of-change.mdx A Mermaid diagram illustrating the process of making architectural decisions based on blast radius, reversibility, and uncertainty. It guides whether to prototype, timebox experiments, or decide quickly. ```mermaid flowchart TB A([Proposed decision]) --> B{"High blast radius?"}; B -- Yes --> C{"Hard to reverse?"}; B -- No --> D{"Low uncertainty?"}; C -- Yes --> E["Prototype and measure"]; C -- No --> F["Timebox experiment"]; E --> G["Document ADR"]; F --> G; D -- Yes --> H["Decide fast"]; D -- No --> F; G --> I["Guardrails and rollout"]; H --> I; ``` -------------------------------- ### Go gRPC Client for Orders Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/system-thinking-basics/interfaces-and-contracts.mdx A Go client implementation for the Orders gRPC service. It shows how to connect to the gRPC server, create an Orders client, construct a CreateOrder request, and process the response or any encountered errors. ```go package main import ( "context" "log" "time" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" pb "path/to/your/gen/go/orders/v1" ) func main() { conn, err := grpc.Dial("localhost:50051", grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() c := pb.NewOrdersClient(conn) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() req := &pb.CreateOrderRequest{ IdempotencyKey: "a-unique-key", OrderId: "ord-123", ItemIds: []string{"item-abc", "item-def"}, } r, err := c.CreateOrder(ctx, req) if err != nil { log.Fatalf("could not create order: %v", err) } log.Printf("Order created with ETag: %s", r.GetEtag()) } ``` -------------------------------- ### Python Actor Example (asyncio) Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/programming-paradigms/actor-model.mdx Implements a counter actor using Python's asyncio. The actor processes messages from a queue, incrementing a counter or reporting its value. It runs in a separate task managed by asyncio. ```python import asyncio class CounterActor: def __init__(self): self._count = 0 self._mailbox = asyncio.Queue() async def run(self): """The actor's main processing loop.""" while True: message = await self._mailbox.get() if message == "get": print(f"Count is: {self._count}") elif isinstance(message, int): self._count += message self._mailbox.task_done() def send(self, message): """Send a message to the actor's mailbox.""" self._mailbox.put_nowait(message) async def main(): actor = CounterActor() # Start the actor's processing loop in the background asyncio.create_task(actor.run()) actor.send(1) actor.send(1) actor.send("get") await asyncio.sleep(0.1) # Allow time for processing if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Checklist Component Basic Usage (React) Source: https://github.com/archman-dev/website/blob/main/editing/widgets/checklist.mdx Demonstrates the basic usage of the Checklist component with a title and a simple list of items. It's used to represent service readiness criteria. ```jsx import Checklist from "@site/src/components/Checklist"; Versioning, items: ["SemVer in docs", "Backward compatible changes"], }, ]} /> ``` -------------------------------- ### Create customers table with indexes and constraints Source: https://github.com/archman-dev/website/blob/main/docs/foundational-concepts/data-fundamentals/data-modeling/physical.mdx Defines the 'customers' table with an InnoDB engine for ACID compliance. It includes primary key, unique constraints on email, check constraints for email format, and indexes for common query patterns like status, registration date, name search, and creation date. It also features a composite index for name and status lookup. ```sql -- Primary table with InnoDB engine for ACID compliance CREATE TABLE customers ( customer_id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(255) NOT NULL, first_name VARCHAR(100) NOT NULL, last_name VARCHAR(100) NOT NULL, registration_date DATE NOT NULL, status ENUM('active', 'inactive', 'suspended') NOT NULL DEFAULT 'active', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- Constraints UNIQUE KEY uk_customers_email (email), CONSTRAINT chk_email_format CHECK (email REGEXP '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$') ) ENGINE=InnoDB; -- Indexes for common query patterns CREATE INDEX idx_customers_status ON customers(status); CREATE INDEX idx_customers_registration_date ON customers(registration_date); CREATE INDEX idx_customers_name_search ON customers(first_name, last_name); CREATE INDEX idx_customers_created_at ON customers(created_at); -- Composite index for customer lookup by name and status CREATE INDEX idx_customers_name_status ON customers(first_name, last_name, status); ```